blob: 9cf6569a6220c57a064752b7a2d8b64b56984b75 [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;
Varun Shahaf8cfe32019-08-16 16:11:24 -070020import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070021import static android.app.AppOpsManager.MODE_ALLOWED;
Eugene Susla93519852018-06-13 16:44:31 -070022import static android.app.AppOpsManager.MODE_DEFAULT;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070023import static android.app.AppOpsManager.MODE_ERRORED;
24import static android.app.AppOpsManager.MODE_IGNORED;
25import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060026import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070027
Jeff Sharkey673db442015-06-11 19:30:57 -070028import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080029import android.annotation.Nullable;
Jeff Sharkey197fe1f2020-01-07 22:06:37 -070030import android.annotation.SystemApi;
Alex Kershawba014ac2020-01-20 22:25:02 +000031import android.annotation.TestApi;
Dianne Hackborn35654b62013-01-14 17:38:02 -080032import android.app.AppOpsManager;
Artur Satayeve23a0eb2019-12-10 17:47:52 +000033import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey9edef252019-05-20 14:00:17 -060034import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070035import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.pm.ProviderInfo;
37import android.content.res.AssetFileDescriptor;
38import android.content.res.Configuration;
39import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070040import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.database.SQLException;
42import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070043import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010045import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080046import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070047import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080048import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070049import android.os.ICancellationSignal;
Dmitri Plotnikovbe61c442020-03-24 15:43:57 -070050import android.os.Parcel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070052import android.os.Process;
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -080053import android.os.RemoteCallback;
Ben Lin1cf454f2016-11-10 13:50:54 -080054import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060055import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070056import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060057import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010058import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070059import android.util.Log;
Philip P. Moltmann128b7032019-09-27 08:44:12 -070060import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060062import com.android.internal.annotations.VisibleForTesting;
63
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080065import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070067import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080068import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070069import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080070import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060071import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
73/**
74 * Content providers are one of the primary building blocks of Android applications, providing
75 * content to applications. They encapsulate data and provide it to applications through the single
76 * {@link ContentResolver} interface. A content provider is only required if you need to share
77 * data between multiple applications. For example, the contacts data is used by multiple
78 * applications and must be stored in a content provider. If you don't need to share data amongst
79 * multiple applications you can use a database directly via
80 * {@link android.database.sqlite.SQLiteDatabase}.
81 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 * <p>When a request is made via
83 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
84 * request to the content provider registered with the authority. The content provider can interpret
85 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
86 * URIs.</p>
87 *
88 * <p>The primary methods that need to be implemented are:
89 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070090 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * <li>{@link #query} which returns data to the caller</li>
92 * <li>{@link #insert} which inserts new data into the content provider</li>
93 * <li>{@link #update} which updates existing data in the content provider</li>
94 * <li>{@link #delete} which deletes data from the content provider</li>
95 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
96 * </ul></p>
97 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070098 * <p class="caution">Data access methods (such as {@link #insert} and
99 * {@link #update}) may be called from many threads at once, and must be thread-safe.
100 * Other methods (such as {@link #onCreate}) are only called from the application
101 * main thread, and must avoid performing lengthy operations. See the method
102 * descriptions for their expected thread behavior.</p>
103 *
104 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
105 * ContentProvider instance, so subclasses don't have to worry about the details of
106 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700107 *
108 * <div class="special reference">
109 * <h3>Developer Guides</h3>
110 * <p>For more information about using content providers, read the
111 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
112 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700113 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700115public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800116
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700117 private static final String TAG = "ContentProvider";
118
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900119 /*
120 * Note: if you add methods to ContentProvider, you must add similar methods to
121 * MockContentProvider.
122 */
123
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100124 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700126 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100127
128 // Since most Providers have only one authority, we keep both a String and a String[] to improve
129 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100130 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100131 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100132 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100133 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100134 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100136 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100138 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700139 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700140 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800141 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700142 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700144 private ThreadLocal<Pair<String, String>> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 private Transport mTransport = new Transport();
147
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700148 /**
149 * Construct a ContentProvider instance. Content providers must be
150 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
151 * in the manifest</a>, accessed with {@link ContentResolver}, and created
152 * automatically by the system, so applications usually do not create
153 * ContentProvider instances directly.
154 *
155 * <p>At construction time, the object is uninitialized, and most fields and
156 * methods are unavailable. Subclasses should initialize themselves in
157 * {@link #onCreate}, not the constructor.
158 *
159 * <p>Content providers are created on the application main thread at
160 * application launch time. The constructor must not perform lengthy
161 * operations, or application startup will be delayed.
162 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900163 public ContentProvider() {
164 }
165
166 /**
167 * Constructor just for mocking.
168 *
169 * @param context A Context object which should be some mock instance (like the
170 * instance of {@link android.test.mock.MockContext}).
171 * @param readPermission The read permision you want this instance should have in the
172 * test, which is available via {@link #getReadPermission()}.
173 * @param writePermission The write permission you want this instance should have
174 * in the test, which is available via {@link #getWritePermission()}.
175 * @param pathPermissions The PathPermissions you want this instance should have
176 * in the test, which is available via {@link #getPathPermissions()}.
177 * @hide
178 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100179 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900180 public ContentProvider(
181 Context context,
182 String readPermission,
183 String writePermission,
184 PathPermission[] pathPermissions) {
185 mContext = context;
186 mReadPermission = readPermission;
187 mWritePermission = writePermission;
188 mPathPermissions = pathPermissions;
189 }
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 /**
192 * Given an IContentProvider, try to coerce it back to the real
193 * ContentProvider object if it is running in the local process. This can
194 * be used if you know you are running in the same process as a provider,
195 * and want to get direct access to its implementation details. Most
196 * clients should not nor have a reason to use it.
197 *
198 * @param abstractInterface The ContentProvider interface that is to be
199 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800200 * @return If the IContentProvider is non-{@code null} and local, returns its actual
201 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 * @hide
203 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100204 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 public static ContentProvider coerceToLocalContentProvider(
206 IContentProvider abstractInterface) {
207 if (abstractInterface instanceof Transport) {
208 return ((Transport)abstractInterface).getContentProvider();
209 }
210 return null;
211 }
212
213 /**
214 * Binder object that deals with remoting.
215 *
216 * @hide
217 */
218 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700219 volatile AppOpsManager mAppOpsManager = null;
220 volatile int mReadOp = AppOpsManager.OP_NONE;
221 volatile int mWriteOp = AppOpsManager.OP_NONE;
222 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 ContentProvider getContentProvider() {
225 return ContentProvider.this;
226 }
227
Jeff Brownd2183652011-10-09 12:39:53 -0700228 @Override
229 public String getProviderName() {
230 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 }
232
Jeff Brown75ea64f2012-01-25 19:37:13 -0800233 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800234 public Cursor query(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700235 @Nullable String[] projection, @Nullable Bundle queryArgs,
236 @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600237 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100238 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800239 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700240 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700241 // The caller has no access to the data, so return an empty cursor with
242 // the columns in the requested order. The caller may ask for an invalid
243 // column and we would not catch that but this is not a problem in practice.
244 // We do not call ContentProvider#query with a modified where clause since
245 // the implementation is not guaranteed to be backed by a SQL database, hence
246 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700247 if (projection != null) {
248 return new MatrixCursor(projection, 0);
249 }
250
251 // Null projection means all columns but we have no idea which they are.
252 // However, the caller may be expecting to access them my index. Hence,
253 // we have to execute the query as if allowed to get a cursor with the
254 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700255 Cursor cursor;
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700256 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800257 new Pair<>(callingPkg, attributionTag));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700258 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700259 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700260 uri, projection, queryArgs,
261 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700262 } catch (RemoteException e) {
263 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700264 } finally {
265 setCallingPackage(original);
266 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700267 if (cursor == null) {
268 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700269 }
270
271 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700272 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800273 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600274 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700275 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800276 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700277 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700278 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800279 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700280 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700281 } catch (RemoteException e) {
282 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700283 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700284 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600285 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288
Jeff Brown75ea64f2012-01-25 19:37:13 -0800289 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700291 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600292 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100293 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600294 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
295 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700296 return mInterface.getType(uri);
297 } catch (RemoteException e) {
298 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600299 } finally {
300 Trace.traceEnd(TRACE_TAG_DATABASE);
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 }
303
Jeff Brown75ea64f2012-01-25 19:37:13 -0800304 @Override
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -0800305 public void getTypeAsync(Uri uri, RemoteCallback callback) {
306 final Bundle result = new Bundle();
Dmitri Plotnikovbe61c442020-03-24 15:43:57 -0700307 try {
308 result.putString(ContentResolver.REMOTE_CALLBACK_RESULT, getType(uri));
309 } catch (Exception e) {
Dmitri Plotnikovda4f3c82020-03-25 14:08:20 -0700310 putExceptionInBundle(result, ContentResolver.REMOTE_CALLBACK_ERROR, e);
Dmitri Plotnikovbe61c442020-03-24 15:43:57 -0700311 }
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -0800312 callback.sendResult(result);
313 }
314
315 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800316 public Uri insert(String callingPkg, @Nullable String attributionTag, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700317 ContentValues initialValues, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600318 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100319 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100320 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800321 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700322 != AppOpsManager.MODE_ALLOWED) {
323 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800324 new Pair<>(callingPkg, attributionTag));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700325 try {
326 return rejectInsert(uri, initialValues);
327 } finally {
328 setCallingPackage(original);
329 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800330 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600331 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700332 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800333 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700334 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700335 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700336 } catch (RemoteException e) {
337 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700338 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700339 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600340 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 }
343
Jeff Brown75ea64f2012-01-25 19:37:13 -0800344 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800345 public int bulkInsert(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700346 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600347 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100348 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800349 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700350 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800351 return 0;
352 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600353 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700354 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800355 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700356 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700357 return mInterface.bulkInsert(uri, initialValues);
358 } catch (RemoteException e) {
359 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700360 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700361 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600362 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 }
365
Jeff Brown75ea64f2012-01-25 19:37:13 -0800366 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800367 public ContentProviderResult[] applyBatch(String callingPkg,
368 @Nullable String attributionTag, String authority,
369 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700370 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700371 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100372 int numOperations = operations.size();
373 final int[] userIds = new int[numOperations];
374 for (int i = 0; i < numOperations; i++) {
375 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100376 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600377 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600378 uri = validateIncomingUri(uri);
379 uri = maybeGetUriWithoutUserId(uri);
380 // Rebuild operation if we changed the Uri above
381 if (!Objects.equals(operation.getUri(), uri)) {
382 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100383 operations.set(i, operation);
384 }
Fred Quintana89437372009-05-15 15:10:40 -0700385 if (operation.isReadOperation()) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800386 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800387 != AppOpsManager.MODE_ALLOWED) {
388 throw new OperationApplicationException("App op not allowed", 0);
389 }
Fred Quintana89437372009-05-15 15:10:40 -0700390 }
Fred Quintana89437372009-05-15 15:10:40 -0700391 if (operation.isWriteOperation()) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800392 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800393 != AppOpsManager.MODE_ALLOWED) {
394 throw new OperationApplicationException("App op not allowed", 0);
395 }
Fred Quintana89437372009-05-15 15:10:40 -0700396 }
397 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600398 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700399 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800400 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700402 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700403 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800404 if (results != null) {
405 for (int i = 0; i < results.length ; i++) {
406 if (userIds[i] != UserHandle.USER_CURRENT) {
407 // Adding the userId to the uri.
408 results[i] = new ContentProviderResult(results[i], userIds[i]);
409 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100410 }
411 }
412 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700413 } catch (RemoteException e) {
414 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700415 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700416 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600417 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700418 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700419 }
420
Jeff Brown75ea64f2012-01-25 19:37:13 -0800421 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800422 public int delete(String callingPkg, @Nullable String attributionTag, Uri uri,
423 Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600424 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100425 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800426 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700427 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800428 return 0;
429 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600430 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700431 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800432 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700433 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700434 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700435 } catch (RemoteException e) {
436 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700437 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700438 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600439 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
442
Jeff Brown75ea64f2012-01-25 19:37:13 -0800443 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800444 public int update(String callingPkg, @Nullable String attributionTag, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700445 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600446 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100447 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800448 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700449 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800450 return 0;
451 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600452 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700453 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800454 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700455 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700456 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700457 } catch (RemoteException e) {
458 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700459 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700460 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600461 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 }
464
Jeff Brown75ea64f2012-01-25 19:37:13 -0800465 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800466 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700467 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
468 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600469 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100470 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800471 enforceFilePermission(callingPkg, attributionTag, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600472 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700473 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800474 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700475 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700476 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700477 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700478 } catch (RemoteException e) {
479 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700480 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700481 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600482 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 }
485
Jeff Brown75ea64f2012-01-25 19:37:13 -0800486 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800487 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700488 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600490 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100491 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800492 enforceFilePermission(callingPkg, attributionTag, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600493 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700494 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800495 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700496 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700497 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700498 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700499 } catch (RemoteException e) {
500 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700501 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700502 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600503 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 }
506
Jeff Brown75ea64f2012-01-25 19:37:13 -0800507 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800508 public Bundle call(String callingPkg, @Nullable String attributionTag, String authority,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700509 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700510 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600511 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600512 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700513 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800514 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700515 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700516 return mInterface.call(authority, method, arg, extras);
517 } catch (RemoteException e) {
518 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700519 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700520 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600521 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700522 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800523 }
524
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700525 @Override
526 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700527 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600528 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100529 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600530 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
531 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700532 return mInterface.getStreamTypes(uri, mimeTypeFilter);
533 } catch (RemoteException e) {
534 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600535 } finally {
536 Trace.traceEnd(TRACE_TAG_DATABASE);
537 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700538 }
539
540 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700541 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800542 @Nullable String attributionTag, Uri uri, String mimeType, Bundle opts,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700543 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600544 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600545 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100546 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800547 enforceFilePermission(callingPkg, attributionTag, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600548 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700549 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800550 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700551 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700552 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700553 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700554 } catch (RemoteException e) {
555 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700556 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700557 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600558 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700559 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700560 }
561
Jeff Brown75ea64f2012-01-25 19:37:13 -0800562 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700563 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800564 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800565 }
566
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700567 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800568 public Uri canonicalize(String callingPkg, @Nullable String attributionTag, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600569 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100570 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100571 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800572 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700573 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700574 return null;
575 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600576 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700577 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800578 new Pair<>(callingPkg, attributionTag));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700579 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700580 return maybeAddUserId(mInterface.canonicalize(uri), userId);
581 } catch (RemoteException e) {
582 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700583 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700584 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600585 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700586 }
587 }
588
589 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800590 public void canonicalizeAsync(String callingPkg, @Nullable String attributionTag, Uri uri,
Dmitri Plotnikov7a223fb2020-02-14 17:04:13 -0800591 RemoteCallback callback) {
592 final Bundle result = new Bundle();
Dmitri Plotnikovda4f3c82020-03-25 14:08:20 -0700593 try {
594 result.putParcelable(ContentResolver.REMOTE_CALLBACK_RESULT,
595 canonicalize(callingPkg, attributionTag, uri));
596 } catch (Exception e) {
597 putExceptionInBundle(result, ContentResolver.REMOTE_CALLBACK_ERROR, e);
598 }
Dmitri Plotnikov7a223fb2020-02-14 17:04:13 -0800599 callback.sendResult(result);
600 }
601
602 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800603 public Uri uncanonicalize(String callingPkg, String attributionTag, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600604 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100605 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100606 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800607 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700608 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700609 return null;
610 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600611 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700612 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800613 new Pair<>(callingPkg, attributionTag));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700614 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700615 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
616 } catch (RemoteException e) {
617 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700618 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700619 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600620 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700621 }
622 }
623
Ben Lin1cf454f2016-11-10 13:50:54 -0800624 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800625 public boolean refresh(String callingPkg, String attributionTag, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800626 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600627 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800628 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800629 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700630 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800631 return false;
632 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600633 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700634 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800635 new Pair<>(callingPkg, attributionTag));
Ben Lin1cf454f2016-11-10 13:50:54 -0800636 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700637 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800638 CancellationSignal.fromTransport(cancellationSignal));
639 } finally {
640 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600641 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800642 }
643 }
644
Jeff Sharkey9edef252019-05-20 14:00:17 -0600645 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800646 public int checkUriPermission(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700647 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600648 uri = validateIncomingUri(uri);
649 uri = maybeGetUriWithoutUserId(uri);
650 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700651 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800652 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600653 try {
654 return mInterface.checkUriPermission(uri, uid, modeFlags);
655 } catch (RemoteException e) {
656 throw e.rethrowAsRuntimeException();
657 } finally {
658 setCallingPackage(original);
659 Trace.traceEnd(TRACE_TAG_DATABASE);
660 }
661 }
662
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800663 private void enforceFilePermission(String callingPkg, @Nullable String attributionTag,
664 Uri uri, String mode, IBinder callerToken)
665 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800666 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800667 if (enforceWritePermission(callingPkg, attributionTag, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800668 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800669 throw new FileNotFoundException("App op not allowed");
670 }
671 } else {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800672 if (enforceReadPermission(callingPkg, attributionTag, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800673 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800674 throw new FileNotFoundException("App op not allowed");
675 }
676 }
677 }
678
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800679 private int enforceReadPermission(String callingPkg, @Nullable String attributionTag,
680 Uri uri, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800681 throws SecurityException {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800682 final int mode = enforceReadPermissionInner(uri, callingPkg, attributionTag,
683 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700684 if (mode != MODE_ALLOWED) {
685 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800686 }
Svet Ganov99b60432015-06-27 13:15:22 -0700687
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800688 return noteProxyOp(callingPkg, attributionTag, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800689 }
690
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800691 private int enforceWritePermission(String callingPkg, String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700692 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800693 throws SecurityException {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800694 final int mode = enforceWritePermissionInner(uri, callingPkg, attributionTag,
695 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700696 if (mode != MODE_ALLOWED) {
697 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800698 }
Svet Ganov99b60432015-06-27 13:15:22 -0700699
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800700 return noteProxyOp(callingPkg, attributionTag, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700701 }
702
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800703 private int noteProxyOp(String callingPkg, String attributionTag, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700704 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700705 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800706 attributionTag, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700707 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700708 }
709
Dianne Hackborn35654b62013-01-14 17:38:02 -0800710 return AppOpsManager.MODE_ALLOWED;
711 }
Dmitri Plotnikovda4f3c82020-03-25 14:08:20 -0700712
713 private void putExceptionInBundle(Bundle bundle, String key, Exception e) {
714 Parcel parcel = Parcel.obtain();
715 try {
716 try {
717 parcel.writeException(e);
718 } catch (Exception ex) {
719 // getType threw an unparcelable exception. Wrap the message into
720 // a parcelable exception type
721 parcel.writeException(new IllegalStateException(e.getMessage()));
722 }
723 bundle.putByteArray(key, parcel.marshall());
724 } finally {
725 parcel.recycle();
726 }
727 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700728 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800729
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100730 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700731 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
732 return true;
733 }
734 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
735 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100736 == PERMISSION_GRANTED;
737 }
738
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700739 /**
740 * Verify that calling app holds both the given permission and any app-op
741 * associated with that permission.
742 */
743 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800744 @Nullable String attributionTag, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700745 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
746 callerToken) != PERMISSION_GRANTED) {
747 return MODE_ERRORED;
748 }
749
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800750 return mTransport.noteProxyOp(callingPkg, attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700751 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700752 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700753
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700754 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700755 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800756 @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700757 final Context context = getContext();
758 final int pid = Binder.getCallingPid();
759 final int uid = Binder.getCallingUid();
760 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700761 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700762
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700763 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700764 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700765 }
766
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100767 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700768 final String componentPerm = getReadPermission();
769 if (componentPerm != null) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800770 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700771 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700772 if (mode == MODE_ALLOWED) {
773 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700774 } else {
775 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700776 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700777 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700778 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700779
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700780 // track if unprotected read is allowed; any denied
781 // <path-permission> below removes this ability
782 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700783
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700784 final PathPermission[] pps = getPathPermissions();
785 if (pps != null) {
786 final String path = uri.getPath();
787 for (PathPermission pp : pps) {
788 final String pathPerm = pp.getReadPermission();
789 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800790 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
791 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700792 if (mode == MODE_ALLOWED) {
793 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700794 } else {
795 // any denied <path-permission> means we lose
796 // default <provider> access.
797 allowDefaultRead = false;
798 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700799 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700800 }
801 }
802 }
803 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700804
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700805 // if we passed <path-permission> checks above, and no default
806 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700807 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700809
810 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800811 final int callingUserId = UserHandle.getUserId(uid);
812 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
813 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800814 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
815 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700816 return MODE_ALLOWED;
817 }
818
819 // If the worst denial we found above was ignored, then pass that
820 // ignored through; otherwise we assume it should be a real error below.
821 if (strongestMode == MODE_IGNORED) {
822 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700823 }
824
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600825 final String suffix;
826 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
827 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
828 } else if (mExported) {
829 suffix = " requires " + missingPerm + ", or grantUriPermission()";
830 } else {
831 suffix = " requires the provider be exported, or grantUriPermission()";
832 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700833 throw new SecurityException("Permission Denial: reading "
834 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600835 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700836 }
837
838 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700839 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800840 @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700841 final Context context = getContext();
842 final int pid = Binder.getCallingPid();
843 final int uid = Binder.getCallingUid();
844 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700845 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700846
847 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700848 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700849 }
850
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100851 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700852 final String componentPerm = getWritePermission();
853 if (componentPerm != null) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800854 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg,
855 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700856 if (mode == MODE_ALLOWED) {
857 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700858 } else {
859 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700860 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700861 }
862 }
863
864 // track if unprotected write is allowed; any denied
865 // <path-permission> below removes this ability
866 boolean allowDefaultWrite = (componentPerm == null);
867
868 final PathPermission[] pps = getPathPermissions();
869 if (pps != null) {
870 final String path = uri.getPath();
871 for (PathPermission pp : pps) {
872 final String pathPerm = pp.getWritePermission();
873 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800874 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
875 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700876 if (mode == MODE_ALLOWED) {
877 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700878 } else {
879 // any denied <path-permission> means we lose
880 // default <provider> access.
881 allowDefaultWrite = false;
882 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700883 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700884 }
885 }
886 }
887 }
888
889 // if we passed <path-permission> checks above, and no default
890 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700891 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700892 }
893
894 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800895 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
896 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700897 return MODE_ALLOWED;
898 }
899
900 // If the worst denial we found above was ignored, then pass that
901 // ignored through; otherwise we assume it should be a real error below.
902 if (strongestMode == MODE_IGNORED) {
903 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700904 }
905
906 final String failReason = mExported
907 ? " requires " + missingPerm + ", or grantUriPermission()"
908 : " requires the provider be exported, or grantUriPermission()";
909 throw new SecurityException("Permission Denial: writing "
910 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
911 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700915 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800916 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 * constructor.
918 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700919 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 return mContext;
921 }
922
923 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700924 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
925 * after {@link #onCreate}. When called before context was created, an IllegalStateException
926 * will be thrown.
927 * <p>
928 * Note A provider must be declared in the manifest and created automatically by the system,
929 * and context is only available after {@link #onCreate} is called.
930 */
931 @NonNull
932 public final Context requireContext() {
933 final Context ctx = getContext();
934 if (ctx == null) {
935 throw new IllegalStateException("Cannot find context from the provider.");
936 }
937 return ctx;
938 }
939
940 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700941 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700942 * which can be used later to restore the previous state.
943 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700944 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
945 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700946 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600947 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700948 return original;
949 }
950
951 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700952 * Return the package name of the caller that initiated the request being
953 * processed on the current thread. The returned package will have been
954 * verified to belong to the calling UID. Returns {@code null} if not
955 * currently processing a request.
956 * <p>
957 * This will always return {@code null} when processing
958 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
959 *
960 * @see Binder#getCallingUid()
961 * @see Context#grantUriPermission(String, Uri, int)
962 * @throws SecurityException if the calling package doesn't belong to the
963 * calling UID.
964 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700965 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700966 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700967 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700968 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
969 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700970 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700971
972 return null;
973 }
974
975 /**
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800976 * Return the attribution tag of the caller that initiated the request being
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700977 * processed on the current thread. Returns {@code null} if not currently processing
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800978 * a request of the request is for the default attribution.
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700979 * <p>
980 * This will always return {@code null} when processing
981 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
982 *
983 * @see #getCallingPackage
984 */
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800985 public final @Nullable String getCallingAttributionTag() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700986 final Pair<String, String> pkg = mCallingPackage.get();
987 if (pkg != null) {
988 return pkg.second;
989 }
990
991 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700992 }
993
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700994 /**
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800995 * @removed
996 */
997 @Deprecated
998 public final @Nullable String getCallingFeatureId() {
999 return getCallingAttributionTag();
1000 }
1001
1002 /**
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001003 * Return the package name of the caller that initiated the request being
1004 * processed on the current thread. The returned package will have
1005 * <em>not</em> been verified to belong to the calling UID. Returns
1006 * {@code null} if not currently processing a request.
1007 * <p>
1008 * This will always return {@code null} when processing
1009 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
1010 *
1011 * @see Binder#getCallingUid()
1012 * @see Context#grantUriPermission(String, Uri, int)
1013 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001014 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001015 final Pair<String, String> pkg = mCallingPackage.get();
1016 if (pkg != null) {
1017 return pkg.first;
1018 }
1019
1020 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001021 }
1022
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001023 /**
1024 * Called whenever the value of {@link #getCallingPackage()} changes, giving
1025 * the provider an opportunity to invalidate any security related caching it
1026 * may be performing.
1027 * <p>
1028 * This typically happens when a {@link ContentProvider} makes a nested call
1029 * back into itself when already processing a call from a remote process.
1030 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001031 public void onCallingPackageChanged() {
1032 }
1033
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001034 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001035 * Opaque token representing the identity of an incoming IPC.
1036 */
1037 public final class CallingIdentity {
1038 /** {@hide} */
1039 public final long binderToken;
1040 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001041 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001042
1043 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001044 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001045 this.binderToken = binderToken;
1046 this.callingPackage = callingPackage;
1047 }
1048 }
1049
1050 /**
1051 * Reset the identity of the incoming IPC on the current thread.
1052 * <p>
1053 * Internally this calls {@link Binder#clearCallingIdentity()} and also
1054 * clears any value stored in {@link #getCallingPackage()}.
1055 *
1056 * @return Returns an opaque token that can be used to restore the original
1057 * calling identity by passing it to
1058 * {@link #restoreCallingIdentity}.
1059 */
1060 public final @NonNull CallingIdentity clearCallingIdentity() {
1061 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
1062 }
1063
1064 /**
1065 * Restore the identity of the incoming IPC on the current thread back to a
1066 * previously identity that was returned by {@link #clearCallingIdentity}.
1067 * <p>
1068 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
1069 * also restores any value stored in {@link #getCallingPackage()}.
1070 */
1071 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
1072 Binder.restoreCallingIdentity(identity.binderToken);
1073 mCallingPackage.set(identity.callingPackage);
1074 }
1075
1076 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001077 * Change the authorities of the ContentProvider.
1078 * This is normally set for you from its manifest information when the provider is first
1079 * created.
1080 * @hide
1081 * @param authorities the semi-colon separated authorities of the ContentProvider.
1082 */
1083 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001084 if (authorities != null) {
1085 if (authorities.indexOf(';') == -1) {
1086 mAuthority = authorities;
1087 mAuthorities = null;
1088 } else {
1089 mAuthority = null;
1090 mAuthorities = authorities.split(";");
1091 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001092 }
1093 }
1094
1095 /** @hide */
1096 protected final boolean matchesOurAuthorities(String authority) {
1097 if (mAuthority != null) {
1098 return mAuthority.equals(authority);
1099 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001100 if (mAuthorities != null) {
1101 int length = mAuthorities.length;
1102 for (int i = 0; i < length; i++) {
1103 if (mAuthorities[i].equals(authority)) return true;
1104 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001105 }
1106 return false;
1107 }
1108
1109
1110 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * Change the permission required to read data from the content
1112 * provider. This is normally set for you from its manifest information
1113 * when the provider is first created.
1114 *
1115 * @param permission Name of the permission required for read-only access.
1116 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001117 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 mReadPermission = permission;
1119 }
1120
1121 /**
1122 * Return the name of the permission required for read-only access to
1123 * this content provider. This method can be called from multiple
1124 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001125 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1126 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001128 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 return mReadPermission;
1130 }
1131
1132 /**
1133 * Change the permission required to read and write data in the content
1134 * provider. This is normally set for you from its manifest information
1135 * when the provider is first created.
1136 *
1137 * @param permission Name of the permission required for read/write access.
1138 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001139 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 mWritePermission = permission;
1141 }
1142
1143 /**
1144 * Return the name of the permission required for read/write access to
1145 * this content provider. This method can be called from multiple
1146 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001147 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1148 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001150 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 return mWritePermission;
1152 }
1153
1154 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001155 * Change the path-based permission required to read and/or write data in
1156 * the content provider. This is normally set for you from its manifest
1157 * information when the provider is first created.
1158 *
1159 * @param permissions Array of path permission descriptions.
1160 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001161 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001162 mPathPermissions = permissions;
1163 }
1164
1165 /**
1166 * Return the path-based permissions required for read and/or write access to
1167 * this content provider. This method can be called from multiple
1168 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001169 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1170 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001171 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001172 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001173 return mPathPermissions;
1174 }
1175
Dianne Hackborn35654b62013-01-14 17:38:02 -08001176 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001177 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001178 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001179 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001180 mTransport.mReadOp = readOp;
1181 mTransport.mWriteOp = writeOp;
1182 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001183 }
1184
Dianne Hackborn961321f2013-02-05 17:22:41 -08001185 /** @hide */
1186 public AppOpsManager getAppOpsManager() {
1187 return mTransport.mAppOpsManager;
1188 }
1189
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001190 /** @hide */
1191 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001192 if (mTransport == null) {
1193 return;
1194 }
1195 if (enabled) {
1196 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1197 } else {
1198 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001199 }
1200 }
1201
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001202 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001203 * Implement this to initialize your content provider on startup.
1204 * This method is called for all registered content providers on the
1205 * application main thread at application launch time. It must not perform
1206 * lengthy operations, or application startup will be delayed.
1207 *
1208 * <p>You should defer nontrivial initialization (such as opening,
1209 * upgrading, and scanning databases) until the content provider is used
1210 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1211 * keeps application startup fast, avoids unnecessary work if the provider
1212 * turns out not to be needed, and stops database errors (such as a full
1213 * disk) from halting application launch.
1214 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001215 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001216 * is a helpful utility class that makes it easy to manage databases,
1217 * and will automatically defer opening until first use. If you do use
1218 * SQLiteOpenHelper, make sure to avoid calling
1219 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1220 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1221 * from this method. (Instead, override
1222 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1223 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 *
1225 * @return true if the provider was successfully loaded, false otherwise
1226 */
1227 public abstract boolean onCreate();
1228
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001229 /**
1230 * {@inheritDoc}
1231 * This method is always called on the application main thread, and must
1232 * not perform lengthy operations.
1233 *
1234 * <p>The default content provider implementation does nothing.
1235 * Override this method to take appropriate action.
1236 * (Content providers do not usually care about things like screen
1237 * orientation, but may want to know about locale changes.)
1238 */
Steve McKayea93fe72016-12-02 11:35:35 -08001239 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 public void onConfigurationChanged(Configuration newConfig) {
1241 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001242
1243 /**
1244 * {@inheritDoc}
1245 * This method is always called on the application main thread, and must
1246 * not perform lengthy operations.
1247 *
1248 * <p>The default content provider implementation does nothing.
1249 * Subclasses may override this method to take appropriate action.
1250 */
Steve McKayea93fe72016-12-02 11:35:35 -08001251 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 public void onLowMemory() {
1253 }
1254
Steve McKayea93fe72016-12-02 11:35:35 -08001255 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001256 public void onTrimMemory(int level) {
1257 }
1258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001260 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001261 *
1262 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1263 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1264 * implementation of this method.
1265 *
1266 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001267 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1268 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 * <p>
1270 * Example client call:<p>
1271 * <pre>// Request a specific record.
1272 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001273 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 projection, // Which columns to return.
1275 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001276 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 People.NAME + " ASC"); // Sort order.</pre>
1278 * Example implementation:<p>
1279 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1280 // proper SQL syntax for us.
1281 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1282
1283 // Set the table we're querying.
1284 qBuilder.setTables(DATABASE_TABLE_NAME);
1285
1286 // If the query ends in a specific record number, we're
1287 // being asked for a specific record, so set the
1288 // WHERE clause in our query.
1289 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1290 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1291 }
1292
1293 // Make the query.
1294 Cursor c = qBuilder.query(mDb,
1295 projection,
1296 selection,
1297 selectionArgs,
1298 groupBy,
1299 having,
1300 sortOrder);
1301 c.setNotificationUri(getContext().getContentResolver(), uri);
1302 return c;</pre>
1303 *
1304 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001305 * if the client is requesting a specific record, the URI will end in a record number
1306 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1307 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001309 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001311 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001312 * @param selectionArgs You may include ?s in selection, which will be replaced by
1313 * the values from selectionArgs, in order that they appear in the selection.
1314 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001316 * If {@code null} then the provider is free to define the sort order.
1317 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001319 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1320 @Nullable String selection, @Nullable String[] selectionArgs,
1321 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322
Fred Quintana5bba6322009-10-05 14:21:12 -07001323 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001324 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001325 *
1326 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1327 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1328 *
1329 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001330 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1331 * and Threads</a>.
1332 * <p>
1333 * Example client call:<p>
1334 * <pre>// Request a specific record.
1335 * Cursor managedCursor = managedQuery(
1336 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1337 projection, // Which columns to return.
1338 null, // WHERE clause.
1339 null, // WHERE clause value substitution
1340 People.NAME + " ASC"); // Sort order.</pre>
1341 * Example implementation:<p>
1342 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1343 // proper SQL syntax for us.
1344 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1345
1346 // Set the table we're querying.
1347 qBuilder.setTables(DATABASE_TABLE_NAME);
1348
1349 // If the query ends in a specific record number, we're
1350 // being asked for a specific record, so set the
1351 // WHERE clause in our query.
1352 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1353 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1354 }
1355
1356 // Make the query.
1357 Cursor c = qBuilder.query(mDb,
1358 projection,
1359 selection,
1360 selectionArgs,
1361 groupBy,
1362 having,
1363 sortOrder);
1364 c.setNotificationUri(getContext().getContentResolver(), uri);
1365 return c;</pre>
1366 * <p>
1367 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001368 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1369 * signal to ensure correct operation on older versions of the Android Framework in
1370 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001371 *
1372 * @param uri The URI to query. This will be the full URI sent by the client;
1373 * if the client is requesting a specific record, the URI will end in a record number
1374 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1375 * that _id value.
1376 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001377 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001378 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001379 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001380 * @param selectionArgs You may include ?s in selection, which will be replaced by
1381 * the values from selectionArgs, in order that they appear in the selection.
1382 * The values will be bound as Strings.
1383 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001384 * If {@code null} then the provider is free to define the sort order.
1385 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001386 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001387 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001388 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001389 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001390 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1391 @Nullable String selection, @Nullable String[] selectionArgs,
1392 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001393 return query(uri, projection, selection, selectionArgs, sortOrder);
1394 }
1395
1396 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001397 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1398 * Arguments may include traditional SQL style query arguments. When present these
1399 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001400 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001401 *
1402 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001403 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1404 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1405 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001406 *
Steve McKay76b27702017-04-24 12:07:53 -07001407 * <p>This method can be called from multiple threads, as described in
1408 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1409 * and Threads</a>.
1410 *
1411 * <p>
1412 * Example client call:<p>
1413 * <pre>// Request 20 records starting at row index 30.
1414 Bundle queryArgs = new Bundle();
1415 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1416 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1417
1418 Cursor cursor = getContentResolver().query(
1419 contentUri, // Content Uri is specific to individual content providers.
1420 projection, // String[] describing which columns to return.
1421 queryArgs, // Query arguments.
1422 null); // Cancellation signal.</pre>
1423 *
1424 * Example implementation:<p>
1425 * <pre>
1426
1427 int recordsetSize = 0x1000; // Actual value is implementation specific.
1428 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1429
1430 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1431 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1432
1433 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1434
1435 // Calculate the number of items to include in the cursor.
1436 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1437
1438 // Build the paged result set....
1439 for (int i = offset; i < offset + numItems; i++) {
1440 // populate row from your data.
1441 }
1442
1443 Bundle extras = new Bundle();
1444 c.setExtras(extras);
1445
1446 // Any QUERY_ARG_* key may be included if honored.
1447 // In an actual implementation, include only keys that are both present in queryArgs
1448 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1449 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1450 // then QUERY_ARG_OFFSET should be omitted.
1451 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1452 ContentResolver.QUERY_ARG_OFFSET,
1453 ContentResolver.QUERY_ARG_LIMIT
1454 });
1455
1456 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1457
1458 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1459
1460 return cursor;</pre>
1461 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001462 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1463 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001464 *
1465 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001466 * @param projection The list of columns to put into the cursor.
1467 * If {@code null} provide a default set of columns.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001468 * @param queryArgs A Bundle containing additional information necessary for
1469 * the operation. Arguments may include SQL style arguments, such
1470 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1471 * the documentation for each individual provider will indicate
1472 * which arguments they support.
Steve McKayea93fe72016-12-02 11:35:35 -08001473 * @param cancellationSignal A signal to cancel the operation in progress,
1474 * or {@code null}.
1475 * @return a Cursor or {@code null}.
1476 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001477 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001478 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1479 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1480 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001481
Steve McKayd7ece9f2017-01-12 16:59:59 -08001482 // if client doesn't supply an SQL sort order argument, attempt to build one from
1483 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001484 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001485 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1486 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1487 }
1488
Steve McKayea93fe72016-12-02 11:35:35 -08001489 return query(
1490 uri,
1491 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001492 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1493 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1494 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001495 cancellationSignal);
1496 }
1497
1498 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001499 * Implement this to handle requests for the MIME type of the data at the
1500 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 * <code>vnd.android.cursor.item</code> for a single record,
1502 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001503 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001504 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1505 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001507 * <p>Note that there are no permissions needed for an application to
1508 * access this information; if your content provider requires read and/or
1509 * write permissions, or is not exported, all applications can still call
1510 * this method regardless of their access permissions. This allows them
1511 * to retrieve the MIME type for a URI when dispatching intents.
1512 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001514 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001516 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001517 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
1519 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001520 * Implement this to support canonicalization of URIs that refer to your
1521 * content provider. A canonical URI is one that can be transported across
1522 * devices, backup/restore, and other contexts, and still be able to refer
1523 * to the same data item. Typically this is implemented by adding query
1524 * params to the URI allowing the content provider to verify that an incoming
1525 * canonical URI references the same data as it was originally intended for and,
1526 * if it doesn't, to find that data (if it exists) in the current environment.
1527 *
1528 * <p>For example, if the content provider holds people and a normal URI in it
1529 * is created with a row index into that people database, the cananical representation
1530 * may have an additional query param at the end which specifies the name of the
1531 * person it is intended for. Later calls into the provider with that URI will look
1532 * up the row of that URI's base index and, if it doesn't match or its entry's
1533 * name doesn't match the name in the query param, perform a query on its database
1534 * to find the correct row to operate on.</p>
1535 *
1536 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1537 * URIs (including this one) must perform this verification and recovery of any
1538 * canonical URIs they receive. In addition, you must also implement
1539 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1540 *
1541 * <p>The default implementation of this method returns null, indicating that
1542 * canonical URIs are not supported.</p>
1543 *
1544 * @param url The Uri to canonicalize.
1545 *
1546 * @return Return the canonical representation of <var>url</var>, or null if
1547 * canonicalization of that Uri is not supported.
1548 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001549 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001550 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001551 return null;
1552 }
1553
1554 /**
1555 * Remove canonicalization from canonical URIs previously returned by
1556 * {@link #canonicalize}. For example, if your implementation is to add
1557 * a query param to canonicalize a URI, this method can simply trip any
1558 * query params on the URI. The default implementation always returns the
1559 * same <var>url</var> that was passed in.
1560 *
1561 * @param url The Uri to remove any canonicalization from.
1562 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001563 * @return Return the non-canonical representation of <var>url</var>, return
1564 * the <var>url</var> as-is if there is nothing to do, or return null if
1565 * the data identified by the canonical representation can not be found in
1566 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001567 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001568 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001569 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001570 return url;
1571 }
1572
1573 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001574 * Implement this to support refresh of content identified by {@code uri}.
1575 * By default, this method returns false; providers who wish to implement
1576 * this should return true to signal the client that the provider has tried
1577 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001578 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001579 * This allows clients to request an explicit refresh of content identified
1580 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001581 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001582 * Client code should only invoke this method when there is a strong
1583 * indication (such as a user initiated pull to refresh gesture) that the
1584 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001585 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001586 * Remember to send
1587 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001588 * notifications when content changes.
1589 *
1590 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001591 * @param extras Additional options from the client. The definitions of
1592 * these are specific to the content provider being called.
1593 * @param cancellationSignal A signal to cancel the operation in progress,
1594 * or {@code null} if none. For example, if you called refresh on
1595 * a particular uri, you should call
1596 * {@link CancellationSignal#throwIfCanceled()} to check whether
1597 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001598 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001599 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001600 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001601 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001602 @Nullable CancellationSignal cancellationSignal) {
1603 return false;
1604 }
1605
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001606 /**
1607 * Perform a detailed internal check on a {@link Uri} to determine if a UID
1608 * is able to access it with specific mode flags.
1609 * <p>
1610 * This method is typically used when the provider implements more dynamic
1611 * access controls that cannot be expressed with {@code <path-permission>}
1612 * style static rules.
Jeff Sharkeyce8a353b2020-03-19 21:41:57 -06001613 * <p>
1614 * Because validation of these dynamic access controls has significant
1615 * system health impact, this feature is only available to providers that
1616 * are built into the system.
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001617 *
1618 * @param uri the {@link Uri} to perform an access check on.
1619 * @param uid the UID to check the permission for.
1620 * @param modeFlags the access flags to use for the access check, such as
1621 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}.
1622 * @return {@link PackageManager#PERMISSION_GRANTED} if access is allowed,
1623 * otherwise {@link PackageManager#PERMISSION_DENIED}.
1624 * @hide
1625 */
Jeff Sharkey9edef252019-05-20 14:00:17 -06001626 @Override
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001627 @SystemApi
Jeff Sharkey9edef252019-05-20 14:00:17 -06001628 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1629 return PackageManager.PERMISSION_DENIED;
1630 }
1631
Ben Lin1cf454f2016-11-10 13:50:54 -08001632 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001633 * @hide
1634 * Implementation when a caller has performed an insert on the content
1635 * provider, but that call has been rejected for the operation given
1636 * to {@link #setAppOps(int, int)}. The default implementation simply
1637 * returns a dummy URI that is the base URI with a 0 path element
1638 * appended.
1639 */
1640 public Uri rejectInsert(Uri uri, ContentValues values) {
1641 // If not allowed, we need to return some reasonable URI. Maybe the
1642 // content provider should be responsible for this, but for now we
1643 // will just return the base URI with a dummy '0' tagged on to it.
1644 // You shouldn't be able to read if you can't write, anyway, so it
1645 // shouldn't matter much what is returned.
1646 return uri.buildUpon().appendPath("0").build();
1647 }
1648
1649 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001650 * Implement this to handle requests to insert a new row. As a courtesy,
1651 * call
1652 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1653 * notifyChange()} after inserting. This method can be called from multiple
1654 * threads, as described in <a href="
1655 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001656 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001657 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001658 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 * @param values A set of column_name/value pairs to add to the database.
1660 * @return The URI for the newly inserted item.
1661 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001662 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663
1664 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001665 * Implement this to handle requests to insert a new row. As a courtesy,
1666 * call
1667 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1668 * notifyChange()} after inserting. This method can be called from multiple
1669 * threads, as described in <a href="
1670 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1671 * and Threads</a>.
1672 *
1673 * @param uri The content:// URI of the insertion request.
1674 * @param values A set of column_name/value pairs to add to the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001675 * @param extras A Bundle containing additional information necessary for
1676 * the operation. Arguments may include SQL style arguments, such
1677 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1678 * the documentation for each individual provider will indicate
1679 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001680 * @return The URI for the newly inserted item.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001681 * @throws IllegalArgumentException if the provider doesn't support one of
1682 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001683 */
1684 @Override
1685 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1686 @Nullable Bundle extras) {
1687 return insert(uri, values);
1688 }
1689
1690 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001691 * Override this to handle requests to insert a set of new rows, or the
1692 * default implementation will iterate over the values and call
1693 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1695 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001696 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001697 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1698 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 *
1700 * @param uri The content:// URI of the insertion request.
1701 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001702 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 * @return The number of values that were inserted.
1704 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001705 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001706 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 int numValues = values.length;
1708 for (int i = 0; i < numValues; i++) {
1709 insert(uri, values[i]);
1710 }
1711 return numValues;
1712 }
1713
1714 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001715 * Implement this to handle requests to delete one or more rows. The
1716 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001717 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001718 * As a courtesy, call
1719 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1720 * notifyChange()} after deleting. This method can be called from multiple
1721 * threads, as described in <a href="
1722 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001723 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001724 * <p>
1725 * The implementation is responsible for parsing out a row ID at the end of
1726 * the URI, if a specific row is being deleted. That is, the client would
1727 * pass in <code>content://contacts/people/22</code> and the implementation
1728 * is responsible for parsing the record number (22) when creating a SQL
1729 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001731 * @param uri The full URI to query, including a row ID (if a specific
1732 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 * @param selection An optional restriction to apply to rows when deleting.
1734 * @return The number of rows affected.
1735 * @throws SQLException
1736 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001737 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1738 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739
1740 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001741 * Implement this to handle requests to delete one or more rows. The
1742 * implementation should apply the selection clause when performing
1743 * deletion, allowing the operation to affect multiple rows in a directory.
1744 * As a courtesy, call
1745 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1746 * notifyChange()} after deleting. This method can be called from multiple
1747 * threads, as described in <a href="
1748 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1749 * and Threads</a>.
1750 * <p>
1751 * The implementation is responsible for parsing out a row ID at the end of
1752 * the URI, if a specific row is being deleted. That is, the client would
1753 * pass in <code>content://contacts/people/22</code> and the implementation
1754 * is responsible for parsing the record number (22) when creating a SQL
1755 * statement.
1756 *
1757 * @param uri The full URI to query, including a row ID (if a specific
1758 * record is requested).
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001759 * @param extras A Bundle containing additional information necessary for
1760 * the operation. Arguments may include SQL style arguments, such
1761 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1762 * the documentation for each individual provider will indicate
1763 * which arguments they support.
1764 * @throws IllegalArgumentException if the provider doesn't support one of
1765 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001766 * @throws SQLException
1767 */
1768 @Override
1769 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1770 extras = (extras != null) ? extras : Bundle.EMPTY;
1771 return delete(uri,
1772 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1773 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1774 }
1775
1776 /**
1777 * Implement this to handle requests to update one or more rows. The
1778 * implementation should update all rows matching the selection to set the
1779 * columns according to the provided values map. As a courtesy, call
1780 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1781 * notifyChange()} after updating. This method can be called from multiple
1782 * threads, as described in <a href="
1783 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001784 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001786 * @param uri The URI to query. This can potentially have a record ID if
1787 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001788 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 * @param selection An optional filter to match rows to update.
1790 * @return the number of rows affected.
1791 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001792 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001793 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794
1795 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001796 * Implement this to handle requests to update one or more rows. The
1797 * implementation should update all rows matching the selection to set the
1798 * columns according to the provided values map. As a courtesy, call
1799 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1800 * notifyChange()} after updating. This method can be called from multiple
1801 * threads, as described in <a href="
1802 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1803 * and Threads</a>.
1804 *
1805 * @param uri The URI to query. This can potentially have a record ID if
1806 * this is an update request for a specific record.
1807 * @param values A set of column_name/value pairs to update in the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001808 * @param extras A Bundle containing additional information necessary for
1809 * the operation. Arguments may include SQL style arguments, such
1810 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1811 * the documentation for each individual provider will indicate
1812 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001813 * @return the number of rows affected.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001814 * @throws IllegalArgumentException if the provider doesn't support one of
1815 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001816 */
1817 @Override
1818 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1819 @Nullable Bundle extras) {
1820 extras = (extras != null) ? extras : Bundle.EMPTY;
1821 return update(uri, values,
1822 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1823 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1824 }
1825
1826 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001827 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001828 * The default implementation always throws {@link FileNotFoundException}.
1829 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001830 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1831 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001832 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001833 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1834 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001835 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 *
1837 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1838 * their responsibility to close it when done. That is, the implementation
1839 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001840 * <p>
1841 * If opened with the exclusive "r" or "w" modes, the returned
1842 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1843 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1844 * supports seeking.
1845 * <p>
1846 * If you need to detect when the returned ParcelFileDescriptor has been
1847 * closed, or if the remote process has crashed or encountered some other
1848 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1849 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1850 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1851 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001852 * <p>
1853 * If you need to return a large file that isn't backed by a real file on
1854 * disk, such as a file on a network share or cloud storage service,
1855 * consider using
1856 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1857 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001859 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1860 * to return the appropriate MIME type for the data returned here with
1861 * the same URI. This will allow intent resolution to automatically determine the data MIME
1862 * type and select the appropriate matching targets as part of its operation.</p>
1863 *
1864 * <p class="note">For better interoperability with other applications, it is recommended
1865 * that for any URIs that can be opened, you also support queries on them
1866 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1867 * You may also want to support other common columns if you have additional meta-data
1868 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1869 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1870 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 * @param uri The URI whose file is to be opened.
1872 * @param mode Access mode for the file. May be "r" for read-only access,
1873 * "rw" for read and write access, or "rwt" for read and write access
1874 * that truncates any existing file.
1875 *
1876 * @return Returns a new ParcelFileDescriptor which you can use to access
1877 * the file.
1878 *
1879 * @throws FileNotFoundException Throws FileNotFoundException if there is
1880 * no file associated with the given URI or the mode is invalid.
1881 * @throws SecurityException Throws SecurityException if the caller does
1882 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001883 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 * @see #openAssetFile(Uri, String)
1885 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001886 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001887 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001888 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001889 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 throws FileNotFoundException {
1891 throw new FileNotFoundException("No files supported by provider at "
1892 + uri);
1893 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001896 * Override this to handle requests to open a file blob.
1897 * The default implementation always throws {@link FileNotFoundException}.
1898 * This method can be called from multiple threads, as described in
1899 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1900 * and Threads</a>.
1901 *
1902 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1903 * to the caller. This way large data (such as images and documents) can be
1904 * returned without copying the content.
1905 *
1906 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1907 * their responsibility to close it when done. That is, the implementation
1908 * of this method should create a new ParcelFileDescriptor for each call.
1909 * <p>
1910 * If opened with the exclusive "r" or "w" modes, the returned
1911 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1912 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1913 * supports seeking.
1914 * <p>
1915 * If you need to detect when the returned ParcelFileDescriptor has been
1916 * closed, or if the remote process has crashed or encountered some other
1917 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1918 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1919 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1920 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1921 *
1922 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1923 * to return the appropriate MIME type for the data returned here with
1924 * the same URI. This will allow intent resolution to automatically determine the data MIME
1925 * type and select the appropriate matching targets as part of its operation.</p>
1926 *
1927 * <p class="note">For better interoperability with other applications, it is recommended
1928 * that for any URIs that can be opened, you also support queries on them
1929 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1930 * You may also want to support other common columns if you have additional meta-data
1931 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1932 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1933 *
1934 * @param uri The URI whose file is to be opened.
1935 * @param mode Access mode for the file. May be "r" for read-only access,
1936 * "w" for write-only access, "rw" for read and write access, or
1937 * "rwt" for read and write access that truncates any existing
1938 * file.
1939 * @param signal A signal to cancel the operation in progress, or
1940 * {@code null} if none. For example, if you are downloading a
1941 * file from the network to service a "rw" mode request, you
1942 * should periodically call
1943 * {@link CancellationSignal#throwIfCanceled()} to check whether
1944 * the client has canceled the request and abort the download.
1945 *
1946 * @return Returns a new ParcelFileDescriptor which you can use to access
1947 * the file.
1948 *
1949 * @throws FileNotFoundException Throws FileNotFoundException if there is
1950 * no file associated with the given URI or the mode is invalid.
1951 * @throws SecurityException Throws SecurityException if the caller does
1952 * not have permission to access the file.
1953 *
1954 * @see #openAssetFile(Uri, String)
1955 * @see #openFileHelper(Uri, String)
1956 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001957 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001958 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001959 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001960 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1961 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001962 return openFile(uri, mode);
1963 }
1964
1965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 * This is like {@link #openFile}, but can be implemented by providers
1967 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001968 * inside of their .apk.
1969 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001970 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1971 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001972 *
1973 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001974 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001975 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1977 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1978 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001979 * <p>
1980 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1981 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001982 *
1983 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 * should create the AssetFileDescriptor with
1985 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001986 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001988 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1989 * to return the appropriate MIME type for the data returned here with
1990 * the same URI. This will allow intent resolution to automatically determine the data MIME
1991 * type and select the appropriate matching targets as part of its operation.</p>
1992 *
1993 * <p class="note">For better interoperability with other applications, it is recommended
1994 * that for any URIs that can be opened, you also support queries on them
1995 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1996 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 * @param uri The URI whose file is to be opened.
1998 * @param mode Access mode for the file. May be "r" for read-only access,
1999 * "w" for write-only access (erasing whatever data is currently in
2000 * the file), "wa" for write-only access to append to any existing data,
2001 * "rw" for read and write access on any existing data, and "rwt" for read
2002 * and write access that truncates any existing file.
2003 *
2004 * @return Returns a new AssetFileDescriptor which you can use to access
2005 * the file.
2006 *
2007 * @throws FileNotFoundException Throws FileNotFoundException if there is
2008 * no file associated with the given URI or the mode is invalid.
2009 * @throws SecurityException Throws SecurityException if the caller does
2010 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08002011 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 * @see #openFile(Uri, String)
2013 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08002014 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002016 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 throws FileNotFoundException {
2018 ParcelFileDescriptor fd = openFile(uri, mode);
2019 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
2020 }
2021
2022 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002023 * This is like {@link #openFile}, but can be implemented by providers
2024 * that need to be able to return sub-sections of files, often assets
2025 * inside of their .apk.
2026 * This method can be called from multiple threads, as described in
2027 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2028 * and Threads</a>.
2029 *
2030 * <p>If you implement this, your clients must be able to deal with such
2031 * file slices, either directly with
2032 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
2033 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
2034 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
2035 * methods.
2036 * <p>
2037 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2038 * streaming of data.
2039 *
2040 * <p class="note">If you are implementing this to return a full file, you
2041 * should create the AssetFileDescriptor with
2042 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
2043 * applications that cannot handle sub-sections of files.</p>
2044 *
2045 * <p class="note">For use in Intents, you will want to implement {@link #getType}
2046 * to return the appropriate MIME type for the data returned here with
2047 * the same URI. This will allow intent resolution to automatically determine the data MIME
2048 * type and select the appropriate matching targets as part of its operation.</p>
2049 *
2050 * <p class="note">For better interoperability with other applications, it is recommended
2051 * that for any URIs that can be opened, you also support queries on them
2052 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
2053 *
2054 * @param uri The URI whose file is to be opened.
2055 * @param mode Access mode for the file. May be "r" for read-only access,
2056 * "w" for write-only access (erasing whatever data is currently in
2057 * the file), "wa" for write-only access to append to any existing data,
2058 * "rw" for read and write access on any existing data, and "rwt" for read
2059 * and write access that truncates any existing file.
2060 * @param signal A signal to cancel the operation in progress, or
2061 * {@code null} if none. For example, if you are downloading a
2062 * file from the network to service a "rw" mode request, you
2063 * should periodically call
2064 * {@link CancellationSignal#throwIfCanceled()} to check whether
2065 * the client has canceled the request and abort the download.
2066 *
2067 * @return Returns a new AssetFileDescriptor which you can use to access
2068 * the file.
2069 *
2070 * @throws FileNotFoundException Throws FileNotFoundException if there is
2071 * no file associated with the given URI or the mode is invalid.
2072 * @throws SecurityException Throws SecurityException if the caller does
2073 * not have permission to access the file.
2074 *
2075 * @see #openFile(Uri, String)
2076 * @see #openFileHelper(Uri, String)
2077 * @see #getType(android.net.Uri)
2078 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002079 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002080 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
2081 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002082 return openAssetFile(uri, mode);
2083 }
2084
2085 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 * Convenience for subclasses that wish to implement {@link #openFile}
2087 * by looking up a column named "_data" at the given URI.
2088 *
2089 * @param uri The URI to be opened.
2090 * @param mode The file mode. May be "r" for read-only access,
2091 * "w" for write-only access (erasing whatever data is currently in
2092 * the file), "wa" for write-only access to append to any existing data,
2093 * "rw" for read and write access on any existing data, and "rwt" for read
2094 * and write access that truncates any existing file.
2095 *
2096 * @return Returns a new ParcelFileDescriptor that can be used by the
2097 * client to access the file.
2098 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002099 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
2100 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
2102 int count = (c != null) ? c.getCount() : 0;
2103 if (count != 1) {
2104 // If there is not exactly one result, throw an appropriate
2105 // exception.
2106 if (c != null) {
2107 c.close();
2108 }
2109 if (count == 0) {
2110 throw new FileNotFoundException("No entry for " + uri);
2111 }
2112 throw new FileNotFoundException("Multiple items at " + uri);
2113 }
2114
2115 c.moveToFirst();
2116 int i = c.getColumnIndex("_data");
2117 String path = (i >= 0 ? c.getString(i) : null);
2118 c.close();
2119 if (path == null) {
2120 throw new FileNotFoundException("Column _data not found.");
2121 }
2122
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002123 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 return ParcelFileDescriptor.open(new File(path), modeBits);
2125 }
2126
2127 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002128 * Called by a client to determine the types of data streams that this
2129 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002130 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002131 * of a particular type, return that MIME type if it matches the given
2132 * mimeTypeFilter. If it can perform type conversions, return an array
2133 * of all supported MIME types that match mimeTypeFilter.
2134 *
2135 * @param uri The data in the content provider being queried.
2136 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002137 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002138 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002139 * given mimeTypeFilter. Otherwise returns an array of all available
2140 * concrete MIME types.
2141 *
2142 * @see #getType(Uri)
2143 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002144 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002145 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002146 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002147 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002148 return null;
2149 }
2150
2151 /**
2152 * Called by a client to open a read-only stream containing data of a
2153 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2154 * except the file can only be read-only and the content provider may
2155 * perform data conversions to generate data of the desired type.
2156 *
2157 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002158 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002159 * {@link #openAssetFile(Uri, String)}.
2160 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002161 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002162 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002163 * <p>
2164 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2165 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002166 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002167 * <p class="note">For better interoperability with other applications, it is recommended
2168 * that for any URIs that can be opened, you also support queries on them
2169 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2170 * You may also want to support other common columns if you have additional meta-data
2171 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2172 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2173 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002174 * @param uri The data in the content provider being queried.
2175 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002176 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002177 * requirements; in this case the content provider will pick its best
2178 * type matching the pattern.
2179 * @param opts Additional options from the client. The definitions of
2180 * these are specific to the content provider being called.
2181 *
2182 * @return Returns a new AssetFileDescriptor from which the client can
2183 * read data of the desired type.
2184 *
2185 * @throws FileNotFoundException Throws FileNotFoundException if there is
2186 * no file associated with the given URI or the mode is invalid.
2187 * @throws SecurityException Throws SecurityException if the caller does
2188 * not have permission to access the data.
2189 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2190 * content provider does not support the requested MIME type.
2191 *
2192 * @see #getStreamTypes(Uri, String)
2193 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002194 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002195 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002196 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2197 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002198 if ("*/*".equals(mimeTypeFilter)) {
2199 // If they can take anything, the untyped open call is good enough.
2200 return openAssetFile(uri, "r");
2201 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002202 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002203 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002204 // Use old untyped open call if this provider has a type for this
2205 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002206 return openAssetFile(uri, "r");
2207 }
2208 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2209 }
2210
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002211
2212 /**
2213 * Called by a client to open a read-only stream containing data of a
2214 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2215 * except the file can only be read-only and the content provider may
2216 * perform data conversions to generate data of the desired type.
2217 *
2218 * <p>The default implementation compares the given mimeType against the
2219 * result of {@link #getType(Uri)} and, if they match, simply calls
2220 * {@link #openAssetFile(Uri, String)}.
2221 *
2222 * <p>See {@link ClipData} for examples of the use and implementation
2223 * of this method.
2224 * <p>
2225 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2226 * streaming of data.
2227 *
2228 * <p class="note">For better interoperability with other applications, it is recommended
2229 * that for any URIs that can be opened, you also support queries on them
2230 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2231 * You may also want to support other common columns if you have additional meta-data
2232 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2233 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2234 *
2235 * @param uri The data in the content provider being queried.
2236 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002237 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002238 * requirements; in this case the content provider will pick its best
2239 * type matching the pattern.
2240 * @param opts Additional options from the client. The definitions of
2241 * these are specific to the content provider being called.
2242 * @param signal A signal to cancel the operation in progress, or
2243 * {@code null} if none. For example, if you are downloading a
2244 * file from the network to service a "rw" mode request, you
2245 * should periodically call
2246 * {@link CancellationSignal#throwIfCanceled()} to check whether
2247 * the client has canceled the request and abort the download.
2248 *
2249 * @return Returns a new AssetFileDescriptor from which the client can
2250 * read data of the desired type.
2251 *
2252 * @throws FileNotFoundException Throws FileNotFoundException if there is
2253 * no file associated with the given URI or the mode is invalid.
2254 * @throws SecurityException Throws SecurityException if the caller does
2255 * not have permission to access the data.
2256 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2257 * content provider does not support the requested MIME type.
2258 *
2259 * @see #getStreamTypes(Uri, String)
2260 * @see #openAssetFile(Uri, String)
2261 * @see ClipDescription#compareMimeTypes(String, String)
2262 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002263 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002264 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2265 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2266 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002267 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2268 }
2269
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002270 /**
2271 * Interface to write a stream of data to a pipe. Use with
2272 * {@link ContentProvider#openPipeHelper}.
2273 */
2274 public interface PipeDataWriter<T> {
2275 /**
2276 * Called from a background thread to stream data out to a pipe.
2277 * Note that the pipe is blocking, so this thread can block on
2278 * writes for an arbitrary amount of time if the client is slow
2279 * at reading.
2280 *
2281 * @param output The pipe where data should be written. This will be
2282 * closed for you upon returning from this function.
2283 * @param uri The URI whose data is to be written.
2284 * @param mimeType The desired type of data to be written.
2285 * @param opts Options supplied by caller.
2286 * @param args Your own custom arguments.
2287 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002288 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2289 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002290 }
2291
2292 /**
2293 * A helper function for implementing {@link #openTypedAssetFile}, for
2294 * creating a data pipe and background thread allowing you to stream
2295 * generated data back to the client. This function returns a new
2296 * ParcelFileDescriptor that should be returned to the caller (the caller
2297 * is responsible for closing it).
2298 *
2299 * @param uri The URI whose data is to be written.
2300 * @param mimeType The desired type of data to be written.
2301 * @param opts Options supplied by caller.
2302 * @param args Your own custom arguments.
2303 * @param func Interface implementing the function that will actually
2304 * stream the data.
2305 * @return Returns a new ParcelFileDescriptor holding the read side of
2306 * the pipe. This should be returned to the caller for reading; the caller
2307 * is responsible for closing it when done.
2308 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002309 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2310 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2311 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002312 try {
2313 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2314
2315 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2316 @Override
2317 protected Object doInBackground(Object... params) {
2318 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2319 try {
2320 fds[1].close();
2321 } catch (IOException e) {
2322 Log.w(TAG, "Failure closing pipe", e);
2323 }
2324 return null;
2325 }
2326 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002327 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002328
2329 return fds[0];
2330 } catch (IOException e) {
2331 throw new FileNotFoundException("failure making pipe");
2332 }
2333 }
2334
2335 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 * Returns true if this instance is a temporary content provider.
2337 * @return true if this instance is a temporary content provider
2338 */
2339 protected boolean isTemporary() {
2340 return false;
2341 }
2342
2343 /**
2344 * Returns the Binder object for this provider.
2345 *
2346 * @return the Binder object for this provider
2347 * @hide
2348 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002349 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 public IContentProvider getIContentProvider() {
2351 return mTransport;
2352 }
2353
2354 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002355 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2356 * when directly instantiating the provider for testing.
2357 * @hide
2358 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002359 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002360 public void attachInfoForTesting(Context context, ProviderInfo info) {
2361 attachInfo(context, info, true);
2362 }
2363
2364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 * After being instantiated, this is called to tell the content provider
2366 * about itself.
2367 *
2368 * @param context The context this provider is running in
2369 * @param info Registered information about this content provider
2370 */
2371 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002372 attachInfo(context, info, false);
2373 }
2374
2375 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002376 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002377 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 /*
2380 * Only allow it to be set once, so after the content service gives
2381 * this to us clients can't change it.
2382 */
2383 if (mContext == null) {
2384 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002385 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002386 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2387 Context.APP_OPS_SERVICE);
2388 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002389 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 if (info != null) {
2391 setReadPermission(info.readPermission);
2392 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002393 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002394 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002395 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002396 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002398 if (Build.IS_DEBUGGABLE) {
2399 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2400 Log.VERBOSE));
2401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 ContentProvider.this.onCreate();
2403 }
2404 }
Fred Quintanace31b232009-05-04 16:01:15 -07002405
2406 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002407 * Override this to handle requests to perform a batch of operations, or the
2408 * default implementation will iterate over the operations and call
2409 * {@link ContentProviderOperation#apply} on each of them.
2410 * If all calls to {@link ContentProviderOperation#apply} succeed
2411 * then a {@link ContentProviderResult} array with as many
2412 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002413 * fail, it is up to the implementation how many of the others take effect.
2414 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002415 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2416 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002417 *
Fred Quintanace31b232009-05-04 16:01:15 -07002418 * @param operations the operations to apply
2419 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002420 * @throws OperationApplicationException thrown if any operation fails.
2421 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002422 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002423 @Override
2424 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2425 @NonNull ArrayList<ContentProviderOperation> operations)
2426 throws OperationApplicationException {
2427 return applyBatch(operations);
2428 }
2429
Jeff Sharkey673db442015-06-11 19:30:57 -07002430 public @NonNull ContentProviderResult[] applyBatch(
2431 @NonNull ArrayList<ContentProviderOperation> operations)
2432 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002433 final int numOperations = operations.size();
2434 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2435 for (int i = 0; i < numOperations; i++) {
2436 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002437 }
2438 return results;
2439 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002440
2441 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002442 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002443 * interfaces that are cheaper and/or unnatural for a table-like
2444 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002445 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002446 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2447 * on this entry into the content provider besides the basic ability for the application
2448 * to get access to the provider at all. For example, it has no idea whether the call
2449 * being executed may read or write data in the provider, so can't enforce those
2450 * individual permissions. Any implementation of this method <strong>must</strong>
2451 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2452 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002453 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2454 * @param arg provider-defined String argument. May be {@code null}.
2455 * @param extras provider-defined Bundle argument. May be {@code null}.
2456 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002457 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002458 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002459 @Override
2460 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2461 @Nullable String arg, @Nullable Bundle extras) {
2462 return call(method, arg, extras);
2463 }
2464
Jeff Sharkey673db442015-06-11 19:30:57 -07002465 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2466 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002467 return null;
2468 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002469
2470 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002471 * Implement this to shut down the ContentProvider instance. You can then
2472 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002473 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002474 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002475 * Android normally handles ContentProvider startup and shutdown
2476 * automatically. You do not need to start up or shut down a
2477 * ContentProvider. When you invoke a test method on a ContentProvider,
2478 * however, a ContentProvider instance is started and keeps running after
2479 * the test finishes, even if a succeeding test instantiates another
2480 * ContentProvider. A conflict develops because the two instances are
2481 * usually running against the same underlying data source (for example, an
2482 * sqlite database).
2483 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002484 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002485 * Implementing shutDown() avoids this conflict by providing a way to
2486 * terminate the ContentProvider. This method can also prevent memory leaks
2487 * from multiple instantiations of the ContentProvider, and it can ensure
2488 * unit test isolation by allowing you to completely clean up the test
2489 * fixture before moving on to the next test.
2490 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002491 */
2492 public void shutdown() {
2493 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2494 "connections are gracefully shutdown");
2495 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002496
2497 /**
2498 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002499 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002500 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002501 * @param fd The raw file descriptor that the dump is being sent to.
2502 * @param writer The PrintWriter to which you should dump your state. This will be
2503 * closed for you after you return.
2504 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002505 */
2506 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2507 writer.println("nothing to dump");
2508 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002509
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002510 private void validateIncomingAuthority(String authority) throws SecurityException {
2511 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2512 String message = "The authority " + authority + " does not match the one of the "
2513 + "contentProvider: ";
2514 if (mAuthority != null) {
2515 message += mAuthority;
2516 } else {
2517 message += Arrays.toString(mAuthorities);
2518 }
2519 throw new SecurityException(message);
2520 }
2521 }
2522
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002523 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002524 @VisibleForTesting
2525 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002526 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002527 if (!mSingleUser) {
2528 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2529 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2530 throw new SecurityException("trying to query a ContentProvider in user "
2531 + mContext.getUserId() + " with a uri belonging to user " + userId);
2532 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002533 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002534 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002535
2536 // Normalize the path by removing any empty path segments, which can be
2537 // a source of security issues.
2538 final String encodedPath = uri.getEncodedPath();
2539 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002540 final Uri normalized = uri.buildUpon()
2541 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2542 Log.w(TAG, "Normalized " + uri + " to " + normalized
2543 + " to avoid possible security issues");
2544 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002545 } else {
2546 return uri;
2547 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002548 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002549
2550 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002551 private Uri maybeGetUriWithoutUserId(Uri uri) {
2552 if (mSingleUser) {
2553 return uri;
2554 }
2555 return getUriWithoutUserId(uri);
2556 }
2557
2558 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002559 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2560 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002561 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002562 if (end == -1) return defaultUserId;
2563 String userIdString = auth.substring(0, end);
2564 try {
2565 return Integer.parseInt(userIdString);
2566 } catch (NumberFormatException e) {
2567 Log.w(TAG, "Error parsing userId.", e);
2568 return UserHandle.USER_NULL;
2569 }
2570 }
2571
2572 /** @hide */
2573 public static int getUserIdFromAuthority(String auth) {
2574 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2575 }
2576
2577 /** @hide */
2578 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2579 if (uri == null) return defaultUserId;
2580 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2581 }
2582
2583 /** @hide */
2584 public static int getUserIdFromUri(Uri uri) {
2585 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2586 }
2587
2588 /**
Alex Kershawba014ac2020-01-20 22:25:02 +00002589 * Returns the user associated with the given URI.
2590 *
2591 * @hide
2592 */
2593 @TestApi
2594 public @NonNull static UserHandle getUserHandleFromUri(@NonNull Uri uri) {
2595 return UserHandle.of(getUserIdFromUri(uri, Process.myUserHandle().getIdentifier()));
2596 }
2597
2598 /**
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002599 * Removes userId part from authority string. Expects format:
2600 * userId@some.authority
2601 * If there is no userId in the authority, it symply returns the argument
2602 * @hide
2603 */
2604 public static String getAuthorityWithoutUserId(String auth) {
2605 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002606 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002607 return auth.substring(end+1);
2608 }
2609
2610 /** @hide */
2611 public static Uri getUriWithoutUserId(Uri uri) {
2612 if (uri == null) return null;
2613 Uri.Builder builder = uri.buildUpon();
2614 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2615 return builder.build();
2616 }
2617
2618 /** @hide */
2619 public static boolean uriHasUserId(Uri uri) {
2620 if (uri == null) return false;
2621 return !TextUtils.isEmpty(uri.getUserInfo());
2622 }
2623
2624 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002625 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002626 public static Uri maybeAddUserId(Uri uri, int userId) {
2627 if (uri == null) return null;
2628 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002629 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002630 if (!uriHasUserId(uri)) {
2631 //We don't add the user Id if there's already one
2632 Uri.Builder builder = uri.buildUpon();
2633 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2634 return builder.build();
2635 }
2636 }
2637 return uri;
2638 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002639}