blob: dd9370d374920cbf694a487a83ba84433e3d855b [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
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060054import com.android.internal.annotations.VisibleForTesting;
55
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080057import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070059import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080060import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070061import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080062import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060063import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
65/**
66 * Content providers are one of the primary building blocks of Android applications, providing
67 * content to applications. They encapsulate data and provide it to applications through the single
68 * {@link ContentResolver} interface. A content provider is only required if you need to share
69 * data between multiple applications. For example, the contacts data is used by multiple
70 * applications and must be stored in a content provider. If you don't need to share data amongst
71 * multiple applications you can use a database directly via
72 * {@link android.database.sqlite.SQLiteDatabase}.
73 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 * <p>When a request is made via
75 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
76 * request to the content provider registered with the authority. The content provider can interpret
77 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
78 * URIs.</p>
79 *
80 * <p>The primary methods that need to be implemented are:
81 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070082 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * <li>{@link #query} which returns data to the caller</li>
84 * <li>{@link #insert} which inserts new data into the content provider</li>
85 * <li>{@link #update} which updates existing data in the content provider</li>
86 * <li>{@link #delete} which deletes data from the content provider</li>
87 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
88 * </ul></p>
89 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070090 * <p class="caution">Data access methods (such as {@link #insert} and
91 * {@link #update}) may be called from many threads at once, and must be thread-safe.
92 * Other methods (such as {@link #onCreate}) are only called from the application
93 * main thread, and must avoid performing lengthy operations. See the method
94 * descriptions for their expected thread behavior.</p>
95 *
96 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
97 * ContentProvider instance, so subclasses don't have to worry about the details of
98 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070099 *
100 * <div class="special reference">
101 * <h3>Developer Guides</h3>
102 * <p>For more information about using content providers, read the
103 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
104 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700106public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800107
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700108 private static final String TAG = "ContentProvider";
109
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900110 /*
111 * Note: if you add methods to ContentProvider, you must add similar methods to
112 * MockContentProvider.
113 */
114
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100115 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700117 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100118
119 // Since most Providers have only one authority, we keep both a String and a String[] to improve
120 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100121 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100122 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100123 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100124 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100125 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100127 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700130 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700131 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800132 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700133 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Steve McKayea93fe72016-12-02 11:35:35 -0800135 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private Transport mTransport = new Transport();
138
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700139 /**
140 * Construct a ContentProvider instance. Content providers must be
141 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
142 * in the manifest</a>, accessed with {@link ContentResolver}, and created
143 * automatically by the system, so applications usually do not create
144 * ContentProvider instances directly.
145 *
146 * <p>At construction time, the object is uninitialized, and most fields and
147 * methods are unavailable. Subclasses should initialize themselves in
148 * {@link #onCreate}, not the constructor.
149 *
150 * <p>Content providers are created on the application main thread at
151 * application launch time. The constructor must not perform lengthy
152 * operations, or application startup will be delayed.
153 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900154 public ContentProvider() {
155 }
156
157 /**
158 * Constructor just for mocking.
159 *
160 * @param context A Context object which should be some mock instance (like the
161 * instance of {@link android.test.mock.MockContext}).
162 * @param readPermission The read permision you want this instance should have in the
163 * test, which is available via {@link #getReadPermission()}.
164 * @param writePermission The write permission you want this instance should have
165 * in the test, which is available via {@link #getWritePermission()}.
166 * @param pathPermissions The PathPermissions you want this instance should have
167 * in the test, which is available via {@link #getPathPermissions()}.
168 * @hide
169 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100170 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900171 public ContentProvider(
172 Context context,
173 String readPermission,
174 String writePermission,
175 PathPermission[] pathPermissions) {
176 mContext = context;
177 mReadPermission = readPermission;
178 mWritePermission = writePermission;
179 mPathPermissions = pathPermissions;
180 }
181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 /**
183 * Given an IContentProvider, try to coerce it back to the real
184 * ContentProvider object if it is running in the local process. This can
185 * be used if you know you are running in the same process as a provider,
186 * and want to get direct access to its implementation details. Most
187 * clients should not nor have a reason to use it.
188 *
189 * @param abstractInterface The ContentProvider interface that is to be
190 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800191 * @return If the IContentProvider is non-{@code null} and local, returns its actual
192 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 * @hide
194 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100195 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 public static ContentProvider coerceToLocalContentProvider(
197 IContentProvider abstractInterface) {
198 if (abstractInterface instanceof Transport) {
199 return ((Transport)abstractInterface).getContentProvider();
200 }
201 return null;
202 }
203
204 /**
205 * Binder object that deals with remoting.
206 *
207 * @hide
208 */
209 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800210 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800211 int mReadOp = AppOpsManager.OP_NONE;
212 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 ContentProvider getContentProvider() {
215 return ContentProvider.this;
216 }
217
Jeff Brownd2183652011-10-09 12:39:53 -0700218 @Override
219 public String getProviderName() {
220 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 }
222
Jeff Brown75ea64f2012-01-25 19:37:13 -0800223 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800224 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
225 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600226 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100227 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800228 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700229 // The caller has no access to the data, so return an empty cursor with
230 // the columns in the requested order. The caller may ask for an invalid
231 // column and we would not catch that but this is not a problem in practice.
232 // We do not call ContentProvider#query with a modified where clause since
233 // the implementation is not guaranteed to be backed by a SQL database, hence
234 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700235 if (projection != null) {
236 return new MatrixCursor(projection, 0);
237 }
238
239 // Null projection means all columns but we have no idea which they are.
240 // However, the caller may be expecting to access them my index. Hence,
241 // we have to execute the query as if allowed to get a cursor with the
242 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700243 Cursor cursor;
244 final String original = setCallingPackage(callingPkg);
245 try {
246 cursor = ContentProvider.this.query(
247 uri, projection, queryArgs,
248 CancellationSignal.fromTransport(cancellationSignal));
249 } finally {
250 setCallingPackage(original);
251 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700252 if (cursor == null) {
253 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700254 }
255
256 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700257 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800258 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600259 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700260 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700261 try {
262 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800263 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700264 CancellationSignal.fromTransport(cancellationSignal));
265 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700266 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600267 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270
Jeff Brown75ea64f2012-01-25 19:37:13 -0800271 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700273 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600274 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100275 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600276 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
277 try {
278 return ContentProvider.this.getType(uri);
279 } finally {
280 Trace.traceEnd(TRACE_TAG_DATABASE);
281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 }
283
Jeff Brown75ea64f2012-01-25 19:37:13 -0800284 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800285 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600286 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100287 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100288 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800289 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700290 final String original = setCallingPackage(callingPkg);
291 try {
292 return rejectInsert(uri, initialValues);
293 } finally {
294 setCallingPackage(original);
295 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800296 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600297 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700298 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700299 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100300 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700301 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700302 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600303 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 }
306
Jeff Brown75ea64f2012-01-25 19:37:13 -0800307 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800308 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600309 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100310 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800311 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800312 return 0;
313 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600314 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700315 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700316 try {
317 return ContentProvider.this.bulkInsert(uri, initialValues);
318 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700319 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600320 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 }
323
Jeff Brown75ea64f2012-01-25 19:37:13 -0800324 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800325 public ContentProviderResult[] applyBatch(String callingPkg,
326 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700327 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100328 int numOperations = operations.size();
329 final int[] userIds = new int[numOperations];
330 for (int i = 0; i < numOperations; i++) {
331 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100332 Uri uri = operation.getUri();
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600333 uri = validateIncomingUri(uri);
334 uri = maybeGetUriWithoutUserId(uri);
335 // Rebuild operation if we changed the Uri above
336 if (!Objects.equals(operation.getUri(), uri)) {
337 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100338 operations.set(i, operation);
339 }
Fred Quintana89437372009-05-15 15:10:40 -0700340 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800341 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800342 != AppOpsManager.MODE_ALLOWED) {
343 throw new OperationApplicationException("App op not allowed", 0);
344 }
Fred Quintana89437372009-05-15 15:10:40 -0700345 }
Fred Quintana89437372009-05-15 15:10:40 -0700346 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800347 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800348 != AppOpsManager.MODE_ALLOWED) {
349 throw new OperationApplicationException("App op not allowed", 0);
350 }
Fred Quintana89437372009-05-15 15:10:40 -0700351 }
352 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600353 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700354 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100356 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800357 if (results != null) {
358 for (int i = 0; i < results.length ; i++) {
359 if (userIds[i] != UserHandle.USER_CURRENT) {
360 // Adding the userId to the uri.
361 results[i] = new ContentProviderResult(results[i], userIds[i]);
362 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100363 }
364 }
365 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700366 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700367 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600368 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700369 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700370 }
371
Jeff Brown75ea64f2012-01-25 19:37:13 -0800372 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800373 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600374 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100375 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800376 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800377 return 0;
378 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600379 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700380 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700381 try {
382 return ContentProvider.this.delete(uri, selection, selectionArgs);
383 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700384 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600385 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 }
388
Jeff Brown75ea64f2012-01-25 19:37:13 -0800389 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800390 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600392 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100393 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800394 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800395 return 0;
396 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600397 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700398 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700399 try {
400 return ContentProvider.this.update(uri, values, selection, selectionArgs);
401 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700402 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600403 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406
Jeff Brown75ea64f2012-01-25 19:37:13 -0800407 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700408 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800409 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
410 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600411 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100412 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800413 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600414 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700415 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700416 try {
417 return ContentProvider.this.openFile(
418 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
419 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700420 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600421 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 }
424
Jeff Brown75ea64f2012-01-25 19:37:13 -0800425 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700426 public AssetFileDescriptor openAssetFile(
427 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600429 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100430 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800431 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600432 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700433 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700434 try {
435 return ContentProvider.this.openAssetFile(
436 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
437 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700438 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600439 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
442
Jeff Brown75ea64f2012-01-25 19:37:13 -0800443 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800444 public Bundle call(
445 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600446 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600447 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700448 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700449 try {
450 return ContentProvider.this.call(method, arg, extras);
451 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700452 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600453 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700454 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800455 }
456
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700457 @Override
458 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700459 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600460 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100461 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600462 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
463 try {
464 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
465 } finally {
466 Trace.traceEnd(TRACE_TAG_DATABASE);
467 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700468 }
469
470 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800471 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700472 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600473 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600474 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100475 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800476 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600477 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700478 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700479 try {
480 return ContentProvider.this.openTypedAssetFile(
481 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
482 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700483 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600484 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700485 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700486 }
487
Jeff Brown75ea64f2012-01-25 19:37:13 -0800488 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700489 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800490 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800491 }
492
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700493 @Override
494 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600495 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100496 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100497 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800498 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700499 return null;
500 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600501 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700502 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700503 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100504 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700505 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700506 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600507 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700508 }
509 }
510
511 @Override
512 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600513 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100514 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100515 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800516 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700517 return null;
518 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600519 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700520 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700521 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100522 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700523 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700524 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600525 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700526 }
527 }
528
Ben Lin1cf454f2016-11-10 13:50:54 -0800529 @Override
530 public boolean refresh(String callingPkg, Uri uri, Bundle args,
531 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600532 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800533 uri = getUriWithoutUserId(uri);
534 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
535 return false;
536 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600537 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800538 final String original = setCallingPackage(callingPkg);
539 try {
540 return ContentProvider.this.refresh(uri, args,
541 CancellationSignal.fromTransport(cancellationSignal));
542 } finally {
543 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600544 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800545 }
546 }
547
Dianne Hackbornff170242014-11-19 10:59:01 -0800548 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
549 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800550 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800551 if (enforceWritePermission(callingPkg, uri, callerToken)
552 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800553 throw new FileNotFoundException("App op not allowed");
554 }
555 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800556 if (enforceReadPermission(callingPkg, uri, callerToken)
557 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800558 throw new FileNotFoundException("App op not allowed");
559 }
560 }
561 }
562
Dianne Hackbornff170242014-11-19 10:59:01 -0800563 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
564 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700565 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
566 if (mode != MODE_ALLOWED) {
567 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800568 }
Svet Ganov99b60432015-06-27 13:15:22 -0700569
570 if (mReadOp != AppOpsManager.OP_NONE) {
571 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
572 }
573
Dianne Hackborn35654b62013-01-14 17:38:02 -0800574 return AppOpsManager.MODE_ALLOWED;
575 }
576
Dianne Hackbornff170242014-11-19 10:59:01 -0800577 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
578 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700579 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
580 if (mode != MODE_ALLOWED) {
581 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800582 }
Svet Ganov99b60432015-06-27 13:15:22 -0700583
584 if (mWriteOp != AppOpsManager.OP_NONE) {
585 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
586 }
587
Dianne Hackborn35654b62013-01-14 17:38:02 -0800588 return AppOpsManager.MODE_ALLOWED;
589 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700590 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800591
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100592 boolean checkUser(int pid, int uid, Context context) {
593 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700594 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100595 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
596 == PERMISSION_GRANTED;
597 }
598
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700599 /**
600 * Verify that calling app holds both the given permission and any app-op
601 * associated with that permission.
602 */
603 private int checkPermissionAndAppOp(String permission, String callingPkg,
604 IBinder callerToken) {
605 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
606 callerToken) != PERMISSION_GRANTED) {
607 return MODE_ERRORED;
608 }
609
610 final int permOp = AppOpsManager.permissionToOpCode(permission);
611 if (permOp != AppOpsManager.OP_NONE) {
612 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
613 }
614
615 return MODE_ALLOWED;
616 }
617
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700618 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700619 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800620 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700621 final Context context = getContext();
622 final int pid = Binder.getCallingPid();
623 final int uid = Binder.getCallingUid();
624 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700625 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700626
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700627 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700628 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700629 }
630
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100631 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700632 final String componentPerm = getReadPermission();
633 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700634 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
635 if (mode == MODE_ALLOWED) {
636 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700637 } else {
638 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700639 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700640 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700641 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700642
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700643 // track if unprotected read is allowed; any denied
644 // <path-permission> below removes this ability
645 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700646
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700647 final PathPermission[] pps = getPathPermissions();
648 if (pps != null) {
649 final String path = uri.getPath();
650 for (PathPermission pp : pps) {
651 final String pathPerm = pp.getReadPermission();
652 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700653 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
654 if (mode == MODE_ALLOWED) {
655 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700656 } else {
657 // any denied <path-permission> means we lose
658 // default <provider> access.
659 allowDefaultRead = false;
660 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700661 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700662 }
663 }
664 }
665 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700666
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700667 // if we passed <path-permission> checks above, and no default
668 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700669 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700671
672 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800673 final int callingUserId = UserHandle.getUserId(uid);
674 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
675 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800676 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
677 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700678 return MODE_ALLOWED;
679 }
680
681 // If the worst denial we found above was ignored, then pass that
682 // ignored through; otherwise we assume it should be a real error below.
683 if (strongestMode == MODE_IGNORED) {
684 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700685 }
686
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600687 final String suffix;
688 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
689 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
690 } else if (mExported) {
691 suffix = " requires " + missingPerm + ", or grantUriPermission()";
692 } else {
693 suffix = " requires the provider be exported, or grantUriPermission()";
694 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700695 throw new SecurityException("Permission Denial: reading "
696 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600697 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700698 }
699
700 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700701 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800702 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700703 final Context context = getContext();
704 final int pid = Binder.getCallingPid();
705 final int uid = Binder.getCallingUid();
706 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700707 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700708
709 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700710 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700711 }
712
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100713 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700714 final String componentPerm = getWritePermission();
715 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700716 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
717 if (mode == MODE_ALLOWED) {
718 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700719 } else {
720 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700721 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700722 }
723 }
724
725 // track if unprotected write is allowed; any denied
726 // <path-permission> below removes this ability
727 boolean allowDefaultWrite = (componentPerm == null);
728
729 final PathPermission[] pps = getPathPermissions();
730 if (pps != null) {
731 final String path = uri.getPath();
732 for (PathPermission pp : pps) {
733 final String pathPerm = pp.getWritePermission();
734 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700735 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
736 if (mode == MODE_ALLOWED) {
737 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700738 } else {
739 // any denied <path-permission> means we lose
740 // default <provider> access.
741 allowDefaultWrite = false;
742 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700743 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700744 }
745 }
746 }
747 }
748
749 // if we passed <path-permission> checks above, and no default
750 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700751 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700752 }
753
754 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800755 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
756 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700757 return MODE_ALLOWED;
758 }
759
760 // If the worst denial we found above was ignored, then pass that
761 // ignored through; otherwise we assume it should be a real error below.
762 if (strongestMode == MODE_IGNORED) {
763 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700764 }
765
766 final String failReason = mExported
767 ? " requires " + missingPerm + ", or grantUriPermission()"
768 : " requires the provider be exported, or grantUriPermission()";
769 throw new SecurityException("Permission Denial: writing "
770 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
771 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700775 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800776 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 * constructor.
778 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700779 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 return mContext;
781 }
782
783 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700784 * Set the calling package, returning the current value (or {@code null})
785 * which can be used later to restore the previous state.
786 */
787 private String setCallingPackage(String callingPackage) {
788 final String original = mCallingPackage.get();
789 mCallingPackage.set(callingPackage);
790 return original;
791 }
792
793 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700794 * Return the package name of the caller that initiated the request being
795 * processed on the current thread. The returned package will have been
796 * verified to belong to the calling UID. Returns {@code null} if not
797 * currently processing a request.
798 * <p>
799 * This will always return {@code null} when processing
800 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
801 *
802 * @see Binder#getCallingUid()
803 * @see Context#grantUriPermission(String, Uri, int)
804 * @throws SecurityException if the calling package doesn't belong to the
805 * calling UID.
806 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700807 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700808 final String pkg = mCallingPackage.get();
809 if (pkg != null) {
810 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
811 }
812 return pkg;
813 }
814
815 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100816 * Change the authorities of the ContentProvider.
817 * This is normally set for you from its manifest information when the provider is first
818 * created.
819 * @hide
820 * @param authorities the semi-colon separated authorities of the ContentProvider.
821 */
822 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100823 if (authorities != null) {
824 if (authorities.indexOf(';') == -1) {
825 mAuthority = authorities;
826 mAuthorities = null;
827 } else {
828 mAuthority = null;
829 mAuthorities = authorities.split(";");
830 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100831 }
832 }
833
834 /** @hide */
835 protected final boolean matchesOurAuthorities(String authority) {
836 if (mAuthority != null) {
837 return mAuthority.equals(authority);
838 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100839 if (mAuthorities != null) {
840 int length = mAuthorities.length;
841 for (int i = 0; i < length; i++) {
842 if (mAuthorities[i].equals(authority)) return true;
843 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100844 }
845 return false;
846 }
847
848
849 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 * Change the permission required to read data from the content
851 * provider. This is normally set for you from its manifest information
852 * when the provider is first created.
853 *
854 * @param permission Name of the permission required for read-only access.
855 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700856 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 mReadPermission = permission;
858 }
859
860 /**
861 * Return the name of the permission required for read-only access to
862 * this content provider. This method can be called from multiple
863 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800864 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
865 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700867 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 return mReadPermission;
869 }
870
871 /**
872 * Change the permission required to read and write data in the content
873 * provider. This is normally set for you from its manifest information
874 * when the provider is first created.
875 *
876 * @param permission Name of the permission required for read/write access.
877 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700878 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 mWritePermission = permission;
880 }
881
882 /**
883 * Return the name of the permission required for read/write access to
884 * this content provider. This method can be called from multiple
885 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800886 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
887 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700889 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 return mWritePermission;
891 }
892
893 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700894 * Change the path-based permission required to read and/or write data in
895 * the content provider. This is normally set for you from its manifest
896 * information when the provider is first created.
897 *
898 * @param permissions Array of path permission descriptions.
899 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700900 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700901 mPathPermissions = permissions;
902 }
903
904 /**
905 * Return the path-based permissions required for read and/or write access to
906 * this content provider. This method can be called from multiple
907 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800908 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
909 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700910 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700911 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700912 return mPathPermissions;
913 }
914
Dianne Hackborn35654b62013-01-14 17:38:02 -0800915 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100916 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800917 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800918 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800919 mTransport.mReadOp = readOp;
920 mTransport.mWriteOp = writeOp;
921 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800922 }
923
Dianne Hackborn961321f2013-02-05 17:22:41 -0800924 /** @hide */
925 public AppOpsManager getAppOpsManager() {
926 return mTransport.mAppOpsManager;
927 }
928
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700929 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700930 * Implement this to initialize your content provider on startup.
931 * This method is called for all registered content providers on the
932 * application main thread at application launch time. It must not perform
933 * lengthy operations, or application startup will be delayed.
934 *
935 * <p>You should defer nontrivial initialization (such as opening,
936 * upgrading, and scanning databases) until the content provider is used
937 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
938 * keeps application startup fast, avoids unnecessary work if the provider
939 * turns out not to be needed, and stops database errors (such as a full
940 * disk) from halting application launch.
941 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700942 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700943 * is a helpful utility class that makes it easy to manage databases,
944 * and will automatically defer opening until first use. If you do use
945 * SQLiteOpenHelper, make sure to avoid calling
946 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
947 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
948 * from this method. (Instead, override
949 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
950 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 *
952 * @return true if the provider was successfully loaded, false otherwise
953 */
954 public abstract boolean onCreate();
955
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700956 /**
957 * {@inheritDoc}
958 * This method is always called on the application main thread, and must
959 * not perform lengthy operations.
960 *
961 * <p>The default content provider implementation does nothing.
962 * Override this method to take appropriate action.
963 * (Content providers do not usually care about things like screen
964 * orientation, but may want to know about locale changes.)
965 */
Steve McKayea93fe72016-12-02 11:35:35 -0800966 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 public void onConfigurationChanged(Configuration newConfig) {
968 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700969
970 /**
971 * {@inheritDoc}
972 * This method is always called on the application main thread, and must
973 * not perform lengthy operations.
974 *
975 * <p>The default content provider implementation does nothing.
976 * Subclasses may override this method to take appropriate action.
977 */
Steve McKayea93fe72016-12-02 11:35:35 -0800978 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 public void onLowMemory() {
980 }
981
Steve McKayea93fe72016-12-02 11:35:35 -0800982 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700983 public void onTrimMemory(int level) {
984 }
985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700987 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800988 *
989 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
990 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
991 * implementation of this method.
992 *
993 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800994 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
995 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 * <p>
997 * Example client call:<p>
998 * <pre>// Request a specific record.
999 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001000 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 projection, // Which columns to return.
1002 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001003 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 People.NAME + " ASC"); // Sort order.</pre>
1005 * Example implementation:<p>
1006 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1007 // proper SQL syntax for us.
1008 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1009
1010 // Set the table we're querying.
1011 qBuilder.setTables(DATABASE_TABLE_NAME);
1012
1013 // If the query ends in a specific record number, we're
1014 // being asked for a specific record, so set the
1015 // WHERE clause in our query.
1016 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1017 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1018 }
1019
1020 // Make the query.
1021 Cursor c = qBuilder.query(mDb,
1022 projection,
1023 selection,
1024 selectionArgs,
1025 groupBy,
1026 having,
1027 sortOrder);
1028 c.setNotificationUri(getContext().getContentResolver(), uri);
1029 return c;</pre>
1030 *
1031 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001032 * if the client is requesting a specific record, the URI will end in a record number
1033 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1034 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001036 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001038 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001039 * @param selectionArgs You may include ?s in selection, which will be replaced by
1040 * the values from selectionArgs, in order that they appear in the selection.
1041 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001043 * If {@code null} then the provider is free to define the sort order.
1044 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001046 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1047 @Nullable String selection, @Nullable String[] selectionArgs,
1048 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049
Fred Quintana5bba6322009-10-05 14:21:12 -07001050 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001051 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001052 *
1053 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1054 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1055 *
1056 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001057 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1058 * and Threads</a>.
1059 * <p>
1060 * Example client call:<p>
1061 * <pre>// Request a specific record.
1062 * Cursor managedCursor = managedQuery(
1063 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1064 projection, // Which columns to return.
1065 null, // WHERE clause.
1066 null, // WHERE clause value substitution
1067 People.NAME + " ASC"); // Sort order.</pre>
1068 * Example implementation:<p>
1069 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1070 // proper SQL syntax for us.
1071 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1072
1073 // Set the table we're querying.
1074 qBuilder.setTables(DATABASE_TABLE_NAME);
1075
1076 // If the query ends in a specific record number, we're
1077 // being asked for a specific record, so set the
1078 // WHERE clause in our query.
1079 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1080 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1081 }
1082
1083 // Make the query.
1084 Cursor c = qBuilder.query(mDb,
1085 projection,
1086 selection,
1087 selectionArgs,
1088 groupBy,
1089 having,
1090 sortOrder);
1091 c.setNotificationUri(getContext().getContentResolver(), uri);
1092 return c;</pre>
1093 * <p>
1094 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001095 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1096 * signal to ensure correct operation on older versions of the Android Framework in
1097 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001098 *
1099 * @param uri The URI to query. This will be the full URI sent by the client;
1100 * if the client is requesting a specific record, the URI will end in a record number
1101 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1102 * that _id value.
1103 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001104 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001105 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001106 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001107 * @param selectionArgs You may include ?s in selection, which will be replaced by
1108 * the values from selectionArgs, in order that they appear in the selection.
1109 * The values will be bound as Strings.
1110 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001111 * If {@code null} then the provider is free to define the sort order.
1112 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001113 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001114 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001115 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001116 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001117 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1118 @Nullable String selection, @Nullable String[] selectionArgs,
1119 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001120 return query(uri, projection, selection, selectionArgs, sortOrder);
1121 }
1122
1123 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001124 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1125 * Arguments may include traditional SQL style query arguments. When present these
1126 * should be handled according to the contract established in
1127 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1128 *
1129 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001130 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1131 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1132 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001133 *
Steve McKay76b27702017-04-24 12:07:53 -07001134 * <p>This method can be called from multiple threads, as described in
1135 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1136 * and Threads</a>.
1137 *
1138 * <p>
1139 * Example client call:<p>
1140 * <pre>// Request 20 records starting at row index 30.
1141 Bundle queryArgs = new Bundle();
1142 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1143 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1144
1145 Cursor cursor = getContentResolver().query(
1146 contentUri, // Content Uri is specific to individual content providers.
1147 projection, // String[] describing which columns to return.
1148 queryArgs, // Query arguments.
1149 null); // Cancellation signal.</pre>
1150 *
1151 * Example implementation:<p>
1152 * <pre>
1153
1154 int recordsetSize = 0x1000; // Actual value is implementation specific.
1155 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1156
1157 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1158 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1159
1160 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1161
1162 // Calculate the number of items to include in the cursor.
1163 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1164
1165 // Build the paged result set....
1166 for (int i = offset; i < offset + numItems; i++) {
1167 // populate row from your data.
1168 }
1169
1170 Bundle extras = new Bundle();
1171 c.setExtras(extras);
1172
1173 // Any QUERY_ARG_* key may be included if honored.
1174 // In an actual implementation, include only keys that are both present in queryArgs
1175 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1176 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1177 // then QUERY_ARG_OFFSET should be omitted.
1178 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1179 ContentResolver.QUERY_ARG_OFFSET,
1180 ContentResolver.QUERY_ARG_LIMIT
1181 });
1182
1183 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1184
1185 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1186
1187 return cursor;</pre>
1188 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001189 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1190 * implementation details.
1191 *
1192 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001193 * @param projection The list of columns to put into the cursor.
1194 * If {@code null} provide a default set of columns.
1195 * @param queryArgs A Bundle containing all additional information necessary for the query.
1196 * Values in the Bundle may include SQL style arguments.
1197 * @param cancellationSignal A signal to cancel the operation in progress,
1198 * or {@code null}.
1199 * @return a Cursor or {@code null}.
1200 */
1201 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1202 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1203 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001204
Steve McKayd7ece9f2017-01-12 16:59:59 -08001205 // if client doesn't supply an SQL sort order argument, attempt to build one from
1206 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001207 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001208 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1209 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1210 }
1211
Steve McKayea93fe72016-12-02 11:35:35 -08001212 return query(
1213 uri,
1214 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001215 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1216 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1217 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001218 cancellationSignal);
1219 }
1220
1221 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001222 * Implement this to handle requests for the MIME type of the data at the
1223 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 * <code>vnd.android.cursor.item</code> for a single record,
1225 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001226 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001227 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1228 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001230 * <p>Note that there are no permissions needed for an application to
1231 * access this information; if your content provider requires read and/or
1232 * write permissions, or is not exported, all applications can still call
1233 * this method regardless of their access permissions. This allows them
1234 * to retrieve the MIME type for a URI when dispatching intents.
1235 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001237 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001239 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240
1241 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001242 * Implement this to support canonicalization of URIs that refer to your
1243 * content provider. A canonical URI is one that can be transported across
1244 * devices, backup/restore, and other contexts, and still be able to refer
1245 * to the same data item. Typically this is implemented by adding query
1246 * params to the URI allowing the content provider to verify that an incoming
1247 * canonical URI references the same data as it was originally intended for and,
1248 * if it doesn't, to find that data (if it exists) in the current environment.
1249 *
1250 * <p>For example, if the content provider holds people and a normal URI in it
1251 * is created with a row index into that people database, the cananical representation
1252 * may have an additional query param at the end which specifies the name of the
1253 * person it is intended for. Later calls into the provider with that URI will look
1254 * up the row of that URI's base index and, if it doesn't match or its entry's
1255 * name doesn't match the name in the query param, perform a query on its database
1256 * to find the correct row to operate on.</p>
1257 *
1258 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1259 * URIs (including this one) must perform this verification and recovery of any
1260 * canonical URIs they receive. In addition, you must also implement
1261 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1262 *
1263 * <p>The default implementation of this method returns null, indicating that
1264 * canonical URIs are not supported.</p>
1265 *
1266 * @param url The Uri to canonicalize.
1267 *
1268 * @return Return the canonical representation of <var>url</var>, or null if
1269 * canonicalization of that Uri is not supported.
1270 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001271 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001272 return null;
1273 }
1274
1275 /**
1276 * Remove canonicalization from canonical URIs previously returned by
1277 * {@link #canonicalize}. For example, if your implementation is to add
1278 * a query param to canonicalize a URI, this method can simply trip any
1279 * query params on the URI. The default implementation always returns the
1280 * same <var>url</var> that was passed in.
1281 *
1282 * @param url The Uri to remove any canonicalization from.
1283 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001284 * @return Return the non-canonical representation of <var>url</var>, return
1285 * the <var>url</var> as-is if there is nothing to do, or return null if
1286 * the data identified by the canonical representation can not be found in
1287 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001288 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001289 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001290 return url;
1291 }
1292
1293 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001294 * Implement this to support refresh of content identified by {@code uri}. By default, this
1295 * method returns false; providers who wish to implement this should return true to signal the
1296 * client that the provider has tried refreshing with its own implementation.
1297 * <p>
1298 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1299 * <p>
1300 * Client code should only invoke this method when there is a strong indication (such as a user
1301 * initiated pull to refresh gesture) that the content is stale.
1302 * <p>
1303 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1304 * notifications when content changes.
1305 *
1306 * @param uri The Uri identifying the data to refresh.
1307 * @param args Additional options from the client. The definitions of these are specific to the
1308 * content provider being called.
1309 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1310 * none. For example, if you called refresh on a particular uri, you should call
1311 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1312 * canceled the refresh request.
1313 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001314 */
1315 public boolean refresh(Uri uri, @Nullable Bundle args,
1316 @Nullable CancellationSignal cancellationSignal) {
1317 return false;
1318 }
1319
1320 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001321 * @hide
1322 * Implementation when a caller has performed an insert on the content
1323 * provider, but that call has been rejected for the operation given
1324 * to {@link #setAppOps(int, int)}. The default implementation simply
1325 * returns a dummy URI that is the base URI with a 0 path element
1326 * appended.
1327 */
1328 public Uri rejectInsert(Uri uri, ContentValues values) {
1329 // If not allowed, we need to return some reasonable URI. Maybe the
1330 // content provider should be responsible for this, but for now we
1331 // will just return the base URI with a dummy '0' tagged on to it.
1332 // You shouldn't be able to read if you can't write, anyway, so it
1333 // shouldn't matter much what is returned.
1334 return uri.buildUpon().appendPath("0").build();
1335 }
1336
1337 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001338 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1340 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001341 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001342 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1343 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001344 * @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 -08001345 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001346 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 * @return The URI for the newly inserted item.
1348 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001349 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350
1351 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001352 * Override this to handle requests to insert a set of new rows, or the
1353 * default implementation will iterate over the values and call
1354 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1356 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001357 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001358 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1359 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 *
1361 * @param uri The content:// URI of the insertion request.
1362 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001363 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 * @return The number of values that were inserted.
1365 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001366 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 int numValues = values.length;
1368 for (int i = 0; i < numValues; i++) {
1369 insert(uri, values[i]);
1370 }
1371 return numValues;
1372 }
1373
1374 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001375 * Implement this to handle requests to delete one or more rows.
1376 * The implementation should apply the selection clause when performing
1377 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001378 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001380 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001381 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1382 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 *
1384 * <p>The implementation is responsible for parsing out a row ID at the end
1385 * of the URI, if a specific row is being deleted. That is, the client would
1386 * pass in <code>content://contacts/people/22</code> and the implementation is
1387 * responsible for parsing the record number (22) when creating a SQL statement.
1388 *
1389 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1390 * @param selection An optional restriction to apply to rows when deleting.
1391 * @return The number of rows affected.
1392 * @throws SQLException
1393 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001394 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1395 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396
1397 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001398 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001399 * The implementation should update all rows matching the selection
1400 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1402 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001403 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001404 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1405 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 *
1407 * @param uri The URI to query. This can potentially have a record ID if this
1408 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001409 * @param values A set of column_name/value pairs to update in the database.
1410 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 * @param selection An optional filter to match rows to update.
1412 * @return the number of rows affected.
1413 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001414 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001415 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416
1417 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001418 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001419 * The default implementation always throws {@link FileNotFoundException}.
1420 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001421 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1422 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001423 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001424 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1425 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001426 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 *
1428 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1429 * their responsibility to close it when done. That is, the implementation
1430 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001431 * <p>
1432 * If opened with the exclusive "r" or "w" modes, the returned
1433 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1434 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1435 * supports seeking.
1436 * <p>
1437 * If you need to detect when the returned ParcelFileDescriptor has been
1438 * closed, or if the remote process has crashed or encountered some other
1439 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1440 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1441 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1442 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001443 * <p>
1444 * If you need to return a large file that isn't backed by a real file on
1445 * disk, such as a file on a network share or cloud storage service,
1446 * consider using
1447 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1448 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001450 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1451 * to return the appropriate MIME type for the data returned here with
1452 * the same URI. This will allow intent resolution to automatically determine the data MIME
1453 * type and select the appropriate matching targets as part of its operation.</p>
1454 *
1455 * <p class="note">For better interoperability with other applications, it is recommended
1456 * that for any URIs that can be opened, you also support queries on them
1457 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1458 * You may also want to support other common columns if you have additional meta-data
1459 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1460 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1461 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 * @param uri The URI whose file is to be opened.
1463 * @param mode Access mode for the file. May be "r" for read-only access,
1464 * "rw" for read and write access, or "rwt" for read and write access
1465 * that truncates any existing file.
1466 *
1467 * @return Returns a new ParcelFileDescriptor which you can use to access
1468 * the file.
1469 *
1470 * @throws FileNotFoundException Throws FileNotFoundException if there is
1471 * no file associated with the given URI or the mode is invalid.
1472 * @throws SecurityException Throws SecurityException if the caller does
1473 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001474 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 * @see #openAssetFile(Uri, String)
1476 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001477 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001478 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001479 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001480 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 throws FileNotFoundException {
1482 throw new FileNotFoundException("No files supported by provider at "
1483 + uri);
1484 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001487 * Override this to handle requests to open a file blob.
1488 * The default implementation always throws {@link FileNotFoundException}.
1489 * This method can be called from multiple threads, as described in
1490 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1491 * and Threads</a>.
1492 *
1493 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1494 * to the caller. This way large data (such as images and documents) can be
1495 * returned without copying the content.
1496 *
1497 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1498 * their responsibility to close it when done. That is, the implementation
1499 * of this method should create a new ParcelFileDescriptor for each call.
1500 * <p>
1501 * If opened with the exclusive "r" or "w" modes, the returned
1502 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1503 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1504 * supports seeking.
1505 * <p>
1506 * If you need to detect when the returned ParcelFileDescriptor has been
1507 * closed, or if the remote process has crashed or encountered some other
1508 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1509 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1510 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1511 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1512 *
1513 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1514 * to return the appropriate MIME type for the data returned here with
1515 * the same URI. This will allow intent resolution to automatically determine the data MIME
1516 * type and select the appropriate matching targets as part of its operation.</p>
1517 *
1518 * <p class="note">For better interoperability with other applications, it is recommended
1519 * that for any URIs that can be opened, you also support queries on them
1520 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1521 * You may also want to support other common columns if you have additional meta-data
1522 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1523 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1524 *
1525 * @param uri The URI whose file is to be opened.
1526 * @param mode Access mode for the file. May be "r" for read-only access,
1527 * "w" for write-only access, "rw" for read and write access, or
1528 * "rwt" for read and write access that truncates any existing
1529 * file.
1530 * @param signal A signal to cancel the operation in progress, or
1531 * {@code null} if none. For example, if you are downloading a
1532 * file from the network to service a "rw" mode request, you
1533 * should periodically call
1534 * {@link CancellationSignal#throwIfCanceled()} to check whether
1535 * the client has canceled the request and abort the download.
1536 *
1537 * @return Returns a new ParcelFileDescriptor which you can use to access
1538 * the file.
1539 *
1540 * @throws FileNotFoundException Throws FileNotFoundException if there is
1541 * no file associated with the given URI or the mode is invalid.
1542 * @throws SecurityException Throws SecurityException if the caller does
1543 * not have permission to access the file.
1544 *
1545 * @see #openAssetFile(Uri, String)
1546 * @see #openFileHelper(Uri, String)
1547 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001548 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001549 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001550 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1551 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001552 return openFile(uri, mode);
1553 }
1554
1555 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 * This is like {@link #openFile}, but can be implemented by providers
1557 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001558 * inside of their .apk.
1559 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001560 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1561 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001562 *
1563 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001564 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001565 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1567 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1568 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001569 * <p>
1570 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1571 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001572 *
1573 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 * should create the AssetFileDescriptor with
1575 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001576 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001578 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1579 * to return the appropriate MIME type for the data returned here with
1580 * the same URI. This will allow intent resolution to automatically determine the data MIME
1581 * type and select the appropriate matching targets as part of its operation.</p>
1582 *
1583 * <p class="note">For better interoperability with other applications, it is recommended
1584 * that for any URIs that can be opened, you also support queries on them
1585 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1586 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 * @param uri The URI whose file is to be opened.
1588 * @param mode Access mode for the file. May be "r" for read-only access,
1589 * "w" for write-only access (erasing whatever data is currently in
1590 * the file), "wa" for write-only access to append to any existing data,
1591 * "rw" for read and write access on any existing data, and "rwt" for read
1592 * and write access that truncates any existing file.
1593 *
1594 * @return Returns a new AssetFileDescriptor which you can use to access
1595 * the file.
1596 *
1597 * @throws FileNotFoundException Throws FileNotFoundException if there is
1598 * no file associated with the given URI or the mode is invalid.
1599 * @throws SecurityException Throws SecurityException if the caller does
1600 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001601 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 * @see #openFile(Uri, String)
1603 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001604 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001606 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 throws FileNotFoundException {
1608 ParcelFileDescriptor fd = openFile(uri, mode);
1609 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1610 }
1611
1612 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001613 * This is like {@link #openFile}, but can be implemented by providers
1614 * that need to be able to return sub-sections of files, often assets
1615 * inside of their .apk.
1616 * This method can be called from multiple threads, as described in
1617 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1618 * and Threads</a>.
1619 *
1620 * <p>If you implement this, your clients must be able to deal with such
1621 * file slices, either directly with
1622 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1623 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1624 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1625 * methods.
1626 * <p>
1627 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1628 * streaming of data.
1629 *
1630 * <p class="note">If you are implementing this to return a full file, you
1631 * should create the AssetFileDescriptor with
1632 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1633 * applications that cannot handle sub-sections of files.</p>
1634 *
1635 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1636 * to return the appropriate MIME type for the data returned here with
1637 * the same URI. This will allow intent resolution to automatically determine the data MIME
1638 * type and select the appropriate matching targets as part of its operation.</p>
1639 *
1640 * <p class="note">For better interoperability with other applications, it is recommended
1641 * that for any URIs that can be opened, you also support queries on them
1642 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1643 *
1644 * @param uri The URI whose file is to be opened.
1645 * @param mode Access mode for the file. May be "r" for read-only access,
1646 * "w" for write-only access (erasing whatever data is currently in
1647 * the file), "wa" for write-only access to append to any existing data,
1648 * "rw" for read and write access on any existing data, and "rwt" for read
1649 * and write access that truncates any existing file.
1650 * @param signal A signal to cancel the operation in progress, or
1651 * {@code null} if none. For example, if you are downloading a
1652 * file from the network to service a "rw" mode request, you
1653 * should periodically call
1654 * {@link CancellationSignal#throwIfCanceled()} to check whether
1655 * the client has canceled the request and abort the download.
1656 *
1657 * @return Returns a new AssetFileDescriptor which you can use to access
1658 * the file.
1659 *
1660 * @throws FileNotFoundException Throws FileNotFoundException if there is
1661 * no file associated with the given URI or the mode is invalid.
1662 * @throws SecurityException Throws SecurityException if the caller does
1663 * not have permission to access the file.
1664 *
1665 * @see #openFile(Uri, String)
1666 * @see #openFileHelper(Uri, String)
1667 * @see #getType(android.net.Uri)
1668 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001669 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1670 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001671 return openAssetFile(uri, mode);
1672 }
1673
1674 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 * Convenience for subclasses that wish to implement {@link #openFile}
1676 * by looking up a column named "_data" at the given URI.
1677 *
1678 * @param uri The URI to be opened.
1679 * @param mode The file mode. May be "r" for read-only access,
1680 * "w" for write-only access (erasing whatever data is currently in
1681 * the file), "wa" for write-only access to append to any existing data,
1682 * "rw" for read and write access on any existing data, and "rwt" for read
1683 * and write access that truncates any existing file.
1684 *
1685 * @return Returns a new ParcelFileDescriptor that can be used by the
1686 * client to access the file.
1687 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001688 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1689 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1691 int count = (c != null) ? c.getCount() : 0;
1692 if (count != 1) {
1693 // If there is not exactly one result, throw an appropriate
1694 // exception.
1695 if (c != null) {
1696 c.close();
1697 }
1698 if (count == 0) {
1699 throw new FileNotFoundException("No entry for " + uri);
1700 }
1701 throw new FileNotFoundException("Multiple items at " + uri);
1702 }
1703
1704 c.moveToFirst();
1705 int i = c.getColumnIndex("_data");
1706 String path = (i >= 0 ? c.getString(i) : null);
1707 c.close();
1708 if (path == null) {
1709 throw new FileNotFoundException("Column _data not found.");
1710 }
1711
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001712 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 return ParcelFileDescriptor.open(new File(path), modeBits);
1714 }
1715
1716 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001717 * Called by a client to determine the types of data streams that this
1718 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001719 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001720 * of a particular type, return that MIME type if it matches the given
1721 * mimeTypeFilter. If it can perform type conversions, return an array
1722 * of all supported MIME types that match mimeTypeFilter.
1723 *
1724 * @param uri The data in the content provider being queried.
1725 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001726 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001727 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001728 * given mimeTypeFilter. Otherwise returns an array of all available
1729 * concrete MIME types.
1730 *
1731 * @see #getType(Uri)
1732 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001733 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001734 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001735 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001736 return null;
1737 }
1738
1739 /**
1740 * Called by a client to open a read-only stream containing data of a
1741 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1742 * except the file can only be read-only and the content provider may
1743 * perform data conversions to generate data of the desired type.
1744 *
1745 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001746 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001747 * {@link #openAssetFile(Uri, String)}.
1748 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001749 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001750 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001751 * <p>
1752 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1753 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001754 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001755 * <p class="note">For better interoperability with other applications, it is recommended
1756 * that for any URIs that can be opened, you also support queries on them
1757 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1758 * You may also want to support other common columns if you have additional meta-data
1759 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1760 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1761 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001762 * @param uri The data in the content provider being queried.
1763 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001764 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001765 * requirements; in this case the content provider will pick its best
1766 * type matching the pattern.
1767 * @param opts Additional options from the client. The definitions of
1768 * these are specific to the content provider being called.
1769 *
1770 * @return Returns a new AssetFileDescriptor from which the client can
1771 * read data of the desired type.
1772 *
1773 * @throws FileNotFoundException Throws FileNotFoundException if there is
1774 * no file associated with the given URI or the mode is invalid.
1775 * @throws SecurityException Throws SecurityException if the caller does
1776 * not have permission to access the data.
1777 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1778 * content provider does not support the requested MIME type.
1779 *
1780 * @see #getStreamTypes(Uri, String)
1781 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001782 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001783 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001784 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1785 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001786 if ("*/*".equals(mimeTypeFilter)) {
1787 // If they can take anything, the untyped open call is good enough.
1788 return openAssetFile(uri, "r");
1789 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001790 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001791 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001792 // Use old untyped open call if this provider has a type for this
1793 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001794 return openAssetFile(uri, "r");
1795 }
1796 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1797 }
1798
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001799
1800 /**
1801 * Called by a client to open a read-only stream containing data of a
1802 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1803 * except the file can only be read-only and the content provider may
1804 * perform data conversions to generate data of the desired type.
1805 *
1806 * <p>The default implementation compares the given mimeType against the
1807 * result of {@link #getType(Uri)} and, if they match, simply calls
1808 * {@link #openAssetFile(Uri, String)}.
1809 *
1810 * <p>See {@link ClipData} for examples of the use and implementation
1811 * of this method.
1812 * <p>
1813 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1814 * streaming of data.
1815 *
1816 * <p class="note">For better interoperability with other applications, it is recommended
1817 * that for any URIs that can be opened, you also support queries on them
1818 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1819 * You may also want to support other common columns if you have additional meta-data
1820 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1821 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1822 *
1823 * @param uri The data in the content provider being queried.
1824 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001825 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001826 * requirements; in this case the content provider will pick its best
1827 * type matching the pattern.
1828 * @param opts Additional options from the client. The definitions of
1829 * these are specific to the content provider being called.
1830 * @param signal A signal to cancel the operation in progress, or
1831 * {@code null} if none. For example, if you are downloading a
1832 * file from the network to service a "rw" mode request, you
1833 * should periodically call
1834 * {@link CancellationSignal#throwIfCanceled()} to check whether
1835 * the client has canceled the request and abort the download.
1836 *
1837 * @return Returns a new AssetFileDescriptor from which the client can
1838 * read data of the desired type.
1839 *
1840 * @throws FileNotFoundException Throws FileNotFoundException if there is
1841 * no file associated with the given URI or the mode is invalid.
1842 * @throws SecurityException Throws SecurityException if the caller does
1843 * not have permission to access the data.
1844 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1845 * content provider does not support the requested MIME type.
1846 *
1847 * @see #getStreamTypes(Uri, String)
1848 * @see #openAssetFile(Uri, String)
1849 * @see ClipDescription#compareMimeTypes(String, String)
1850 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001851 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1852 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1853 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001854 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1855 }
1856
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001857 /**
1858 * Interface to write a stream of data to a pipe. Use with
1859 * {@link ContentProvider#openPipeHelper}.
1860 */
1861 public interface PipeDataWriter<T> {
1862 /**
1863 * Called from a background thread to stream data out to a pipe.
1864 * Note that the pipe is blocking, so this thread can block on
1865 * writes for an arbitrary amount of time if the client is slow
1866 * at reading.
1867 *
1868 * @param output The pipe where data should be written. This will be
1869 * closed for you upon returning from this function.
1870 * @param uri The URI whose data is to be written.
1871 * @param mimeType The desired type of data to be written.
1872 * @param opts Options supplied by caller.
1873 * @param args Your own custom arguments.
1874 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001875 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1876 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001877 }
1878
1879 /**
1880 * A helper function for implementing {@link #openTypedAssetFile}, for
1881 * creating a data pipe and background thread allowing you to stream
1882 * generated data back to the client. This function returns a new
1883 * ParcelFileDescriptor that should be returned to the caller (the caller
1884 * is responsible for closing it).
1885 *
1886 * @param uri The URI whose data is to be written.
1887 * @param mimeType The desired type of data to be written.
1888 * @param opts Options supplied by caller.
1889 * @param args Your own custom arguments.
1890 * @param func Interface implementing the function that will actually
1891 * stream the data.
1892 * @return Returns a new ParcelFileDescriptor holding the read side of
1893 * the pipe. This should be returned to the caller for reading; the caller
1894 * is responsible for closing it when done.
1895 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001896 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1897 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1898 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001899 try {
1900 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1901
1902 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1903 @Override
1904 protected Object doInBackground(Object... params) {
1905 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1906 try {
1907 fds[1].close();
1908 } catch (IOException e) {
1909 Log.w(TAG, "Failure closing pipe", e);
1910 }
1911 return null;
1912 }
1913 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001914 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001915
1916 return fds[0];
1917 } catch (IOException e) {
1918 throw new FileNotFoundException("failure making pipe");
1919 }
1920 }
1921
1922 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 * Returns true if this instance is a temporary content provider.
1924 * @return true if this instance is a temporary content provider
1925 */
1926 protected boolean isTemporary() {
1927 return false;
1928 }
1929
1930 /**
1931 * Returns the Binder object for this provider.
1932 *
1933 * @return the Binder object for this provider
1934 * @hide
1935 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001936 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 public IContentProvider getIContentProvider() {
1938 return mTransport;
1939 }
1940
1941 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001942 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1943 * when directly instantiating the provider for testing.
1944 * @hide
1945 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001946 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001947 public void attachInfoForTesting(Context context, ProviderInfo info) {
1948 attachInfo(context, info, true);
1949 }
1950
1951 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 * After being instantiated, this is called to tell the content provider
1953 * about itself.
1954 *
1955 * @param context The context this provider is running in
1956 * @param info Registered information about this content provider
1957 */
1958 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001959 attachInfo(context, info, false);
1960 }
1961
1962 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001963 mNoPerms = testing;
1964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 /*
1966 * Only allow it to be set once, so after the content service gives
1967 * this to us clients can't change it.
1968 */
1969 if (mContext == null) {
1970 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06001971 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001972 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1973 Context.APP_OPS_SERVICE);
1974 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001975 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 if (info != null) {
1977 setReadPermission(info.readPermission);
1978 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001979 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001980 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001981 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001982 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984 ContentProvider.this.onCreate();
1985 }
1986 }
Fred Quintanace31b232009-05-04 16:01:15 -07001987
1988 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001989 * Override this to handle requests to perform a batch of operations, or the
1990 * default implementation will iterate over the operations and call
1991 * {@link ContentProviderOperation#apply} on each of them.
1992 * If all calls to {@link ContentProviderOperation#apply} succeed
1993 * then a {@link ContentProviderResult} array with as many
1994 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001995 * fail, it is up to the implementation how many of the others take effect.
1996 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001997 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1998 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001999 *
Fred Quintanace31b232009-05-04 16:01:15 -07002000 * @param operations the operations to apply
2001 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002002 * @throws OperationApplicationException thrown if any operation fails.
2003 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002004 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002005 public @NonNull ContentProviderResult[] applyBatch(
2006 @NonNull ArrayList<ContentProviderOperation> operations)
2007 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002008 final int numOperations = operations.size();
2009 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2010 for (int i = 0; i < numOperations; i++) {
2011 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002012 }
2013 return results;
2014 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002015
2016 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002017 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002018 * interfaces that are cheaper and/or unnatural for a table-like
2019 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002020 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002021 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2022 * on this entry into the content provider besides the basic ability for the application
2023 * to get access to the provider at all. For example, it has no idea whether the call
2024 * being executed may read or write data in the provider, so can't enforce those
2025 * individual permissions. Any implementation of this method <strong>must</strong>
2026 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2027 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002028 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2029 * @param arg provider-defined String argument. May be {@code null}.
2030 * @param extras provider-defined Bundle argument. May be {@code null}.
2031 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002032 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002033 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002034 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2035 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002036 return null;
2037 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002038
2039 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002040 * Implement this to shut down the ContentProvider instance. You can then
2041 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002042 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002043 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002044 * Android normally handles ContentProvider startup and shutdown
2045 * automatically. You do not need to start up or shut down a
2046 * ContentProvider. When you invoke a test method on a ContentProvider,
2047 * however, a ContentProvider instance is started and keeps running after
2048 * the test finishes, even if a succeeding test instantiates another
2049 * ContentProvider. A conflict develops because the two instances are
2050 * usually running against the same underlying data source (for example, an
2051 * sqlite database).
2052 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002053 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002054 * Implementing shutDown() avoids this conflict by providing a way to
2055 * terminate the ContentProvider. This method can also prevent memory leaks
2056 * from multiple instantiations of the ContentProvider, and it can ensure
2057 * unit test isolation by allowing you to completely clean up the test
2058 * fixture before moving on to the next test.
2059 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002060 */
2061 public void shutdown() {
2062 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2063 "connections are gracefully shutdown");
2064 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002065
2066 /**
2067 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002068 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002069 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002070 * @param fd The raw file descriptor that the dump is being sent to.
2071 * @param writer The PrintWriter to which you should dump your state. This will be
2072 * closed for you after you return.
2073 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002074 */
2075 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2076 writer.println("nothing to dump");
2077 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002078
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002079 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002080 @VisibleForTesting
2081 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002082 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002083 if (!mSingleUser) {
2084 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2085 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2086 throw new SecurityException("trying to query a ContentProvider in user "
2087 + mContext.getUserId() + " with a uri belonging to user " + userId);
2088 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002089 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002090 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2091 String message = "The authority of the uri " + uri + " does not match the one of the "
2092 + "contentProvider: ";
2093 if (mAuthority != null) {
2094 message += mAuthority;
2095 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002096 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002097 }
2098 throw new SecurityException(message);
2099 }
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002100
2101 // Normalize the path by removing any empty path segments, which can be
2102 // a source of security issues.
2103 final String encodedPath = uri.getEncodedPath();
2104 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
2105 return uri.buildUpon().encodedPath(encodedPath.replaceAll("//+", "/")).build();
2106 } else {
2107 return uri;
2108 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002109 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002110
2111 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002112 private Uri maybeGetUriWithoutUserId(Uri uri) {
2113 if (mSingleUser) {
2114 return uri;
2115 }
2116 return getUriWithoutUserId(uri);
2117 }
2118
2119 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002120 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2121 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002122 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002123 if (end == -1) return defaultUserId;
2124 String userIdString = auth.substring(0, end);
2125 try {
2126 return Integer.parseInt(userIdString);
2127 } catch (NumberFormatException e) {
2128 Log.w(TAG, "Error parsing userId.", e);
2129 return UserHandle.USER_NULL;
2130 }
2131 }
2132
2133 /** @hide */
2134 public static int getUserIdFromAuthority(String auth) {
2135 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2136 }
2137
2138 /** @hide */
2139 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2140 if (uri == null) return defaultUserId;
2141 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2142 }
2143
2144 /** @hide */
2145 public static int getUserIdFromUri(Uri uri) {
2146 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2147 }
2148
2149 /**
2150 * Removes userId part from authority string. Expects format:
2151 * userId@some.authority
2152 * If there is no userId in the authority, it symply returns the argument
2153 * @hide
2154 */
2155 public static String getAuthorityWithoutUserId(String auth) {
2156 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002157 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002158 return auth.substring(end+1);
2159 }
2160
2161 /** @hide */
2162 public static Uri getUriWithoutUserId(Uri uri) {
2163 if (uri == null) return null;
2164 Uri.Builder builder = uri.buildUpon();
2165 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2166 return builder.build();
2167 }
2168
2169 /** @hide */
2170 public static boolean uriHasUserId(Uri uri) {
2171 if (uri == null) return false;
2172 return !TextUtils.isEmpty(uri.getUserInfo());
2173 }
2174
2175 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002176 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002177 public static Uri maybeAddUserId(Uri uri, int userId) {
2178 if (uri == null) return null;
2179 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002180 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002181 if (!uriHasUserId(uri)) {
2182 //We don't add the user Id if there's already one
2183 Uri.Builder builder = uri.buildUpon();
2184 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2185 return builder.build();
2186 }
2187 }
2188 return uri;
2189 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002190}