blob: 4ea3726bee6dfb406f8dd2af6fcc2c21f04f78bd [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Nicolas Prevot504d78e2014-06-26 10:07:33 +010019import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070020import static android.app.AppOpsManager.MODE_ALLOWED;
Eugene Susla93519852018-06-13 16:44:31 -070021import static android.app.AppOpsManager.MODE_DEFAULT;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070022import static android.app.AppOpsManager.MODE_ERRORED;
23import static android.app.AppOpsManager.MODE_IGNORED;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060025import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070026
Jeff Sharkey673db442015-06-11 19:30:57 -070027import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080028import android.annotation.Nullable;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010029import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080030import android.app.AppOpsManager;
Jeff Sharkey9edef252019-05-20 14:00:17 -060031import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070032import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.content.pm.ProviderInfo;
34import android.content.res.AssetFileDescriptor;
35import android.content.res.Configuration;
36import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070037import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.database.SQLException;
39import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070040import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010042import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070044import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080045import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070046import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070048import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080049import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060050import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060052import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010053import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070054import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060056import com.android.internal.annotations.VisibleForTesting;
57
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080059import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070061import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080062import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070063import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080064import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060065import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67/**
68 * Content providers are one of the primary building blocks of Android applications, providing
69 * content to applications. They encapsulate data and provide it to applications through the single
70 * {@link ContentResolver} interface. A content provider is only required if you need to share
71 * data between multiple applications. For example, the contacts data is used by multiple
72 * applications and must be stored in a content provider. If you don't need to share data amongst
73 * multiple applications you can use a database directly via
74 * {@link android.database.sqlite.SQLiteDatabase}.
75 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * <p>When a request is made via
77 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
78 * request to the content provider registered with the authority. The content provider can interpret
79 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
80 * URIs.</p>
81 *
82 * <p>The primary methods that need to be implemented are:
83 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070084 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * <li>{@link #query} which returns data to the caller</li>
86 * <li>{@link #insert} which inserts new data into the content provider</li>
87 * <li>{@link #update} which updates existing data in the content provider</li>
88 * <li>{@link #delete} which deletes data from the content provider</li>
89 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
90 * </ul></p>
91 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070092 * <p class="caution">Data access methods (such as {@link #insert} and
93 * {@link #update}) may be called from many threads at once, and must be thread-safe.
94 * Other methods (such as {@link #onCreate}) are only called from the application
95 * main thread, and must avoid performing lengthy operations. See the method
96 * descriptions for their expected thread behavior.</p>
97 *
98 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
99 * ContentProvider instance, so subclasses don't have to worry about the details of
100 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700101 *
102 * <div class="special reference">
103 * <h3>Developer Guides</h3>
104 * <p>For more information about using content providers, read the
105 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
106 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700107 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700109public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800110
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700111 private static final String TAG = "ContentProvider";
112
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900113 /*
114 * Note: if you add methods to ContentProvider, you must add similar methods to
115 * MockContentProvider.
116 */
117
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100118 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700120 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100121
122 // Since most Providers have only one authority, we keep both a String and a String[] to improve
123 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100124 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100125 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100126 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100127 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100128 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100130 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100132 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700133 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700134 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800135 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700136 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
Jeff Sharkey497789e2019-02-15 19:41:30 -0700138 private ThreadLocal<String> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 private Transport mTransport = new Transport();
141
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700142 /**
143 * Construct a ContentProvider instance. Content providers must be
144 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
145 * in the manifest</a>, accessed with {@link ContentResolver}, and created
146 * automatically by the system, so applications usually do not create
147 * ContentProvider instances directly.
148 *
149 * <p>At construction time, the object is uninitialized, and most fields and
150 * methods are unavailable. Subclasses should initialize themselves in
151 * {@link #onCreate}, not the constructor.
152 *
153 * <p>Content providers are created on the application main thread at
154 * application launch time. The constructor must not perform lengthy
155 * operations, or application startup will be delayed.
156 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900157 public ContentProvider() {
158 }
159
160 /**
161 * Constructor just for mocking.
162 *
163 * @param context A Context object which should be some mock instance (like the
164 * instance of {@link android.test.mock.MockContext}).
165 * @param readPermission The read permision you want this instance should have in the
166 * test, which is available via {@link #getReadPermission()}.
167 * @param writePermission The write permission you want this instance should have
168 * in the test, which is available via {@link #getWritePermission()}.
169 * @param pathPermissions The PathPermissions you want this instance should have
170 * in the test, which is available via {@link #getPathPermissions()}.
171 * @hide
172 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100173 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900174 public ContentProvider(
175 Context context,
176 String readPermission,
177 String writePermission,
178 PathPermission[] pathPermissions) {
179 mContext = context;
180 mReadPermission = readPermission;
181 mWritePermission = writePermission;
182 mPathPermissions = pathPermissions;
183 }
184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 /**
186 * Given an IContentProvider, try to coerce it back to the real
187 * ContentProvider object if it is running in the local process. This can
188 * be used if you know you are running in the same process as a provider,
189 * and want to get direct access to its implementation details. Most
190 * clients should not nor have a reason to use it.
191 *
192 * @param abstractInterface The ContentProvider interface that is to be
193 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800194 * @return If the IContentProvider is non-{@code null} and local, returns its actual
195 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 * @hide
197 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100198 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 public static ContentProvider coerceToLocalContentProvider(
200 IContentProvider abstractInterface) {
201 if (abstractInterface instanceof Transport) {
202 return ((Transport)abstractInterface).getContentProvider();
203 }
204 return null;
205 }
206
207 /**
208 * Binder object that deals with remoting.
209 *
210 * @hide
211 */
212 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700213 volatile AppOpsManager mAppOpsManager = null;
214 volatile int mReadOp = AppOpsManager.OP_NONE;
215 volatile int mWriteOp = AppOpsManager.OP_NONE;
216 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 ContentProvider getContentProvider() {
219 return ContentProvider.this;
220 }
221
Jeff Brownd2183652011-10-09 12:39:53 -0700222 @Override
223 public String getProviderName() {
224 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 }
226
Jeff Brown75ea64f2012-01-25 19:37:13 -0800227 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800228 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
229 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600230 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100231 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800232 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700233 // The caller has no access to the data, so return an empty cursor with
234 // the columns in the requested order. The caller may ask for an invalid
235 // column and we would not catch that but this is not a problem in practice.
236 // We do not call ContentProvider#query with a modified where clause since
237 // the implementation is not guaranteed to be backed by a SQL database, hence
238 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700239 if (projection != null) {
240 return new MatrixCursor(projection, 0);
241 }
242
243 // Null projection means all columns but we have no idea which they are.
244 // However, the caller may be expecting to access them my index. Hence,
245 // we have to execute the query as if allowed to get a cursor with the
246 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700247 Cursor cursor;
248 final String original = setCallingPackage(callingPkg);
249 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700250 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700251 uri, projection, queryArgs,
252 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700253 } catch (RemoteException e) {
254 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700255 } finally {
256 setCallingPackage(original);
257 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700258 if (cursor == null) {
259 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700260 }
261
262 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700263 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800264 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600265 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700266 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700267 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700268 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800269 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700270 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700271 } catch (RemoteException e) {
272 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700273 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700274 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600275 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278
Jeff Brown75ea64f2012-01-25 19:37:13 -0800279 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700281 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600282 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100283 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600284 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
285 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700286 return mInterface.getType(uri);
287 } catch (RemoteException e) {
288 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600289 } finally {
290 Trace.traceEnd(TRACE_TAG_DATABASE);
291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293
Jeff Brown75ea64f2012-01-25 19:37:13 -0800294 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800295 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600296 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100297 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100298 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800299 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700300 final String original = setCallingPackage(callingPkg);
301 try {
302 return rejectInsert(uri, initialValues);
303 } finally {
304 setCallingPackage(original);
305 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800306 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600307 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700308 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700309 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700310 return maybeAddUserId(mInterface.insert(uri, initialValues), userId);
311 } catch (RemoteException e) {
312 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700313 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700314 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600315 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 }
318
Jeff Brown75ea64f2012-01-25 19:37:13 -0800319 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800320 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600321 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100322 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800323 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800324 return 0;
325 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600326 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700329 return mInterface.bulkInsert(uri, initialValues);
330 } catch (RemoteException e) {
331 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700332 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700333 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600334 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 }
337
Jeff Brown75ea64f2012-01-25 19:37:13 -0800338 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700339 public ContentProviderResult[] applyBatch(String callingPkg, String authority,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800340 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700341 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700342 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100343 int numOperations = operations.size();
344 final int[] userIds = new int[numOperations];
345 for (int i = 0; i < numOperations; i++) {
346 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100347 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600348 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600349 uri = validateIncomingUri(uri);
350 uri = maybeGetUriWithoutUserId(uri);
351 // Rebuild operation if we changed the Uri above
352 if (!Objects.equals(operation.getUri(), uri)) {
353 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100354 operations.set(i, operation);
355 }
Fred Quintana89437372009-05-15 15:10:40 -0700356 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800357 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800358 != AppOpsManager.MODE_ALLOWED) {
359 throw new OperationApplicationException("App op not allowed", 0);
360 }
Fred Quintana89437372009-05-15 15:10:40 -0700361 }
Fred Quintana89437372009-05-15 15:10:40 -0700362 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800363 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800364 != AppOpsManager.MODE_ALLOWED) {
365 throw new OperationApplicationException("App op not allowed", 0);
366 }
Fred Quintana89437372009-05-15 15:10:40 -0700367 }
368 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600369 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700370 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700371 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700372 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700373 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800374 if (results != null) {
375 for (int i = 0; i < results.length ; i++) {
376 if (userIds[i] != UserHandle.USER_CURRENT) {
377 // Adding the userId to the uri.
378 results[i] = new ContentProviderResult(results[i], userIds[i]);
379 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100380 }
381 }
382 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700383 } catch (RemoteException e) {
384 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700385 } 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 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700389 }
390
Jeff Brown75ea64f2012-01-25 19:37:13 -0800391 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800392 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600393 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100394 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800395 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800396 return 0;
397 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600398 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700399 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700400 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700401 return mInterface.delete(uri, selection, selectionArgs);
402 } catch (RemoteException e) {
403 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700404 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700405 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600406 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 }
409
Jeff Brown75ea64f2012-01-25 19:37:13 -0800410 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800411 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 String[] selectionArgs) {
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 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800416 return 0;
417 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600418 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700419 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700420 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700421 return mInterface.update(uri, values, selection, selectionArgs);
422 } catch (RemoteException e) {
423 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700425 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600426 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 }
429
Jeff Brown75ea64f2012-01-25 19:37:13 -0800430 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700431 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800432 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
433 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600434 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100435 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800436 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600437 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700438 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700439 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700440 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700441 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700442 } catch (RemoteException e) {
443 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700444 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700445 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600446 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
449
Jeff Brown75ea64f2012-01-25 19:37:13 -0800450 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700451 public AssetFileDescriptor openAssetFile(
452 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600454 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100455 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800456 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600457 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700458 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700459 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700460 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700461 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700462 } catch (RemoteException e) {
463 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700464 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700465 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600466 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 }
469
Jeff Brown75ea64f2012-01-25 19:37:13 -0800470 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700471 public Bundle call(String callingPkg, String authority, String method, @Nullable String arg,
472 @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700473 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600474 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600475 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700476 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700477 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700478 return mInterface.call(authority, method, arg, extras);
479 } catch (RemoteException e) {
480 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700481 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700482 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600483 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700484 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800485 }
486
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700487 @Override
488 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700489 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600490 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100491 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600492 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
493 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700494 return mInterface.getStreamTypes(uri, mimeTypeFilter);
495 } catch (RemoteException e) {
496 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600497 } finally {
498 Trace.traceEnd(TRACE_TAG_DATABASE);
499 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700500 }
501
502 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800503 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700504 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600505 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600506 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100507 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800508 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600509 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700510 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700511 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700512 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700513 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700514 } catch (RemoteException e) {
515 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700516 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700517 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600518 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700519 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700520 }
521
Jeff Brown75ea64f2012-01-25 19:37:13 -0800522 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700523 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800524 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800525 }
526
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700527 @Override
528 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600529 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100530 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100531 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800532 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700533 return null;
534 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600535 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700536 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700537 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700538 return maybeAddUserId(mInterface.canonicalize(uri), userId);
539 } catch (RemoteException e) {
540 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700541 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700542 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600543 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700544 }
545 }
546
547 @Override
548 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600549 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100550 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100551 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800552 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700553 return null;
554 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600555 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700556 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700557 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700558 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
559 } catch (RemoteException e) {
560 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700561 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700562 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600563 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700564 }
565 }
566
Ben Lin1cf454f2016-11-10 13:50:54 -0800567 @Override
568 public boolean refresh(String callingPkg, Uri uri, Bundle args,
569 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600570 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800571 uri = getUriWithoutUserId(uri);
572 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
573 return false;
574 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600575 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800576 final String original = setCallingPackage(callingPkg);
577 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700578 return mInterface.refresh(uri, args,
Ben Lin1cf454f2016-11-10 13:50:54 -0800579 CancellationSignal.fromTransport(cancellationSignal));
580 } finally {
581 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600582 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800583 }
584 }
585
Jeff Sharkey9edef252019-05-20 14:00:17 -0600586 @Override
587 public int checkUriPermission(String callingPkg, Uri uri, int uid, int modeFlags) {
588 uri = validateIncomingUri(uri);
589 uri = maybeGetUriWithoutUserId(uri);
590 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
591 final String original = setCallingPackage(callingPkg);
592 try {
593 return mInterface.checkUriPermission(uri, uid, modeFlags);
594 } catch (RemoteException e) {
595 throw e.rethrowAsRuntimeException();
596 } finally {
597 setCallingPackage(original);
598 Trace.traceEnd(TRACE_TAG_DATABASE);
599 }
600 }
601
Dianne Hackbornff170242014-11-19 10:59:01 -0800602 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
603 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800604 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800605 if (enforceWritePermission(callingPkg, uri, callerToken)
606 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800607 throw new FileNotFoundException("App op not allowed");
608 }
609 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800610 if (enforceReadPermission(callingPkg, uri, callerToken)
611 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800612 throw new FileNotFoundException("App op not allowed");
613 }
614 }
615 }
616
Dianne Hackbornff170242014-11-19 10:59:01 -0800617 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
618 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700619 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
620 if (mode != MODE_ALLOWED) {
621 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800622 }
Svet Ganov99b60432015-06-27 13:15:22 -0700623
Eugene Susla93519852018-06-13 16:44:31 -0700624 return noteProxyOp(callingPkg, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800625 }
626
Dianne Hackbornff170242014-11-19 10:59:01 -0800627 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
628 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700629 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
630 if (mode != MODE_ALLOWED) {
631 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800632 }
Svet Ganov99b60432015-06-27 13:15:22 -0700633
Eugene Susla93519852018-06-13 16:44:31 -0700634 return noteProxyOp(callingPkg, mWriteOp);
635 }
636
637 private int noteProxyOp(String callingPkg, int op) {
638 if (op != AppOpsManager.OP_NONE) {
639 int mode = mAppOpsManager.noteProxyOp(op, callingPkg);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700640 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700641 }
642
Dianne Hackborn35654b62013-01-14 17:38:02 -0800643 return AppOpsManager.MODE_ALLOWED;
644 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700645 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800646
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100647 boolean checkUser(int pid, int uid, Context context) {
648 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700649 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100650 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
651 == PERMISSION_GRANTED;
652 }
653
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700654 /**
655 * Verify that calling app holds both the given permission and any app-op
656 * associated with that permission.
657 */
658 private int checkPermissionAndAppOp(String permission, String callingPkg,
659 IBinder callerToken) {
660 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
661 callerToken) != PERMISSION_GRANTED) {
662 return MODE_ERRORED;
663 }
664
Eugene Susla93519852018-06-13 16:44:31 -0700665 return mTransport.noteProxyOp(callingPkg, AppOpsManager.permissionToOpCode(permission));
666 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700667
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700668 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700669 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800670 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700671 final Context context = getContext();
672 final int pid = Binder.getCallingPid();
673 final int uid = Binder.getCallingUid();
674 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700675 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700676
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700677 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700678 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700679 }
680
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100681 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700682 final String componentPerm = getReadPermission();
683 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700684 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
685 if (mode == MODE_ALLOWED) {
686 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700687 } else {
688 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700689 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700690 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700691 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700692
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700693 // track if unprotected read is allowed; any denied
694 // <path-permission> below removes this ability
695 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700696
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700697 final PathPermission[] pps = getPathPermissions();
698 if (pps != null) {
699 final String path = uri.getPath();
700 for (PathPermission pp : pps) {
701 final String pathPerm = pp.getReadPermission();
702 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700703 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
704 if (mode == MODE_ALLOWED) {
705 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700706 } else {
707 // any denied <path-permission> means we lose
708 // default <provider> access.
709 allowDefaultRead = false;
710 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700711 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700712 }
713 }
714 }
715 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700716
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700717 // if we passed <path-permission> checks above, and no default
718 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700719 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700721
722 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800723 final int callingUserId = UserHandle.getUserId(uid);
724 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
725 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800726 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
727 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700728 return MODE_ALLOWED;
729 }
730
731 // If the worst denial we found above was ignored, then pass that
732 // ignored through; otherwise we assume it should be a real error below.
733 if (strongestMode == MODE_IGNORED) {
734 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700735 }
736
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600737 final String suffix;
738 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
739 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
740 } else if (mExported) {
741 suffix = " requires " + missingPerm + ", or grantUriPermission()";
742 } else {
743 suffix = " requires the provider be exported, or grantUriPermission()";
744 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700745 throw new SecurityException("Permission Denial: reading "
746 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600747 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700748 }
749
750 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700751 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800752 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700753 final Context context = getContext();
754 final int pid = Binder.getCallingPid();
755 final int uid = Binder.getCallingUid();
756 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700757 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700758
759 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700760 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700761 }
762
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100763 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700764 final String componentPerm = getWritePermission();
765 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700766 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
767 if (mode == MODE_ALLOWED) {
768 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700769 } else {
770 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700771 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700772 }
773 }
774
775 // track if unprotected write is allowed; any denied
776 // <path-permission> below removes this ability
777 boolean allowDefaultWrite = (componentPerm == null);
778
779 final PathPermission[] pps = getPathPermissions();
780 if (pps != null) {
781 final String path = uri.getPath();
782 for (PathPermission pp : pps) {
783 final String pathPerm = pp.getWritePermission();
784 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700785 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
786 if (mode == MODE_ALLOWED) {
787 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700788 } else {
789 // any denied <path-permission> means we lose
790 // default <provider> access.
791 allowDefaultWrite = false;
792 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700793 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700794 }
795 }
796 }
797 }
798
799 // if we passed <path-permission> checks above, and no default
800 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700801 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700802 }
803
804 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800805 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
806 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700807 return MODE_ALLOWED;
808 }
809
810 // If the worst denial we found above was ignored, then pass that
811 // ignored through; otherwise we assume it should be a real error below.
812 if (strongestMode == MODE_IGNORED) {
813 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700814 }
815
816 final String failReason = mExported
817 ? " requires " + missingPerm + ", or grantUriPermission()"
818 : " requires the provider be exported, or grantUriPermission()";
819 throw new SecurityException("Permission Denial: writing "
820 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
821 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 }
823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700825 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800826 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 * constructor.
828 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700829 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 return mContext;
831 }
832
833 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700834 * Set the calling package, returning the current value (or {@code null})
835 * which can be used later to restore the previous state.
836 */
837 private String setCallingPackage(String callingPackage) {
838 final String original = mCallingPackage.get();
839 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600840 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700841 return original;
842 }
843
844 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700845 * Return the package name of the caller that initiated the request being
846 * processed on the current thread. The returned package will have been
847 * verified to belong to the calling UID. Returns {@code null} if not
848 * currently processing a request.
849 * <p>
850 * This will always return {@code null} when processing
851 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
852 *
853 * @see Binder#getCallingUid()
854 * @see Context#grantUriPermission(String, Uri, int)
855 * @throws SecurityException if the calling package doesn't belong to the
856 * calling UID.
857 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700858 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700859 final String pkg = mCallingPackage.get();
860 if (pkg != null) {
861 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
862 }
863 return pkg;
864 }
865
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600866 /** {@hide} */
867 public final @Nullable String getCallingPackageUnchecked() {
868 return mCallingPackage.get();
869 }
870
871 /** {@hide} */
872 public void onCallingPackageChanged() {
873 }
874
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700875 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600876 * Opaque token representing the identity of an incoming IPC.
877 */
878 public final class CallingIdentity {
879 /** {@hide} */
880 public final long binderToken;
881 /** {@hide} */
882 public final String callingPackage;
883
884 /** {@hide} */
885 public CallingIdentity(long binderToken, String callingPackage) {
886 this.binderToken = binderToken;
887 this.callingPackage = callingPackage;
888 }
889 }
890
891 /**
892 * Reset the identity of the incoming IPC on the current thread.
893 * <p>
894 * Internally this calls {@link Binder#clearCallingIdentity()} and also
895 * clears any value stored in {@link #getCallingPackage()}.
896 *
897 * @return Returns an opaque token that can be used to restore the original
898 * calling identity by passing it to
899 * {@link #restoreCallingIdentity}.
900 */
901 public final @NonNull CallingIdentity clearCallingIdentity() {
902 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
903 }
904
905 /**
906 * Restore the identity of the incoming IPC on the current thread back to a
907 * previously identity that was returned by {@link #clearCallingIdentity}.
908 * <p>
909 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
910 * also restores any value stored in {@link #getCallingPackage()}.
911 */
912 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
913 Binder.restoreCallingIdentity(identity.binderToken);
914 mCallingPackage.set(identity.callingPackage);
915 }
916
917 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100918 * Change the authorities of the ContentProvider.
919 * This is normally set for you from its manifest information when the provider is first
920 * created.
921 * @hide
922 * @param authorities the semi-colon separated authorities of the ContentProvider.
923 */
924 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100925 if (authorities != null) {
926 if (authorities.indexOf(';') == -1) {
927 mAuthority = authorities;
928 mAuthorities = null;
929 } else {
930 mAuthority = null;
931 mAuthorities = authorities.split(";");
932 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100933 }
934 }
935
936 /** @hide */
937 protected final boolean matchesOurAuthorities(String authority) {
938 if (mAuthority != null) {
939 return mAuthority.equals(authority);
940 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100941 if (mAuthorities != null) {
942 int length = mAuthorities.length;
943 for (int i = 0; i < length; i++) {
944 if (mAuthorities[i].equals(authority)) return true;
945 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100946 }
947 return false;
948 }
949
950
951 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 * Change the permission required to read data from the content
953 * provider. This is normally set for you from its manifest information
954 * when the provider is first created.
955 *
956 * @param permission Name of the permission required for read-only access.
957 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700958 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 mReadPermission = permission;
960 }
961
962 /**
963 * Return the name of the permission required for read-only access to
964 * this content provider. This method can be called from multiple
965 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800966 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
967 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700969 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 return mReadPermission;
971 }
972
973 /**
974 * Change the permission required to read and write data in the content
975 * provider. This is normally set for you from its manifest information
976 * when the provider is first created.
977 *
978 * @param permission Name of the permission required for read/write access.
979 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700980 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 mWritePermission = permission;
982 }
983
984 /**
985 * Return the name of the permission required for read/write access to
986 * this content provider. This method can be called from multiple
987 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800988 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
989 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700991 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 return mWritePermission;
993 }
994
995 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700996 * Change the path-based permission required to read and/or write data in
997 * the content provider. This is normally set for you from its manifest
998 * information when the provider is first created.
999 *
1000 * @param permissions Array of path permission descriptions.
1001 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001002 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001003 mPathPermissions = permissions;
1004 }
1005
1006 /**
1007 * Return the path-based permissions required for read and/or write access to
1008 * this content provider. This method can be called from multiple
1009 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001010 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1011 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001012 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001013 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001014 return mPathPermissions;
1015 }
1016
Dianne Hackborn35654b62013-01-14 17:38:02 -08001017 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001018 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001019 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001020 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001021 mTransport.mReadOp = readOp;
1022 mTransport.mWriteOp = writeOp;
1023 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001024 }
1025
Dianne Hackborn961321f2013-02-05 17:22:41 -08001026 /** @hide */
1027 public AppOpsManager getAppOpsManager() {
1028 return mTransport.mAppOpsManager;
1029 }
1030
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001031 /** @hide */
1032 public final void setTransportLoggingEnabled(boolean enabled) {
1033 if (enabled) {
1034 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1035 } else {
1036 mTransport.mInterface = this;
1037 }
1038 }
1039
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001040 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001041 * Implement this to initialize your content provider on startup.
1042 * This method is called for all registered content providers on the
1043 * application main thread at application launch time. It must not perform
1044 * lengthy operations, or application startup will be delayed.
1045 *
1046 * <p>You should defer nontrivial initialization (such as opening,
1047 * upgrading, and scanning databases) until the content provider is used
1048 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1049 * keeps application startup fast, avoids unnecessary work if the provider
1050 * turns out not to be needed, and stops database errors (such as a full
1051 * disk) from halting application launch.
1052 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001053 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001054 * is a helpful utility class that makes it easy to manage databases,
1055 * and will automatically defer opening until first use. If you do use
1056 * SQLiteOpenHelper, make sure to avoid calling
1057 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1058 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1059 * from this method. (Instead, override
1060 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1061 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 *
1063 * @return true if the provider was successfully loaded, false otherwise
1064 */
1065 public abstract boolean onCreate();
1066
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001067 /**
1068 * {@inheritDoc}
1069 * This method is always called on the application main thread, and must
1070 * not perform lengthy operations.
1071 *
1072 * <p>The default content provider implementation does nothing.
1073 * Override this method to take appropriate action.
1074 * (Content providers do not usually care about things like screen
1075 * orientation, but may want to know about locale changes.)
1076 */
Steve McKayea93fe72016-12-02 11:35:35 -08001077 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 public void onConfigurationChanged(Configuration newConfig) {
1079 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001080
1081 /**
1082 * {@inheritDoc}
1083 * This method is always called on the application main thread, and must
1084 * not perform lengthy operations.
1085 *
1086 * <p>The default content provider implementation does nothing.
1087 * Subclasses may override this method to take appropriate action.
1088 */
Steve McKayea93fe72016-12-02 11:35:35 -08001089 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 public void onLowMemory() {
1091 }
1092
Steve McKayea93fe72016-12-02 11:35:35 -08001093 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001094 public void onTrimMemory(int level) {
1095 }
1096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001098 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001099 *
1100 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1101 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1102 * implementation of this method.
1103 *
1104 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001105 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1106 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 * <p>
1108 * Example client call:<p>
1109 * <pre>// Request a specific record.
1110 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001111 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 projection, // Which columns to return.
1113 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001114 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 People.NAME + " ASC"); // Sort order.</pre>
1116 * Example implementation:<p>
1117 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1118 // proper SQL syntax for us.
1119 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1120
1121 // Set the table we're querying.
1122 qBuilder.setTables(DATABASE_TABLE_NAME);
1123
1124 // If the query ends in a specific record number, we're
1125 // being asked for a specific record, so set the
1126 // WHERE clause in our query.
1127 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1128 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1129 }
1130
1131 // Make the query.
1132 Cursor c = qBuilder.query(mDb,
1133 projection,
1134 selection,
1135 selectionArgs,
1136 groupBy,
1137 having,
1138 sortOrder);
1139 c.setNotificationUri(getContext().getContentResolver(), uri);
1140 return c;</pre>
1141 *
1142 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001143 * if the client is requesting a specific record, the URI will end in a record number
1144 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1145 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001147 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001149 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001150 * @param selectionArgs You may include ?s in selection, which will be replaced by
1151 * the values from selectionArgs, in order that they appear in the selection.
1152 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001154 * If {@code null} then the provider is free to define the sort order.
1155 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001157 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1158 @Nullable String selection, @Nullable String[] selectionArgs,
1159 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160
Fred Quintana5bba6322009-10-05 14:21:12 -07001161 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001162 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001163 *
1164 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1165 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1166 *
1167 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001168 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1169 * and Threads</a>.
1170 * <p>
1171 * Example client call:<p>
1172 * <pre>// Request a specific record.
1173 * Cursor managedCursor = managedQuery(
1174 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1175 projection, // Which columns to return.
1176 null, // WHERE clause.
1177 null, // WHERE clause value substitution
1178 People.NAME + " ASC"); // Sort order.</pre>
1179 * Example implementation:<p>
1180 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1181 // proper SQL syntax for us.
1182 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1183
1184 // Set the table we're querying.
1185 qBuilder.setTables(DATABASE_TABLE_NAME);
1186
1187 // If the query ends in a specific record number, we're
1188 // being asked for a specific record, so set the
1189 // WHERE clause in our query.
1190 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1191 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1192 }
1193
1194 // Make the query.
1195 Cursor c = qBuilder.query(mDb,
1196 projection,
1197 selection,
1198 selectionArgs,
1199 groupBy,
1200 having,
1201 sortOrder);
1202 c.setNotificationUri(getContext().getContentResolver(), uri);
1203 return c;</pre>
1204 * <p>
1205 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001206 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1207 * signal to ensure correct operation on older versions of the Android Framework in
1208 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001209 *
1210 * @param uri The URI to query. This will be the full URI sent by the client;
1211 * if the client is requesting a specific record, the URI will end in a record number
1212 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1213 * that _id value.
1214 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001215 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001216 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001217 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001218 * @param selectionArgs You may include ?s in selection, which will be replaced by
1219 * the values from selectionArgs, in order that they appear in the selection.
1220 * The values will be bound as Strings.
1221 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001222 * If {@code null} then the provider is free to define the sort order.
1223 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001224 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001225 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001226 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001227 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001228 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1229 @Nullable String selection, @Nullable String[] selectionArgs,
1230 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001231 return query(uri, projection, selection, selectionArgs, sortOrder);
1232 }
1233
1234 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001235 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1236 * Arguments may include traditional SQL style query arguments. When present these
1237 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001238 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001239 *
1240 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001241 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1242 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1243 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001244 *
Steve McKay76b27702017-04-24 12:07:53 -07001245 * <p>This method can be called from multiple threads, as described in
1246 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1247 * and Threads</a>.
1248 *
1249 * <p>
1250 * Example client call:<p>
1251 * <pre>// Request 20 records starting at row index 30.
1252 Bundle queryArgs = new Bundle();
1253 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1254 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1255
1256 Cursor cursor = getContentResolver().query(
1257 contentUri, // Content Uri is specific to individual content providers.
1258 projection, // String[] describing which columns to return.
1259 queryArgs, // Query arguments.
1260 null); // Cancellation signal.</pre>
1261 *
1262 * Example implementation:<p>
1263 * <pre>
1264
1265 int recordsetSize = 0x1000; // Actual value is implementation specific.
1266 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1267
1268 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1269 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1270
1271 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1272
1273 // Calculate the number of items to include in the cursor.
1274 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1275
1276 // Build the paged result set....
1277 for (int i = offset; i < offset + numItems; i++) {
1278 // populate row from your data.
1279 }
1280
1281 Bundle extras = new Bundle();
1282 c.setExtras(extras);
1283
1284 // Any QUERY_ARG_* key may be included if honored.
1285 // In an actual implementation, include only keys that are both present in queryArgs
1286 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1287 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1288 // then QUERY_ARG_OFFSET should be omitted.
1289 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1290 ContentResolver.QUERY_ARG_OFFSET,
1291 ContentResolver.QUERY_ARG_LIMIT
1292 });
1293
1294 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1295
1296 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1297
1298 return cursor;</pre>
1299 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001300 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1301 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001302 *
1303 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001304 * @param projection The list of columns to put into the cursor.
1305 * If {@code null} provide a default set of columns.
1306 * @param queryArgs A Bundle containing all additional information necessary for the query.
1307 * Values in the Bundle may include SQL style arguments.
1308 * @param cancellationSignal A signal to cancel the operation in progress,
1309 * or {@code null}.
1310 * @return a Cursor or {@code null}.
1311 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001312 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001313 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1314 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1315 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001316
Steve McKayd7ece9f2017-01-12 16:59:59 -08001317 // if client doesn't supply an SQL sort order argument, attempt to build one from
1318 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001319 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001320 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1321 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1322 }
1323
Steve McKayea93fe72016-12-02 11:35:35 -08001324 return query(
1325 uri,
1326 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001327 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1328 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1329 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001330 cancellationSignal);
1331 }
1332
1333 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001334 * Implement this to handle requests for the MIME type of the data at the
1335 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 * <code>vnd.android.cursor.item</code> for a single record,
1337 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001338 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001339 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1340 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001342 * <p>Note that there are no permissions needed for an application to
1343 * access this information; if your content provider requires read and/or
1344 * write permissions, or is not exported, all applications can still call
1345 * this method regardless of their access permissions. This allows them
1346 * to retrieve the MIME type for a URI when dispatching intents.
1347 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001349 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001351 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001352 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353
1354 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001355 * Implement this to support canonicalization of URIs that refer to your
1356 * content provider. A canonical URI is one that can be transported across
1357 * devices, backup/restore, and other contexts, and still be able to refer
1358 * to the same data item. Typically this is implemented by adding query
1359 * params to the URI allowing the content provider to verify that an incoming
1360 * canonical URI references the same data as it was originally intended for and,
1361 * if it doesn't, to find that data (if it exists) in the current environment.
1362 *
1363 * <p>For example, if the content provider holds people and a normal URI in it
1364 * is created with a row index into that people database, the cananical representation
1365 * may have an additional query param at the end which specifies the name of the
1366 * person it is intended for. Later calls into the provider with that URI will look
1367 * up the row of that URI's base index and, if it doesn't match or its entry's
1368 * name doesn't match the name in the query param, perform a query on its database
1369 * to find the correct row to operate on.</p>
1370 *
1371 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1372 * URIs (including this one) must perform this verification and recovery of any
1373 * canonical URIs they receive. In addition, you must also implement
1374 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1375 *
1376 * <p>The default implementation of this method returns null, indicating that
1377 * canonical URIs are not supported.</p>
1378 *
1379 * @param url The Uri to canonicalize.
1380 *
1381 * @return Return the canonical representation of <var>url</var>, or null if
1382 * canonicalization of that Uri is not supported.
1383 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001384 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001385 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001386 return null;
1387 }
1388
1389 /**
1390 * Remove canonicalization from canonical URIs previously returned by
1391 * {@link #canonicalize}. For example, if your implementation is to add
1392 * a query param to canonicalize a URI, this method can simply trip any
1393 * query params on the URI. The default implementation always returns the
1394 * same <var>url</var> that was passed in.
1395 *
1396 * @param url The Uri to remove any canonicalization from.
1397 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001398 * @return Return the non-canonical representation of <var>url</var>, return
1399 * the <var>url</var> as-is if there is nothing to do, or return null if
1400 * the data identified by the canonical representation can not be found in
1401 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001402 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001403 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001404 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001405 return url;
1406 }
1407
1408 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001409 * Implement this to support refresh of content identified by {@code uri}. By default, this
1410 * method returns false; providers who wish to implement this should return true to signal the
1411 * client that the provider has tried refreshing with its own implementation.
1412 * <p>
1413 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1414 * <p>
1415 * Client code should only invoke this method when there is a strong indication (such as a user
1416 * initiated pull to refresh gesture) that the content is stale.
1417 * <p>
1418 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1419 * notifications when content changes.
1420 *
1421 * @param uri The Uri identifying the data to refresh.
1422 * @param args Additional options from the client. The definitions of these are specific to the
1423 * content provider being called.
1424 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1425 * none. For example, if you called refresh on a particular uri, you should call
1426 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1427 * canceled the refresh request.
1428 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001429 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001430 @Override
Ben Lin1cf454f2016-11-10 13:50:54 -08001431 public boolean refresh(Uri uri, @Nullable Bundle args,
1432 @Nullable CancellationSignal cancellationSignal) {
1433 return false;
1434 }
1435
Jeff Sharkey9edef252019-05-20 14:00:17 -06001436 /** {@hide} */
1437 @Override
1438 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1439 return PackageManager.PERMISSION_DENIED;
1440 }
1441
Ben Lin1cf454f2016-11-10 13:50:54 -08001442 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001443 * @hide
1444 * Implementation when a caller has performed an insert on the content
1445 * provider, but that call has been rejected for the operation given
1446 * to {@link #setAppOps(int, int)}. The default implementation simply
1447 * returns a dummy URI that is the base URI with a 0 path element
1448 * appended.
1449 */
1450 public Uri rejectInsert(Uri uri, ContentValues values) {
1451 // If not allowed, we need to return some reasonable URI. Maybe the
1452 // content provider should be responsible for this, but for now we
1453 // will just return the base URI with a dummy '0' tagged on to it.
1454 // You shouldn't be able to read if you can't write, anyway, so it
1455 // shouldn't matter much what is returned.
1456 return uri.buildUpon().appendPath("0").build();
1457 }
1458
1459 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001460 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1462 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001463 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001464 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1465 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001466 * @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 -08001467 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001468 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 * @return The URI for the newly inserted item.
1470 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001471 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001472 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473
1474 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001475 * Override this to handle requests to insert a set of new rows, or the
1476 * default implementation will iterate over the values and call
1477 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1479 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001480 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001481 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1482 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 *
1484 * @param uri The content:// URI of the insertion request.
1485 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001486 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 * @return The number of values that were inserted.
1488 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001489 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001490 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 int numValues = values.length;
1492 for (int i = 0; i < numValues; i++) {
1493 insert(uri, values[i]);
1494 }
1495 return numValues;
1496 }
1497
1498 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001499 * Implement this to handle requests to delete one or more rows.
1500 * The implementation should apply the selection clause when performing
1501 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001502 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001504 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001505 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1506 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 *
1508 * <p>The implementation is responsible for parsing out a row ID at the end
1509 * of the URI, if a specific row is being deleted. That is, the client would
1510 * pass in <code>content://contacts/people/22</code> and the implementation is
1511 * responsible for parsing the record number (22) when creating a SQL statement.
1512 *
1513 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1514 * @param selection An optional restriction to apply to rows when deleting.
1515 * @return The number of rows affected.
1516 * @throws SQLException
1517 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001518 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001519 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1520 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521
1522 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001523 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001524 * The implementation should update all rows matching the selection
1525 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1527 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001528 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001529 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1530 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 *
1532 * @param uri The URI to query. This can potentially have a record ID if this
1533 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001534 * @param values A set of column_name/value pairs to update in the database.
1535 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 * @param selection An optional filter to match rows to update.
1537 * @return the number of rows affected.
1538 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001539 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001540 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001541 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542
1543 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001544 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001545 * The default implementation always throws {@link FileNotFoundException}.
1546 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001547 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1548 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001549 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001550 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1551 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001552 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 *
1554 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1555 * their responsibility to close it when done. That is, the implementation
1556 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001557 * <p>
1558 * If opened with the exclusive "r" or "w" modes, the returned
1559 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1560 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1561 * supports seeking.
1562 * <p>
1563 * If you need to detect when the returned ParcelFileDescriptor has been
1564 * closed, or if the remote process has crashed or encountered some other
1565 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1566 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1567 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1568 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001569 * <p>
1570 * If you need to return a large file that isn't backed by a real file on
1571 * disk, such as a file on a network share or cloud storage service,
1572 * consider using
1573 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1574 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001576 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1577 * to return the appropriate MIME type for the data returned here with
1578 * the same URI. This will allow intent resolution to automatically determine the data MIME
1579 * type and select the appropriate matching targets as part of its operation.</p>
1580 *
1581 * <p class="note">For better interoperability with other applications, it is recommended
1582 * that for any URIs that can be opened, you also support queries on them
1583 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1584 * You may also want to support other common columns if you have additional meta-data
1585 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1586 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1587 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 * @param uri The URI whose file is to be opened.
1589 * @param mode Access mode for the file. May be "r" for read-only access,
1590 * "rw" for read and write access, or "rwt" for read and write access
1591 * that truncates any existing file.
1592 *
1593 * @return Returns a new ParcelFileDescriptor which you can use to access
1594 * the file.
1595 *
1596 * @throws FileNotFoundException Throws FileNotFoundException if there is
1597 * no file associated with the given URI or the mode is invalid.
1598 * @throws SecurityException Throws SecurityException if the caller does
1599 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001600 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 * @see #openAssetFile(Uri, String)
1602 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001603 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001604 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001605 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001606 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 throws FileNotFoundException {
1608 throw new FileNotFoundException("No files supported by provider at "
1609 + uri);
1610 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001613 * Override this to handle requests to open a file blob.
1614 * The default implementation always throws {@link FileNotFoundException}.
1615 * This method can be called from multiple threads, as described in
1616 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1617 * and Threads</a>.
1618 *
1619 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1620 * to the caller. This way large data (such as images and documents) can be
1621 * returned without copying the content.
1622 *
1623 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1624 * their responsibility to close it when done. That is, the implementation
1625 * of this method should create a new ParcelFileDescriptor for each call.
1626 * <p>
1627 * If opened with the exclusive "r" or "w" modes, the returned
1628 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1629 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1630 * supports seeking.
1631 * <p>
1632 * If you need to detect when the returned ParcelFileDescriptor has been
1633 * closed, or if the remote process has crashed or encountered some other
1634 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1635 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1636 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1637 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1638 *
1639 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1640 * to return the appropriate MIME type for the data returned here with
1641 * the same URI. This will allow intent resolution to automatically determine the data MIME
1642 * type and select the appropriate matching targets as part of its operation.</p>
1643 *
1644 * <p class="note">For better interoperability with other applications, it is recommended
1645 * that for any URIs that can be opened, you also support queries on them
1646 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1647 * You may also want to support other common columns if you have additional meta-data
1648 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1649 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1650 *
1651 * @param uri The URI whose file is to be opened.
1652 * @param mode Access mode for the file. May be "r" for read-only access,
1653 * "w" for write-only access, "rw" for read and write access, or
1654 * "rwt" for read and write access that truncates any existing
1655 * file.
1656 * @param signal A signal to cancel the operation in progress, or
1657 * {@code null} if none. For example, if you are downloading a
1658 * file from the network to service a "rw" mode request, you
1659 * should periodically call
1660 * {@link CancellationSignal#throwIfCanceled()} to check whether
1661 * the client has canceled the request and abort the download.
1662 *
1663 * @return Returns a new ParcelFileDescriptor which you can use to access
1664 * the file.
1665 *
1666 * @throws FileNotFoundException Throws FileNotFoundException if there is
1667 * no file associated with the given URI or the mode is invalid.
1668 * @throws SecurityException Throws SecurityException if the caller does
1669 * not have permission to access the file.
1670 *
1671 * @see #openAssetFile(Uri, String)
1672 * @see #openFileHelper(Uri, String)
1673 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001674 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001675 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001676 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001677 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1678 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001679 return openFile(uri, mode);
1680 }
1681
1682 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 * This is like {@link #openFile}, but can be implemented by providers
1684 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001685 * inside of their .apk.
1686 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001687 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1688 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001689 *
1690 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001691 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001692 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1694 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1695 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001696 * <p>
1697 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1698 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001699 *
1700 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 * should create the AssetFileDescriptor with
1702 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001703 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001705 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1706 * to return the appropriate MIME type for the data returned here with
1707 * the same URI. This will allow intent resolution to automatically determine the data MIME
1708 * type and select the appropriate matching targets as part of its operation.</p>
1709 *
1710 * <p class="note">For better interoperability with other applications, it is recommended
1711 * that for any URIs that can be opened, you also support queries on them
1712 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1713 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 * @param uri The URI whose file is to be opened.
1715 * @param mode Access mode for the file. May be "r" for read-only access,
1716 * "w" for write-only access (erasing whatever data is currently in
1717 * the file), "wa" for write-only access to append to any existing data,
1718 * "rw" for read and write access on any existing data, and "rwt" for read
1719 * and write access that truncates any existing file.
1720 *
1721 * @return Returns a new AssetFileDescriptor which you can use to access
1722 * the file.
1723 *
1724 * @throws FileNotFoundException Throws FileNotFoundException if there is
1725 * no file associated with the given URI or the mode is invalid.
1726 * @throws SecurityException Throws SecurityException if the caller does
1727 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001728 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 * @see #openFile(Uri, String)
1730 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001731 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001733 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 throws FileNotFoundException {
1735 ParcelFileDescriptor fd = openFile(uri, mode);
1736 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1737 }
1738
1739 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001740 * This is like {@link #openFile}, but can be implemented by providers
1741 * that need to be able to return sub-sections of files, often assets
1742 * inside of their .apk.
1743 * This method can be called from multiple threads, as described in
1744 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1745 * and Threads</a>.
1746 *
1747 * <p>If you implement this, your clients must be able to deal with such
1748 * file slices, either directly with
1749 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1750 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1751 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1752 * methods.
1753 * <p>
1754 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1755 * streaming of data.
1756 *
1757 * <p class="note">If you are implementing this to return a full file, you
1758 * should create the AssetFileDescriptor with
1759 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1760 * applications that cannot handle sub-sections of files.</p>
1761 *
1762 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1763 * to return the appropriate MIME type for the data returned here with
1764 * the same URI. This will allow intent resolution to automatically determine the data MIME
1765 * type and select the appropriate matching targets as part of its operation.</p>
1766 *
1767 * <p class="note">For better interoperability with other applications, it is recommended
1768 * that for any URIs that can be opened, you also support queries on them
1769 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1770 *
1771 * @param uri The URI whose file is to be opened.
1772 * @param mode Access mode for the file. May be "r" for read-only access,
1773 * "w" for write-only access (erasing whatever data is currently in
1774 * the file), "wa" for write-only access to append to any existing data,
1775 * "rw" for read and write access on any existing data, and "rwt" for read
1776 * and write access that truncates any existing file.
1777 * @param signal A signal to cancel the operation in progress, or
1778 * {@code null} if none. For example, if you are downloading a
1779 * file from the network to service a "rw" mode request, you
1780 * should periodically call
1781 * {@link CancellationSignal#throwIfCanceled()} to check whether
1782 * the client has canceled the request and abort the download.
1783 *
1784 * @return Returns a new AssetFileDescriptor which you can use to access
1785 * the file.
1786 *
1787 * @throws FileNotFoundException Throws FileNotFoundException if there is
1788 * no file associated with the given URI or the mode is invalid.
1789 * @throws SecurityException Throws SecurityException if the caller does
1790 * not have permission to access the file.
1791 *
1792 * @see #openFile(Uri, String)
1793 * @see #openFileHelper(Uri, String)
1794 * @see #getType(android.net.Uri)
1795 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001796 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001797 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1798 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001799 return openAssetFile(uri, mode);
1800 }
1801
1802 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 * Convenience for subclasses that wish to implement {@link #openFile}
1804 * by looking up a column named "_data" at the given URI.
1805 *
1806 * @param uri The URI to be opened.
1807 * @param mode The file mode. May be "r" for read-only access,
1808 * "w" for write-only access (erasing whatever data is currently in
1809 * the file), "wa" for write-only access to append to any existing data,
1810 * "rw" for read and write access on any existing data, and "rwt" for read
1811 * and write access that truncates any existing file.
1812 *
1813 * @return Returns a new ParcelFileDescriptor that can be used by the
1814 * client to access the file.
1815 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001816 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1817 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1819 int count = (c != null) ? c.getCount() : 0;
1820 if (count != 1) {
1821 // If there is not exactly one result, throw an appropriate
1822 // exception.
1823 if (c != null) {
1824 c.close();
1825 }
1826 if (count == 0) {
1827 throw new FileNotFoundException("No entry for " + uri);
1828 }
1829 throw new FileNotFoundException("Multiple items at " + uri);
1830 }
1831
1832 c.moveToFirst();
1833 int i = c.getColumnIndex("_data");
1834 String path = (i >= 0 ? c.getString(i) : null);
1835 c.close();
1836 if (path == null) {
1837 throw new FileNotFoundException("Column _data not found.");
1838 }
1839
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001840 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 return ParcelFileDescriptor.open(new File(path), modeBits);
1842 }
1843
1844 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001845 * Called by a client to determine the types of data streams that this
1846 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001847 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001848 * of a particular type, return that MIME type if it matches the given
1849 * mimeTypeFilter. If it can perform type conversions, return an array
1850 * of all supported MIME types that match mimeTypeFilter.
1851 *
1852 * @param uri The data in the content provider being queried.
1853 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001854 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001855 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001856 * given mimeTypeFilter. Otherwise returns an array of all available
1857 * concrete MIME types.
1858 *
1859 * @see #getType(Uri)
1860 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001861 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001862 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001863 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001864 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001865 return null;
1866 }
1867
1868 /**
1869 * Called by a client to open a read-only stream containing data of a
1870 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1871 * except the file can only be read-only and the content provider may
1872 * perform data conversions to generate data of the desired type.
1873 *
1874 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001875 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001876 * {@link #openAssetFile(Uri, String)}.
1877 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001878 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001879 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001880 * <p>
1881 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1882 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001883 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001884 * <p class="note">For better interoperability with other applications, it is recommended
1885 * that for any URIs that can be opened, you also support queries on them
1886 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1887 * You may also want to support other common columns if you have additional meta-data
1888 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1889 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1890 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001891 * @param uri The data in the content provider being queried.
1892 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001893 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001894 * requirements; in this case the content provider will pick its best
1895 * type matching the pattern.
1896 * @param opts Additional options from the client. The definitions of
1897 * these are specific to the content provider being called.
1898 *
1899 * @return Returns a new AssetFileDescriptor from which the client can
1900 * read data of the desired type.
1901 *
1902 * @throws FileNotFoundException Throws FileNotFoundException if there is
1903 * no file associated with the given URI or the mode is invalid.
1904 * @throws SecurityException Throws SecurityException if the caller does
1905 * not have permission to access the data.
1906 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1907 * content provider does not support the requested MIME type.
1908 *
1909 * @see #getStreamTypes(Uri, String)
1910 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001911 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001912 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001913 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1914 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001915 if ("*/*".equals(mimeTypeFilter)) {
1916 // If they can take anything, the untyped open call is good enough.
1917 return openAssetFile(uri, "r");
1918 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001919 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001920 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001921 // Use old untyped open call if this provider has a type for this
1922 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001923 return openAssetFile(uri, "r");
1924 }
1925 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1926 }
1927
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001928
1929 /**
1930 * Called by a client to open a read-only stream containing data of a
1931 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1932 * except the file can only be read-only and the content provider may
1933 * perform data conversions to generate data of the desired type.
1934 *
1935 * <p>The default implementation compares the given mimeType against the
1936 * result of {@link #getType(Uri)} and, if they match, simply calls
1937 * {@link #openAssetFile(Uri, String)}.
1938 *
1939 * <p>See {@link ClipData} for examples of the use and implementation
1940 * of this method.
1941 * <p>
1942 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1943 * streaming of data.
1944 *
1945 * <p class="note">For better interoperability with other applications, it is recommended
1946 * that for any URIs that can be opened, you also support queries on them
1947 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1948 * You may also want to support other common columns if you have additional meta-data
1949 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1950 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1951 *
1952 * @param uri The data in the content provider being queried.
1953 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001954 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001955 * requirements; in this case the content provider will pick its best
1956 * type matching the pattern.
1957 * @param opts Additional options from the client. The definitions of
1958 * these are specific to the content provider being called.
1959 * @param signal A signal to cancel the operation in progress, or
1960 * {@code null} if none. For example, if you are downloading a
1961 * file from the network to service a "rw" mode request, you
1962 * should periodically call
1963 * {@link CancellationSignal#throwIfCanceled()} to check whether
1964 * the client has canceled the request and abort the download.
1965 *
1966 * @return Returns a new AssetFileDescriptor from which the client can
1967 * read data of the desired type.
1968 *
1969 * @throws FileNotFoundException Throws FileNotFoundException if there is
1970 * no file associated with the given URI or the mode is invalid.
1971 * @throws SecurityException Throws SecurityException if the caller does
1972 * not have permission to access the data.
1973 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1974 * content provider does not support the requested MIME type.
1975 *
1976 * @see #getStreamTypes(Uri, String)
1977 * @see #openAssetFile(Uri, String)
1978 * @see ClipDescription#compareMimeTypes(String, String)
1979 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001980 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001981 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1982 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1983 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001984 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1985 }
1986
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001987 /**
1988 * Interface to write a stream of data to a pipe. Use with
1989 * {@link ContentProvider#openPipeHelper}.
1990 */
1991 public interface PipeDataWriter<T> {
1992 /**
1993 * Called from a background thread to stream data out to a pipe.
1994 * Note that the pipe is blocking, so this thread can block on
1995 * writes for an arbitrary amount of time if the client is slow
1996 * at reading.
1997 *
1998 * @param output The pipe where data should be written. This will be
1999 * closed for you upon returning from this function.
2000 * @param uri The URI whose data is to be written.
2001 * @param mimeType The desired type of data to be written.
2002 * @param opts Options supplied by caller.
2003 * @param args Your own custom arguments.
2004 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002005 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2006 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002007 }
2008
2009 /**
2010 * A helper function for implementing {@link #openTypedAssetFile}, for
2011 * creating a data pipe and background thread allowing you to stream
2012 * generated data back to the client. This function returns a new
2013 * ParcelFileDescriptor that should be returned to the caller (the caller
2014 * is responsible for closing it).
2015 *
2016 * @param uri The URI whose data is to be written.
2017 * @param mimeType The desired type of data to be written.
2018 * @param opts Options supplied by caller.
2019 * @param args Your own custom arguments.
2020 * @param func Interface implementing the function that will actually
2021 * stream the data.
2022 * @return Returns a new ParcelFileDescriptor holding the read side of
2023 * the pipe. This should be returned to the caller for reading; the caller
2024 * is responsible for closing it when done.
2025 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002026 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2027 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2028 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002029 try {
2030 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2031
2032 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2033 @Override
2034 protected Object doInBackground(Object... params) {
2035 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2036 try {
2037 fds[1].close();
2038 } catch (IOException e) {
2039 Log.w(TAG, "Failure closing pipe", e);
2040 }
2041 return null;
2042 }
2043 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002044 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002045
2046 return fds[0];
2047 } catch (IOException e) {
2048 throw new FileNotFoundException("failure making pipe");
2049 }
2050 }
2051
2052 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 * Returns true if this instance is a temporary content provider.
2054 * @return true if this instance is a temporary content provider
2055 */
2056 protected boolean isTemporary() {
2057 return false;
2058 }
2059
2060 /**
2061 * Returns the Binder object for this provider.
2062 *
2063 * @return the Binder object for this provider
2064 * @hide
2065 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002066 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 public IContentProvider getIContentProvider() {
2068 return mTransport;
2069 }
2070
2071 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002072 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2073 * when directly instantiating the provider for testing.
2074 * @hide
2075 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002076 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002077 public void attachInfoForTesting(Context context, ProviderInfo info) {
2078 attachInfo(context, info, true);
2079 }
2080
2081 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 * After being instantiated, this is called to tell the content provider
2083 * about itself.
2084 *
2085 * @param context The context this provider is running in
2086 * @param info Registered information about this content provider
2087 */
2088 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002089 attachInfo(context, info, false);
2090 }
2091
2092 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002093 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002094 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 /*
2097 * Only allow it to be set once, so after the content service gives
2098 * this to us clients can't change it.
2099 */
2100 if (mContext == null) {
2101 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002102 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002103 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2104 Context.APP_OPS_SERVICE);
2105 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002106 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 if (info != null) {
2108 setReadPermission(info.readPermission);
2109 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002110 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002111 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002112 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002113 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002115 if (Build.IS_DEBUGGABLE) {
2116 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2117 Log.VERBOSE));
2118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 ContentProvider.this.onCreate();
2120 }
2121 }
Fred Quintanace31b232009-05-04 16:01:15 -07002122
2123 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002124 * Override this to handle requests to perform a batch of operations, or the
2125 * default implementation will iterate over the operations and call
2126 * {@link ContentProviderOperation#apply} on each of them.
2127 * If all calls to {@link ContentProviderOperation#apply} succeed
2128 * then a {@link ContentProviderResult} array with as many
2129 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002130 * fail, it is up to the implementation how many of the others take effect.
2131 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002132 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2133 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002134 *
Fred Quintanace31b232009-05-04 16:01:15 -07002135 * @param operations the operations to apply
2136 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002137 * @throws OperationApplicationException thrown if any operation fails.
2138 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002139 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002140 @Override
2141 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2142 @NonNull ArrayList<ContentProviderOperation> operations)
2143 throws OperationApplicationException {
2144 return applyBatch(operations);
2145 }
2146
Jeff Sharkey673db442015-06-11 19:30:57 -07002147 public @NonNull ContentProviderResult[] applyBatch(
2148 @NonNull ArrayList<ContentProviderOperation> operations)
2149 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002150 final int numOperations = operations.size();
2151 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2152 for (int i = 0; i < numOperations; i++) {
2153 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002154 }
2155 return results;
2156 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002157
2158 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002159 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002160 * interfaces that are cheaper and/or unnatural for a table-like
2161 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002162 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002163 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2164 * on this entry into the content provider besides the basic ability for the application
2165 * to get access to the provider at all. For example, it has no idea whether the call
2166 * being executed may read or write data in the provider, so can't enforce those
2167 * individual permissions. Any implementation of this method <strong>must</strong>
2168 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2169 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002170 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2171 * @param arg provider-defined String argument. May be {@code null}.
2172 * @param extras provider-defined Bundle argument. May be {@code null}.
2173 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002174 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002175 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002176 @Override
2177 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2178 @Nullable String arg, @Nullable Bundle extras) {
2179 return call(method, arg, extras);
2180 }
2181
Jeff Sharkey673db442015-06-11 19:30:57 -07002182 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2183 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002184 return null;
2185 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002186
2187 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002188 * Implement this to shut down the ContentProvider instance. You can then
2189 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002190 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002191 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002192 * Android normally handles ContentProvider startup and shutdown
2193 * automatically. You do not need to start up or shut down a
2194 * ContentProvider. When you invoke a test method on a ContentProvider,
2195 * however, a ContentProvider instance is started and keeps running after
2196 * the test finishes, even if a succeeding test instantiates another
2197 * ContentProvider. A conflict develops because the two instances are
2198 * usually running against the same underlying data source (for example, an
2199 * sqlite database).
2200 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002201 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002202 * Implementing shutDown() avoids this conflict by providing a way to
2203 * terminate the ContentProvider. This method can also prevent memory leaks
2204 * from multiple instantiations of the ContentProvider, and it can ensure
2205 * unit test isolation by allowing you to completely clean up the test
2206 * fixture before moving on to the next test.
2207 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002208 */
2209 public void shutdown() {
2210 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2211 "connections are gracefully shutdown");
2212 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002213
2214 /**
2215 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002216 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002217 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002218 * @param fd The raw file descriptor that the dump is being sent to.
2219 * @param writer The PrintWriter to which you should dump your state. This will be
2220 * closed for you after you return.
2221 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002222 */
2223 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2224 writer.println("nothing to dump");
2225 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002226
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002227 private void validateIncomingAuthority(String authority) throws SecurityException {
2228 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2229 String message = "The authority " + authority + " does not match the one of the "
2230 + "contentProvider: ";
2231 if (mAuthority != null) {
2232 message += mAuthority;
2233 } else {
2234 message += Arrays.toString(mAuthorities);
2235 }
2236 throw new SecurityException(message);
2237 }
2238 }
2239
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002240 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002241 @VisibleForTesting
2242 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002243 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002244 if (!mSingleUser) {
2245 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2246 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2247 throw new SecurityException("trying to query a ContentProvider in user "
2248 + mContext.getUserId() + " with a uri belonging to user " + userId);
2249 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002250 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002251 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002252
2253 // Normalize the path by removing any empty path segments, which can be
2254 // a source of security issues.
2255 final String encodedPath = uri.getEncodedPath();
2256 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002257 final Uri normalized = uri.buildUpon()
2258 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2259 Log.w(TAG, "Normalized " + uri + " to " + normalized
2260 + " to avoid possible security issues");
2261 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002262 } else {
2263 return uri;
2264 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002265 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002266
2267 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002268 private Uri maybeGetUriWithoutUserId(Uri uri) {
2269 if (mSingleUser) {
2270 return uri;
2271 }
2272 return getUriWithoutUserId(uri);
2273 }
2274
2275 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002276 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2277 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002278 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002279 if (end == -1) return defaultUserId;
2280 String userIdString = auth.substring(0, end);
2281 try {
2282 return Integer.parseInt(userIdString);
2283 } catch (NumberFormatException e) {
2284 Log.w(TAG, "Error parsing userId.", e);
2285 return UserHandle.USER_NULL;
2286 }
2287 }
2288
2289 /** @hide */
2290 public static int getUserIdFromAuthority(String auth) {
2291 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2292 }
2293
2294 /** @hide */
2295 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2296 if (uri == null) return defaultUserId;
2297 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2298 }
2299
2300 /** @hide */
2301 public static int getUserIdFromUri(Uri uri) {
2302 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2303 }
2304
2305 /**
2306 * Removes userId part from authority string. Expects format:
2307 * userId@some.authority
2308 * If there is no userId in the authority, it symply returns the argument
2309 * @hide
2310 */
2311 public static String getAuthorityWithoutUserId(String auth) {
2312 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002313 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002314 return auth.substring(end+1);
2315 }
2316
2317 /** @hide */
2318 public static Uri getUriWithoutUserId(Uri uri) {
2319 if (uri == null) return null;
2320 Uri.Builder builder = uri.buildUpon();
2321 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2322 return builder.build();
2323 }
2324
2325 /** @hide */
2326 public static boolean uriHasUserId(Uri uri) {
2327 if (uri == null) return false;
2328 return !TextUtils.isEmpty(uri.getUserInfo());
2329 }
2330
2331 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002332 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002333 public static Uri maybeAddUserId(Uri uri, int userId) {
2334 if (uri == null) return null;
2335 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002336 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002337 if (!uriHasUserId(uri)) {
2338 //We don't add the user Id if there's already one
2339 Uri.Builder builder = uri.buildUpon();
2340 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2341 return builder.build();
2342 }
2343 }
2344 return uri;
2345 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002346}