blob: 4e1a898c16a33fa1d0363a4a3d5c7b50333cc82a [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 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700108public abstract class ContentProvider implements 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
Dianne Hackborn35654b62013-01-14 17:38:02 -0800327 public ContentProviderResult[] applyBatch(String callingPkg,
328 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 {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100359 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800360 if (results != null) {
361 for (int i = 0; i < results.length ; i++) {
362 if (userIds[i] != UserHandle.USER_CURRENT) {
363 // Adding the userId to the uri.
364 results[i] = new ContentProviderResult(results[i], userIds[i]);
365 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100366 }
367 }
368 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700369 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700370 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600371 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700372 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700373 }
374
Jeff Brown75ea64f2012-01-25 19:37:13 -0800375 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800376 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600377 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100378 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800379 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800380 return 0;
381 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600382 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700383 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700384 try {
385 return ContentProvider.this.delete(uri, selection, selectionArgs);
386 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700387 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600388 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 }
391
Jeff Brown75ea64f2012-01-25 19:37:13 -0800392 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800393 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600395 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100396 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800397 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800398 return 0;
399 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600400 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700401 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700402 try {
403 return ContentProvider.this.update(uri, values, selection, selectionArgs);
404 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700405 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600406 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 }
409
Jeff Brown75ea64f2012-01-25 19:37:13 -0800410 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700411 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800412 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
413 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600414 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100415 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800416 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600417 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700418 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700419 try {
420 return ContentProvider.this.openFile(
421 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
422 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600424 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 }
427
Jeff Brown75ea64f2012-01-25 19:37:13 -0800428 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700429 public AssetFileDescriptor openAssetFile(
430 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600432 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100433 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800434 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600435 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700436 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700437 try {
438 return ContentProvider.this.openAssetFile(
439 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
440 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700441 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600442 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 }
445
Jeff Brown75ea64f2012-01-25 19:37:13 -0800446 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800447 public Bundle call(
448 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600449 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600450 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700451 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700452 try {
453 return ContentProvider.this.call(method, arg, extras);
454 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700455 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600456 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700457 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800458 }
459
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700460 @Override
461 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700462 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600463 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100464 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600465 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
466 try {
467 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
468 } finally {
469 Trace.traceEnd(TRACE_TAG_DATABASE);
470 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700471 }
472
473 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800474 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700475 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600476 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600477 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100478 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800479 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600480 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700481 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700482 try {
483 return ContentProvider.this.openTypedAssetFile(
484 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
485 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700486 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600487 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700488 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700489 }
490
Jeff Brown75ea64f2012-01-25 19:37:13 -0800491 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700492 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800493 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800494 }
495
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700496 @Override
497 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600498 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100499 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100500 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800501 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700502 return null;
503 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600504 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700505 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700506 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100507 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700508 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700509 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600510 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700511 }
512 }
513
514 @Override
515 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600516 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100517 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100518 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800519 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700520 return null;
521 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600522 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700523 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700524 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100525 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700526 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700527 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600528 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700529 }
530 }
531
Ben Lin1cf454f2016-11-10 13:50:54 -0800532 @Override
533 public boolean refresh(String callingPkg, Uri uri, Bundle args,
534 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600535 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800536 uri = getUriWithoutUserId(uri);
537 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
538 return false;
539 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600540 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800541 final String original = setCallingPackage(callingPkg);
542 try {
543 return ContentProvider.this.refresh(uri, args,
544 CancellationSignal.fromTransport(cancellationSignal));
545 } finally {
546 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600547 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800548 }
549 }
550
Dianne Hackbornff170242014-11-19 10:59:01 -0800551 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
552 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800553 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800554 if (enforceWritePermission(callingPkg, uri, callerToken)
555 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800556 throw new FileNotFoundException("App op not allowed");
557 }
558 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800559 if (enforceReadPermission(callingPkg, uri, callerToken)
560 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800561 throw new FileNotFoundException("App op not allowed");
562 }
563 }
564 }
565
Dianne Hackbornff170242014-11-19 10:59:01 -0800566 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
567 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700568 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
569 if (mode != MODE_ALLOWED) {
570 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800571 }
Svet Ganov99b60432015-06-27 13:15:22 -0700572
Eugene Susla93519852018-06-13 16:44:31 -0700573 return noteProxyOp(callingPkg, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800574 }
575
Dianne Hackbornff170242014-11-19 10:59:01 -0800576 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
577 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700578 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
579 if (mode != MODE_ALLOWED) {
580 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800581 }
Svet Ganov99b60432015-06-27 13:15:22 -0700582
Eugene Susla93519852018-06-13 16:44:31 -0700583 return noteProxyOp(callingPkg, mWriteOp);
584 }
585
586 private int noteProxyOp(String callingPkg, int op) {
587 if (op != AppOpsManager.OP_NONE) {
588 int mode = mAppOpsManager.noteProxyOp(op, callingPkg);
589 return mode == MODE_DEFAULT ? interpretDefaultAppOpMode(op) : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700590 }
591
Dianne Hackborn35654b62013-01-14 17:38:02 -0800592 return AppOpsManager.MODE_ALLOWED;
593 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700594 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800595
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100596 boolean checkUser(int pid, int uid, Context context) {
597 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700598 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100599 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
600 == PERMISSION_GRANTED;
601 }
602
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700603 /**
604 * Verify that calling app holds both the given permission and any app-op
605 * associated with that permission.
606 */
607 private int checkPermissionAndAppOp(String permission, String callingPkg,
608 IBinder callerToken) {
609 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
610 callerToken) != PERMISSION_GRANTED) {
611 return MODE_ERRORED;
612 }
613
Eugene Susla93519852018-06-13 16:44:31 -0700614 return mTransport.noteProxyOp(callingPkg, AppOpsManager.permissionToOpCode(permission));
615 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700616
Eugene Susla93519852018-06-13 16:44:31 -0700617 /**
618 * Allows for custom interpretations of {@link AppOpsManager#MODE_DEFAULT} by individual
619 * content providers
620 *
621 * @hide
622 */
623 protected int interpretDefaultAppOpMode(int op) {
624 return MODE_IGNORED;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700625 }
626
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700627 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700628 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800629 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700630 final Context context = getContext();
631 final int pid = Binder.getCallingPid();
632 final int uid = Binder.getCallingUid();
633 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700634 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700635
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700636 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700637 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700638 }
639
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100640 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700641 final String componentPerm = getReadPermission();
642 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700643 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
644 if (mode == MODE_ALLOWED) {
645 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700646 } else {
647 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700648 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700649 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700650 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700651
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700652 // track if unprotected read is allowed; any denied
653 // <path-permission> below removes this ability
654 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700655
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700656 final PathPermission[] pps = getPathPermissions();
657 if (pps != null) {
658 final String path = uri.getPath();
659 for (PathPermission pp : pps) {
660 final String pathPerm = pp.getReadPermission();
661 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700662 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
663 if (mode == MODE_ALLOWED) {
664 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700665 } else {
666 // any denied <path-permission> means we lose
667 // default <provider> access.
668 allowDefaultRead = false;
669 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700670 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700671 }
672 }
673 }
674 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700675
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700676 // if we passed <path-permission> checks above, and no default
677 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700678 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700680
681 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800682 final int callingUserId = UserHandle.getUserId(uid);
683 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
684 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800685 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
686 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700687 return MODE_ALLOWED;
688 }
689
690 // If the worst denial we found above was ignored, then pass that
691 // ignored through; otherwise we assume it should be a real error below.
692 if (strongestMode == MODE_IGNORED) {
693 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700694 }
695
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600696 final String suffix;
697 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
698 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
699 } else if (mExported) {
700 suffix = " requires " + missingPerm + ", or grantUriPermission()";
701 } else {
702 suffix = " requires the provider be exported, or grantUriPermission()";
703 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700704 throw new SecurityException("Permission Denial: reading "
705 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600706 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700707 }
708
709 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700710 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800711 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700712 final Context context = getContext();
713 final int pid = Binder.getCallingPid();
714 final int uid = Binder.getCallingUid();
715 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700716 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700717
718 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700719 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700720 }
721
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100722 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700723 final String componentPerm = getWritePermission();
724 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700725 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
726 if (mode == MODE_ALLOWED) {
727 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700728 } else {
729 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700730 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700731 }
732 }
733
734 // track if unprotected write is allowed; any denied
735 // <path-permission> below removes this ability
736 boolean allowDefaultWrite = (componentPerm == null);
737
738 final PathPermission[] pps = getPathPermissions();
739 if (pps != null) {
740 final String path = uri.getPath();
741 for (PathPermission pp : pps) {
742 final String pathPerm = pp.getWritePermission();
743 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700744 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
745 if (mode == MODE_ALLOWED) {
746 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700747 } else {
748 // any denied <path-permission> means we lose
749 // default <provider> access.
750 allowDefaultWrite = false;
751 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700752 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700753 }
754 }
755 }
756 }
757
758 // if we passed <path-permission> checks above, and no default
759 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700760 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700761 }
762
763 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800764 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
765 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700766 return MODE_ALLOWED;
767 }
768
769 // If the worst denial we found above was ignored, then pass that
770 // ignored through; otherwise we assume it should be a real error below.
771 if (strongestMode == MODE_IGNORED) {
772 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700773 }
774
775 final String failReason = mExported
776 ? " requires " + missingPerm + ", or grantUriPermission()"
777 : " requires the provider be exported, or grantUriPermission()";
778 throw new SecurityException("Permission Denial: writing "
779 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
780 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700784 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800785 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 * constructor.
787 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700788 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 return mContext;
790 }
791
792 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700793 * Set the calling package, returning the current value (or {@code null})
794 * which can be used later to restore the previous state.
795 */
796 private String setCallingPackage(String callingPackage) {
797 final String original = mCallingPackage.get();
798 mCallingPackage.set(callingPackage);
799 return original;
800 }
801
802 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700803 * Return the package name of the caller that initiated the request being
804 * processed on the current thread. The returned package will have been
805 * verified to belong to the calling UID. Returns {@code null} if not
806 * currently processing a request.
807 * <p>
808 * This will always return {@code null} when processing
809 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
810 *
811 * @see Binder#getCallingUid()
812 * @see Context#grantUriPermission(String, Uri, int)
813 * @throws SecurityException if the calling package doesn't belong to the
814 * calling UID.
815 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700816 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700817 final String pkg = mCallingPackage.get();
818 if (pkg != null) {
819 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
820 }
821 return pkg;
822 }
823
824 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100825 * Change the authorities of the ContentProvider.
826 * This is normally set for you from its manifest information when the provider is first
827 * created.
828 * @hide
829 * @param authorities the semi-colon separated authorities of the ContentProvider.
830 */
831 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100832 if (authorities != null) {
833 if (authorities.indexOf(';') == -1) {
834 mAuthority = authorities;
835 mAuthorities = null;
836 } else {
837 mAuthority = null;
838 mAuthorities = authorities.split(";");
839 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100840 }
841 }
842
843 /** @hide */
844 protected final boolean matchesOurAuthorities(String authority) {
845 if (mAuthority != null) {
846 return mAuthority.equals(authority);
847 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100848 if (mAuthorities != null) {
849 int length = mAuthorities.length;
850 for (int i = 0; i < length; i++) {
851 if (mAuthorities[i].equals(authority)) return true;
852 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100853 }
854 return false;
855 }
856
857
858 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 * Change the permission required to read data from the content
860 * provider. This is normally set for you from its manifest information
861 * when the provider is first created.
862 *
863 * @param permission Name of the permission required for read-only access.
864 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700865 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 mReadPermission = permission;
867 }
868
869 /**
870 * Return the name of the permission required for read-only access to
871 * this content provider. This method can be called from multiple
872 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800873 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
874 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700876 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 return mReadPermission;
878 }
879
880 /**
881 * Change the permission required to read and write data in the content
882 * provider. This is normally set for you from its manifest information
883 * when the provider is first created.
884 *
885 * @param permission Name of the permission required for read/write access.
886 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700887 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 mWritePermission = permission;
889 }
890
891 /**
892 * Return the name of the permission required for read/write access to
893 * this content provider. This method can be called from multiple
894 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800895 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
896 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700898 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 return mWritePermission;
900 }
901
902 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700903 * Change the path-based permission required to read and/or write data in
904 * the content provider. This is normally set for you from its manifest
905 * information when the provider is first created.
906 *
907 * @param permissions Array of path permission descriptions.
908 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700909 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700910 mPathPermissions = permissions;
911 }
912
913 /**
914 * Return the path-based permissions required for read and/or write access to
915 * this content provider. This method can be called from multiple
916 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800917 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
918 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700919 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700920 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700921 return mPathPermissions;
922 }
923
Dianne Hackborn35654b62013-01-14 17:38:02 -0800924 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100925 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800926 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800927 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800928 mTransport.mReadOp = readOp;
929 mTransport.mWriteOp = writeOp;
930 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800931 }
932
Dianne Hackborn961321f2013-02-05 17:22:41 -0800933 /** @hide */
934 public AppOpsManager getAppOpsManager() {
935 return mTransport.mAppOpsManager;
936 }
937
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700938 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700939 * Implement this to initialize your content provider on startup.
940 * This method is called for all registered content providers on the
941 * application main thread at application launch time. It must not perform
942 * lengthy operations, or application startup will be delayed.
943 *
944 * <p>You should defer nontrivial initialization (such as opening,
945 * upgrading, and scanning databases) until the content provider is used
946 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
947 * keeps application startup fast, avoids unnecessary work if the provider
948 * turns out not to be needed, and stops database errors (such as a full
949 * disk) from halting application launch.
950 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700951 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700952 * is a helpful utility class that makes it easy to manage databases,
953 * and will automatically defer opening until first use. If you do use
954 * SQLiteOpenHelper, make sure to avoid calling
955 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
956 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
957 * from this method. (Instead, override
958 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
959 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 *
961 * @return true if the provider was successfully loaded, false otherwise
962 */
963 public abstract boolean onCreate();
964
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700965 /**
966 * {@inheritDoc}
967 * This method is always called on the application main thread, and must
968 * not perform lengthy operations.
969 *
970 * <p>The default content provider implementation does nothing.
971 * Override this method to take appropriate action.
972 * (Content providers do not usually care about things like screen
973 * orientation, but may want to know about locale changes.)
974 */
Steve McKayea93fe72016-12-02 11:35:35 -0800975 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 public void onConfigurationChanged(Configuration newConfig) {
977 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700978
979 /**
980 * {@inheritDoc}
981 * This method is always called on the application main thread, and must
982 * not perform lengthy operations.
983 *
984 * <p>The default content provider implementation does nothing.
985 * Subclasses may override this method to take appropriate action.
986 */
Steve McKayea93fe72016-12-02 11:35:35 -0800987 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 public void onLowMemory() {
989 }
990
Steve McKayea93fe72016-12-02 11:35:35 -0800991 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700992 public void onTrimMemory(int level) {
993 }
994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700996 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800997 *
998 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
999 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1000 * implementation of this method.
1001 *
1002 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001003 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1004 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 * <p>
1006 * Example client call:<p>
1007 * <pre>// Request a specific record.
1008 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001009 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 projection, // Which columns to return.
1011 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001012 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 People.NAME + " ASC"); // Sort order.</pre>
1014 * Example implementation:<p>
1015 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1016 // proper SQL syntax for us.
1017 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1018
1019 // Set the table we're querying.
1020 qBuilder.setTables(DATABASE_TABLE_NAME);
1021
1022 // If the query ends in a specific record number, we're
1023 // being asked for a specific record, so set the
1024 // WHERE clause in our query.
1025 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1026 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1027 }
1028
1029 // Make the query.
1030 Cursor c = qBuilder.query(mDb,
1031 projection,
1032 selection,
1033 selectionArgs,
1034 groupBy,
1035 having,
1036 sortOrder);
1037 c.setNotificationUri(getContext().getContentResolver(), uri);
1038 return c;</pre>
1039 *
1040 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001041 * if the client is requesting a specific record, the URI will end in a record number
1042 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1043 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001045 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001047 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001048 * @param selectionArgs You may include ?s in selection, which will be replaced by
1049 * the values from selectionArgs, in order that they appear in the selection.
1050 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001052 * If {@code null} then the provider is free to define the sort order.
1053 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001055 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1056 @Nullable String selection, @Nullable String[] selectionArgs,
1057 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058
Fred Quintana5bba6322009-10-05 14:21:12 -07001059 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001060 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001061 *
1062 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1063 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1064 *
1065 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001066 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1067 * and Threads</a>.
1068 * <p>
1069 * Example client call:<p>
1070 * <pre>// Request a specific record.
1071 * Cursor managedCursor = managedQuery(
1072 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1073 projection, // Which columns to return.
1074 null, // WHERE clause.
1075 null, // WHERE clause value substitution
1076 People.NAME + " ASC"); // Sort order.</pre>
1077 * Example implementation:<p>
1078 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1079 // proper SQL syntax for us.
1080 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1081
1082 // Set the table we're querying.
1083 qBuilder.setTables(DATABASE_TABLE_NAME);
1084
1085 // If the query ends in a specific record number, we're
1086 // being asked for a specific record, so set the
1087 // WHERE clause in our query.
1088 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1089 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1090 }
1091
1092 // Make the query.
1093 Cursor c = qBuilder.query(mDb,
1094 projection,
1095 selection,
1096 selectionArgs,
1097 groupBy,
1098 having,
1099 sortOrder);
1100 c.setNotificationUri(getContext().getContentResolver(), uri);
1101 return c;</pre>
1102 * <p>
1103 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001104 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1105 * signal to ensure correct operation on older versions of the Android Framework in
1106 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001107 *
1108 * @param uri The URI to query. This will be the full URI sent by the client;
1109 * if the client is requesting a specific record, the URI will end in a record number
1110 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1111 * that _id value.
1112 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001113 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001114 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001115 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001116 * @param selectionArgs You may include ?s in selection, which will be replaced by
1117 * the values from selectionArgs, in order that they appear in the selection.
1118 * The values will be bound as Strings.
1119 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001120 * If {@code null} then the provider is free to define the sort order.
1121 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001122 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001123 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001124 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001125 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001126 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1127 @Nullable String selection, @Nullable String[] selectionArgs,
1128 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001129 return query(uri, projection, selection, selectionArgs, sortOrder);
1130 }
1131
1132 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001133 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1134 * Arguments may include traditional SQL style query arguments. When present these
1135 * should be handled according to the contract established in
1136 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1137 *
1138 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001139 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1140 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1141 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001142 *
Steve McKay76b27702017-04-24 12:07:53 -07001143 * <p>This method can be called from multiple threads, as described in
1144 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1145 * and Threads</a>.
1146 *
1147 * <p>
1148 * Example client call:<p>
1149 * <pre>// Request 20 records starting at row index 30.
1150 Bundle queryArgs = new Bundle();
1151 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1152 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1153
1154 Cursor cursor = getContentResolver().query(
1155 contentUri, // Content Uri is specific to individual content providers.
1156 projection, // String[] describing which columns to return.
1157 queryArgs, // Query arguments.
1158 null); // Cancellation signal.</pre>
1159 *
1160 * Example implementation:<p>
1161 * <pre>
1162
1163 int recordsetSize = 0x1000; // Actual value is implementation specific.
1164 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1165
1166 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1167 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1168
1169 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1170
1171 // Calculate the number of items to include in the cursor.
1172 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1173
1174 // Build the paged result set....
1175 for (int i = offset; i < offset + numItems; i++) {
1176 // populate row from your data.
1177 }
1178
1179 Bundle extras = new Bundle();
1180 c.setExtras(extras);
1181
1182 // Any QUERY_ARG_* key may be included if honored.
1183 // In an actual implementation, include only keys that are both present in queryArgs
1184 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1185 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1186 // then QUERY_ARG_OFFSET should be omitted.
1187 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1188 ContentResolver.QUERY_ARG_OFFSET,
1189 ContentResolver.QUERY_ARG_LIMIT
1190 });
1191
1192 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1193
1194 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1195
1196 return cursor;</pre>
1197 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001198 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1199 * implementation details.
1200 *
1201 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001202 * @param projection The list of columns to put into the cursor.
1203 * If {@code null} provide a default set of columns.
1204 * @param queryArgs A Bundle containing all additional information necessary for the query.
1205 * Values in the Bundle may include SQL style arguments.
1206 * @param cancellationSignal A signal to cancel the operation in progress,
1207 * or {@code null}.
1208 * @return a Cursor or {@code null}.
1209 */
1210 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1211 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1212 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001213
Steve McKayd7ece9f2017-01-12 16:59:59 -08001214 // if client doesn't supply an SQL sort order argument, attempt to build one from
1215 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001216 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001217 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1218 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1219 }
1220
Steve McKayea93fe72016-12-02 11:35:35 -08001221 return query(
1222 uri,
1223 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001224 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1225 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1226 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001227 cancellationSignal);
1228 }
1229
1230 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001231 * Implement this to handle requests for the MIME type of the data at the
1232 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 * <code>vnd.android.cursor.item</code> for a single record,
1234 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001235 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001236 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1237 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001239 * <p>Note that there are no permissions needed for an application to
1240 * access this information; if your content provider requires read and/or
1241 * write permissions, or is not exported, all applications can still call
1242 * this method regardless of their access permissions. This allows them
1243 * to retrieve the MIME type for a URI when dispatching intents.
1244 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001246 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001248 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249
1250 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001251 * Implement this to support canonicalization of URIs that refer to your
1252 * content provider. A canonical URI is one that can be transported across
1253 * devices, backup/restore, and other contexts, and still be able to refer
1254 * to the same data item. Typically this is implemented by adding query
1255 * params to the URI allowing the content provider to verify that an incoming
1256 * canonical URI references the same data as it was originally intended for and,
1257 * if it doesn't, to find that data (if it exists) in the current environment.
1258 *
1259 * <p>For example, if the content provider holds people and a normal URI in it
1260 * is created with a row index into that people database, the cananical representation
1261 * may have an additional query param at the end which specifies the name of the
1262 * person it is intended for. Later calls into the provider with that URI will look
1263 * up the row of that URI's base index and, if it doesn't match or its entry's
1264 * name doesn't match the name in the query param, perform a query on its database
1265 * to find the correct row to operate on.</p>
1266 *
1267 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1268 * URIs (including this one) must perform this verification and recovery of any
1269 * canonical URIs they receive. In addition, you must also implement
1270 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1271 *
1272 * <p>The default implementation of this method returns null, indicating that
1273 * canonical URIs are not supported.</p>
1274 *
1275 * @param url The Uri to canonicalize.
1276 *
1277 * @return Return the canonical representation of <var>url</var>, or null if
1278 * canonicalization of that Uri is not supported.
1279 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001280 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001281 return null;
1282 }
1283
1284 /**
1285 * Remove canonicalization from canonical URIs previously returned by
1286 * {@link #canonicalize}. For example, if your implementation is to add
1287 * a query param to canonicalize a URI, this method can simply trip any
1288 * query params on the URI. The default implementation always returns the
1289 * same <var>url</var> that was passed in.
1290 *
1291 * @param url The Uri to remove any canonicalization from.
1292 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001293 * @return Return the non-canonical representation of <var>url</var>, return
1294 * the <var>url</var> as-is if there is nothing to do, or return null if
1295 * the data identified by the canonical representation can not be found in
1296 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001297 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001298 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001299 return url;
1300 }
1301
1302 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001303 * Implement this to support refresh of content identified by {@code uri}. By default, this
1304 * method returns false; providers who wish to implement this should return true to signal the
1305 * client that the provider has tried refreshing with its own implementation.
1306 * <p>
1307 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1308 * <p>
1309 * Client code should only invoke this method when there is a strong indication (such as a user
1310 * initiated pull to refresh gesture) that the content is stale.
1311 * <p>
1312 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1313 * notifications when content changes.
1314 *
1315 * @param uri The Uri identifying the data to refresh.
1316 * @param args Additional options from the client. The definitions of these are specific to the
1317 * content provider being called.
1318 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1319 * none. For example, if you called refresh on a particular uri, you should call
1320 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1321 * canceled the refresh request.
1322 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001323 */
1324 public boolean refresh(Uri uri, @Nullable Bundle args,
1325 @Nullable CancellationSignal cancellationSignal) {
1326 return false;
1327 }
1328
1329 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001330 * @hide
1331 * Implementation when a caller has performed an insert on the content
1332 * provider, but that call has been rejected for the operation given
1333 * to {@link #setAppOps(int, int)}. The default implementation simply
1334 * returns a dummy URI that is the base URI with a 0 path element
1335 * appended.
1336 */
1337 public Uri rejectInsert(Uri uri, ContentValues values) {
1338 // If not allowed, we need to return some reasonable URI. Maybe the
1339 // content provider should be responsible for this, but for now we
1340 // will just return the base URI with a dummy '0' tagged on to it.
1341 // You shouldn't be able to read if you can't write, anyway, so it
1342 // shouldn't matter much what is returned.
1343 return uri.buildUpon().appendPath("0").build();
1344 }
1345
1346 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001347 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1349 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001350 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001351 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1352 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001353 * @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 -08001354 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001355 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 * @return The URI for the newly inserted item.
1357 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001358 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359
1360 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001361 * Override this to handle requests to insert a set of new rows, or the
1362 * default implementation will iterate over the values and call
1363 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1365 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001366 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001367 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1368 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 *
1370 * @param uri The content:// URI of the insertion request.
1371 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001372 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 * @return The number of values that were inserted.
1374 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001375 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 int numValues = values.length;
1377 for (int i = 0; i < numValues; i++) {
1378 insert(uri, values[i]);
1379 }
1380 return numValues;
1381 }
1382
1383 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001384 * Implement this to handle requests to delete one or more rows.
1385 * The implementation should apply the selection clause when performing
1386 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001387 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001389 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001390 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1391 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 *
1393 * <p>The implementation is responsible for parsing out a row ID at the end
1394 * of the URI, if a specific row is being deleted. That is, the client would
1395 * pass in <code>content://contacts/people/22</code> and the implementation is
1396 * responsible for parsing the record number (22) when creating a SQL statement.
1397 *
1398 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1399 * @param selection An optional restriction to apply to rows when deleting.
1400 * @return The number of rows affected.
1401 * @throws SQLException
1402 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001403 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1404 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405
1406 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001407 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001408 * The implementation should update all rows matching the selection
1409 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1411 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001412 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001413 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1414 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 *
1416 * @param uri The URI to query. This can potentially have a record ID if this
1417 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001418 * @param values A set of column_name/value pairs to update in the database.
1419 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 * @param selection An optional filter to match rows to update.
1421 * @return the number of rows affected.
1422 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001423 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001424 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425
1426 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001427 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001428 * The default implementation always throws {@link FileNotFoundException}.
1429 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001430 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1431 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001432 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001433 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1434 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001435 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 *
1437 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1438 * their responsibility to close it when done. That is, the implementation
1439 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001440 * <p>
1441 * If opened with the exclusive "r" or "w" modes, the returned
1442 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1443 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1444 * supports seeking.
1445 * <p>
1446 * If you need to detect when the returned ParcelFileDescriptor has been
1447 * closed, or if the remote process has crashed or encountered some other
1448 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1449 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1450 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1451 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001452 * <p>
1453 * If you need to return a large file that isn't backed by a real file on
1454 * disk, such as a file on a network share or cloud storage service,
1455 * consider using
1456 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1457 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001459 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1460 * to return the appropriate MIME type for the data returned here with
1461 * the same URI. This will allow intent resolution to automatically determine the data MIME
1462 * type and select the appropriate matching targets as part of its operation.</p>
1463 *
1464 * <p class="note">For better interoperability with other applications, it is recommended
1465 * that for any URIs that can be opened, you also support queries on them
1466 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1467 * You may also want to support other common columns if you have additional meta-data
1468 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1469 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1470 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 * @param uri The URI whose file is to be opened.
1472 * @param mode Access mode for the file. May be "r" for read-only access,
1473 * "rw" for read and write access, or "rwt" for read and write access
1474 * that truncates any existing file.
1475 *
1476 * @return Returns a new ParcelFileDescriptor which you can use to access
1477 * the file.
1478 *
1479 * @throws FileNotFoundException Throws FileNotFoundException if there is
1480 * no file associated with the given URI or the mode is invalid.
1481 * @throws SecurityException Throws SecurityException if the caller does
1482 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001483 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 * @see #openAssetFile(Uri, String)
1485 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001486 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001487 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001488 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001489 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 throws FileNotFoundException {
1491 throw new FileNotFoundException("No files supported by provider at "
1492 + uri);
1493 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001496 * Override this to handle requests to open a file blob.
1497 * The default implementation always throws {@link FileNotFoundException}.
1498 * This method can be called from multiple threads, as described in
1499 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1500 * and Threads</a>.
1501 *
1502 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1503 * to the caller. This way large data (such as images and documents) can be
1504 * returned without copying the content.
1505 *
1506 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1507 * their responsibility to close it when done. That is, the implementation
1508 * of this method should create a new ParcelFileDescriptor for each call.
1509 * <p>
1510 * If opened with the exclusive "r" or "w" modes, the returned
1511 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1512 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1513 * supports seeking.
1514 * <p>
1515 * If you need to detect when the returned ParcelFileDescriptor has been
1516 * closed, or if the remote process has crashed or encountered some other
1517 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1518 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1519 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1520 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1521 *
1522 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1523 * to return the appropriate MIME type for the data returned here with
1524 * the same URI. This will allow intent resolution to automatically determine the data MIME
1525 * type and select the appropriate matching targets as part of its operation.</p>
1526 *
1527 * <p class="note">For better interoperability with other applications, it is recommended
1528 * that for any URIs that can be opened, you also support queries on them
1529 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1530 * You may also want to support other common columns if you have additional meta-data
1531 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1532 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1533 *
1534 * @param uri The URI whose file is to be opened.
1535 * @param mode Access mode for the file. May be "r" for read-only access,
1536 * "w" for write-only access, "rw" for read and write access, or
1537 * "rwt" for read and write access that truncates any existing
1538 * file.
1539 * @param signal A signal to cancel the operation in progress, or
1540 * {@code null} if none. For example, if you are downloading a
1541 * file from the network to service a "rw" mode request, you
1542 * should periodically call
1543 * {@link CancellationSignal#throwIfCanceled()} to check whether
1544 * the client has canceled the request and abort the download.
1545 *
1546 * @return Returns a new ParcelFileDescriptor which you can use to access
1547 * the file.
1548 *
1549 * @throws FileNotFoundException Throws FileNotFoundException if there is
1550 * no file associated with the given URI or the mode is invalid.
1551 * @throws SecurityException Throws SecurityException if the caller does
1552 * not have permission to access the file.
1553 *
1554 * @see #openAssetFile(Uri, String)
1555 * @see #openFileHelper(Uri, String)
1556 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001557 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001558 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001559 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1560 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001561 return openFile(uri, mode);
1562 }
1563
1564 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 * This is like {@link #openFile}, but can be implemented by providers
1566 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001567 * inside of their .apk.
1568 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001569 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1570 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001571 *
1572 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001573 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001574 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1576 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1577 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001578 * <p>
1579 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1580 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001581 *
1582 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 * should create the AssetFileDescriptor with
1584 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001585 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001587 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1588 * to return the appropriate MIME type for the data returned here with
1589 * the same URI. This will allow intent resolution to automatically determine the data MIME
1590 * type and select the appropriate matching targets as part of its operation.</p>
1591 *
1592 * <p class="note">For better interoperability with other applications, it is recommended
1593 * that for any URIs that can be opened, you also support queries on them
1594 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1595 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 * @param uri The URI whose file is to be opened.
1597 * @param mode Access mode for the file. May be "r" for read-only access,
1598 * "w" for write-only access (erasing whatever data is currently in
1599 * the file), "wa" for write-only access to append to any existing data,
1600 * "rw" for read and write access on any existing data, and "rwt" for read
1601 * and write access that truncates any existing file.
1602 *
1603 * @return Returns a new AssetFileDescriptor which you can use to access
1604 * the file.
1605 *
1606 * @throws FileNotFoundException Throws FileNotFoundException if there is
1607 * no file associated with the given URI or the mode is invalid.
1608 * @throws SecurityException Throws SecurityException if the caller does
1609 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001610 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 * @see #openFile(Uri, String)
1612 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001613 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001615 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 throws FileNotFoundException {
1617 ParcelFileDescriptor fd = openFile(uri, mode);
1618 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1619 }
1620
1621 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001622 * This is like {@link #openFile}, but can be implemented by providers
1623 * that need to be able to return sub-sections of files, often assets
1624 * inside of their .apk.
1625 * This method can be called from multiple threads, as described in
1626 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1627 * and Threads</a>.
1628 *
1629 * <p>If you implement this, your clients must be able to deal with such
1630 * file slices, either directly with
1631 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1632 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1633 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1634 * methods.
1635 * <p>
1636 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1637 * streaming of data.
1638 *
1639 * <p class="note">If you are implementing this to return a full file, you
1640 * should create the AssetFileDescriptor with
1641 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1642 * applications that cannot handle sub-sections of files.</p>
1643 *
1644 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1645 * to return the appropriate MIME type for the data returned here with
1646 * the same URI. This will allow intent resolution to automatically determine the data MIME
1647 * type and select the appropriate matching targets as part of its operation.</p>
1648 *
1649 * <p class="note">For better interoperability with other applications, it is recommended
1650 * that for any URIs that can be opened, you also support queries on them
1651 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1652 *
1653 * @param uri The URI whose file is to be opened.
1654 * @param mode Access mode for the file. May be "r" for read-only access,
1655 * "w" for write-only access (erasing whatever data is currently in
1656 * the file), "wa" for write-only access to append to any existing data,
1657 * "rw" for read and write access on any existing data, and "rwt" for read
1658 * and write access that truncates any existing file.
1659 * @param signal A signal to cancel the operation in progress, or
1660 * {@code null} if none. For example, if you are downloading a
1661 * file from the network to service a "rw" mode request, you
1662 * should periodically call
1663 * {@link CancellationSignal#throwIfCanceled()} to check whether
1664 * the client has canceled the request and abort the download.
1665 *
1666 * @return Returns a new AssetFileDescriptor which you can use to access
1667 * the file.
1668 *
1669 * @throws FileNotFoundException Throws FileNotFoundException if there is
1670 * no file associated with the given URI or the mode is invalid.
1671 * @throws SecurityException Throws SecurityException if the caller does
1672 * not have permission to access the file.
1673 *
1674 * @see #openFile(Uri, String)
1675 * @see #openFileHelper(Uri, String)
1676 * @see #getType(android.net.Uri)
1677 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001678 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1679 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001680 return openAssetFile(uri, mode);
1681 }
1682
1683 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 * Convenience for subclasses that wish to implement {@link #openFile}
1685 * by looking up a column named "_data" at the given URI.
1686 *
1687 * @param uri The URI to be opened.
1688 * @param mode The file mode. May be "r" for read-only access,
1689 * "w" for write-only access (erasing whatever data is currently in
1690 * the file), "wa" for write-only access to append to any existing data,
1691 * "rw" for read and write access on any existing data, and "rwt" for read
1692 * and write access that truncates any existing file.
1693 *
1694 * @return Returns a new ParcelFileDescriptor that can be used by the
1695 * client to access the file.
1696 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001697 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1698 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1700 int count = (c != null) ? c.getCount() : 0;
1701 if (count != 1) {
1702 // If there is not exactly one result, throw an appropriate
1703 // exception.
1704 if (c != null) {
1705 c.close();
1706 }
1707 if (count == 0) {
1708 throw new FileNotFoundException("No entry for " + uri);
1709 }
1710 throw new FileNotFoundException("Multiple items at " + uri);
1711 }
1712
1713 c.moveToFirst();
1714 int i = c.getColumnIndex("_data");
1715 String path = (i >= 0 ? c.getString(i) : null);
1716 c.close();
1717 if (path == null) {
1718 throw new FileNotFoundException("Column _data not found.");
1719 }
1720
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001721 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 return ParcelFileDescriptor.open(new File(path), modeBits);
1723 }
1724
1725 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001726 * Called by a client to determine the types of data streams that this
1727 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001728 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001729 * of a particular type, return that MIME type if it matches the given
1730 * mimeTypeFilter. If it can perform type conversions, return an array
1731 * of all supported MIME types that match mimeTypeFilter.
1732 *
1733 * @param uri The data in the content provider being queried.
1734 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001735 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001736 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001737 * given mimeTypeFilter. Otherwise returns an array of all available
1738 * concrete MIME types.
1739 *
1740 * @see #getType(Uri)
1741 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001742 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001743 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001744 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001745 return null;
1746 }
1747
1748 /**
1749 * Called by a client to open a read-only stream containing data of a
1750 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1751 * except the file can only be read-only and the content provider may
1752 * perform data conversions to generate data of the desired type.
1753 *
1754 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001755 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001756 * {@link #openAssetFile(Uri, String)}.
1757 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001758 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001759 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001760 * <p>
1761 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1762 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001763 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001764 * <p class="note">For better interoperability with other applications, it is recommended
1765 * that for any URIs that can be opened, you also support queries on them
1766 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1767 * You may also want to support other common columns if you have additional meta-data
1768 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1769 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1770 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001771 * @param uri The data in the content provider being queried.
1772 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001773 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001774 * requirements; in this case the content provider will pick its best
1775 * type matching the pattern.
1776 * @param opts Additional options from the client. The definitions of
1777 * these are specific to the content provider being called.
1778 *
1779 * @return Returns a new AssetFileDescriptor from which the client can
1780 * read data of the desired type.
1781 *
1782 * @throws FileNotFoundException Throws FileNotFoundException if there is
1783 * no file associated with the given URI or the mode is invalid.
1784 * @throws SecurityException Throws SecurityException if the caller does
1785 * not have permission to access the data.
1786 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1787 * content provider does not support the requested MIME type.
1788 *
1789 * @see #getStreamTypes(Uri, String)
1790 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001791 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001792 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001793 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1794 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001795 if ("*/*".equals(mimeTypeFilter)) {
1796 // If they can take anything, the untyped open call is good enough.
1797 return openAssetFile(uri, "r");
1798 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001799 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001800 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001801 // Use old untyped open call if this provider has a type for this
1802 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001803 return openAssetFile(uri, "r");
1804 }
1805 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1806 }
1807
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001808
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
1816 * result of {@link #getType(Uri)} and, if they match, simply calls
1817 * {@link #openAssetFile(Uri, String)}.
1818 *
1819 * <p>See {@link ClipData} for examples of the use and implementation
1820 * of this method.
1821 * <p>
1822 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1823 * streaming of data.
1824 *
1825 * <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 *
1832 * @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
Jeff Sharkeybd3b9022013-08-20 15:20:04 -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 * @param signal A signal to cancel the operation in progress, or
1840 * {@code null} if none. For example, if you are downloading a
1841 * file from the network to service a "rw" mode request, you
1842 * should periodically call
1843 * {@link CancellationSignal#throwIfCanceled()} to check whether
1844 * the client has canceled the request and abort the download.
1845 *
1846 * @return Returns a new AssetFileDescriptor from which the client can
1847 * read data of the desired type.
1848 *
1849 * @throws FileNotFoundException Throws FileNotFoundException if there is
1850 * no file associated with the given URI or the mode is invalid.
1851 * @throws SecurityException Throws SecurityException if the caller does
1852 * not have permission to access the data.
1853 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1854 * content provider does not support the requested MIME type.
1855 *
1856 * @see #getStreamTypes(Uri, String)
1857 * @see #openAssetFile(Uri, String)
1858 * @see ClipDescription#compareMimeTypes(String, String)
1859 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001860 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1861 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1862 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001863 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1864 }
1865
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001866 /**
1867 * Interface to write a stream of data to a pipe. Use with
1868 * {@link ContentProvider#openPipeHelper}.
1869 */
1870 public interface PipeDataWriter<T> {
1871 /**
1872 * Called from a background thread to stream data out to a pipe.
1873 * Note that the pipe is blocking, so this thread can block on
1874 * writes for an arbitrary amount of time if the client is slow
1875 * at reading.
1876 *
1877 * @param output The pipe where data should be written. This will be
1878 * closed for you upon returning from this function.
1879 * @param uri The URI whose data is to be written.
1880 * @param mimeType The desired type of data to be written.
1881 * @param opts Options supplied by caller.
1882 * @param args Your own custom arguments.
1883 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001884 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1885 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001886 }
1887
1888 /**
1889 * A helper function for implementing {@link #openTypedAssetFile}, for
1890 * creating a data pipe and background thread allowing you to stream
1891 * generated data back to the client. This function returns a new
1892 * ParcelFileDescriptor that should be returned to the caller (the caller
1893 * is responsible for closing it).
1894 *
1895 * @param uri The URI whose data is to be written.
1896 * @param mimeType The desired type of data to be written.
1897 * @param opts Options supplied by caller.
1898 * @param args Your own custom arguments.
1899 * @param func Interface implementing the function that will actually
1900 * stream the data.
1901 * @return Returns a new ParcelFileDescriptor holding the read side of
1902 * the pipe. This should be returned to the caller for reading; the caller
1903 * is responsible for closing it when done.
1904 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001905 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1906 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1907 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001908 try {
1909 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1910
1911 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1912 @Override
1913 protected Object doInBackground(Object... params) {
1914 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1915 try {
1916 fds[1].close();
1917 } catch (IOException e) {
1918 Log.w(TAG, "Failure closing pipe", e);
1919 }
1920 return null;
1921 }
1922 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001923 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001924
1925 return fds[0];
1926 } catch (IOException e) {
1927 throw new FileNotFoundException("failure making pipe");
1928 }
1929 }
1930
1931 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 * Returns true if this instance is a temporary content provider.
1933 * @return true if this instance is a temporary content provider
1934 */
1935 protected boolean isTemporary() {
1936 return false;
1937 }
1938
1939 /**
1940 * Returns the Binder object for this provider.
1941 *
1942 * @return the Binder object for this provider
1943 * @hide
1944 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001945 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 public IContentProvider getIContentProvider() {
1947 return mTransport;
1948 }
1949
1950 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001951 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1952 * when directly instantiating the provider for testing.
1953 * @hide
1954 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001955 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001956 public void attachInfoForTesting(Context context, ProviderInfo info) {
1957 attachInfo(context, info, true);
1958 }
1959
1960 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 * After being instantiated, this is called to tell the content provider
1962 * about itself.
1963 *
1964 * @param context The context this provider is running in
1965 * @param info Registered information about this content provider
1966 */
1967 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001968 attachInfo(context, info, false);
1969 }
1970
1971 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001972 mNoPerms = testing;
1973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 /*
1975 * Only allow it to be set once, so after the content service gives
1976 * this to us clients can't change it.
1977 */
1978 if (mContext == null) {
1979 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06001980 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001981 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1982 Context.APP_OPS_SERVICE);
1983 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001984 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if (info != null) {
1986 setReadPermission(info.readPermission);
1987 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001988 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001989 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001990 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001991 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993 ContentProvider.this.onCreate();
1994 }
1995 }
Fred Quintanace31b232009-05-04 16:01:15 -07001996
1997 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001998 * Override this to handle requests to perform a batch of operations, or the
1999 * default implementation will iterate over the operations and call
2000 * {@link ContentProviderOperation#apply} on each of them.
2001 * If all calls to {@link ContentProviderOperation#apply} succeed
2002 * then a {@link ContentProviderResult} array with as many
2003 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002004 * fail, it is up to the implementation how many of the others take effect.
2005 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002006 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2007 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002008 *
Fred Quintanace31b232009-05-04 16:01:15 -07002009 * @param operations the operations to apply
2010 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002011 * @throws OperationApplicationException thrown if any operation fails.
2012 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002013 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002014 public @NonNull ContentProviderResult[] applyBatch(
2015 @NonNull ArrayList<ContentProviderOperation> operations)
2016 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002017 final int numOperations = operations.size();
2018 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2019 for (int i = 0; i < numOperations; i++) {
2020 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002021 }
2022 return results;
2023 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002024
2025 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002026 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002027 * interfaces that are cheaper and/or unnatural for a table-like
2028 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002029 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002030 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2031 * on this entry into the content provider besides the basic ability for the application
2032 * to get access to the provider at all. For example, it has no idea whether the call
2033 * being executed may read or write data in the provider, so can't enforce those
2034 * individual permissions. Any implementation of this method <strong>must</strong>
2035 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2036 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002037 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2038 * @param arg provider-defined String argument. May be {@code null}.
2039 * @param extras provider-defined Bundle argument. May be {@code null}.
2040 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002041 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002042 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002043 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2044 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002045 return null;
2046 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002047
2048 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002049 * Implement this to shut down the ContentProvider instance. You can then
2050 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002051 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002052 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002053 * Android normally handles ContentProvider startup and shutdown
2054 * automatically. You do not need to start up or shut down a
2055 * ContentProvider. When you invoke a test method on a ContentProvider,
2056 * however, a ContentProvider instance is started and keeps running after
2057 * the test finishes, even if a succeeding test instantiates another
2058 * ContentProvider. A conflict develops because the two instances are
2059 * usually running against the same underlying data source (for example, an
2060 * sqlite database).
2061 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002062 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002063 * Implementing shutDown() avoids this conflict by providing a way to
2064 * terminate the ContentProvider. This method can also prevent memory leaks
2065 * from multiple instantiations of the ContentProvider, and it can ensure
2066 * unit test isolation by allowing you to completely clean up the test
2067 * fixture before moving on to the next test.
2068 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002069 */
2070 public void shutdown() {
2071 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2072 "connections are gracefully shutdown");
2073 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002074
2075 /**
2076 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002077 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002078 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002079 * @param fd The raw file descriptor that the dump is being sent to.
2080 * @param writer The PrintWriter to which you should dump your state. This will be
2081 * closed for you after you return.
2082 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002083 */
2084 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2085 writer.println("nothing to dump");
2086 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002087
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002088 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002089 @VisibleForTesting
2090 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002091 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002092 if (!mSingleUser) {
2093 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2094 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2095 throw new SecurityException("trying to query a ContentProvider in user "
2096 + mContext.getUserId() + " with a uri belonging to user " + userId);
2097 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002098 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002099 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2100 String message = "The authority of the uri " + uri + " does not match the one of the "
2101 + "contentProvider: ";
2102 if (mAuthority != null) {
2103 message += mAuthority;
2104 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002105 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002106 }
2107 throw new SecurityException(message);
2108 }
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002109
2110 // Normalize the path by removing any empty path segments, which can be
2111 // a source of security issues.
2112 final String encodedPath = uri.getEncodedPath();
2113 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
2114 return uri.buildUpon().encodedPath(encodedPath.replaceAll("//+", "/")).build();
2115 } else {
2116 return uri;
2117 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002118 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002119
2120 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002121 private Uri maybeGetUriWithoutUserId(Uri uri) {
2122 if (mSingleUser) {
2123 return uri;
2124 }
2125 return getUriWithoutUserId(uri);
2126 }
2127
2128 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002129 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2130 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002131 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002132 if (end == -1) return defaultUserId;
2133 String userIdString = auth.substring(0, end);
2134 try {
2135 return Integer.parseInt(userIdString);
2136 } catch (NumberFormatException e) {
2137 Log.w(TAG, "Error parsing userId.", e);
2138 return UserHandle.USER_NULL;
2139 }
2140 }
2141
2142 /** @hide */
2143 public static int getUserIdFromAuthority(String auth) {
2144 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2145 }
2146
2147 /** @hide */
2148 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2149 if (uri == null) return defaultUserId;
2150 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2151 }
2152
2153 /** @hide */
2154 public static int getUserIdFromUri(Uri uri) {
2155 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2156 }
2157
2158 /**
2159 * Removes userId part from authority string. Expects format:
2160 * userId@some.authority
2161 * If there is no userId in the authority, it symply returns the argument
2162 * @hide
2163 */
2164 public static String getAuthorityWithoutUserId(String auth) {
2165 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002166 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002167 return auth.substring(end+1);
2168 }
2169
2170 /** @hide */
2171 public static Uri getUriWithoutUserId(Uri uri) {
2172 if (uri == null) return null;
2173 Uri.Builder builder = uri.buildUpon();
2174 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2175 return builder.build();
2176 }
2177
2178 /** @hide */
2179 public static boolean uriHasUserId(Uri uri) {
2180 if (uri == null) return false;
2181 return !TextUtils.isEmpty(uri.getUserInfo());
2182 }
2183
2184 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002185 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002186 public static Uri maybeAddUserId(Uri uri, int userId) {
2187 if (uri == null) return null;
2188 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002189 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002190 if (!uriHasUserId(uri)) {
2191 //We don't add the user Id if there's already one
2192 Uri.Builder builder = uri.buildUpon();
2193 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2194 return builder.build();
2195 }
2196 }
2197 return uri;
2198 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002199}