blob: 7bde87101d8da7cd07b1debed30ac15a5222811a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Nicolas Prevot504d78e2014-06-26 10:07:33 +010019import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070020import static android.app.AppOpsManager.MODE_ALLOWED;
21import static android.app.AppOpsManager.MODE_ERRORED;
22import static android.app.AppOpsManager.MODE_IGNORED;
23import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060024import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070025
Jeff Sharkey673db442015-06-11 19:30:57 -070026import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080027import android.annotation.Nullable;
Dianne Hackborn35654b62013-01-14 17:38:02 -080028import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070029import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.pm.ProviderInfo;
31import android.content.res.AssetFileDescriptor;
32import android.content.res.Configuration;
33import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070034import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.SQLException;
36import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070037import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080039import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070040import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080041import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070042import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070044import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080045import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060046import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060048import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010049import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070050import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
52import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080053import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070055import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080056import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070057import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080058import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60/**
61 * Content providers are one of the primary building blocks of Android applications, providing
62 * content to applications. They encapsulate data and provide it to applications through the single
63 * {@link ContentResolver} interface. A content provider is only required if you need to share
64 * data between multiple applications. For example, the contacts data is used by multiple
65 * applications and must be stored in a content provider. If you don't need to share data amongst
66 * multiple applications you can use a database directly via
67 * {@link android.database.sqlite.SQLiteDatabase}.
68 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * <p>When a request is made via
70 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
71 * request to the content provider registered with the authority. The content provider can interpret
72 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
73 * URIs.</p>
74 *
75 * <p>The primary methods that need to be implemented are:
76 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070077 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 * <li>{@link #query} which returns data to the caller</li>
79 * <li>{@link #insert} which inserts new data into the content provider</li>
80 * <li>{@link #update} which updates existing data in the content provider</li>
81 * <li>{@link #delete} which deletes data from the content provider</li>
82 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
83 * </ul></p>
84 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070085 * <p class="caution">Data access methods (such as {@link #insert} and
86 * {@link #update}) may be called from many threads at once, and must be thread-safe.
87 * Other methods (such as {@link #onCreate}) are only called from the application
88 * main thread, and must avoid performing lengthy operations. See the method
89 * descriptions for their expected thread behavior.</p>
90 *
91 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
92 * ContentProvider instance, so subclasses don't have to worry about the details of
93 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070094 *
95 * <div class="special reference">
96 * <h3>Developer Guides</h3>
97 * <p>For more information about using content providers, read the
98 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
99 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700101public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800102
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700103 private static final String TAG = "ContentProvider";
104
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900105 /*
106 * Note: if you add methods to ContentProvider, you must add similar methods to
107 * MockContentProvider.
108 */
109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700111 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100112
113 // Since most Providers have only one authority, we keep both a String and a String[] to improve
114 // performance.
115 private String mAuthority;
116 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private String mReadPermission;
118 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700119 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700120 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800121 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700122 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Steve McKayea93fe72016-12-02 11:35:35 -0800124 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private Transport mTransport = new Transport();
127
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700128 /**
129 * Construct a ContentProvider instance. Content providers must be
130 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
131 * in the manifest</a>, accessed with {@link ContentResolver}, and created
132 * automatically by the system, so applications usually do not create
133 * ContentProvider instances directly.
134 *
135 * <p>At construction time, the object is uninitialized, and most fields and
136 * methods are unavailable. Subclasses should initialize themselves in
137 * {@link #onCreate}, not the constructor.
138 *
139 * <p>Content providers are created on the application main thread at
140 * application launch time. The constructor must not perform lengthy
141 * operations, or application startup will be delayed.
142 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900143 public ContentProvider() {
144 }
145
146 /**
147 * Constructor just for mocking.
148 *
149 * @param context A Context object which should be some mock instance (like the
150 * instance of {@link android.test.mock.MockContext}).
151 * @param readPermission The read permision you want this instance should have in the
152 * test, which is available via {@link #getReadPermission()}.
153 * @param writePermission The write permission you want this instance should have
154 * in the test, which is available via {@link #getWritePermission()}.
155 * @param pathPermissions The PathPermissions you want this instance should have
156 * in the test, which is available via {@link #getPathPermissions()}.
157 * @hide
158 */
159 public ContentProvider(
160 Context context,
161 String readPermission,
162 String writePermission,
163 PathPermission[] pathPermissions) {
164 mContext = context;
165 mReadPermission = readPermission;
166 mWritePermission = writePermission;
167 mPathPermissions = pathPermissions;
168 }
169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 /**
171 * Given an IContentProvider, try to coerce it back to the real
172 * ContentProvider object if it is running in the local process. This can
173 * be used if you know you are running in the same process as a provider,
174 * and want to get direct access to its implementation details. Most
175 * clients should not nor have a reason to use it.
176 *
177 * @param abstractInterface The ContentProvider interface that is to be
178 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800179 * @return If the IContentProvider is non-{@code null} and local, returns its actual
180 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 * @hide
182 */
183 public static ContentProvider coerceToLocalContentProvider(
184 IContentProvider abstractInterface) {
185 if (abstractInterface instanceof Transport) {
186 return ((Transport)abstractInterface).getContentProvider();
187 }
188 return null;
189 }
190
191 /**
192 * Binder object that deals with remoting.
193 *
194 * @hide
195 */
196 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800197 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800198 int mReadOp = AppOpsManager.OP_NONE;
199 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 ContentProvider getContentProvider() {
202 return ContentProvider.this;
203 }
204
Jeff Brownd2183652011-10-09 12:39:53 -0700205 @Override
206 public String getProviderName() {
207 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 }
209
Jeff Brown75ea64f2012-01-25 19:37:13 -0800210 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800211 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
212 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100213 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100214 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800215 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700216 // The caller has no access to the data, so return an empty cursor with
217 // the columns in the requested order. The caller may ask for an invalid
218 // column and we would not catch that but this is not a problem in practice.
219 // We do not call ContentProvider#query with a modified where clause since
220 // the implementation is not guaranteed to be backed by a SQL database, hence
221 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700222 if (projection != null) {
223 return new MatrixCursor(projection, 0);
224 }
225
226 // Null projection means all columns but we have no idea which they are.
227 // However, the caller may be expecting to access them my index. Hence,
228 // we have to execute the query as if allowed to get a cursor with the
229 // columns. We then use the column names to return an empty cursor.
Steve McKayea93fe72016-12-02 11:35:35 -0800230 Cursor cursor = ContentProvider.this.query(
231 uri, projection, queryArgs,
232 CancellationSignal.fromTransport(cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700233 if (cursor == null) {
234 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700235 }
236
237 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700238 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800239 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600240 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700241 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700242 try {
243 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800244 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700245 CancellationSignal.fromTransport(cancellationSignal));
246 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700247 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600248 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 }
251
Jeff Brown75ea64f2012-01-25 19:37:13 -0800252 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100254 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100255 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600256 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
257 try {
258 return ContentProvider.this.getType(uri);
259 } finally {
260 Trace.traceEnd(TRACE_TAG_DATABASE);
261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 }
263
Jeff Brown75ea64f2012-01-25 19:37:13 -0800264 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800265 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100266 validateIncomingUri(uri);
267 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100268 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800269 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800270 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800271 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600272 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700273 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700274 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100275 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700276 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700277 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600278 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281
Jeff Brown75ea64f2012-01-25 19:37:13 -0800282 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800283 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100284 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100285 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800286 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800287 return 0;
288 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600289 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700290 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700291 try {
292 return ContentProvider.this.bulkInsert(uri, initialValues);
293 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700294 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600295 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 }
298
Jeff Brown75ea64f2012-01-25 19:37:13 -0800299 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800300 public ContentProviderResult[] applyBatch(String callingPkg,
301 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700302 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100303 int numOperations = operations.size();
304 final int[] userIds = new int[numOperations];
305 for (int i = 0; i < numOperations; i++) {
306 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100307 Uri uri = operation.getUri();
308 validateIncomingUri(uri);
309 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100310 if (userIds[i] != UserHandle.USER_CURRENT) {
311 // Removing the user id from the uri.
312 operation = new ContentProviderOperation(operation, true);
313 operations.set(i, operation);
314 }
Fred Quintana89437372009-05-15 15:10:40 -0700315 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800316 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800317 != AppOpsManager.MODE_ALLOWED) {
318 throw new OperationApplicationException("App op not allowed", 0);
319 }
Fred Quintana89437372009-05-15 15:10:40 -0700320 }
Fred Quintana89437372009-05-15 15:10:40 -0700321 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800322 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800323 != AppOpsManager.MODE_ALLOWED) {
324 throw new OperationApplicationException("App op not allowed", 0);
325 }
Fred Quintana89437372009-05-15 15:10:40 -0700326 }
327 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600328 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700329 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700330 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100331 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800332 if (results != null) {
333 for (int i = 0; i < results.length ; i++) {
334 if (userIds[i] != UserHandle.USER_CURRENT) {
335 // Adding the userId to the uri.
336 results[i] = new ContentProviderResult(results[i], userIds[i]);
337 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100338 }
339 }
340 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700341 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700342 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600343 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700344 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700345 }
346
Jeff Brown75ea64f2012-01-25 19:37:13 -0800347 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800348 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100349 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100350 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800351 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800352 return 0;
353 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600354 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700355 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700356 try {
357 return ContentProvider.this.delete(uri, selection, selectionArgs);
358 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700359 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600360 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 }
363
Jeff Brown75ea64f2012-01-25 19:37:13 -0800364 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800365 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100367 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100368 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800369 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800370 return 0;
371 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600372 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700373 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700374 try {
375 return ContentProvider.this.update(uri, values, selection, selectionArgs);
376 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700377 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600378 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381
Jeff Brown75ea64f2012-01-25 19:37:13 -0800382 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700383 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800384 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
385 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100386 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100387 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800388 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600389 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700390 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700391 try {
392 return ContentProvider.this.openFile(
393 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
394 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700395 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600396 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 }
399
Jeff Brown75ea64f2012-01-25 19:37:13 -0800400 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700401 public AssetFileDescriptor openAssetFile(
402 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100404 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100405 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800406 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600407 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700408 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700409 try {
410 return ContentProvider.this.openAssetFile(
411 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
412 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700413 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600414 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 }
417
Jeff Brown75ea64f2012-01-25 19:37:13 -0800418 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800419 public Bundle call(
420 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600421 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600422 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 try {
425 return ContentProvider.this.call(method, arg, extras);
426 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700427 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600428 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700429 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800430 }
431
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700432 @Override
433 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100434 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100435 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600436 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
437 try {
438 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
439 } finally {
440 Trace.traceEnd(TRACE_TAG_DATABASE);
441 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700442 }
443
444 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800445 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700446 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600447 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100448 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100449 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800450 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600451 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700452 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700453 try {
454 return ContentProvider.this.openTypedAssetFile(
455 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
456 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700457 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600458 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700459 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700460 }
461
Jeff Brown75ea64f2012-01-25 19:37:13 -0800462 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700463 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800464 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800465 }
466
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700467 @Override
468 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100469 validateIncomingUri(uri);
470 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100471 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800472 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700473 return null;
474 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600475 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700476 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700477 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100478 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700479 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700480 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600481 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700482 }
483 }
484
485 @Override
486 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100487 validateIncomingUri(uri);
488 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100489 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800490 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700491 return null;
492 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600493 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700494 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700495 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100496 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700497 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700498 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600499 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700500 }
501 }
502
Ben Lin1cf454f2016-11-10 13:50:54 -0800503 @Override
504 public boolean refresh(String callingPkg, Uri uri, Bundle args,
505 ICancellationSignal cancellationSignal) throws RemoteException {
506 validateIncomingUri(uri);
507 uri = getUriWithoutUserId(uri);
508 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
509 return false;
510 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600511 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800512 final String original = setCallingPackage(callingPkg);
513 try {
514 return ContentProvider.this.refresh(uri, args,
515 CancellationSignal.fromTransport(cancellationSignal));
516 } finally {
517 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600518 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800519 }
520 }
521
Dianne Hackbornff170242014-11-19 10:59:01 -0800522 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
523 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800524 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800525 if (enforceWritePermission(callingPkg, uri, callerToken)
526 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800527 throw new FileNotFoundException("App op not allowed");
528 }
529 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800530 if (enforceReadPermission(callingPkg, uri, callerToken)
531 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800532 throw new FileNotFoundException("App op not allowed");
533 }
534 }
535 }
536
Dianne Hackbornff170242014-11-19 10:59:01 -0800537 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
538 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700539 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
540 if (mode != MODE_ALLOWED) {
541 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800542 }
Svet Ganov99b60432015-06-27 13:15:22 -0700543
544 if (mReadOp != AppOpsManager.OP_NONE) {
545 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
546 }
547
Dianne Hackborn35654b62013-01-14 17:38:02 -0800548 return AppOpsManager.MODE_ALLOWED;
549 }
550
Dianne Hackbornff170242014-11-19 10:59:01 -0800551 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
552 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700553 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
554 if (mode != MODE_ALLOWED) {
555 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800556 }
Svet Ganov99b60432015-06-27 13:15:22 -0700557
558 if (mWriteOp != AppOpsManager.OP_NONE) {
559 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
560 }
561
Dianne Hackborn35654b62013-01-14 17:38:02 -0800562 return AppOpsManager.MODE_ALLOWED;
563 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700564 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800565
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100566 boolean checkUser(int pid, int uid, Context context) {
567 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700568 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100569 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
570 == PERMISSION_GRANTED;
571 }
572
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700573 /**
574 * Verify that calling app holds both the given permission and any app-op
575 * associated with that permission.
576 */
577 private int checkPermissionAndAppOp(String permission, String callingPkg,
578 IBinder callerToken) {
579 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
580 callerToken) != PERMISSION_GRANTED) {
581 return MODE_ERRORED;
582 }
583
584 final int permOp = AppOpsManager.permissionToOpCode(permission);
585 if (permOp != AppOpsManager.OP_NONE) {
586 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
587 }
588
589 return MODE_ALLOWED;
590 }
591
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700592 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700593 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800594 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700595 final Context context = getContext();
596 final int pid = Binder.getCallingPid();
597 final int uid = Binder.getCallingUid();
598 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700599 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700600
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700601 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700602 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700603 }
604
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100605 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700606 final String componentPerm = getReadPermission();
607 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700608 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
609 if (mode == MODE_ALLOWED) {
610 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700611 } else {
612 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700613 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700614 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700615 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700616
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700617 // track if unprotected read is allowed; any denied
618 // <path-permission> below removes this ability
619 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700620
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700621 final PathPermission[] pps = getPathPermissions();
622 if (pps != null) {
623 final String path = uri.getPath();
624 for (PathPermission pp : pps) {
625 final String pathPerm = pp.getReadPermission();
626 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700627 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
628 if (mode == MODE_ALLOWED) {
629 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700630 } else {
631 // any denied <path-permission> means we lose
632 // default <provider> access.
633 allowDefaultRead = false;
634 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700635 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700636 }
637 }
638 }
639 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700640
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700641 // if we passed <path-permission> checks above, and no default
642 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700643 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700645
646 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800647 final int callingUserId = UserHandle.getUserId(uid);
648 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
649 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800650 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
651 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700652 return MODE_ALLOWED;
653 }
654
655 // If the worst denial we found above was ignored, then pass that
656 // ignored through; otherwise we assume it should be a real error below.
657 if (strongestMode == MODE_IGNORED) {
658 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700659 }
660
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600661 final String suffix;
662 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
663 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
664 } else if (mExported) {
665 suffix = " requires " + missingPerm + ", or grantUriPermission()";
666 } else {
667 suffix = " requires the provider be exported, or grantUriPermission()";
668 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700669 throw new SecurityException("Permission Denial: reading "
670 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600671 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700672 }
673
674 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700675 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800676 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700677 final Context context = getContext();
678 final int pid = Binder.getCallingPid();
679 final int uid = Binder.getCallingUid();
680 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700681 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700682
683 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700684 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700685 }
686
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100687 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700688 final String componentPerm = getWritePermission();
689 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700690 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
691 if (mode == MODE_ALLOWED) {
692 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700693 } else {
694 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700695 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700696 }
697 }
698
699 // track if unprotected write is allowed; any denied
700 // <path-permission> below removes this ability
701 boolean allowDefaultWrite = (componentPerm == null);
702
703 final PathPermission[] pps = getPathPermissions();
704 if (pps != null) {
705 final String path = uri.getPath();
706 for (PathPermission pp : pps) {
707 final String pathPerm = pp.getWritePermission();
708 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700709 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
710 if (mode == MODE_ALLOWED) {
711 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700712 } else {
713 // any denied <path-permission> means we lose
714 // default <provider> access.
715 allowDefaultWrite = false;
716 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700717 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700718 }
719 }
720 }
721 }
722
723 // if we passed <path-permission> checks above, and no default
724 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700725 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700726 }
727
728 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800729 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
730 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700731 return MODE_ALLOWED;
732 }
733
734 // If the worst denial we found above was ignored, then pass that
735 // ignored through; otherwise we assume it should be a real error below.
736 if (strongestMode == MODE_IGNORED) {
737 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700738 }
739
740 final String failReason = mExported
741 ? " requires " + missingPerm + ", or grantUriPermission()"
742 : " requires the provider be exported, or grantUriPermission()";
743 throw new SecurityException("Permission Denial: writing "
744 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
745 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700749 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800750 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 * constructor.
752 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700753 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 return mContext;
755 }
756
757 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700758 * Set the calling package, returning the current value (or {@code null})
759 * which can be used later to restore the previous state.
760 */
761 private String setCallingPackage(String callingPackage) {
762 final String original = mCallingPackage.get();
763 mCallingPackage.set(callingPackage);
764 return original;
765 }
766
767 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700768 * Return the package name of the caller that initiated the request being
769 * processed on the current thread. The returned package will have been
770 * verified to belong to the calling UID. Returns {@code null} if not
771 * currently processing a request.
772 * <p>
773 * This will always return {@code null} when processing
774 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
775 *
776 * @see Binder#getCallingUid()
777 * @see Context#grantUriPermission(String, Uri, int)
778 * @throws SecurityException if the calling package doesn't belong to the
779 * calling UID.
780 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700781 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700782 final String pkg = mCallingPackage.get();
783 if (pkg != null) {
784 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
785 }
786 return pkg;
787 }
788
789 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100790 * Change the authorities of the ContentProvider.
791 * This is normally set for you from its manifest information when the provider is first
792 * created.
793 * @hide
794 * @param authorities the semi-colon separated authorities of the ContentProvider.
795 */
796 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100797 if (authorities != null) {
798 if (authorities.indexOf(';') == -1) {
799 mAuthority = authorities;
800 mAuthorities = null;
801 } else {
802 mAuthority = null;
803 mAuthorities = authorities.split(";");
804 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100805 }
806 }
807
808 /** @hide */
809 protected final boolean matchesOurAuthorities(String authority) {
810 if (mAuthority != null) {
811 return mAuthority.equals(authority);
812 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100813 if (mAuthorities != null) {
814 int length = mAuthorities.length;
815 for (int i = 0; i < length; i++) {
816 if (mAuthorities[i].equals(authority)) return true;
817 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100818 }
819 return false;
820 }
821
822
823 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 * Change the permission required to read data from the content
825 * provider. This is normally set for you from its manifest information
826 * when the provider is first created.
827 *
828 * @param permission Name of the permission required for read-only access.
829 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700830 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 mReadPermission = permission;
832 }
833
834 /**
835 * Return the name of the permission required for read-only access to
836 * this content provider. This method can be called from multiple
837 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800838 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
839 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700841 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 return mReadPermission;
843 }
844
845 /**
846 * Change the permission required to read and write data in the content
847 * provider. This is normally set for you from its manifest information
848 * when the provider is first created.
849 *
850 * @param permission Name of the permission required for read/write access.
851 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700852 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 mWritePermission = permission;
854 }
855
856 /**
857 * Return the name of the permission required for read/write access to
858 * this content provider. This method can be called from multiple
859 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800860 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
861 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700863 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 return mWritePermission;
865 }
866
867 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700868 * Change the path-based permission required to read and/or write data in
869 * the content provider. This is normally set for you from its manifest
870 * information when the provider is first created.
871 *
872 * @param permissions Array of path permission descriptions.
873 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700874 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700875 mPathPermissions = permissions;
876 }
877
878 /**
879 * Return the path-based permissions required for read and/or write access to
880 * this content provider. This method can be called from multiple
881 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800882 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
883 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700884 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700885 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700886 return mPathPermissions;
887 }
888
Dianne Hackborn35654b62013-01-14 17:38:02 -0800889 /** @hide */
890 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800891 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800892 mTransport.mReadOp = readOp;
893 mTransport.mWriteOp = writeOp;
894 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800895 }
896
Dianne Hackborn961321f2013-02-05 17:22:41 -0800897 /** @hide */
898 public AppOpsManager getAppOpsManager() {
899 return mTransport.mAppOpsManager;
900 }
901
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700902 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700903 * Implement this to initialize your content provider on startup.
904 * This method is called for all registered content providers on the
905 * application main thread at application launch time. It must not perform
906 * lengthy operations, or application startup will be delayed.
907 *
908 * <p>You should defer nontrivial initialization (such as opening,
909 * upgrading, and scanning databases) until the content provider is used
910 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
911 * keeps application startup fast, avoids unnecessary work if the provider
912 * turns out not to be needed, and stops database errors (such as a full
913 * disk) from halting application launch.
914 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700915 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700916 * is a helpful utility class that makes it easy to manage databases,
917 * and will automatically defer opening until first use. If you do use
918 * SQLiteOpenHelper, make sure to avoid calling
919 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
920 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
921 * from this method. (Instead, override
922 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
923 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 *
925 * @return true if the provider was successfully loaded, false otherwise
926 */
927 public abstract boolean onCreate();
928
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700929 /**
930 * {@inheritDoc}
931 * This method is always called on the application main thread, and must
932 * not perform lengthy operations.
933 *
934 * <p>The default content provider implementation does nothing.
935 * Override this method to take appropriate action.
936 * (Content providers do not usually care about things like screen
937 * orientation, but may want to know about locale changes.)
938 */
Steve McKayea93fe72016-12-02 11:35:35 -0800939 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 public void onConfigurationChanged(Configuration newConfig) {
941 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700942
943 /**
944 * {@inheritDoc}
945 * This method is always called on the application main thread, and must
946 * not perform lengthy operations.
947 *
948 * <p>The default content provider implementation does nothing.
949 * Subclasses may override this method to take appropriate action.
950 */
Steve McKayea93fe72016-12-02 11:35:35 -0800951 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 public void onLowMemory() {
953 }
954
Steve McKayea93fe72016-12-02 11:35:35 -0800955 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700956 public void onTrimMemory(int level) {
957 }
958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700960 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800961 *
962 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
963 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
964 * implementation of this method.
965 *
966 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800967 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
968 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 * <p>
970 * Example client call:<p>
971 * <pre>// Request a specific record.
972 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000973 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 projection, // Which columns to return.
975 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000976 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 People.NAME + " ASC"); // Sort order.</pre>
978 * Example implementation:<p>
979 * <pre>// SQLiteQueryBuilder is a helper class that creates the
980 // proper SQL syntax for us.
981 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
982
983 // Set the table we're querying.
984 qBuilder.setTables(DATABASE_TABLE_NAME);
985
986 // If the query ends in a specific record number, we're
987 // being asked for a specific record, so set the
988 // WHERE clause in our query.
989 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
990 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
991 }
992
993 // Make the query.
994 Cursor c = qBuilder.query(mDb,
995 projection,
996 selection,
997 selectionArgs,
998 groupBy,
999 having,
1000 sortOrder);
1001 c.setNotificationUri(getContext().getContentResolver(), uri);
1002 return c;</pre>
1003 *
1004 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001005 * if the client is requesting a specific record, the URI will end in a record number
1006 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1007 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001009 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001011 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001012 * @param selectionArgs You may include ?s in selection, which will be replaced by
1013 * the values from selectionArgs, in order that they appear in the selection.
1014 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001016 * If {@code null} then the provider is free to define the sort order.
1017 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001019 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1020 @Nullable String selection, @Nullable String[] selectionArgs,
1021 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022
Fred Quintana5bba6322009-10-05 14:21:12 -07001023 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001024 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001025 *
1026 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1027 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1028 *
1029 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001030 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1031 * and Threads</a>.
1032 * <p>
1033 * Example client call:<p>
1034 * <pre>// Request a specific record.
1035 * Cursor managedCursor = managedQuery(
1036 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1037 projection, // Which columns to return.
1038 null, // WHERE clause.
1039 null, // WHERE clause value substitution
1040 People.NAME + " ASC"); // Sort order.</pre>
1041 * Example implementation:<p>
1042 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1043 // proper SQL syntax for us.
1044 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1045
1046 // Set the table we're querying.
1047 qBuilder.setTables(DATABASE_TABLE_NAME);
1048
1049 // If the query ends in a specific record number, we're
1050 // being asked for a specific record, so set the
1051 // WHERE clause in our query.
1052 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1053 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1054 }
1055
1056 // Make the query.
1057 Cursor c = qBuilder.query(mDb,
1058 projection,
1059 selection,
1060 selectionArgs,
1061 groupBy,
1062 having,
1063 sortOrder);
1064 c.setNotificationUri(getContext().getContentResolver(), uri);
1065 return c;</pre>
1066 * <p>
1067 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001068 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1069 * signal to ensure correct operation on older versions of the Android Framework in
1070 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001071 *
1072 * @param uri The URI to query. This will be the full URI sent by the client;
1073 * if the client is requesting a specific record, the URI will end in a record number
1074 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1075 * that _id value.
1076 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001077 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001078 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001079 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001080 * @param selectionArgs You may include ?s in selection, which will be replaced by
1081 * the values from selectionArgs, in order that they appear in the selection.
1082 * The values will be bound as Strings.
1083 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001084 * If {@code null} then the provider is free to define the sort order.
1085 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001086 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001087 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001088 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001089 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001090 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1091 @Nullable String selection, @Nullable String[] selectionArgs,
1092 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001093 return query(uri, projection, selection, selectionArgs, sortOrder);
1094 }
1095
1096 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001097 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1098 * Arguments may include traditional SQL style query arguments. When present these
1099 * should be handled according to the contract established in
1100 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1101 *
1102 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001103 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1104 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1105 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001106 *
Steve McKay76b27702017-04-24 12:07:53 -07001107 * <p>This method can be called from multiple threads, as described in
1108 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1109 * and Threads</a>.
1110 *
1111 * <p>
1112 * Example client call:<p>
1113 * <pre>// Request 20 records starting at row index 30.
1114 Bundle queryArgs = new Bundle();
1115 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1116 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1117
1118 Cursor cursor = getContentResolver().query(
1119 contentUri, // Content Uri is specific to individual content providers.
1120 projection, // String[] describing which columns to return.
1121 queryArgs, // Query arguments.
1122 null); // Cancellation signal.</pre>
1123 *
1124 * Example implementation:<p>
1125 * <pre>
1126
1127 int recordsetSize = 0x1000; // Actual value is implementation specific.
1128 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1129
1130 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1131 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1132
1133 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1134
1135 // Calculate the number of items to include in the cursor.
1136 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1137
1138 // Build the paged result set....
1139 for (int i = offset; i < offset + numItems; i++) {
1140 // populate row from your data.
1141 }
1142
1143 Bundle extras = new Bundle();
1144 c.setExtras(extras);
1145
1146 // Any QUERY_ARG_* key may be included if honored.
1147 // In an actual implementation, include only keys that are both present in queryArgs
1148 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1149 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1150 // then QUERY_ARG_OFFSET should be omitted.
1151 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1152 ContentResolver.QUERY_ARG_OFFSET,
1153 ContentResolver.QUERY_ARG_LIMIT
1154 });
1155
1156 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1157
1158 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1159
1160 return cursor;</pre>
1161 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001162 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1163 * implementation details.
1164 *
1165 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001166 * @param projection The list of columns to put into the cursor.
1167 * If {@code null} provide a default set of columns.
1168 * @param queryArgs A Bundle containing all additional information necessary for the query.
1169 * Values in the Bundle may include SQL style arguments.
1170 * @param cancellationSignal A signal to cancel the operation in progress,
1171 * or {@code null}.
1172 * @return a Cursor or {@code null}.
1173 */
1174 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1175 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1176 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001177
Steve McKayd7ece9f2017-01-12 16:59:59 -08001178 // if client doesn't supply an SQL sort order argument, attempt to build one from
1179 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001180 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001181 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1182 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1183 }
1184
Steve McKayea93fe72016-12-02 11:35:35 -08001185 return query(
1186 uri,
1187 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001188 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1189 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1190 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001191 cancellationSignal);
1192 }
1193
1194 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001195 * Implement this to handle requests for the MIME type of the data at the
1196 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 * <code>vnd.android.cursor.item</code> for a single record,
1198 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001199 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001200 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1201 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001203 * <p>Note that there are no permissions needed for an application to
1204 * access this information; if your content provider requires read and/or
1205 * write permissions, or is not exported, all applications can still call
1206 * this method regardless of their access permissions. This allows them
1207 * to retrieve the MIME type for a URI when dispatching intents.
1208 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001210 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001212 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213
1214 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001215 * Implement this to support canonicalization of URIs that refer to your
1216 * content provider. A canonical URI is one that can be transported across
1217 * devices, backup/restore, and other contexts, and still be able to refer
1218 * to the same data item. Typically this is implemented by adding query
1219 * params to the URI allowing the content provider to verify that an incoming
1220 * canonical URI references the same data as it was originally intended for and,
1221 * if it doesn't, to find that data (if it exists) in the current environment.
1222 *
1223 * <p>For example, if the content provider holds people and a normal URI in it
1224 * is created with a row index into that people database, the cananical representation
1225 * may have an additional query param at the end which specifies the name of the
1226 * person it is intended for. Later calls into the provider with that URI will look
1227 * up the row of that URI's base index and, if it doesn't match or its entry's
1228 * name doesn't match the name in the query param, perform a query on its database
1229 * to find the correct row to operate on.</p>
1230 *
1231 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1232 * URIs (including this one) must perform this verification and recovery of any
1233 * canonical URIs they receive. In addition, you must also implement
1234 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1235 *
1236 * <p>The default implementation of this method returns null, indicating that
1237 * canonical URIs are not supported.</p>
1238 *
1239 * @param url The Uri to canonicalize.
1240 *
1241 * @return Return the canonical representation of <var>url</var>, or null if
1242 * canonicalization of that Uri is not supported.
1243 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001244 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001245 return null;
1246 }
1247
1248 /**
1249 * Remove canonicalization from canonical URIs previously returned by
1250 * {@link #canonicalize}. For example, if your implementation is to add
1251 * a query param to canonicalize a URI, this method can simply trip any
1252 * query params on the URI. The default implementation always returns the
1253 * same <var>url</var> that was passed in.
1254 *
1255 * @param url The Uri to remove any canonicalization from.
1256 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001257 * @return Return the non-canonical representation of <var>url</var>, return
1258 * the <var>url</var> as-is if there is nothing to do, or return null if
1259 * the data identified by the canonical representation can not be found in
1260 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001261 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001262 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001263 return url;
1264 }
1265
1266 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001267 * Implement this to support refresh of content identified by {@code uri}. By default, this
1268 * method returns false; providers who wish to implement this should return true to signal the
1269 * client that the provider has tried refreshing with its own implementation.
1270 * <p>
1271 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1272 * <p>
1273 * Client code should only invoke this method when there is a strong indication (such as a user
1274 * initiated pull to refresh gesture) that the content is stale.
1275 * <p>
1276 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1277 * notifications when content changes.
1278 *
1279 * @param uri The Uri identifying the data to refresh.
1280 * @param args Additional options from the client. The definitions of these are specific to the
1281 * content provider being called.
1282 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1283 * none. For example, if you called refresh on a particular uri, you should call
1284 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1285 * canceled the refresh request.
1286 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001287 */
1288 public boolean refresh(Uri uri, @Nullable Bundle args,
1289 @Nullable CancellationSignal cancellationSignal) {
1290 return false;
1291 }
1292
1293 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001294 * @hide
1295 * Implementation when a caller has performed an insert on the content
1296 * provider, but that call has been rejected for the operation given
1297 * to {@link #setAppOps(int, int)}. The default implementation simply
1298 * returns a dummy URI that is the base URI with a 0 path element
1299 * appended.
1300 */
1301 public Uri rejectInsert(Uri uri, ContentValues values) {
1302 // If not allowed, we need to return some reasonable URI. Maybe the
1303 // content provider should be responsible for this, but for now we
1304 // will just return the base URI with a dummy '0' tagged on to it.
1305 // You shouldn't be able to read if you can't write, anyway, so it
1306 // shouldn't matter much what is returned.
1307 return uri.buildUpon().appendPath("0").build();
1308 }
1309
1310 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001311 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1313 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001314 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001315 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1316 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001317 * @param uri The content:// URI of the insertion request. This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001319 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 * @return The URI for the newly inserted item.
1321 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001322 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323
1324 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001325 * Override this to handle requests to insert a set of new rows, or the
1326 * default implementation will iterate over the values and call
1327 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1329 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001330 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001331 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1332 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 *
1334 * @param uri The content:// URI of the insertion request.
1335 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001336 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 * @return The number of values that were inserted.
1338 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001339 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 int numValues = values.length;
1341 for (int i = 0; i < numValues; i++) {
1342 insert(uri, values[i]);
1343 }
1344 return numValues;
1345 }
1346
1347 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001348 * Implement this to handle requests to delete one or more rows.
1349 * The implementation should apply the selection clause when performing
1350 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001351 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001353 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001354 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1355 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 *
1357 * <p>The implementation is responsible for parsing out a row ID at the end
1358 * of the URI, if a specific row is being deleted. That is, the client would
1359 * pass in <code>content://contacts/people/22</code> and the implementation is
1360 * responsible for parsing the record number (22) when creating a SQL statement.
1361 *
1362 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1363 * @param selection An optional restriction to apply to rows when deleting.
1364 * @return The number of rows affected.
1365 * @throws SQLException
1366 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001367 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1368 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
1370 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001371 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001372 * The implementation should update all rows matching the selection
1373 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1375 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001376 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001377 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1378 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 *
1380 * @param uri The URI to query. This can potentially have a record ID if this
1381 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001382 * @param values A set of column_name/value pairs to update in the database.
1383 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 * @param selection An optional filter to match rows to update.
1385 * @return the number of rows affected.
1386 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001387 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001388 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001391 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001392 * The default implementation always throws {@link FileNotFoundException}.
1393 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001394 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1395 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001396 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001397 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1398 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001399 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 *
1401 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1402 * their responsibility to close it when done. That is, the implementation
1403 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001404 * <p>
1405 * If opened with the exclusive "r" or "w" modes, the returned
1406 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1407 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1408 * supports seeking.
1409 * <p>
1410 * If you need to detect when the returned ParcelFileDescriptor has been
1411 * closed, or if the remote process has crashed or encountered some other
1412 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1413 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1414 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1415 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001416 * <p>
1417 * If you need to return a large file that isn't backed by a real file on
1418 * disk, such as a file on a network share or cloud storage service,
1419 * consider using
1420 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1421 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001423 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1424 * to return the appropriate MIME type for the data returned here with
1425 * the same URI. This will allow intent resolution to automatically determine the data MIME
1426 * type and select the appropriate matching targets as part of its operation.</p>
1427 *
1428 * <p class="note">For better interoperability with other applications, it is recommended
1429 * that for any URIs that can be opened, you also support queries on them
1430 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1431 * You may also want to support other common columns if you have additional meta-data
1432 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1433 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1434 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 * @param uri The URI whose file is to be opened.
1436 * @param mode Access mode for the file. May be "r" for read-only access,
1437 * "rw" for read and write access, or "rwt" for read and write access
1438 * that truncates any existing file.
1439 *
1440 * @return Returns a new ParcelFileDescriptor which you can use to access
1441 * the file.
1442 *
1443 * @throws FileNotFoundException Throws FileNotFoundException if there is
1444 * no file associated with the given URI or the mode is invalid.
1445 * @throws SecurityException Throws SecurityException if the caller does
1446 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001447 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 * @see #openAssetFile(Uri, String)
1449 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001450 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001451 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001452 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001453 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 throws FileNotFoundException {
1455 throw new FileNotFoundException("No files supported by provider at "
1456 + uri);
1457 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001460 * Override this to handle requests to open a file blob.
1461 * The default implementation always throws {@link FileNotFoundException}.
1462 * This method can be called from multiple threads, as described in
1463 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1464 * and Threads</a>.
1465 *
1466 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1467 * to the caller. This way large data (such as images and documents) can be
1468 * returned without copying the content.
1469 *
1470 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1471 * their responsibility to close it when done. That is, the implementation
1472 * of this method should create a new ParcelFileDescriptor for each call.
1473 * <p>
1474 * If opened with the exclusive "r" or "w" modes, the returned
1475 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1476 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1477 * supports seeking.
1478 * <p>
1479 * If you need to detect when the returned ParcelFileDescriptor has been
1480 * closed, or if the remote process has crashed or encountered some other
1481 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1482 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1483 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1484 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1485 *
1486 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1487 * to return the appropriate MIME type for the data returned here with
1488 * the same URI. This will allow intent resolution to automatically determine the data MIME
1489 * type and select the appropriate matching targets as part of its operation.</p>
1490 *
1491 * <p class="note">For better interoperability with other applications, it is recommended
1492 * that for any URIs that can be opened, you also support queries on them
1493 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1494 * You may also want to support other common columns if you have additional meta-data
1495 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1496 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1497 *
1498 * @param uri The URI whose file is to be opened.
1499 * @param mode Access mode for the file. May be "r" for read-only access,
1500 * "w" for write-only access, "rw" for read and write access, or
1501 * "rwt" for read and write access that truncates any existing
1502 * file.
1503 * @param signal A signal to cancel the operation in progress, or
1504 * {@code null} if none. For example, if you are downloading a
1505 * file from the network to service a "rw" mode request, you
1506 * should periodically call
1507 * {@link CancellationSignal#throwIfCanceled()} to check whether
1508 * the client has canceled the request and abort the download.
1509 *
1510 * @return Returns a new ParcelFileDescriptor which you can use to access
1511 * the file.
1512 *
1513 * @throws FileNotFoundException Throws FileNotFoundException if there is
1514 * no file associated with the given URI or the mode is invalid.
1515 * @throws SecurityException Throws SecurityException if the caller does
1516 * not have permission to access the file.
1517 *
1518 * @see #openAssetFile(Uri, String)
1519 * @see #openFileHelper(Uri, String)
1520 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001521 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001522 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001523 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1524 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001525 return openFile(uri, mode);
1526 }
1527
1528 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 * This is like {@link #openFile}, but can be implemented by providers
1530 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001531 * inside of their .apk.
1532 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001533 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1534 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001535 *
1536 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001537 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001538 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1540 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1541 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001542 * <p>
1543 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1544 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001545 *
1546 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 * should create the AssetFileDescriptor with
1548 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001549 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001551 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1552 * to return the appropriate MIME type for the data returned here with
1553 * the same URI. This will allow intent resolution to automatically determine the data MIME
1554 * type and select the appropriate matching targets as part of its operation.</p>
1555 *
1556 * <p class="note">For better interoperability with other applications, it is recommended
1557 * that for any URIs that can be opened, you also support queries on them
1558 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1559 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 * @param uri The URI whose file is to be opened.
1561 * @param mode Access mode for the file. May be "r" for read-only access,
1562 * "w" for write-only access (erasing whatever data is currently in
1563 * the file), "wa" for write-only access to append to any existing data,
1564 * "rw" for read and write access on any existing data, and "rwt" for read
1565 * and write access that truncates any existing file.
1566 *
1567 * @return Returns a new AssetFileDescriptor which you can use to access
1568 * the file.
1569 *
1570 * @throws FileNotFoundException Throws FileNotFoundException if there is
1571 * no file associated with the given URI or the mode is invalid.
1572 * @throws SecurityException Throws SecurityException if the caller does
1573 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001574 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 * @see #openFile(Uri, String)
1576 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001577 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001579 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 throws FileNotFoundException {
1581 ParcelFileDescriptor fd = openFile(uri, mode);
1582 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1583 }
1584
1585 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001586 * This is like {@link #openFile}, but can be implemented by providers
1587 * that need to be able to return sub-sections of files, often assets
1588 * inside of their .apk.
1589 * This method can be called from multiple threads, as described in
1590 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1591 * and Threads</a>.
1592 *
1593 * <p>If you implement this, your clients must be able to deal with such
1594 * file slices, either directly with
1595 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1596 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1597 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1598 * methods.
1599 * <p>
1600 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1601 * streaming of data.
1602 *
1603 * <p class="note">If you are implementing this to return a full file, you
1604 * should create the AssetFileDescriptor with
1605 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1606 * applications that cannot handle sub-sections of files.</p>
1607 *
1608 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1609 * to return the appropriate MIME type for the data returned here with
1610 * the same URI. This will allow intent resolution to automatically determine the data MIME
1611 * type and select the appropriate matching targets as part of its operation.</p>
1612 *
1613 * <p class="note">For better interoperability with other applications, it is recommended
1614 * that for any URIs that can be opened, you also support queries on them
1615 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1616 *
1617 * @param uri The URI whose file is to be opened.
1618 * @param mode Access mode for the file. May be "r" for read-only access,
1619 * "w" for write-only access (erasing whatever data is currently in
1620 * the file), "wa" for write-only access to append to any existing data,
1621 * "rw" for read and write access on any existing data, and "rwt" for read
1622 * and write access that truncates any existing file.
1623 * @param signal A signal to cancel the operation in progress, or
1624 * {@code null} if none. For example, if you are downloading a
1625 * file from the network to service a "rw" mode request, you
1626 * should periodically call
1627 * {@link CancellationSignal#throwIfCanceled()} to check whether
1628 * the client has canceled the request and abort the download.
1629 *
1630 * @return Returns a new AssetFileDescriptor which you can use to access
1631 * the file.
1632 *
1633 * @throws FileNotFoundException Throws FileNotFoundException if there is
1634 * no file associated with the given URI or the mode is invalid.
1635 * @throws SecurityException Throws SecurityException if the caller does
1636 * not have permission to access the file.
1637 *
1638 * @see #openFile(Uri, String)
1639 * @see #openFileHelper(Uri, String)
1640 * @see #getType(android.net.Uri)
1641 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001642 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1643 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001644 return openAssetFile(uri, mode);
1645 }
1646
1647 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 * Convenience for subclasses that wish to implement {@link #openFile}
1649 * by looking up a column named "_data" at the given URI.
1650 *
1651 * @param uri The URI to be opened.
1652 * @param mode The file mode. May be "r" for read-only access,
1653 * "w" for write-only access (erasing whatever data is currently in
1654 * the file), "wa" for write-only access to append to any existing data,
1655 * "rw" for read and write access on any existing data, and "rwt" for read
1656 * and write access that truncates any existing file.
1657 *
1658 * @return Returns a new ParcelFileDescriptor that can be used by the
1659 * client to access the file.
1660 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001661 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1662 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1664 int count = (c != null) ? c.getCount() : 0;
1665 if (count != 1) {
1666 // If there is not exactly one result, throw an appropriate
1667 // exception.
1668 if (c != null) {
1669 c.close();
1670 }
1671 if (count == 0) {
1672 throw new FileNotFoundException("No entry for " + uri);
1673 }
1674 throw new FileNotFoundException("Multiple items at " + uri);
1675 }
1676
1677 c.moveToFirst();
1678 int i = c.getColumnIndex("_data");
1679 String path = (i >= 0 ? c.getString(i) : null);
1680 c.close();
1681 if (path == null) {
1682 throw new FileNotFoundException("Column _data not found.");
1683 }
1684
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001685 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 return ParcelFileDescriptor.open(new File(path), modeBits);
1687 }
1688
1689 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001690 * Called by a client to determine the types of data streams that this
1691 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001692 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001693 * of a particular type, return that MIME type if it matches the given
1694 * mimeTypeFilter. If it can perform type conversions, return an array
1695 * of all supported MIME types that match mimeTypeFilter.
1696 *
1697 * @param uri The data in the content provider being queried.
1698 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001699 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001700 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001701 * given mimeTypeFilter. Otherwise returns an array of all available
1702 * concrete MIME types.
1703 *
1704 * @see #getType(Uri)
1705 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001706 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001707 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001708 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001709 return null;
1710 }
1711
1712 /**
1713 * Called by a client to open a read-only stream containing data of a
1714 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1715 * except the file can only be read-only and the content provider may
1716 * perform data conversions to generate data of the desired type.
1717 *
1718 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001719 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001720 * {@link #openAssetFile(Uri, String)}.
1721 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001722 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001723 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001724 * <p>
1725 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1726 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001727 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001728 * <p class="note">For better interoperability with other applications, it is recommended
1729 * that for any URIs that can be opened, you also support queries on them
1730 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1731 * You may also want to support other common columns if you have additional meta-data
1732 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1733 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1734 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001735 * @param uri The data in the content provider being queried.
1736 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001737 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001738 * requirements; in this case the content provider will pick its best
1739 * type matching the pattern.
1740 * @param opts Additional options from the client. The definitions of
1741 * these are specific to the content provider being called.
1742 *
1743 * @return Returns a new AssetFileDescriptor from which the client can
1744 * read data of the desired type.
1745 *
1746 * @throws FileNotFoundException Throws FileNotFoundException if there is
1747 * no file associated with the given URI or the mode is invalid.
1748 * @throws SecurityException Throws SecurityException if the caller does
1749 * not have permission to access the data.
1750 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1751 * content provider does not support the requested MIME type.
1752 *
1753 * @see #getStreamTypes(Uri, String)
1754 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001755 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001756 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001757 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1758 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001759 if ("*/*".equals(mimeTypeFilter)) {
1760 // If they can take anything, the untyped open call is good enough.
1761 return openAssetFile(uri, "r");
1762 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001763 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001764 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001765 // Use old untyped open call if this provider has a type for this
1766 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001767 return openAssetFile(uri, "r");
1768 }
1769 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1770 }
1771
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001772
1773 /**
1774 * Called by a client to open a read-only stream containing data of a
1775 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1776 * except the file can only be read-only and the content provider may
1777 * perform data conversions to generate data of the desired type.
1778 *
1779 * <p>The default implementation compares the given mimeType against the
1780 * result of {@link #getType(Uri)} and, if they match, simply calls
1781 * {@link #openAssetFile(Uri, String)}.
1782 *
1783 * <p>See {@link ClipData} for examples of the use and implementation
1784 * of this method.
1785 * <p>
1786 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1787 * streaming of data.
1788 *
1789 * <p class="note">For better interoperability with other applications, it is recommended
1790 * that for any URIs that can be opened, you also support queries on them
1791 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1792 * You may also want to support other common columns if you have additional meta-data
1793 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1794 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1795 *
1796 * @param uri The data in the content provider being queried.
1797 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001798 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001799 * requirements; in this case the content provider will pick its best
1800 * type matching the pattern.
1801 * @param opts Additional options from the client. The definitions of
1802 * these are specific to the content provider being called.
1803 * @param signal A signal to cancel the operation in progress, or
1804 * {@code null} if none. For example, if you are downloading a
1805 * file from the network to service a "rw" mode request, you
1806 * should periodically call
1807 * {@link CancellationSignal#throwIfCanceled()} to check whether
1808 * the client has canceled the request and abort the download.
1809 *
1810 * @return Returns a new AssetFileDescriptor from which the client can
1811 * read data of the desired type.
1812 *
1813 * @throws FileNotFoundException Throws FileNotFoundException if there is
1814 * no file associated with the given URI or the mode is invalid.
1815 * @throws SecurityException Throws SecurityException if the caller does
1816 * not have permission to access the data.
1817 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1818 * content provider does not support the requested MIME type.
1819 *
1820 * @see #getStreamTypes(Uri, String)
1821 * @see #openAssetFile(Uri, String)
1822 * @see ClipDescription#compareMimeTypes(String, String)
1823 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001824 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1825 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1826 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001827 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1828 }
1829
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001830 /**
1831 * Interface to write a stream of data to a pipe. Use with
1832 * {@link ContentProvider#openPipeHelper}.
1833 */
1834 public interface PipeDataWriter<T> {
1835 /**
1836 * Called from a background thread to stream data out to a pipe.
1837 * Note that the pipe is blocking, so this thread can block on
1838 * writes for an arbitrary amount of time if the client is slow
1839 * at reading.
1840 *
1841 * @param output The pipe where data should be written. This will be
1842 * closed for you upon returning from this function.
1843 * @param uri The URI whose data is to be written.
1844 * @param mimeType The desired type of data to be written.
1845 * @param opts Options supplied by caller.
1846 * @param args Your own custom arguments.
1847 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001848 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1849 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001850 }
1851
1852 /**
1853 * A helper function for implementing {@link #openTypedAssetFile}, for
1854 * creating a data pipe and background thread allowing you to stream
1855 * generated data back to the client. This function returns a new
1856 * ParcelFileDescriptor that should be returned to the caller (the caller
1857 * is responsible for closing it).
1858 *
1859 * @param uri The URI whose data is to be written.
1860 * @param mimeType The desired type of data to be written.
1861 * @param opts Options supplied by caller.
1862 * @param args Your own custom arguments.
1863 * @param func Interface implementing the function that will actually
1864 * stream the data.
1865 * @return Returns a new ParcelFileDescriptor holding the read side of
1866 * the pipe. This should be returned to the caller for reading; the caller
1867 * is responsible for closing it when done.
1868 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001869 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1870 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1871 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001872 try {
1873 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1874
1875 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1876 @Override
1877 protected Object doInBackground(Object... params) {
1878 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1879 try {
1880 fds[1].close();
1881 } catch (IOException e) {
1882 Log.w(TAG, "Failure closing pipe", e);
1883 }
1884 return null;
1885 }
1886 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001887 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001888
1889 return fds[0];
1890 } catch (IOException e) {
1891 throw new FileNotFoundException("failure making pipe");
1892 }
1893 }
1894
1895 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 * Returns true if this instance is a temporary content provider.
1897 * @return true if this instance is a temporary content provider
1898 */
1899 protected boolean isTemporary() {
1900 return false;
1901 }
1902
1903 /**
1904 * Returns the Binder object for this provider.
1905 *
1906 * @return the Binder object for this provider
1907 * @hide
1908 */
1909 public IContentProvider getIContentProvider() {
1910 return mTransport;
1911 }
1912
1913 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001914 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1915 * when directly instantiating the provider for testing.
1916 * @hide
1917 */
1918 public void attachInfoForTesting(Context context, ProviderInfo info) {
1919 attachInfo(context, info, true);
1920 }
1921
1922 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 * After being instantiated, this is called to tell the content provider
1924 * about itself.
1925 *
1926 * @param context The context this provider is running in
1927 * @param info Registered information about this content provider
1928 */
1929 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001930 attachInfo(context, info, false);
1931 }
1932
1933 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001934 mNoPerms = testing;
1935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 /*
1937 * Only allow it to be set once, so after the content service gives
1938 * this to us clients can't change it.
1939 */
1940 if (mContext == null) {
1941 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001942 if (context != null) {
1943 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1944 Context.APP_OPS_SERVICE);
1945 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001946 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 if (info != null) {
1948 setReadPermission(info.readPermission);
1949 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001950 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001951 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001952 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001953 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
1955 ContentProvider.this.onCreate();
1956 }
1957 }
Fred Quintanace31b232009-05-04 16:01:15 -07001958
1959 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001960 * Override this to handle requests to perform a batch of operations, or the
1961 * default implementation will iterate over the operations and call
1962 * {@link ContentProviderOperation#apply} on each of them.
1963 * If all calls to {@link ContentProviderOperation#apply} succeed
1964 * then a {@link ContentProviderResult} array with as many
1965 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001966 * fail, it is up to the implementation how many of the others take effect.
1967 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001968 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1969 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001970 *
Fred Quintanace31b232009-05-04 16:01:15 -07001971 * @param operations the operations to apply
1972 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001973 * @throws OperationApplicationException thrown if any operation fails.
1974 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001975 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001976 public @NonNull ContentProviderResult[] applyBatch(
1977 @NonNull ArrayList<ContentProviderOperation> operations)
1978 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001979 final int numOperations = operations.size();
1980 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1981 for (int i = 0; i < numOperations; i++) {
1982 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001983 }
1984 return results;
1985 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001986
1987 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001988 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001989 * interfaces that are cheaper and/or unnatural for a table-like
1990 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001991 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001992 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1993 * on this entry into the content provider besides the basic ability for the application
1994 * to get access to the provider at all. For example, it has no idea whether the call
1995 * being executed may read or write data in the provider, so can't enforce those
1996 * individual permissions. Any implementation of this method <strong>must</strong>
1997 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1998 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001999 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2000 * @param arg provider-defined String argument. May be {@code null}.
2001 * @param extras provider-defined Bundle argument. May be {@code null}.
2002 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002003 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002004 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002005 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2006 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002007 return null;
2008 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002009
2010 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002011 * Implement this to shut down the ContentProvider instance. You can then
2012 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002013 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002014 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002015 * Android normally handles ContentProvider startup and shutdown
2016 * automatically. You do not need to start up or shut down a
2017 * ContentProvider. When you invoke a test method on a ContentProvider,
2018 * however, a ContentProvider instance is started and keeps running after
2019 * the test finishes, even if a succeeding test instantiates another
2020 * ContentProvider. A conflict develops because the two instances are
2021 * usually running against the same underlying data source (for example, an
2022 * sqlite database).
2023 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002024 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002025 * Implementing shutDown() avoids this conflict by providing a way to
2026 * terminate the ContentProvider. This method can also prevent memory leaks
2027 * from multiple instantiations of the ContentProvider, and it can ensure
2028 * unit test isolation by allowing you to completely clean up the test
2029 * fixture before moving on to the next test.
2030 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002031 */
2032 public void shutdown() {
2033 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2034 "connections are gracefully shutdown");
2035 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002036
2037 /**
2038 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002039 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002040 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002041 * @param fd The raw file descriptor that the dump is being sent to.
2042 * @param writer The PrintWriter to which you should dump your state. This will be
2043 * closed for you after you return.
2044 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002045 */
2046 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2047 writer.println("nothing to dump");
2048 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002049
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002050 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002051 private void validateIncomingUri(Uri uri) throws SecurityException {
2052 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002053 if (!mSingleUser) {
2054 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2055 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2056 throw new SecurityException("trying to query a ContentProvider in user "
2057 + mContext.getUserId() + " with a uri belonging to user " + userId);
2058 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002059 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002060 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2061 String message = "The authority of the uri " + uri + " does not match the one of the "
2062 + "contentProvider: ";
2063 if (mAuthority != null) {
2064 message += mAuthority;
2065 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002066 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002067 }
2068 throw new SecurityException(message);
2069 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002070 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002071
2072 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002073 private Uri maybeGetUriWithoutUserId(Uri uri) {
2074 if (mSingleUser) {
2075 return uri;
2076 }
2077 return getUriWithoutUserId(uri);
2078 }
2079
2080 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002081 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2082 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002083 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002084 if (end == -1) return defaultUserId;
2085 String userIdString = auth.substring(0, end);
2086 try {
2087 return Integer.parseInt(userIdString);
2088 } catch (NumberFormatException e) {
2089 Log.w(TAG, "Error parsing userId.", e);
2090 return UserHandle.USER_NULL;
2091 }
2092 }
2093
2094 /** @hide */
2095 public static int getUserIdFromAuthority(String auth) {
2096 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2097 }
2098
2099 /** @hide */
2100 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2101 if (uri == null) return defaultUserId;
2102 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2103 }
2104
2105 /** @hide */
2106 public static int getUserIdFromUri(Uri uri) {
2107 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2108 }
2109
2110 /**
2111 * Removes userId part from authority string. Expects format:
2112 * userId@some.authority
2113 * If there is no userId in the authority, it symply returns the argument
2114 * @hide
2115 */
2116 public static String getAuthorityWithoutUserId(String auth) {
2117 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002118 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002119 return auth.substring(end+1);
2120 }
2121
2122 /** @hide */
2123 public static Uri getUriWithoutUserId(Uri uri) {
2124 if (uri == null) return null;
2125 Uri.Builder builder = uri.buildUpon();
2126 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2127 return builder.build();
2128 }
2129
2130 /** @hide */
2131 public static boolean uriHasUserId(Uri uri) {
2132 if (uri == null) return false;
2133 return !TextUtils.isEmpty(uri.getUserInfo());
2134 }
2135
2136 /** @hide */
2137 public static Uri maybeAddUserId(Uri uri, int userId) {
2138 if (uri == null) return null;
2139 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002140 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002141 if (!uriHasUserId(uri)) {
2142 //We don't add the user Id if there's already one
2143 Uri.Builder builder = uri.buildUpon();
2144 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2145 return builder.build();
2146 }
2147 }
2148 return uri;
2149 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002150}