blob: a13a438cd7f788afa1171f34f414178b36c06609 [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>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700105 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700107public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800108
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700109 private static final String TAG = "ContentProvider";
110
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900111 /*
112 * Note: if you add methods to ContentProvider, you must add similar methods to
113 * MockContentProvider.
114 */
115
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100116 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700118 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100119
120 // Since most Providers have only one authority, we keep both a String and a String[] to improve
121 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100122 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100123 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100124 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100125 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100126 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100128 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100130 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700131 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700132 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800133 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700134 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Steve McKayea93fe72016-12-02 11:35:35 -0800136 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private Transport mTransport = new Transport();
139
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700140 /**
141 * Construct a ContentProvider instance. Content providers must be
142 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
143 * in the manifest</a>, accessed with {@link ContentResolver}, and created
144 * automatically by the system, so applications usually do not create
145 * ContentProvider instances directly.
146 *
147 * <p>At construction time, the object is uninitialized, and most fields and
148 * methods are unavailable. Subclasses should initialize themselves in
149 * {@link #onCreate}, not the constructor.
150 *
151 * <p>Content providers are created on the application main thread at
152 * application launch time. The constructor must not perform lengthy
153 * operations, or application startup will be delayed.
154 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900155 public ContentProvider() {
156 }
157
158 /**
159 * Constructor just for mocking.
160 *
161 * @param context A Context object which should be some mock instance (like the
162 * instance of {@link android.test.mock.MockContext}).
163 * @param readPermission The read permision you want this instance should have in the
164 * test, which is available via {@link #getReadPermission()}.
165 * @param writePermission The write permission you want this instance should have
166 * in the test, which is available via {@link #getWritePermission()}.
167 * @param pathPermissions The PathPermissions you want this instance should have
168 * in the test, which is available via {@link #getPathPermissions()}.
169 * @hide
170 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100171 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900172 public ContentProvider(
173 Context context,
174 String readPermission,
175 String writePermission,
176 PathPermission[] pathPermissions) {
177 mContext = context;
178 mReadPermission = readPermission;
179 mWritePermission = writePermission;
180 mPathPermissions = pathPermissions;
181 }
182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 /**
184 * Given an IContentProvider, try to coerce it back to the real
185 * ContentProvider object if it is running in the local process. This can
186 * be used if you know you are running in the same process as a provider,
187 * and want to get direct access to its implementation details. Most
188 * clients should not nor have a reason to use it.
189 *
190 * @param abstractInterface The ContentProvider interface that is to be
191 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800192 * @return If the IContentProvider is non-{@code null} and local, returns its actual
193 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 * @hide
195 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100196 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 public static ContentProvider coerceToLocalContentProvider(
198 IContentProvider abstractInterface) {
199 if (abstractInterface instanceof Transport) {
200 return ((Transport)abstractInterface).getContentProvider();
201 }
202 return null;
203 }
204
205 /**
206 * Binder object that deals with remoting.
207 *
208 * @hide
209 */
210 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800211 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800212 int mReadOp = AppOpsManager.OP_NONE;
213 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 ContentProvider getContentProvider() {
216 return ContentProvider.this;
217 }
218
Jeff Brownd2183652011-10-09 12:39:53 -0700219 @Override
220 public String getProviderName() {
221 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 }
223
Jeff Brown75ea64f2012-01-25 19:37:13 -0800224 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800225 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
226 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600227 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100228 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800229 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700230 // The caller has no access to the data, so return an empty cursor with
231 // the columns in the requested order. The caller may ask for an invalid
232 // column and we would not catch that but this is not a problem in practice.
233 // We do not call ContentProvider#query with a modified where clause since
234 // the implementation is not guaranteed to be backed by a SQL database, hence
235 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700236 if (projection != null) {
237 return new MatrixCursor(projection, 0);
238 }
239
240 // Null projection means all columns but we have no idea which they are.
241 // However, the caller may be expecting to access them my index. Hence,
242 // we have to execute the query as if allowed to get a cursor with the
243 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700244 Cursor cursor;
245 final String original = setCallingPackage(callingPkg);
246 try {
247 cursor = ContentProvider.this.query(
248 uri, projection, queryArgs,
249 CancellationSignal.fromTransport(cancellationSignal));
250 } finally {
251 setCallingPackage(original);
252 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700253 if (cursor == null) {
254 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700255 }
256
257 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700258 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800259 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600260 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700261 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700262 try {
263 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800264 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700265 CancellationSignal.fromTransport(cancellationSignal));
266 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700267 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600268 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 }
271
Jeff Brown75ea64f2012-01-25 19:37:13 -0800272 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700274 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600275 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100276 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600277 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
278 try {
279 return ContentProvider.this.getType(uri);
280 } finally {
281 Trace.traceEnd(TRACE_TAG_DATABASE);
282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284
Jeff Brown75ea64f2012-01-25 19:37:13 -0800285 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800286 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600287 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100288 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100289 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800290 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700291 final String original = setCallingPackage(callingPkg);
292 try {
293 return rejectInsert(uri, initialValues);
294 } finally {
295 setCallingPackage(original);
296 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800297 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600298 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700299 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700300 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100301 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700302 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700303 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600304 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 }
307
Jeff Brown75ea64f2012-01-25 19:37:13 -0800308 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800309 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600310 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100311 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800312 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800313 return 0;
314 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600315 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700316 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700317 try {
318 return ContentProvider.this.bulkInsert(uri, initialValues);
319 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700320 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600321 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
324
Jeff Brown75ea64f2012-01-25 19:37:13 -0800325 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800326 public ContentProviderResult[] applyBatch(String callingPkg,
327 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700328 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100329 int numOperations = operations.size();
330 final int[] userIds = new int[numOperations];
331 for (int i = 0; i < numOperations; i++) {
332 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100333 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600334 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600335 uri = validateIncomingUri(uri);
336 uri = maybeGetUriWithoutUserId(uri);
337 // Rebuild operation if we changed the Uri above
338 if (!Objects.equals(operation.getUri(), uri)) {
339 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100340 operations.set(i, operation);
341 }
Fred Quintana89437372009-05-15 15:10:40 -0700342 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800343 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800344 != AppOpsManager.MODE_ALLOWED) {
345 throw new OperationApplicationException("App op not allowed", 0);
346 }
Fred Quintana89437372009-05-15 15:10:40 -0700347 }
Fred Quintana89437372009-05-15 15:10:40 -0700348 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800349 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800350 != AppOpsManager.MODE_ALLOWED) {
351 throw new OperationApplicationException("App op not allowed", 0);
352 }
Fred Quintana89437372009-05-15 15:10:40 -0700353 }
354 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600355 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700356 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700357 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100358 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800359 if (results != null) {
360 for (int i = 0; i < results.length ; i++) {
361 if (userIds[i] != UserHandle.USER_CURRENT) {
362 // Adding the userId to the uri.
363 results[i] = new ContentProviderResult(results[i], userIds[i]);
364 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100365 }
366 }
367 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700368 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600370 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700371 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700372 }
373
Jeff Brown75ea64f2012-01-25 19:37:13 -0800374 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800375 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600376 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100377 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800378 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800379 return 0;
380 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600381 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700382 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700383 try {
384 return ContentProvider.this.delete(uri, selection, selectionArgs);
385 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700386 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600387 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 }
390
Jeff Brown75ea64f2012-01-25 19:37:13 -0800391 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800392 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600394 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100395 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800396 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800397 return 0;
398 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600399 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700400 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 try {
402 return ContentProvider.this.update(uri, values, selection, selectionArgs);
403 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700404 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600405 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
408
Jeff Brown75ea64f2012-01-25 19:37:13 -0800409 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700410 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800411 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
412 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600413 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100414 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800415 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600416 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700417 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700418 try {
419 return ContentProvider.this.openFile(
420 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
421 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700422 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600423 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
426
Jeff Brown75ea64f2012-01-25 19:37:13 -0800427 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700428 public AssetFileDescriptor openAssetFile(
429 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600431 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100432 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800433 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600434 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700435 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700436 try {
437 return ContentProvider.this.openAssetFile(
438 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
439 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700440 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600441 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 }
444
Jeff Brown75ea64f2012-01-25 19:37:13 -0800445 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800446 public Bundle call(
447 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600448 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600449 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700450 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700451 try {
452 return ContentProvider.this.call(method, arg, extras);
453 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700454 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600455 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700456 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800457 }
458
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700459 @Override
460 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700461 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600462 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100463 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600464 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
465 try {
466 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
467 } finally {
468 Trace.traceEnd(TRACE_TAG_DATABASE);
469 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700470 }
471
472 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800473 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700474 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600475 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600476 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100477 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800478 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600479 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700480 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700481 try {
482 return ContentProvider.this.openTypedAssetFile(
483 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
484 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700485 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600486 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700487 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700488 }
489
Jeff Brown75ea64f2012-01-25 19:37:13 -0800490 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700491 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800492 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800493 }
494
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700495 @Override
496 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600497 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100498 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100499 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800500 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700501 return null;
502 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600503 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700504 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700505 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100506 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700507 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700508 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600509 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700510 }
511 }
512
513 @Override
514 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600515 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100516 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100517 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800518 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700519 return null;
520 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600521 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700522 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700523 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100524 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700525 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700526 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600527 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700528 }
529 }
530
Ben Lin1cf454f2016-11-10 13:50:54 -0800531 @Override
532 public boolean refresh(String callingPkg, Uri uri, Bundle args,
533 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600534 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800535 uri = getUriWithoutUserId(uri);
536 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
537 return false;
538 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600539 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800540 final String original = setCallingPackage(callingPkg);
541 try {
542 return ContentProvider.this.refresh(uri, args,
543 CancellationSignal.fromTransport(cancellationSignal));
544 } finally {
545 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600546 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800547 }
548 }
549
Dianne Hackbornff170242014-11-19 10:59:01 -0800550 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
551 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800552 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800553 if (enforceWritePermission(callingPkg, uri, callerToken)
554 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800555 throw new FileNotFoundException("App op not allowed");
556 }
557 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800558 if (enforceReadPermission(callingPkg, uri, callerToken)
559 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800560 throw new FileNotFoundException("App op not allowed");
561 }
562 }
563 }
564
Dianne Hackbornff170242014-11-19 10:59:01 -0800565 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
566 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700567 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
568 if (mode != MODE_ALLOWED) {
569 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800570 }
Svet Ganov99b60432015-06-27 13:15:22 -0700571
572 if (mReadOp != AppOpsManager.OP_NONE) {
573 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
574 }
575
Dianne Hackborn35654b62013-01-14 17:38:02 -0800576 return AppOpsManager.MODE_ALLOWED;
577 }
578
Dianne Hackbornff170242014-11-19 10:59:01 -0800579 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
580 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700581 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
582 if (mode != MODE_ALLOWED) {
583 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800584 }
Svet Ganov99b60432015-06-27 13:15:22 -0700585
586 if (mWriteOp != AppOpsManager.OP_NONE) {
587 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
588 }
589
Dianne Hackborn35654b62013-01-14 17:38:02 -0800590 return AppOpsManager.MODE_ALLOWED;
591 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700592 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800593
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100594 boolean checkUser(int pid, int uid, Context context) {
595 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700596 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100597 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
598 == PERMISSION_GRANTED;
599 }
600
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700601 /**
602 * Verify that calling app holds both the given permission and any app-op
603 * associated with that permission.
604 */
605 private int checkPermissionAndAppOp(String permission, String callingPkg,
606 IBinder callerToken) {
607 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
608 callerToken) != PERMISSION_GRANTED) {
609 return MODE_ERRORED;
610 }
611
612 final int permOp = AppOpsManager.permissionToOpCode(permission);
613 if (permOp != AppOpsManager.OP_NONE) {
614 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
615 }
616
617 return MODE_ALLOWED;
618 }
619
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700620 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700621 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800622 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700623 final Context context = getContext();
624 final int pid = Binder.getCallingPid();
625 final int uid = Binder.getCallingUid();
626 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700627 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700628
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700629 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700630 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700631 }
632
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100633 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700634 final String componentPerm = getReadPermission();
635 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700636 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
637 if (mode == MODE_ALLOWED) {
638 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700639 } else {
640 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700641 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700642 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700643 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700644
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700645 // track if unprotected read is allowed; any denied
646 // <path-permission> below removes this ability
647 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700648
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700649 final PathPermission[] pps = getPathPermissions();
650 if (pps != null) {
651 final String path = uri.getPath();
652 for (PathPermission pp : pps) {
653 final String pathPerm = pp.getReadPermission();
654 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700655 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
656 if (mode == MODE_ALLOWED) {
657 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700658 } else {
659 // any denied <path-permission> means we lose
660 // default <provider> access.
661 allowDefaultRead = false;
662 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700663 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700664 }
665 }
666 }
667 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700668
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700669 // if we passed <path-permission> checks above, and no default
670 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700671 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700673
674 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800675 final int callingUserId = UserHandle.getUserId(uid);
676 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
677 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800678 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
679 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700680 return MODE_ALLOWED;
681 }
682
683 // If the worst denial we found above was ignored, then pass that
684 // ignored through; otherwise we assume it should be a real error below.
685 if (strongestMode == MODE_IGNORED) {
686 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700687 }
688
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600689 final String suffix;
690 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
691 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
692 } else if (mExported) {
693 suffix = " requires " + missingPerm + ", or grantUriPermission()";
694 } else {
695 suffix = " requires the provider be exported, or grantUriPermission()";
696 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700697 throw new SecurityException("Permission Denial: reading "
698 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600699 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700700 }
701
702 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700703 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800704 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700705 final Context context = getContext();
706 final int pid = Binder.getCallingPid();
707 final int uid = Binder.getCallingUid();
708 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700709 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700710
711 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700712 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700713 }
714
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100715 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700716 final String componentPerm = getWritePermission();
717 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700718 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
719 if (mode == MODE_ALLOWED) {
720 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700721 } else {
722 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700723 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700724 }
725 }
726
727 // track if unprotected write is allowed; any denied
728 // <path-permission> below removes this ability
729 boolean allowDefaultWrite = (componentPerm == null);
730
731 final PathPermission[] pps = getPathPermissions();
732 if (pps != null) {
733 final String path = uri.getPath();
734 for (PathPermission pp : pps) {
735 final String pathPerm = pp.getWritePermission();
736 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700737 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
738 if (mode == MODE_ALLOWED) {
739 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700740 } else {
741 // any denied <path-permission> means we lose
742 // default <provider> access.
743 allowDefaultWrite = false;
744 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700745 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700746 }
747 }
748 }
749 }
750
751 // if we passed <path-permission> checks above, and no default
752 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700753 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700754 }
755
756 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800757 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
758 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700759 return MODE_ALLOWED;
760 }
761
762 // If the worst denial we found above was ignored, then pass that
763 // ignored through; otherwise we assume it should be a real error below.
764 if (strongestMode == MODE_IGNORED) {
765 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700766 }
767
768 final String failReason = mExported
769 ? " requires " + missingPerm + ", or grantUriPermission()"
770 : " requires the provider be exported, or grantUriPermission()";
771 throw new SecurityException("Permission Denial: writing "
772 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
773 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 }
775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700777 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800778 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 * constructor.
780 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700781 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 return mContext;
783 }
784
785 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700786 * Set the calling package, returning the current value (or {@code null})
787 * which can be used later to restore the previous state.
788 */
789 private String setCallingPackage(String callingPackage) {
790 final String original = mCallingPackage.get();
791 mCallingPackage.set(callingPackage);
792 return original;
793 }
794
795 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700796 * Return the package name of the caller that initiated the request being
797 * processed on the current thread. The returned package will have been
798 * verified to belong to the calling UID. Returns {@code null} if not
799 * currently processing a request.
800 * <p>
801 * This will always return {@code null} when processing
802 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
803 *
804 * @see Binder#getCallingUid()
805 * @see Context#grantUriPermission(String, Uri, int)
806 * @throws SecurityException if the calling package doesn't belong to the
807 * calling UID.
808 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700809 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700810 final String pkg = mCallingPackage.get();
811 if (pkg != null) {
812 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
813 }
814 return pkg;
815 }
816
817 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100818 * Change the authorities of the ContentProvider.
819 * This is normally set for you from its manifest information when the provider is first
820 * created.
821 * @hide
822 * @param authorities the semi-colon separated authorities of the ContentProvider.
823 */
824 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100825 if (authorities != null) {
826 if (authorities.indexOf(';') == -1) {
827 mAuthority = authorities;
828 mAuthorities = null;
829 } else {
830 mAuthority = null;
831 mAuthorities = authorities.split(";");
832 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100833 }
834 }
835
836 /** @hide */
837 protected final boolean matchesOurAuthorities(String authority) {
838 if (mAuthority != null) {
839 return mAuthority.equals(authority);
840 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100841 if (mAuthorities != null) {
842 int length = mAuthorities.length;
843 for (int i = 0; i < length; i++) {
844 if (mAuthorities[i].equals(authority)) return true;
845 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100846 }
847 return false;
848 }
849
850
851 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 * Change the permission required to read data from the content
853 * provider. This is normally set for you from its manifest information
854 * when the provider is first created.
855 *
856 * @param permission Name of the permission required for read-only access.
857 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700858 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mReadPermission = permission;
860 }
861
862 /**
863 * Return the name of the permission required for read-only access to
864 * this content provider. This method can be called from multiple
865 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800866 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
867 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700869 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 return mReadPermission;
871 }
872
873 /**
874 * Change the permission required to read and write data in the content
875 * provider. This is normally set for you from its manifest information
876 * when the provider is first created.
877 *
878 * @param permission Name of the permission required for read/write access.
879 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700880 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 mWritePermission = permission;
882 }
883
884 /**
885 * Return the name of the permission required for read/write access to
886 * this content provider. This method can be called from multiple
887 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800888 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
889 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700891 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 return mWritePermission;
893 }
894
895 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700896 * Change the path-based permission required to read and/or write data in
897 * the content provider. This is normally set for you from its manifest
898 * information when the provider is first created.
899 *
900 * @param permissions Array of path permission descriptions.
901 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700902 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700903 mPathPermissions = permissions;
904 }
905
906 /**
907 * Return the path-based permissions required for read and/or write access to
908 * this content provider. This method can be called from multiple
909 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800910 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
911 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700912 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700913 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700914 return mPathPermissions;
915 }
916
Dianne Hackborn35654b62013-01-14 17:38:02 -0800917 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100918 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800919 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800920 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800921 mTransport.mReadOp = readOp;
922 mTransport.mWriteOp = writeOp;
923 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800924 }
925
Dianne Hackborn961321f2013-02-05 17:22:41 -0800926 /** @hide */
927 public AppOpsManager getAppOpsManager() {
928 return mTransport.mAppOpsManager;
929 }
930
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700931 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700932 * Implement this to initialize your content provider on startup.
933 * This method is called for all registered content providers on the
934 * application main thread at application launch time. It must not perform
935 * lengthy operations, or application startup will be delayed.
936 *
937 * <p>You should defer nontrivial initialization (such as opening,
938 * upgrading, and scanning databases) until the content provider is used
939 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
940 * keeps application startup fast, avoids unnecessary work if the provider
941 * turns out not to be needed, and stops database errors (such as a full
942 * disk) from halting application launch.
943 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700944 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700945 * is a helpful utility class that makes it easy to manage databases,
946 * and will automatically defer opening until first use. If you do use
947 * SQLiteOpenHelper, make sure to avoid calling
948 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
949 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
950 * from this method. (Instead, override
951 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
952 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 *
954 * @return true if the provider was successfully loaded, false otherwise
955 */
956 public abstract boolean onCreate();
957
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700958 /**
959 * {@inheritDoc}
960 * This method is always called on the application main thread, and must
961 * not perform lengthy operations.
962 *
963 * <p>The default content provider implementation does nothing.
964 * Override this method to take appropriate action.
965 * (Content providers do not usually care about things like screen
966 * orientation, but may want to know about locale changes.)
967 */
Steve McKayea93fe72016-12-02 11:35:35 -0800968 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 public void onConfigurationChanged(Configuration newConfig) {
970 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700971
972 /**
973 * {@inheritDoc}
974 * This method is always called on the application main thread, and must
975 * not perform lengthy operations.
976 *
977 * <p>The default content provider implementation does nothing.
978 * Subclasses may override this method to take appropriate action.
979 */
Steve McKayea93fe72016-12-02 11:35:35 -0800980 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 public void onLowMemory() {
982 }
983
Steve McKayea93fe72016-12-02 11:35:35 -0800984 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700985 public void onTrimMemory(int level) {
986 }
987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700989 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800990 *
991 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
992 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
993 * implementation of this method.
994 *
995 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800996 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
997 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 * <p>
999 * Example client call:<p>
1000 * <pre>// Request a specific record.
1001 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001002 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 projection, // Which columns to return.
1004 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001005 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 People.NAME + " ASC"); // Sort order.</pre>
1007 * Example implementation:<p>
1008 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1009 // proper SQL syntax for us.
1010 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1011
1012 // Set the table we're querying.
1013 qBuilder.setTables(DATABASE_TABLE_NAME);
1014
1015 // If the query ends in a specific record number, we're
1016 // being asked for a specific record, so set the
1017 // WHERE clause in our query.
1018 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1019 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1020 }
1021
1022 // Make the query.
1023 Cursor c = qBuilder.query(mDb,
1024 projection,
1025 selection,
1026 selectionArgs,
1027 groupBy,
1028 having,
1029 sortOrder);
1030 c.setNotificationUri(getContext().getContentResolver(), uri);
1031 return c;</pre>
1032 *
1033 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001034 * if the client is requesting a specific record, the URI will end in a record number
1035 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1036 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001038 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001040 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001041 * @param selectionArgs You may include ?s in selection, which will be replaced by
1042 * the values from selectionArgs, in order that they appear in the selection.
1043 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001045 * If {@code null} then the provider is free to define the sort order.
1046 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001048 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1049 @Nullable String selection, @Nullable String[] selectionArgs,
1050 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051
Fred Quintana5bba6322009-10-05 14:21:12 -07001052 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001053 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001054 *
1055 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1056 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1057 *
1058 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001059 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1060 * and Threads</a>.
1061 * <p>
1062 * Example client call:<p>
1063 * <pre>// Request a specific record.
1064 * Cursor managedCursor = managedQuery(
1065 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1066 projection, // Which columns to return.
1067 null, // WHERE clause.
1068 null, // WHERE clause value substitution
1069 People.NAME + " ASC"); // Sort order.</pre>
1070 * Example implementation:<p>
1071 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1072 // proper SQL syntax for us.
1073 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1074
1075 // Set the table we're querying.
1076 qBuilder.setTables(DATABASE_TABLE_NAME);
1077
1078 // If the query ends in a specific record number, we're
1079 // being asked for a specific record, so set the
1080 // WHERE clause in our query.
1081 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1082 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1083 }
1084
1085 // Make the query.
1086 Cursor c = qBuilder.query(mDb,
1087 projection,
1088 selection,
1089 selectionArgs,
1090 groupBy,
1091 having,
1092 sortOrder);
1093 c.setNotificationUri(getContext().getContentResolver(), uri);
1094 return c;</pre>
1095 * <p>
1096 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001097 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1098 * signal to ensure correct operation on older versions of the Android Framework in
1099 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001100 *
1101 * @param uri The URI to query. This will be the full URI sent by the client;
1102 * if the client is requesting a specific record, the URI will end in a record number
1103 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1104 * that _id value.
1105 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001106 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001107 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001108 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001109 * @param selectionArgs You may include ?s in selection, which will be replaced by
1110 * the values from selectionArgs, in order that they appear in the selection.
1111 * The values will be bound as Strings.
1112 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001113 * If {@code null} then the provider is free to define the sort order.
1114 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001115 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001116 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001117 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001118 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001119 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1120 @Nullable String selection, @Nullable String[] selectionArgs,
1121 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001122 return query(uri, projection, selection, selectionArgs, sortOrder);
1123 }
1124
1125 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001126 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1127 * Arguments may include traditional SQL style query arguments. When present these
1128 * should be handled according to the contract established in
1129 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1130 *
1131 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001132 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1133 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1134 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001135 *
Steve McKay76b27702017-04-24 12:07:53 -07001136 * <p>This method can be called from multiple threads, as described in
1137 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1138 * and Threads</a>.
1139 *
1140 * <p>
1141 * Example client call:<p>
1142 * <pre>// Request 20 records starting at row index 30.
1143 Bundle queryArgs = new Bundle();
1144 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1145 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1146
1147 Cursor cursor = getContentResolver().query(
1148 contentUri, // Content Uri is specific to individual content providers.
1149 projection, // String[] describing which columns to return.
1150 queryArgs, // Query arguments.
1151 null); // Cancellation signal.</pre>
1152 *
1153 * Example implementation:<p>
1154 * <pre>
1155
1156 int recordsetSize = 0x1000; // Actual value is implementation specific.
1157 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1158
1159 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1160 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1161
1162 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1163
1164 // Calculate the number of items to include in the cursor.
1165 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1166
1167 // Build the paged result set....
1168 for (int i = offset; i < offset + numItems; i++) {
1169 // populate row from your data.
1170 }
1171
1172 Bundle extras = new Bundle();
1173 c.setExtras(extras);
1174
1175 // Any QUERY_ARG_* key may be included if honored.
1176 // In an actual implementation, include only keys that are both present in queryArgs
1177 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1178 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1179 // then QUERY_ARG_OFFSET should be omitted.
1180 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1181 ContentResolver.QUERY_ARG_OFFSET,
1182 ContentResolver.QUERY_ARG_LIMIT
1183 });
1184
1185 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1186
1187 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1188
1189 return cursor;</pre>
1190 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001191 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1192 * implementation details.
1193 *
1194 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001195 * @param projection The list of columns to put into the cursor.
1196 * If {@code null} provide a default set of columns.
1197 * @param queryArgs A Bundle containing all additional information necessary for the query.
1198 * Values in the Bundle may include SQL style arguments.
1199 * @param cancellationSignal A signal to cancel the operation in progress,
1200 * or {@code null}.
1201 * @return a Cursor or {@code null}.
1202 */
1203 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1204 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1205 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001206
Steve McKayd7ece9f2017-01-12 16:59:59 -08001207 // if client doesn't supply an SQL sort order argument, attempt to build one from
1208 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001209 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001210 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1211 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1212 }
1213
Steve McKayea93fe72016-12-02 11:35:35 -08001214 return query(
1215 uri,
1216 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001217 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1218 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1219 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001220 cancellationSignal);
1221 }
1222
1223 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001224 * Implement this to handle requests for the MIME type of the data at the
1225 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 * <code>vnd.android.cursor.item</code> for a single record,
1227 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001228 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001229 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1230 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001232 * <p>Note that there are no permissions needed for an application to
1233 * access this information; if your content provider requires read and/or
1234 * write permissions, or is not exported, all applications can still call
1235 * this method regardless of their access permissions. This allows them
1236 * to retrieve the MIME type for a URI when dispatching intents.
1237 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001239 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001241 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242
1243 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001244 * Implement this to support canonicalization of URIs that refer to your
1245 * content provider. A canonical URI is one that can be transported across
1246 * devices, backup/restore, and other contexts, and still be able to refer
1247 * to the same data item. Typically this is implemented by adding query
1248 * params to the URI allowing the content provider to verify that an incoming
1249 * canonical URI references the same data as it was originally intended for and,
1250 * if it doesn't, to find that data (if it exists) in the current environment.
1251 *
1252 * <p>For example, if the content provider holds people and a normal URI in it
1253 * is created with a row index into that people database, the cananical representation
1254 * may have an additional query param at the end which specifies the name of the
1255 * person it is intended for. Later calls into the provider with that URI will look
1256 * up the row of that URI's base index and, if it doesn't match or its entry's
1257 * name doesn't match the name in the query param, perform a query on its database
1258 * to find the correct row to operate on.</p>
1259 *
1260 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1261 * URIs (including this one) must perform this verification and recovery of any
1262 * canonical URIs they receive. In addition, you must also implement
1263 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1264 *
1265 * <p>The default implementation of this method returns null, indicating that
1266 * canonical URIs are not supported.</p>
1267 *
1268 * @param url The Uri to canonicalize.
1269 *
1270 * @return Return the canonical representation of <var>url</var>, or null if
1271 * canonicalization of that Uri is not supported.
1272 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001273 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001274 return null;
1275 }
1276
1277 /**
1278 * Remove canonicalization from canonical URIs previously returned by
1279 * {@link #canonicalize}. For example, if your implementation is to add
1280 * a query param to canonicalize a URI, this method can simply trip any
1281 * query params on the URI. The default implementation always returns the
1282 * same <var>url</var> that was passed in.
1283 *
1284 * @param url The Uri to remove any canonicalization from.
1285 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001286 * @return Return the non-canonical representation of <var>url</var>, return
1287 * the <var>url</var> as-is if there is nothing to do, or return null if
1288 * the data identified by the canonical representation can not be found in
1289 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001290 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001291 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001292 return url;
1293 }
1294
1295 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001296 * Implement this to support refresh of content identified by {@code uri}. By default, this
1297 * method returns false; providers who wish to implement this should return true to signal the
1298 * client that the provider has tried refreshing with its own implementation.
1299 * <p>
1300 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1301 * <p>
1302 * Client code should only invoke this method when there is a strong indication (such as a user
1303 * initiated pull to refresh gesture) that the content is stale.
1304 * <p>
1305 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1306 * notifications when content changes.
1307 *
1308 * @param uri The Uri identifying the data to refresh.
1309 * @param args Additional options from the client. The definitions of these are specific to the
1310 * content provider being called.
1311 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1312 * none. For example, if you called refresh on a particular uri, you should call
1313 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1314 * canceled the refresh request.
1315 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001316 */
1317 public boolean refresh(Uri uri, @Nullable Bundle args,
1318 @Nullable CancellationSignal cancellationSignal) {
1319 return false;
1320 }
1321
1322 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001323 * @hide
1324 * Implementation when a caller has performed an insert on the content
1325 * provider, but that call has been rejected for the operation given
1326 * to {@link #setAppOps(int, int)}. The default implementation simply
1327 * returns a dummy URI that is the base URI with a 0 path element
1328 * appended.
1329 */
1330 public Uri rejectInsert(Uri uri, ContentValues values) {
1331 // If not allowed, we need to return some reasonable URI. Maybe the
1332 // content provider should be responsible for this, but for now we
1333 // will just return the base URI with a dummy '0' tagged on to it.
1334 // You shouldn't be able to read if you can't write, anyway, so it
1335 // shouldn't matter much what is returned.
1336 return uri.buildUpon().appendPath("0").build();
1337 }
1338
1339 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001340 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1342 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001343 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001344 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1345 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001346 * @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 -08001347 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001348 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 * @return The URI for the newly inserted item.
1350 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001351 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352
1353 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001354 * Override this to handle requests to insert a set of new rows, or the
1355 * default implementation will iterate over the values and call
1356 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1358 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001359 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001360 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1361 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 *
1363 * @param uri The content:// URI of the insertion request.
1364 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001365 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 * @return The number of values that were inserted.
1367 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001368 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 int numValues = values.length;
1370 for (int i = 0; i < numValues; i++) {
1371 insert(uri, values[i]);
1372 }
1373 return numValues;
1374 }
1375
1376 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001377 * Implement this to handle requests to delete one or more rows.
1378 * The implementation should apply the selection clause when performing
1379 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001380 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001382 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001383 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1384 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 *
1386 * <p>The implementation is responsible for parsing out a row ID at the end
1387 * of the URI, if a specific row is being deleted. That is, the client would
1388 * pass in <code>content://contacts/people/22</code> and the implementation is
1389 * responsible for parsing the record number (22) when creating a SQL statement.
1390 *
1391 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1392 * @param selection An optional restriction to apply to rows when deleting.
1393 * @return The number of rows affected.
1394 * @throws SQLException
1395 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001396 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1397 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398
1399 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001400 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001401 * The implementation should update all rows matching the selection
1402 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1404 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001405 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001406 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1407 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 *
1409 * @param uri The URI to query. This can potentially have a record ID if this
1410 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001411 * @param values A set of column_name/value pairs to update in the database.
1412 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 * @param selection An optional filter to match rows to update.
1414 * @return the number of rows affected.
1415 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001416 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001417 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418
1419 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001420 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001421 * The default implementation always throws {@link FileNotFoundException}.
1422 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001423 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1424 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001425 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001426 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1427 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001428 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 *
1430 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1431 * their responsibility to close it when done. That is, the implementation
1432 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001433 * <p>
1434 * If opened with the exclusive "r" or "w" modes, the returned
1435 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1436 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1437 * supports seeking.
1438 * <p>
1439 * If you need to detect when the returned ParcelFileDescriptor has been
1440 * closed, or if the remote process has crashed or encountered some other
1441 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1442 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1443 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1444 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001445 * <p>
1446 * If you need to return a large file that isn't backed by a real file on
1447 * disk, such as a file on a network share or cloud storage service,
1448 * consider using
1449 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1450 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001452 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1453 * to return the appropriate MIME type for the data returned here with
1454 * the same URI. This will allow intent resolution to automatically determine the data MIME
1455 * type and select the appropriate matching targets as part of its operation.</p>
1456 *
1457 * <p class="note">For better interoperability with other applications, it is recommended
1458 * that for any URIs that can be opened, you also support queries on them
1459 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1460 * You may also want to support other common columns if you have additional meta-data
1461 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1462 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1463 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 * @param uri The URI whose file is to be opened.
1465 * @param mode Access mode for the file. May be "r" for read-only access,
1466 * "rw" for read and write access, or "rwt" for read and write access
1467 * that truncates any existing file.
1468 *
1469 * @return Returns a new ParcelFileDescriptor which you can use to access
1470 * the file.
1471 *
1472 * @throws FileNotFoundException Throws FileNotFoundException if there is
1473 * no file associated with the given URI or the mode is invalid.
1474 * @throws SecurityException Throws SecurityException if the caller does
1475 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001476 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 * @see #openAssetFile(Uri, String)
1478 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001479 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001480 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001481 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001482 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 throws FileNotFoundException {
1484 throw new FileNotFoundException("No files supported by provider at "
1485 + uri);
1486 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001489 * Override this to handle requests to open a file blob.
1490 * The default implementation always throws {@link FileNotFoundException}.
1491 * This method can be called from multiple threads, as described in
1492 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1493 * and Threads</a>.
1494 *
1495 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1496 * to the caller. This way large data (such as images and documents) can be
1497 * returned without copying the content.
1498 *
1499 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1500 * their responsibility to close it when done. That is, the implementation
1501 * of this method should create a new ParcelFileDescriptor for each call.
1502 * <p>
1503 * If opened with the exclusive "r" or "w" modes, the returned
1504 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1505 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1506 * supports seeking.
1507 * <p>
1508 * If you need to detect when the returned ParcelFileDescriptor has been
1509 * closed, or if the remote process has crashed or encountered some other
1510 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1511 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1512 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1513 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1514 *
1515 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1516 * to return the appropriate MIME type for the data returned here with
1517 * the same URI. This will allow intent resolution to automatically determine the data MIME
1518 * type and select the appropriate matching targets as part of its operation.</p>
1519 *
1520 * <p class="note">For better interoperability with other applications, it is recommended
1521 * that for any URIs that can be opened, you also support queries on them
1522 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1523 * You may also want to support other common columns if you have additional meta-data
1524 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1525 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1526 *
1527 * @param uri The URI whose file is to be opened.
1528 * @param mode Access mode for the file. May be "r" for read-only access,
1529 * "w" for write-only access, "rw" for read and write access, or
1530 * "rwt" for read and write access that truncates any existing
1531 * file.
1532 * @param signal A signal to cancel the operation in progress, or
1533 * {@code null} if none. For example, if you are downloading a
1534 * file from the network to service a "rw" mode request, you
1535 * should periodically call
1536 * {@link CancellationSignal#throwIfCanceled()} to check whether
1537 * the client has canceled the request and abort the download.
1538 *
1539 * @return Returns a new ParcelFileDescriptor which you can use to access
1540 * the file.
1541 *
1542 * @throws FileNotFoundException Throws FileNotFoundException if there is
1543 * no file associated with the given URI or the mode is invalid.
1544 * @throws SecurityException Throws SecurityException if the caller does
1545 * not have permission to access the file.
1546 *
1547 * @see #openAssetFile(Uri, String)
1548 * @see #openFileHelper(Uri, String)
1549 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001550 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001551 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001552 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1553 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001554 return openFile(uri, mode);
1555 }
1556
1557 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 * This is like {@link #openFile}, but can be implemented by providers
1559 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001560 * inside of their .apk.
1561 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001562 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1563 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001564 *
1565 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001566 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001567 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1569 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1570 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001571 * <p>
1572 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1573 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001574 *
1575 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 * should create the AssetFileDescriptor with
1577 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001578 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001580 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1581 * to return the appropriate MIME type for the data returned here with
1582 * the same URI. This will allow intent resolution to automatically determine the data MIME
1583 * type and select the appropriate matching targets as part of its operation.</p>
1584 *
1585 * <p class="note">For better interoperability with other applications, it is recommended
1586 * that for any URIs that can be opened, you also support queries on them
1587 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1588 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 * @param uri The URI whose file is to be opened.
1590 * @param mode Access mode for the file. May be "r" for read-only access,
1591 * "w" for write-only access (erasing whatever data is currently in
1592 * the file), "wa" for write-only access to append to any existing data,
1593 * "rw" for read and write access on any existing data, and "rwt" for read
1594 * and write access that truncates any existing file.
1595 *
1596 * @return Returns a new AssetFileDescriptor which you can use to access
1597 * the file.
1598 *
1599 * @throws FileNotFoundException Throws FileNotFoundException if there is
1600 * no file associated with the given URI or the mode is invalid.
1601 * @throws SecurityException Throws SecurityException if the caller does
1602 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001603 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 * @see #openFile(Uri, String)
1605 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001606 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001608 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 throws FileNotFoundException {
1610 ParcelFileDescriptor fd = openFile(uri, mode);
1611 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1612 }
1613
1614 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001615 * This is like {@link #openFile}, but can be implemented by providers
1616 * that need to be able to return sub-sections of files, often assets
1617 * inside of their .apk.
1618 * This method can be called from multiple threads, as described in
1619 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1620 * and Threads</a>.
1621 *
1622 * <p>If you implement this, your clients must be able to deal with such
1623 * file slices, either directly with
1624 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1625 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1626 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1627 * methods.
1628 * <p>
1629 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1630 * streaming of data.
1631 *
1632 * <p class="note">If you are implementing this to return a full file, you
1633 * should create the AssetFileDescriptor with
1634 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1635 * applications that cannot handle sub-sections of files.</p>
1636 *
1637 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1638 * to return the appropriate MIME type for the data returned here with
1639 * the same URI. This will allow intent resolution to automatically determine the data MIME
1640 * type and select the appropriate matching targets as part of its operation.</p>
1641 *
1642 * <p class="note">For better interoperability with other applications, it is recommended
1643 * that for any URIs that can be opened, you also support queries on them
1644 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1645 *
1646 * @param uri The URI whose file is to be opened.
1647 * @param mode Access mode for the file. May be "r" for read-only access,
1648 * "w" for write-only access (erasing whatever data is currently in
1649 * the file), "wa" for write-only access to append to any existing data,
1650 * "rw" for read and write access on any existing data, and "rwt" for read
1651 * and write access that truncates any existing file.
1652 * @param signal A signal to cancel the operation in progress, or
1653 * {@code null} if none. For example, if you are downloading a
1654 * file from the network to service a "rw" mode request, you
1655 * should periodically call
1656 * {@link CancellationSignal#throwIfCanceled()} to check whether
1657 * the client has canceled the request and abort the download.
1658 *
1659 * @return Returns a new AssetFileDescriptor which you can use to access
1660 * the file.
1661 *
1662 * @throws FileNotFoundException Throws FileNotFoundException if there is
1663 * no file associated with the given URI or the mode is invalid.
1664 * @throws SecurityException Throws SecurityException if the caller does
1665 * not have permission to access the file.
1666 *
1667 * @see #openFile(Uri, String)
1668 * @see #openFileHelper(Uri, String)
1669 * @see #getType(android.net.Uri)
1670 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001671 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1672 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001673 return openAssetFile(uri, mode);
1674 }
1675
1676 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 * Convenience for subclasses that wish to implement {@link #openFile}
1678 * by looking up a column named "_data" at the given URI.
1679 *
1680 * @param uri The URI to be opened.
1681 * @param mode The file mode. May be "r" for read-only access,
1682 * "w" for write-only access (erasing whatever data is currently in
1683 * the file), "wa" for write-only access to append to any existing data,
1684 * "rw" for read and write access on any existing data, and "rwt" for read
1685 * and write access that truncates any existing file.
1686 *
1687 * @return Returns a new ParcelFileDescriptor that can be used by the
1688 * client to access the file.
1689 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001690 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1691 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1693 int count = (c != null) ? c.getCount() : 0;
1694 if (count != 1) {
1695 // If there is not exactly one result, throw an appropriate
1696 // exception.
1697 if (c != null) {
1698 c.close();
1699 }
1700 if (count == 0) {
1701 throw new FileNotFoundException("No entry for " + uri);
1702 }
1703 throw new FileNotFoundException("Multiple items at " + uri);
1704 }
1705
1706 c.moveToFirst();
1707 int i = c.getColumnIndex("_data");
1708 String path = (i >= 0 ? c.getString(i) : null);
1709 c.close();
1710 if (path == null) {
1711 throw new FileNotFoundException("Column _data not found.");
1712 }
1713
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001714 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 return ParcelFileDescriptor.open(new File(path), modeBits);
1716 }
1717
1718 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001719 * Called by a client to determine the types of data streams that this
1720 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001721 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001722 * of a particular type, return that MIME type if it matches the given
1723 * mimeTypeFilter. If it can perform type conversions, return an array
1724 * of all supported MIME types that match mimeTypeFilter.
1725 *
1726 * @param uri The data in the content provider being queried.
1727 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001728 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001729 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001730 * given mimeTypeFilter. Otherwise returns an array of all available
1731 * concrete MIME types.
1732 *
1733 * @see #getType(Uri)
1734 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001735 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001736 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001737 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001738 return null;
1739 }
1740
1741 /**
1742 * Called by a client to open a read-only stream containing data of a
1743 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1744 * except the file can only be read-only and the content provider may
1745 * perform data conversions to generate data of the desired type.
1746 *
1747 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001748 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001749 * {@link #openAssetFile(Uri, String)}.
1750 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001751 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001752 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001753 * <p>
1754 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1755 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001756 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001757 * <p class="note">For better interoperability with other applications, it is recommended
1758 * that for any URIs that can be opened, you also support queries on them
1759 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1760 * You may also want to support other common columns if you have additional meta-data
1761 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1762 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1763 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001764 * @param uri The data in the content provider being queried.
1765 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001766 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001767 * requirements; in this case the content provider will pick its best
1768 * type matching the pattern.
1769 * @param opts Additional options from the client. The definitions of
1770 * these are specific to the content provider being called.
1771 *
1772 * @return Returns a new AssetFileDescriptor from which the client can
1773 * read data of the desired type.
1774 *
1775 * @throws FileNotFoundException Throws FileNotFoundException if there is
1776 * no file associated with the given URI or the mode is invalid.
1777 * @throws SecurityException Throws SecurityException if the caller does
1778 * not have permission to access the data.
1779 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1780 * content provider does not support the requested MIME type.
1781 *
1782 * @see #getStreamTypes(Uri, String)
1783 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001784 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001785 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001786 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1787 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001788 if ("*/*".equals(mimeTypeFilter)) {
1789 // If they can take anything, the untyped open call is good enough.
1790 return openAssetFile(uri, "r");
1791 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001792 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001793 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001794 // Use old untyped open call if this provider has a type for this
1795 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001796 return openAssetFile(uri, "r");
1797 }
1798 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1799 }
1800
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001801
1802 /**
1803 * Called by a client to open a read-only stream containing data of a
1804 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1805 * except the file can only be read-only and the content provider may
1806 * perform data conversions to generate data of the desired type.
1807 *
1808 * <p>The default implementation compares the given mimeType against the
1809 * result of {@link #getType(Uri)} and, if they match, simply calls
1810 * {@link #openAssetFile(Uri, String)}.
1811 *
1812 * <p>See {@link ClipData} for examples of the use and implementation
1813 * of this method.
1814 * <p>
1815 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1816 * streaming of data.
1817 *
1818 * <p class="note">For better interoperability with other applications, it is recommended
1819 * that for any URIs that can be opened, you also support queries on them
1820 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1821 * You may also want to support other common columns if you have additional meta-data
1822 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1823 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1824 *
1825 * @param uri The data in the content provider being queried.
1826 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001827 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001828 * requirements; in this case the content provider will pick its best
1829 * type matching the pattern.
1830 * @param opts Additional options from the client. The definitions of
1831 * these are specific to the content provider being called.
1832 * @param signal A signal to cancel the operation in progress, or
1833 * {@code null} if none. For example, if you are downloading a
1834 * file from the network to service a "rw" mode request, you
1835 * should periodically call
1836 * {@link CancellationSignal#throwIfCanceled()} to check whether
1837 * the client has canceled the request and abort the download.
1838 *
1839 * @return Returns a new AssetFileDescriptor from which the client can
1840 * read data of the desired type.
1841 *
1842 * @throws FileNotFoundException Throws FileNotFoundException if there is
1843 * no file associated with the given URI or the mode is invalid.
1844 * @throws SecurityException Throws SecurityException if the caller does
1845 * not have permission to access the data.
1846 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1847 * content provider does not support the requested MIME type.
1848 *
1849 * @see #getStreamTypes(Uri, String)
1850 * @see #openAssetFile(Uri, String)
1851 * @see ClipDescription#compareMimeTypes(String, String)
1852 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001853 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1854 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1855 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001856 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1857 }
1858
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001859 /**
1860 * Interface to write a stream of data to a pipe. Use with
1861 * {@link ContentProvider#openPipeHelper}.
1862 */
1863 public interface PipeDataWriter<T> {
1864 /**
1865 * Called from a background thread to stream data out to a pipe.
1866 * Note that the pipe is blocking, so this thread can block on
1867 * writes for an arbitrary amount of time if the client is slow
1868 * at reading.
1869 *
1870 * @param output The pipe where data should be written. This will be
1871 * closed for you upon returning from this function.
1872 * @param uri The URI whose data is to be written.
1873 * @param mimeType The desired type of data to be written.
1874 * @param opts Options supplied by caller.
1875 * @param args Your own custom arguments.
1876 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001877 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1878 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001879 }
1880
1881 /**
1882 * A helper function for implementing {@link #openTypedAssetFile}, for
1883 * creating a data pipe and background thread allowing you to stream
1884 * generated data back to the client. This function returns a new
1885 * ParcelFileDescriptor that should be returned to the caller (the caller
1886 * is responsible for closing it).
1887 *
1888 * @param uri The URI whose data is to be written.
1889 * @param mimeType The desired type of data to be written.
1890 * @param opts Options supplied by caller.
1891 * @param args Your own custom arguments.
1892 * @param func Interface implementing the function that will actually
1893 * stream the data.
1894 * @return Returns a new ParcelFileDescriptor holding the read side of
1895 * the pipe. This should be returned to the caller for reading; the caller
1896 * is responsible for closing it when done.
1897 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001898 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1899 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1900 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001901 try {
1902 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1903
1904 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1905 @Override
1906 protected Object doInBackground(Object... params) {
1907 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1908 try {
1909 fds[1].close();
1910 } catch (IOException e) {
1911 Log.w(TAG, "Failure closing pipe", e);
1912 }
1913 return null;
1914 }
1915 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001916 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001917
1918 return fds[0];
1919 } catch (IOException e) {
1920 throw new FileNotFoundException("failure making pipe");
1921 }
1922 }
1923
1924 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 * Returns true if this instance is a temporary content provider.
1926 * @return true if this instance is a temporary content provider
1927 */
1928 protected boolean isTemporary() {
1929 return false;
1930 }
1931
1932 /**
1933 * Returns the Binder object for this provider.
1934 *
1935 * @return the Binder object for this provider
1936 * @hide
1937 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001938 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 public IContentProvider getIContentProvider() {
1940 return mTransport;
1941 }
1942
1943 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001944 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1945 * when directly instantiating the provider for testing.
1946 * @hide
1947 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001948 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001949 public void attachInfoForTesting(Context context, ProviderInfo info) {
1950 attachInfo(context, info, true);
1951 }
1952
1953 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 * After being instantiated, this is called to tell the content provider
1955 * about itself.
1956 *
1957 * @param context The context this provider is running in
1958 * @param info Registered information about this content provider
1959 */
1960 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001961 attachInfo(context, info, false);
1962 }
1963
1964 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001965 mNoPerms = testing;
1966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 /*
1968 * Only allow it to be set once, so after the content service gives
1969 * this to us clients can't change it.
1970 */
1971 if (mContext == null) {
1972 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06001973 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001974 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1975 Context.APP_OPS_SERVICE);
1976 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001977 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if (info != null) {
1979 setReadPermission(info.readPermission);
1980 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001981 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001982 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001983 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001984 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 ContentProvider.this.onCreate();
1987 }
1988 }
Fred Quintanace31b232009-05-04 16:01:15 -07001989
1990 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001991 * Override this to handle requests to perform a batch of operations, or the
1992 * default implementation will iterate over the operations and call
1993 * {@link ContentProviderOperation#apply} on each of them.
1994 * If all calls to {@link ContentProviderOperation#apply} succeed
1995 * then a {@link ContentProviderResult} array with as many
1996 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001997 * fail, it is up to the implementation how many of the others take effect.
1998 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001999 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2000 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002001 *
Fred Quintanace31b232009-05-04 16:01:15 -07002002 * @param operations the operations to apply
2003 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002004 * @throws OperationApplicationException thrown if any operation fails.
2005 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002006 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002007 public @NonNull ContentProviderResult[] applyBatch(
2008 @NonNull ArrayList<ContentProviderOperation> operations)
2009 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002010 final int numOperations = operations.size();
2011 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2012 for (int i = 0; i < numOperations; i++) {
2013 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002014 }
2015 return results;
2016 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002017
2018 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002019 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002020 * interfaces that are cheaper and/or unnatural for a table-like
2021 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002022 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002023 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2024 * on this entry into the content provider besides the basic ability for the application
2025 * to get access to the provider at all. For example, it has no idea whether the call
2026 * being executed may read or write data in the provider, so can't enforce those
2027 * individual permissions. Any implementation of this method <strong>must</strong>
2028 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2029 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002030 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2031 * @param arg provider-defined String argument. May be {@code null}.
2032 * @param extras provider-defined Bundle argument. May be {@code null}.
2033 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002034 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002035 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002036 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2037 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002038 return null;
2039 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002040
2041 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002042 * Implement this to shut down the ContentProvider instance. You can then
2043 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002044 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002045 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002046 * Android normally handles ContentProvider startup and shutdown
2047 * automatically. You do not need to start up or shut down a
2048 * ContentProvider. When you invoke a test method on a ContentProvider,
2049 * however, a ContentProvider instance is started and keeps running after
2050 * the test finishes, even if a succeeding test instantiates another
2051 * ContentProvider. A conflict develops because the two instances are
2052 * usually running against the same underlying data source (for example, an
2053 * sqlite database).
2054 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002055 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002056 * Implementing shutDown() avoids this conflict by providing a way to
2057 * terminate the ContentProvider. This method can also prevent memory leaks
2058 * from multiple instantiations of the ContentProvider, and it can ensure
2059 * unit test isolation by allowing you to completely clean up the test
2060 * fixture before moving on to the next test.
2061 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002062 */
2063 public void shutdown() {
2064 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2065 "connections are gracefully shutdown");
2066 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002067
2068 /**
2069 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002070 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002071 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002072 * @param fd The raw file descriptor that the dump is being sent to.
2073 * @param writer The PrintWriter to which you should dump your state. This will be
2074 * closed for you after you return.
2075 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002076 */
2077 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2078 writer.println("nothing to dump");
2079 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002080
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002081 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002082 @VisibleForTesting
2083 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002084 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002085 if (!mSingleUser) {
2086 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2087 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2088 throw new SecurityException("trying to query a ContentProvider in user "
2089 + mContext.getUserId() + " with a uri belonging to user " + userId);
2090 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002091 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002092 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2093 String message = "The authority of the uri " + uri + " does not match the one of the "
2094 + "contentProvider: ";
2095 if (mAuthority != null) {
2096 message += mAuthority;
2097 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002098 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002099 }
2100 throw new SecurityException(message);
2101 }
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002102
2103 // Normalize the path by removing any empty path segments, which can be
2104 // a source of security issues.
2105 final String encodedPath = uri.getEncodedPath();
2106 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002107 final Uri normalized = uri.buildUpon()
2108 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2109 Log.w(TAG, "Normalized " + uri + " to " + normalized
2110 + " to avoid possible security issues");
2111 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002112 } else {
2113 return uri;
2114 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002115 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002116
2117 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002118 private Uri maybeGetUriWithoutUserId(Uri uri) {
2119 if (mSingleUser) {
2120 return uri;
2121 }
2122 return getUriWithoutUserId(uri);
2123 }
2124
2125 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002126 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2127 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002128 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002129 if (end == -1) return defaultUserId;
2130 String userIdString = auth.substring(0, end);
2131 try {
2132 return Integer.parseInt(userIdString);
2133 } catch (NumberFormatException e) {
2134 Log.w(TAG, "Error parsing userId.", e);
2135 return UserHandle.USER_NULL;
2136 }
2137 }
2138
2139 /** @hide */
2140 public static int getUserIdFromAuthority(String auth) {
2141 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2142 }
2143
2144 /** @hide */
2145 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2146 if (uri == null) return defaultUserId;
2147 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2148 }
2149
2150 /** @hide */
2151 public static int getUserIdFromUri(Uri uri) {
2152 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2153 }
2154
2155 /**
2156 * Removes userId part from authority string. Expects format:
2157 * userId@some.authority
2158 * If there is no userId in the authority, it symply returns the argument
2159 * @hide
2160 */
2161 public static String getAuthorityWithoutUserId(String auth) {
2162 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002163 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002164 return auth.substring(end+1);
2165 }
2166
2167 /** @hide */
2168 public static Uri getUriWithoutUserId(Uri uri) {
2169 if (uri == null) return null;
2170 Uri.Builder builder = uri.buildUpon();
2171 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2172 return builder.build();
2173 }
2174
2175 /** @hide */
2176 public static boolean uriHasUserId(Uri uri) {
2177 if (uri == null) return false;
2178 return !TextUtils.isEmpty(uri.getUserInfo());
2179 }
2180
2181 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002182 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002183 public static Uri maybeAddUserId(Uri uri, int userId) {
2184 if (uri == null) return null;
2185 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002186 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002187 if (!uriHasUserId(uri)) {
2188 //We don't add the user Id if there's already one
2189 Uri.Builder builder = uri.buildUpon();
2190 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2191 return builder.build();
2192 }
2193 }
2194 return uri;
2195 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002196}