blob: bd1e6a46280522e41e9367bac11e62f7530901f3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Nicolas Prevot504d78e2014-06-26 10:07:33 +010019import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070020import static android.app.AppOpsManager.MODE_ALLOWED;
21import static android.app.AppOpsManager.MODE_ERRORED;
22import static android.app.AppOpsManager.MODE_IGNORED;
23import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060024import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070025
Jeff Sharkey673db442015-06-11 19:30:57 -070026import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080027import android.annotation.Nullable;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010028import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080029import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070030import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.pm.ProviderInfo;
32import android.content.res.AssetFileDescriptor;
33import android.content.res.Configuration;
34import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070035import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.database.SQLException;
37import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070038import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010040import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080041import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070042import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080043import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070044import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070046import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080047import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060048import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060050import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010051import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070052import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053
54import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080055import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070057import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080058import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070059import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080060import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
62/**
63 * Content providers are one of the primary building blocks of Android applications, providing
64 * content to applications. They encapsulate data and provide it to applications through the single
65 * {@link ContentResolver} interface. A content provider is only required if you need to share
66 * data between multiple applications. For example, the contacts data is used by multiple
67 * applications and must be stored in a content provider. If you don't need to share data amongst
68 * multiple applications you can use a database directly via
69 * {@link android.database.sqlite.SQLiteDatabase}.
70 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * <p>When a request is made via
72 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
73 * request to the content provider registered with the authority. The content provider can interpret
74 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
75 * URIs.</p>
76 *
77 * <p>The primary methods that need to be implemented are:
78 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070079 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 * <li>{@link #query} which returns data to the caller</li>
81 * <li>{@link #insert} which inserts new data into the content provider</li>
82 * <li>{@link #update} which updates existing data in the content provider</li>
83 * <li>{@link #delete} which deletes data from the content provider</li>
84 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
85 * </ul></p>
86 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070087 * <p class="caution">Data access methods (such as {@link #insert} and
88 * {@link #update}) may be called from many threads at once, and must be thread-safe.
89 * Other methods (such as {@link #onCreate}) are only called from the application
90 * main thread, and must avoid performing lengthy operations. See the method
91 * descriptions for their expected thread behavior.</p>
92 *
93 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
94 * ContentProvider instance, so subclasses don't have to worry about the details of
95 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070096 *
97 * <div class="special reference">
98 * <h3>Developer Guides</h3>
99 * <p>For more information about using content providers, read the
100 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
101 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700103public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800104
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700105 private static final String TAG = "ContentProvider";
106
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900107 /*
108 * Note: if you add methods to ContentProvider, you must add similar methods to
109 * MockContentProvider.
110 */
111
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100112 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700114 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100115
116 // Since most Providers have only one authority, we keep both a String and a String[] to improve
117 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100118 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100119 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100120 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100121 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100122 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100124 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100126 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700127 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700128 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800129 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700130 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Steve McKayea93fe72016-12-02 11:35:35 -0800132 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private Transport mTransport = new Transport();
135
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700136 /**
137 * Construct a ContentProvider instance. Content providers must be
138 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
139 * in the manifest</a>, accessed with {@link ContentResolver}, and created
140 * automatically by the system, so applications usually do not create
141 * ContentProvider instances directly.
142 *
143 * <p>At construction time, the object is uninitialized, and most fields and
144 * methods are unavailable. Subclasses should initialize themselves in
145 * {@link #onCreate}, not the constructor.
146 *
147 * <p>Content providers are created on the application main thread at
148 * application launch time. The constructor must not perform lengthy
149 * operations, or application startup will be delayed.
150 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900151 public ContentProvider() {
152 }
153
154 /**
155 * Constructor just for mocking.
156 *
157 * @param context A Context object which should be some mock instance (like the
158 * instance of {@link android.test.mock.MockContext}).
159 * @param readPermission The read permision you want this instance should have in the
160 * test, which is available via {@link #getReadPermission()}.
161 * @param writePermission The write permission you want this instance should have
162 * in the test, which is available via {@link #getWritePermission()}.
163 * @param pathPermissions The PathPermissions you want this instance should have
164 * in the test, which is available via {@link #getPathPermissions()}.
165 * @hide
166 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100167 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900168 public ContentProvider(
169 Context context,
170 String readPermission,
171 String writePermission,
172 PathPermission[] pathPermissions) {
173 mContext = context;
174 mReadPermission = readPermission;
175 mWritePermission = writePermission;
176 mPathPermissions = pathPermissions;
177 }
178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 /**
180 * Given an IContentProvider, try to coerce it back to the real
181 * ContentProvider object if it is running in the local process. This can
182 * be used if you know you are running in the same process as a provider,
183 * and want to get direct access to its implementation details. Most
184 * clients should not nor have a reason to use it.
185 *
186 * @param abstractInterface The ContentProvider interface that is to be
187 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800188 * @return If the IContentProvider is non-{@code null} and local, returns its actual
189 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 * @hide
191 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100192 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 public static ContentProvider coerceToLocalContentProvider(
194 IContentProvider abstractInterface) {
195 if (abstractInterface instanceof Transport) {
196 return ((Transport)abstractInterface).getContentProvider();
197 }
198 return null;
199 }
200
201 /**
202 * Binder object that deals with remoting.
203 *
204 * @hide
205 */
206 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800207 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800208 int mReadOp = AppOpsManager.OP_NONE;
209 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 ContentProvider getContentProvider() {
212 return ContentProvider.this;
213 }
214
Jeff Brownd2183652011-10-09 12:39:53 -0700215 @Override
216 public String getProviderName() {
217 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 }
219
Jeff Brown75ea64f2012-01-25 19:37:13 -0800220 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800221 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
222 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100223 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100224 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800225 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700226 // The caller has no access to the data, so return an empty cursor with
227 // the columns in the requested order. The caller may ask for an invalid
228 // column and we would not catch that but this is not a problem in practice.
229 // We do not call ContentProvider#query with a modified where clause since
230 // the implementation is not guaranteed to be backed by a SQL database, hence
231 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700232 if (projection != null) {
233 return new MatrixCursor(projection, 0);
234 }
235
236 // Null projection means all columns but we have no idea which they are.
237 // However, the caller may be expecting to access them my index. Hence,
238 // we have to execute the query as if allowed to get a cursor with the
239 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700240 Cursor cursor;
241 final String original = setCallingPackage(callingPkg);
242 try {
243 cursor = ContentProvider.this.query(
244 uri, projection, queryArgs,
245 CancellationSignal.fromTransport(cancellationSignal));
246 } finally {
247 setCallingPackage(original);
248 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700249 if (cursor == null) {
250 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700251 }
252
253 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700254 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800255 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600256 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700257 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700258 try {
259 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800260 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700261 CancellationSignal.fromTransport(cancellationSignal));
262 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700263 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600264 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 }
267
Jeff Brown75ea64f2012-01-25 19:37:13 -0800268 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700270 // getCallingPackage() isn't available in getType(), as the javadoc states.
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100271 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100272 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600273 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
274 try {
275 return ContentProvider.this.getType(uri);
276 } finally {
277 Trace.traceEnd(TRACE_TAG_DATABASE);
278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
280
Jeff Brown75ea64f2012-01-25 19:37:13 -0800281 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800282 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100283 validateIncomingUri(uri);
284 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100285 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800286 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700287 final String original = setCallingPackage(callingPkg);
288 try {
289 return rejectInsert(uri, initialValues);
290 } finally {
291 setCallingPackage(original);
292 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800293 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600294 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700295 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700296 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100297 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700298 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700299 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600300 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 }
303
Jeff Brown75ea64f2012-01-25 19:37:13 -0800304 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800305 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100306 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100307 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800308 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800309 return 0;
310 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600311 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700312 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700313 try {
314 return ContentProvider.this.bulkInsert(uri, initialValues);
315 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700316 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600317 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 }
320
Jeff Brown75ea64f2012-01-25 19:37:13 -0800321 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800322 public ContentProviderResult[] applyBatch(String callingPkg,
323 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700324 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100325 int numOperations = operations.size();
326 final int[] userIds = new int[numOperations];
327 for (int i = 0; i < numOperations; i++) {
328 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100329 Uri uri = operation.getUri();
330 validateIncomingUri(uri);
331 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100332 if (userIds[i] != UserHandle.USER_CURRENT) {
333 // Removing the user id from the uri.
334 operation = new ContentProviderOperation(operation, true);
335 operations.set(i, operation);
336 }
Fred Quintana89437372009-05-15 15:10:40 -0700337 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800338 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800339 != AppOpsManager.MODE_ALLOWED) {
340 throw new OperationApplicationException("App op not allowed", 0);
341 }
Fred Quintana89437372009-05-15 15:10:40 -0700342 }
Fred Quintana89437372009-05-15 15:10:40 -0700343 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800344 if (enforceWritePermission(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 }
349 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600350 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700351 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700352 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100353 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800354 if (results != null) {
355 for (int i = 0; i < results.length ; i++) {
356 if (userIds[i] != UserHandle.USER_CURRENT) {
357 // Adding the userId to the uri.
358 results[i] = new ContentProviderResult(results[i], userIds[i]);
359 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100360 }
361 }
362 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700363 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700364 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600365 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700366 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700367 }
368
Jeff Brown75ea64f2012-01-25 19:37:13 -0800369 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800370 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100371 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100372 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800373 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800374 return 0;
375 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600376 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700377 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700378 try {
379 return ContentProvider.this.delete(uri, selection, selectionArgs);
380 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700381 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600382 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 }
385
Jeff Brown75ea64f2012-01-25 19:37:13 -0800386 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800387 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100389 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100390 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800391 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800392 return 0;
393 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600394 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700395 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700396 try {
397 return ContentProvider.this.update(uri, values, selection, selectionArgs);
398 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700399 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600400 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 }
403
Jeff Brown75ea64f2012-01-25 19:37:13 -0800404 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700405 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800406 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
407 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100408 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100409 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800410 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600411 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700412 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700413 try {
414 return ContentProvider.this.openFile(
415 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
416 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700417 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600418 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 }
421
Jeff Brown75ea64f2012-01-25 19:37:13 -0800422 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700423 public AssetFileDescriptor openAssetFile(
424 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100426 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100427 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800428 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600429 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700430 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700431 try {
432 return ContentProvider.this.openAssetFile(
433 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
434 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700435 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600436 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 }
439
Jeff Brown75ea64f2012-01-25 19:37:13 -0800440 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800441 public Bundle call(
442 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600443 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600444 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700445 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700446 try {
447 return ContentProvider.this.call(method, arg, extras);
448 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700449 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600450 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700451 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800452 }
453
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700454 @Override
455 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700456 // getCallingPackage() isn't available in getType(), as the javadoc states.
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100457 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100458 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600459 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
460 try {
461 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
462 } finally {
463 Trace.traceEnd(TRACE_TAG_DATABASE);
464 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700465 }
466
467 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800468 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700469 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600470 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100471 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100472 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800473 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600474 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700475 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700476 try {
477 return ContentProvider.this.openTypedAssetFile(
478 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
479 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700480 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600481 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700482 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700483 }
484
Jeff Brown75ea64f2012-01-25 19:37:13 -0800485 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700486 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800487 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800488 }
489
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700490 @Override
491 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100492 validateIncomingUri(uri);
493 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100494 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800495 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700496 return null;
497 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600498 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700499 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700500 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100501 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700502 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700503 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600504 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700505 }
506 }
507
508 @Override
509 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100510 validateIncomingUri(uri);
511 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100512 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800513 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700514 return null;
515 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600516 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700517 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700518 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100519 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700520 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700521 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600522 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700523 }
524 }
525
Ben Lin1cf454f2016-11-10 13:50:54 -0800526 @Override
527 public boolean refresh(String callingPkg, Uri uri, Bundle args,
528 ICancellationSignal cancellationSignal) throws RemoteException {
529 validateIncomingUri(uri);
530 uri = getUriWithoutUserId(uri);
531 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
532 return false;
533 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600534 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800535 final String original = setCallingPackage(callingPkg);
536 try {
537 return ContentProvider.this.refresh(uri, args,
538 CancellationSignal.fromTransport(cancellationSignal));
539 } finally {
540 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600541 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800542 }
543 }
544
Dianne Hackbornff170242014-11-19 10:59:01 -0800545 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
546 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800547 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800548 if (enforceWritePermission(callingPkg, uri, callerToken)
549 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800550 throw new FileNotFoundException("App op not allowed");
551 }
552 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800553 if (enforceReadPermission(callingPkg, uri, callerToken)
554 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800555 throw new FileNotFoundException("App op not allowed");
556 }
557 }
558 }
559
Dianne Hackbornff170242014-11-19 10:59:01 -0800560 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
561 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700562 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
563 if (mode != MODE_ALLOWED) {
564 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800565 }
Svet Ganov99b60432015-06-27 13:15:22 -0700566
567 if (mReadOp != AppOpsManager.OP_NONE) {
568 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
569 }
570
Dianne Hackborn35654b62013-01-14 17:38:02 -0800571 return AppOpsManager.MODE_ALLOWED;
572 }
573
Dianne Hackbornff170242014-11-19 10:59:01 -0800574 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
575 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700576 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
577 if (mode != MODE_ALLOWED) {
578 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800579 }
Svet Ganov99b60432015-06-27 13:15:22 -0700580
581 if (mWriteOp != AppOpsManager.OP_NONE) {
582 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
583 }
584
Dianne Hackborn35654b62013-01-14 17:38:02 -0800585 return AppOpsManager.MODE_ALLOWED;
586 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700587 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800588
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100589 boolean checkUser(int pid, int uid, Context context) {
590 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700591 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100592 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
593 == PERMISSION_GRANTED;
594 }
595
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700596 /**
597 * Verify that calling app holds both the given permission and any app-op
598 * associated with that permission.
599 */
600 private int checkPermissionAndAppOp(String permission, String callingPkg,
601 IBinder callerToken) {
602 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
603 callerToken) != PERMISSION_GRANTED) {
604 return MODE_ERRORED;
605 }
606
607 final int permOp = AppOpsManager.permissionToOpCode(permission);
608 if (permOp != AppOpsManager.OP_NONE) {
609 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
610 }
611
612 return MODE_ALLOWED;
613 }
614
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700615 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700616 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800617 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700618 final Context context = getContext();
619 final int pid = Binder.getCallingPid();
620 final int uid = Binder.getCallingUid();
621 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700622 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700623
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700624 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700625 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700626 }
627
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100628 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700629 final String componentPerm = getReadPermission();
630 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700631 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
632 if (mode == MODE_ALLOWED) {
633 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700634 } else {
635 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700636 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700637 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700638 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700639
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700640 // track if unprotected read is allowed; any denied
641 // <path-permission> below removes this ability
642 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700643
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700644 final PathPermission[] pps = getPathPermissions();
645 if (pps != null) {
646 final String path = uri.getPath();
647 for (PathPermission pp : pps) {
648 final String pathPerm = pp.getReadPermission();
649 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700650 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
651 if (mode == MODE_ALLOWED) {
652 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700653 } else {
654 // any denied <path-permission> means we lose
655 // default <provider> access.
656 allowDefaultRead = false;
657 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700658 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700659 }
660 }
661 }
662 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700663
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700664 // if we passed <path-permission> checks above, and no default
665 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700666 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700668
669 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800670 final int callingUserId = UserHandle.getUserId(uid);
671 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
672 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800673 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
674 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700675 return MODE_ALLOWED;
676 }
677
678 // If the worst denial we found above was ignored, then pass that
679 // ignored through; otherwise we assume it should be a real error below.
680 if (strongestMode == MODE_IGNORED) {
681 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700682 }
683
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600684 final String suffix;
685 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
686 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
687 } else if (mExported) {
688 suffix = " requires " + missingPerm + ", or grantUriPermission()";
689 } else {
690 suffix = " requires the provider be exported, or grantUriPermission()";
691 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700692 throw new SecurityException("Permission Denial: reading "
693 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600694 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700695 }
696
697 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700698 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800699 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700700 final Context context = getContext();
701 final int pid = Binder.getCallingPid();
702 final int uid = Binder.getCallingUid();
703 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700704 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700705
706 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700707 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700708 }
709
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100710 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700711 final String componentPerm = getWritePermission();
712 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700713 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
714 if (mode == MODE_ALLOWED) {
715 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700716 } else {
717 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700718 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700719 }
720 }
721
722 // track if unprotected write is allowed; any denied
723 // <path-permission> below removes this ability
724 boolean allowDefaultWrite = (componentPerm == null);
725
726 final PathPermission[] pps = getPathPermissions();
727 if (pps != null) {
728 final String path = uri.getPath();
729 for (PathPermission pp : pps) {
730 final String pathPerm = pp.getWritePermission();
731 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700732 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
733 if (mode == MODE_ALLOWED) {
734 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700735 } else {
736 // any denied <path-permission> means we lose
737 // default <provider> access.
738 allowDefaultWrite = false;
739 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700740 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700741 }
742 }
743 }
744 }
745
746 // if we passed <path-permission> checks above, and no default
747 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700748 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700749 }
750
751 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800752 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
753 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700754 return MODE_ALLOWED;
755 }
756
757 // If the worst denial we found above was ignored, then pass that
758 // ignored through; otherwise we assume it should be a real error below.
759 if (strongestMode == MODE_IGNORED) {
760 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700761 }
762
763 final String failReason = mExported
764 ? " requires " + missingPerm + ", or grantUriPermission()"
765 : " requires the provider be exported, or grantUriPermission()";
766 throw new SecurityException("Permission Denial: writing "
767 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
768 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700772 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800773 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 * constructor.
775 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700776 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 return mContext;
778 }
779
780 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700781 * Set the calling package, returning the current value (or {@code null})
782 * which can be used later to restore the previous state.
783 */
784 private String setCallingPackage(String callingPackage) {
785 final String original = mCallingPackage.get();
786 mCallingPackage.set(callingPackage);
787 return original;
788 }
789
790 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700791 * Return the package name of the caller that initiated the request being
792 * processed on the current thread. The returned package will have been
793 * verified to belong to the calling UID. Returns {@code null} if not
794 * currently processing a request.
795 * <p>
796 * This will always return {@code null} when processing
797 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
798 *
799 * @see Binder#getCallingUid()
800 * @see Context#grantUriPermission(String, Uri, int)
801 * @throws SecurityException if the calling package doesn't belong to the
802 * calling UID.
803 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700804 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700805 final String pkg = mCallingPackage.get();
806 if (pkg != null) {
807 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
808 }
809 return pkg;
810 }
811
812 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100813 * Change the authorities of the ContentProvider.
814 * This is normally set for you from its manifest information when the provider is first
815 * created.
816 * @hide
817 * @param authorities the semi-colon separated authorities of the ContentProvider.
818 */
819 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100820 if (authorities != null) {
821 if (authorities.indexOf(';') == -1) {
822 mAuthority = authorities;
823 mAuthorities = null;
824 } else {
825 mAuthority = null;
826 mAuthorities = authorities.split(";");
827 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100828 }
829 }
830
831 /** @hide */
832 protected final boolean matchesOurAuthorities(String authority) {
833 if (mAuthority != null) {
834 return mAuthority.equals(authority);
835 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100836 if (mAuthorities != null) {
837 int length = mAuthorities.length;
838 for (int i = 0; i < length; i++) {
839 if (mAuthorities[i].equals(authority)) return true;
840 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100841 }
842 return false;
843 }
844
845
846 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 * Change the permission required to read data from the content
848 * provider. This is normally set for you from its manifest information
849 * when the provider is first created.
850 *
851 * @param permission Name of the permission required for read-only access.
852 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700853 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 mReadPermission = permission;
855 }
856
857 /**
858 * Return the name of the permission required for read-only access to
859 * this content provider. This method can be called from multiple
860 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800861 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
862 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700864 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 return mReadPermission;
866 }
867
868 /**
869 * Change the permission required to read and write data in the content
870 * provider. This is normally set for you from its manifest information
871 * when the provider is first created.
872 *
873 * @param permission Name of the permission required for read/write access.
874 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700875 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 mWritePermission = permission;
877 }
878
879 /**
880 * Return the name of the permission required for read/write access to
881 * this content provider. This method can be called from multiple
882 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800883 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
884 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700886 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 return mWritePermission;
888 }
889
890 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700891 * Change the path-based permission required to read and/or write data in
892 * the content provider. This is normally set for you from its manifest
893 * information when the provider is first created.
894 *
895 * @param permissions Array of path permission descriptions.
896 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700897 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700898 mPathPermissions = permissions;
899 }
900
901 /**
902 * Return the path-based permissions required for read and/or write access to
903 * this content provider. This method can be called from multiple
904 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800905 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
906 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700907 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700908 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700909 return mPathPermissions;
910 }
911
Dianne Hackborn35654b62013-01-14 17:38:02 -0800912 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100913 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800914 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800915 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800916 mTransport.mReadOp = readOp;
917 mTransport.mWriteOp = writeOp;
918 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800919 }
920
Dianne Hackborn961321f2013-02-05 17:22:41 -0800921 /** @hide */
922 public AppOpsManager getAppOpsManager() {
923 return mTransport.mAppOpsManager;
924 }
925
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700926 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700927 * Implement this to initialize your content provider on startup.
928 * This method is called for all registered content providers on the
929 * application main thread at application launch time. It must not perform
930 * lengthy operations, or application startup will be delayed.
931 *
932 * <p>You should defer nontrivial initialization (such as opening,
933 * upgrading, and scanning databases) until the content provider is used
934 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
935 * keeps application startup fast, avoids unnecessary work if the provider
936 * turns out not to be needed, and stops database errors (such as a full
937 * disk) from halting application launch.
938 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700939 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700940 * is a helpful utility class that makes it easy to manage databases,
941 * and will automatically defer opening until first use. If you do use
942 * SQLiteOpenHelper, make sure to avoid calling
943 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
944 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
945 * from this method. (Instead, override
946 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
947 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 *
949 * @return true if the provider was successfully loaded, false otherwise
950 */
951 public abstract boolean onCreate();
952
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700953 /**
954 * {@inheritDoc}
955 * This method is always called on the application main thread, and must
956 * not perform lengthy operations.
957 *
958 * <p>The default content provider implementation does nothing.
959 * Override this method to take appropriate action.
960 * (Content providers do not usually care about things like screen
961 * orientation, but may want to know about locale changes.)
962 */
Steve McKayea93fe72016-12-02 11:35:35 -0800963 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 public void onConfigurationChanged(Configuration newConfig) {
965 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700966
967 /**
968 * {@inheritDoc}
969 * This method is always called on the application main thread, and must
970 * not perform lengthy operations.
971 *
972 * <p>The default content provider implementation does nothing.
973 * Subclasses may override this method to take appropriate action.
974 */
Steve McKayea93fe72016-12-02 11:35:35 -0800975 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 public void onLowMemory() {
977 }
978
Steve McKayea93fe72016-12-02 11:35:35 -0800979 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700980 public void onTrimMemory(int level) {
981 }
982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700984 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800985 *
986 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
987 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
988 * implementation of this method.
989 *
990 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800991 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
992 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 * <p>
994 * Example client call:<p>
995 * <pre>// Request a specific record.
996 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000997 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 projection, // Which columns to return.
999 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001000 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 People.NAME + " ASC"); // Sort order.</pre>
1002 * Example implementation:<p>
1003 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1004 // proper SQL syntax for us.
1005 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1006
1007 // Set the table we're querying.
1008 qBuilder.setTables(DATABASE_TABLE_NAME);
1009
1010 // If the query ends in a specific record number, we're
1011 // being asked for a specific record, so set the
1012 // WHERE clause in our query.
1013 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1014 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1015 }
1016
1017 // Make the query.
1018 Cursor c = qBuilder.query(mDb,
1019 projection,
1020 selection,
1021 selectionArgs,
1022 groupBy,
1023 having,
1024 sortOrder);
1025 c.setNotificationUri(getContext().getContentResolver(), uri);
1026 return c;</pre>
1027 *
1028 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001029 * if the client is requesting a specific record, the URI will end in a record number
1030 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1031 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001033 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001035 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001036 * @param selectionArgs You may include ?s in selection, which will be replaced by
1037 * the values from selectionArgs, in order that they appear in the selection.
1038 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001040 * If {@code null} then the provider is free to define the sort order.
1041 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001043 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1044 @Nullable String selection, @Nullable String[] selectionArgs,
1045 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046
Fred Quintana5bba6322009-10-05 14:21:12 -07001047 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001048 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001049 *
1050 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1051 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1052 *
1053 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001054 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1055 * and Threads</a>.
1056 * <p>
1057 * Example client call:<p>
1058 * <pre>// Request a specific record.
1059 * Cursor managedCursor = managedQuery(
1060 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1061 projection, // Which columns to return.
1062 null, // WHERE clause.
1063 null, // WHERE clause value substitution
1064 People.NAME + " ASC"); // Sort order.</pre>
1065 * Example implementation:<p>
1066 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1067 // proper SQL syntax for us.
1068 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1069
1070 // Set the table we're querying.
1071 qBuilder.setTables(DATABASE_TABLE_NAME);
1072
1073 // If the query ends in a specific record number, we're
1074 // being asked for a specific record, so set the
1075 // WHERE clause in our query.
1076 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1077 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1078 }
1079
1080 // Make the query.
1081 Cursor c = qBuilder.query(mDb,
1082 projection,
1083 selection,
1084 selectionArgs,
1085 groupBy,
1086 having,
1087 sortOrder);
1088 c.setNotificationUri(getContext().getContentResolver(), uri);
1089 return c;</pre>
1090 * <p>
1091 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001092 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1093 * signal to ensure correct operation on older versions of the Android Framework in
1094 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001095 *
1096 * @param uri The URI to query. This will be the full URI sent by the client;
1097 * if the client is requesting a specific record, the URI will end in a record number
1098 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1099 * that _id value.
1100 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001101 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001102 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001103 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001104 * @param selectionArgs You may include ?s in selection, which will be replaced by
1105 * the values from selectionArgs, in order that they appear in the selection.
1106 * The values will be bound as Strings.
1107 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001108 * If {@code null} then the provider is free to define the sort order.
1109 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001110 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001111 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001112 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001113 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001114 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1115 @Nullable String selection, @Nullable String[] selectionArgs,
1116 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001117 return query(uri, projection, selection, selectionArgs, sortOrder);
1118 }
1119
1120 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001121 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1122 * Arguments may include traditional SQL style query arguments. When present these
1123 * should be handled according to the contract established in
1124 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1125 *
1126 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001127 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1128 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1129 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001130 *
Steve McKay76b27702017-04-24 12:07:53 -07001131 * <p>This method can be called from multiple threads, as described in
1132 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1133 * and Threads</a>.
1134 *
1135 * <p>
1136 * Example client call:<p>
1137 * <pre>// Request 20 records starting at row index 30.
1138 Bundle queryArgs = new Bundle();
1139 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1140 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1141
1142 Cursor cursor = getContentResolver().query(
1143 contentUri, // Content Uri is specific to individual content providers.
1144 projection, // String[] describing which columns to return.
1145 queryArgs, // Query arguments.
1146 null); // Cancellation signal.</pre>
1147 *
1148 * Example implementation:<p>
1149 * <pre>
1150
1151 int recordsetSize = 0x1000; // Actual value is implementation specific.
1152 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1153
1154 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1155 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1156
1157 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1158
1159 // Calculate the number of items to include in the cursor.
1160 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1161
1162 // Build the paged result set....
1163 for (int i = offset; i < offset + numItems; i++) {
1164 // populate row from your data.
1165 }
1166
1167 Bundle extras = new Bundle();
1168 c.setExtras(extras);
1169
1170 // Any QUERY_ARG_* key may be included if honored.
1171 // In an actual implementation, include only keys that are both present in queryArgs
1172 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1173 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1174 // then QUERY_ARG_OFFSET should be omitted.
1175 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1176 ContentResolver.QUERY_ARG_OFFSET,
1177 ContentResolver.QUERY_ARG_LIMIT
1178 });
1179
1180 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1181
1182 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1183
1184 return cursor;</pre>
1185 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001186 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1187 * implementation details.
1188 *
1189 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001190 * @param projection The list of columns to put into the cursor.
1191 * If {@code null} provide a default set of columns.
1192 * @param queryArgs A Bundle containing all additional information necessary for the query.
1193 * Values in the Bundle may include SQL style arguments.
1194 * @param cancellationSignal A signal to cancel the operation in progress,
1195 * or {@code null}.
1196 * @return a Cursor or {@code null}.
1197 */
1198 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1199 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1200 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001201
Steve McKayd7ece9f2017-01-12 16:59:59 -08001202 // if client doesn't supply an SQL sort order argument, attempt to build one from
1203 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001204 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001205 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1206 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1207 }
1208
Steve McKayea93fe72016-12-02 11:35:35 -08001209 return query(
1210 uri,
1211 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001212 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1213 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1214 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001215 cancellationSignal);
1216 }
1217
1218 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001219 * Implement this to handle requests for the MIME type of the data at the
1220 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 * <code>vnd.android.cursor.item</code> for a single record,
1222 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001223 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001224 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1225 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001227 * <p>Note that there are no permissions needed for an application to
1228 * access this information; if your content provider requires read and/or
1229 * write permissions, or is not exported, all applications can still call
1230 * this method regardless of their access permissions. This allows them
1231 * to retrieve the MIME type for a URI when dispatching intents.
1232 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001234 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001236 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237
1238 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001239 * Implement this to support canonicalization of URIs that refer to your
1240 * content provider. A canonical URI is one that can be transported across
1241 * devices, backup/restore, and other contexts, and still be able to refer
1242 * to the same data item. Typically this is implemented by adding query
1243 * params to the URI allowing the content provider to verify that an incoming
1244 * canonical URI references the same data as it was originally intended for and,
1245 * if it doesn't, to find that data (if it exists) in the current environment.
1246 *
1247 * <p>For example, if the content provider holds people and a normal URI in it
1248 * is created with a row index into that people database, the cananical representation
1249 * may have an additional query param at the end which specifies the name of the
1250 * person it is intended for. Later calls into the provider with that URI will look
1251 * up the row of that URI's base index and, if it doesn't match or its entry's
1252 * name doesn't match the name in the query param, perform a query on its database
1253 * to find the correct row to operate on.</p>
1254 *
1255 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1256 * URIs (including this one) must perform this verification and recovery of any
1257 * canonical URIs they receive. In addition, you must also implement
1258 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1259 *
1260 * <p>The default implementation of this method returns null, indicating that
1261 * canonical URIs are not supported.</p>
1262 *
1263 * @param url The Uri to canonicalize.
1264 *
1265 * @return Return the canonical representation of <var>url</var>, or null if
1266 * canonicalization of that Uri is not supported.
1267 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001268 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001269 return null;
1270 }
1271
1272 /**
1273 * Remove canonicalization from canonical URIs previously returned by
1274 * {@link #canonicalize}. For example, if your implementation is to add
1275 * a query param to canonicalize a URI, this method can simply trip any
1276 * query params on the URI. The default implementation always returns the
1277 * same <var>url</var> that was passed in.
1278 *
1279 * @param url The Uri to remove any canonicalization from.
1280 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001281 * @return Return the non-canonical representation of <var>url</var>, return
1282 * the <var>url</var> as-is if there is nothing to do, or return null if
1283 * the data identified by the canonical representation can not be found in
1284 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001285 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001286 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001287 return url;
1288 }
1289
1290 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001291 * Implement this to support refresh of content identified by {@code uri}. By default, this
1292 * method returns false; providers who wish to implement this should return true to signal the
1293 * client that the provider has tried refreshing with its own implementation.
1294 * <p>
1295 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1296 * <p>
1297 * Client code should only invoke this method when there is a strong indication (such as a user
1298 * initiated pull to refresh gesture) that the content is stale.
1299 * <p>
1300 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1301 * notifications when content changes.
1302 *
1303 * @param uri The Uri identifying the data to refresh.
1304 * @param args Additional options from the client. The definitions of these are specific to the
1305 * content provider being called.
1306 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1307 * none. For example, if you called refresh on a particular uri, you should call
1308 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1309 * canceled the refresh request.
1310 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001311 */
1312 public boolean refresh(Uri uri, @Nullable Bundle args,
1313 @Nullable CancellationSignal cancellationSignal) {
1314 return false;
1315 }
1316
1317 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001318 * @hide
1319 * Implementation when a caller has performed an insert on the content
1320 * provider, but that call has been rejected for the operation given
1321 * to {@link #setAppOps(int, int)}. The default implementation simply
1322 * returns a dummy URI that is the base URI with a 0 path element
1323 * appended.
1324 */
1325 public Uri rejectInsert(Uri uri, ContentValues values) {
1326 // If not allowed, we need to return some reasonable URI. Maybe the
1327 // content provider should be responsible for this, but for now we
1328 // will just return the base URI with a dummy '0' tagged on to it.
1329 // You shouldn't be able to read if you can't write, anyway, so it
1330 // shouldn't matter much what is returned.
1331 return uri.buildUpon().appendPath("0").build();
1332 }
1333
1334 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001335 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1337 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001338 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001339 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1340 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001341 * @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 -08001342 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001343 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 * @return The URI for the newly inserted item.
1345 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001346 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347
1348 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001349 * Override this to handle requests to insert a set of new rows, or the
1350 * default implementation will iterate over the values and call
1351 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1353 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001354 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001355 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1356 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 *
1358 * @param uri The content:// URI of the insertion request.
1359 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001360 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 * @return The number of values that were inserted.
1362 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001363 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 int numValues = values.length;
1365 for (int i = 0; i < numValues; i++) {
1366 insert(uri, values[i]);
1367 }
1368 return numValues;
1369 }
1370
1371 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001372 * Implement this to handle requests to delete one or more rows.
1373 * The implementation should apply the selection clause when performing
1374 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001375 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001377 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001378 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1379 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 *
1381 * <p>The implementation is responsible for parsing out a row ID at the end
1382 * of the URI, if a specific row is being deleted. That is, the client would
1383 * pass in <code>content://contacts/people/22</code> and the implementation is
1384 * responsible for parsing the record number (22) when creating a SQL statement.
1385 *
1386 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1387 * @param selection An optional restriction to apply to rows when deleting.
1388 * @return The number of rows affected.
1389 * @throws SQLException
1390 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001391 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1392 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393
1394 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001395 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001396 * The implementation should update all rows matching the selection
1397 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1399 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001400 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001401 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1402 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 *
1404 * @param uri The URI to query. This can potentially have a record ID if this
1405 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001406 * @param values A set of column_name/value pairs to update in the database.
1407 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 * @param selection An optional filter to match rows to update.
1409 * @return the number of rows affected.
1410 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001411 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001412 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413
1414 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001415 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001416 * The default implementation always throws {@link FileNotFoundException}.
1417 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001418 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1419 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001420 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001421 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1422 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001423 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 *
1425 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1426 * their responsibility to close it when done. That is, the implementation
1427 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001428 * <p>
1429 * If opened with the exclusive "r" or "w" modes, the returned
1430 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1431 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1432 * supports seeking.
1433 * <p>
1434 * If you need to detect when the returned ParcelFileDescriptor has been
1435 * closed, or if the remote process has crashed or encountered some other
1436 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1437 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1438 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1439 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001440 * <p>
1441 * If you need to return a large file that isn't backed by a real file on
1442 * disk, such as a file on a network share or cloud storage service,
1443 * consider using
1444 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1445 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001447 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1448 * to return the appropriate MIME type for the data returned here with
1449 * the same URI. This will allow intent resolution to automatically determine the data MIME
1450 * type and select the appropriate matching targets as part of its operation.</p>
1451 *
1452 * <p class="note">For better interoperability with other applications, it is recommended
1453 * that for any URIs that can be opened, you also support queries on them
1454 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1455 * You may also want to support other common columns if you have additional meta-data
1456 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1457 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1458 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 * @param uri The URI whose file is to be opened.
1460 * @param mode Access mode for the file. May be "r" for read-only access,
1461 * "rw" for read and write access, or "rwt" for read and write access
1462 * that truncates any existing file.
1463 *
1464 * @return Returns a new ParcelFileDescriptor which you can use to access
1465 * the file.
1466 *
1467 * @throws FileNotFoundException Throws FileNotFoundException if there is
1468 * no file associated with the given URI or the mode is invalid.
1469 * @throws SecurityException Throws SecurityException if the caller does
1470 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001471 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 * @see #openAssetFile(Uri, String)
1473 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001474 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001475 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001476 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001477 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 throws FileNotFoundException {
1479 throw new FileNotFoundException("No files supported by provider at "
1480 + uri);
1481 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001484 * Override this to handle requests to open a file blob.
1485 * The default implementation always throws {@link FileNotFoundException}.
1486 * This method can be called from multiple threads, as described in
1487 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1488 * and Threads</a>.
1489 *
1490 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1491 * to the caller. This way large data (such as images and documents) can be
1492 * returned without copying the content.
1493 *
1494 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1495 * their responsibility to close it when done. That is, the implementation
1496 * of this method should create a new ParcelFileDescriptor for each call.
1497 * <p>
1498 * If opened with the exclusive "r" or "w" modes, the returned
1499 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1500 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1501 * supports seeking.
1502 * <p>
1503 * If you need to detect when the returned ParcelFileDescriptor has been
1504 * closed, or if the remote process has crashed or encountered some other
1505 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1506 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1507 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1508 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1509 *
1510 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1511 * to return the appropriate MIME type for the data returned here with
1512 * the same URI. This will allow intent resolution to automatically determine the data MIME
1513 * type and select the appropriate matching targets as part of its operation.</p>
1514 *
1515 * <p class="note">For better interoperability with other applications, it is recommended
1516 * that for any URIs that can be opened, you also support queries on them
1517 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1518 * You may also want to support other common columns if you have additional meta-data
1519 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1520 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1521 *
1522 * @param uri The URI whose file is to be opened.
1523 * @param mode Access mode for the file. May be "r" for read-only access,
1524 * "w" for write-only access, "rw" for read and write access, or
1525 * "rwt" for read and write access that truncates any existing
1526 * file.
1527 * @param signal A signal to cancel the operation in progress, or
1528 * {@code null} if none. For example, if you are downloading a
1529 * file from the network to service a "rw" mode request, you
1530 * should periodically call
1531 * {@link CancellationSignal#throwIfCanceled()} to check whether
1532 * the client has canceled the request and abort the download.
1533 *
1534 * @return Returns a new ParcelFileDescriptor which you can use to access
1535 * the file.
1536 *
1537 * @throws FileNotFoundException Throws FileNotFoundException if there is
1538 * no file associated with the given URI or the mode is invalid.
1539 * @throws SecurityException Throws SecurityException if the caller does
1540 * not have permission to access the file.
1541 *
1542 * @see #openAssetFile(Uri, String)
1543 * @see #openFileHelper(Uri, String)
1544 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001545 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001546 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001547 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1548 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001549 return openFile(uri, mode);
1550 }
1551
1552 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 * This is like {@link #openFile}, but can be implemented by providers
1554 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001555 * inside of their .apk.
1556 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001557 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1558 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001559 *
1560 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001561 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001562 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1564 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1565 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001566 * <p>
1567 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1568 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001569 *
1570 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 * should create the AssetFileDescriptor with
1572 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001573 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001575 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1576 * to return the appropriate MIME type for the data returned here with
1577 * the same URI. This will allow intent resolution to automatically determine the data MIME
1578 * type and select the appropriate matching targets as part of its operation.</p>
1579 *
1580 * <p class="note">For better interoperability with other applications, it is recommended
1581 * that for any URIs that can be opened, you also support queries on them
1582 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1583 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 * @param uri The URI whose file is to be opened.
1585 * @param mode Access mode for the file. May be "r" for read-only access,
1586 * "w" for write-only access (erasing whatever data is currently in
1587 * the file), "wa" for write-only access to append to any existing data,
1588 * "rw" for read and write access on any existing data, and "rwt" for read
1589 * and write access that truncates any existing file.
1590 *
1591 * @return Returns a new AssetFileDescriptor which you can use to access
1592 * the file.
1593 *
1594 * @throws FileNotFoundException Throws FileNotFoundException if there is
1595 * no file associated with the given URI or the mode is invalid.
1596 * @throws SecurityException Throws SecurityException if the caller does
1597 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001598 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 * @see #openFile(Uri, String)
1600 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001601 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001603 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 throws FileNotFoundException {
1605 ParcelFileDescriptor fd = openFile(uri, mode);
1606 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1607 }
1608
1609 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001610 * This is like {@link #openFile}, but can be implemented by providers
1611 * that need to be able to return sub-sections of files, often assets
1612 * inside of their .apk.
1613 * This method can be called from multiple threads, as described in
1614 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1615 * and Threads</a>.
1616 *
1617 * <p>If you implement this, your clients must be able to deal with such
1618 * file slices, either directly with
1619 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1620 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1621 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1622 * methods.
1623 * <p>
1624 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1625 * streaming of data.
1626 *
1627 * <p class="note">If you are implementing this to return a full file, you
1628 * should create the AssetFileDescriptor with
1629 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1630 * applications that cannot handle sub-sections of files.</p>
1631 *
1632 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1633 * to return the appropriate MIME type for the data returned here with
1634 * the same URI. This will allow intent resolution to automatically determine the data MIME
1635 * type and select the appropriate matching targets as part of its operation.</p>
1636 *
1637 * <p class="note">For better interoperability with other applications, it is recommended
1638 * that for any URIs that can be opened, you also support queries on them
1639 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1640 *
1641 * @param uri The URI whose file is to be opened.
1642 * @param mode Access mode for the file. May be "r" for read-only access,
1643 * "w" for write-only access (erasing whatever data is currently in
1644 * the file), "wa" for write-only access to append to any existing data,
1645 * "rw" for read and write access on any existing data, and "rwt" for read
1646 * and write access that truncates any existing file.
1647 * @param signal A signal to cancel the operation in progress, or
1648 * {@code null} if none. For example, if you are downloading a
1649 * file from the network to service a "rw" mode request, you
1650 * should periodically call
1651 * {@link CancellationSignal#throwIfCanceled()} to check whether
1652 * the client has canceled the request and abort the download.
1653 *
1654 * @return Returns a new AssetFileDescriptor which you can use to access
1655 * the file.
1656 *
1657 * @throws FileNotFoundException Throws FileNotFoundException if there is
1658 * no file associated with the given URI or the mode is invalid.
1659 * @throws SecurityException Throws SecurityException if the caller does
1660 * not have permission to access the file.
1661 *
1662 * @see #openFile(Uri, String)
1663 * @see #openFileHelper(Uri, String)
1664 * @see #getType(android.net.Uri)
1665 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001666 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1667 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001668 return openAssetFile(uri, mode);
1669 }
1670
1671 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 * Convenience for subclasses that wish to implement {@link #openFile}
1673 * by looking up a column named "_data" at the given URI.
1674 *
1675 * @param uri The URI to be opened.
1676 * @param mode The file mode. May be "r" for read-only access,
1677 * "w" for write-only access (erasing whatever data is currently in
1678 * the file), "wa" for write-only access to append to any existing data,
1679 * "rw" for read and write access on any existing data, and "rwt" for read
1680 * and write access that truncates any existing file.
1681 *
1682 * @return Returns a new ParcelFileDescriptor that can be used by the
1683 * client to access the file.
1684 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001685 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1686 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1688 int count = (c != null) ? c.getCount() : 0;
1689 if (count != 1) {
1690 // If there is not exactly one result, throw an appropriate
1691 // exception.
1692 if (c != null) {
1693 c.close();
1694 }
1695 if (count == 0) {
1696 throw new FileNotFoundException("No entry for " + uri);
1697 }
1698 throw new FileNotFoundException("Multiple items at " + uri);
1699 }
1700
1701 c.moveToFirst();
1702 int i = c.getColumnIndex("_data");
1703 String path = (i >= 0 ? c.getString(i) : null);
1704 c.close();
1705 if (path == null) {
1706 throw new FileNotFoundException("Column _data not found.");
1707 }
1708
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001709 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 return ParcelFileDescriptor.open(new File(path), modeBits);
1711 }
1712
1713 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001714 * Called by a client to determine the types of data streams that this
1715 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001716 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001717 * of a particular type, return that MIME type if it matches the given
1718 * mimeTypeFilter. If it can perform type conversions, return an array
1719 * of all supported MIME types that match mimeTypeFilter.
1720 *
1721 * @param uri The data in the content provider being queried.
1722 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001723 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001724 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001725 * given mimeTypeFilter. Otherwise returns an array of all available
1726 * concrete MIME types.
1727 *
1728 * @see #getType(Uri)
1729 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001730 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001731 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001732 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001733 return null;
1734 }
1735
1736 /**
1737 * Called by a client to open a read-only stream containing data of a
1738 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1739 * except the file can only be read-only and the content provider may
1740 * perform data conversions to generate data of the desired type.
1741 *
1742 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001743 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001744 * {@link #openAssetFile(Uri, String)}.
1745 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001746 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001747 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001748 * <p>
1749 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1750 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001751 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001752 * <p class="note">For better interoperability with other applications, it is recommended
1753 * that for any URIs that can be opened, you also support queries on them
1754 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1755 * You may also want to support other common columns if you have additional meta-data
1756 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1757 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1758 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001759 * @param uri The data in the content provider being queried.
1760 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001761 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001762 * requirements; in this case the content provider will pick its best
1763 * type matching the pattern.
1764 * @param opts Additional options from the client. The definitions of
1765 * these are specific to the content provider being called.
1766 *
1767 * @return Returns a new AssetFileDescriptor from which the client can
1768 * read data of the desired type.
1769 *
1770 * @throws FileNotFoundException Throws FileNotFoundException if there is
1771 * no file associated with the given URI or the mode is invalid.
1772 * @throws SecurityException Throws SecurityException if the caller does
1773 * not have permission to access the data.
1774 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1775 * content provider does not support the requested MIME type.
1776 *
1777 * @see #getStreamTypes(Uri, String)
1778 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001779 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001780 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001781 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1782 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001783 if ("*/*".equals(mimeTypeFilter)) {
1784 // If they can take anything, the untyped open call is good enough.
1785 return openAssetFile(uri, "r");
1786 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001787 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001788 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001789 // Use old untyped open call if this provider has a type for this
1790 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001791 return openAssetFile(uri, "r");
1792 }
1793 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1794 }
1795
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001796
1797 /**
1798 * Called by a client to open a read-only stream containing data of a
1799 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1800 * except the file can only be read-only and the content provider may
1801 * perform data conversions to generate data of the desired type.
1802 *
1803 * <p>The default implementation compares the given mimeType against the
1804 * result of {@link #getType(Uri)} and, if they match, simply calls
1805 * {@link #openAssetFile(Uri, String)}.
1806 *
1807 * <p>See {@link ClipData} for examples of the use and implementation
1808 * of this method.
1809 * <p>
1810 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1811 * streaming of data.
1812 *
1813 * <p class="note">For better interoperability with other applications, it is recommended
1814 * that for any URIs that can be opened, you also support queries on them
1815 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1816 * You may also want to support other common columns if you have additional meta-data
1817 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1818 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1819 *
1820 * @param uri The data in the content provider being queried.
1821 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001822 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001823 * requirements; in this case the content provider will pick its best
1824 * type matching the pattern.
1825 * @param opts Additional options from the client. The definitions of
1826 * these are specific to the content provider being called.
1827 * @param signal A signal to cancel the operation in progress, or
1828 * {@code null} if none. For example, if you are downloading a
1829 * file from the network to service a "rw" mode request, you
1830 * should periodically call
1831 * {@link CancellationSignal#throwIfCanceled()} to check whether
1832 * the client has canceled the request and abort the download.
1833 *
1834 * @return Returns a new AssetFileDescriptor from which the client can
1835 * read data of the desired type.
1836 *
1837 * @throws FileNotFoundException Throws FileNotFoundException if there is
1838 * no file associated with the given URI or the mode is invalid.
1839 * @throws SecurityException Throws SecurityException if the caller does
1840 * not have permission to access the data.
1841 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1842 * content provider does not support the requested MIME type.
1843 *
1844 * @see #getStreamTypes(Uri, String)
1845 * @see #openAssetFile(Uri, String)
1846 * @see ClipDescription#compareMimeTypes(String, String)
1847 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001848 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1849 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1850 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001851 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1852 }
1853
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001854 /**
1855 * Interface to write a stream of data to a pipe. Use with
1856 * {@link ContentProvider#openPipeHelper}.
1857 */
1858 public interface PipeDataWriter<T> {
1859 /**
1860 * Called from a background thread to stream data out to a pipe.
1861 * Note that the pipe is blocking, so this thread can block on
1862 * writes for an arbitrary amount of time if the client is slow
1863 * at reading.
1864 *
1865 * @param output The pipe where data should be written. This will be
1866 * closed for you upon returning from this function.
1867 * @param uri The URI whose data is to be written.
1868 * @param mimeType The desired type of data to be written.
1869 * @param opts Options supplied by caller.
1870 * @param args Your own custom arguments.
1871 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001872 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1873 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001874 }
1875
1876 /**
1877 * A helper function for implementing {@link #openTypedAssetFile}, for
1878 * creating a data pipe and background thread allowing you to stream
1879 * generated data back to the client. This function returns a new
1880 * ParcelFileDescriptor that should be returned to the caller (the caller
1881 * is responsible for closing it).
1882 *
1883 * @param uri The URI whose data is to be written.
1884 * @param mimeType The desired type of data to be written.
1885 * @param opts Options supplied by caller.
1886 * @param args Your own custom arguments.
1887 * @param func Interface implementing the function that will actually
1888 * stream the data.
1889 * @return Returns a new ParcelFileDescriptor holding the read side of
1890 * the pipe. This should be returned to the caller for reading; the caller
1891 * is responsible for closing it when done.
1892 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001893 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1894 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1895 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001896 try {
1897 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1898
1899 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1900 @Override
1901 protected Object doInBackground(Object... params) {
1902 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1903 try {
1904 fds[1].close();
1905 } catch (IOException e) {
1906 Log.w(TAG, "Failure closing pipe", e);
1907 }
1908 return null;
1909 }
1910 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001911 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001912
1913 return fds[0];
1914 } catch (IOException e) {
1915 throw new FileNotFoundException("failure making pipe");
1916 }
1917 }
1918
1919 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 * Returns true if this instance is a temporary content provider.
1921 * @return true if this instance is a temporary content provider
1922 */
1923 protected boolean isTemporary() {
1924 return false;
1925 }
1926
1927 /**
1928 * Returns the Binder object for this provider.
1929 *
1930 * @return the Binder object for this provider
1931 * @hide
1932 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001933 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 public IContentProvider getIContentProvider() {
1935 return mTransport;
1936 }
1937
1938 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001939 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1940 * when directly instantiating the provider for testing.
1941 * @hide
1942 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001943 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001944 public void attachInfoForTesting(Context context, ProviderInfo info) {
1945 attachInfo(context, info, true);
1946 }
1947
1948 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 * After being instantiated, this is called to tell the content provider
1950 * about itself.
1951 *
1952 * @param context The context this provider is running in
1953 * @param info Registered information about this content provider
1954 */
1955 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001956 attachInfo(context, info, false);
1957 }
1958
1959 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001960 mNoPerms = testing;
1961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 /*
1963 * Only allow it to be set once, so after the content service gives
1964 * this to us clients can't change it.
1965 */
1966 if (mContext == null) {
1967 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001968 if (context != null) {
1969 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1970 Context.APP_OPS_SERVICE);
1971 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001972 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 if (info != null) {
1974 setReadPermission(info.readPermission);
1975 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001976 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001977 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001978 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001979 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
1981 ContentProvider.this.onCreate();
1982 }
1983 }
Fred Quintanace31b232009-05-04 16:01:15 -07001984
1985 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001986 * Override this to handle requests to perform a batch of operations, or the
1987 * default implementation will iterate over the operations and call
1988 * {@link ContentProviderOperation#apply} on each of them.
1989 * If all calls to {@link ContentProviderOperation#apply} succeed
1990 * then a {@link ContentProviderResult} array with as many
1991 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001992 * fail, it is up to the implementation how many of the others take effect.
1993 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001994 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1995 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001996 *
Fred Quintanace31b232009-05-04 16:01:15 -07001997 * @param operations the operations to apply
1998 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001999 * @throws OperationApplicationException thrown if any operation fails.
2000 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002001 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002002 public @NonNull ContentProviderResult[] applyBatch(
2003 @NonNull ArrayList<ContentProviderOperation> operations)
2004 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002005 final int numOperations = operations.size();
2006 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2007 for (int i = 0; i < numOperations; i++) {
2008 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002009 }
2010 return results;
2011 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002012
2013 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002014 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002015 * interfaces that are cheaper and/or unnatural for a table-like
2016 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002017 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002018 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2019 * on this entry into the content provider besides the basic ability for the application
2020 * to get access to the provider at all. For example, it has no idea whether the call
2021 * being executed may read or write data in the provider, so can't enforce those
2022 * individual permissions. Any implementation of this method <strong>must</strong>
2023 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2024 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002025 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2026 * @param arg provider-defined String argument. May be {@code null}.
2027 * @param extras provider-defined Bundle argument. May be {@code null}.
2028 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002029 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002030 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002031 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2032 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002033 return null;
2034 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002035
2036 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002037 * Implement this to shut down the ContentProvider instance. You can then
2038 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002039 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002040 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002041 * Android normally handles ContentProvider startup and shutdown
2042 * automatically. You do not need to start up or shut down a
2043 * ContentProvider. When you invoke a test method on a ContentProvider,
2044 * however, a ContentProvider instance is started and keeps running after
2045 * the test finishes, even if a succeeding test instantiates another
2046 * ContentProvider. A conflict develops because the two instances are
2047 * usually running against the same underlying data source (for example, an
2048 * sqlite database).
2049 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002050 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002051 * Implementing shutDown() avoids this conflict by providing a way to
2052 * terminate the ContentProvider. This method can also prevent memory leaks
2053 * from multiple instantiations of the ContentProvider, and it can ensure
2054 * unit test isolation by allowing you to completely clean up the test
2055 * fixture before moving on to the next test.
2056 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002057 */
2058 public void shutdown() {
2059 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2060 "connections are gracefully shutdown");
2061 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002062
2063 /**
2064 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002065 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002066 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002067 * @param fd The raw file descriptor that the dump is being sent to.
2068 * @param writer The PrintWriter to which you should dump your state. This will be
2069 * closed for you after you return.
2070 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002071 */
2072 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2073 writer.println("nothing to dump");
2074 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002075
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002076 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002077 private void validateIncomingUri(Uri uri) throws SecurityException {
2078 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002079 if (!mSingleUser) {
2080 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2081 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2082 throw new SecurityException("trying to query a ContentProvider in user "
2083 + mContext.getUserId() + " with a uri belonging to user " + userId);
2084 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002085 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002086 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2087 String message = "The authority of the uri " + uri + " does not match the one of the "
2088 + "contentProvider: ";
2089 if (mAuthority != null) {
2090 message += mAuthority;
2091 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002092 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002093 }
2094 throw new SecurityException(message);
2095 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002096 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002097
2098 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002099 private Uri maybeGetUriWithoutUserId(Uri uri) {
2100 if (mSingleUser) {
2101 return uri;
2102 }
2103 return getUriWithoutUserId(uri);
2104 }
2105
2106 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002107 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2108 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002109 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002110 if (end == -1) return defaultUserId;
2111 String userIdString = auth.substring(0, end);
2112 try {
2113 return Integer.parseInt(userIdString);
2114 } catch (NumberFormatException e) {
2115 Log.w(TAG, "Error parsing userId.", e);
2116 return UserHandle.USER_NULL;
2117 }
2118 }
2119
2120 /** @hide */
2121 public static int getUserIdFromAuthority(String auth) {
2122 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2123 }
2124
2125 /** @hide */
2126 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2127 if (uri == null) return defaultUserId;
2128 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2129 }
2130
2131 /** @hide */
2132 public static int getUserIdFromUri(Uri uri) {
2133 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2134 }
2135
2136 /**
2137 * Removes userId part from authority string. Expects format:
2138 * userId@some.authority
2139 * If there is no userId in the authority, it symply returns the argument
2140 * @hide
2141 */
2142 public static String getAuthorityWithoutUserId(String auth) {
2143 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002144 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002145 return auth.substring(end+1);
2146 }
2147
2148 /** @hide */
2149 public static Uri getUriWithoutUserId(Uri uri) {
2150 if (uri == null) return null;
2151 Uri.Builder builder = uri.buildUpon();
2152 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2153 return builder.build();
2154 }
2155
2156 /** @hide */
2157 public static boolean uriHasUserId(Uri uri) {
2158 if (uri == null) return false;
2159 return !TextUtils.isEmpty(uri.getUserInfo());
2160 }
2161
2162 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002163 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002164 public static Uri maybeAddUserId(Uri uri, int userId) {
2165 if (uri == null) return null;
2166 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002167 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002168 if (!uriHasUserId(uri)) {
2169 //We don't add the user Id if there's already one
2170 Uri.Builder builder = uri.buildUpon();
2171 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2172 return builder.build();
2173 }
2174 }
2175 return uri;
2176 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002177}