blob: 5a12e4ecca1b78418384d988a8769272786254c7 [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;
Eugene Susla93519852018-06-13 16:44:31 -070021import static android.app.AppOpsManager.MODE_DEFAULT;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070022import static android.app.AppOpsManager.MODE_ERRORED;
23import static android.app.AppOpsManager.MODE_IGNORED;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060025import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070026
Jeff Sharkey673db442015-06-11 19:30:57 -070027import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080028import android.annotation.Nullable;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010029import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080030import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070031import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.pm.ProviderInfo;
33import android.content.res.AssetFileDescriptor;
34import android.content.res.Configuration;
35import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070036import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.database.SQLException;
38import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070039import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010041import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080042import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070043import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080044import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070045import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070047import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080048import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060049import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070050import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060051import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010052import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070053import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060055import com.android.internal.annotations.VisibleForTesting;
56
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080058import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070060import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080061import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070062import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080063import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060064import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
66/**
67 * Content providers are one of the primary building blocks of Android applications, providing
68 * content to applications. They encapsulate data and provide it to applications through the single
69 * {@link ContentResolver} interface. A content provider is only required if you need to share
70 * data between multiple applications. For example, the contacts data is used by multiple
71 * applications and must be stored in a content provider. If you don't need to share data amongst
72 * multiple applications you can use a database directly via
73 * {@link android.database.sqlite.SQLiteDatabase}.
74 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 * <p>When a request is made via
76 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
77 * request to the content provider registered with the authority. The content provider can interpret
78 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
79 * URIs.</p>
80 *
81 * <p>The primary methods that need to be implemented are:
82 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070083 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * <li>{@link #query} which returns data to the caller</li>
85 * <li>{@link #insert} which inserts new data into the content provider</li>
86 * <li>{@link #update} which updates existing data in the content provider</li>
87 * <li>{@link #delete} which deletes data from the content provider</li>
88 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
89 * </ul></p>
90 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070091 * <p class="caution">Data access methods (such as {@link #insert} and
92 * {@link #update}) may be called from many threads at once, and must be thread-safe.
93 * Other methods (such as {@link #onCreate}) are only called from the application
94 * main thread, and must avoid performing lengthy operations. See the method
95 * descriptions for their expected thread behavior.</p>
96 *
97 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
98 * ContentProvider instance, so subclasses don't have to worry about the details of
99 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700100 *
101 * <div class="special reference">
102 * <h3>Developer Guides</h3>
103 * <p>For more information about using content providers, read the
104 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
105 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700106 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700108public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800109
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700110 private static final String TAG = "ContentProvider";
111
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900112 /*
113 * Note: if you add methods to ContentProvider, you must add similar methods to
114 * MockContentProvider.
115 */
116
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100117 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700119 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100120
121 // Since most Providers have only one authority, we keep both a String and a String[] to improve
122 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100123 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100124 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100125 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100126 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100127 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100131 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700132 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700133 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800134 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700135 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Steve McKayea93fe72016-12-02 11:35:35 -0800137 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private Transport mTransport = new Transport();
140
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700141 /**
142 * Construct a ContentProvider instance. Content providers must be
143 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
144 * in the manifest</a>, accessed with {@link ContentResolver}, and created
145 * automatically by the system, so applications usually do not create
146 * ContentProvider instances directly.
147 *
148 * <p>At construction time, the object is uninitialized, and most fields and
149 * methods are unavailable. Subclasses should initialize themselves in
150 * {@link #onCreate}, not the constructor.
151 *
152 * <p>Content providers are created on the application main thread at
153 * application launch time. The constructor must not perform lengthy
154 * operations, or application startup will be delayed.
155 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900156 public ContentProvider() {
157 }
158
159 /**
160 * Constructor just for mocking.
161 *
162 * @param context A Context object which should be some mock instance (like the
163 * instance of {@link android.test.mock.MockContext}).
164 * @param readPermission The read permision you want this instance should have in the
165 * test, which is available via {@link #getReadPermission()}.
166 * @param writePermission The write permission you want this instance should have
167 * in the test, which is available via {@link #getWritePermission()}.
168 * @param pathPermissions The PathPermissions you want this instance should have
169 * in the test, which is available via {@link #getPathPermissions()}.
170 * @hide
171 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100172 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900173 public ContentProvider(
174 Context context,
175 String readPermission,
176 String writePermission,
177 PathPermission[] pathPermissions) {
178 mContext = context;
179 mReadPermission = readPermission;
180 mWritePermission = writePermission;
181 mPathPermissions = pathPermissions;
182 }
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 /**
185 * Given an IContentProvider, try to coerce it back to the real
186 * ContentProvider object if it is running in the local process. This can
187 * be used if you know you are running in the same process as a provider,
188 * and want to get direct access to its implementation details. Most
189 * clients should not nor have a reason to use it.
190 *
191 * @param abstractInterface The ContentProvider interface that is to be
192 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800193 * @return If the IContentProvider is non-{@code null} and local, returns its actual
194 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 * @hide
196 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100197 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 public static ContentProvider coerceToLocalContentProvider(
199 IContentProvider abstractInterface) {
200 if (abstractInterface instanceof Transport) {
201 return ((Transport)abstractInterface).getContentProvider();
202 }
203 return null;
204 }
205
206 /**
207 * Binder object that deals with remoting.
208 *
209 * @hide
210 */
211 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800212 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800213 int mReadOp = AppOpsManager.OP_NONE;
214 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 ContentProvider getContentProvider() {
217 return ContentProvider.this;
218 }
219
Jeff Brownd2183652011-10-09 12:39:53 -0700220 @Override
221 public String getProviderName() {
222 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 }
224
Jeff Brown75ea64f2012-01-25 19:37:13 -0800225 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800226 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
227 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600228 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100229 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800230 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700231 // The caller has no access to the data, so return an empty cursor with
232 // the columns in the requested order. The caller may ask for an invalid
233 // column and we would not catch that but this is not a problem in practice.
234 // We do not call ContentProvider#query with a modified where clause since
235 // the implementation is not guaranteed to be backed by a SQL database, hence
236 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700237 if (projection != null) {
238 return new MatrixCursor(projection, 0);
239 }
240
241 // Null projection means all columns but we have no idea which they are.
242 // However, the caller may be expecting to access them my index. Hence,
243 // we have to execute the query as if allowed to get a cursor with the
244 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700245 Cursor cursor;
246 final String original = setCallingPackage(callingPkg);
247 try {
248 cursor = ContentProvider.this.query(
249 uri, projection, queryArgs,
250 CancellationSignal.fromTransport(cancellationSignal));
251 } finally {
252 setCallingPackage(original);
253 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700254 if (cursor == null) {
255 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700256 }
257
258 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700259 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800260 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600261 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700262 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700263 try {
264 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800265 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700266 CancellationSignal.fromTransport(cancellationSignal));
267 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700268 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600269 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 }
272
Jeff Brown75ea64f2012-01-25 19:37:13 -0800273 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700275 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600276 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100277 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600278 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
279 try {
280 return ContentProvider.this.getType(uri);
281 } finally {
282 Trace.traceEnd(TRACE_TAG_DATABASE);
283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285
Jeff Brown75ea64f2012-01-25 19:37:13 -0800286 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800287 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600288 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100289 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100290 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800291 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700292 final String original = setCallingPackage(callingPkg);
293 try {
294 return rejectInsert(uri, initialValues);
295 } finally {
296 setCallingPackage(original);
297 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800298 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600299 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700300 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700301 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100302 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700303 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700304 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600305 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 }
308
Jeff Brown75ea64f2012-01-25 19:37:13 -0800309 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800310 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600311 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100312 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800313 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800314 return 0;
315 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600316 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700317 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700318 try {
319 return ContentProvider.this.bulkInsert(uri, initialValues);
320 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700321 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600322 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325
Jeff Brown75ea64f2012-01-25 19:37:13 -0800326 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700327 public ContentProviderResult[] applyBatch(String callingPkg, String authority,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800328 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700329 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100330 int numOperations = operations.size();
331 final int[] userIds = new int[numOperations];
332 for (int i = 0; i < numOperations; i++) {
333 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100334 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600335 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600336 uri = validateIncomingUri(uri);
337 uri = maybeGetUriWithoutUserId(uri);
338 // Rebuild operation if we changed the Uri above
339 if (!Objects.equals(operation.getUri(), uri)) {
340 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100341 operations.set(i, operation);
342 }
Fred Quintana89437372009-05-15 15:10:40 -0700343 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800344 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800345 != AppOpsManager.MODE_ALLOWED) {
346 throw new OperationApplicationException("App op not allowed", 0);
347 }
Fred Quintana89437372009-05-15 15:10:40 -0700348 }
Fred Quintana89437372009-05-15 15:10:40 -0700349 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800350 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800351 != AppOpsManager.MODE_ALLOWED) {
352 throw new OperationApplicationException("App op not allowed", 0);
353 }
Fred Quintana89437372009-05-15 15:10:40 -0700354 }
355 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600356 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700357 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700358 try {
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700359 ContentProviderResult[] results = ContentProvider.this.applyBatch(authority,
360 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800361 if (results != null) {
362 for (int i = 0; i < results.length ; i++) {
363 if (userIds[i] != UserHandle.USER_CURRENT) {
364 // Adding the userId to the uri.
365 results[i] = new ContentProviderResult(results[i], userIds[i]);
366 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100367 }
368 }
369 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700371 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600372 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700373 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700374 }
375
Jeff Brown75ea64f2012-01-25 19:37:13 -0800376 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800377 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600378 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100379 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800380 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800381 return 0;
382 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600383 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700384 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700385 try {
386 return ContentProvider.this.delete(uri, selection, selectionArgs);
387 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700388 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600389 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 }
392
Jeff Brown75ea64f2012-01-25 19:37:13 -0800393 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800394 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600396 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100397 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800398 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800399 return 0;
400 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600401 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700402 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700403 try {
404 return ContentProvider.this.update(uri, values, selection, selectionArgs);
405 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700406 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600407 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 }
410
Jeff Brown75ea64f2012-01-25 19:37:13 -0800411 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700412 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800413 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
414 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600415 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100416 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800417 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600418 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700419 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700420 try {
421 return ContentProvider.this.openFile(
422 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
423 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700424 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600425 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
428
Jeff Brown75ea64f2012-01-25 19:37:13 -0800429 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700430 public AssetFileDescriptor openAssetFile(
431 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600433 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100434 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800435 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600436 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700437 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700438 try {
439 return ContentProvider.this.openAssetFile(
440 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
441 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700442 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600443 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
446
Jeff Brown75ea64f2012-01-25 19:37:13 -0800447 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700448 public Bundle call(String callingPkg, String authority, String method, @Nullable String arg,
449 @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600450 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600451 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700452 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700453 try {
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700454 return ContentProvider.this.call(authority, method, arg, extras);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700455 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700456 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600457 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700458 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800459 }
460
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700461 @Override
462 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700463 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600464 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100465 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600466 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
467 try {
468 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
469 } finally {
470 Trace.traceEnd(TRACE_TAG_DATABASE);
471 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700472 }
473
474 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800475 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700476 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600477 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600478 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100479 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800480 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600481 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700482 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700483 try {
484 return ContentProvider.this.openTypedAssetFile(
485 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
486 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700487 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600488 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700489 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700490 }
491
Jeff Brown75ea64f2012-01-25 19:37:13 -0800492 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700493 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800494 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800495 }
496
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700497 @Override
498 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600499 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100500 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100501 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800502 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700503 return null;
504 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600505 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700506 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700507 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100508 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700509 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700510 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600511 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700512 }
513 }
514
515 @Override
516 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600517 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100518 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100519 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800520 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700521 return null;
522 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600523 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700524 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700525 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100526 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700527 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700528 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600529 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700530 }
531 }
532
Ben Lin1cf454f2016-11-10 13:50:54 -0800533 @Override
534 public boolean refresh(String callingPkg, Uri uri, Bundle args,
535 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600536 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800537 uri = getUriWithoutUserId(uri);
538 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
539 return false;
540 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600541 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800542 final String original = setCallingPackage(callingPkg);
543 try {
544 return ContentProvider.this.refresh(uri, args,
545 CancellationSignal.fromTransport(cancellationSignal));
546 } finally {
547 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600548 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800549 }
550 }
551
Dianne Hackbornff170242014-11-19 10:59:01 -0800552 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
553 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800554 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800555 if (enforceWritePermission(callingPkg, uri, callerToken)
556 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800557 throw new FileNotFoundException("App op not allowed");
558 }
559 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800560 if (enforceReadPermission(callingPkg, uri, callerToken)
561 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800562 throw new FileNotFoundException("App op not allowed");
563 }
564 }
565 }
566
Dianne Hackbornff170242014-11-19 10:59:01 -0800567 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
568 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700569 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
570 if (mode != MODE_ALLOWED) {
571 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800572 }
Svet Ganov99b60432015-06-27 13:15:22 -0700573
Eugene Susla93519852018-06-13 16:44:31 -0700574 return noteProxyOp(callingPkg, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800575 }
576
Dianne Hackbornff170242014-11-19 10:59:01 -0800577 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
578 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700579 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
580 if (mode != MODE_ALLOWED) {
581 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800582 }
Svet Ganov99b60432015-06-27 13:15:22 -0700583
Eugene Susla93519852018-06-13 16:44:31 -0700584 return noteProxyOp(callingPkg, mWriteOp);
585 }
586
587 private int noteProxyOp(String callingPkg, int op) {
588 if (op != AppOpsManager.OP_NONE) {
589 int mode = mAppOpsManager.noteProxyOp(op, callingPkg);
Eugene Suslab22f71e2018-11-30 10:17:20 -0800590 int nonDefaultMode = mode == MODE_DEFAULT ? interpretDefaultAppOpMode(op) : mode;
591 if (mode == MODE_DEFAULT && nonDefaultMode == MODE_IGNORED) {
Eugene Suslaaaa54272018-12-06 11:04:21 -0800592 Log.w(TAG, "Denying access for " + callingPkg + " to " + getClass().getName()
Eugene Suslab22f71e2018-11-30 10:17:20 -0800593 + " (" + AppOpsManager.opToName(op)
594 + " = " + AppOpsManager.opToName(mode) + ")");
595 }
596 return mode == MODE_DEFAULT ? nonDefaultMode : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700597 }
598
Dianne Hackborn35654b62013-01-14 17:38:02 -0800599 return AppOpsManager.MODE_ALLOWED;
600 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700601 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800602
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100603 boolean checkUser(int pid, int uid, Context context) {
604 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700605 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100606 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
607 == PERMISSION_GRANTED;
608 }
609
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700610 /**
611 * Verify that calling app holds both the given permission and any app-op
612 * associated with that permission.
613 */
614 private int checkPermissionAndAppOp(String permission, String callingPkg,
615 IBinder callerToken) {
616 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
617 callerToken) != PERMISSION_GRANTED) {
618 return MODE_ERRORED;
619 }
620
Eugene Susla93519852018-06-13 16:44:31 -0700621 return mTransport.noteProxyOp(callingPkg, AppOpsManager.permissionToOpCode(permission));
622 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700623
Eugene Susla93519852018-06-13 16:44:31 -0700624 /**
625 * Allows for custom interpretations of {@link AppOpsManager#MODE_DEFAULT} by individual
626 * content providers
627 *
628 * @hide
629 */
630 protected int interpretDefaultAppOpMode(int op) {
631 return MODE_IGNORED;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700632 }
633
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700634 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700635 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800636 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700637 final Context context = getContext();
638 final int pid = Binder.getCallingPid();
639 final int uid = Binder.getCallingUid();
640 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700641 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700642
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700643 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700644 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700645 }
646
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100647 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700648 final String componentPerm = getReadPermission();
649 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700650 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
651 if (mode == MODE_ALLOWED) {
652 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700653 } else {
654 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700655 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700656 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700657 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700658
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700659 // track if unprotected read is allowed; any denied
660 // <path-permission> below removes this ability
661 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700662
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700663 final PathPermission[] pps = getPathPermissions();
664 if (pps != null) {
665 final String path = uri.getPath();
666 for (PathPermission pp : pps) {
667 final String pathPerm = pp.getReadPermission();
668 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700669 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
670 if (mode == MODE_ALLOWED) {
671 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700672 } else {
673 // any denied <path-permission> means we lose
674 // default <provider> access.
675 allowDefaultRead = false;
676 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700677 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700678 }
679 }
680 }
681 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700682
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700683 // if we passed <path-permission> checks above, and no default
684 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700685 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700687
688 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800689 final int callingUserId = UserHandle.getUserId(uid);
690 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
691 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800692 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
693 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700694 return MODE_ALLOWED;
695 }
696
697 // If the worst denial we found above was ignored, then pass that
698 // ignored through; otherwise we assume it should be a real error below.
699 if (strongestMode == MODE_IGNORED) {
700 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700701 }
702
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600703 final String suffix;
704 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
705 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
706 } else if (mExported) {
707 suffix = " requires " + missingPerm + ", or grantUriPermission()";
708 } else {
709 suffix = " requires the provider be exported, or grantUriPermission()";
710 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700711 throw new SecurityException("Permission Denial: reading "
712 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600713 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700714 }
715
716 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700717 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800718 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700719 final Context context = getContext();
720 final int pid = Binder.getCallingPid();
721 final int uid = Binder.getCallingUid();
722 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700723 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700724
725 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700726 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700727 }
728
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100729 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700730 final String componentPerm = getWritePermission();
731 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700732 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
733 if (mode == MODE_ALLOWED) {
734 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700735 } else {
736 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700737 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700738 }
739 }
740
741 // track if unprotected write is allowed; any denied
742 // <path-permission> below removes this ability
743 boolean allowDefaultWrite = (componentPerm == null);
744
745 final PathPermission[] pps = getPathPermissions();
746 if (pps != null) {
747 final String path = uri.getPath();
748 for (PathPermission pp : pps) {
749 final String pathPerm = pp.getWritePermission();
750 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700751 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
752 if (mode == MODE_ALLOWED) {
753 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700754 } else {
755 // any denied <path-permission> means we lose
756 // default <provider> access.
757 allowDefaultWrite = false;
758 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700759 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700760 }
761 }
762 }
763 }
764
765 // if we passed <path-permission> checks above, and no default
766 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700767 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700768 }
769
770 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800771 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
772 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700773 return MODE_ALLOWED;
774 }
775
776 // If the worst denial we found above was ignored, then pass that
777 // ignored through; otherwise we assume it should be a real error below.
778 if (strongestMode == MODE_IGNORED) {
779 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700780 }
781
782 final String failReason = mExported
783 ? " requires " + missingPerm + ", or grantUriPermission()"
784 : " requires the provider be exported, or grantUriPermission()";
785 throw new SecurityException("Permission Denial: writing "
786 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
787 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 }
789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700791 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800792 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 * constructor.
794 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700795 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 return mContext;
797 }
798
799 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700800 * Set the calling package, returning the current value (or {@code null})
801 * which can be used later to restore the previous state.
802 */
803 private String setCallingPackage(String callingPackage) {
804 final String original = mCallingPackage.get();
805 mCallingPackage.set(callingPackage);
806 return original;
807 }
808
809 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700810 * Return the package name of the caller that initiated the request being
811 * processed on the current thread. The returned package will have been
812 * verified to belong to the calling UID. Returns {@code null} if not
813 * currently processing a request.
814 * <p>
815 * This will always return {@code null} when processing
816 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
817 *
818 * @see Binder#getCallingUid()
819 * @see Context#grantUriPermission(String, Uri, int)
820 * @throws SecurityException if the calling package doesn't belong to the
821 * calling UID.
822 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700823 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700824 final String pkg = mCallingPackage.get();
825 if (pkg != null) {
826 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
827 }
828 return pkg;
829 }
830
831 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600832 * Opaque token representing the identity of an incoming IPC.
833 */
834 public final class CallingIdentity {
835 /** {@hide} */
836 public final long binderToken;
837 /** {@hide} */
838 public final String callingPackage;
839
840 /** {@hide} */
841 public CallingIdentity(long binderToken, String callingPackage) {
842 this.binderToken = binderToken;
843 this.callingPackage = callingPackage;
844 }
845 }
846
847 /**
848 * Reset the identity of the incoming IPC on the current thread.
849 * <p>
850 * Internally this calls {@link Binder#clearCallingIdentity()} and also
851 * clears any value stored in {@link #getCallingPackage()}.
852 *
853 * @return Returns an opaque token that can be used to restore the original
854 * calling identity by passing it to
855 * {@link #restoreCallingIdentity}.
856 */
857 public final @NonNull CallingIdentity clearCallingIdentity() {
858 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
859 }
860
861 /**
862 * Restore the identity of the incoming IPC on the current thread back to a
863 * previously identity that was returned by {@link #clearCallingIdentity}.
864 * <p>
865 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
866 * also restores any value stored in {@link #getCallingPackage()}.
867 */
868 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
869 Binder.restoreCallingIdentity(identity.binderToken);
870 mCallingPackage.set(identity.callingPackage);
871 }
872
873 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100874 * Change the authorities of the ContentProvider.
875 * This is normally set for you from its manifest information when the provider is first
876 * created.
877 * @hide
878 * @param authorities the semi-colon separated authorities of the ContentProvider.
879 */
880 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100881 if (authorities != null) {
882 if (authorities.indexOf(';') == -1) {
883 mAuthority = authorities;
884 mAuthorities = null;
885 } else {
886 mAuthority = null;
887 mAuthorities = authorities.split(";");
888 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100889 }
890 }
891
892 /** @hide */
893 protected final boolean matchesOurAuthorities(String authority) {
894 if (mAuthority != null) {
895 return mAuthority.equals(authority);
896 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100897 if (mAuthorities != null) {
898 int length = mAuthorities.length;
899 for (int i = 0; i < length; i++) {
900 if (mAuthorities[i].equals(authority)) return true;
901 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100902 }
903 return false;
904 }
905
906
907 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 * Change the permission required to read data from the content
909 * provider. This is normally set for you from its manifest information
910 * when the provider is first created.
911 *
912 * @param permission Name of the permission required for read-only access.
913 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700914 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mReadPermission = permission;
916 }
917
918 /**
919 * Return the name of the permission required for read-only access to
920 * this content provider. This method can be called from multiple
921 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800922 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
923 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700925 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 return mReadPermission;
927 }
928
929 /**
930 * Change the permission required to read and write data in the content
931 * provider. This is normally set for you from its manifest information
932 * when the provider is first created.
933 *
934 * @param permission Name of the permission required for read/write access.
935 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700936 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 mWritePermission = permission;
938 }
939
940 /**
941 * Return the name of the permission required for read/write access to
942 * this content provider. This method can be called from multiple
943 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800944 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
945 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700947 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 return mWritePermission;
949 }
950
951 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700952 * Change the path-based permission required to read and/or write data in
953 * the content provider. This is normally set for you from its manifest
954 * information when the provider is first created.
955 *
956 * @param permissions Array of path permission descriptions.
957 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700958 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700959 mPathPermissions = permissions;
960 }
961
962 /**
963 * Return the path-based permissions required for read and/or write access to
964 * this content provider. This method can be called from multiple
965 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800966 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
967 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700968 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700969 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700970 return mPathPermissions;
971 }
972
Dianne Hackborn35654b62013-01-14 17:38:02 -0800973 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100974 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800975 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800976 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800977 mTransport.mReadOp = readOp;
978 mTransport.mWriteOp = writeOp;
979 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800980 }
981
Dianne Hackborn961321f2013-02-05 17:22:41 -0800982 /** @hide */
983 public AppOpsManager getAppOpsManager() {
984 return mTransport.mAppOpsManager;
985 }
986
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700987 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700988 * Implement this to initialize your content provider on startup.
989 * This method is called for all registered content providers on the
990 * application main thread at application launch time. It must not perform
991 * lengthy operations, or application startup will be delayed.
992 *
993 * <p>You should defer nontrivial initialization (such as opening,
994 * upgrading, and scanning databases) until the content provider is used
995 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
996 * keeps application startup fast, avoids unnecessary work if the provider
997 * turns out not to be needed, and stops database errors (such as a full
998 * disk) from halting application launch.
999 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001000 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001001 * is a helpful utility class that makes it easy to manage databases,
1002 * and will automatically defer opening until first use. If you do use
1003 * SQLiteOpenHelper, make sure to avoid calling
1004 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1005 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1006 * from this method. (Instead, override
1007 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1008 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 *
1010 * @return true if the provider was successfully loaded, false otherwise
1011 */
1012 public abstract boolean onCreate();
1013
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001014 /**
1015 * {@inheritDoc}
1016 * This method is always called on the application main thread, and must
1017 * not perform lengthy operations.
1018 *
1019 * <p>The default content provider implementation does nothing.
1020 * Override this method to take appropriate action.
1021 * (Content providers do not usually care about things like screen
1022 * orientation, but may want to know about locale changes.)
1023 */
Steve McKayea93fe72016-12-02 11:35:35 -08001024 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 public void onConfigurationChanged(Configuration newConfig) {
1026 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001027
1028 /**
1029 * {@inheritDoc}
1030 * This method is always called on the application main thread, and must
1031 * not perform lengthy operations.
1032 *
1033 * <p>The default content provider implementation does nothing.
1034 * Subclasses may override this method to take appropriate action.
1035 */
Steve McKayea93fe72016-12-02 11:35:35 -08001036 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 public void onLowMemory() {
1038 }
1039
Steve McKayea93fe72016-12-02 11:35:35 -08001040 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001041 public void onTrimMemory(int level) {
1042 }
1043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001045 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001046 *
1047 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1048 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1049 * implementation of this method.
1050 *
1051 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001052 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1053 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 * <p>
1055 * Example client call:<p>
1056 * <pre>// Request a specific record.
1057 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001058 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 projection, // Which columns to return.
1060 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001061 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 People.NAME + " ASC"); // Sort order.</pre>
1063 * Example implementation:<p>
1064 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1065 // proper SQL syntax for us.
1066 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1067
1068 // Set the table we're querying.
1069 qBuilder.setTables(DATABASE_TABLE_NAME);
1070
1071 // If the query ends in a specific record number, we're
1072 // being asked for a specific record, so set the
1073 // WHERE clause in our query.
1074 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1075 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1076 }
1077
1078 // Make the query.
1079 Cursor c = qBuilder.query(mDb,
1080 projection,
1081 selection,
1082 selectionArgs,
1083 groupBy,
1084 having,
1085 sortOrder);
1086 c.setNotificationUri(getContext().getContentResolver(), uri);
1087 return c;</pre>
1088 *
1089 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001090 * if the client is requesting a specific record, the URI will end in a record number
1091 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1092 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001094 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001096 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001097 * @param selectionArgs You may include ?s in selection, which will be replaced by
1098 * the values from selectionArgs, in order that they appear in the selection.
1099 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001101 * If {@code null} then the provider is free to define the sort order.
1102 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001104 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1105 @Nullable String selection, @Nullable String[] selectionArgs,
1106 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107
Fred Quintana5bba6322009-10-05 14:21:12 -07001108 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001109 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001110 *
1111 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1112 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1113 *
1114 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001115 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1116 * and Threads</a>.
1117 * <p>
1118 * Example client call:<p>
1119 * <pre>// Request a specific record.
1120 * Cursor managedCursor = managedQuery(
1121 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1122 projection, // Which columns to return.
1123 null, // WHERE clause.
1124 null, // WHERE clause value substitution
1125 People.NAME + " ASC"); // Sort order.</pre>
1126 * Example implementation:<p>
1127 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1128 // proper SQL syntax for us.
1129 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1130
1131 // Set the table we're querying.
1132 qBuilder.setTables(DATABASE_TABLE_NAME);
1133
1134 // If the query ends in a specific record number, we're
1135 // being asked for a specific record, so set the
1136 // WHERE clause in our query.
1137 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1138 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1139 }
1140
1141 // Make the query.
1142 Cursor c = qBuilder.query(mDb,
1143 projection,
1144 selection,
1145 selectionArgs,
1146 groupBy,
1147 having,
1148 sortOrder);
1149 c.setNotificationUri(getContext().getContentResolver(), uri);
1150 return c;</pre>
1151 * <p>
1152 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001153 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1154 * signal to ensure correct operation on older versions of the Android Framework in
1155 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001156 *
1157 * @param uri The URI to query. This will be the full URI sent by the client;
1158 * if the client is requesting a specific record, the URI will end in a record number
1159 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1160 * that _id value.
1161 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001162 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001163 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001164 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001165 * @param selectionArgs You may include ?s in selection, which will be replaced by
1166 * the values from selectionArgs, in order that they appear in the selection.
1167 * The values will be bound as Strings.
1168 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001169 * If {@code null} then the provider is free to define the sort order.
1170 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001171 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001172 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001173 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001174 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001175 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1176 @Nullable String selection, @Nullable String[] selectionArgs,
1177 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001178 return query(uri, projection, selection, selectionArgs, sortOrder);
1179 }
1180
1181 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001182 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1183 * Arguments may include traditional SQL style query arguments. When present these
1184 * should be handled according to the contract established in
1185 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1186 *
1187 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001188 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1189 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1190 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001191 *
Steve McKay76b27702017-04-24 12:07:53 -07001192 * <p>This method can be called from multiple threads, as described in
1193 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1194 * and Threads</a>.
1195 *
1196 * <p>
1197 * Example client call:<p>
1198 * <pre>// Request 20 records starting at row index 30.
1199 Bundle queryArgs = new Bundle();
1200 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1201 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1202
1203 Cursor cursor = getContentResolver().query(
1204 contentUri, // Content Uri is specific to individual content providers.
1205 projection, // String[] describing which columns to return.
1206 queryArgs, // Query arguments.
1207 null); // Cancellation signal.</pre>
1208 *
1209 * Example implementation:<p>
1210 * <pre>
1211
1212 int recordsetSize = 0x1000; // Actual value is implementation specific.
1213 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1214
1215 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1216 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1217
1218 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1219
1220 // Calculate the number of items to include in the cursor.
1221 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1222
1223 // Build the paged result set....
1224 for (int i = offset; i < offset + numItems; i++) {
1225 // populate row from your data.
1226 }
1227
1228 Bundle extras = new Bundle();
1229 c.setExtras(extras);
1230
1231 // Any QUERY_ARG_* key may be included if honored.
1232 // In an actual implementation, include only keys that are both present in queryArgs
1233 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1234 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1235 // then QUERY_ARG_OFFSET should be omitted.
1236 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1237 ContentResolver.QUERY_ARG_OFFSET,
1238 ContentResolver.QUERY_ARG_LIMIT
1239 });
1240
1241 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1242
1243 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1244
1245 return cursor;</pre>
1246 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001247 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1248 * implementation details.
1249 *
1250 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001251 * @param projection The list of columns to put into the cursor.
1252 * If {@code null} provide a default set of columns.
1253 * @param queryArgs A Bundle containing all additional information necessary for the query.
1254 * Values in the Bundle may include SQL style arguments.
1255 * @param cancellationSignal A signal to cancel the operation in progress,
1256 * or {@code null}.
1257 * @return a Cursor or {@code null}.
1258 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001259 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001260 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1261 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1262 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001263
Steve McKayd7ece9f2017-01-12 16:59:59 -08001264 // if client doesn't supply an SQL sort order argument, attempt to build one from
1265 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001266 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001267 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1268 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1269 }
1270
Steve McKayea93fe72016-12-02 11:35:35 -08001271 return query(
1272 uri,
1273 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001274 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1275 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1276 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001277 cancellationSignal);
1278 }
1279
1280 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001281 * Implement this to handle requests for the MIME type of the data at the
1282 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * <code>vnd.android.cursor.item</code> for a single record,
1284 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001285 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001286 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1287 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001289 * <p>Note that there are no permissions needed for an application to
1290 * access this information; if your content provider requires read and/or
1291 * write permissions, or is not exported, all applications can still call
1292 * this method regardless of their access permissions. This allows them
1293 * to retrieve the MIME type for a URI when dispatching intents.
1294 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001296 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001298 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001299 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300
1301 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001302 * Implement this to support canonicalization of URIs that refer to your
1303 * content provider. A canonical URI is one that can be transported across
1304 * devices, backup/restore, and other contexts, and still be able to refer
1305 * to the same data item. Typically this is implemented by adding query
1306 * params to the URI allowing the content provider to verify that an incoming
1307 * canonical URI references the same data as it was originally intended for and,
1308 * if it doesn't, to find that data (if it exists) in the current environment.
1309 *
1310 * <p>For example, if the content provider holds people and a normal URI in it
1311 * is created with a row index into that people database, the cananical representation
1312 * may have an additional query param at the end which specifies the name of the
1313 * person it is intended for. Later calls into the provider with that URI will look
1314 * up the row of that URI's base index and, if it doesn't match or its entry's
1315 * name doesn't match the name in the query param, perform a query on its database
1316 * to find the correct row to operate on.</p>
1317 *
1318 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1319 * URIs (including this one) must perform this verification and recovery of any
1320 * canonical URIs they receive. In addition, you must also implement
1321 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1322 *
1323 * <p>The default implementation of this method returns null, indicating that
1324 * canonical URIs are not supported.</p>
1325 *
1326 * @param url The Uri to canonicalize.
1327 *
1328 * @return Return the canonical representation of <var>url</var>, or null if
1329 * canonicalization of that Uri is not supported.
1330 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001331 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001332 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001333 return null;
1334 }
1335
1336 /**
1337 * Remove canonicalization from canonical URIs previously returned by
1338 * {@link #canonicalize}. For example, if your implementation is to add
1339 * a query param to canonicalize a URI, this method can simply trip any
1340 * query params on the URI. The default implementation always returns the
1341 * same <var>url</var> that was passed in.
1342 *
1343 * @param url The Uri to remove any canonicalization from.
1344 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001345 * @return Return the non-canonical representation of <var>url</var>, return
1346 * the <var>url</var> as-is if there is nothing to do, or return null if
1347 * the data identified by the canonical representation can not be found in
1348 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001349 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001350 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001351 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001352 return url;
1353 }
1354
1355 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001356 * Implement this to support refresh of content identified by {@code uri}. By default, this
1357 * method returns false; providers who wish to implement this should return true to signal the
1358 * client that the provider has tried refreshing with its own implementation.
1359 * <p>
1360 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1361 * <p>
1362 * Client code should only invoke this method when there is a strong indication (such as a user
1363 * initiated pull to refresh gesture) that the content is stale.
1364 * <p>
1365 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1366 * notifications when content changes.
1367 *
1368 * @param uri The Uri identifying the data to refresh.
1369 * @param args Additional options from the client. The definitions of these are specific to the
1370 * content provider being called.
1371 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1372 * none. For example, if you called refresh on a particular uri, you should call
1373 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1374 * canceled the refresh request.
1375 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001376 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001377 @Override
Ben Lin1cf454f2016-11-10 13:50:54 -08001378 public boolean refresh(Uri uri, @Nullable Bundle args,
1379 @Nullable CancellationSignal cancellationSignal) {
1380 return false;
1381 }
1382
1383 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001384 * @hide
1385 * Implementation when a caller has performed an insert on the content
1386 * provider, but that call has been rejected for the operation given
1387 * to {@link #setAppOps(int, int)}. The default implementation simply
1388 * returns a dummy URI that is the base URI with a 0 path element
1389 * appended.
1390 */
1391 public Uri rejectInsert(Uri uri, ContentValues values) {
1392 // If not allowed, we need to return some reasonable URI. Maybe the
1393 // content provider should be responsible for this, but for now we
1394 // will just return the base URI with a dummy '0' tagged on to it.
1395 // You shouldn't be able to read if you can't write, anyway, so it
1396 // shouldn't matter much what is returned.
1397 return uri.buildUpon().appendPath("0").build();
1398 }
1399
1400 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001401 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1403 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001404 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001405 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1406 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001407 * @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 -08001408 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001409 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 * @return The URI for the newly inserted item.
1411 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001412 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001413 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414
1415 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001416 * Override this to handle requests to insert a set of new rows, or the
1417 * default implementation will iterate over the values and call
1418 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1420 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001421 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001422 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1423 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 *
1425 * @param uri The content:// URI of the insertion request.
1426 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001427 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 * @return The number of values that were inserted.
1429 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001430 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001431 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 int numValues = values.length;
1433 for (int i = 0; i < numValues; i++) {
1434 insert(uri, values[i]);
1435 }
1436 return numValues;
1437 }
1438
1439 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001440 * Implement this to handle requests to delete one or more rows.
1441 * The implementation should apply the selection clause when performing
1442 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001443 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001445 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001446 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1447 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 *
1449 * <p>The implementation is responsible for parsing out a row ID at the end
1450 * of the URI, if a specific row is being deleted. That is, the client would
1451 * pass in <code>content://contacts/people/22</code> and the implementation is
1452 * responsible for parsing the record number (22) when creating a SQL statement.
1453 *
1454 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1455 * @param selection An optional restriction to apply to rows when deleting.
1456 * @return The number of rows affected.
1457 * @throws SQLException
1458 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001459 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001460 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1461 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462
1463 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001464 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001465 * The implementation should update all rows matching the selection
1466 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1468 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001469 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001470 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1471 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 *
1473 * @param uri The URI to query. This can potentially have a record ID if this
1474 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001475 * @param values A set of column_name/value pairs to update in the database.
1476 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 * @param selection An optional filter to match rows to update.
1478 * @return the number of rows affected.
1479 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001480 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001481 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001482 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483
1484 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001485 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001486 * The default implementation always throws {@link FileNotFoundException}.
1487 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001488 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1489 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001490 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001491 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1492 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001493 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 *
1495 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1496 * their responsibility to close it when done. That is, the implementation
1497 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001498 * <p>
1499 * If opened with the exclusive "r" or "w" modes, the returned
1500 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1501 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1502 * supports seeking.
1503 * <p>
1504 * If you need to detect when the returned ParcelFileDescriptor has been
1505 * closed, or if the remote process has crashed or encountered some other
1506 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1507 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1508 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1509 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001510 * <p>
1511 * If you need to return a large file that isn't backed by a real file on
1512 * disk, such as a file on a network share or cloud storage service,
1513 * consider using
1514 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1515 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001517 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1518 * to return the appropriate MIME type for the data returned here with
1519 * the same URI. This will allow intent resolution to automatically determine the data MIME
1520 * type and select the appropriate matching targets as part of its operation.</p>
1521 *
1522 * <p class="note">For better interoperability with other applications, it is recommended
1523 * that for any URIs that can be opened, you also support queries on them
1524 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1525 * You may also want to support other common columns if you have additional meta-data
1526 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1527 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1528 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 * @param uri The URI whose file is to be opened.
1530 * @param mode Access mode for the file. May be "r" for read-only access,
1531 * "rw" for read and write access, or "rwt" for read and write access
1532 * that truncates any existing file.
1533 *
1534 * @return Returns a new ParcelFileDescriptor which you can use to access
1535 * the file.
1536 *
1537 * @throws FileNotFoundException Throws FileNotFoundException if there is
1538 * no file associated with the given URI or the mode is invalid.
1539 * @throws SecurityException Throws SecurityException if the caller does
1540 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001541 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 * @see #openAssetFile(Uri, String)
1543 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001544 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001545 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001546 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001547 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 throws FileNotFoundException {
1549 throw new FileNotFoundException("No files supported by provider at "
1550 + uri);
1551 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001554 * Override this to handle requests to open a file blob.
1555 * The default implementation always throws {@link FileNotFoundException}.
1556 * This method can be called from multiple threads, as described in
1557 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1558 * and Threads</a>.
1559 *
1560 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1561 * to the caller. This way large data (such as images and documents) can be
1562 * returned without copying the content.
1563 *
1564 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1565 * their responsibility to close it when done. That is, the implementation
1566 * of this method should create a new ParcelFileDescriptor for each call.
1567 * <p>
1568 * If opened with the exclusive "r" or "w" modes, the returned
1569 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1570 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1571 * supports seeking.
1572 * <p>
1573 * If you need to detect when the returned ParcelFileDescriptor has been
1574 * closed, or if the remote process has crashed or encountered some other
1575 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1576 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1577 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1578 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1579 *
1580 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1581 * to return the appropriate MIME type for the data returned here with
1582 * the same URI. This will allow intent resolution to automatically determine the data MIME
1583 * type and select the appropriate matching targets as part of its operation.</p>
1584 *
1585 * <p class="note">For better interoperability with other applications, it is recommended
1586 * that for any URIs that can be opened, you also support queries on them
1587 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1588 * You may also want to support other common columns if you have additional meta-data
1589 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1590 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1591 *
1592 * @param uri The URI whose file is to be opened.
1593 * @param mode Access mode for the file. May be "r" for read-only access,
1594 * "w" for write-only access, "rw" for read and write access, or
1595 * "rwt" for read and write access that truncates any existing
1596 * file.
1597 * @param signal A signal to cancel the operation in progress, or
1598 * {@code null} if none. For example, if you are downloading a
1599 * file from the network to service a "rw" mode request, you
1600 * should periodically call
1601 * {@link CancellationSignal#throwIfCanceled()} to check whether
1602 * the client has canceled the request and abort the download.
1603 *
1604 * @return Returns a new ParcelFileDescriptor which you can use to access
1605 * the file.
1606 *
1607 * @throws FileNotFoundException Throws FileNotFoundException if there is
1608 * no file associated with the given URI or the mode is invalid.
1609 * @throws SecurityException Throws SecurityException if the caller does
1610 * not have permission to access the file.
1611 *
1612 * @see #openAssetFile(Uri, String)
1613 * @see #openFileHelper(Uri, String)
1614 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001615 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001616 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001617 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001618 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1619 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001620 return openFile(uri, mode);
1621 }
1622
1623 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 * This is like {@link #openFile}, but can be implemented by providers
1625 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001626 * inside of their .apk.
1627 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001628 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1629 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001630 *
1631 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001632 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001633 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1635 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1636 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001637 * <p>
1638 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1639 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001640 *
1641 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 * should create the AssetFileDescriptor with
1643 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001644 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001646 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1647 * to return the appropriate MIME type for the data returned here with
1648 * the same URI. This will allow intent resolution to automatically determine the data MIME
1649 * type and select the appropriate matching targets as part of its operation.</p>
1650 *
1651 * <p class="note">For better interoperability with other applications, it is recommended
1652 * that for any URIs that can be opened, you also support queries on them
1653 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1654 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 * @param uri The URI whose file is to be opened.
1656 * @param mode Access mode for the file. May be "r" for read-only access,
1657 * "w" for write-only access (erasing whatever data is currently in
1658 * the file), "wa" for write-only access to append to any existing data,
1659 * "rw" for read and write access on any existing data, and "rwt" for read
1660 * and write access that truncates any existing file.
1661 *
1662 * @return Returns a new AssetFileDescriptor which you can use to access
1663 * the file.
1664 *
1665 * @throws FileNotFoundException Throws FileNotFoundException if there is
1666 * no file associated with the given URI or the mode is invalid.
1667 * @throws SecurityException Throws SecurityException if the caller does
1668 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001669 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 * @see #openFile(Uri, String)
1671 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001672 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001674 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 throws FileNotFoundException {
1676 ParcelFileDescriptor fd = openFile(uri, mode);
1677 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1678 }
1679
1680 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001681 * This is like {@link #openFile}, but can be implemented by providers
1682 * that need to be able to return sub-sections of files, often assets
1683 * inside of their .apk.
1684 * This method can be called from multiple threads, as described in
1685 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1686 * and Threads</a>.
1687 *
1688 * <p>If you implement this, your clients must be able to deal with such
1689 * file slices, either directly with
1690 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1691 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1692 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1693 * methods.
1694 * <p>
1695 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1696 * streaming of data.
1697 *
1698 * <p class="note">If you are implementing this to return a full file, you
1699 * should create the AssetFileDescriptor with
1700 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1701 * applications that cannot handle sub-sections of files.</p>
1702 *
1703 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1704 * to return the appropriate MIME type for the data returned here with
1705 * the same URI. This will allow intent resolution to automatically determine the data MIME
1706 * type and select the appropriate matching targets as part of its operation.</p>
1707 *
1708 * <p class="note">For better interoperability with other applications, it is recommended
1709 * that for any URIs that can be opened, you also support queries on them
1710 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1711 *
1712 * @param uri The URI whose file is to be opened.
1713 * @param mode Access mode for the file. May be "r" for read-only access,
1714 * "w" for write-only access (erasing whatever data is currently in
1715 * the file), "wa" for write-only access to append to any existing data,
1716 * "rw" for read and write access on any existing data, and "rwt" for read
1717 * and write access that truncates any existing file.
1718 * @param signal A signal to cancel the operation in progress, or
1719 * {@code null} if none. For example, if you are downloading a
1720 * file from the network to service a "rw" mode request, you
1721 * should periodically call
1722 * {@link CancellationSignal#throwIfCanceled()} to check whether
1723 * the client has canceled the request and abort the download.
1724 *
1725 * @return Returns a new AssetFileDescriptor which you can use to access
1726 * the file.
1727 *
1728 * @throws FileNotFoundException Throws FileNotFoundException if there is
1729 * no file associated with the given URI or the mode is invalid.
1730 * @throws SecurityException Throws SecurityException if the caller does
1731 * not have permission to access the file.
1732 *
1733 * @see #openFile(Uri, String)
1734 * @see #openFileHelper(Uri, String)
1735 * @see #getType(android.net.Uri)
1736 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001737 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001738 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1739 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001740 return openAssetFile(uri, mode);
1741 }
1742
1743 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 * Convenience for subclasses that wish to implement {@link #openFile}
1745 * by looking up a column named "_data" at the given URI.
1746 *
1747 * @param uri The URI to be opened.
1748 * @param mode The file mode. May be "r" for read-only access,
1749 * "w" for write-only access (erasing whatever data is currently in
1750 * the file), "wa" for write-only access to append to any existing data,
1751 * "rw" for read and write access on any existing data, and "rwt" for read
1752 * and write access that truncates any existing file.
1753 *
1754 * @return Returns a new ParcelFileDescriptor that can be used by the
1755 * client to access the file.
1756 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001757 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1758 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1760 int count = (c != null) ? c.getCount() : 0;
1761 if (count != 1) {
1762 // If there is not exactly one result, throw an appropriate
1763 // exception.
1764 if (c != null) {
1765 c.close();
1766 }
1767 if (count == 0) {
1768 throw new FileNotFoundException("No entry for " + uri);
1769 }
1770 throw new FileNotFoundException("Multiple items at " + uri);
1771 }
1772
1773 c.moveToFirst();
1774 int i = c.getColumnIndex("_data");
1775 String path = (i >= 0 ? c.getString(i) : null);
1776 c.close();
1777 if (path == null) {
1778 throw new FileNotFoundException("Column _data not found.");
1779 }
1780
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001781 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 return ParcelFileDescriptor.open(new File(path), modeBits);
1783 }
1784
1785 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001786 * Called by a client to determine the types of data streams that this
1787 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001788 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001789 * of a particular type, return that MIME type if it matches the given
1790 * mimeTypeFilter. If it can perform type conversions, return an array
1791 * of all supported MIME types that match mimeTypeFilter.
1792 *
1793 * @param uri The data in the content provider being queried.
1794 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001795 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001796 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001797 * given mimeTypeFilter. Otherwise returns an array of all available
1798 * concrete MIME types.
1799 *
1800 * @see #getType(Uri)
1801 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001802 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001803 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001804 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001805 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001806 return null;
1807 }
1808
1809 /**
1810 * Called by a client to open a read-only stream containing data of a
1811 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1812 * except the file can only be read-only and the content provider may
1813 * perform data conversions to generate data of the desired type.
1814 *
1815 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001816 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001817 * {@link #openAssetFile(Uri, String)}.
1818 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001819 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001820 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001821 * <p>
1822 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1823 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001824 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001825 * <p class="note">For better interoperability with other applications, it is recommended
1826 * that for any URIs that can be opened, you also support queries on them
1827 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1828 * You may also want to support other common columns if you have additional meta-data
1829 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1830 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1831 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001832 * @param uri The data in the content provider being queried.
1833 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001834 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001835 * requirements; in this case the content provider will pick its best
1836 * type matching the pattern.
1837 * @param opts Additional options from the client. The definitions of
1838 * these are specific to the content provider being called.
1839 *
1840 * @return Returns a new AssetFileDescriptor from which the client can
1841 * read data of the desired type.
1842 *
1843 * @throws FileNotFoundException Throws FileNotFoundException if there is
1844 * no file associated with the given URI or the mode is invalid.
1845 * @throws SecurityException Throws SecurityException if the caller does
1846 * not have permission to access the data.
1847 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1848 * content provider does not support the requested MIME type.
1849 *
1850 * @see #getStreamTypes(Uri, String)
1851 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001852 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001853 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001854 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1855 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001856 if ("*/*".equals(mimeTypeFilter)) {
1857 // If they can take anything, the untyped open call is good enough.
1858 return openAssetFile(uri, "r");
1859 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001860 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001861 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001862 // Use old untyped open call if this provider has a type for this
1863 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001864 return openAssetFile(uri, "r");
1865 }
1866 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1867 }
1868
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001869
1870 /**
1871 * Called by a client to open a read-only stream containing data of a
1872 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1873 * except the file can only be read-only and the content provider may
1874 * perform data conversions to generate data of the desired type.
1875 *
1876 * <p>The default implementation compares the given mimeType against the
1877 * result of {@link #getType(Uri)} and, if they match, simply calls
1878 * {@link #openAssetFile(Uri, String)}.
1879 *
1880 * <p>See {@link ClipData} for examples of the use and implementation
1881 * of this method.
1882 * <p>
1883 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1884 * streaming of data.
1885 *
1886 * <p class="note">For better interoperability with other applications, it is recommended
1887 * that for any URIs that can be opened, you also support queries on them
1888 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1889 * You may also want to support other common columns if you have additional meta-data
1890 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1891 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1892 *
1893 * @param uri The data in the content provider being queried.
1894 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001895 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001896 * requirements; in this case the content provider will pick its best
1897 * type matching the pattern.
1898 * @param opts Additional options from the client. The definitions of
1899 * these are specific to the content provider being called.
1900 * @param signal A signal to cancel the operation in progress, or
1901 * {@code null} if none. For example, if you are downloading a
1902 * file from the network to service a "rw" mode request, you
1903 * should periodically call
1904 * {@link CancellationSignal#throwIfCanceled()} to check whether
1905 * the client has canceled the request and abort the download.
1906 *
1907 * @return Returns a new AssetFileDescriptor from which the client can
1908 * read data of the desired type.
1909 *
1910 * @throws FileNotFoundException Throws FileNotFoundException if there is
1911 * no file associated with the given URI or the mode is invalid.
1912 * @throws SecurityException Throws SecurityException if the caller does
1913 * not have permission to access the data.
1914 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1915 * content provider does not support the requested MIME type.
1916 *
1917 * @see #getStreamTypes(Uri, String)
1918 * @see #openAssetFile(Uri, String)
1919 * @see ClipDescription#compareMimeTypes(String, String)
1920 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001921 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001922 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1923 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1924 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001925 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1926 }
1927
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001928 /**
1929 * Interface to write a stream of data to a pipe. Use with
1930 * {@link ContentProvider#openPipeHelper}.
1931 */
1932 public interface PipeDataWriter<T> {
1933 /**
1934 * Called from a background thread to stream data out to a pipe.
1935 * Note that the pipe is blocking, so this thread can block on
1936 * writes for an arbitrary amount of time if the client is slow
1937 * at reading.
1938 *
1939 * @param output The pipe where data should be written. This will be
1940 * closed for you upon returning from this function.
1941 * @param uri The URI whose data is to be written.
1942 * @param mimeType The desired type of data to be written.
1943 * @param opts Options supplied by caller.
1944 * @param args Your own custom arguments.
1945 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001946 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1947 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001948 }
1949
1950 /**
1951 * A helper function for implementing {@link #openTypedAssetFile}, for
1952 * creating a data pipe and background thread allowing you to stream
1953 * generated data back to the client. This function returns a new
1954 * ParcelFileDescriptor that should be returned to the caller (the caller
1955 * is responsible for closing it).
1956 *
1957 * @param uri The URI whose data is to be written.
1958 * @param mimeType The desired type of data to be written.
1959 * @param opts Options supplied by caller.
1960 * @param args Your own custom arguments.
1961 * @param func Interface implementing the function that will actually
1962 * stream the data.
1963 * @return Returns a new ParcelFileDescriptor holding the read side of
1964 * the pipe. This should be returned to the caller for reading; the caller
1965 * is responsible for closing it when done.
1966 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001967 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1968 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1969 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001970 try {
1971 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1972
1973 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1974 @Override
1975 protected Object doInBackground(Object... params) {
1976 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1977 try {
1978 fds[1].close();
1979 } catch (IOException e) {
1980 Log.w(TAG, "Failure closing pipe", e);
1981 }
1982 return null;
1983 }
1984 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001985 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001986
1987 return fds[0];
1988 } catch (IOException e) {
1989 throw new FileNotFoundException("failure making pipe");
1990 }
1991 }
1992
1993 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 * Returns true if this instance is a temporary content provider.
1995 * @return true if this instance is a temporary content provider
1996 */
1997 protected boolean isTemporary() {
1998 return false;
1999 }
2000
2001 /**
2002 * Returns the Binder object for this provider.
2003 *
2004 * @return the Binder object for this provider
2005 * @hide
2006 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002007 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 public IContentProvider getIContentProvider() {
2009 return mTransport;
2010 }
2011
2012 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002013 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2014 * when directly instantiating the provider for testing.
2015 * @hide
2016 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002017 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002018 public void attachInfoForTesting(Context context, ProviderInfo info) {
2019 attachInfo(context, info, true);
2020 }
2021
2022 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 * After being instantiated, this is called to tell the content provider
2024 * about itself.
2025 *
2026 * @param context The context this provider is running in
2027 * @param info Registered information about this content provider
2028 */
2029 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002030 attachInfo(context, info, false);
2031 }
2032
2033 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002034 mNoPerms = testing;
2035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 /*
2037 * Only allow it to be set once, so after the content service gives
2038 * this to us clients can't change it.
2039 */
2040 if (mContext == null) {
2041 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002042 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002043 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2044 Context.APP_OPS_SERVICE);
2045 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002046 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 if (info != null) {
2048 setReadPermission(info.readPermission);
2049 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002050 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002051 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002052 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002053 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 }
2055 ContentProvider.this.onCreate();
2056 }
2057 }
Fred Quintanace31b232009-05-04 16:01:15 -07002058
2059 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002060 * Override this to handle requests to perform a batch of operations, or the
2061 * default implementation will iterate over the operations and call
2062 * {@link ContentProviderOperation#apply} on each of them.
2063 * If all calls to {@link ContentProviderOperation#apply} succeed
2064 * then a {@link ContentProviderResult} array with as many
2065 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002066 * fail, it is up to the implementation how many of the others take effect.
2067 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002068 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2069 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002070 *
Fred Quintanace31b232009-05-04 16:01:15 -07002071 * @param operations the operations to apply
2072 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002073 * @throws OperationApplicationException thrown if any operation fails.
2074 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002075 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002076 @Override
2077 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2078 @NonNull ArrayList<ContentProviderOperation> operations)
2079 throws OperationApplicationException {
2080 return applyBatch(operations);
2081 }
2082
Jeff Sharkey673db442015-06-11 19:30:57 -07002083 public @NonNull ContentProviderResult[] applyBatch(
2084 @NonNull ArrayList<ContentProviderOperation> operations)
2085 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002086 final int numOperations = operations.size();
2087 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2088 for (int i = 0; i < numOperations; i++) {
2089 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002090 }
2091 return results;
2092 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002093
2094 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002095 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002096 * interfaces that are cheaper and/or unnatural for a table-like
2097 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002098 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002099 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2100 * on this entry into the content provider besides the basic ability for the application
2101 * to get access to the provider at all. For example, it has no idea whether the call
2102 * being executed may read or write data in the provider, so can't enforce those
2103 * individual permissions. Any implementation of this method <strong>must</strong>
2104 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2105 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002106 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2107 * @param arg provider-defined String argument. May be {@code null}.
2108 * @param extras provider-defined Bundle argument. May be {@code null}.
2109 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002110 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002111 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002112 @Override
2113 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2114 @Nullable String arg, @Nullable Bundle extras) {
2115 return call(method, arg, extras);
2116 }
2117
Jeff Sharkey673db442015-06-11 19:30:57 -07002118 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2119 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002120 return null;
2121 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002122
2123 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002124 * Implement this to shut down the ContentProvider instance. You can then
2125 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002126 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002127 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002128 * Android normally handles ContentProvider startup and shutdown
2129 * automatically. You do not need to start up or shut down a
2130 * ContentProvider. When you invoke a test method on a ContentProvider,
2131 * however, a ContentProvider instance is started and keeps running after
2132 * the test finishes, even if a succeeding test instantiates another
2133 * ContentProvider. A conflict develops because the two instances are
2134 * usually running against the same underlying data source (for example, an
2135 * sqlite database).
2136 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002137 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002138 * Implementing shutDown() avoids this conflict by providing a way to
2139 * terminate the ContentProvider. This method can also prevent memory leaks
2140 * from multiple instantiations of the ContentProvider, and it can ensure
2141 * unit test isolation by allowing you to completely clean up the test
2142 * fixture before moving on to the next test.
2143 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002144 */
2145 public void shutdown() {
2146 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2147 "connections are gracefully shutdown");
2148 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002149
2150 /**
2151 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002152 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002153 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002154 * @param fd The raw file descriptor that the dump is being sent to.
2155 * @param writer The PrintWriter to which you should dump your state. This will be
2156 * closed for you after you return.
2157 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002158 */
2159 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2160 writer.println("nothing to dump");
2161 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002162
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002163 private void validateIncomingAuthority(String authority) throws SecurityException {
2164 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2165 String message = "The authority " + authority + " does not match the one of the "
2166 + "contentProvider: ";
2167 if (mAuthority != null) {
2168 message += mAuthority;
2169 } else {
2170 message += Arrays.toString(mAuthorities);
2171 }
2172 throw new SecurityException(message);
2173 }
2174 }
2175
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002176 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002177 @VisibleForTesting
2178 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002179 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002180 if (!mSingleUser) {
2181 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2182 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2183 throw new SecurityException("trying to query a ContentProvider in user "
2184 + mContext.getUserId() + " with a uri belonging to user " + userId);
2185 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002186 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002187 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002188
2189 // Normalize the path by removing any empty path segments, which can be
2190 // a source of security issues.
2191 final String encodedPath = uri.getEncodedPath();
2192 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002193 final Uri normalized = uri.buildUpon()
2194 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2195 Log.w(TAG, "Normalized " + uri + " to " + normalized
2196 + " to avoid possible security issues");
2197 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002198 } else {
2199 return uri;
2200 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002201 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002202
2203 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002204 private Uri maybeGetUriWithoutUserId(Uri uri) {
2205 if (mSingleUser) {
2206 return uri;
2207 }
2208 return getUriWithoutUserId(uri);
2209 }
2210
2211 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002212 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2213 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002214 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002215 if (end == -1) return defaultUserId;
2216 String userIdString = auth.substring(0, end);
2217 try {
2218 return Integer.parseInt(userIdString);
2219 } catch (NumberFormatException e) {
2220 Log.w(TAG, "Error parsing userId.", e);
2221 return UserHandle.USER_NULL;
2222 }
2223 }
2224
2225 /** @hide */
2226 public static int getUserIdFromAuthority(String auth) {
2227 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2228 }
2229
2230 /** @hide */
2231 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2232 if (uri == null) return defaultUserId;
2233 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2234 }
2235
2236 /** @hide */
2237 public static int getUserIdFromUri(Uri uri) {
2238 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2239 }
2240
2241 /**
2242 * Removes userId part from authority string. Expects format:
2243 * userId@some.authority
2244 * If there is no userId in the authority, it symply returns the argument
2245 * @hide
2246 */
2247 public static String getAuthorityWithoutUserId(String auth) {
2248 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002249 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002250 return auth.substring(end+1);
2251 }
2252
2253 /** @hide */
2254 public static Uri getUriWithoutUserId(Uri uri) {
2255 if (uri == null) return null;
2256 Uri.Builder builder = uri.buildUpon();
2257 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2258 return builder.build();
2259 }
2260
2261 /** @hide */
2262 public static boolean uriHasUserId(Uri uri) {
2263 if (uri == null) return false;
2264 return !TextUtils.isEmpty(uri.getUserInfo());
2265 }
2266
2267 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002268 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002269 public static Uri maybeAddUserId(Uri uri, int userId) {
2270 if (uri == null) return null;
2271 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002272 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002273 if (!uriHasUserId(uri)) {
2274 //We don't add the user Id if there's already one
2275 Uri.Builder builder = uri.buildUpon();
2276 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2277 return builder.build();
2278 }
2279 }
2280 return uri;
2281 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002282}