ContentProvider.java revision bba231d7a63b58a8c2b174722ed1487b0f7d8270
154b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project/*
254b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * Copyright (C) 2006 The Android Open Source Project
354b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project *
454b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "License");
53ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * you may not use this file except in compliance with the License.
63ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * You may obtain a copy of the License at
73ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang *
83ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang *      http://www.apache.org/licenses/LICENSE-2.0
93ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang *
1054b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * Unless required by applicable law or agreed to in writing, software
1154b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * distributed under the License is distributed on an "AS IS" BASIS,
123ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
133ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * See the License for the specific language governing permissions and
143ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * limitations under the License.
1525ba5b6564224dceefa086b5c439ef28dad530caMathias Agopian */
163ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang
17b5af325fb1d21a9295bf3009cc95e5ead4999247Mike Reedpackage android.content;
18e4a838051de5e56f44c71117073a035b804b5d04Andreas Huber
19e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport static android.content.pm.PackageManager.PERMISSION_GRANTED;
2054b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Projectimport static android.Manifest.permission.INTERACT_ACROSS_USERS;
21bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huber
2237105cc7710f988984e92b65989b78ed59693b8bAndreas Huberimport android.app.AppOpsManager;
2337105cc7710f988984e92b65989b78ed59693b8bAndreas Huberimport android.content.pm.PathPermission;
24bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.content.pm.ProviderInfo;
25bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.content.res.AssetFileDescriptor;
26bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.content.res.Configuration;
27bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.database.Cursor;
28bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.database.SQLException;
29bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.net.Uri;
30bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.os.AsyncTask;
31bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.os.Binder;
32bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.os.Bundle;
33bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huberimport android.os.CancellationSignal;
34e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.os.ICancellationSignal;
35e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.os.OperationCanceledException;
36e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.os.ParcelFileDescriptor;
37e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.os.Process;
38e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.os.UserHandle;
39e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.util.Log;
40e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport android.text.TextUtils;
41e4a838051de5e56f44c71117073a035b804b5d04Andreas Huber
42e4a838051de5e56f44c71117073a035b804b5d04Andreas Huberimport java.io.File;
4354b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Projectimport java.io.FileDescriptor;
4454b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Projectimport java.io.FileNotFoundException;
4554b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Projectimport java.io.IOException;
463ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiangimport java.io.PrintWriter;
4720cb94eeb5b9672573fc86bf51e09bd66a774581Nicolas Cataniaimport java.util.ArrayList;
48bfb9fb143b67c2d0307af2bce9af3c08f362b29aAndreas Huber
493ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang/**
503ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * Content providers are one of the primary building blocks of Android applications, providing
513ca47d101db63b619f15723d5131ff7bc8f3a5beJianhong Jiang * content to applications. They encapsulate data and provide it to applications through the single
5254b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * {@link ContentResolver} interface. A content provider is only required if you need to share
5354b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * data between multiple applications. For example, the contacts data is used by multiple
5454b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * applications and must be stored in a content provider. If you don't need to share data amongst
5554b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * multiple applications you can use a database directly via
5654b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * {@link android.database.sqlite.SQLiteDatabase}.
5754b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project *
5854b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * <p>When a request is made via
5954b6cfa9a9e5b861a9930af873580d6dc20f773The Android Open Source Project * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
60f013e1afd1e68af5e3b868c26a653bbfb39538f8The Android Open Source Project * request to the content provider registered with the authority. The content provider can interpret
61f013e1afd1e68af5e3b868c26a653bbfb39538f8The Android Open Source Project * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
62f013e1afd1e68af5e3b868c26a653bbfb39538f8The Android Open Source Project * URIs.</p>
63 *
64 * <p>The primary methods that need to be implemented are:
65 * <ul>
66 *   <li>{@link #onCreate} which is called to initialize the provider</li>
67 *   <li>{@link #query} which returns data to the caller</li>
68 *   <li>{@link #insert} which inserts new data into the content provider</li>
69 *   <li>{@link #update} which updates existing data in the content provider</li>
70 *   <li>{@link #delete} which deletes data from the content provider</li>
71 *   <li>{@link #getType} which returns the MIME type of data in the content provider</li>
72 * </ul></p>
73 *
74 * <p class="caution">Data access methods (such as {@link #insert} and
75 * {@link #update}) may be called from many threads at once, and must be thread-safe.
76 * Other methods (such as {@link #onCreate}) are only called from the application
77 * main thread, and must avoid performing lengthy operations.  See the method
78 * descriptions for their expected thread behavior.</p>
79 *
80 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
81 * ContentProvider instance, so subclasses don't have to worry about the details of
82 * cross-process calls.</p>
83 *
84 * <div class="special reference">
85 * <h3>Developer Guides</h3>
86 * <p>For more information about using content providers, read the
87 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
88 * developer guide.</p>
89 */
90public abstract class ContentProvider implements ComponentCallbacks2 {
91    private static final String TAG = "ContentProvider";
92
93    /*
94     * Note: if you add methods to ContentProvider, you must add similar methods to
95     *       MockContentProvider.
96     */
97
98    private Context mContext = null;
99    private int mMyUid;
100
101    // Since most Providers have only one authority, we keep both a String and a String[] to improve
102    // performance.
103    private String mAuthority;
104    private String[] mAuthorities;
105    private String mReadPermission;
106    private String mWritePermission;
107    private PathPermission[] mPathPermissions;
108    private boolean mExported;
109    private boolean mNoPerms;
110    private boolean mSingleUser;
111
112    private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
113
114    private Transport mTransport = new Transport();
115
116    /**
117     * Construct a ContentProvider instance.  Content providers must be
118     * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
119     * in the manifest</a>, accessed with {@link ContentResolver}, and created
120     * automatically by the system, so applications usually do not create
121     * ContentProvider instances directly.
122     *
123     * <p>At construction time, the object is uninitialized, and most fields and
124     * methods are unavailable.  Subclasses should initialize themselves in
125     * {@link #onCreate}, not the constructor.
126     *
127     * <p>Content providers are created on the application main thread at
128     * application launch time.  The constructor must not perform lengthy
129     * operations, or application startup will be delayed.
130     */
131    public ContentProvider() {
132    }
133
134    /**
135     * Constructor just for mocking.
136     *
137     * @param context A Context object which should be some mock instance (like the
138     * instance of {@link android.test.mock.MockContext}).
139     * @param readPermission The read permision you want this instance should have in the
140     * test, which is available via {@link #getReadPermission()}.
141     * @param writePermission The write permission you want this instance should have
142     * in the test, which is available via {@link #getWritePermission()}.
143     * @param pathPermissions The PathPermissions you want this instance should have
144     * in the test, which is available via {@link #getPathPermissions()}.
145     * @hide
146     */
147    public ContentProvider(
148            Context context,
149            String readPermission,
150            String writePermission,
151            PathPermission[] pathPermissions) {
152        mContext = context;
153        mReadPermission = readPermission;
154        mWritePermission = writePermission;
155        mPathPermissions = pathPermissions;
156    }
157
158    /**
159     * Given an IContentProvider, try to coerce it back to the real
160     * ContentProvider object if it is running in the local process.  This can
161     * be used if you know you are running in the same process as a provider,
162     * and want to get direct access to its implementation details.  Most
163     * clients should not nor have a reason to use it.
164     *
165     * @param abstractInterface The ContentProvider interface that is to be
166     *              coerced.
167     * @return If the IContentProvider is non-{@code null} and local, returns its actual
168     * ContentProvider instance.  Otherwise returns {@code null}.
169     * @hide
170     */
171    public static ContentProvider coerceToLocalContentProvider(
172            IContentProvider abstractInterface) {
173        if (abstractInterface instanceof Transport) {
174            return ((Transport)abstractInterface).getContentProvider();
175        }
176        return null;
177    }
178
179    /**
180     * Binder object that deals with remoting.
181     *
182     * @hide
183     */
184    class Transport extends ContentProviderNative {
185        AppOpsManager mAppOpsManager = null;
186        int mReadOp = AppOpsManager.OP_NONE;
187        int mWriteOp = AppOpsManager.OP_NONE;
188
189        ContentProvider getContentProvider() {
190            return ContentProvider.this;
191        }
192
193        @Override
194        public String getProviderName() {
195            return getContentProvider().getClass().getName();
196        }
197
198        @Override
199        public Cursor query(String callingPkg, Uri uri, String[] projection,
200                String selection, String[] selectionArgs, String sortOrder,
201                ICancellationSignal cancellationSignal) {
202            validateIncomingUri(uri);
203            uri = getUriWithoutUserId(uri);
204            if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
205                return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
206                        CancellationSignal.fromTransport(cancellationSignal));
207            }
208            final String original = setCallingPackage(callingPkg);
209            try {
210                return ContentProvider.this.query(
211                        uri, projection, selection, selectionArgs, sortOrder,
212                        CancellationSignal.fromTransport(cancellationSignal));
213            } finally {
214                setCallingPackage(original);
215            }
216        }
217
218        @Override
219        public String getType(Uri uri) {
220            validateIncomingUri(uri);
221            uri = getUriWithoutUserId(uri);
222            return ContentProvider.this.getType(uri);
223        }
224
225        @Override
226        public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
227            validateIncomingUri(uri);
228            int userId = getUserIdFromUri(uri);
229            uri = getUriWithoutUserId(uri);
230            if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
231                return rejectInsert(uri, initialValues);
232            }
233            final String original = setCallingPackage(callingPkg);
234            try {
235                return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
236            } finally {
237                setCallingPackage(original);
238            }
239        }
240
241        @Override
242        public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
243            validateIncomingUri(uri);
244            uri = getUriWithoutUserId(uri);
245            if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
246                return 0;
247            }
248            final String original = setCallingPackage(callingPkg);
249            try {
250                return ContentProvider.this.bulkInsert(uri, initialValues);
251            } finally {
252                setCallingPackage(original);
253            }
254        }
255
256        @Override
257        public ContentProviderResult[] applyBatch(String callingPkg,
258                ArrayList<ContentProviderOperation> operations)
259                throws OperationApplicationException {
260            int numOperations = operations.size();
261            final int[] userIds = new int[numOperations];
262            for (int i = 0; i < numOperations; i++) {
263                ContentProviderOperation operation = operations.get(i);
264                Uri uri = operation.getUri();
265                validateIncomingUri(uri);
266                userIds[i] = getUserIdFromUri(uri);
267                if (userIds[i] != UserHandle.USER_CURRENT) {
268                    // Removing the user id from the uri.
269                    operation = new ContentProviderOperation(operation, true);
270                    operations.set(i, operation);
271                }
272                if (operation.isReadOperation()) {
273                    if (enforceReadPermission(callingPkg, uri)
274                            != AppOpsManager.MODE_ALLOWED) {
275                        throw new OperationApplicationException("App op not allowed", 0);
276                    }
277                }
278                if (operation.isWriteOperation()) {
279                    if (enforceWritePermission(callingPkg, uri)
280                            != AppOpsManager.MODE_ALLOWED) {
281                        throw new OperationApplicationException("App op not allowed", 0);
282                    }
283                }
284            }
285            final String original = setCallingPackage(callingPkg);
286            try {
287                ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
288                for (int i = 0; i < results.length ; i++) {
289                    if (userIds[i] != UserHandle.USER_CURRENT) {
290                        // Adding the userId to the uri.
291                        results[i] = new ContentProviderResult(results[i], userIds[i]);
292                    }
293                }
294                return results;
295            } finally {
296                setCallingPackage(original);
297            }
298        }
299
300        @Override
301        public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
302            validateIncomingUri(uri);
303            uri = getUriWithoutUserId(uri);
304            if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
305                return 0;
306            }
307            final String original = setCallingPackage(callingPkg);
308            try {
309                return ContentProvider.this.delete(uri, selection, selectionArgs);
310            } finally {
311                setCallingPackage(original);
312            }
313        }
314
315        @Override
316        public int update(String callingPkg, Uri uri, ContentValues values, String selection,
317                String[] selectionArgs) {
318            validateIncomingUri(uri);
319            uri = getUriWithoutUserId(uri);
320            if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
321                return 0;
322            }
323            final String original = setCallingPackage(callingPkg);
324            try {
325                return ContentProvider.this.update(uri, values, selection, selectionArgs);
326            } finally {
327                setCallingPackage(original);
328            }
329        }
330
331        @Override
332        public ParcelFileDescriptor openFile(
333                String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
334                throws FileNotFoundException {
335            validateIncomingUri(uri);
336            uri = getUriWithoutUserId(uri);
337            enforceFilePermission(callingPkg, uri, mode);
338            final String original = setCallingPackage(callingPkg);
339            try {
340                return ContentProvider.this.openFile(
341                        uri, mode, CancellationSignal.fromTransport(cancellationSignal));
342            } finally {
343                setCallingPackage(original);
344            }
345        }
346
347        @Override
348        public AssetFileDescriptor openAssetFile(
349                String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
350                throws FileNotFoundException {
351            validateIncomingUri(uri);
352            uri = getUriWithoutUserId(uri);
353            enforceFilePermission(callingPkg, uri, mode);
354            final String original = setCallingPackage(callingPkg);
355            try {
356                return ContentProvider.this.openAssetFile(
357                        uri, mode, CancellationSignal.fromTransport(cancellationSignal));
358            } finally {
359                setCallingPackage(original);
360            }
361        }
362
363        @Override
364        public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
365            final String original = setCallingPackage(callingPkg);
366            try {
367                return ContentProvider.this.call(method, arg, extras);
368            } finally {
369                setCallingPackage(original);
370            }
371        }
372
373        @Override
374        public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
375            validateIncomingUri(uri);
376            uri = getUriWithoutUserId(uri);
377            return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
378        }
379
380        @Override
381        public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
382                Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
383            validateIncomingUri(uri);
384            uri = getUriWithoutUserId(uri);
385            enforceFilePermission(callingPkg, uri, "r");
386            final String original = setCallingPackage(callingPkg);
387            try {
388                return ContentProvider.this.openTypedAssetFile(
389                        uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
390            } finally {
391                setCallingPackage(original);
392            }
393        }
394
395        @Override
396        public ICancellationSignal createCancellationSignal() {
397            return CancellationSignal.createTransport();
398        }
399
400        @Override
401        public Uri canonicalize(String callingPkg, Uri uri) {
402            validateIncomingUri(uri);
403            int userId = getUserIdFromUri(uri);
404            uri = getUriWithoutUserId(uri);
405            if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
406                return null;
407            }
408            final String original = setCallingPackage(callingPkg);
409            try {
410                return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
411            } finally {
412                setCallingPackage(original);
413            }
414        }
415
416        @Override
417        public Uri uncanonicalize(String callingPkg, Uri uri) {
418            validateIncomingUri(uri);
419            int userId = getUserIdFromUri(uri);
420            uri = getUriWithoutUserId(uri);
421            if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
422                return null;
423            }
424            final String original = setCallingPackage(callingPkg);
425            try {
426                return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
427            } finally {
428                setCallingPackage(original);
429            }
430        }
431
432        private void enforceFilePermission(String callingPkg, Uri uri, String mode)
433                throws FileNotFoundException, SecurityException {
434            if (mode != null && mode.indexOf('w') != -1) {
435                if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
436                    throw new FileNotFoundException("App op not allowed");
437                }
438            } else {
439                if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
440                    throw new FileNotFoundException("App op not allowed");
441                }
442            }
443        }
444
445        private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
446            enforceReadPermissionInner(uri);
447            if (mReadOp != AppOpsManager.OP_NONE) {
448                return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
449            }
450            return AppOpsManager.MODE_ALLOWED;
451        }
452
453        private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
454            enforceWritePermissionInner(uri);
455            if (mWriteOp != AppOpsManager.OP_NONE) {
456                return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
457            }
458            return AppOpsManager.MODE_ALLOWED;
459        }
460    }
461
462    boolean checkUser(int pid, int uid, Context context) {
463        return UserHandle.getUserId(uid) == context.getUserId()
464                || mSingleUser
465                || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
466                == PERMISSION_GRANTED;
467    }
468
469    /** {@hide} */
470    protected void enforceReadPermissionInner(Uri uri) throws SecurityException {
471        final Context context = getContext();
472        final int pid = Binder.getCallingPid();
473        final int uid = Binder.getCallingUid();
474        String missingPerm = null;
475
476        if (UserHandle.isSameApp(uid, mMyUid)) {
477            return;
478        }
479
480        if (mExported && checkUser(pid, uid, context)) {
481            final String componentPerm = getReadPermission();
482            if (componentPerm != null) {
483                if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
484                    return;
485                } else {
486                    missingPerm = componentPerm;
487                }
488            }
489
490            // track if unprotected read is allowed; any denied
491            // <path-permission> below removes this ability
492            boolean allowDefaultRead = (componentPerm == null);
493
494            final PathPermission[] pps = getPathPermissions();
495            if (pps != null) {
496                final String path = uri.getPath();
497                for (PathPermission pp : pps) {
498                    final String pathPerm = pp.getReadPermission();
499                    if (pathPerm != null && pp.match(path)) {
500                        if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
501                            return;
502                        } else {
503                            // any denied <path-permission> means we lose
504                            // default <provider> access.
505                            allowDefaultRead = false;
506                            missingPerm = pathPerm;
507                        }
508                    }
509                }
510            }
511
512            // if we passed <path-permission> checks above, and no default
513            // <provider> permission, then allow access.
514            if (allowDefaultRead) return;
515        }
516
517        // last chance, check against any uri grants
518        final int callingUserId = UserHandle.getUserId(uid);
519        final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
520                ? maybeAddUserId(uri, callingUserId) : uri;
521        if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
522                == PERMISSION_GRANTED) {
523            return;
524        }
525
526        final String failReason = mExported
527                ? " requires " + missingPerm + ", or grantUriPermission()"
528                : " requires the provider be exported, or grantUriPermission()";
529        throw new SecurityException("Permission Denial: reading "
530                + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
531                + ", uid=" + uid + failReason);
532    }
533
534    /** {@hide} */
535    protected void enforceWritePermissionInner(Uri uri) throws SecurityException {
536        final Context context = getContext();
537        final int pid = Binder.getCallingPid();
538        final int uid = Binder.getCallingUid();
539        String missingPerm = null;
540
541        if (UserHandle.isSameApp(uid, mMyUid)) {
542            return;
543        }
544
545        if (mExported && checkUser(pid, uid, context)) {
546            final String componentPerm = getWritePermission();
547            if (componentPerm != null) {
548                if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
549                    return;
550                } else {
551                    missingPerm = componentPerm;
552                }
553            }
554
555            // track if unprotected write is allowed; any denied
556            // <path-permission> below removes this ability
557            boolean allowDefaultWrite = (componentPerm == null);
558
559            final PathPermission[] pps = getPathPermissions();
560            if (pps != null) {
561                final String path = uri.getPath();
562                for (PathPermission pp : pps) {
563                    final String pathPerm = pp.getWritePermission();
564                    if (pathPerm != null && pp.match(path)) {
565                        if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
566                            return;
567                        } else {
568                            // any denied <path-permission> means we lose
569                            // default <provider> access.
570                            allowDefaultWrite = false;
571                            missingPerm = pathPerm;
572                        }
573                    }
574                }
575            }
576
577            // if we passed <path-permission> checks above, and no default
578            // <provider> permission, then allow access.
579            if (allowDefaultWrite) return;
580        }
581
582        // last chance, check against any uri grants
583        if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
584                == PERMISSION_GRANTED) {
585            return;
586        }
587
588        final String failReason = mExported
589                ? " requires " + missingPerm + ", or grantUriPermission()"
590                : " requires the provider be exported, or grantUriPermission()";
591        throw new SecurityException("Permission Denial: writing "
592                + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
593                + ", uid=" + uid + failReason);
594    }
595
596    /**
597     * Retrieves the Context this provider is running in.  Only available once
598     * {@link #onCreate} has been called -- this will return {@code null} in the
599     * constructor.
600     */
601    public final Context getContext() {
602        return mContext;
603    }
604
605    /**
606     * Set the calling package, returning the current value (or {@code null})
607     * which can be used later to restore the previous state.
608     */
609    private String setCallingPackage(String callingPackage) {
610        final String original = mCallingPackage.get();
611        mCallingPackage.set(callingPackage);
612        return original;
613    }
614
615    /**
616     * Return the package name of the caller that initiated the request being
617     * processed on the current thread. The returned package will have been
618     * verified to belong to the calling UID. Returns {@code null} if not
619     * currently processing a request.
620     * <p>
621     * This will always return {@code null} when processing
622     * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
623     *
624     * @see Binder#getCallingUid()
625     * @see Context#grantUriPermission(String, Uri, int)
626     * @throws SecurityException if the calling package doesn't belong to the
627     *             calling UID.
628     */
629    public final String getCallingPackage() {
630        final String pkg = mCallingPackage.get();
631        if (pkg != null) {
632            mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
633        }
634        return pkg;
635    }
636
637    /**
638     * Change the authorities of the ContentProvider.
639     * This is normally set for you from its manifest information when the provider is first
640     * created.
641     * @hide
642     * @param authorities the semi-colon separated authorities of the ContentProvider.
643     */
644    protected final void setAuthorities(String authorities) {
645        if (authorities != null) {
646            if (authorities.indexOf(';') == -1) {
647                mAuthority = authorities;
648                mAuthorities = null;
649            } else {
650                mAuthority = null;
651                mAuthorities = authorities.split(";");
652            }
653        }
654    }
655
656    /** @hide */
657    protected final boolean matchesOurAuthorities(String authority) {
658        if (mAuthority != null) {
659            return mAuthority.equals(authority);
660        }
661        if (mAuthorities != null) {
662            int length = mAuthorities.length;
663            for (int i = 0; i < length; i++) {
664                if (mAuthorities[i].equals(authority)) return true;
665            }
666        }
667        return false;
668    }
669
670
671    /**
672     * Change the permission required to read data from the content
673     * provider.  This is normally set for you from its manifest information
674     * when the provider is first created.
675     *
676     * @param permission Name of the permission required for read-only access.
677     */
678    protected final void setReadPermission(String permission) {
679        mReadPermission = permission;
680    }
681
682    /**
683     * Return the name of the permission required for read-only access to
684     * this content provider.  This method can be called from multiple
685     * threads, as described in
686     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
687     * and Threads</a>.
688     */
689    public final String getReadPermission() {
690        return mReadPermission;
691    }
692
693    /**
694     * Change the permission required to read and write data in the content
695     * provider.  This is normally set for you from its manifest information
696     * when the provider is first created.
697     *
698     * @param permission Name of the permission required for read/write access.
699     */
700    protected final void setWritePermission(String permission) {
701        mWritePermission = permission;
702    }
703
704    /**
705     * Return the name of the permission required for read/write access to
706     * this content provider.  This method can be called from multiple
707     * threads, as described in
708     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
709     * and Threads</a>.
710     */
711    public final String getWritePermission() {
712        return mWritePermission;
713    }
714
715    /**
716     * Change the path-based permission required to read and/or write data in
717     * the content provider.  This is normally set for you from its manifest
718     * information when the provider is first created.
719     *
720     * @param permissions Array of path permission descriptions.
721     */
722    protected final void setPathPermissions(PathPermission[] permissions) {
723        mPathPermissions = permissions;
724    }
725
726    /**
727     * Return the path-based permissions required for read and/or write access to
728     * this content provider.  This method can be called from multiple
729     * threads, as described in
730     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
731     * and Threads</a>.
732     */
733    public final PathPermission[] getPathPermissions() {
734        return mPathPermissions;
735    }
736
737    /** @hide */
738    public final void setAppOps(int readOp, int writeOp) {
739        if (!mNoPerms) {
740            mTransport.mReadOp = readOp;
741            mTransport.mWriteOp = writeOp;
742        }
743    }
744
745    /** @hide */
746    public AppOpsManager getAppOpsManager() {
747        return mTransport.mAppOpsManager;
748    }
749
750    /**
751     * Implement this to initialize your content provider on startup.
752     * This method is called for all registered content providers on the
753     * application main thread at application launch time.  It must not perform
754     * lengthy operations, or application startup will be delayed.
755     *
756     * <p>You should defer nontrivial initialization (such as opening,
757     * upgrading, and scanning databases) until the content provider is used
758     * (via {@link #query}, {@link #insert}, etc).  Deferred initialization
759     * keeps application startup fast, avoids unnecessary work if the provider
760     * turns out not to be needed, and stops database errors (such as a full
761     * disk) from halting application launch.
762     *
763     * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
764     * is a helpful utility class that makes it easy to manage databases,
765     * and will automatically defer opening until first use.  If you do use
766     * SQLiteOpenHelper, make sure to avoid calling
767     * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
768     * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
769     * from this method.  (Instead, override
770     * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
771     * database when it is first opened.)
772     *
773     * @return true if the provider was successfully loaded, false otherwise
774     */
775    public abstract boolean onCreate();
776
777    /**
778     * {@inheritDoc}
779     * This method is always called on the application main thread, and must
780     * not perform lengthy operations.
781     *
782     * <p>The default content provider implementation does nothing.
783     * Override this method to take appropriate action.
784     * (Content providers do not usually care about things like screen
785     * orientation, but may want to know about locale changes.)
786     */
787    public void onConfigurationChanged(Configuration newConfig) {
788    }
789
790    /**
791     * {@inheritDoc}
792     * This method is always called on the application main thread, and must
793     * not perform lengthy operations.
794     *
795     * <p>The default content provider implementation does nothing.
796     * Subclasses may override this method to take appropriate action.
797     */
798    public void onLowMemory() {
799    }
800
801    public void onTrimMemory(int level) {
802    }
803
804    /**
805     * @hide
806     * Implementation when a caller has performed a query on the content
807     * provider, but that call has been rejected for the operation given
808     * to {@link #setAppOps(int, int)}.  The default implementation
809     * rewrites the <var>selection</var> argument to include a condition
810     * that is never true (so will always result in an empty cursor)
811     * and calls through to {@link #query(android.net.Uri, String[], String, String[],
812     * String, android.os.CancellationSignal)} with that.
813     */
814    public Cursor rejectQuery(Uri uri, String[] projection,
815            String selection, String[] selectionArgs, String sortOrder,
816            CancellationSignal cancellationSignal) {
817        // The read is not allowed...  to fake it out, we replace the given
818        // selection statement with a dummy one that will always be false.
819        // This way we will get a cursor back that has the correct structure
820        // but contains no rows.
821        if (selection == null || selection.isEmpty()) {
822            selection = "'A' = 'B'";
823        } else {
824            selection = "'A' = 'B' AND (" + selection + ")";
825        }
826        return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
827    }
828
829    /**
830     * Implement this to handle query requests from clients.
831     * This method can be called from multiple threads, as described in
832     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
833     * and Threads</a>.
834     * <p>
835     * Example client call:<p>
836     * <pre>// Request a specific record.
837     * Cursor managedCursor = managedQuery(
838                ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
839                projection,    // Which columns to return.
840                null,          // WHERE clause.
841                null,          // WHERE clause value substitution
842                People.NAME + " ASC");   // Sort order.</pre>
843     * Example implementation:<p>
844     * <pre>// SQLiteQueryBuilder is a helper class that creates the
845        // proper SQL syntax for us.
846        SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
847
848        // Set the table we're querying.
849        qBuilder.setTables(DATABASE_TABLE_NAME);
850
851        // If the query ends in a specific record number, we're
852        // being asked for a specific record, so set the
853        // WHERE clause in our query.
854        if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
855            qBuilder.appendWhere("_id=" + uri.getPathLeafId());
856        }
857
858        // Make the query.
859        Cursor c = qBuilder.query(mDb,
860                projection,
861                selection,
862                selectionArgs,
863                groupBy,
864                having,
865                sortOrder);
866        c.setNotificationUri(getContext().getContentResolver(), uri);
867        return c;</pre>
868     *
869     * @param uri The URI to query. This will be the full URI sent by the client;
870     *      if the client is requesting a specific record, the URI will end in a record number
871     *      that the implementation should parse and add to a WHERE or HAVING clause, specifying
872     *      that _id value.
873     * @param projection The list of columns to put into the cursor. If
874     *      {@code null} all columns are included.
875     * @param selection A selection criteria to apply when filtering rows.
876     *      If {@code null} then all rows are included.
877     * @param selectionArgs You may include ?s in selection, which will be replaced by
878     *      the values from selectionArgs, in order that they appear in the selection.
879     *      The values will be bound as Strings.
880     * @param sortOrder How the rows in the cursor should be sorted.
881     *      If {@code null} then the provider is free to define the sort order.
882     * @return a Cursor or {@code null}.
883     */
884    public abstract Cursor query(Uri uri, String[] projection,
885            String selection, String[] selectionArgs, String sortOrder);
886
887    /**
888     * Implement this to handle query requests from clients with support for cancellation.
889     * This method can be called from multiple threads, as described in
890     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
891     * and Threads</a>.
892     * <p>
893     * Example client call:<p>
894     * <pre>// Request a specific record.
895     * Cursor managedCursor = managedQuery(
896                ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
897                projection,    // Which columns to return.
898                null,          // WHERE clause.
899                null,          // WHERE clause value substitution
900                People.NAME + " ASC");   // Sort order.</pre>
901     * Example implementation:<p>
902     * <pre>// SQLiteQueryBuilder is a helper class that creates the
903        // proper SQL syntax for us.
904        SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
905
906        // Set the table we're querying.
907        qBuilder.setTables(DATABASE_TABLE_NAME);
908
909        // If the query ends in a specific record number, we're
910        // being asked for a specific record, so set the
911        // WHERE clause in our query.
912        if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
913            qBuilder.appendWhere("_id=" + uri.getPathLeafId());
914        }
915
916        // Make the query.
917        Cursor c = qBuilder.query(mDb,
918                projection,
919                selection,
920                selectionArgs,
921                groupBy,
922                having,
923                sortOrder);
924        c.setNotificationUri(getContext().getContentResolver(), uri);
925        return c;</pre>
926     * <p>
927     * If you implement this method then you must also implement the version of
928     * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
929     * signal to ensure correct operation on older versions of the Android Framework in
930     * which the cancellation signal overload was not available.
931     *
932     * @param uri The URI to query. This will be the full URI sent by the client;
933     *      if the client is requesting a specific record, the URI will end in a record number
934     *      that the implementation should parse and add to a WHERE or HAVING clause, specifying
935     *      that _id value.
936     * @param projection The list of columns to put into the cursor. If
937     *      {@code null} all columns are included.
938     * @param selection A selection criteria to apply when filtering rows.
939     *      If {@code null} then all rows are included.
940     * @param selectionArgs You may include ?s in selection, which will be replaced by
941     *      the values from selectionArgs, in order that they appear in the selection.
942     *      The values will be bound as Strings.
943     * @param sortOrder How the rows in the cursor should be sorted.
944     *      If {@code null} then the provider is free to define the sort order.
945     * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
946     * If the operation is canceled, then {@link OperationCanceledException} will be thrown
947     * when the query is executed.
948     * @return a Cursor or {@code null}.
949     */
950    public Cursor query(Uri uri, String[] projection,
951            String selection, String[] selectionArgs, String sortOrder,
952            CancellationSignal cancellationSignal) {
953        return query(uri, projection, selection, selectionArgs, sortOrder);
954    }
955
956    /**
957     * Implement this to handle requests for the MIME type of the data at the
958     * given URI.  The returned MIME type should start with
959     * <code>vnd.android.cursor.item</code> for a single record,
960     * or <code>vnd.android.cursor.dir/</code> for multiple items.
961     * This method can be called from multiple threads, as described in
962     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
963     * and Threads</a>.
964     *
965     * <p>Note that there are no permissions needed for an application to
966     * access this information; if your content provider requires read and/or
967     * write permissions, or is not exported, all applications can still call
968     * this method regardless of their access permissions.  This allows them
969     * to retrieve the MIME type for a URI when dispatching intents.
970     *
971     * @param uri the URI to query.
972     * @return a MIME type string, or {@code null} if there is no type.
973     */
974    public abstract String getType(Uri uri);
975
976    /**
977     * Implement this to support canonicalization of URIs that refer to your
978     * content provider.  A canonical URI is one that can be transported across
979     * devices, backup/restore, and other contexts, and still be able to refer
980     * to the same data item.  Typically this is implemented by adding query
981     * params to the URI allowing the content provider to verify that an incoming
982     * canonical URI references the same data as it was originally intended for and,
983     * if it doesn't, to find that data (if it exists) in the current environment.
984     *
985     * <p>For example, if the content provider holds people and a normal URI in it
986     * is created with a row index into that people database, the cananical representation
987     * may have an additional query param at the end which specifies the name of the
988     * person it is intended for.  Later calls into the provider with that URI will look
989     * up the row of that URI's base index and, if it doesn't match or its entry's
990     * name doesn't match the name in the query param, perform a query on its database
991     * to find the correct row to operate on.</p>
992     *
993     * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
994     * URIs (including this one) must perform this verification and recovery of any
995     * canonical URIs they receive.  In addition, you must also implement
996     * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
997     *
998     * <p>The default implementation of this method returns null, indicating that
999     * canonical URIs are not supported.</p>
1000     *
1001     * @param url The Uri to canonicalize.
1002     *
1003     * @return Return the canonical representation of <var>url</var>, or null if
1004     * canonicalization of that Uri is not supported.
1005     */
1006    public Uri canonicalize(Uri url) {
1007        return null;
1008    }
1009
1010    /**
1011     * Remove canonicalization from canonical URIs previously returned by
1012     * {@link #canonicalize}.  For example, if your implementation is to add
1013     * a query param to canonicalize a URI, this method can simply trip any
1014     * query params on the URI.  The default implementation always returns the
1015     * same <var>url</var> that was passed in.
1016     *
1017     * @param url The Uri to remove any canonicalization from.
1018     *
1019     * @return Return the non-canonical representation of <var>url</var>, return
1020     * the <var>url</var> as-is if there is nothing to do, or return null if
1021     * the data identified by the canonical representation can not be found in
1022     * the current environment.
1023     */
1024    public Uri uncanonicalize(Uri url) {
1025        return url;
1026    }
1027
1028    /**
1029     * @hide
1030     * Implementation when a caller has performed an insert on the content
1031     * provider, but that call has been rejected for the operation given
1032     * to {@link #setAppOps(int, int)}.  The default implementation simply
1033     * returns a dummy URI that is the base URI with a 0 path element
1034     * appended.
1035     */
1036    public Uri rejectInsert(Uri uri, ContentValues values) {
1037        // If not allowed, we need to return some reasonable URI.  Maybe the
1038        // content provider should be responsible for this, but for now we
1039        // will just return the base URI with a dummy '0' tagged on to it.
1040        // You shouldn't be able to read if you can't write, anyway, so it
1041        // shouldn't matter much what is returned.
1042        return uri.buildUpon().appendPath("0").build();
1043    }
1044
1045    /**
1046     * Implement this to handle requests to insert a new row.
1047     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1048     * after inserting.
1049     * This method can be called from multiple threads, as described in
1050     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1051     * and Threads</a>.
1052     * @param uri The content:// URI of the insertion request. This must not be {@code null}.
1053     * @param values A set of column_name/value pairs to add to the database.
1054     *     This must not be {@code null}.
1055     * @return The URI for the newly inserted item.
1056     */
1057    public abstract Uri insert(Uri uri, ContentValues values);
1058
1059    /**
1060     * Override this to handle requests to insert a set of new rows, or the
1061     * default implementation will iterate over the values and call
1062     * {@link #insert} on each of them.
1063     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1064     * after inserting.
1065     * This method can be called from multiple threads, as described in
1066     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1067     * and Threads</a>.
1068     *
1069     * @param uri The content:// URI of the insertion request.
1070     * @param values An array of sets of column_name/value pairs to add to the database.
1071     *    This must not be {@code null}.
1072     * @return The number of values that were inserted.
1073     */
1074    public int bulkInsert(Uri uri, ContentValues[] values) {
1075        int numValues = values.length;
1076        for (int i = 0; i < numValues; i++) {
1077            insert(uri, values[i]);
1078        }
1079        return numValues;
1080    }
1081
1082    /**
1083     * Implement this to handle requests to delete one or more rows.
1084     * The implementation should apply the selection clause when performing
1085     * deletion, allowing the operation to affect multiple rows in a directory.
1086     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1087     * after deleting.
1088     * This method can be called from multiple threads, as described in
1089     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1090     * and Threads</a>.
1091     *
1092     * <p>The implementation is responsible for parsing out a row ID at the end
1093     * of the URI, if a specific row is being deleted. That is, the client would
1094     * pass in <code>content://contacts/people/22</code> and the implementation is
1095     * responsible for parsing the record number (22) when creating a SQL statement.
1096     *
1097     * @param uri The full URI to query, including a row ID (if a specific record is requested).
1098     * @param selection An optional restriction to apply to rows when deleting.
1099     * @return The number of rows affected.
1100     * @throws SQLException
1101     */
1102    public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1103
1104    /**
1105     * Implement this to handle requests to update one or more rows.
1106     * The implementation should update all rows matching the selection
1107     * to set the columns according to the provided values map.
1108     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1109     * after updating.
1110     * This method can be called from multiple threads, as described in
1111     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1112     * and Threads</a>.
1113     *
1114     * @param uri The URI to query. This can potentially have a record ID if this
1115     * is an update request for a specific record.
1116     * @param values A set of column_name/value pairs to update in the database.
1117     *     This must not be {@code null}.
1118     * @param selection An optional filter to match rows to update.
1119     * @return the number of rows affected.
1120     */
1121    public abstract int update(Uri uri, ContentValues values, String selection,
1122            String[] selectionArgs);
1123
1124    /**
1125     * Override this to handle requests to open a file blob.
1126     * The default implementation always throws {@link FileNotFoundException}.
1127     * This method can be called from multiple threads, as described in
1128     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1129     * and Threads</a>.
1130     *
1131     * <p>This method returns a ParcelFileDescriptor, which is returned directly
1132     * to the caller.  This way large data (such as images and documents) can be
1133     * returned without copying the content.
1134     *
1135     * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1136     * their responsibility to close it when done.  That is, the implementation
1137     * of this method should create a new ParcelFileDescriptor for each call.
1138     * <p>
1139     * If opened with the exclusive "r" or "w" modes, the returned
1140     * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1141     * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1142     * supports seeking.
1143     * <p>
1144     * If you need to detect when the returned ParcelFileDescriptor has been
1145     * closed, or if the remote process has crashed or encountered some other
1146     * error, you can use {@link ParcelFileDescriptor#open(File, int,
1147     * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1148     * {@link ParcelFileDescriptor#createReliablePipe()}, or
1149     * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1150     *
1151     * <p class="note">For use in Intents, you will want to implement {@link #getType}
1152     * to return the appropriate MIME type for the data returned here with
1153     * the same URI.  This will allow intent resolution to automatically determine the data MIME
1154     * type and select the appropriate matching targets as part of its operation.</p>
1155     *
1156     * <p class="note">For better interoperability with other applications, it is recommended
1157     * that for any URIs that can be opened, you also support queries on them
1158     * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1159     * You may also want to support other common columns if you have additional meta-data
1160     * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1161     * in {@link android.provider.MediaStore.MediaColumns}.</p>
1162     *
1163     * @param uri The URI whose file is to be opened.
1164     * @param mode Access mode for the file.  May be "r" for read-only access,
1165     * "rw" for read and write access, or "rwt" for read and write access
1166     * that truncates any existing file.
1167     *
1168     * @return Returns a new ParcelFileDescriptor which you can use to access
1169     * the file.
1170     *
1171     * @throws FileNotFoundException Throws FileNotFoundException if there is
1172     * no file associated with the given URI or the mode is invalid.
1173     * @throws SecurityException Throws SecurityException if the caller does
1174     * not have permission to access the file.
1175     *
1176     * @see #openAssetFile(Uri, String)
1177     * @see #openFileHelper(Uri, String)
1178     * @see #getType(android.net.Uri)
1179     * @see ParcelFileDescriptor#parseMode(String)
1180     */
1181    public ParcelFileDescriptor openFile(Uri uri, String mode)
1182            throws FileNotFoundException {
1183        throw new FileNotFoundException("No files supported by provider at "
1184                + uri);
1185    }
1186
1187    /**
1188     * Override this to handle requests to open a file blob.
1189     * The default implementation always throws {@link FileNotFoundException}.
1190     * This method can be called from multiple threads, as described in
1191     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1192     * and Threads</a>.
1193     *
1194     * <p>This method returns a ParcelFileDescriptor, which is returned directly
1195     * to the caller.  This way large data (such as images and documents) can be
1196     * returned without copying the content.
1197     *
1198     * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1199     * their responsibility to close it when done.  That is, the implementation
1200     * of this method should create a new ParcelFileDescriptor for each call.
1201     * <p>
1202     * If opened with the exclusive "r" or "w" modes, the returned
1203     * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1204     * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1205     * supports seeking.
1206     * <p>
1207     * If you need to detect when the returned ParcelFileDescriptor has been
1208     * closed, or if the remote process has crashed or encountered some other
1209     * error, you can use {@link ParcelFileDescriptor#open(File, int,
1210     * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1211     * {@link ParcelFileDescriptor#createReliablePipe()}, or
1212     * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1213     *
1214     * <p class="note">For use in Intents, you will want to implement {@link #getType}
1215     * to return the appropriate MIME type for the data returned here with
1216     * the same URI.  This will allow intent resolution to automatically determine the data MIME
1217     * type and select the appropriate matching targets as part of its operation.</p>
1218     *
1219     * <p class="note">For better interoperability with other applications, it is recommended
1220     * that for any URIs that can be opened, you also support queries on them
1221     * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1222     * You may also want to support other common columns if you have additional meta-data
1223     * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1224     * in {@link android.provider.MediaStore.MediaColumns}.</p>
1225     *
1226     * @param uri The URI whose file is to be opened.
1227     * @param mode Access mode for the file. May be "r" for read-only access,
1228     *            "w" for write-only access, "rw" for read and write access, or
1229     *            "rwt" for read and write access that truncates any existing
1230     *            file.
1231     * @param signal A signal to cancel the operation in progress, or
1232     *            {@code null} if none. For example, if you are downloading a
1233     *            file from the network to service a "rw" mode request, you
1234     *            should periodically call
1235     *            {@link CancellationSignal#throwIfCanceled()} to check whether
1236     *            the client has canceled the request and abort the download.
1237     *
1238     * @return Returns a new ParcelFileDescriptor which you can use to access
1239     * the file.
1240     *
1241     * @throws FileNotFoundException Throws FileNotFoundException if there is
1242     * no file associated with the given URI or the mode is invalid.
1243     * @throws SecurityException Throws SecurityException if the caller does
1244     * not have permission to access the file.
1245     *
1246     * @see #openAssetFile(Uri, String)
1247     * @see #openFileHelper(Uri, String)
1248     * @see #getType(android.net.Uri)
1249     * @see ParcelFileDescriptor#parseMode(String)
1250     */
1251    public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1252            throws FileNotFoundException {
1253        return openFile(uri, mode);
1254    }
1255
1256    /**
1257     * This is like {@link #openFile}, but can be implemented by providers
1258     * that need to be able to return sub-sections of files, often assets
1259     * inside of their .apk.
1260     * This method can be called from multiple threads, as described in
1261     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1262     * and Threads</a>.
1263     *
1264     * <p>If you implement this, your clients must be able to deal with such
1265     * file slices, either directly with
1266     * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1267     * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1268     * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1269     * methods.
1270     * <p>
1271     * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1272     * streaming of data.
1273     *
1274     * <p class="note">If you are implementing this to return a full file, you
1275     * should create the AssetFileDescriptor with
1276     * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1277     * applications that cannot handle sub-sections of files.</p>
1278     *
1279     * <p class="note">For use in Intents, you will want to implement {@link #getType}
1280     * to return the appropriate MIME type for the data returned here with
1281     * the same URI.  This will allow intent resolution to automatically determine the data MIME
1282     * type and select the appropriate matching targets as part of its operation.</p>
1283     *
1284     * <p class="note">For better interoperability with other applications, it is recommended
1285     * that for any URIs that can be opened, you also support queries on them
1286     * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1287     *
1288     * @param uri The URI whose file is to be opened.
1289     * @param mode Access mode for the file.  May be "r" for read-only access,
1290     * "w" for write-only access (erasing whatever data is currently in
1291     * the file), "wa" for write-only access to append to any existing data,
1292     * "rw" for read and write access on any existing data, and "rwt" for read
1293     * and write access that truncates any existing file.
1294     *
1295     * @return Returns a new AssetFileDescriptor which you can use to access
1296     * the file.
1297     *
1298     * @throws FileNotFoundException Throws FileNotFoundException if there is
1299     * no file associated with the given URI or the mode is invalid.
1300     * @throws SecurityException Throws SecurityException if the caller does
1301     * not have permission to access the file.
1302     *
1303     * @see #openFile(Uri, String)
1304     * @see #openFileHelper(Uri, String)
1305     * @see #getType(android.net.Uri)
1306     */
1307    public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1308            throws FileNotFoundException {
1309        ParcelFileDescriptor fd = openFile(uri, mode);
1310        return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1311    }
1312
1313    /**
1314     * This is like {@link #openFile}, but can be implemented by providers
1315     * that need to be able to return sub-sections of files, often assets
1316     * inside of their .apk.
1317     * This method can be called from multiple threads, as described in
1318     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1319     * and Threads</a>.
1320     *
1321     * <p>If you implement this, your clients must be able to deal with such
1322     * file slices, either directly with
1323     * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1324     * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1325     * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1326     * methods.
1327     * <p>
1328     * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1329     * streaming of data.
1330     *
1331     * <p class="note">If you are implementing this to return a full file, you
1332     * should create the AssetFileDescriptor with
1333     * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1334     * applications that cannot handle sub-sections of files.</p>
1335     *
1336     * <p class="note">For use in Intents, you will want to implement {@link #getType}
1337     * to return the appropriate MIME type for the data returned here with
1338     * the same URI.  This will allow intent resolution to automatically determine the data MIME
1339     * type and select the appropriate matching targets as part of its operation.</p>
1340     *
1341     * <p class="note">For better interoperability with other applications, it is recommended
1342     * that for any URIs that can be opened, you also support queries on them
1343     * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1344     *
1345     * @param uri The URI whose file is to be opened.
1346     * @param mode Access mode for the file.  May be "r" for read-only access,
1347     * "w" for write-only access (erasing whatever data is currently in
1348     * the file), "wa" for write-only access to append to any existing data,
1349     * "rw" for read and write access on any existing data, and "rwt" for read
1350     * and write access that truncates any existing file.
1351     * @param signal A signal to cancel the operation in progress, or
1352     *            {@code null} if none. For example, if you are downloading a
1353     *            file from the network to service a "rw" mode request, you
1354     *            should periodically call
1355     *            {@link CancellationSignal#throwIfCanceled()} to check whether
1356     *            the client has canceled the request and abort the download.
1357     *
1358     * @return Returns a new AssetFileDescriptor which you can use to access
1359     * the file.
1360     *
1361     * @throws FileNotFoundException Throws FileNotFoundException if there is
1362     * no file associated with the given URI or the mode is invalid.
1363     * @throws SecurityException Throws SecurityException if the caller does
1364     * not have permission to access the file.
1365     *
1366     * @see #openFile(Uri, String)
1367     * @see #openFileHelper(Uri, String)
1368     * @see #getType(android.net.Uri)
1369     */
1370    public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1371            throws FileNotFoundException {
1372        return openAssetFile(uri, mode);
1373    }
1374
1375    /**
1376     * Convenience for subclasses that wish to implement {@link #openFile}
1377     * by looking up a column named "_data" at the given URI.
1378     *
1379     * @param uri The URI to be opened.
1380     * @param mode The file mode.  May be "r" for read-only access,
1381     * "w" for write-only access (erasing whatever data is currently in
1382     * the file), "wa" for write-only access to append to any existing data,
1383     * "rw" for read and write access on any existing data, and "rwt" for read
1384     * and write access that truncates any existing file.
1385     *
1386     * @return Returns a new ParcelFileDescriptor that can be used by the
1387     * client to access the file.
1388     */
1389    protected final ParcelFileDescriptor openFileHelper(Uri uri,
1390            String mode) throws FileNotFoundException {
1391        Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1392        int count = (c != null) ? c.getCount() : 0;
1393        if (count != 1) {
1394            // If there is not exactly one result, throw an appropriate
1395            // exception.
1396            if (c != null) {
1397                c.close();
1398            }
1399            if (count == 0) {
1400                throw new FileNotFoundException("No entry for " + uri);
1401            }
1402            throw new FileNotFoundException("Multiple items at " + uri);
1403        }
1404
1405        c.moveToFirst();
1406        int i = c.getColumnIndex("_data");
1407        String path = (i >= 0 ? c.getString(i) : null);
1408        c.close();
1409        if (path == null) {
1410            throw new FileNotFoundException("Column _data not found.");
1411        }
1412
1413        int modeBits = ParcelFileDescriptor.parseMode(mode);
1414        return ParcelFileDescriptor.open(new File(path), modeBits);
1415    }
1416
1417    /**
1418     * Called by a client to determine the types of data streams that this
1419     * content provider supports for the given URI.  The default implementation
1420     * returns {@code null}, meaning no types.  If your content provider stores data
1421     * of a particular type, return that MIME type if it matches the given
1422     * mimeTypeFilter.  If it can perform type conversions, return an array
1423     * of all supported MIME types that match mimeTypeFilter.
1424     *
1425     * @param uri The data in the content provider being queried.
1426     * @param mimeTypeFilter The type of data the client desires.  May be
1427     * a pattern, such as *&#47;* to retrieve all possible data types.
1428     * @return Returns {@code null} if there are no possible data streams for the
1429     * given mimeTypeFilter.  Otherwise returns an array of all available
1430     * concrete MIME types.
1431     *
1432     * @see #getType(Uri)
1433     * @see #openTypedAssetFile(Uri, String, Bundle)
1434     * @see ClipDescription#compareMimeTypes(String, String)
1435     */
1436    public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1437        return null;
1438    }
1439
1440    /**
1441     * Called by a client to open a read-only stream containing data of a
1442     * particular MIME type.  This is like {@link #openAssetFile(Uri, String)},
1443     * except the file can only be read-only and the content provider may
1444     * perform data conversions to generate data of the desired type.
1445     *
1446     * <p>The default implementation compares the given mimeType against the
1447     * result of {@link #getType(Uri)} and, if they match, simply calls
1448     * {@link #openAssetFile(Uri, String)}.
1449     *
1450     * <p>See {@link ClipData} for examples of the use and implementation
1451     * of this method.
1452     * <p>
1453     * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1454     * streaming of data.
1455     *
1456     * <p class="note">For better interoperability with other applications, it is recommended
1457     * that for any URIs that can be opened, you also support queries on them
1458     * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1459     * You may also want to support other common columns if you have additional meta-data
1460     * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1461     * in {@link android.provider.MediaStore.MediaColumns}.</p>
1462     *
1463     * @param uri The data in the content provider being queried.
1464     * @param mimeTypeFilter The type of data the client desires.  May be
1465     * a pattern, such as *&#47;*, if the caller does not have specific type
1466     * requirements; in this case the content provider will pick its best
1467     * type matching the pattern.
1468     * @param opts Additional options from the client.  The definitions of
1469     * these are specific to the content provider being called.
1470     *
1471     * @return Returns a new AssetFileDescriptor from which the client can
1472     * read data of the desired type.
1473     *
1474     * @throws FileNotFoundException Throws FileNotFoundException if there is
1475     * no file associated with the given URI or the mode is invalid.
1476     * @throws SecurityException Throws SecurityException if the caller does
1477     * not have permission to access the data.
1478     * @throws IllegalArgumentException Throws IllegalArgumentException if the
1479     * content provider does not support the requested MIME type.
1480     *
1481     * @see #getStreamTypes(Uri, String)
1482     * @see #openAssetFile(Uri, String)
1483     * @see ClipDescription#compareMimeTypes(String, String)
1484     */
1485    public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1486            throws FileNotFoundException {
1487        if ("*/*".equals(mimeTypeFilter)) {
1488            // If they can take anything, the untyped open call is good enough.
1489            return openAssetFile(uri, "r");
1490        }
1491        String baseType = getType(uri);
1492        if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
1493            // Use old untyped open call if this provider has a type for this
1494            // URI and it matches the request.
1495            return openAssetFile(uri, "r");
1496        }
1497        throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1498    }
1499
1500
1501    /**
1502     * Called by a client to open a read-only stream containing data of a
1503     * particular MIME type.  This is like {@link #openAssetFile(Uri, String)},
1504     * except the file can only be read-only and the content provider may
1505     * perform data conversions to generate data of the desired type.
1506     *
1507     * <p>The default implementation compares the given mimeType against the
1508     * result of {@link #getType(Uri)} and, if they match, simply calls
1509     * {@link #openAssetFile(Uri, String)}.
1510     *
1511     * <p>See {@link ClipData} for examples of the use and implementation
1512     * of this method.
1513     * <p>
1514     * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1515     * streaming of data.
1516     *
1517     * <p class="note">For better interoperability with other applications, it is recommended
1518     * that for any URIs that can be opened, you also support queries on them
1519     * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1520     * You may also want to support other common columns if you have additional meta-data
1521     * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1522     * in {@link android.provider.MediaStore.MediaColumns}.</p>
1523     *
1524     * @param uri The data in the content provider being queried.
1525     * @param mimeTypeFilter The type of data the client desires.  May be
1526     * a pattern, such as *&#47;*, if the caller does not have specific type
1527     * requirements; in this case the content provider will pick its best
1528     * type matching the pattern.
1529     * @param opts Additional options from the client.  The definitions of
1530     * these are specific to the content provider being called.
1531     * @param signal A signal to cancel the operation in progress, or
1532     *            {@code null} if none. For example, if you are downloading a
1533     *            file from the network to service a "rw" mode request, you
1534     *            should periodically call
1535     *            {@link CancellationSignal#throwIfCanceled()} to check whether
1536     *            the client has canceled the request and abort the download.
1537     *
1538     * @return Returns a new AssetFileDescriptor from which the client can
1539     * read data of the desired type.
1540     *
1541     * @throws FileNotFoundException Throws FileNotFoundException if there is
1542     * no file associated with the given URI or the mode is invalid.
1543     * @throws SecurityException Throws SecurityException if the caller does
1544     * not have permission to access the data.
1545     * @throws IllegalArgumentException Throws IllegalArgumentException if the
1546     * content provider does not support the requested MIME type.
1547     *
1548     * @see #getStreamTypes(Uri, String)
1549     * @see #openAssetFile(Uri, String)
1550     * @see ClipDescription#compareMimeTypes(String, String)
1551     */
1552    public AssetFileDescriptor openTypedAssetFile(
1553            Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1554            throws FileNotFoundException {
1555        return openTypedAssetFile(uri, mimeTypeFilter, opts);
1556    }
1557
1558    /**
1559     * Interface to write a stream of data to a pipe.  Use with
1560     * {@link ContentProvider#openPipeHelper}.
1561     */
1562    public interface PipeDataWriter<T> {
1563        /**
1564         * Called from a background thread to stream data out to a pipe.
1565         * Note that the pipe is blocking, so this thread can block on
1566         * writes for an arbitrary amount of time if the client is slow
1567         * at reading.
1568         *
1569         * @param output The pipe where data should be written.  This will be
1570         * closed for you upon returning from this function.
1571         * @param uri The URI whose data is to be written.
1572         * @param mimeType The desired type of data to be written.
1573         * @param opts Options supplied by caller.
1574         * @param args Your own custom arguments.
1575         */
1576        public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1577                Bundle opts, T args);
1578    }
1579
1580    /**
1581     * A helper function for implementing {@link #openTypedAssetFile}, for
1582     * creating a data pipe and background thread allowing you to stream
1583     * generated data back to the client.  This function returns a new
1584     * ParcelFileDescriptor that should be returned to the caller (the caller
1585     * is responsible for closing it).
1586     *
1587     * @param uri The URI whose data is to be written.
1588     * @param mimeType The desired type of data to be written.
1589     * @param opts Options supplied by caller.
1590     * @param args Your own custom arguments.
1591     * @param func Interface implementing the function that will actually
1592     * stream the data.
1593     * @return Returns a new ParcelFileDescriptor holding the read side of
1594     * the pipe.  This should be returned to the caller for reading; the caller
1595     * is responsible for closing it when done.
1596     */
1597    public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1598            final Bundle opts, final T args, final PipeDataWriter<T> func)
1599            throws FileNotFoundException {
1600        try {
1601            final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1602
1603            AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1604                @Override
1605                protected Object doInBackground(Object... params) {
1606                    func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1607                    try {
1608                        fds[1].close();
1609                    } catch (IOException e) {
1610                        Log.w(TAG, "Failure closing pipe", e);
1611                    }
1612                    return null;
1613                }
1614            };
1615            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
1616
1617            return fds[0];
1618        } catch (IOException e) {
1619            throw new FileNotFoundException("failure making pipe");
1620        }
1621    }
1622
1623    /**
1624     * Returns true if this instance is a temporary content provider.
1625     * @return true if this instance is a temporary content provider
1626     */
1627    protected boolean isTemporary() {
1628        return false;
1629    }
1630
1631    /**
1632     * Returns the Binder object for this provider.
1633     *
1634     * @return the Binder object for this provider
1635     * @hide
1636     */
1637    public IContentProvider getIContentProvider() {
1638        return mTransport;
1639    }
1640
1641    /**
1642     * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1643     * when directly instantiating the provider for testing.
1644     * @hide
1645     */
1646    public void attachInfoForTesting(Context context, ProviderInfo info) {
1647        attachInfo(context, info, true);
1648    }
1649
1650    /**
1651     * After being instantiated, this is called to tell the content provider
1652     * about itself.
1653     *
1654     * @param context The context this provider is running in
1655     * @param info Registered information about this content provider
1656     */
1657    public void attachInfo(Context context, ProviderInfo info) {
1658        attachInfo(context, info, false);
1659    }
1660
1661    private void attachInfo(Context context, ProviderInfo info, boolean testing) {
1662        mNoPerms = testing;
1663
1664        /*
1665         * Only allow it to be set once, so after the content service gives
1666         * this to us clients can't change it.
1667         */
1668        if (mContext == null) {
1669            mContext = context;
1670            if (context != null) {
1671                mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1672                        Context.APP_OPS_SERVICE);
1673            }
1674            mMyUid = Process.myUid();
1675            if (info != null) {
1676                setReadPermission(info.readPermission);
1677                setWritePermission(info.writePermission);
1678                setPathPermissions(info.pathPermissions);
1679                mExported = info.exported;
1680                mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
1681                setAuthorities(info.authority);
1682            }
1683            ContentProvider.this.onCreate();
1684        }
1685    }
1686
1687    /**
1688     * Override this to handle requests to perform a batch of operations, or the
1689     * default implementation will iterate over the operations and call
1690     * {@link ContentProviderOperation#apply} on each of them.
1691     * If all calls to {@link ContentProviderOperation#apply} succeed
1692     * then a {@link ContentProviderResult} array with as many
1693     * elements as there were operations will be returned.  If any of the calls
1694     * fail, it is up to the implementation how many of the others take effect.
1695     * This method can be called from multiple threads, as described in
1696     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1697     * and Threads</a>.
1698     *
1699     * @param operations the operations to apply
1700     * @return the results of the applications
1701     * @throws OperationApplicationException thrown if any operation fails.
1702     * @see ContentProviderOperation#apply
1703     */
1704    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
1705            throws OperationApplicationException {
1706        final int numOperations = operations.size();
1707        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1708        for (int i = 0; i < numOperations; i++) {
1709            results[i] = operations.get(i).apply(this, results, i);
1710        }
1711        return results;
1712    }
1713
1714    /**
1715     * Call a provider-defined method.  This can be used to implement
1716     * interfaces that are cheaper and/or unnatural for a table-like
1717     * model.
1718     *
1719     * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1720     * on this entry into the content provider besides the basic ability for the application
1721     * to get access to the provider at all.  For example, it has no idea whether the call
1722     * being executed may read or write data in the provider, so can't enforce those
1723     * individual permissions.  Any implementation of this method <strong>must</strong>
1724     * do its own permission checks on incoming calls to make sure they are allowed.</p>
1725     *
1726     * @param method method name to call.  Opaque to framework, but should not be {@code null}.
1727     * @param arg provider-defined String argument.  May be {@code null}.
1728     * @param extras provider-defined Bundle argument.  May be {@code null}.
1729     * @return provider-defined return value.  May be {@code null}, which is also
1730     *   the default for providers which don't implement any call methods.
1731     */
1732    public Bundle call(String method, String arg, Bundle extras) {
1733        return null;
1734    }
1735
1736    /**
1737     * Implement this to shut down the ContentProvider instance. You can then
1738     * invoke this method in unit tests.
1739     *
1740     * <p>
1741     * Android normally handles ContentProvider startup and shutdown
1742     * automatically. You do not need to start up or shut down a
1743     * ContentProvider. When you invoke a test method on a ContentProvider,
1744     * however, a ContentProvider instance is started and keeps running after
1745     * the test finishes, even if a succeeding test instantiates another
1746     * ContentProvider. A conflict develops because the two instances are
1747     * usually running against the same underlying data source (for example, an
1748     * sqlite database).
1749     * </p>
1750     * <p>
1751     * Implementing shutDown() avoids this conflict by providing a way to
1752     * terminate the ContentProvider. This method can also prevent memory leaks
1753     * from multiple instantiations of the ContentProvider, and it can ensure
1754     * unit test isolation by allowing you to completely clean up the test
1755     * fixture before moving on to the next test.
1756     * </p>
1757     */
1758    public void shutdown() {
1759        Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1760                "connections are gracefully shutdown");
1761    }
1762
1763    /**
1764     * Print the Provider's state into the given stream.  This gets invoked if
1765     * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
1766     *
1767     * @param fd The raw file descriptor that the dump is being sent to.
1768     * @param writer The PrintWriter to which you should dump your state.  This will be
1769     * closed for you after you return.
1770     * @param args additional arguments to the dump request.
1771     */
1772    public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1773        writer.println("nothing to dump");
1774    }
1775
1776    /** @hide */
1777    private void validateIncomingUri(Uri uri) throws SecurityException {
1778        String auth = uri.getAuthority();
1779        int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1780        if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1781            throw new SecurityException("trying to query a ContentProvider in user "
1782                    + mContext.getUserId() + " with a uri belonging to user " + userId);
1783        }
1784        if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1785            String message = "The authority of the uri " + uri + " does not match the one of the "
1786                    + "contentProvider: ";
1787            if (mAuthority != null) {
1788                message += mAuthority;
1789            } else {
1790                message += mAuthorities;
1791            }
1792            throw new SecurityException(message);
1793        }
1794    }
1795
1796    /** @hide */
1797    public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1798        if (auth == null) return defaultUserId;
1799        int end = auth.lastIndexOf('@');
1800        if (end == -1) return defaultUserId;
1801        String userIdString = auth.substring(0, end);
1802        try {
1803            return Integer.parseInt(userIdString);
1804        } catch (NumberFormatException e) {
1805            Log.w(TAG, "Error parsing userId.", e);
1806            return UserHandle.USER_NULL;
1807        }
1808    }
1809
1810    /** @hide */
1811    public static int getUserIdFromAuthority(String auth) {
1812        return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1813    }
1814
1815    /** @hide */
1816    public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1817        if (uri == null) return defaultUserId;
1818        return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1819    }
1820
1821    /** @hide */
1822    public static int getUserIdFromUri(Uri uri) {
1823        return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1824    }
1825
1826    /**
1827     * Removes userId part from authority string. Expects format:
1828     * userId@some.authority
1829     * If there is no userId in the authority, it symply returns the argument
1830     * @hide
1831     */
1832    public static String getAuthorityWithoutUserId(String auth) {
1833        if (auth == null) return null;
1834        int end = auth.lastIndexOf('@');
1835        return auth.substring(end+1);
1836    }
1837
1838    /** @hide */
1839    public static Uri getUriWithoutUserId(Uri uri) {
1840        if (uri == null) return null;
1841        Uri.Builder builder = uri.buildUpon();
1842        builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1843        return builder.build();
1844    }
1845
1846    /** @hide */
1847    public static boolean uriHasUserId(Uri uri) {
1848        if (uri == null) return false;
1849        return !TextUtils.isEmpty(uri.getUserInfo());
1850    }
1851
1852    /** @hide */
1853    public static Uri maybeAddUserId(Uri uri, int userId) {
1854        if (uri == null) return null;
1855        if (userId != UserHandle.USER_CURRENT
1856                && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1857            if (!uriHasUserId(uri)) {
1858                //We don't add the user Id if there's already one
1859                Uri.Builder builder = uri.buildUpon();
1860                builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1861                return builder.build();
1862            }
1863        }
1864        return uri;
1865    }
1866}
1867