blob: 145c92731458d3e4ad5da0e78edf6573257a7b1f [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 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600825 * Opaque token representing the identity of an incoming IPC.
826 */
827 public final class CallingIdentity {
828 /** {@hide} */
829 public final long binderToken;
830 /** {@hide} */
831 public final String callingPackage;
832
833 /** {@hide} */
834 public CallingIdentity(long binderToken, String callingPackage) {
835 this.binderToken = binderToken;
836 this.callingPackage = callingPackage;
837 }
838 }
839
840 /**
841 * Reset the identity of the incoming IPC on the current thread.
842 * <p>
843 * Internally this calls {@link Binder#clearCallingIdentity()} and also
844 * clears any value stored in {@link #getCallingPackage()}.
845 *
846 * @return Returns an opaque token that can be used to restore the original
847 * calling identity by passing it to
848 * {@link #restoreCallingIdentity}.
849 */
850 public final @NonNull CallingIdentity clearCallingIdentity() {
851 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
852 }
853
854 /**
855 * Restore the identity of the incoming IPC on the current thread back to a
856 * previously identity that was returned by {@link #clearCallingIdentity}.
857 * <p>
858 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
859 * also restores any value stored in {@link #getCallingPackage()}.
860 */
861 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
862 Binder.restoreCallingIdentity(identity.binderToken);
863 mCallingPackage.set(identity.callingPackage);
864 }
865
866 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100867 * Change the authorities of the ContentProvider.
868 * This is normally set for you from its manifest information when the provider is first
869 * created.
870 * @hide
871 * @param authorities the semi-colon separated authorities of the ContentProvider.
872 */
873 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100874 if (authorities != null) {
875 if (authorities.indexOf(';') == -1) {
876 mAuthority = authorities;
877 mAuthorities = null;
878 } else {
879 mAuthority = null;
880 mAuthorities = authorities.split(";");
881 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100882 }
883 }
884
885 /** @hide */
886 protected final boolean matchesOurAuthorities(String authority) {
887 if (mAuthority != null) {
888 return mAuthority.equals(authority);
889 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100890 if (mAuthorities != null) {
891 int length = mAuthorities.length;
892 for (int i = 0; i < length; i++) {
893 if (mAuthorities[i].equals(authority)) return true;
894 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100895 }
896 return false;
897 }
898
899
900 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 * Change the permission required to read data from the content
902 * provider. This is normally set for you from its manifest information
903 * when the provider is first created.
904 *
905 * @param permission Name of the permission required for read-only access.
906 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700907 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 mReadPermission = permission;
909 }
910
911 /**
912 * Return the name of the permission required for read-only access to
913 * this content provider. This method can be called from multiple
914 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800915 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
916 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700918 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 return mReadPermission;
920 }
921
922 /**
923 * Change the permission required to read and write data in the content
924 * provider. This is normally set for you from its manifest information
925 * when the provider is first created.
926 *
927 * @param permission Name of the permission required for read/write access.
928 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700929 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 mWritePermission = permission;
931 }
932
933 /**
934 * Return the name of the permission required for read/write access to
935 * this content provider. This method can be called from multiple
936 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800937 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
938 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700940 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 return mWritePermission;
942 }
943
944 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700945 * Change the path-based permission required to read and/or write data in
946 * the content provider. This is normally set for you from its manifest
947 * information when the provider is first created.
948 *
949 * @param permissions Array of path permission descriptions.
950 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700951 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700952 mPathPermissions = permissions;
953 }
954
955 /**
956 * Return the path-based permissions required for read and/or write access to
957 * this content provider. This method can be called from multiple
958 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800959 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
960 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700961 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700962 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700963 return mPathPermissions;
964 }
965
Dianne Hackborn35654b62013-01-14 17:38:02 -0800966 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100967 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800968 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800969 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800970 mTransport.mReadOp = readOp;
971 mTransport.mWriteOp = writeOp;
972 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800973 }
974
Dianne Hackborn961321f2013-02-05 17:22:41 -0800975 /** @hide */
976 public AppOpsManager getAppOpsManager() {
977 return mTransport.mAppOpsManager;
978 }
979
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700980 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700981 * Implement this to initialize your content provider on startup.
982 * This method is called for all registered content providers on the
983 * application main thread at application launch time. It must not perform
984 * lengthy operations, or application startup will be delayed.
985 *
986 * <p>You should defer nontrivial initialization (such as opening,
987 * upgrading, and scanning databases) until the content provider is used
988 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
989 * keeps application startup fast, avoids unnecessary work if the provider
990 * turns out not to be needed, and stops database errors (such as a full
991 * disk) from halting application launch.
992 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700993 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700994 * is a helpful utility class that makes it easy to manage databases,
995 * and will automatically defer opening until first use. If you do use
996 * SQLiteOpenHelper, make sure to avoid calling
997 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
998 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
999 * from this method. (Instead, override
1000 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1001 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 *
1003 * @return true if the provider was successfully loaded, false otherwise
1004 */
1005 public abstract boolean onCreate();
1006
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001007 /**
1008 * {@inheritDoc}
1009 * This method is always called on the application main thread, and must
1010 * not perform lengthy operations.
1011 *
1012 * <p>The default content provider implementation does nothing.
1013 * Override this method to take appropriate action.
1014 * (Content providers do not usually care about things like screen
1015 * orientation, but may want to know about locale changes.)
1016 */
Steve McKayea93fe72016-12-02 11:35:35 -08001017 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 public void onConfigurationChanged(Configuration newConfig) {
1019 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001020
1021 /**
1022 * {@inheritDoc}
1023 * This method is always called on the application main thread, and must
1024 * not perform lengthy operations.
1025 *
1026 * <p>The default content provider implementation does nothing.
1027 * Subclasses may override this method to take appropriate action.
1028 */
Steve McKayea93fe72016-12-02 11:35:35 -08001029 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 public void onLowMemory() {
1031 }
1032
Steve McKayea93fe72016-12-02 11:35:35 -08001033 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001034 public void onTrimMemory(int level) {
1035 }
1036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001038 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001039 *
1040 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1041 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1042 * implementation of this method.
1043 *
1044 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001045 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1046 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 * <p>
1048 * Example client call:<p>
1049 * <pre>// Request a specific record.
1050 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001051 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 projection, // Which columns to return.
1053 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001054 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 People.NAME + " ASC"); // Sort order.</pre>
1056 * Example implementation:<p>
1057 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1058 // proper SQL syntax for us.
1059 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1060
1061 // Set the table we're querying.
1062 qBuilder.setTables(DATABASE_TABLE_NAME);
1063
1064 // If the query ends in a specific record number, we're
1065 // being asked for a specific record, so set the
1066 // WHERE clause in our query.
1067 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1068 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1069 }
1070
1071 // Make the query.
1072 Cursor c = qBuilder.query(mDb,
1073 projection,
1074 selection,
1075 selectionArgs,
1076 groupBy,
1077 having,
1078 sortOrder);
1079 c.setNotificationUri(getContext().getContentResolver(), uri);
1080 return c;</pre>
1081 *
1082 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001083 * if the client is requesting a specific record, the URI will end in a record number
1084 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1085 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001087 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001089 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001090 * @param selectionArgs You may include ?s in selection, which will be replaced by
1091 * the values from selectionArgs, in order that they appear in the selection.
1092 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001094 * If {@code null} then the provider is free to define the sort order.
1095 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001097 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1098 @Nullable String selection, @Nullable String[] selectionArgs,
1099 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100
Fred Quintana5bba6322009-10-05 14:21:12 -07001101 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001102 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001103 *
1104 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1105 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1106 *
1107 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001108 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1109 * and Threads</a>.
1110 * <p>
1111 * Example client call:<p>
1112 * <pre>// Request a specific record.
1113 * Cursor managedCursor = managedQuery(
1114 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1115 projection, // Which columns to return.
1116 null, // WHERE clause.
1117 null, // WHERE clause value substitution
1118 People.NAME + " ASC"); // Sort order.</pre>
1119 * Example implementation:<p>
1120 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1121 // proper SQL syntax for us.
1122 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1123
1124 // Set the table we're querying.
1125 qBuilder.setTables(DATABASE_TABLE_NAME);
1126
1127 // If the query ends in a specific record number, we're
1128 // being asked for a specific record, so set the
1129 // WHERE clause in our query.
1130 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1131 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1132 }
1133
1134 // Make the query.
1135 Cursor c = qBuilder.query(mDb,
1136 projection,
1137 selection,
1138 selectionArgs,
1139 groupBy,
1140 having,
1141 sortOrder);
1142 c.setNotificationUri(getContext().getContentResolver(), uri);
1143 return c;</pre>
1144 * <p>
1145 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001146 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1147 * signal to ensure correct operation on older versions of the Android Framework in
1148 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001149 *
1150 * @param uri The URI to query. This will be the full URI sent by the client;
1151 * if the client is requesting a specific record, the URI will end in a record number
1152 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1153 * that _id value.
1154 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001155 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001156 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001157 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001158 * @param selectionArgs You may include ?s in selection, which will be replaced by
1159 * the values from selectionArgs, in order that they appear in the selection.
1160 * The values will be bound as Strings.
1161 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001162 * If {@code null} then the provider is free to define the sort order.
1163 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001164 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001165 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001166 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001167 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001168 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1169 @Nullable String selection, @Nullable String[] selectionArgs,
1170 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001171 return query(uri, projection, selection, selectionArgs, sortOrder);
1172 }
1173
1174 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001175 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1176 * Arguments may include traditional SQL style query arguments. When present these
1177 * should be handled according to the contract established in
1178 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1179 *
1180 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001181 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1182 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1183 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001184 *
Steve McKay76b27702017-04-24 12:07:53 -07001185 * <p>This method can be called from multiple threads, as described in
1186 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1187 * and Threads</a>.
1188 *
1189 * <p>
1190 * Example client call:<p>
1191 * <pre>// Request 20 records starting at row index 30.
1192 Bundle queryArgs = new Bundle();
1193 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1194 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1195
1196 Cursor cursor = getContentResolver().query(
1197 contentUri, // Content Uri is specific to individual content providers.
1198 projection, // String[] describing which columns to return.
1199 queryArgs, // Query arguments.
1200 null); // Cancellation signal.</pre>
1201 *
1202 * Example implementation:<p>
1203 * <pre>
1204
1205 int recordsetSize = 0x1000; // Actual value is implementation specific.
1206 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1207
1208 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1209 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1210
1211 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1212
1213 // Calculate the number of items to include in the cursor.
1214 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1215
1216 // Build the paged result set....
1217 for (int i = offset; i < offset + numItems; i++) {
1218 // populate row from your data.
1219 }
1220
1221 Bundle extras = new Bundle();
1222 c.setExtras(extras);
1223
1224 // Any QUERY_ARG_* key may be included if honored.
1225 // In an actual implementation, include only keys that are both present in queryArgs
1226 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1227 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1228 // then QUERY_ARG_OFFSET should be omitted.
1229 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1230 ContentResolver.QUERY_ARG_OFFSET,
1231 ContentResolver.QUERY_ARG_LIMIT
1232 });
1233
1234 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1235
1236 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1237
1238 return cursor;</pre>
1239 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001240 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1241 * implementation details.
1242 *
1243 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001244 * @param projection The list of columns to put into the cursor.
1245 * If {@code null} provide a default set of columns.
1246 * @param queryArgs A Bundle containing all additional information necessary for the query.
1247 * Values in the Bundle may include SQL style arguments.
1248 * @param cancellationSignal A signal to cancel the operation in progress,
1249 * or {@code null}.
1250 * @return a Cursor or {@code null}.
1251 */
1252 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1253 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1254 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001255
Steve McKayd7ece9f2017-01-12 16:59:59 -08001256 // if client doesn't supply an SQL sort order argument, attempt to build one from
1257 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001258 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001259 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1260 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1261 }
1262
Steve McKayea93fe72016-12-02 11:35:35 -08001263 return query(
1264 uri,
1265 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001266 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1267 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1268 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001269 cancellationSignal);
1270 }
1271
1272 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001273 * Implement this to handle requests for the MIME type of the data at the
1274 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * <code>vnd.android.cursor.item</code> for a single record,
1276 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001277 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001278 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1279 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001281 * <p>Note that there are no permissions needed for an application to
1282 * access this information; if your content provider requires read and/or
1283 * write permissions, or is not exported, all applications can still call
1284 * this method regardless of their access permissions. This allows them
1285 * to retrieve the MIME type for a URI when dispatching intents.
1286 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001288 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001290 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291
1292 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001293 * Implement this to support canonicalization of URIs that refer to your
1294 * content provider. A canonical URI is one that can be transported across
1295 * devices, backup/restore, and other contexts, and still be able to refer
1296 * to the same data item. Typically this is implemented by adding query
1297 * params to the URI allowing the content provider to verify that an incoming
1298 * canonical URI references the same data as it was originally intended for and,
1299 * if it doesn't, to find that data (if it exists) in the current environment.
1300 *
1301 * <p>For example, if the content provider holds people and a normal URI in it
1302 * is created with a row index into that people database, the cananical representation
1303 * may have an additional query param at the end which specifies the name of the
1304 * person it is intended for. Later calls into the provider with that URI will look
1305 * up the row of that URI's base index and, if it doesn't match or its entry's
1306 * name doesn't match the name in the query param, perform a query on its database
1307 * to find the correct row to operate on.</p>
1308 *
1309 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1310 * URIs (including this one) must perform this verification and recovery of any
1311 * canonical URIs they receive. In addition, you must also implement
1312 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1313 *
1314 * <p>The default implementation of this method returns null, indicating that
1315 * canonical URIs are not supported.</p>
1316 *
1317 * @param url The Uri to canonicalize.
1318 *
1319 * @return Return the canonical representation of <var>url</var>, or null if
1320 * canonicalization of that Uri is not supported.
1321 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001322 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001323 return null;
1324 }
1325
1326 /**
1327 * Remove canonicalization from canonical URIs previously returned by
1328 * {@link #canonicalize}. For example, if your implementation is to add
1329 * a query param to canonicalize a URI, this method can simply trip any
1330 * query params on the URI. The default implementation always returns the
1331 * same <var>url</var> that was passed in.
1332 *
1333 * @param url The Uri to remove any canonicalization from.
1334 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001335 * @return Return the non-canonical representation of <var>url</var>, return
1336 * the <var>url</var> as-is if there is nothing to do, or return null if
1337 * the data identified by the canonical representation can not be found in
1338 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001339 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001340 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001341 return url;
1342 }
1343
1344 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001345 * Implement this to support refresh of content identified by {@code uri}. By default, this
1346 * method returns false; providers who wish to implement this should return true to signal the
1347 * client that the provider has tried refreshing with its own implementation.
1348 * <p>
1349 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1350 * <p>
1351 * Client code should only invoke this method when there is a strong indication (such as a user
1352 * initiated pull to refresh gesture) that the content is stale.
1353 * <p>
1354 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1355 * notifications when content changes.
1356 *
1357 * @param uri The Uri identifying the data to refresh.
1358 * @param args Additional options from the client. The definitions of these are specific to the
1359 * content provider being called.
1360 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1361 * none. For example, if you called refresh on a particular uri, you should call
1362 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1363 * canceled the refresh request.
1364 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001365 */
1366 public boolean refresh(Uri uri, @Nullable Bundle args,
1367 @Nullable CancellationSignal cancellationSignal) {
1368 return false;
1369 }
1370
1371 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001372 * @hide
1373 * Implementation when a caller has performed an insert on the content
1374 * provider, but that call has been rejected for the operation given
1375 * to {@link #setAppOps(int, int)}. The default implementation simply
1376 * returns a dummy URI that is the base URI with a 0 path element
1377 * appended.
1378 */
1379 public Uri rejectInsert(Uri uri, ContentValues values) {
1380 // If not allowed, we need to return some reasonable URI. Maybe the
1381 // content provider should be responsible for this, but for now we
1382 // will just return the base URI with a dummy '0' tagged on to it.
1383 // You shouldn't be able to read if you can't write, anyway, so it
1384 // shouldn't matter much what is returned.
1385 return uri.buildUpon().appendPath("0").build();
1386 }
1387
1388 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001389 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1391 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001392 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001393 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1394 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001395 * @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 -08001396 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001397 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 * @return The URI for the newly inserted item.
1399 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001400 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401
1402 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001403 * Override this to handle requests to insert a set of new rows, or the
1404 * default implementation will iterate over the values and call
1405 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1407 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001408 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001409 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1410 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 *
1412 * @param uri The content:// URI of the insertion request.
1413 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001414 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 * @return The number of values that were inserted.
1416 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001417 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 int numValues = values.length;
1419 for (int i = 0; i < numValues; i++) {
1420 insert(uri, values[i]);
1421 }
1422 return numValues;
1423 }
1424
1425 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001426 * Implement this to handle requests to delete one or more rows.
1427 * The implementation should apply the selection clause when performing
1428 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001429 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001431 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001432 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1433 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 *
1435 * <p>The implementation is responsible for parsing out a row ID at the end
1436 * of the URI, if a specific row is being deleted. That is, the client would
1437 * pass in <code>content://contacts/people/22</code> and the implementation is
1438 * responsible for parsing the record number (22) when creating a SQL statement.
1439 *
1440 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1441 * @param selection An optional restriction to apply to rows when deleting.
1442 * @return The number of rows affected.
1443 * @throws SQLException
1444 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001445 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1446 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447
1448 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001449 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001450 * The implementation should update all rows matching the selection
1451 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1453 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001454 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001455 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1456 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 *
1458 * @param uri The URI to query. This can potentially have a record ID if this
1459 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001460 * @param values A set of column_name/value pairs to update in the database.
1461 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 * @param selection An optional filter to match rows to update.
1463 * @return the number of rows affected.
1464 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001465 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001466 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467
1468 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001469 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001470 * The default implementation always throws {@link FileNotFoundException}.
1471 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001472 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1473 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001474 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001475 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1476 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001477 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 *
1479 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1480 * their responsibility to close it when done. That is, the implementation
1481 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001482 * <p>
1483 * If opened with the exclusive "r" or "w" modes, the returned
1484 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1485 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1486 * supports seeking.
1487 * <p>
1488 * If you need to detect when the returned ParcelFileDescriptor has been
1489 * closed, or if the remote process has crashed or encountered some other
1490 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1491 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1492 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1493 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001494 * <p>
1495 * If you need to return a large file that isn't backed by a real file on
1496 * disk, such as a file on a network share or cloud storage service,
1497 * consider using
1498 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1499 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001501 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1502 * to return the appropriate MIME type for the data returned here with
1503 * the same URI. This will allow intent resolution to automatically determine the data MIME
1504 * type and select the appropriate matching targets as part of its operation.</p>
1505 *
1506 * <p class="note">For better interoperability with other applications, it is recommended
1507 * that for any URIs that can be opened, you also support queries on them
1508 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1509 * You may also want to support other common columns if you have additional meta-data
1510 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1511 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1512 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 * @param uri The URI whose file is to be opened.
1514 * @param mode Access mode for the file. May be "r" for read-only access,
1515 * "rw" for read and write access, or "rwt" for read and write access
1516 * that truncates any existing file.
1517 *
1518 * @return Returns a new ParcelFileDescriptor which you can use to access
1519 * the file.
1520 *
1521 * @throws FileNotFoundException Throws FileNotFoundException if there is
1522 * no file associated with the given URI or the mode is invalid.
1523 * @throws SecurityException Throws SecurityException if the caller does
1524 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001525 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 * @see #openAssetFile(Uri, String)
1527 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001528 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001529 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001530 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001531 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 throws FileNotFoundException {
1533 throw new FileNotFoundException("No files supported by provider at "
1534 + uri);
1535 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001538 * Override this to handle requests to open a file blob.
1539 * The default implementation always throws {@link FileNotFoundException}.
1540 * This method can be called from multiple threads, as described in
1541 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1542 * and Threads</a>.
1543 *
1544 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1545 * to the caller. This way large data (such as images and documents) can be
1546 * returned without copying the content.
1547 *
1548 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1549 * their responsibility to close it when done. That is, the implementation
1550 * of this method should create a new ParcelFileDescriptor for each call.
1551 * <p>
1552 * If opened with the exclusive "r" or "w" modes, the returned
1553 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1554 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1555 * supports seeking.
1556 * <p>
1557 * If you need to detect when the returned ParcelFileDescriptor has been
1558 * closed, or if the remote process has crashed or encountered some other
1559 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1560 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1561 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1562 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1563 *
1564 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1565 * to return the appropriate MIME type for the data returned here with
1566 * the same URI. This will allow intent resolution to automatically determine the data MIME
1567 * type and select the appropriate matching targets as part of its operation.</p>
1568 *
1569 * <p class="note">For better interoperability with other applications, it is recommended
1570 * that for any URIs that can be opened, you also support queries on them
1571 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1572 * You may also want to support other common columns if you have additional meta-data
1573 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1574 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1575 *
1576 * @param uri The URI whose file is to be opened.
1577 * @param mode Access mode for the file. May be "r" for read-only access,
1578 * "w" for write-only access, "rw" for read and write access, or
1579 * "rwt" for read and write access that truncates any existing
1580 * file.
1581 * @param signal A signal to cancel the operation in progress, or
1582 * {@code null} if none. For example, if you are downloading a
1583 * file from the network to service a "rw" mode request, you
1584 * should periodically call
1585 * {@link CancellationSignal#throwIfCanceled()} to check whether
1586 * the client has canceled the request and abort the download.
1587 *
1588 * @return Returns a new ParcelFileDescriptor which you can use to access
1589 * the file.
1590 *
1591 * @throws FileNotFoundException Throws FileNotFoundException if there is
1592 * no file associated with the given URI or the mode is invalid.
1593 * @throws SecurityException Throws SecurityException if the caller does
1594 * not have permission to access the file.
1595 *
1596 * @see #openAssetFile(Uri, String)
1597 * @see #openFileHelper(Uri, String)
1598 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001599 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001600 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001601 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1602 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001603 return openFile(uri, mode);
1604 }
1605
1606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 * This is like {@link #openFile}, but can be implemented by providers
1608 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001609 * inside of their .apk.
1610 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001611 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1612 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001613 *
1614 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001615 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001616 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1618 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1619 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001620 * <p>
1621 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1622 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001623 *
1624 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 * should create the AssetFileDescriptor with
1626 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001627 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001629 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1630 * to return the appropriate MIME type for the data returned here with
1631 * the same URI. This will allow intent resolution to automatically determine the data MIME
1632 * type and select the appropriate matching targets as part of its operation.</p>
1633 *
1634 * <p class="note">For better interoperability with other applications, it is recommended
1635 * that for any URIs that can be opened, you also support queries on them
1636 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1637 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 * @param uri The URI whose file is to be opened.
1639 * @param mode Access mode for the file. May be "r" for read-only access,
1640 * "w" for write-only access (erasing whatever data is currently in
1641 * the file), "wa" for write-only access to append to any existing data,
1642 * "rw" for read and write access on any existing data, and "rwt" for read
1643 * and write access that truncates any existing file.
1644 *
1645 * @return Returns a new AssetFileDescriptor which you can use to access
1646 * the file.
1647 *
1648 * @throws FileNotFoundException Throws FileNotFoundException if there is
1649 * no file associated with the given URI or the mode is invalid.
1650 * @throws SecurityException Throws SecurityException if the caller does
1651 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001652 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 * @see #openFile(Uri, String)
1654 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001655 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001657 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 throws FileNotFoundException {
1659 ParcelFileDescriptor fd = openFile(uri, mode);
1660 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1661 }
1662
1663 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001664 * This is like {@link #openFile}, but can be implemented by providers
1665 * that need to be able to return sub-sections of files, often assets
1666 * inside of their .apk.
1667 * This method can be called from multiple threads, as described in
1668 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1669 * and Threads</a>.
1670 *
1671 * <p>If you implement this, your clients must be able to deal with such
1672 * file slices, either directly with
1673 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1674 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1675 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1676 * methods.
1677 * <p>
1678 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1679 * streaming of data.
1680 *
1681 * <p class="note">If you are implementing this to return a full file, you
1682 * should create the AssetFileDescriptor with
1683 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1684 * applications that cannot handle sub-sections of files.</p>
1685 *
1686 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1687 * to return the appropriate MIME type for the data returned here with
1688 * the same URI. This will allow intent resolution to automatically determine the data MIME
1689 * type and select the appropriate matching targets as part of its operation.</p>
1690 *
1691 * <p class="note">For better interoperability with other applications, it is recommended
1692 * that for any URIs that can be opened, you also support queries on them
1693 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1694 *
1695 * @param uri The URI whose file is to be opened.
1696 * @param mode Access mode for the file. May be "r" for read-only access,
1697 * "w" for write-only access (erasing whatever data is currently in
1698 * the file), "wa" for write-only access to append to any existing data,
1699 * "rw" for read and write access on any existing data, and "rwt" for read
1700 * and write access that truncates any existing file.
1701 * @param signal A signal to cancel the operation in progress, or
1702 * {@code null} if none. For example, if you are downloading a
1703 * file from the network to service a "rw" mode request, you
1704 * should periodically call
1705 * {@link CancellationSignal#throwIfCanceled()} to check whether
1706 * the client has canceled the request and abort the download.
1707 *
1708 * @return Returns a new AssetFileDescriptor which you can use to access
1709 * the file.
1710 *
1711 * @throws FileNotFoundException Throws FileNotFoundException if there is
1712 * no file associated with the given URI or the mode is invalid.
1713 * @throws SecurityException Throws SecurityException if the caller does
1714 * not have permission to access the file.
1715 *
1716 * @see #openFile(Uri, String)
1717 * @see #openFileHelper(Uri, String)
1718 * @see #getType(android.net.Uri)
1719 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001720 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1721 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001722 return openAssetFile(uri, mode);
1723 }
1724
1725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 * Convenience for subclasses that wish to implement {@link #openFile}
1727 * by looking up a column named "_data" at the given URI.
1728 *
1729 * @param uri The URI to be opened.
1730 * @param mode The file mode. May be "r" for read-only access,
1731 * "w" for write-only access (erasing whatever data is currently in
1732 * the file), "wa" for write-only access to append to any existing data,
1733 * "rw" for read and write access on any existing data, and "rwt" for read
1734 * and write access that truncates any existing file.
1735 *
1736 * @return Returns a new ParcelFileDescriptor that can be used by the
1737 * client to access the file.
1738 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001739 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1740 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1742 int count = (c != null) ? c.getCount() : 0;
1743 if (count != 1) {
1744 // If there is not exactly one result, throw an appropriate
1745 // exception.
1746 if (c != null) {
1747 c.close();
1748 }
1749 if (count == 0) {
1750 throw new FileNotFoundException("No entry for " + uri);
1751 }
1752 throw new FileNotFoundException("Multiple items at " + uri);
1753 }
1754
1755 c.moveToFirst();
1756 int i = c.getColumnIndex("_data");
1757 String path = (i >= 0 ? c.getString(i) : null);
1758 c.close();
1759 if (path == null) {
1760 throw new FileNotFoundException("Column _data not found.");
1761 }
1762
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001763 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 return ParcelFileDescriptor.open(new File(path), modeBits);
1765 }
1766
1767 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001768 * Called by a client to determine the types of data streams that this
1769 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001770 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001771 * of a particular type, return that MIME type if it matches the given
1772 * mimeTypeFilter. If it can perform type conversions, return an array
1773 * of all supported MIME types that match mimeTypeFilter.
1774 *
1775 * @param uri The data in the content provider being queried.
1776 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001777 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001778 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001779 * given mimeTypeFilter. Otherwise returns an array of all available
1780 * concrete MIME types.
1781 *
1782 * @see #getType(Uri)
1783 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001784 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001785 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001786 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001787 return null;
1788 }
1789
1790 /**
1791 * Called by a client to open a read-only stream containing data of a
1792 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1793 * except the file can only be read-only and the content provider may
1794 * perform data conversions to generate data of the desired type.
1795 *
1796 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001797 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001798 * {@link #openAssetFile(Uri, String)}.
1799 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001800 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001801 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001802 * <p>
1803 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1804 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001805 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001806 * <p class="note">For better interoperability with other applications, it is recommended
1807 * that for any URIs that can be opened, you also support queries on them
1808 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1809 * You may also want to support other common columns if you have additional meta-data
1810 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1811 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1812 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001813 * @param uri The data in the content provider being queried.
1814 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001815 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001816 * requirements; in this case the content provider will pick its best
1817 * type matching the pattern.
1818 * @param opts Additional options from the client. The definitions of
1819 * these are specific to the content provider being called.
1820 *
1821 * @return Returns a new AssetFileDescriptor from which the client can
1822 * read data of the desired type.
1823 *
1824 * @throws FileNotFoundException Throws FileNotFoundException if there is
1825 * no file associated with the given URI or the mode is invalid.
1826 * @throws SecurityException Throws SecurityException if the caller does
1827 * not have permission to access the data.
1828 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1829 * content provider does not support the requested MIME type.
1830 *
1831 * @see #getStreamTypes(Uri, String)
1832 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001833 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001834 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001835 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1836 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001837 if ("*/*".equals(mimeTypeFilter)) {
1838 // If they can take anything, the untyped open call is good enough.
1839 return openAssetFile(uri, "r");
1840 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001841 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001842 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001843 // Use old untyped open call if this provider has a type for this
1844 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001845 return openAssetFile(uri, "r");
1846 }
1847 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1848 }
1849
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001850
1851 /**
1852 * Called by a client to open a read-only stream containing data of a
1853 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1854 * except the file can only be read-only and the content provider may
1855 * perform data conversions to generate data of the desired type.
1856 *
1857 * <p>The default implementation compares the given mimeType against the
1858 * result of {@link #getType(Uri)} and, if they match, simply calls
1859 * {@link #openAssetFile(Uri, String)}.
1860 *
1861 * <p>See {@link ClipData} for examples of the use and implementation
1862 * of this method.
1863 * <p>
1864 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1865 * streaming of data.
1866 *
1867 * <p class="note">For better interoperability with other applications, it is recommended
1868 * that for any URIs that can be opened, you also support queries on them
1869 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1870 * You may also want to support other common columns if you have additional meta-data
1871 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1872 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1873 *
1874 * @param uri The data in the content provider being queried.
1875 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001876 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001877 * requirements; in this case the content provider will pick its best
1878 * type matching the pattern.
1879 * @param opts Additional options from the client. The definitions of
1880 * these are specific to the content provider being called.
1881 * @param signal A signal to cancel the operation in progress, or
1882 * {@code null} if none. For example, if you are downloading a
1883 * file from the network to service a "rw" mode request, you
1884 * should periodically call
1885 * {@link CancellationSignal#throwIfCanceled()} to check whether
1886 * the client has canceled the request and abort the download.
1887 *
1888 * @return Returns a new AssetFileDescriptor from which the client can
1889 * read data of the desired type.
1890 *
1891 * @throws FileNotFoundException Throws FileNotFoundException if there is
1892 * no file associated with the given URI or the mode is invalid.
1893 * @throws SecurityException Throws SecurityException if the caller does
1894 * not have permission to access the data.
1895 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1896 * content provider does not support the requested MIME type.
1897 *
1898 * @see #getStreamTypes(Uri, String)
1899 * @see #openAssetFile(Uri, String)
1900 * @see ClipDescription#compareMimeTypes(String, String)
1901 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001902 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1903 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1904 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001905 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1906 }
1907
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001908 /**
1909 * Interface to write a stream of data to a pipe. Use with
1910 * {@link ContentProvider#openPipeHelper}.
1911 */
1912 public interface PipeDataWriter<T> {
1913 /**
1914 * Called from a background thread to stream data out to a pipe.
1915 * Note that the pipe is blocking, so this thread can block on
1916 * writes for an arbitrary amount of time if the client is slow
1917 * at reading.
1918 *
1919 * @param output The pipe where data should be written. This will be
1920 * closed for you upon returning from this function.
1921 * @param uri The URI whose data is to be written.
1922 * @param mimeType The desired type of data to be written.
1923 * @param opts Options supplied by caller.
1924 * @param args Your own custom arguments.
1925 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001926 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1927 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001928 }
1929
1930 /**
1931 * A helper function for implementing {@link #openTypedAssetFile}, for
1932 * creating a data pipe and background thread allowing you to stream
1933 * generated data back to the client. This function returns a new
1934 * ParcelFileDescriptor that should be returned to the caller (the caller
1935 * is responsible for closing it).
1936 *
1937 * @param uri The URI whose data is to be written.
1938 * @param mimeType The desired type of data to be written.
1939 * @param opts Options supplied by caller.
1940 * @param args Your own custom arguments.
1941 * @param func Interface implementing the function that will actually
1942 * stream the data.
1943 * @return Returns a new ParcelFileDescriptor holding the read side of
1944 * the pipe. This should be returned to the caller for reading; the caller
1945 * is responsible for closing it when done.
1946 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001947 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1948 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1949 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001950 try {
1951 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1952
1953 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1954 @Override
1955 protected Object doInBackground(Object... params) {
1956 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1957 try {
1958 fds[1].close();
1959 } catch (IOException e) {
1960 Log.w(TAG, "Failure closing pipe", e);
1961 }
1962 return null;
1963 }
1964 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001965 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001966
1967 return fds[0];
1968 } catch (IOException e) {
1969 throw new FileNotFoundException("failure making pipe");
1970 }
1971 }
1972
1973 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 * Returns true if this instance is a temporary content provider.
1975 * @return true if this instance is a temporary content provider
1976 */
1977 protected boolean isTemporary() {
1978 return false;
1979 }
1980
1981 /**
1982 * Returns the Binder object for this provider.
1983 *
1984 * @return the Binder object for this provider
1985 * @hide
1986 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001987 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 public IContentProvider getIContentProvider() {
1989 return mTransport;
1990 }
1991
1992 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001993 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1994 * when directly instantiating the provider for testing.
1995 * @hide
1996 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001997 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001998 public void attachInfoForTesting(Context context, ProviderInfo info) {
1999 attachInfo(context, info, true);
2000 }
2001
2002 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 * After being instantiated, this is called to tell the content provider
2004 * about itself.
2005 *
2006 * @param context The context this provider is running in
2007 * @param info Registered information about this content provider
2008 */
2009 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002010 attachInfo(context, info, false);
2011 }
2012
2013 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002014 mNoPerms = testing;
2015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 /*
2017 * Only allow it to be set once, so after the content service gives
2018 * this to us clients can't change it.
2019 */
2020 if (mContext == null) {
2021 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002022 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002023 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2024 Context.APP_OPS_SERVICE);
2025 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002026 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 if (info != null) {
2028 setReadPermission(info.readPermission);
2029 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002030 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002031 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002032 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002033 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
2035 ContentProvider.this.onCreate();
2036 }
2037 }
Fred Quintanace31b232009-05-04 16:01:15 -07002038
2039 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002040 * Override this to handle requests to perform a batch of operations, or the
2041 * default implementation will iterate over the operations and call
2042 * {@link ContentProviderOperation#apply} on each of them.
2043 * If all calls to {@link ContentProviderOperation#apply} succeed
2044 * then a {@link ContentProviderResult} array with as many
2045 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002046 * fail, it is up to the implementation how many of the others take effect.
2047 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002048 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2049 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002050 *
Fred Quintanace31b232009-05-04 16:01:15 -07002051 * @param operations the operations to apply
2052 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002053 * @throws OperationApplicationException thrown if any operation fails.
2054 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002055 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002056 public @NonNull ContentProviderResult[] applyBatch(
2057 @NonNull ArrayList<ContentProviderOperation> operations)
2058 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002059 final int numOperations = operations.size();
2060 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2061 for (int i = 0; i < numOperations; i++) {
2062 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002063 }
2064 return results;
2065 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002066
2067 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002068 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002069 * interfaces that are cheaper and/or unnatural for a table-like
2070 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002071 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002072 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2073 * on this entry into the content provider besides the basic ability for the application
2074 * to get access to the provider at all. For example, it has no idea whether the call
2075 * being executed may read or write data in the provider, so can't enforce those
2076 * individual permissions. Any implementation of this method <strong>must</strong>
2077 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2078 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002079 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2080 * @param arg provider-defined String argument. May be {@code null}.
2081 * @param extras provider-defined Bundle argument. May be {@code null}.
2082 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002083 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002084 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002085 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2086 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002087 return null;
2088 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002089
2090 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002091 * Implement this to shut down the ContentProvider instance. You can then
2092 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002093 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002094 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002095 * Android normally handles ContentProvider startup and shutdown
2096 * automatically. You do not need to start up or shut down a
2097 * ContentProvider. When you invoke a test method on a ContentProvider,
2098 * however, a ContentProvider instance is started and keeps running after
2099 * the test finishes, even if a succeeding test instantiates another
2100 * ContentProvider. A conflict develops because the two instances are
2101 * usually running against the same underlying data source (for example, an
2102 * sqlite database).
2103 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002104 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002105 * Implementing shutDown() avoids this conflict by providing a way to
2106 * terminate the ContentProvider. This method can also prevent memory leaks
2107 * from multiple instantiations of the ContentProvider, and it can ensure
2108 * unit test isolation by allowing you to completely clean up the test
2109 * fixture before moving on to the next test.
2110 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002111 */
2112 public void shutdown() {
2113 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2114 "connections are gracefully shutdown");
2115 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002116
2117 /**
2118 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002119 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002120 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002121 * @param fd The raw file descriptor that the dump is being sent to.
2122 * @param writer The PrintWriter to which you should dump your state. This will be
2123 * closed for you after you return.
2124 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002125 */
2126 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2127 writer.println("nothing to dump");
2128 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002129
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002130 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002131 @VisibleForTesting
2132 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002133 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002134 if (!mSingleUser) {
2135 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2136 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2137 throw new SecurityException("trying to query a ContentProvider in user "
2138 + mContext.getUserId() + " with a uri belonging to user " + userId);
2139 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002140 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002141 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2142 String message = "The authority of the uri " + uri + " does not match the one of the "
2143 + "contentProvider: ";
2144 if (mAuthority != null) {
2145 message += mAuthority;
2146 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002147 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002148 }
2149 throw new SecurityException(message);
2150 }
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002151
2152 // Normalize the path by removing any empty path segments, which can be
2153 // a source of security issues.
2154 final String encodedPath = uri.getEncodedPath();
2155 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002156 final Uri normalized = uri.buildUpon()
2157 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2158 Log.w(TAG, "Normalized " + uri + " to " + normalized
2159 + " to avoid possible security issues");
2160 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002161 } else {
2162 return uri;
2163 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002164 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002165
2166 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002167 private Uri maybeGetUriWithoutUserId(Uri uri) {
2168 if (mSingleUser) {
2169 return uri;
2170 }
2171 return getUriWithoutUserId(uri);
2172 }
2173
2174 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002175 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2176 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002177 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002178 if (end == -1) return defaultUserId;
2179 String userIdString = auth.substring(0, end);
2180 try {
2181 return Integer.parseInt(userIdString);
2182 } catch (NumberFormatException e) {
2183 Log.w(TAG, "Error parsing userId.", e);
2184 return UserHandle.USER_NULL;
2185 }
2186 }
2187
2188 /** @hide */
2189 public static int getUserIdFromAuthority(String auth) {
2190 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2191 }
2192
2193 /** @hide */
2194 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2195 if (uri == null) return defaultUserId;
2196 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2197 }
2198
2199 /** @hide */
2200 public static int getUserIdFromUri(Uri uri) {
2201 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2202 }
2203
2204 /**
2205 * Removes userId part from authority string. Expects format:
2206 * userId@some.authority
2207 * If there is no userId in the authority, it symply returns the argument
2208 * @hide
2209 */
2210 public static String getAuthorityWithoutUserId(String auth) {
2211 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002212 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002213 return auth.substring(end+1);
2214 }
2215
2216 /** @hide */
2217 public static Uri getUriWithoutUserId(Uri uri) {
2218 if (uri == null) return null;
2219 Uri.Builder builder = uri.buildUpon();
2220 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2221 return builder.build();
2222 }
2223
2224 /** @hide */
2225 public static boolean uriHasUserId(Uri uri) {
2226 if (uri == null) return false;
2227 return !TextUtils.isEmpty(uri.getUserInfo());
2228 }
2229
2230 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002231 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002232 public static Uri maybeAddUserId(Uri uri, int userId) {
2233 if (uri == null) return null;
2234 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002235 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002236 if (!uriHasUserId(uri)) {
2237 //We don't add the user Id if there's already one
2238 Uri.Builder builder = uri.buildUpon();
2239 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2240 return builder.build();
2241 }
2242 }
2243 return uri;
2244 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002245}