blob: 5340d00b04868d23bddb8c966cc7b1c6f49b3357 [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) {
310 Parcel parcel = Parcel.obtain();
311 try {
312 try {
313 parcel.writeException(e);
314 } catch (Exception ex) {
315 // getType threw an unparcelable exception. Wrap the message into
316 // a parcelable exception type
317 parcel.writeException(new IllegalStateException(e.getMessage()));
318 }
319 result.putByteArray(ContentResolver.REMOTE_CALLBACK_ERROR, parcel.marshall());
320 } finally {
321 parcel.recycle();
322 }
323 }
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -0800324 callback.sendResult(result);
325 }
326
327 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800328 public Uri insert(String callingPkg, @Nullable String attributionTag, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700329 ContentValues initialValues, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600330 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100331 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100332 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800333 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700334 != AppOpsManager.MODE_ALLOWED) {
335 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800336 new Pair<>(callingPkg, attributionTag));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700337 try {
338 return rejectInsert(uri, initialValues);
339 } finally {
340 setCallingPackage(original);
341 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800342 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600343 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700344 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800345 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700346 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700347 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700348 } catch (RemoteException e) {
349 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700350 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700351 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600352 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 }
355
Jeff Brown75ea64f2012-01-25 19:37:13 -0800356 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800357 public int bulkInsert(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700358 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600359 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100360 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800361 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700362 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800363 return 0;
364 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600365 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700366 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800367 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700368 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700369 return mInterface.bulkInsert(uri, initialValues);
370 } catch (RemoteException e) {
371 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700372 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700373 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600374 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 }
377
Jeff Brown75ea64f2012-01-25 19:37:13 -0800378 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800379 public ContentProviderResult[] applyBatch(String callingPkg,
380 @Nullable String attributionTag, String authority,
381 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700382 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700383 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100384 int numOperations = operations.size();
385 final int[] userIds = new int[numOperations];
386 for (int i = 0; i < numOperations; i++) {
387 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100388 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600389 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600390 uri = validateIncomingUri(uri);
391 uri = maybeGetUriWithoutUserId(uri);
392 // Rebuild operation if we changed the Uri above
393 if (!Objects.equals(operation.getUri(), uri)) {
394 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100395 operations.set(i, operation);
396 }
Fred Quintana89437372009-05-15 15:10:40 -0700397 if (operation.isReadOperation()) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800398 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800399 != AppOpsManager.MODE_ALLOWED) {
400 throw new OperationApplicationException("App op not allowed", 0);
401 }
Fred Quintana89437372009-05-15 15:10:40 -0700402 }
Fred Quintana89437372009-05-15 15:10:40 -0700403 if (operation.isWriteOperation()) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800404 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800405 != AppOpsManager.MODE_ALLOWED) {
406 throw new OperationApplicationException("App op not allowed", 0);
407 }
Fred Quintana89437372009-05-15 15:10:40 -0700408 }
409 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600410 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700411 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800412 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700413 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700414 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700415 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800416 if (results != null) {
417 for (int i = 0; i < results.length ; i++) {
418 if (userIds[i] != UserHandle.USER_CURRENT) {
419 // Adding the userId to the uri.
420 results[i] = new ContentProviderResult(results[i], userIds[i]);
421 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100422 }
423 }
424 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700425 } catch (RemoteException e) {
426 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700427 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700428 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600429 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700430 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700431 }
432
Jeff Brown75ea64f2012-01-25 19:37:13 -0800433 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800434 public int delete(String callingPkg, @Nullable String attributionTag, Uri uri,
435 Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600436 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100437 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800438 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700439 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800440 return 0;
441 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600442 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700443 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800444 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700445 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700446 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700447 } catch (RemoteException e) {
448 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700449 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700450 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600451 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454
Jeff Brown75ea64f2012-01-25 19:37:13 -0800455 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800456 public int update(String callingPkg, @Nullable String attributionTag, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700457 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600458 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100459 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800460 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700461 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800462 return 0;
463 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600464 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700465 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800466 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700467 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700468 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700469 } catch (RemoteException e) {
470 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700471 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700472 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600473 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 }
476
Jeff Brown75ea64f2012-01-25 19:37:13 -0800477 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800478 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700479 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
480 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600481 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100482 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800483 enforceFilePermission(callingPkg, attributionTag, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600484 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700485 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800486 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700487 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700488 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700489 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700490 } catch (RemoteException e) {
491 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700492 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700493 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600494 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
497
Jeff Brown75ea64f2012-01-25 19:37:13 -0800498 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800499 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700500 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600502 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100503 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800504 enforceFilePermission(callingPkg, attributionTag, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600505 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700506 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800507 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700508 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700509 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700510 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700511 } catch (RemoteException e) {
512 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700513 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700514 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600515 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 }
518
Jeff Brown75ea64f2012-01-25 19:37:13 -0800519 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800520 public Bundle call(String callingPkg, @Nullable String attributionTag, String authority,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700521 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700522 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600523 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600524 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700525 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800526 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700527 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700528 return mInterface.call(authority, method, arg, extras);
529 } catch (RemoteException e) {
530 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700531 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700532 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600533 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700534 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800535 }
536
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700537 @Override
538 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700539 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600540 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100541 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600542 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
543 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700544 return mInterface.getStreamTypes(uri, mimeTypeFilter);
545 } catch (RemoteException e) {
546 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600547 } finally {
548 Trace.traceEnd(TRACE_TAG_DATABASE);
549 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700550 }
551
552 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700553 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800554 @Nullable String attributionTag, Uri uri, String mimeType, Bundle opts,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700555 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600556 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600557 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100558 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800559 enforceFilePermission(callingPkg, attributionTag, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600560 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700561 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800562 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700563 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700564 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700565 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700566 } catch (RemoteException e) {
567 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700568 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700569 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600570 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700571 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700572 }
573
Jeff Brown75ea64f2012-01-25 19:37:13 -0800574 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700575 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800576 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800577 }
578
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700579 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800580 public Uri canonicalize(String callingPkg, @Nullable String attributionTag, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600581 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100582 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100583 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800584 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700585 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700586 return null;
587 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600588 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700589 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800590 new Pair<>(callingPkg, attributionTag));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700591 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700592 return maybeAddUserId(mInterface.canonicalize(uri), userId);
593 } catch (RemoteException e) {
594 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700595 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700596 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600597 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700598 }
599 }
600
601 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800602 public void canonicalizeAsync(String callingPkg, @Nullable String attributionTag, Uri uri,
Dmitri Plotnikov7a223fb2020-02-14 17:04:13 -0800603 RemoteCallback callback) {
604 final Bundle result = new Bundle();
605 result.putParcelable(ContentResolver.REMOTE_CALLBACK_RESULT,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800606 canonicalize(callingPkg, attributionTag, uri));
Dmitri Plotnikov7a223fb2020-02-14 17:04:13 -0800607 callback.sendResult(result);
608 }
609
610 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800611 public Uri uncanonicalize(String callingPkg, String attributionTag, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600612 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100613 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100614 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800615 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700616 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700617 return null;
618 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600619 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700620 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800621 new Pair<>(callingPkg, attributionTag));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700622 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700623 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
624 } catch (RemoteException e) {
625 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700626 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700627 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600628 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700629 }
630 }
631
Ben Lin1cf454f2016-11-10 13:50:54 -0800632 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800633 public boolean refresh(String callingPkg, String attributionTag, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800634 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600635 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800636 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800637 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700638 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800639 return false;
640 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600641 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700642 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800643 new Pair<>(callingPkg, attributionTag));
Ben Lin1cf454f2016-11-10 13:50:54 -0800644 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700645 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800646 CancellationSignal.fromTransport(cancellationSignal));
647 } finally {
648 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600649 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800650 }
651 }
652
Jeff Sharkey9edef252019-05-20 14:00:17 -0600653 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800654 public int checkUriPermission(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700655 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600656 uri = validateIncomingUri(uri);
657 uri = maybeGetUriWithoutUserId(uri);
658 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700659 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800660 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600661 try {
662 return mInterface.checkUriPermission(uri, uid, modeFlags);
663 } catch (RemoteException e) {
664 throw e.rethrowAsRuntimeException();
665 } finally {
666 setCallingPackage(original);
667 Trace.traceEnd(TRACE_TAG_DATABASE);
668 }
669 }
670
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800671 private void enforceFilePermission(String callingPkg, @Nullable String attributionTag,
672 Uri uri, String mode, IBinder callerToken)
673 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800674 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800675 if (enforceWritePermission(callingPkg, attributionTag, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800676 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800677 throw new FileNotFoundException("App op not allowed");
678 }
679 } else {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800680 if (enforceReadPermission(callingPkg, attributionTag, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800681 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800682 throw new FileNotFoundException("App op not allowed");
683 }
684 }
685 }
686
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800687 private int enforceReadPermission(String callingPkg, @Nullable String attributionTag,
688 Uri uri, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800689 throws SecurityException {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800690 final int mode = enforceReadPermissionInner(uri, callingPkg, attributionTag,
691 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700692 if (mode != MODE_ALLOWED) {
693 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800694 }
Svet Ganov99b60432015-06-27 13:15:22 -0700695
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800696 return noteProxyOp(callingPkg, attributionTag, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800697 }
698
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800699 private int enforceWritePermission(String callingPkg, String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700700 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800701 throws SecurityException {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800702 final int mode = enforceWritePermissionInner(uri, callingPkg, attributionTag,
703 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700704 if (mode != MODE_ALLOWED) {
705 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800706 }
Svet Ganov99b60432015-06-27 13:15:22 -0700707
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800708 return noteProxyOp(callingPkg, attributionTag, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700709 }
710
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800711 private int noteProxyOp(String callingPkg, String attributionTag, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700712 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700713 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800714 attributionTag, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700715 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700716 }
717
Dianne Hackborn35654b62013-01-14 17:38:02 -0800718 return AppOpsManager.MODE_ALLOWED;
719 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700720 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800721
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100722 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700723 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
724 return true;
725 }
726 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
727 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100728 == PERMISSION_GRANTED;
729 }
730
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700731 /**
732 * Verify that calling app holds both the given permission and any app-op
733 * associated with that permission.
734 */
735 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800736 @Nullable String attributionTag, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700737 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
738 callerToken) != PERMISSION_GRANTED) {
739 return MODE_ERRORED;
740 }
741
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800742 return mTransport.noteProxyOp(callingPkg, attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700743 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700744 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700745
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700746 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700747 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800748 @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700749 final Context context = getContext();
750 final int pid = Binder.getCallingPid();
751 final int uid = Binder.getCallingUid();
752 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700753 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700754
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700755 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700756 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700757 }
758
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100759 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700760 final String componentPerm = getReadPermission();
761 if (componentPerm != null) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800762 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700763 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700764 if (mode == MODE_ALLOWED) {
765 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700766 } else {
767 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700768 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700769 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700770 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700771
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700772 // track if unprotected read is allowed; any denied
773 // <path-permission> below removes this ability
774 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700775
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700776 final PathPermission[] pps = getPathPermissions();
777 if (pps != null) {
778 final String path = uri.getPath();
779 for (PathPermission pp : pps) {
780 final String pathPerm = pp.getReadPermission();
781 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800782 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
783 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700784 if (mode == MODE_ALLOWED) {
785 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700786 } else {
787 // any denied <path-permission> means we lose
788 // default <provider> access.
789 allowDefaultRead = false;
790 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700791 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700792 }
793 }
794 }
795 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700796
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700797 // if we passed <path-permission> checks above, and no default
798 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700799 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700801
802 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800803 final int callingUserId = UserHandle.getUserId(uid);
804 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
805 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800806 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
807 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700808 return MODE_ALLOWED;
809 }
810
811 // If the worst denial we found above was ignored, then pass that
812 // ignored through; otherwise we assume it should be a real error below.
813 if (strongestMode == MODE_IGNORED) {
814 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700815 }
816
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600817 final String suffix;
818 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
819 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
820 } else if (mExported) {
821 suffix = " requires " + missingPerm + ", or grantUriPermission()";
822 } else {
823 suffix = " requires the provider be exported, or grantUriPermission()";
824 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700825 throw new SecurityException("Permission Denial: reading "
826 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600827 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700828 }
829
830 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700831 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800832 @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700833 final Context context = getContext();
834 final int pid = Binder.getCallingPid();
835 final int uid = Binder.getCallingUid();
836 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700837 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700838
839 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700840 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700841 }
842
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100843 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700844 final String componentPerm = getWritePermission();
845 if (componentPerm != null) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800846 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg,
847 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700848 if (mode == MODE_ALLOWED) {
849 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700850 } else {
851 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700852 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700853 }
854 }
855
856 // track if unprotected write is allowed; any denied
857 // <path-permission> below removes this ability
858 boolean allowDefaultWrite = (componentPerm == null);
859
860 final PathPermission[] pps = getPathPermissions();
861 if (pps != null) {
862 final String path = uri.getPath();
863 for (PathPermission pp : pps) {
864 final String pathPerm = pp.getWritePermission();
865 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800866 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
867 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700868 if (mode == MODE_ALLOWED) {
869 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700870 } else {
871 // any denied <path-permission> means we lose
872 // default <provider> access.
873 allowDefaultWrite = false;
874 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700875 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700876 }
877 }
878 }
879 }
880
881 // if we passed <path-permission> checks above, and no default
882 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700883 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700884 }
885
886 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800887 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
888 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700889 return MODE_ALLOWED;
890 }
891
892 // If the worst denial we found above was ignored, then pass that
893 // ignored through; otherwise we assume it should be a real error below.
894 if (strongestMode == MODE_IGNORED) {
895 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700896 }
897
898 final String failReason = mExported
899 ? " requires " + missingPerm + ", or grantUriPermission()"
900 : " requires the provider be exported, or grantUriPermission()";
901 throw new SecurityException("Permission Denial: writing "
902 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
903 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 }
905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700907 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800908 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 * constructor.
910 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700911 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 return mContext;
913 }
914
915 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700916 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
917 * after {@link #onCreate}. When called before context was created, an IllegalStateException
918 * will be thrown.
919 * <p>
920 * Note A provider must be declared in the manifest and created automatically by the system,
921 * and context is only available after {@link #onCreate} is called.
922 */
923 @NonNull
924 public final Context requireContext() {
925 final Context ctx = getContext();
926 if (ctx == null) {
927 throw new IllegalStateException("Cannot find context from the provider.");
928 }
929 return ctx;
930 }
931
932 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700933 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700934 * which can be used later to restore the previous state.
935 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700936 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
937 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700938 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600939 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700940 return original;
941 }
942
943 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700944 * Return the package name of the caller that initiated the request being
945 * processed on the current thread. The returned package will have been
946 * verified to belong to the calling UID. Returns {@code null} if not
947 * currently processing a request.
948 * <p>
949 * This will always return {@code null} when processing
950 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
951 *
952 * @see Binder#getCallingUid()
953 * @see Context#grantUriPermission(String, Uri, int)
954 * @throws SecurityException if the calling package doesn't belong to the
955 * calling UID.
956 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700957 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700958 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700959 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700960 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
961 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700962 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700963
964 return null;
965 }
966
967 /**
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800968 * Return the attribution tag of the caller that initiated the request being
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700969 * processed on the current thread. Returns {@code null} if not currently processing
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800970 * a request of the request is for the default attribution.
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700971 * <p>
972 * This will always return {@code null} when processing
973 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
974 *
975 * @see #getCallingPackage
976 */
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800977 public final @Nullable String getCallingAttributionTag() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700978 final Pair<String, String> pkg = mCallingPackage.get();
979 if (pkg != null) {
980 return pkg.second;
981 }
982
983 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700984 }
985
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700986 /**
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800987 * @removed
988 */
989 @Deprecated
990 public final @Nullable String getCallingFeatureId() {
991 return getCallingAttributionTag();
992 }
993
994 /**
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700995 * Return the package name of the caller that initiated the request being
996 * processed on the current thread. The returned package will have
997 * <em>not</em> been verified to belong to the calling UID. Returns
998 * {@code null} if not currently processing a request.
999 * <p>
1000 * This will always return {@code null} when processing
1001 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
1002 *
1003 * @see Binder#getCallingUid()
1004 * @see Context#grantUriPermission(String, Uri, int)
1005 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001006 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001007 final Pair<String, String> pkg = mCallingPackage.get();
1008 if (pkg != null) {
1009 return pkg.first;
1010 }
1011
1012 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001013 }
1014
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001015 /**
1016 * Called whenever the value of {@link #getCallingPackage()} changes, giving
1017 * the provider an opportunity to invalidate any security related caching it
1018 * may be performing.
1019 * <p>
1020 * This typically happens when a {@link ContentProvider} makes a nested call
1021 * back into itself when already processing a call from a remote process.
1022 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001023 public void onCallingPackageChanged() {
1024 }
1025
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001026 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001027 * Opaque token representing the identity of an incoming IPC.
1028 */
1029 public final class CallingIdentity {
1030 /** {@hide} */
1031 public final long binderToken;
1032 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001033 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001034
1035 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001036 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001037 this.binderToken = binderToken;
1038 this.callingPackage = callingPackage;
1039 }
1040 }
1041
1042 /**
1043 * Reset the identity of the incoming IPC on the current thread.
1044 * <p>
1045 * Internally this calls {@link Binder#clearCallingIdentity()} and also
1046 * clears any value stored in {@link #getCallingPackage()}.
1047 *
1048 * @return Returns an opaque token that can be used to restore the original
1049 * calling identity by passing it to
1050 * {@link #restoreCallingIdentity}.
1051 */
1052 public final @NonNull CallingIdentity clearCallingIdentity() {
1053 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
1054 }
1055
1056 /**
1057 * Restore the identity of the incoming IPC on the current thread back to a
1058 * previously identity that was returned by {@link #clearCallingIdentity}.
1059 * <p>
1060 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
1061 * also restores any value stored in {@link #getCallingPackage()}.
1062 */
1063 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
1064 Binder.restoreCallingIdentity(identity.binderToken);
1065 mCallingPackage.set(identity.callingPackage);
1066 }
1067
1068 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001069 * Change the authorities of the ContentProvider.
1070 * This is normally set for you from its manifest information when the provider is first
1071 * created.
1072 * @hide
1073 * @param authorities the semi-colon separated authorities of the ContentProvider.
1074 */
1075 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001076 if (authorities != null) {
1077 if (authorities.indexOf(';') == -1) {
1078 mAuthority = authorities;
1079 mAuthorities = null;
1080 } else {
1081 mAuthority = null;
1082 mAuthorities = authorities.split(";");
1083 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001084 }
1085 }
1086
1087 /** @hide */
1088 protected final boolean matchesOurAuthorities(String authority) {
1089 if (mAuthority != null) {
1090 return mAuthority.equals(authority);
1091 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001092 if (mAuthorities != null) {
1093 int length = mAuthorities.length;
1094 for (int i = 0; i < length; i++) {
1095 if (mAuthorities[i].equals(authority)) return true;
1096 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001097 }
1098 return false;
1099 }
1100
1101
1102 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 * Change the permission required to read data from the content
1104 * provider. This is normally set for you from its manifest information
1105 * when the provider is first created.
1106 *
1107 * @param permission Name of the permission required for read-only access.
1108 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001109 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 mReadPermission = permission;
1111 }
1112
1113 /**
1114 * Return the name of the permission required for read-only access to
1115 * this content provider. This method can be called from multiple
1116 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001117 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1118 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001120 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return mReadPermission;
1122 }
1123
1124 /**
1125 * Change the permission required to read and write data in the content
1126 * provider. This is normally set for you from its manifest information
1127 * when the provider is first created.
1128 *
1129 * @param permission Name of the permission required for read/write access.
1130 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001131 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 mWritePermission = permission;
1133 }
1134
1135 /**
1136 * Return the name of the permission required for read/write access to
1137 * this content provider. This method can be called from multiple
1138 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001139 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1140 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001142 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 return mWritePermission;
1144 }
1145
1146 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001147 * Change the path-based permission required to read and/or write data in
1148 * the content provider. This is normally set for you from its manifest
1149 * information when the provider is first created.
1150 *
1151 * @param permissions Array of path permission descriptions.
1152 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001153 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001154 mPathPermissions = permissions;
1155 }
1156
1157 /**
1158 * Return the path-based permissions required for read and/or write access to
1159 * this content provider. This method can be called from multiple
1160 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001161 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1162 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001163 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001164 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001165 return mPathPermissions;
1166 }
1167
Dianne Hackborn35654b62013-01-14 17:38:02 -08001168 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001169 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001170 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001171 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001172 mTransport.mReadOp = readOp;
1173 mTransport.mWriteOp = writeOp;
1174 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001175 }
1176
Dianne Hackborn961321f2013-02-05 17:22:41 -08001177 /** @hide */
1178 public AppOpsManager getAppOpsManager() {
1179 return mTransport.mAppOpsManager;
1180 }
1181
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001182 /** @hide */
1183 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001184 if (mTransport == null) {
1185 return;
1186 }
1187 if (enabled) {
1188 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1189 } else {
1190 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001191 }
1192 }
1193
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001194 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001195 * Implement this to initialize your content provider on startup.
1196 * This method is called for all registered content providers on the
1197 * application main thread at application launch time. It must not perform
1198 * lengthy operations, or application startup will be delayed.
1199 *
1200 * <p>You should defer nontrivial initialization (such as opening,
1201 * upgrading, and scanning databases) until the content provider is used
1202 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1203 * keeps application startup fast, avoids unnecessary work if the provider
1204 * turns out not to be needed, and stops database errors (such as a full
1205 * disk) from halting application launch.
1206 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001207 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001208 * is a helpful utility class that makes it easy to manage databases,
1209 * and will automatically defer opening until first use. If you do use
1210 * SQLiteOpenHelper, make sure to avoid calling
1211 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1212 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1213 * from this method. (Instead, override
1214 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1215 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 *
1217 * @return true if the provider was successfully loaded, false otherwise
1218 */
1219 public abstract boolean onCreate();
1220
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001221 /**
1222 * {@inheritDoc}
1223 * This method is always called on the application main thread, and must
1224 * not perform lengthy operations.
1225 *
1226 * <p>The default content provider implementation does nothing.
1227 * Override this method to take appropriate action.
1228 * (Content providers do not usually care about things like screen
1229 * orientation, but may want to know about locale changes.)
1230 */
Steve McKayea93fe72016-12-02 11:35:35 -08001231 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 public void onConfigurationChanged(Configuration newConfig) {
1233 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001234
1235 /**
1236 * {@inheritDoc}
1237 * This method is always called on the application main thread, and must
1238 * not perform lengthy operations.
1239 *
1240 * <p>The default content provider implementation does nothing.
1241 * Subclasses may override this method to take appropriate action.
1242 */
Steve McKayea93fe72016-12-02 11:35:35 -08001243 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 public void onLowMemory() {
1245 }
1246
Steve McKayea93fe72016-12-02 11:35:35 -08001247 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001248 public void onTrimMemory(int level) {
1249 }
1250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001252 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001253 *
1254 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1255 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1256 * implementation of this method.
1257 *
1258 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001259 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1260 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 * <p>
1262 * Example client call:<p>
1263 * <pre>// Request a specific record.
1264 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001265 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 projection, // Which columns to return.
1267 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001268 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 People.NAME + " ASC"); // Sort order.</pre>
1270 * Example implementation:<p>
1271 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1272 // proper SQL syntax for us.
1273 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1274
1275 // Set the table we're querying.
1276 qBuilder.setTables(DATABASE_TABLE_NAME);
1277
1278 // If the query ends in a specific record number, we're
1279 // being asked for a specific record, so set the
1280 // WHERE clause in our query.
1281 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1282 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1283 }
1284
1285 // Make the query.
1286 Cursor c = qBuilder.query(mDb,
1287 projection,
1288 selection,
1289 selectionArgs,
1290 groupBy,
1291 having,
1292 sortOrder);
1293 c.setNotificationUri(getContext().getContentResolver(), uri);
1294 return c;</pre>
1295 *
1296 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001297 * if the client is requesting a specific record, the URI will end in a record number
1298 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1299 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001301 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001303 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001304 * @param selectionArgs You may include ?s in selection, which will be replaced by
1305 * the values from selectionArgs, in order that they appear in the selection.
1306 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001308 * If {@code null} then the provider is free to define the sort order.
1309 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001311 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1312 @Nullable String selection, @Nullable String[] selectionArgs,
1313 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314
Fred Quintana5bba6322009-10-05 14:21:12 -07001315 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001316 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001317 *
1318 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1319 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1320 *
1321 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001322 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1323 * and Threads</a>.
1324 * <p>
1325 * Example client call:<p>
1326 * <pre>// Request a specific record.
1327 * Cursor managedCursor = managedQuery(
1328 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1329 projection, // Which columns to return.
1330 null, // WHERE clause.
1331 null, // WHERE clause value substitution
1332 People.NAME + " ASC"); // Sort order.</pre>
1333 * Example implementation:<p>
1334 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1335 // proper SQL syntax for us.
1336 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1337
1338 // Set the table we're querying.
1339 qBuilder.setTables(DATABASE_TABLE_NAME);
1340
1341 // If the query ends in a specific record number, we're
1342 // being asked for a specific record, so set the
1343 // WHERE clause in our query.
1344 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1345 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1346 }
1347
1348 // Make the query.
1349 Cursor c = qBuilder.query(mDb,
1350 projection,
1351 selection,
1352 selectionArgs,
1353 groupBy,
1354 having,
1355 sortOrder);
1356 c.setNotificationUri(getContext().getContentResolver(), uri);
1357 return c;</pre>
1358 * <p>
1359 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001360 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1361 * signal to ensure correct operation on older versions of the Android Framework in
1362 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001363 *
1364 * @param uri The URI to query. This will be the full URI sent by the client;
1365 * if the client is requesting a specific record, the URI will end in a record number
1366 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1367 * that _id value.
1368 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001369 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001370 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001371 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001372 * @param selectionArgs You may include ?s in selection, which will be replaced by
1373 * the values from selectionArgs, in order that they appear in the selection.
1374 * The values will be bound as Strings.
1375 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001376 * If {@code null} then the provider is free to define the sort order.
1377 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001378 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001379 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001380 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001381 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001382 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1383 @Nullable String selection, @Nullable String[] selectionArgs,
1384 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001385 return query(uri, projection, selection, selectionArgs, sortOrder);
1386 }
1387
1388 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001389 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1390 * Arguments may include traditional SQL style query arguments. When present these
1391 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001392 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001393 *
1394 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001395 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1396 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1397 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001398 *
Steve McKay76b27702017-04-24 12:07:53 -07001399 * <p>This method can be called from multiple threads, as described in
1400 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1401 * and Threads</a>.
1402 *
1403 * <p>
1404 * Example client call:<p>
1405 * <pre>// Request 20 records starting at row index 30.
1406 Bundle queryArgs = new Bundle();
1407 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1408 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1409
1410 Cursor cursor = getContentResolver().query(
1411 contentUri, // Content Uri is specific to individual content providers.
1412 projection, // String[] describing which columns to return.
1413 queryArgs, // Query arguments.
1414 null); // Cancellation signal.</pre>
1415 *
1416 * Example implementation:<p>
1417 * <pre>
1418
1419 int recordsetSize = 0x1000; // Actual value is implementation specific.
1420 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1421
1422 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1423 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1424
1425 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1426
1427 // Calculate the number of items to include in the cursor.
1428 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1429
1430 // Build the paged result set....
1431 for (int i = offset; i < offset + numItems; i++) {
1432 // populate row from your data.
1433 }
1434
1435 Bundle extras = new Bundle();
1436 c.setExtras(extras);
1437
1438 // Any QUERY_ARG_* key may be included if honored.
1439 // In an actual implementation, include only keys that are both present in queryArgs
1440 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1441 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1442 // then QUERY_ARG_OFFSET should be omitted.
1443 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1444 ContentResolver.QUERY_ARG_OFFSET,
1445 ContentResolver.QUERY_ARG_LIMIT
1446 });
1447
1448 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1449
1450 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1451
1452 return cursor;</pre>
1453 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001454 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1455 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001456 *
1457 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001458 * @param projection The list of columns to put into the cursor.
1459 * If {@code null} provide a default set of columns.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001460 * @param queryArgs A Bundle containing additional information necessary for
1461 * the operation. Arguments may include SQL style arguments, such
1462 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1463 * the documentation for each individual provider will indicate
1464 * which arguments they support.
Steve McKayea93fe72016-12-02 11:35:35 -08001465 * @param cancellationSignal A signal to cancel the operation in progress,
1466 * or {@code null}.
1467 * @return a Cursor or {@code null}.
1468 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001469 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001470 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1471 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1472 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001473
Steve McKayd7ece9f2017-01-12 16:59:59 -08001474 // if client doesn't supply an SQL sort order argument, attempt to build one from
1475 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001476 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001477 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1478 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1479 }
1480
Steve McKayea93fe72016-12-02 11:35:35 -08001481 return query(
1482 uri,
1483 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001484 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1485 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1486 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001487 cancellationSignal);
1488 }
1489
1490 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001491 * Implement this to handle requests for the MIME type of the data at the
1492 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 * <code>vnd.android.cursor.item</code> for a single record,
1494 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001495 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001496 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1497 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001499 * <p>Note that there are no permissions needed for an application to
1500 * access this information; if your content provider requires read and/or
1501 * write permissions, or is not exported, all applications can still call
1502 * this method regardless of their access permissions. This allows them
1503 * to retrieve the MIME type for a URI when dispatching intents.
1504 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001506 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001508 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001509 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
1511 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001512 * Implement this to support canonicalization of URIs that refer to your
1513 * content provider. A canonical URI is one that can be transported across
1514 * devices, backup/restore, and other contexts, and still be able to refer
1515 * to the same data item. Typically this is implemented by adding query
1516 * params to the URI allowing the content provider to verify that an incoming
1517 * canonical URI references the same data as it was originally intended for and,
1518 * if it doesn't, to find that data (if it exists) in the current environment.
1519 *
1520 * <p>For example, if the content provider holds people and a normal URI in it
1521 * is created with a row index into that people database, the cananical representation
1522 * may have an additional query param at the end which specifies the name of the
1523 * person it is intended for. Later calls into the provider with that URI will look
1524 * up the row of that URI's base index and, if it doesn't match or its entry's
1525 * name doesn't match the name in the query param, perform a query on its database
1526 * to find the correct row to operate on.</p>
1527 *
1528 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1529 * URIs (including this one) must perform this verification and recovery of any
1530 * canonical URIs they receive. In addition, you must also implement
1531 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1532 *
1533 * <p>The default implementation of this method returns null, indicating that
1534 * canonical URIs are not supported.</p>
1535 *
1536 * @param url The Uri to canonicalize.
1537 *
1538 * @return Return the canonical representation of <var>url</var>, or null if
1539 * canonicalization of that Uri is not supported.
1540 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001541 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001542 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001543 return null;
1544 }
1545
1546 /**
1547 * Remove canonicalization from canonical URIs previously returned by
1548 * {@link #canonicalize}. For example, if your implementation is to add
1549 * a query param to canonicalize a URI, this method can simply trip any
1550 * query params on the URI. The default implementation always returns the
1551 * same <var>url</var> that was passed in.
1552 *
1553 * @param url The Uri to remove any canonicalization from.
1554 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001555 * @return Return the non-canonical representation of <var>url</var>, return
1556 * the <var>url</var> as-is if there is nothing to do, or return null if
1557 * the data identified by the canonical representation can not be found in
1558 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001559 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001560 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001561 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001562 return url;
1563 }
1564
1565 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001566 * Implement this to support refresh of content identified by {@code uri}.
1567 * By default, this method returns false; providers who wish to implement
1568 * this should return true to signal the client that the provider has tried
1569 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001570 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001571 * This allows clients to request an explicit refresh of content identified
1572 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001573 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001574 * Client code should only invoke this method when there is a strong
1575 * indication (such as a user initiated pull to refresh gesture) that the
1576 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001577 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001578 * Remember to send
1579 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001580 * notifications when content changes.
1581 *
1582 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001583 * @param extras Additional options from the client. The definitions of
1584 * these are specific to the content provider being called.
1585 * @param cancellationSignal A signal to cancel the operation in progress,
1586 * or {@code null} if none. For example, if you called refresh on
1587 * a particular uri, you should call
1588 * {@link CancellationSignal#throwIfCanceled()} to check whether
1589 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001590 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001591 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001592 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001593 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001594 @Nullable CancellationSignal cancellationSignal) {
1595 return false;
1596 }
1597
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001598 /**
1599 * Perform a detailed internal check on a {@link Uri} to determine if a UID
1600 * is able to access it with specific mode flags.
1601 * <p>
1602 * This method is typically used when the provider implements more dynamic
1603 * access controls that cannot be expressed with {@code <path-permission>}
1604 * style static rules.
1605 *
1606 * @param uri the {@link Uri} to perform an access check on.
1607 * @param uid the UID to check the permission for.
1608 * @param modeFlags the access flags to use for the access check, such as
1609 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}.
1610 * @return {@link PackageManager#PERMISSION_GRANTED} if access is allowed,
1611 * otherwise {@link PackageManager#PERMISSION_DENIED}.
1612 * @hide
1613 */
Jeff Sharkey9edef252019-05-20 14:00:17 -06001614 @Override
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001615 @SystemApi
Jeff Sharkey9edef252019-05-20 14:00:17 -06001616 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1617 return PackageManager.PERMISSION_DENIED;
1618 }
1619
Ben Lin1cf454f2016-11-10 13:50:54 -08001620 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001621 * @hide
1622 * Implementation when a caller has performed an insert on the content
1623 * provider, but that call has been rejected for the operation given
1624 * to {@link #setAppOps(int, int)}. The default implementation simply
1625 * returns a dummy URI that is the base URI with a 0 path element
1626 * appended.
1627 */
1628 public Uri rejectInsert(Uri uri, ContentValues values) {
1629 // If not allowed, we need to return some reasonable URI. Maybe the
1630 // content provider should be responsible for this, but for now we
1631 // will just return the base URI with a dummy '0' tagged on to it.
1632 // You shouldn't be able to read if you can't write, anyway, so it
1633 // shouldn't matter much what is returned.
1634 return uri.buildUpon().appendPath("0").build();
1635 }
1636
1637 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001638 * Implement this to handle requests to insert a new row. As a courtesy,
1639 * call
1640 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1641 * notifyChange()} after inserting. This method can be called from multiple
1642 * threads, as described in <a href="
1643 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001644 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001645 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001646 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 * @param values A set of column_name/value pairs to add to the database.
1648 * @return The URI for the newly inserted item.
1649 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001650 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651
1652 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001653 * Implement this to handle requests to insert a new row. As a courtesy,
1654 * call
1655 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1656 * notifyChange()} after inserting. This method can be called from multiple
1657 * threads, as described in <a href="
1658 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1659 * and Threads</a>.
1660 *
1661 * @param uri The content:// URI of the insertion request.
1662 * @param values A set of column_name/value pairs to add to the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001663 * @param extras A Bundle containing additional information necessary for
1664 * the operation. Arguments may include SQL style arguments, such
1665 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1666 * the documentation for each individual provider will indicate
1667 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001668 * @return The URI for the newly inserted item.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001669 * @throws IllegalArgumentException if the provider doesn't support one of
1670 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001671 */
1672 @Override
1673 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1674 @Nullable Bundle extras) {
1675 return insert(uri, values);
1676 }
1677
1678 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001679 * Override this to handle requests to insert a set of new rows, or the
1680 * default implementation will iterate over the values and call
1681 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1683 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001684 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001685 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1686 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 *
1688 * @param uri The content:// URI of the insertion request.
1689 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001690 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 * @return The number of values that were inserted.
1692 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001693 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001694 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 int numValues = values.length;
1696 for (int i = 0; i < numValues; i++) {
1697 insert(uri, values[i]);
1698 }
1699 return numValues;
1700 }
1701
1702 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001703 * Implement this to handle requests to delete one or more rows. The
1704 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001705 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001706 * As a courtesy, call
1707 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1708 * notifyChange()} after deleting. This method can be called from multiple
1709 * threads, as described in <a href="
1710 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001711 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001712 * <p>
1713 * The implementation is responsible for parsing out a row ID at the end of
1714 * the URI, if a specific row is being deleted. That is, the client would
1715 * pass in <code>content://contacts/people/22</code> and the implementation
1716 * is responsible for parsing the record number (22) when creating a SQL
1717 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001719 * @param uri The full URI to query, including a row ID (if a specific
1720 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 * @param selection An optional restriction to apply to rows when deleting.
1722 * @return The number of rows affected.
1723 * @throws SQLException
1724 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001725 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1726 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727
1728 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001729 * Implement this to handle requests to delete one or more rows. The
1730 * implementation should apply the selection clause when performing
1731 * deletion, allowing the operation to affect multiple rows in a directory.
1732 * As a courtesy, call
1733 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1734 * notifyChange()} after deleting. This method can be called from multiple
1735 * threads, as described in <a href="
1736 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1737 * and Threads</a>.
1738 * <p>
1739 * The implementation is responsible for parsing out a row ID at the end of
1740 * the URI, if a specific row is being deleted. That is, the client would
1741 * pass in <code>content://contacts/people/22</code> and the implementation
1742 * is responsible for parsing the record number (22) when creating a SQL
1743 * statement.
1744 *
1745 * @param uri The full URI to query, including a row ID (if a specific
1746 * record is requested).
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001747 * @param extras A Bundle containing additional information necessary for
1748 * the operation. Arguments may include SQL style arguments, such
1749 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1750 * the documentation for each individual provider will indicate
1751 * which arguments they support.
1752 * @throws IllegalArgumentException if the provider doesn't support one of
1753 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001754 * @throws SQLException
1755 */
1756 @Override
1757 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1758 extras = (extras != null) ? extras : Bundle.EMPTY;
1759 return delete(uri,
1760 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1761 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1762 }
1763
1764 /**
1765 * Implement this to handle requests to update one or more rows. The
1766 * implementation should update all rows matching the selection to set the
1767 * columns according to the provided values map. As a courtesy, call
1768 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1769 * notifyChange()} after updating. This method can be called from multiple
1770 * threads, as described in <a href="
1771 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001772 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001774 * @param uri The URI to query. This can potentially have a record ID if
1775 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001776 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 * @param selection An optional filter to match rows to update.
1778 * @return the number of rows affected.
1779 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001780 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001781 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782
1783 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001784 * Implement this to handle requests to update one or more rows. The
1785 * implementation should update all rows matching the selection to set the
1786 * columns according to the provided values map. As a courtesy, call
1787 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1788 * notifyChange()} after updating. This method can be called from multiple
1789 * threads, as described in <a href="
1790 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1791 * and Threads</a>.
1792 *
1793 * @param uri The URI to query. This can potentially have a record ID if
1794 * this is an update request for a specific record.
1795 * @param values A set of column_name/value pairs to update in the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001796 * @param extras A Bundle containing additional information necessary for
1797 * the operation. Arguments may include SQL style arguments, such
1798 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1799 * the documentation for each individual provider will indicate
1800 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001801 * @return the number of rows affected.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001802 * @throws IllegalArgumentException if the provider doesn't support one of
1803 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001804 */
1805 @Override
1806 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1807 @Nullable Bundle extras) {
1808 extras = (extras != null) ? extras : Bundle.EMPTY;
1809 return update(uri, values,
1810 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1811 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1812 }
1813
1814 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001815 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001816 * The default implementation always throws {@link FileNotFoundException}.
1817 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001818 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1819 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001820 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001821 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1822 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001823 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 *
1825 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1826 * their responsibility to close it when done. That is, the implementation
1827 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001828 * <p>
1829 * If opened with the exclusive "r" or "w" modes, the returned
1830 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1831 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1832 * supports seeking.
1833 * <p>
1834 * If you need to detect when the returned ParcelFileDescriptor has been
1835 * closed, or if the remote process has crashed or encountered some other
1836 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1837 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1838 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1839 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001840 * <p>
1841 * If you need to return a large file that isn't backed by a real file on
1842 * disk, such as a file on a network share or cloud storage service,
1843 * consider using
1844 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1845 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001847 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1848 * to return the appropriate MIME type for the data returned here with
1849 * the same URI. This will allow intent resolution to automatically determine the data MIME
1850 * type and select the appropriate matching targets as part of its operation.</p>
1851 *
1852 * <p class="note">For better interoperability with other applications, it is recommended
1853 * that for any URIs that can be opened, you also support queries on them
1854 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1855 * You may also want to support other common columns if you have additional meta-data
1856 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1857 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1858 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 * @param uri The URI whose file is to be opened.
1860 * @param mode Access mode for the file. May be "r" for read-only access,
1861 * "rw" for read and write access, or "rwt" for read and write access
1862 * that truncates any existing file.
1863 *
1864 * @return Returns a new ParcelFileDescriptor which you can use to access
1865 * the file.
1866 *
1867 * @throws FileNotFoundException Throws FileNotFoundException if there is
1868 * no file associated with the given URI or the mode is invalid.
1869 * @throws SecurityException Throws SecurityException if the caller does
1870 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001871 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 * @see #openAssetFile(Uri, String)
1873 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001874 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001875 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001876 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001877 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 throws FileNotFoundException {
1879 throw new FileNotFoundException("No files supported by provider at "
1880 + uri);
1881 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001884 * Override this to handle requests to open a file blob.
1885 * The default implementation always throws {@link FileNotFoundException}.
1886 * This method can be called from multiple threads, as described in
1887 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1888 * and Threads</a>.
1889 *
1890 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1891 * to the caller. This way large data (such as images and documents) can be
1892 * returned without copying the content.
1893 *
1894 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1895 * their responsibility to close it when done. That is, the implementation
1896 * of this method should create a new ParcelFileDescriptor for each call.
1897 * <p>
1898 * If opened with the exclusive "r" or "w" modes, the returned
1899 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1900 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1901 * supports seeking.
1902 * <p>
1903 * If you need to detect when the returned ParcelFileDescriptor has been
1904 * closed, or if the remote process has crashed or encountered some other
1905 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1906 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1907 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1908 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1909 *
1910 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1911 * to return the appropriate MIME type for the data returned here with
1912 * the same URI. This will allow intent resolution to automatically determine the data MIME
1913 * type and select the appropriate matching targets as part of its operation.</p>
1914 *
1915 * <p class="note">For better interoperability with other applications, it is recommended
1916 * that for any URIs that can be opened, you also support queries on them
1917 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1918 * You may also want to support other common columns if you have additional meta-data
1919 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1920 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1921 *
1922 * @param uri The URI whose file is to be opened.
1923 * @param mode Access mode for the file. May be "r" for read-only access,
1924 * "w" for write-only access, "rw" for read and write access, or
1925 * "rwt" for read and write access that truncates any existing
1926 * file.
1927 * @param signal A signal to cancel the operation in progress, or
1928 * {@code null} if none. For example, if you are downloading a
1929 * file from the network to service a "rw" mode request, you
1930 * should periodically call
1931 * {@link CancellationSignal#throwIfCanceled()} to check whether
1932 * the client has canceled the request and abort the download.
1933 *
1934 * @return Returns a new ParcelFileDescriptor which you can use to access
1935 * the file.
1936 *
1937 * @throws FileNotFoundException Throws FileNotFoundException if there is
1938 * no file associated with the given URI or the mode is invalid.
1939 * @throws SecurityException Throws SecurityException if the caller does
1940 * not have permission to access the file.
1941 *
1942 * @see #openAssetFile(Uri, String)
1943 * @see #openFileHelper(Uri, String)
1944 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001945 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001946 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001947 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001948 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1949 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001950 return openFile(uri, mode);
1951 }
1952
1953 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 * This is like {@link #openFile}, but can be implemented by providers
1955 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001956 * inside of their .apk.
1957 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001958 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1959 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001960 *
1961 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001962 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001963 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1965 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1966 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001967 * <p>
1968 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1969 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001970 *
1971 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 * should create the AssetFileDescriptor with
1973 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001974 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001976 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1977 * to return the appropriate MIME type for the data returned here with
1978 * the same URI. This will allow intent resolution to automatically determine the data MIME
1979 * type and select the appropriate matching targets as part of its operation.</p>
1980 *
1981 * <p class="note">For better interoperability with other applications, it is recommended
1982 * that for any URIs that can be opened, you also support queries on them
1983 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1984 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 * @param uri The URI whose file is to be opened.
1986 * @param mode Access mode for the file. May be "r" for read-only access,
1987 * "w" for write-only access (erasing whatever data is currently in
1988 * the file), "wa" for write-only access to append to any existing data,
1989 * "rw" for read and write access on any existing data, and "rwt" for read
1990 * and write access that truncates any existing file.
1991 *
1992 * @return Returns a new AssetFileDescriptor which you can use to access
1993 * the file.
1994 *
1995 * @throws FileNotFoundException Throws FileNotFoundException if there is
1996 * no file associated with the given URI or the mode is invalid.
1997 * @throws SecurityException Throws SecurityException if the caller does
1998 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001999 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 * @see #openFile(Uri, String)
2001 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08002002 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002004 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 throws FileNotFoundException {
2006 ParcelFileDescriptor fd = openFile(uri, mode);
2007 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
2008 }
2009
2010 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002011 * This is like {@link #openFile}, but can be implemented by providers
2012 * that need to be able to return sub-sections of files, often assets
2013 * inside of their .apk.
2014 * This method can be called from multiple threads, as described in
2015 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2016 * and Threads</a>.
2017 *
2018 * <p>If you implement this, your clients must be able to deal with such
2019 * file slices, either directly with
2020 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
2021 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
2022 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
2023 * methods.
2024 * <p>
2025 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2026 * streaming of data.
2027 *
2028 * <p class="note">If you are implementing this to return a full file, you
2029 * should create the AssetFileDescriptor with
2030 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
2031 * applications that cannot handle sub-sections of files.</p>
2032 *
2033 * <p class="note">For use in Intents, you will want to implement {@link #getType}
2034 * to return the appropriate MIME type for the data returned here with
2035 * the same URI. This will allow intent resolution to automatically determine the data MIME
2036 * type and select the appropriate matching targets as part of its operation.</p>
2037 *
2038 * <p class="note">For better interoperability with other applications, it is recommended
2039 * that for any URIs that can be opened, you also support queries on them
2040 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
2041 *
2042 * @param uri The URI whose file is to be opened.
2043 * @param mode Access mode for the file. May be "r" for read-only access,
2044 * "w" for write-only access (erasing whatever data is currently in
2045 * the file), "wa" for write-only access to append to any existing data,
2046 * "rw" for read and write access on any existing data, and "rwt" for read
2047 * and write access that truncates any existing file.
2048 * @param signal A signal to cancel the operation in progress, or
2049 * {@code null} if none. For example, if you are downloading a
2050 * file from the network to service a "rw" mode request, you
2051 * should periodically call
2052 * {@link CancellationSignal#throwIfCanceled()} to check whether
2053 * the client has canceled the request and abort the download.
2054 *
2055 * @return Returns a new AssetFileDescriptor which you can use to access
2056 * the file.
2057 *
2058 * @throws FileNotFoundException Throws FileNotFoundException if there is
2059 * no file associated with the given URI or the mode is invalid.
2060 * @throws SecurityException Throws SecurityException if the caller does
2061 * not have permission to access the file.
2062 *
2063 * @see #openFile(Uri, String)
2064 * @see #openFileHelper(Uri, String)
2065 * @see #getType(android.net.Uri)
2066 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002067 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002068 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
2069 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002070 return openAssetFile(uri, mode);
2071 }
2072
2073 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 * Convenience for subclasses that wish to implement {@link #openFile}
2075 * by looking up a column named "_data" at the given URI.
2076 *
2077 * @param uri The URI to be opened.
2078 * @param mode The file mode. May be "r" for read-only access,
2079 * "w" for write-only access (erasing whatever data is currently in
2080 * the file), "wa" for write-only access to append to any existing data,
2081 * "rw" for read and write access on any existing data, and "rwt" for read
2082 * and write access that truncates any existing file.
2083 *
2084 * @return Returns a new ParcelFileDescriptor that can be used by the
2085 * client to access the file.
2086 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002087 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
2088 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
2090 int count = (c != null) ? c.getCount() : 0;
2091 if (count != 1) {
2092 // If there is not exactly one result, throw an appropriate
2093 // exception.
2094 if (c != null) {
2095 c.close();
2096 }
2097 if (count == 0) {
2098 throw new FileNotFoundException("No entry for " + uri);
2099 }
2100 throw new FileNotFoundException("Multiple items at " + uri);
2101 }
2102
2103 c.moveToFirst();
2104 int i = c.getColumnIndex("_data");
2105 String path = (i >= 0 ? c.getString(i) : null);
2106 c.close();
2107 if (path == null) {
2108 throw new FileNotFoundException("Column _data not found.");
2109 }
2110
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002111 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 return ParcelFileDescriptor.open(new File(path), modeBits);
2113 }
2114
2115 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002116 * Called by a client to determine the types of data streams that this
2117 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002118 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002119 * of a particular type, return that MIME type if it matches the given
2120 * mimeTypeFilter. If it can perform type conversions, return an array
2121 * of all supported MIME types that match mimeTypeFilter.
2122 *
2123 * @param uri The data in the content provider being queried.
2124 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002125 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002126 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002127 * given mimeTypeFilter. Otherwise returns an array of all available
2128 * concrete MIME types.
2129 *
2130 * @see #getType(Uri)
2131 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002132 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002133 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002134 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002135 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002136 return null;
2137 }
2138
2139 /**
2140 * Called by a client to open a read-only stream containing data of a
2141 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2142 * except the file can only be read-only and the content provider may
2143 * perform data conversions to generate data of the desired type.
2144 *
2145 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002146 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002147 * {@link #openAssetFile(Uri, String)}.
2148 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002149 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002150 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002151 * <p>
2152 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2153 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002154 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002155 * <p class="note">For better interoperability with other applications, it is recommended
2156 * that for any URIs that can be opened, you also support queries on them
2157 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2158 * You may also want to support other common columns if you have additional meta-data
2159 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2160 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2161 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002162 * @param uri The data in the content provider being queried.
2163 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002164 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002165 * requirements; in this case the content provider will pick its best
2166 * type matching the pattern.
2167 * @param opts Additional options from the client. The definitions of
2168 * these are specific to the content provider being called.
2169 *
2170 * @return Returns a new AssetFileDescriptor from which the client can
2171 * read data of the desired type.
2172 *
2173 * @throws FileNotFoundException Throws FileNotFoundException if there is
2174 * no file associated with the given URI or the mode is invalid.
2175 * @throws SecurityException Throws SecurityException if the caller does
2176 * not have permission to access the data.
2177 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2178 * content provider does not support the requested MIME type.
2179 *
2180 * @see #getStreamTypes(Uri, String)
2181 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002182 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002183 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002184 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2185 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002186 if ("*/*".equals(mimeTypeFilter)) {
2187 // If they can take anything, the untyped open call is good enough.
2188 return openAssetFile(uri, "r");
2189 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002190 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002191 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002192 // Use old untyped open call if this provider has a type for this
2193 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002194 return openAssetFile(uri, "r");
2195 }
2196 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2197 }
2198
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002199
2200 /**
2201 * Called by a client to open a read-only stream containing data of a
2202 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2203 * except the file can only be read-only and the content provider may
2204 * perform data conversions to generate data of the desired type.
2205 *
2206 * <p>The default implementation compares the given mimeType against the
2207 * result of {@link #getType(Uri)} and, if they match, simply calls
2208 * {@link #openAssetFile(Uri, String)}.
2209 *
2210 * <p>See {@link ClipData} for examples of the use and implementation
2211 * of this method.
2212 * <p>
2213 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2214 * streaming of data.
2215 *
2216 * <p class="note">For better interoperability with other applications, it is recommended
2217 * that for any URIs that can be opened, you also support queries on them
2218 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2219 * You may also want to support other common columns if you have additional meta-data
2220 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2221 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2222 *
2223 * @param uri The data in the content provider being queried.
2224 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002225 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002226 * requirements; in this case the content provider will pick its best
2227 * type matching the pattern.
2228 * @param opts Additional options from the client. The definitions of
2229 * these are specific to the content provider being called.
2230 * @param signal A signal to cancel the operation in progress, or
2231 * {@code null} if none. For example, if you are downloading a
2232 * file from the network to service a "rw" mode request, you
2233 * should periodically call
2234 * {@link CancellationSignal#throwIfCanceled()} to check whether
2235 * the client has canceled the request and abort the download.
2236 *
2237 * @return Returns a new AssetFileDescriptor from which the client can
2238 * read data of the desired type.
2239 *
2240 * @throws FileNotFoundException Throws FileNotFoundException if there is
2241 * no file associated with the given URI or the mode is invalid.
2242 * @throws SecurityException Throws SecurityException if the caller does
2243 * not have permission to access the data.
2244 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2245 * content provider does not support the requested MIME type.
2246 *
2247 * @see #getStreamTypes(Uri, String)
2248 * @see #openAssetFile(Uri, String)
2249 * @see ClipDescription#compareMimeTypes(String, String)
2250 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002251 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002252 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2253 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2254 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002255 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2256 }
2257
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002258 /**
2259 * Interface to write a stream of data to a pipe. Use with
2260 * {@link ContentProvider#openPipeHelper}.
2261 */
2262 public interface PipeDataWriter<T> {
2263 /**
2264 * Called from a background thread to stream data out to a pipe.
2265 * Note that the pipe is blocking, so this thread can block on
2266 * writes for an arbitrary amount of time if the client is slow
2267 * at reading.
2268 *
2269 * @param output The pipe where data should be written. This will be
2270 * closed for you upon returning from this function.
2271 * @param uri The URI whose data is to be written.
2272 * @param mimeType The desired type of data to be written.
2273 * @param opts Options supplied by caller.
2274 * @param args Your own custom arguments.
2275 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002276 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2277 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002278 }
2279
2280 /**
2281 * A helper function for implementing {@link #openTypedAssetFile}, for
2282 * creating a data pipe and background thread allowing you to stream
2283 * generated data back to the client. This function returns a new
2284 * ParcelFileDescriptor that should be returned to the caller (the caller
2285 * is responsible for closing it).
2286 *
2287 * @param uri The URI whose data is to be written.
2288 * @param mimeType The desired type of data to be written.
2289 * @param opts Options supplied by caller.
2290 * @param args Your own custom arguments.
2291 * @param func Interface implementing the function that will actually
2292 * stream the data.
2293 * @return Returns a new ParcelFileDescriptor holding the read side of
2294 * the pipe. This should be returned to the caller for reading; the caller
2295 * is responsible for closing it when done.
2296 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002297 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2298 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2299 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002300 try {
2301 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2302
2303 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2304 @Override
2305 protected Object doInBackground(Object... params) {
2306 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2307 try {
2308 fds[1].close();
2309 } catch (IOException e) {
2310 Log.w(TAG, "Failure closing pipe", e);
2311 }
2312 return null;
2313 }
2314 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002315 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002316
2317 return fds[0];
2318 } catch (IOException e) {
2319 throw new FileNotFoundException("failure making pipe");
2320 }
2321 }
2322
2323 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 * Returns true if this instance is a temporary content provider.
2325 * @return true if this instance is a temporary content provider
2326 */
2327 protected boolean isTemporary() {
2328 return false;
2329 }
2330
2331 /**
2332 * Returns the Binder object for this provider.
2333 *
2334 * @return the Binder object for this provider
2335 * @hide
2336 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002337 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 public IContentProvider getIContentProvider() {
2339 return mTransport;
2340 }
2341
2342 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002343 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2344 * when directly instantiating the provider for testing.
2345 * @hide
2346 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002347 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002348 public void attachInfoForTesting(Context context, ProviderInfo info) {
2349 attachInfo(context, info, true);
2350 }
2351
2352 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 * After being instantiated, this is called to tell the content provider
2354 * about itself.
2355 *
2356 * @param context The context this provider is running in
2357 * @param info Registered information about this content provider
2358 */
2359 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002360 attachInfo(context, info, false);
2361 }
2362
2363 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002364 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002365 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 /*
2368 * Only allow it to be set once, so after the content service gives
2369 * this to us clients can't change it.
2370 */
2371 if (mContext == null) {
2372 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002373 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002374 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2375 Context.APP_OPS_SERVICE);
2376 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002377 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (info != null) {
2379 setReadPermission(info.readPermission);
2380 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002381 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002382 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002383 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002384 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002386 if (Build.IS_DEBUGGABLE) {
2387 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2388 Log.VERBOSE));
2389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 ContentProvider.this.onCreate();
2391 }
2392 }
Fred Quintanace31b232009-05-04 16:01:15 -07002393
2394 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002395 * Override this to handle requests to perform a batch of operations, or the
2396 * default implementation will iterate over the operations and call
2397 * {@link ContentProviderOperation#apply} on each of them.
2398 * If all calls to {@link ContentProviderOperation#apply} succeed
2399 * then a {@link ContentProviderResult} array with as many
2400 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002401 * fail, it is up to the implementation how many of the others take effect.
2402 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002403 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2404 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002405 *
Fred Quintanace31b232009-05-04 16:01:15 -07002406 * @param operations the operations to apply
2407 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002408 * @throws OperationApplicationException thrown if any operation fails.
2409 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002410 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002411 @Override
2412 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2413 @NonNull ArrayList<ContentProviderOperation> operations)
2414 throws OperationApplicationException {
2415 return applyBatch(operations);
2416 }
2417
Jeff Sharkey673db442015-06-11 19:30:57 -07002418 public @NonNull ContentProviderResult[] applyBatch(
2419 @NonNull ArrayList<ContentProviderOperation> operations)
2420 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002421 final int numOperations = operations.size();
2422 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2423 for (int i = 0; i < numOperations; i++) {
2424 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002425 }
2426 return results;
2427 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002428
2429 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002430 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002431 * interfaces that are cheaper and/or unnatural for a table-like
2432 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002433 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002434 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2435 * on this entry into the content provider besides the basic ability for the application
2436 * to get access to the provider at all. For example, it has no idea whether the call
2437 * being executed may read or write data in the provider, so can't enforce those
2438 * individual permissions. Any implementation of this method <strong>must</strong>
2439 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2440 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002441 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2442 * @param arg provider-defined String argument. May be {@code null}.
2443 * @param extras provider-defined Bundle argument. May be {@code null}.
2444 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002445 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002446 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002447 @Override
2448 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2449 @Nullable String arg, @Nullable Bundle extras) {
2450 return call(method, arg, extras);
2451 }
2452
Jeff Sharkey673db442015-06-11 19:30:57 -07002453 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2454 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002455 return null;
2456 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002457
2458 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002459 * Implement this to shut down the ContentProvider instance. You can then
2460 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002461 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002462 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002463 * Android normally handles ContentProvider startup and shutdown
2464 * automatically. You do not need to start up or shut down a
2465 * ContentProvider. When you invoke a test method on a ContentProvider,
2466 * however, a ContentProvider instance is started and keeps running after
2467 * the test finishes, even if a succeeding test instantiates another
2468 * ContentProvider. A conflict develops because the two instances are
2469 * usually running against the same underlying data source (for example, an
2470 * sqlite database).
2471 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002472 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002473 * Implementing shutDown() avoids this conflict by providing a way to
2474 * terminate the ContentProvider. This method can also prevent memory leaks
2475 * from multiple instantiations of the ContentProvider, and it can ensure
2476 * unit test isolation by allowing you to completely clean up the test
2477 * fixture before moving on to the next test.
2478 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002479 */
2480 public void shutdown() {
2481 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2482 "connections are gracefully shutdown");
2483 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002484
2485 /**
2486 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002487 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002488 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002489 * @param fd The raw file descriptor that the dump is being sent to.
2490 * @param writer The PrintWriter to which you should dump your state. This will be
2491 * closed for you after you return.
2492 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002493 */
2494 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2495 writer.println("nothing to dump");
2496 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002497
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002498 private void validateIncomingAuthority(String authority) throws SecurityException {
2499 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2500 String message = "The authority " + authority + " does not match the one of the "
2501 + "contentProvider: ";
2502 if (mAuthority != null) {
2503 message += mAuthority;
2504 } else {
2505 message += Arrays.toString(mAuthorities);
2506 }
2507 throw new SecurityException(message);
2508 }
2509 }
2510
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002511 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002512 @VisibleForTesting
2513 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002514 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002515 if (!mSingleUser) {
2516 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2517 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2518 throw new SecurityException("trying to query a ContentProvider in user "
2519 + mContext.getUserId() + " with a uri belonging to user " + userId);
2520 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002521 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002522 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002523
2524 // Normalize the path by removing any empty path segments, which can be
2525 // a source of security issues.
2526 final String encodedPath = uri.getEncodedPath();
2527 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002528 final Uri normalized = uri.buildUpon()
2529 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2530 Log.w(TAG, "Normalized " + uri + " to " + normalized
2531 + " to avoid possible security issues");
2532 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002533 } else {
2534 return uri;
2535 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002536 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002537
2538 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002539 private Uri maybeGetUriWithoutUserId(Uri uri) {
2540 if (mSingleUser) {
2541 return uri;
2542 }
2543 return getUriWithoutUserId(uri);
2544 }
2545
2546 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002547 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2548 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002549 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002550 if (end == -1) return defaultUserId;
2551 String userIdString = auth.substring(0, end);
2552 try {
2553 return Integer.parseInt(userIdString);
2554 } catch (NumberFormatException e) {
2555 Log.w(TAG, "Error parsing userId.", e);
2556 return UserHandle.USER_NULL;
2557 }
2558 }
2559
2560 /** @hide */
2561 public static int getUserIdFromAuthority(String auth) {
2562 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2563 }
2564
2565 /** @hide */
2566 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2567 if (uri == null) return defaultUserId;
2568 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2569 }
2570
2571 /** @hide */
2572 public static int getUserIdFromUri(Uri uri) {
2573 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2574 }
2575
2576 /**
Alex Kershawba014ac2020-01-20 22:25:02 +00002577 * Returns the user associated with the given URI.
2578 *
2579 * @hide
2580 */
2581 @TestApi
2582 public @NonNull static UserHandle getUserHandleFromUri(@NonNull Uri uri) {
2583 return UserHandle.of(getUserIdFromUri(uri, Process.myUserHandle().getIdentifier()));
2584 }
2585
2586 /**
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002587 * Removes userId part from authority string. Expects format:
2588 * userId@some.authority
2589 * If there is no userId in the authority, it symply returns the argument
2590 * @hide
2591 */
2592 public static String getAuthorityWithoutUserId(String auth) {
2593 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002594 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002595 return auth.substring(end+1);
2596 }
2597
2598 /** @hide */
2599 public static Uri getUriWithoutUserId(Uri uri) {
2600 if (uri == null) return null;
2601 Uri.Builder builder = uri.buildUpon();
2602 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2603 return builder.build();
2604 }
2605
2606 /** @hide */
2607 public static boolean uriHasUserId(Uri uri) {
2608 if (uri == null) return false;
2609 return !TextUtils.isEmpty(uri.getUserInfo());
2610 }
2611
2612 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002613 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002614 public static Uri maybeAddUserId(Uri uri, int userId) {
2615 if (uri == null) return null;
2616 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002617 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002618 if (!uriHasUserId(uri)) {
2619 //We don't add the user Id if there's already one
2620 Uri.Builder builder = uri.buildUpon();
2621 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2622 return builder.build();
2623 }
2624 }
2625 return uri;
2626 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002627}