2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.server.content;
19 import android.Manifest;
20 import android.accounts.Account;
21 import android.app.ActivityManager;
22 import android.content.ComponentName;
23 import android.content.ContentResolver;
24 import android.content.Context;
25 import android.content.IContentService;
26 import android.content.Intent;
27 import android.content.ISyncStatusObserver;
28 import android.content.PeriodicSync;
29 import android.content.SyncAdapterType;
30 import android.content.SyncInfo;
31 import android.content.SyncRequest;
32 import android.content.SyncStatusInfo;
33 import android.content.pm.PackageManager;
34 import android.content.pm.PackageManagerInternal;
35 import android.database.IContentObserver;
36 import android.database.sqlite.SQLiteException;
37 import android.net.Uri;
38 import android.os.Binder;
39 import android.os.Bundle;
40 import android.os.IBinder;
41 import android.os.Parcel;
42 import android.os.RemoteException;
43 import android.os.ServiceManager;
44 import android.os.SystemProperties;
45 import android.os.UserHandle;
46 import android.text.TextUtils;
47 import android.util.Log;
48 import android.util.Slog;
49 import android.util.SparseIntArray;
50 import com.android.server.LocalServices;
52 import java.io.FileDescriptor;
53 import java.io.PrintWriter;
54 import java.security.InvalidParameterException;
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.Comparator;
58 import java.util.List;
63 public final class ContentService extends IContentService.Stub {
64 private static final String TAG = "ContentService";
65 private Context mContext;
66 private boolean mFactoryTest;
67 private final ObserverNode mRootNode = new ObserverNode("");
68 private SyncManager mSyncManager = null;
69 private final Object mSyncManagerLock = new Object();
71 private SyncManager getSyncManager() {
72 if (SystemProperties.getBoolean("config.disable_network", false)) {
76 synchronized(mSyncManagerLock) {
78 // Try to create the SyncManager, return null if it fails (e.g. the disk is full).
79 if (mSyncManager == null) mSyncManager = new SyncManager(mContext, mFactoryTest);
80 } catch (SQLiteException e) {
81 Log.e(TAG, "Can't create SyncManager", e);
88 protected synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
89 mContext.enforceCallingOrSelfPermission(Manifest.permission.DUMP,
90 "caller doesn't have the DUMP permission");
92 // This makes it so that future permission checks will be in the context of this
93 // process rather than the caller's process. We will restore this before returning.
94 long identityToken = clearCallingIdentity();
96 if (mSyncManager == null) {
97 pw.println("No SyncManager created! (Disk full?)");
99 mSyncManager.dump(fd, pw);
102 pw.println("Observer tree:");
103 synchronized (mRootNode) {
104 int[] counts = new int[2];
105 final SparseIntArray pidCounts = new SparseIntArray();
106 mRootNode.dumpLocked(fd, pw, args, "", " ", counts, pidCounts);
108 ArrayList<Integer> sorted = new ArrayList<Integer>();
109 for (int i=0; i<pidCounts.size(); i++) {
110 sorted.add(pidCounts.keyAt(i));
112 Collections.sort(sorted, new Comparator<Integer>() {
114 public int compare(Integer lhs, Integer rhs) {
115 int lc = pidCounts.get(lhs);
116 int rc = pidCounts.get(rhs);
119 } else if (lc > rc) {
126 for (int i=0; i<sorted.size(); i++) {
127 int pid = sorted.get(i);
128 pw.print(" pid "); pw.print(pid); pw.print(": ");
129 pw.print(pidCounts.get(pid)); pw.println(" observers");
132 pw.print(" Total number of nodes: "); pw.println(counts[0]);
133 pw.print(" Total number of observers: "); pw.println(counts[1]);
136 restoreCallingIdentity(identityToken);
141 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
142 throws RemoteException {
144 return super.onTransact(code, data, reply, flags);
145 } catch (RuntimeException e) {
146 // The content service only throws security exceptions, so let's
148 if (!(e instanceof SecurityException)) {
149 Slog.wtf(TAG, "Content Service Crash", e);
155 /*package*/ ContentService(Context context, boolean factoryTest) {
157 mFactoryTest = factoryTest;
159 // Let the package manager query for the sync adapters for a given authority
160 // as we grant default permissions to sync adapters for specific authorities.
161 PackageManagerInternal packageManagerInternal = LocalServices.getService(
162 PackageManagerInternal.class);
163 packageManagerInternal.setSyncAdapterPackagesprovider(
164 new PackageManagerInternal.SyncAdapterPackagesProvider() {
166 public String[] getPackages(String authority, int userId) {
167 return getSyncAdapterPackagesForAuthorityAsUser(authority, userId);
172 public void systemReady() {
177 * Register a content observer tied to a specific user's view of the provider.
178 * @param userHandle the user whose view of the provider is to be observed. May be
179 * the calling user without requiring any permission, otherwise the caller needs to
180 * hold the INTERACT_ACROSS_USERS_FULL permission or hold a read uri grant to the uri.
181 * Pseudousers USER_ALL and USER_CURRENT are properly handled; all other pseudousers
185 public void registerContentObserver(Uri uri, boolean notifyForDescendants,
186 IContentObserver observer, int userHandle) {
187 if (observer == null || uri == null) {
188 throw new IllegalArgumentException("You must pass a valid uri and observer");
191 final int uid = Binder.getCallingUid();
192 final int pid = Binder.getCallingPid();
193 final int callingUserHandle = UserHandle.getCallingUserId();
194 // Registering an observer for any user other than the calling user requires uri grant or
195 // cross user permission
196 if (callingUserHandle != userHandle &&
197 mContext.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
198 != PackageManager.PERMISSION_GRANTED) {
199 enforceCrossUserPermission(userHandle,
200 "no permission to observe other users' provider view");
203 if (userHandle < 0) {
204 if (userHandle == UserHandle.USER_CURRENT) {
205 userHandle = ActivityManager.getCurrentUser();
206 } else if (userHandle != UserHandle.USER_ALL) {
207 throw new InvalidParameterException("Bad user handle for registerContentObserver: "
212 synchronized (mRootNode) {
213 mRootNode.addObserverLocked(uri, observer, notifyForDescendants, mRootNode,
214 uid, pid, userHandle);
215 if (false) Log.v(TAG, "Registered observer " + observer + " at " + uri +
216 " with notifyForDescendants " + notifyForDescendants);
220 public void registerContentObserver(Uri uri, boolean notifyForDescendants,
221 IContentObserver observer) {
222 registerContentObserver(uri, notifyForDescendants, observer,
223 UserHandle.getCallingUserId());
226 public void unregisterContentObserver(IContentObserver observer) {
227 if (observer == null) {
228 throw new IllegalArgumentException("You must pass a valid observer");
230 synchronized (mRootNode) {
231 mRootNode.removeObserverLocked(observer);
232 if (false) Log.v(TAG, "Unregistered observer " + observer);
237 * Notify observers of a particular user's view of the provider.
238 * @param userHandle the user whose view of the provider is to be notified. May be
239 * the calling user without requiring any permission, otherwise the caller needs to
240 * hold the INTERACT_ACROSS_USERS_FULL permission or hold a write uri grant to the uri.
241 * Pseudousers USER_ALL and USER_CURRENT are properly interpreted; no other pseudousers are
245 public void notifyChange(Uri uri, IContentObserver observer,
246 boolean observerWantsSelfNotifications, boolean syncToNetwork,
248 if (Log.isLoggable(TAG, Log.VERBOSE)) {
249 Log.v(TAG, "Notifying update of " + uri + " for user " + userHandle
250 + " from observer " + observer + ", syncToNetwork " + syncToNetwork);
253 final int uid = Binder.getCallingUid();
254 final int pid = Binder.getCallingPid();
255 final int callingUserHandle = UserHandle.getCallingUserId();
256 // Notify for any user other than the caller requires uri grant or cross user permission
257 if (callingUserHandle != userHandle &&
258 mContext.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
259 != PackageManager.PERMISSION_GRANTED) {
260 enforceCrossUserPermission(userHandle, "no permission to notify other users");
263 // We passed the permission check; resolve pseudouser targets as appropriate
264 if (userHandle < 0) {
265 if (userHandle == UserHandle.USER_CURRENT) {
266 userHandle = ActivityManager.getCurrentUser();
267 } else if (userHandle != UserHandle.USER_ALL) {
268 throw new InvalidParameterException("Bad user handle for notifyChange: "
273 // This makes it so that future permission checks will be in the context of this
274 // process rather than the caller's process. We will restore this before returning.
275 long identityToken = clearCallingIdentity();
277 ArrayList<ObserverCall> calls = new ArrayList<ObserverCall>();
278 synchronized (mRootNode) {
279 mRootNode.collectObserversLocked(uri, 0, observer, observerWantsSelfNotifications,
282 final int numCalls = calls.size();
283 for (int i=0; i<numCalls; i++) {
284 ObserverCall oc = calls.get(i);
286 oc.mObserver.onChange(oc.mSelfChange, uri, userHandle);
287 if (Log.isLoggable(TAG, Log.VERBOSE)) {
288 Log.v(TAG, "Notified " + oc.mObserver + " of " + "update at " + uri);
290 } catch (RemoteException ex) {
291 synchronized (mRootNode) {
292 Log.w(TAG, "Found dead observer, removing");
293 IBinder binder = oc.mObserver.asBinder();
294 final ArrayList<ObserverNode.ObserverEntry> list
295 = oc.mNode.mObservers;
296 int numList = list.size();
297 for (int j=0; j<numList; j++) {
298 ObserverNode.ObserverEntry oe = list.get(j);
299 if (oe.observer.asBinder() == binder) {
309 SyncManager syncManager = getSyncManager();
310 if (syncManager != null) {
311 syncManager.scheduleLocalSync(null /* all accounts */, callingUserHandle, uid,
316 restoreCallingIdentity(identityToken);
320 public void notifyChange(Uri uri, IContentObserver observer,
321 boolean observerWantsSelfNotifications, boolean syncToNetwork) {
322 notifyChange(uri, observer, observerWantsSelfNotifications, syncToNetwork,
323 UserHandle.getCallingUserId());
327 * Hide this class since it is not part of api,
328 * but current unittest framework requires it to be public
332 public static final class ObserverCall {
333 final ObserverNode mNode;
334 final IContentObserver mObserver;
335 final boolean mSelfChange;
337 ObserverCall(ObserverNode node, IContentObserver observer, boolean selfChange) {
339 mObserver = observer;
340 mSelfChange = selfChange;
344 public void requestSync(Account account, String authority, Bundle extras) {
345 ContentResolver.validateSyncExtrasBundle(extras);
346 int userId = UserHandle.getCallingUserId();
347 int uId = Binder.getCallingUid();
349 // This makes it so that future permission checks will be in the context of this
350 // process rather than the caller's process. We will restore this before returning.
351 long identityToken = clearCallingIdentity();
353 SyncManager syncManager = getSyncManager();
354 if (syncManager != null) {
355 syncManager.scheduleSync(account, userId, uId, authority, extras,
356 0 /* no delay */, 0 /* no delay */,
357 false /* onlyThoseWithUnkownSyncableState */);
360 restoreCallingIdentity(identityToken);
365 * Request a sync with a generic {@link android.content.SyncRequest} object. This will be
367 * periodic OR one-off sync.
369 * anonymous OR provider sync.
370 * Depending on the request, we enqueue to suit in the SyncManager.
371 * @param request The request object. Validation of this object is done by its builder.
373 public void sync(SyncRequest request) {
374 syncAsUser(request, UserHandle.getCallingUserId());
378 * If the user id supplied is different to the calling user, the caller must hold the
379 * INTERACT_ACROSS_USERS_FULL permission.
381 public void syncAsUser(SyncRequest request, int userId) {
382 enforceCrossUserPermission(userId, "no permission to request sync as user: " + userId);
383 int callerUid = Binder.getCallingUid();
384 // This makes it so that future permission checks will be in the context of this
385 // process rather than the caller's process. We will restore this before returning.
386 long identityToken = clearCallingIdentity();
388 SyncManager syncManager = getSyncManager();
389 if (syncManager == null) {
393 Bundle extras = request.getBundle();
394 long flextime = request.getSyncFlexTime();
395 long runAtTime = request.getSyncRunTime();
396 if (request.isPeriodic()) {
397 mContext.enforceCallingOrSelfPermission(
398 Manifest.permission.WRITE_SYNC_SETTINGS,
399 "no permission to write the sync settings");
400 SyncStorageEngine.EndPoint info;
401 info = new SyncStorageEngine.EndPoint(
402 request.getAccount(), request.getProvider(), userId);
403 if (runAtTime < 60) {
404 Slog.w(TAG, "Requested poll frequency of " + runAtTime
405 + " seconds being rounded up to 60 seconds.");
408 // Schedule periodic sync.
409 getSyncManager().getSyncStorageEngine()
410 .updateOrAddPeriodicSync(info, runAtTime, flextime, extras);
412 long beforeRuntimeMillis = (flextime) * 1000;
413 long runtimeMillis = runAtTime * 1000;
414 syncManager.scheduleSync(
415 request.getAccount(), userId, callerUid, request.getProvider(), extras,
416 beforeRuntimeMillis, runtimeMillis,
417 false /* onlyThoseWithUnknownSyncableState */);
420 restoreCallingIdentity(identityToken);
425 * Clear all scheduled sync operations that match the uri and cancel the active sync
426 * if they match the authority and account, if they are present.
428 * @param account filter the pending and active syncs to cancel using this account, or null.
429 * @param authority filter the pending and active syncs to cancel using this authority, or
431 * @param cname cancel syncs running on this service, or null for provider/account.
434 public void cancelSync(Account account, String authority, ComponentName cname) {
435 cancelSyncAsUser(account, authority, cname, UserHandle.getCallingUserId());
439 * Clear all scheduled sync operations that match the uri and cancel the active sync
440 * if they match the authority and account, if they are present.
442 * <p> If the user id supplied is different to the calling user, the caller must hold the
443 * INTERACT_ACROSS_USERS_FULL permission.
445 * @param account filter the pending and active syncs to cancel using this account, or null.
446 * @param authority filter the pending and active syncs to cancel using this authority, or
448 * @param userId the user id for which to cancel sync operations.
449 * @param cname cancel syncs running on this service, or null for provider/account.
452 public void cancelSyncAsUser(Account account, String authority, ComponentName cname,
454 if (authority != null && authority.length() == 0) {
455 throw new IllegalArgumentException("Authority must be non-empty");
457 enforceCrossUserPermission(userId,
458 "no permission to modify the sync settings for user " + userId);
459 // This makes it so that future permission checks will be in the context of this
460 // process rather than the caller's process. We will restore this before returning.
461 long identityToken = clearCallingIdentity();
463 SyncManager syncManager = getSyncManager();
464 if (syncManager != null) {
465 SyncStorageEngine.EndPoint info;
467 info = new SyncStorageEngine.EndPoint(account, authority, userId);
469 info = new SyncStorageEngine.EndPoint(cname, userId);
471 syncManager.clearScheduledSyncOperations(info);
472 syncManager.cancelActiveSync(info, null /* all syncs for this adapter */);
475 restoreCallingIdentity(identityToken);
479 public void cancelRequest(SyncRequest request) {
480 SyncManager syncManager = getSyncManager();
481 if (syncManager == null) return;
482 int userId = UserHandle.getCallingUserId();
484 long identityToken = clearCallingIdentity();
486 SyncStorageEngine.EndPoint info;
487 Bundle extras = new Bundle(request.getBundle());
488 Account account = request.getAccount();
489 String provider = request.getProvider();
490 info = new SyncStorageEngine.EndPoint(account, provider, userId);
491 if (request.isPeriodic()) {
492 // Remove periodic sync.
493 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
494 "no permission to write the sync settings");
495 getSyncManager().getSyncStorageEngine().removePeriodicSync(info, extras);
497 // Cancel active syncs and clear pending syncs from the queue.
498 syncManager.cancelScheduledSyncOperation(info, extras);
499 syncManager.cancelActiveSync(info, extras);
501 restoreCallingIdentity(identityToken);
506 * Get information about the SyncAdapters that are known to the system.
507 * @return an array of SyncAdapters that have registered with the system
510 public SyncAdapterType[] getSyncAdapterTypes() {
511 return getSyncAdapterTypesAsUser(UserHandle.getCallingUserId());
515 * Get information about the SyncAdapters that are known to the system for a particular user.
517 * <p> If the user id supplied is different to the calling user, the caller must hold the
518 * INTERACT_ACROSS_USERS_FULL permission.
520 * @return an array of SyncAdapters that have registered with the system
523 public SyncAdapterType[] getSyncAdapterTypesAsUser(int userId) {
524 enforceCrossUserPermission(userId,
525 "no permission to read sync settings for user " + userId);
526 // This makes it so that future permission checks will be in the context of this
527 // process rather than the caller's process. We will restore this before returning.
528 final long identityToken = clearCallingIdentity();
530 SyncManager syncManager = getSyncManager();
531 return syncManager.getSyncAdapterTypes(userId);
533 restoreCallingIdentity(identityToken);
538 public String[] getSyncAdapterPackagesForAuthorityAsUser(String authority, int userId) {
539 enforceCrossUserPermission(userId,
540 "no permission to read sync settings for user " + userId);
541 // This makes it so that future permission checks will be in the context of this
542 // process rather than the caller's process. We will restore this before returning.
543 final long identityToken = clearCallingIdentity();
545 SyncManager syncManager = getSyncManager();
546 return syncManager.getSyncAdapterPackagesForAuthorityAsUser(authority, userId);
548 restoreCallingIdentity(identityToken);
553 public boolean getSyncAutomatically(Account account, String providerName) {
554 return getSyncAutomaticallyAsUser(account, providerName, UserHandle.getCallingUserId());
558 * If the user id supplied is different to the calling user, the caller must hold the
559 * INTERACT_ACROSS_USERS_FULL permission.
562 public boolean getSyncAutomaticallyAsUser(Account account, String providerName, int userId) {
563 enforceCrossUserPermission(userId,
564 "no permission to read the sync settings for user " + userId);
565 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
566 "no permission to read the sync settings");
568 long identityToken = clearCallingIdentity();
570 SyncManager syncManager = getSyncManager();
571 if (syncManager != null) {
572 return syncManager.getSyncStorageEngine()
573 .getSyncAutomatically(account, userId, providerName);
576 restoreCallingIdentity(identityToken);
582 public void setSyncAutomatically(Account account, String providerName, boolean sync) {
583 setSyncAutomaticallyAsUser(account, providerName, sync, UserHandle.getCallingUserId());
587 public void setSyncAutomaticallyAsUser(Account account, String providerName, boolean sync,
589 if (TextUtils.isEmpty(providerName)) {
590 throw new IllegalArgumentException("Authority must be non-empty");
592 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
593 "no permission to write the sync settings");
594 enforceCrossUserPermission(userId,
595 "no permission to modify the sync settings for user " + userId);
597 long identityToken = clearCallingIdentity();
599 SyncManager syncManager = getSyncManager();
600 if (syncManager != null) {
601 syncManager.getSyncStorageEngine().setSyncAutomatically(account, userId,
605 restoreCallingIdentity(identityToken);
609 /** Old API. Schedule periodic sync with default flex time. */
611 public void addPeriodicSync(Account account, String authority, Bundle extras,
612 long pollFrequency) {
613 if (account == null) {
614 throw new IllegalArgumentException("Account must not be null");
616 if (TextUtils.isEmpty(authority)) {
617 throw new IllegalArgumentException("Authority must not be empty.");
619 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
620 "no permission to write the sync settings");
622 int userId = UserHandle.getCallingUserId();
623 if (pollFrequency < 60) {
624 Slog.w(TAG, "Requested poll frequency of " + pollFrequency
625 + " seconds being rounded up to 60 seconds.");
628 long defaultFlex = SyncStorageEngine.calculateDefaultFlexTime(pollFrequency);
630 long identityToken = clearCallingIdentity();
632 SyncStorageEngine.EndPoint info =
633 new SyncStorageEngine.EndPoint(account, authority, userId);
634 getSyncManager().getSyncStorageEngine()
635 .updateOrAddPeriodicSync(info,
640 restoreCallingIdentity(identityToken);
644 public void removePeriodicSync(Account account, String authority, Bundle extras) {
645 if (account == null) {
646 throw new IllegalArgumentException("Account must not be null");
648 if (TextUtils.isEmpty(authority)) {
649 throw new IllegalArgumentException("Authority must not be empty");
651 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
652 "no permission to write the sync settings");
654 int userId = UserHandle.getCallingUserId();
655 long identityToken = clearCallingIdentity();
657 getSyncManager().getSyncStorageEngine()
659 new SyncStorageEngine.EndPoint(account, authority, userId),
662 restoreCallingIdentity(identityToken);
667 public List<PeriodicSync> getPeriodicSyncs(Account account, String providerName,
668 ComponentName cname) {
669 if (account == null) {
670 throw new IllegalArgumentException("Account must not be null");
672 if (TextUtils.isEmpty(providerName)) {
673 throw new IllegalArgumentException("Authority must not be empty");
675 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
676 "no permission to read the sync settings");
678 int userId = UserHandle.getCallingUserId();
679 long identityToken = clearCallingIdentity();
681 return getSyncManager().getSyncStorageEngine().getPeriodicSyncs(
682 new SyncStorageEngine.EndPoint(account, providerName, userId));
684 restoreCallingIdentity(identityToken);
688 public int getIsSyncable(Account account, String providerName) {
689 return getIsSyncableAsUser(account, providerName, UserHandle.getCallingUserId());
693 * If the user id supplied is different to the calling user, the caller must hold the
694 * INTERACT_ACROSS_USERS_FULL permission.
696 public int getIsSyncableAsUser(Account account, String providerName, int userId) {
697 enforceCrossUserPermission(userId,
698 "no permission to read the sync settings for user " + userId);
699 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
700 "no permission to read the sync settings");
702 long identityToken = clearCallingIdentity();
704 SyncManager syncManager = getSyncManager();
705 if (syncManager != null) {
706 return syncManager.getIsSyncable(
707 account, userId, providerName);
710 restoreCallingIdentity(identityToken);
715 public void setIsSyncable(Account account, String providerName, int syncable) {
716 if (TextUtils.isEmpty(providerName)) {
717 throw new IllegalArgumentException("Authority must not be empty");
719 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
720 "no permission to write the sync settings");
722 int userId = UserHandle.getCallingUserId();
723 long identityToken = clearCallingIdentity();
725 SyncManager syncManager = getSyncManager();
726 if (syncManager != null) {
727 syncManager.getSyncStorageEngine().setIsSyncable(
728 account, userId, providerName, syncable);
731 restoreCallingIdentity(identityToken);
736 public boolean getMasterSyncAutomatically() {
737 return getMasterSyncAutomaticallyAsUser(UserHandle.getCallingUserId());
741 * If the user id supplied is different to the calling user, the caller must hold the
742 * INTERACT_ACROSS_USERS_FULL permission.
745 public boolean getMasterSyncAutomaticallyAsUser(int userId) {
746 enforceCrossUserPermission(userId,
747 "no permission to read the sync settings for user " + userId);
748 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
749 "no permission to read the sync settings");
751 long identityToken = clearCallingIdentity();
753 SyncManager syncManager = getSyncManager();
754 if (syncManager != null) {
755 return syncManager.getSyncStorageEngine().getMasterSyncAutomatically(userId);
758 restoreCallingIdentity(identityToken);
764 public void setMasterSyncAutomatically(boolean flag) {
765 setMasterSyncAutomaticallyAsUser(flag, UserHandle.getCallingUserId());
769 public void setMasterSyncAutomaticallyAsUser(boolean flag, int userId) {
770 enforceCrossUserPermission(userId,
771 "no permission to set the sync status for user " + userId);
772 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
773 "no permission to write the sync settings");
775 long identityToken = clearCallingIdentity();
777 SyncManager syncManager = getSyncManager();
778 if (syncManager != null) {
779 syncManager.getSyncStorageEngine().setMasterSyncAutomatically(flag, userId);
782 restoreCallingIdentity(identityToken);
786 public boolean isSyncActive(Account account, String authority, ComponentName cname) {
787 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
788 "no permission to read the sync stats");
789 int userId = UserHandle.getCallingUserId();
790 int callingUid = Binder.getCallingUid();
791 long identityToken = clearCallingIdentity();
793 SyncManager syncManager = getSyncManager();
794 if (syncManager == null) {
797 return syncManager.getSyncStorageEngine().isSyncActive(
798 new SyncStorageEngine.EndPoint(account, authority, userId));
800 restoreCallingIdentity(identityToken);
804 public List<SyncInfo> getCurrentSyncs() {
805 return getCurrentSyncsAsUser(UserHandle.getCallingUserId());
809 * If the user id supplied is different to the calling user, the caller must hold the
810 * INTERACT_ACROSS_USERS_FULL permission.
812 public List<SyncInfo> getCurrentSyncsAsUser(int userId) {
813 enforceCrossUserPermission(userId,
814 "no permission to read the sync settings for user " + userId);
815 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
816 "no permission to read the sync stats");
818 long identityToken = clearCallingIdentity();
820 return getSyncManager().getSyncStorageEngine().getCurrentSyncsCopy(userId);
822 restoreCallingIdentity(identityToken);
826 public SyncStatusInfo getSyncStatus(Account account, String authority, ComponentName cname) {
827 return getSyncStatusAsUser(account, authority, cname, UserHandle.getCallingUserId());
831 * If the user id supplied is different to the calling user, the caller must hold the
832 * INTERACT_ACROSS_USERS_FULL permission.
834 public SyncStatusInfo getSyncStatusAsUser(Account account, String authority,
835 ComponentName cname, int userId) {
836 if (TextUtils.isEmpty(authority)) {
837 throw new IllegalArgumentException("Authority must not be empty");
840 enforceCrossUserPermission(userId,
841 "no permission to read the sync stats for user " + userId);
842 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
843 "no permission to read the sync stats");
845 int callerUid = Binder.getCallingUid();
846 long identityToken = clearCallingIdentity();
848 SyncManager syncManager = getSyncManager();
849 if (syncManager == null) {
852 SyncStorageEngine.EndPoint info;
853 if (!(account == null || authority == null)) {
854 info = new SyncStorageEngine.EndPoint(account, authority, userId);
856 throw new IllegalArgumentException("Must call sync status with valid authority");
858 return syncManager.getSyncStorageEngine().getStatusByAuthority(info);
860 restoreCallingIdentity(identityToken);
864 public boolean isSyncPending(Account account, String authority, ComponentName cname) {
865 return isSyncPendingAsUser(account, authority, cname, UserHandle.getCallingUserId());
869 public boolean isSyncPendingAsUser(Account account, String authority, ComponentName cname,
871 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
872 "no permission to read the sync stats");
873 enforceCrossUserPermission(userId,
874 "no permission to retrieve the sync settings for user " + userId);
875 int callerUid = Binder.getCallingUid();
876 long identityToken = clearCallingIdentity();
877 SyncManager syncManager = getSyncManager();
878 if (syncManager == null) return false;
881 SyncStorageEngine.EndPoint info;
882 if (!(account == null || authority == null)) {
883 info = new SyncStorageEngine.EndPoint(account, authority, userId);
885 throw new IllegalArgumentException("Invalid authority specified");
887 return syncManager.getSyncStorageEngine().isSyncPending(info);
889 restoreCallingIdentity(identityToken);
893 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
894 long identityToken = clearCallingIdentity();
896 SyncManager syncManager = getSyncManager();
897 if (syncManager != null && callback != null) {
898 syncManager.getSyncStorageEngine().addStatusChangeListener(mask, callback);
901 restoreCallingIdentity(identityToken);
905 public void removeStatusChangeListener(ISyncStatusObserver callback) {
906 long identityToken = clearCallingIdentity();
908 SyncManager syncManager = getSyncManager();
909 if (syncManager != null && callback != null) {
910 syncManager.getSyncStorageEngine().removeStatusChangeListener(callback);
913 restoreCallingIdentity(identityToken);
917 public static ContentService main(Context context, boolean factoryTest) {
918 ContentService service = new ContentService(context, factoryTest);
919 ServiceManager.addService(ContentResolver.CONTENT_SERVICE_NAME, service);
924 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS_FULL
925 * permission, if the userHandle is not for the caller.
927 * @param userHandle the user handle of the user we want to act on behalf of.
928 * @param message the message to log on security exception.
930 private void enforceCrossUserPermission(int userHandle, String message) {
931 final int callingUser = UserHandle.getCallingUserId();
932 if (callingUser != userHandle) {
933 mContext.enforceCallingOrSelfPermission(
934 Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
939 * Hide this class since it is not part of api,
940 * but current unittest framework requires it to be public
943 public static final class ObserverNode {
944 private class ObserverEntry implements IBinder.DeathRecipient {
945 public final IContentObserver observer;
946 public final int uid;
947 public final int pid;
948 public final boolean notifyForDescendants;
949 private final int userHandle;
950 private final Object observersLock;
952 public ObserverEntry(IContentObserver o, boolean n, Object observersLock,
953 int _uid, int _pid, int _userHandle) {
954 this.observersLock = observersLock;
958 userHandle = _userHandle;
959 notifyForDescendants = n;
961 observer.asBinder().linkToDeath(this, 0);
962 } catch (RemoteException e) {
967 public void binderDied() {
968 synchronized (observersLock) {
969 removeObserverLocked(observer);
973 public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
974 String name, String prefix, SparseIntArray pidCounts) {
975 pidCounts.put(pid, pidCounts.get(pid)+1);
976 pw.print(prefix); pw.print(name); pw.print(": pid=");
977 pw.print(pid); pw.print(" uid=");
978 pw.print(uid); pw.print(" user=");
979 pw.print(userHandle); pw.print(" target=");
980 pw.println(Integer.toHexString(System.identityHashCode(
981 observer != null ? observer.asBinder() : null)));
985 public static final int INSERT_TYPE = 0;
986 public static final int UPDATE_TYPE = 1;
987 public static final int DELETE_TYPE = 2;
989 private String mName;
990 private ArrayList<ObserverNode> mChildren = new ArrayList<ObserverNode>();
991 private ArrayList<ObserverEntry> mObservers = new ArrayList<ObserverEntry>();
993 public ObserverNode(String name) {
997 public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
998 String name, String prefix, int[] counts, SparseIntArray pidCounts) {
999 String innerName = null;
1000 if (mObservers.size() > 0) {
1001 if ("".equals(name)) {
1004 innerName = name + "/" + mName;
1006 for (int i=0; i<mObservers.size(); i++) {
1008 mObservers.get(i).dumpLocked(fd, pw, args, innerName, prefix,
1012 if (mChildren.size() > 0) {
1013 if (innerName == null) {
1014 if ("".equals(name)) {
1017 innerName = name + "/" + mName;
1020 for (int i=0; i<mChildren.size(); i++) {
1022 mChildren.get(i).dumpLocked(fd, pw, args, innerName, prefix,
1028 private String getUriSegment(Uri uri, int index) {
1031 return uri.getAuthority();
1033 return uri.getPathSegments().get(index - 1);
1040 private int countUriSegments(Uri uri) {
1044 return uri.getPathSegments().size() + 1;
1047 // Invariant: userHandle is either a hard user number or is USER_ALL
1048 public void addObserverLocked(Uri uri, IContentObserver observer,
1049 boolean notifyForDescendants, Object observersLock,
1050 int uid, int pid, int userHandle) {
1051 addObserverLocked(uri, 0, observer, notifyForDescendants, observersLock,
1052 uid, pid, userHandle);
1055 private void addObserverLocked(Uri uri, int index, IContentObserver observer,
1056 boolean notifyForDescendants, Object observersLock,
1057 int uid, int pid, int userHandle) {
1058 // If this is the leaf node add the observer
1059 if (index == countUriSegments(uri)) {
1060 mObservers.add(new ObserverEntry(observer, notifyForDescendants, observersLock,
1061 uid, pid, userHandle));
1065 // Look to see if the proper child already exists
1066 String segment = getUriSegment(uri, index);
1067 if (segment == null) {
1068 throw new IllegalArgumentException("Invalid Uri (" + uri + ") used for observer");
1070 int N = mChildren.size();
1071 for (int i = 0; i < N; i++) {
1072 ObserverNode node = mChildren.get(i);
1073 if (node.mName.equals(segment)) {
1074 node.addObserverLocked(uri, index + 1, observer, notifyForDescendants,
1075 observersLock, uid, pid, userHandle);
1080 // No child found, create one
1081 ObserverNode node = new ObserverNode(segment);
1082 mChildren.add(node);
1083 node.addObserverLocked(uri, index + 1, observer, notifyForDescendants,
1084 observersLock, uid, pid, userHandle);
1087 public boolean removeObserverLocked(IContentObserver observer) {
1088 int size = mChildren.size();
1089 for (int i = 0; i < size; i++) {
1090 boolean empty = mChildren.get(i).removeObserverLocked(observer);
1092 mChildren.remove(i);
1098 IBinder observerBinder = observer.asBinder();
1099 size = mObservers.size();
1100 for (int i = 0; i < size; i++) {
1101 ObserverEntry entry = mObservers.get(i);
1102 if (entry.observer.asBinder() == observerBinder) {
1103 mObservers.remove(i);
1104 // We no longer need to listen for death notifications. Remove it.
1105 observerBinder.unlinkToDeath(entry, 0);
1110 if (mChildren.size() == 0 && mObservers.size() == 0) {
1116 private void collectMyObserversLocked(boolean leaf, IContentObserver observer,
1117 boolean observerWantsSelfNotifications, int targetUserHandle,
1118 ArrayList<ObserverCall> calls) {
1119 int N = mObservers.size();
1120 IBinder observerBinder = observer == null ? null : observer.asBinder();
1121 for (int i = 0; i < N; i++) {
1122 ObserverEntry entry = mObservers.get(i);
1124 // Don't notify the observer if it sent the notification and isn't interested
1125 // in self notifications
1126 boolean selfChange = (entry.observer.asBinder() == observerBinder);
1127 if (selfChange && !observerWantsSelfNotifications) {
1131 // Does this observer match the target user?
1132 if (targetUserHandle == UserHandle.USER_ALL
1133 || entry.userHandle == UserHandle.USER_ALL
1134 || targetUserHandle == entry.userHandle) {
1135 // Make sure the observer is interested in the notification
1136 if (leaf || (!leaf && entry.notifyForDescendants)) {
1137 calls.add(new ObserverCall(this, entry.observer, selfChange));
1144 * targetUserHandle is either a hard user handle or is USER_ALL
1146 public void collectObserversLocked(Uri uri, int index, IContentObserver observer,
1147 boolean observerWantsSelfNotifications, int targetUserHandle,
1148 ArrayList<ObserverCall> calls) {
1149 String segment = null;
1150 int segmentCount = countUriSegments(uri);
1151 if (index >= segmentCount) {
1152 // This is the leaf node, notify all observers
1153 collectMyObserversLocked(true, observer, observerWantsSelfNotifications,
1154 targetUserHandle, calls);
1155 } else if (index < segmentCount){
1156 segment = getUriSegment(uri, index);
1157 // Notify any observers at this level who are interested in descendants
1158 collectMyObserversLocked(false, observer, observerWantsSelfNotifications,
1159 targetUserHandle, calls);
1162 int N = mChildren.size();
1163 for (int i = 0; i < N; i++) {
1164 ObserverNode node = mChildren.get(i);
1165 if (segment == null || node.mName.equals(segment)) {
1166 // We found the child,
1167 node.collectObserversLocked(uri, index + 1,
1168 observer, observerWantsSelfNotifications, targetUserHandle, calls);
1169 if (segment != null) {