blob: 65eb642369c959ed22b6314d30915e52290e1512 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070051import android.os.Process;
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -080052import android.os.RemoteCallback;
Ben Lin1cf454f2016-11-10 13:50:54 -080053import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060054import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070055import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060056import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010057import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070058import android.util.Log;
Philip P. Moltmann128b7032019-09-27 08:44:12 -070059import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060061import com.android.internal.annotations.VisibleForTesting;
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080064import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070066import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080067import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070068import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080069import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060070import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72/**
73 * Content providers are one of the primary building blocks of Android applications, providing
74 * content to applications. They encapsulate data and provide it to applications through the single
75 * {@link ContentResolver} interface. A content provider is only required if you need to share
76 * data between multiple applications. For example, the contacts data is used by multiple
77 * applications and must be stored in a content provider. If you don't need to share data amongst
78 * multiple applications you can use a database directly via
79 * {@link android.database.sqlite.SQLiteDatabase}.
80 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 * <p>When a request is made via
82 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
83 * request to the content provider registered with the authority. The content provider can interpret
84 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
85 * URIs.</p>
86 *
87 * <p>The primary methods that need to be implemented are:
88 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070089 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 * <li>{@link #query} which returns data to the caller</li>
91 * <li>{@link #insert} which inserts new data into the content provider</li>
92 * <li>{@link #update} which updates existing data in the content provider</li>
93 * <li>{@link #delete} which deletes data from the content provider</li>
94 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
95 * </ul></p>
96 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070097 * <p class="caution">Data access methods (such as {@link #insert} and
98 * {@link #update}) may be called from many threads at once, and must be thread-safe.
99 * Other methods (such as {@link #onCreate}) are only called from the application
100 * main thread, and must avoid performing lengthy operations. See the method
101 * descriptions for their expected thread behavior.</p>
102 *
103 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
104 * ContentProvider instance, so subclasses don't have to worry about the details of
105 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700106 *
107 * <div class="special reference">
108 * <h3>Developer Guides</h3>
109 * <p>For more information about using content providers, read the
110 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
111 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700112 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700114public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800115
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700116 private static final String TAG = "ContentProvider";
117
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900118 /*
119 * Note: if you add methods to ContentProvider, you must add similar methods to
120 * MockContentProvider.
121 */
122
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100123 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700125 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100126
127 // Since most Providers have only one authority, we keep both a String and a String[] to improve
128 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100130 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100131 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100132 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100133 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100135 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100137 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700138 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700139 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800140 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700141 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700143 private ThreadLocal<Pair<String, String>> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private Transport mTransport = new Transport();
146
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700147 /**
148 * Construct a ContentProvider instance. Content providers must be
149 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
150 * in the manifest</a>, accessed with {@link ContentResolver}, and created
151 * automatically by the system, so applications usually do not create
152 * ContentProvider instances directly.
153 *
154 * <p>At construction time, the object is uninitialized, and most fields and
155 * methods are unavailable. Subclasses should initialize themselves in
156 * {@link #onCreate}, not the constructor.
157 *
158 * <p>Content providers are created on the application main thread at
159 * application launch time. The constructor must not perform lengthy
160 * operations, or application startup will be delayed.
161 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900162 public ContentProvider() {
163 }
164
165 /**
166 * Constructor just for mocking.
167 *
168 * @param context A Context object which should be some mock instance (like the
169 * instance of {@link android.test.mock.MockContext}).
170 * @param readPermission The read permision you want this instance should have in the
171 * test, which is available via {@link #getReadPermission()}.
172 * @param writePermission The write permission you want this instance should have
173 * in the test, which is available via {@link #getWritePermission()}.
174 * @param pathPermissions The PathPermissions you want this instance should have
175 * in the test, which is available via {@link #getPathPermissions()}.
176 * @hide
177 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900179 public ContentProvider(
180 Context context,
181 String readPermission,
182 String writePermission,
183 PathPermission[] pathPermissions) {
184 mContext = context;
185 mReadPermission = readPermission;
186 mWritePermission = writePermission;
187 mPathPermissions = pathPermissions;
188 }
189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 /**
191 * Given an IContentProvider, try to coerce it back to the real
192 * ContentProvider object if it is running in the local process. This can
193 * be used if you know you are running in the same process as a provider,
194 * and want to get direct access to its implementation details. Most
195 * clients should not nor have a reason to use it.
196 *
197 * @param abstractInterface The ContentProvider interface that is to be
198 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800199 * @return If the IContentProvider is non-{@code null} and local, returns its actual
200 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 * @hide
202 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100203 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 public static ContentProvider coerceToLocalContentProvider(
205 IContentProvider abstractInterface) {
206 if (abstractInterface instanceof Transport) {
207 return ((Transport)abstractInterface).getContentProvider();
208 }
209 return null;
210 }
211
212 /**
213 * Binder object that deals with remoting.
214 *
215 * @hide
216 */
217 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700218 volatile AppOpsManager mAppOpsManager = null;
219 volatile int mReadOp = AppOpsManager.OP_NONE;
220 volatile int mWriteOp = AppOpsManager.OP_NONE;
221 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 ContentProvider getContentProvider() {
224 return ContentProvider.this;
225 }
226
Jeff Brownd2183652011-10-09 12:39:53 -0700227 @Override
228 public String getProviderName() {
229 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 }
231
Jeff Brown75ea64f2012-01-25 19:37:13 -0800232 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800233 public Cursor query(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700234 @Nullable String[] projection, @Nullable Bundle queryArgs,
235 @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600236 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100237 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800238 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700239 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700240 // The caller has no access to the data, so return an empty cursor with
241 // the columns in the requested order. The caller may ask for an invalid
242 // column and we would not catch that but this is not a problem in practice.
243 // We do not call ContentProvider#query with a modified where clause since
244 // the implementation is not guaranteed to be backed by a SQL database, hence
245 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700246 if (projection != null) {
247 return new MatrixCursor(projection, 0);
248 }
249
250 // Null projection means all columns but we have no idea which they are.
251 // However, the caller may be expecting to access them my index. Hence,
252 // we have to execute the query as if allowed to get a cursor with the
253 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700254 Cursor cursor;
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700255 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800256 new Pair<>(callingPkg, attributionTag));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700257 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700258 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700259 uri, projection, queryArgs,
260 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700261 } catch (RemoteException e) {
262 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700263 } finally {
264 setCallingPackage(original);
265 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700266 if (cursor == null) {
267 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700268 }
269
270 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700271 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800272 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600273 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700274 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800275 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700276 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700277 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800278 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700279 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700280 } catch (RemoteException e) {
281 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700282 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700283 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600284 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287
Jeff Brown75ea64f2012-01-25 19:37:13 -0800288 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700290 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600291 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100292 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600293 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
294 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700295 return mInterface.getType(uri);
296 } catch (RemoteException e) {
297 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600298 } finally {
299 Trace.traceEnd(TRACE_TAG_DATABASE);
300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
Jeff Brown75ea64f2012-01-25 19:37:13 -0800303 @Override
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -0800304 public void getTypeAsync(Uri uri, RemoteCallback callback) {
305 final Bundle result = new Bundle();
306 result.putString(ContentResolver.REMOTE_CALLBACK_RESULT, getType(uri));
307 callback.sendResult(result);
308 }
309
310 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800311 public Uri insert(String callingPkg, @Nullable String attributionTag, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700312 ContentValues initialValues, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600313 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100314 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100315 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800316 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700317 != AppOpsManager.MODE_ALLOWED) {
318 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800319 new Pair<>(callingPkg, attributionTag));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700320 try {
321 return rejectInsert(uri, initialValues);
322 } finally {
323 setCallingPackage(original);
324 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800325 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600326 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700327 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800328 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700329 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700330 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700331 } catch (RemoteException e) {
332 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700333 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700334 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600335 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
338
Jeff Brown75ea64f2012-01-25 19:37:13 -0800339 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800340 public int bulkInsert(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700341 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600342 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100343 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800344 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700345 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800346 return 0;
347 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600348 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700349 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800350 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700351 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700352 return mInterface.bulkInsert(uri, initialValues);
353 } catch (RemoteException e) {
354 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700356 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600357 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 }
360
Jeff Brown75ea64f2012-01-25 19:37:13 -0800361 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800362 public ContentProviderResult[] applyBatch(String callingPkg,
363 @Nullable String attributionTag, String authority,
364 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700365 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700366 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100367 int numOperations = operations.size();
368 final int[] userIds = new int[numOperations];
369 for (int i = 0; i < numOperations; i++) {
370 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100371 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600372 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600373 uri = validateIncomingUri(uri);
374 uri = maybeGetUriWithoutUserId(uri);
375 // Rebuild operation if we changed the Uri above
376 if (!Objects.equals(operation.getUri(), uri)) {
377 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100378 operations.set(i, operation);
379 }
Fred Quintana89437372009-05-15 15:10:40 -0700380 if (operation.isReadOperation()) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800381 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800382 != AppOpsManager.MODE_ALLOWED) {
383 throw new OperationApplicationException("App op not allowed", 0);
384 }
Fred Quintana89437372009-05-15 15:10:40 -0700385 }
Fred Quintana89437372009-05-15 15:10:40 -0700386 if (operation.isWriteOperation()) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800387 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800388 != AppOpsManager.MODE_ALLOWED) {
389 throw new OperationApplicationException("App op not allowed", 0);
390 }
Fred Quintana89437372009-05-15 15:10:40 -0700391 }
392 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600393 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700394 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800395 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700396 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700397 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700398 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800399 if (results != null) {
400 for (int i = 0; i < results.length ; i++) {
401 if (userIds[i] != UserHandle.USER_CURRENT) {
402 // Adding the userId to the uri.
403 results[i] = new ContentProviderResult(results[i], userIds[i]);
404 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100405 }
406 }
407 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700408 } catch (RemoteException e) {
409 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700410 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700411 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600412 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700413 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700414 }
415
Jeff Brown75ea64f2012-01-25 19:37:13 -0800416 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800417 public int delete(String callingPkg, @Nullable String attributionTag, Uri uri,
418 Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600419 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100420 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800421 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700422 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800423 return 0;
424 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600425 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700426 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800427 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700428 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700429 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700430 } catch (RemoteException e) {
431 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700432 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700433 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600434 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 }
437
Jeff Brown75ea64f2012-01-25 19:37:13 -0800438 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800439 public int update(String callingPkg, @Nullable String attributionTag, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700440 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600441 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100442 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800443 if (enforceWritePermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700444 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800445 return 0;
446 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600447 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700448 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800449 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700450 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700451 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700452 } catch (RemoteException e) {
453 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700454 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700455 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600456 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 }
459
Jeff Brown75ea64f2012-01-25 19:37:13 -0800460 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800461 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700462 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
463 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600464 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100465 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800466 enforceFilePermission(callingPkg, attributionTag, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600467 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700468 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800469 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700470 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700471 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700472 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700473 } catch (RemoteException e) {
474 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700475 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700476 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600477 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 }
480
Jeff Brown75ea64f2012-01-25 19:37:13 -0800481 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800482 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700483 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600485 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100486 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800487 enforceFilePermission(callingPkg, attributionTag, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600488 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700489 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800490 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700491 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700492 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700493 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700494 } catch (RemoteException e) {
495 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700496 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700497 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600498 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
501
Jeff Brown75ea64f2012-01-25 19:37:13 -0800502 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800503 public Bundle call(String callingPkg, @Nullable String attributionTag, String authority,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700504 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700505 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600506 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600507 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700508 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800509 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700510 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700511 return mInterface.call(authority, method, arg, extras);
512 } catch (RemoteException e) {
513 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700514 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700515 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600516 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700517 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800518 }
519
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700520 @Override
521 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700522 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600523 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100524 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600525 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
526 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700527 return mInterface.getStreamTypes(uri, mimeTypeFilter);
528 } catch (RemoteException e) {
529 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600530 } finally {
531 Trace.traceEnd(TRACE_TAG_DATABASE);
532 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700533 }
534
535 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700536 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800537 @Nullable String attributionTag, Uri uri, String mimeType, Bundle opts,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700538 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600539 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600540 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100541 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800542 enforceFilePermission(callingPkg, attributionTag, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600543 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700544 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800545 new Pair<>(callingPkg, attributionTag));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700546 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700547 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700548 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700549 } catch (RemoteException e) {
550 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700551 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700552 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600553 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700554 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700555 }
556
Jeff Brown75ea64f2012-01-25 19:37:13 -0800557 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700558 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800559 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800560 }
561
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700562 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800563 public Uri canonicalize(String callingPkg, @Nullable String attributionTag, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600564 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100565 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100566 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800567 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700568 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700569 return null;
570 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600571 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700572 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800573 new Pair<>(callingPkg, attributionTag));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700574 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700575 return maybeAddUserId(mInterface.canonicalize(uri), userId);
576 } catch (RemoteException e) {
577 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700578 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700579 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600580 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700581 }
582 }
583
584 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800585 public void canonicalizeAsync(String callingPkg, @Nullable String attributionTag, Uri uri,
Dmitri Plotnikov7a223fb2020-02-14 17:04:13 -0800586 RemoteCallback callback) {
587 final Bundle result = new Bundle();
588 result.putParcelable(ContentResolver.REMOTE_CALLBACK_RESULT,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800589 canonicalize(callingPkg, attributionTag, uri));
Dmitri Plotnikov7a223fb2020-02-14 17:04:13 -0800590 callback.sendResult(result);
591 }
592
593 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800594 public Uri uncanonicalize(String callingPkg, String attributionTag, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600595 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100596 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100597 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800598 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700599 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700600 return null;
601 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600602 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700603 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800604 new Pair<>(callingPkg, attributionTag));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700605 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700606 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
607 } catch (RemoteException e) {
608 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700609 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700610 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600611 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700612 }
613 }
614
Ben Lin1cf454f2016-11-10 13:50:54 -0800615 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800616 public boolean refresh(String callingPkg, String attributionTag, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800617 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600618 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800619 uri = getUriWithoutUserId(uri);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800620 if (enforceReadPermission(callingPkg, attributionTag, uri, null)
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700621 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800622 return false;
623 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600624 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700625 final Pair<String, String> original = setCallingPackage(
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800626 new Pair<>(callingPkg, attributionTag));
Ben Lin1cf454f2016-11-10 13:50:54 -0800627 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700628 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800629 CancellationSignal.fromTransport(cancellationSignal));
630 } finally {
631 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600632 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800633 }
634 }
635
Jeff Sharkey9edef252019-05-20 14:00:17 -0600636 @Override
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800637 public int checkUriPermission(String callingPkg, @Nullable String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700638 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600639 uri = validateIncomingUri(uri);
640 uri = maybeGetUriWithoutUserId(uri);
641 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
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));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600644 try {
645 return mInterface.checkUriPermission(uri, uid, modeFlags);
646 } catch (RemoteException e) {
647 throw e.rethrowAsRuntimeException();
648 } finally {
649 setCallingPackage(original);
650 Trace.traceEnd(TRACE_TAG_DATABASE);
651 }
652 }
653
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800654 private void enforceFilePermission(String callingPkg, @Nullable String attributionTag,
655 Uri uri, String mode, IBinder callerToken)
656 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800657 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800658 if (enforceWritePermission(callingPkg, attributionTag, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800659 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800660 throw new FileNotFoundException("App op not allowed");
661 }
662 } else {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800663 if (enforceReadPermission(callingPkg, attributionTag, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800664 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800665 throw new FileNotFoundException("App op not allowed");
666 }
667 }
668 }
669
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800670 private int enforceReadPermission(String callingPkg, @Nullable String attributionTag,
671 Uri uri, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800672 throws SecurityException {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800673 final int mode = enforceReadPermissionInner(uri, callingPkg, attributionTag,
674 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700675 if (mode != MODE_ALLOWED) {
676 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800677 }
Svet Ganov99b60432015-06-27 13:15:22 -0700678
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800679 return noteProxyOp(callingPkg, attributionTag, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800680 }
681
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800682 private int enforceWritePermission(String callingPkg, String attributionTag, Uri uri,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700683 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800684 throws SecurityException {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800685 final int mode = enforceWritePermissionInner(uri, callingPkg, attributionTag,
686 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700687 if (mode != MODE_ALLOWED) {
688 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800689 }
Svet Ganov99b60432015-06-27 13:15:22 -0700690
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800691 return noteProxyOp(callingPkg, attributionTag, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700692 }
693
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800694 private int noteProxyOp(String callingPkg, String attributionTag, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700695 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700696 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800697 attributionTag, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700698 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700699 }
700
Dianne Hackborn35654b62013-01-14 17:38:02 -0800701 return AppOpsManager.MODE_ALLOWED;
702 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700703 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800704
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100705 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700706 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
707 return true;
708 }
709 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
710 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100711 == PERMISSION_GRANTED;
712 }
713
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700714 /**
715 * Verify that calling app holds both the given permission and any app-op
716 * associated with that permission.
717 */
718 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800719 @Nullable String attributionTag, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700720 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
721 callerToken) != PERMISSION_GRANTED) {
722 return MODE_ERRORED;
723 }
724
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800725 return mTransport.noteProxyOp(callingPkg, attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700726 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700727 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700728
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700729 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700730 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800731 @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700732 final Context context = getContext();
733 final int pid = Binder.getCallingPid();
734 final int uid = Binder.getCallingUid();
735 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700736 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700737
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700738 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700739 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700740 }
741
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100742 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700743 final String componentPerm = getReadPermission();
744 if (componentPerm != null) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800745 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, attributionTag,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700746 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700747 if (mode == MODE_ALLOWED) {
748 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700749 } else {
750 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700751 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700752 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700753 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700754
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700755 // track if unprotected read is allowed; any denied
756 // <path-permission> below removes this ability
757 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700758
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700759 final PathPermission[] pps = getPathPermissions();
760 if (pps != null) {
761 final String path = uri.getPath();
762 for (PathPermission pp : pps) {
763 final String pathPerm = pp.getReadPermission();
764 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800765 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
766 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700767 if (mode == MODE_ALLOWED) {
768 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700769 } else {
770 // any denied <path-permission> means we lose
771 // default <provider> access.
772 allowDefaultRead = false;
773 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700774 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700775 }
776 }
777 }
778 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700779
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700780 // if we passed <path-permission> checks above, and no default
781 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700782 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700784
785 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800786 final int callingUserId = UserHandle.getUserId(uid);
787 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
788 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800789 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
790 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700791 return MODE_ALLOWED;
792 }
793
794 // If the worst denial we found above was ignored, then pass that
795 // ignored through; otherwise we assume it should be a real error below.
796 if (strongestMode == MODE_IGNORED) {
797 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700798 }
799
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600800 final String suffix;
801 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
802 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
803 } else if (mExported) {
804 suffix = " requires " + missingPerm + ", or grantUriPermission()";
805 } else {
806 suffix = " requires the provider be exported, or grantUriPermission()";
807 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700808 throw new SecurityException("Permission Denial: reading "
809 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600810 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700811 }
812
813 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700814 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800815 @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700816 final Context context = getContext();
817 final int pid = Binder.getCallingPid();
818 final int uid = Binder.getCallingUid();
819 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700820 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700821
822 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700823 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700824 }
825
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100826 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700827 final String componentPerm = getWritePermission();
828 if (componentPerm != null) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800829 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg,
830 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700831 if (mode == MODE_ALLOWED) {
832 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700833 } else {
834 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700835 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700836 }
837 }
838
839 // track if unprotected write is allowed; any denied
840 // <path-permission> below removes this ability
841 boolean allowDefaultWrite = (componentPerm == null);
842
843 final PathPermission[] pps = getPathPermissions();
844 if (pps != null) {
845 final String path = uri.getPath();
846 for (PathPermission pp : pps) {
847 final String pathPerm = pp.getWritePermission();
848 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800849 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
850 attributionTag, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700851 if (mode == MODE_ALLOWED) {
852 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700853 } else {
854 // any denied <path-permission> means we lose
855 // default <provider> access.
856 allowDefaultWrite = false;
857 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700858 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700859 }
860 }
861 }
862 }
863
864 // if we passed <path-permission> checks above, and no default
865 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700866 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700867 }
868
869 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800870 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
871 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700872 return MODE_ALLOWED;
873 }
874
875 // If the worst denial we found above was ignored, then pass that
876 // ignored through; otherwise we assume it should be a real error below.
877 if (strongestMode == MODE_IGNORED) {
878 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700879 }
880
881 final String failReason = mExported
882 ? " requires " + missingPerm + ", or grantUriPermission()"
883 : " requires the provider be exported, or grantUriPermission()";
884 throw new SecurityException("Permission Denial: writing "
885 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
886 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 }
888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700890 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800891 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 * constructor.
893 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700894 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 return mContext;
896 }
897
898 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700899 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
900 * after {@link #onCreate}. When called before context was created, an IllegalStateException
901 * will be thrown.
902 * <p>
903 * Note A provider must be declared in the manifest and created automatically by the system,
904 * and context is only available after {@link #onCreate} is called.
905 */
906 @NonNull
907 public final Context requireContext() {
908 final Context ctx = getContext();
909 if (ctx == null) {
910 throw new IllegalStateException("Cannot find context from the provider.");
911 }
912 return ctx;
913 }
914
915 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700916 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700917 * which can be used later to restore the previous state.
918 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700919 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
920 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700921 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600922 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700923 return original;
924 }
925
926 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700927 * Return the package name of the caller that initiated the request being
928 * processed on the current thread. The returned package will have been
929 * verified to belong to the calling UID. Returns {@code null} if not
930 * currently processing a request.
931 * <p>
932 * This will always return {@code null} when processing
933 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
934 *
935 * @see Binder#getCallingUid()
936 * @see Context#grantUriPermission(String, Uri, int)
937 * @throws SecurityException if the calling package doesn't belong to the
938 * calling UID.
939 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700940 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700941 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700942 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700943 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
944 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700945 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700946
947 return null;
948 }
949
950 /**
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800951 * Return the attribution tag of the caller that initiated the request being
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700952 * processed on the current thread. Returns {@code null} if not currently processing
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800953 * a request of the request is for the default attribution.
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700954 * <p>
955 * This will always return {@code null} when processing
956 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
957 *
958 * @see #getCallingPackage
959 */
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800960 public final @Nullable String getCallingAttributionTag() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700961 final Pair<String, String> pkg = mCallingPackage.get();
962 if (pkg != null) {
963 return pkg.second;
964 }
965
966 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700967 }
968
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700969 /**
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -0800970 * @removed
971 */
972 @Deprecated
973 public final @Nullable String getCallingFeatureId() {
974 return getCallingAttributionTag();
975 }
976
977 /**
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700978 * Return the package name of the caller that initiated the request being
979 * processed on the current thread. The returned package will have
980 * <em>not</em> been verified to belong to the calling UID. Returns
981 * {@code null} if not currently processing a request.
982 * <p>
983 * This will always return {@code null} when processing
984 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
985 *
986 * @see Binder#getCallingUid()
987 * @see Context#grantUriPermission(String, Uri, int)
988 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600989 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700990 final Pair<String, String> pkg = mCallingPackage.get();
991 if (pkg != null) {
992 return pkg.first;
993 }
994
995 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600996 }
997
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700998 /**
999 * Called whenever the value of {@link #getCallingPackage()} changes, giving
1000 * the provider an opportunity to invalidate any security related caching it
1001 * may be performing.
1002 * <p>
1003 * This typically happens when a {@link ContentProvider} makes a nested call
1004 * back into itself when already processing a call from a remote process.
1005 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -06001006 public void onCallingPackageChanged() {
1007 }
1008
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001009 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001010 * Opaque token representing the identity of an incoming IPC.
1011 */
1012 public final class CallingIdentity {
1013 /** {@hide} */
1014 public final long binderToken;
1015 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001016 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001017
1018 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -07001019 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -06001020 this.binderToken = binderToken;
1021 this.callingPackage = callingPackage;
1022 }
1023 }
1024
1025 /**
1026 * Reset the identity of the incoming IPC on the current thread.
1027 * <p>
1028 * Internally this calls {@link Binder#clearCallingIdentity()} and also
1029 * clears any value stored in {@link #getCallingPackage()}.
1030 *
1031 * @return Returns an opaque token that can be used to restore the original
1032 * calling identity by passing it to
1033 * {@link #restoreCallingIdentity}.
1034 */
1035 public final @NonNull CallingIdentity clearCallingIdentity() {
1036 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
1037 }
1038
1039 /**
1040 * Restore the identity of the incoming IPC on the current thread back to a
1041 * previously identity that was returned by {@link #clearCallingIdentity}.
1042 * <p>
1043 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
1044 * also restores any value stored in {@link #getCallingPackage()}.
1045 */
1046 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
1047 Binder.restoreCallingIdentity(identity.binderToken);
1048 mCallingPackage.set(identity.callingPackage);
1049 }
1050
1051 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001052 * Change the authorities of the ContentProvider.
1053 * This is normally set for you from its manifest information when the provider is first
1054 * created.
1055 * @hide
1056 * @param authorities the semi-colon separated authorities of the ContentProvider.
1057 */
1058 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001059 if (authorities != null) {
1060 if (authorities.indexOf(';') == -1) {
1061 mAuthority = authorities;
1062 mAuthorities = null;
1063 } else {
1064 mAuthority = null;
1065 mAuthorities = authorities.split(";");
1066 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001067 }
1068 }
1069
1070 /** @hide */
1071 protected final boolean matchesOurAuthorities(String authority) {
1072 if (mAuthority != null) {
1073 return mAuthority.equals(authority);
1074 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001075 if (mAuthorities != null) {
1076 int length = mAuthorities.length;
1077 for (int i = 0; i < length; i++) {
1078 if (mAuthorities[i].equals(authority)) return true;
1079 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001080 }
1081 return false;
1082 }
1083
1084
1085 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 * Change the permission required to read data from the content
1087 * provider. This is normally set for you from its manifest information
1088 * when the provider is first created.
1089 *
1090 * @param permission Name of the permission required for read-only access.
1091 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001092 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 mReadPermission = permission;
1094 }
1095
1096 /**
1097 * Return the name of the permission required for read-only access to
1098 * this content provider. This method can be called from multiple
1099 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001100 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1101 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001103 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 return mReadPermission;
1105 }
1106
1107 /**
1108 * Change the permission required to read and write data in the content
1109 * provider. This is normally set for you from its manifest information
1110 * when the provider is first created.
1111 *
1112 * @param permission Name of the permission required for read/write access.
1113 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001114 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 mWritePermission = permission;
1116 }
1117
1118 /**
1119 * Return the name of the permission required for read/write access to
1120 * this content provider. This method can be called from multiple
1121 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001122 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1123 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001125 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 return mWritePermission;
1127 }
1128
1129 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001130 * Change the path-based permission required to read and/or write data in
1131 * the content provider. This is normally set for you from its manifest
1132 * information when the provider is first created.
1133 *
1134 * @param permissions Array of path permission descriptions.
1135 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001136 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001137 mPathPermissions = permissions;
1138 }
1139
1140 /**
1141 * Return the path-based permissions required for read and/or write access to
1142 * this content provider. This method can be called from multiple
1143 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001144 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1145 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001146 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001147 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001148 return mPathPermissions;
1149 }
1150
Dianne Hackborn35654b62013-01-14 17:38:02 -08001151 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001152 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001153 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001154 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001155 mTransport.mReadOp = readOp;
1156 mTransport.mWriteOp = writeOp;
1157 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001158 }
1159
Dianne Hackborn961321f2013-02-05 17:22:41 -08001160 /** @hide */
1161 public AppOpsManager getAppOpsManager() {
1162 return mTransport.mAppOpsManager;
1163 }
1164
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001165 /** @hide */
1166 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001167 if (mTransport == null) {
1168 return;
1169 }
1170 if (enabled) {
1171 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1172 } else {
1173 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001174 }
1175 }
1176
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001177 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001178 * Implement this to initialize your content provider on startup.
1179 * This method is called for all registered content providers on the
1180 * application main thread at application launch time. It must not perform
1181 * lengthy operations, or application startup will be delayed.
1182 *
1183 * <p>You should defer nontrivial initialization (such as opening,
1184 * upgrading, and scanning databases) until the content provider is used
1185 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1186 * keeps application startup fast, avoids unnecessary work if the provider
1187 * turns out not to be needed, and stops database errors (such as a full
1188 * disk) from halting application launch.
1189 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001190 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001191 * is a helpful utility class that makes it easy to manage databases,
1192 * and will automatically defer opening until first use. If you do use
1193 * SQLiteOpenHelper, make sure to avoid calling
1194 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1195 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1196 * from this method. (Instead, override
1197 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1198 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 *
1200 * @return true if the provider was successfully loaded, false otherwise
1201 */
1202 public abstract boolean onCreate();
1203
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001204 /**
1205 * {@inheritDoc}
1206 * This method is always called on the application main thread, and must
1207 * not perform lengthy operations.
1208 *
1209 * <p>The default content provider implementation does nothing.
1210 * Override this method to take appropriate action.
1211 * (Content providers do not usually care about things like screen
1212 * orientation, but may want to know about locale changes.)
1213 */
Steve McKayea93fe72016-12-02 11:35:35 -08001214 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 public void onConfigurationChanged(Configuration newConfig) {
1216 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001217
1218 /**
1219 * {@inheritDoc}
1220 * This method is always called on the application main thread, and must
1221 * not perform lengthy operations.
1222 *
1223 * <p>The default content provider implementation does nothing.
1224 * Subclasses may override this method to take appropriate action.
1225 */
Steve McKayea93fe72016-12-02 11:35:35 -08001226 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 public void onLowMemory() {
1228 }
1229
Steve McKayea93fe72016-12-02 11:35:35 -08001230 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001231 public void onTrimMemory(int level) {
1232 }
1233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001235 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001236 *
1237 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1238 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1239 * implementation of this method.
1240 *
1241 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001242 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1243 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 * <p>
1245 * Example client call:<p>
1246 * <pre>// Request a specific record.
1247 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001248 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 projection, // Which columns to return.
1250 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001251 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 People.NAME + " ASC"); // Sort order.</pre>
1253 * Example implementation:<p>
1254 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1255 // proper SQL syntax for us.
1256 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1257
1258 // Set the table we're querying.
1259 qBuilder.setTables(DATABASE_TABLE_NAME);
1260
1261 // If the query ends in a specific record number, we're
1262 // being asked for a specific record, so set the
1263 // WHERE clause in our query.
1264 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1265 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1266 }
1267
1268 // Make the query.
1269 Cursor c = qBuilder.query(mDb,
1270 projection,
1271 selection,
1272 selectionArgs,
1273 groupBy,
1274 having,
1275 sortOrder);
1276 c.setNotificationUri(getContext().getContentResolver(), uri);
1277 return c;</pre>
1278 *
1279 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001280 * if the client is requesting a specific record, the URI will end in a record number
1281 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1282 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001284 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001286 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001287 * @param selectionArgs You may include ?s in selection, which will be replaced by
1288 * the values from selectionArgs, in order that they appear in the selection.
1289 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001291 * If {@code null} then the provider is free to define the sort order.
1292 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001294 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1295 @Nullable String selection, @Nullable String[] selectionArgs,
1296 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297
Fred Quintana5bba6322009-10-05 14:21:12 -07001298 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001299 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001300 *
1301 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1302 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1303 *
1304 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001305 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1306 * and Threads</a>.
1307 * <p>
1308 * Example client call:<p>
1309 * <pre>// Request a specific record.
1310 * Cursor managedCursor = managedQuery(
1311 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1312 projection, // Which columns to return.
1313 null, // WHERE clause.
1314 null, // WHERE clause value substitution
1315 People.NAME + " ASC"); // Sort order.</pre>
1316 * Example implementation:<p>
1317 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1318 // proper SQL syntax for us.
1319 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1320
1321 // Set the table we're querying.
1322 qBuilder.setTables(DATABASE_TABLE_NAME);
1323
1324 // If the query ends in a specific record number, we're
1325 // being asked for a specific record, so set the
1326 // WHERE clause in our query.
1327 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1328 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1329 }
1330
1331 // Make the query.
1332 Cursor c = qBuilder.query(mDb,
1333 projection,
1334 selection,
1335 selectionArgs,
1336 groupBy,
1337 having,
1338 sortOrder);
1339 c.setNotificationUri(getContext().getContentResolver(), uri);
1340 return c;</pre>
1341 * <p>
1342 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001343 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1344 * signal to ensure correct operation on older versions of the Android Framework in
1345 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001346 *
1347 * @param uri The URI to query. This will be the full URI sent by the client;
1348 * if the client is requesting a specific record, the URI will end in a record number
1349 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1350 * that _id value.
1351 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001352 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001353 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001354 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001355 * @param selectionArgs You may include ?s in selection, which will be replaced by
1356 * the values from selectionArgs, in order that they appear in the selection.
1357 * The values will be bound as Strings.
1358 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001359 * If {@code null} then the provider is free to define the sort order.
1360 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001361 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001362 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001363 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001364 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001365 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1366 @Nullable String selection, @Nullable String[] selectionArgs,
1367 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001368 return query(uri, projection, selection, selectionArgs, sortOrder);
1369 }
1370
1371 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001372 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1373 * Arguments may include traditional SQL style query arguments. When present these
1374 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001375 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001376 *
1377 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001378 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1379 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1380 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001381 *
Steve McKay76b27702017-04-24 12:07:53 -07001382 * <p>This method can be called from multiple threads, as described in
1383 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1384 * and Threads</a>.
1385 *
1386 * <p>
1387 * Example client call:<p>
1388 * <pre>// Request 20 records starting at row index 30.
1389 Bundle queryArgs = new Bundle();
1390 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1391 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1392
1393 Cursor cursor = getContentResolver().query(
1394 contentUri, // Content Uri is specific to individual content providers.
1395 projection, // String[] describing which columns to return.
1396 queryArgs, // Query arguments.
1397 null); // Cancellation signal.</pre>
1398 *
1399 * Example implementation:<p>
1400 * <pre>
1401
1402 int recordsetSize = 0x1000; // Actual value is implementation specific.
1403 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1404
1405 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1406 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1407
1408 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1409
1410 // Calculate the number of items to include in the cursor.
1411 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1412
1413 // Build the paged result set....
1414 for (int i = offset; i < offset + numItems; i++) {
1415 // populate row from your data.
1416 }
1417
1418 Bundle extras = new Bundle();
1419 c.setExtras(extras);
1420
1421 // Any QUERY_ARG_* key may be included if honored.
1422 // In an actual implementation, include only keys that are both present in queryArgs
1423 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1424 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1425 // then QUERY_ARG_OFFSET should be omitted.
1426 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1427 ContentResolver.QUERY_ARG_OFFSET,
1428 ContentResolver.QUERY_ARG_LIMIT
1429 });
1430
1431 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1432
1433 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1434
1435 return cursor;</pre>
1436 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001437 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1438 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001439 *
1440 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001441 * @param projection The list of columns to put into the cursor.
1442 * If {@code null} provide a default set of columns.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001443 * @param queryArgs A Bundle containing additional information necessary for
1444 * the operation. Arguments may include SQL style arguments, such
1445 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1446 * the documentation for each individual provider will indicate
1447 * which arguments they support.
Steve McKayea93fe72016-12-02 11:35:35 -08001448 * @param cancellationSignal A signal to cancel the operation in progress,
1449 * or {@code null}.
1450 * @return a Cursor or {@code null}.
1451 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001452 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001453 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1454 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1455 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001456
Steve McKayd7ece9f2017-01-12 16:59:59 -08001457 // if client doesn't supply an SQL sort order argument, attempt to build one from
1458 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001459 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001460 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1461 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1462 }
1463
Steve McKayea93fe72016-12-02 11:35:35 -08001464 return query(
1465 uri,
1466 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001467 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1468 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1469 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001470 cancellationSignal);
1471 }
1472
1473 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001474 * Implement this to handle requests for the MIME type of the data at the
1475 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 * <code>vnd.android.cursor.item</code> for a single record,
1477 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001478 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001479 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1480 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001482 * <p>Note that there are no permissions needed for an application to
1483 * access this information; if your content provider requires read and/or
1484 * write permissions, or is not exported, all applications can still call
1485 * this method regardless of their access permissions. This allows them
1486 * to retrieve the MIME type for a URI when dispatching intents.
1487 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001489 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001491 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001492 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493
1494 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001495 * Implement this to support canonicalization of URIs that refer to your
1496 * content provider. A canonical URI is one that can be transported across
1497 * devices, backup/restore, and other contexts, and still be able to refer
1498 * to the same data item. Typically this is implemented by adding query
1499 * params to the URI allowing the content provider to verify that an incoming
1500 * canonical URI references the same data as it was originally intended for and,
1501 * if it doesn't, to find that data (if it exists) in the current environment.
1502 *
1503 * <p>For example, if the content provider holds people and a normal URI in it
1504 * is created with a row index into that people database, the cananical representation
1505 * may have an additional query param at the end which specifies the name of the
1506 * person it is intended for. Later calls into the provider with that URI will look
1507 * up the row of that URI's base index and, if it doesn't match or its entry's
1508 * name doesn't match the name in the query param, perform a query on its database
1509 * to find the correct row to operate on.</p>
1510 *
1511 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1512 * URIs (including this one) must perform this verification and recovery of any
1513 * canonical URIs they receive. In addition, you must also implement
1514 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1515 *
1516 * <p>The default implementation of this method returns null, indicating that
1517 * canonical URIs are not supported.</p>
1518 *
1519 * @param url The Uri to canonicalize.
1520 *
1521 * @return Return the canonical representation of <var>url</var>, or null if
1522 * canonicalization of that Uri is not supported.
1523 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001524 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001525 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001526 return null;
1527 }
1528
1529 /**
1530 * Remove canonicalization from canonical URIs previously returned by
1531 * {@link #canonicalize}. For example, if your implementation is to add
1532 * a query param to canonicalize a URI, this method can simply trip any
1533 * query params on the URI. The default implementation always returns the
1534 * same <var>url</var> that was passed in.
1535 *
1536 * @param url The Uri to remove any canonicalization from.
1537 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001538 * @return Return the non-canonical representation of <var>url</var>, return
1539 * the <var>url</var> as-is if there is nothing to do, or return null if
1540 * the data identified by the canonical representation can not be found in
1541 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001542 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001543 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001544 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001545 return url;
1546 }
1547
1548 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001549 * Implement this to support refresh of content identified by {@code uri}.
1550 * By default, this method returns false; providers who wish to implement
1551 * this should return true to signal the client that the provider has tried
1552 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001553 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001554 * This allows clients to request an explicit refresh of content identified
1555 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001556 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001557 * Client code should only invoke this method when there is a strong
1558 * indication (such as a user initiated pull to refresh gesture) that the
1559 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001560 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001561 * Remember to send
1562 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001563 * notifications when content changes.
1564 *
1565 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001566 * @param extras Additional options from the client. The definitions of
1567 * these are specific to the content provider being called.
1568 * @param cancellationSignal A signal to cancel the operation in progress,
1569 * or {@code null} if none. For example, if you called refresh on
1570 * a particular uri, you should call
1571 * {@link CancellationSignal#throwIfCanceled()} to check whether
1572 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001573 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001574 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001575 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001576 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001577 @Nullable CancellationSignal cancellationSignal) {
1578 return false;
1579 }
1580
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001581 /**
1582 * Perform a detailed internal check on a {@link Uri} to determine if a UID
1583 * is able to access it with specific mode flags.
1584 * <p>
1585 * This method is typically used when the provider implements more dynamic
1586 * access controls that cannot be expressed with {@code <path-permission>}
1587 * style static rules.
Jeff Sharkeyce8a353b2020-03-19 21:41:57 -06001588 * <p>
1589 * Because validation of these dynamic access controls has significant
1590 * system health impact, this feature is only available to providers that
1591 * are built into the system.
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001592 *
1593 * @param uri the {@link Uri} to perform an access check on.
1594 * @param uid the UID to check the permission for.
1595 * @param modeFlags the access flags to use for the access check, such as
1596 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}.
1597 * @return {@link PackageManager#PERMISSION_GRANTED} if access is allowed,
1598 * otherwise {@link PackageManager#PERMISSION_DENIED}.
1599 * @hide
1600 */
Jeff Sharkey9edef252019-05-20 14:00:17 -06001601 @Override
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001602 @SystemApi
Jeff Sharkey9edef252019-05-20 14:00:17 -06001603 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1604 return PackageManager.PERMISSION_DENIED;
1605 }
1606
Ben Lin1cf454f2016-11-10 13:50:54 -08001607 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001608 * @hide
1609 * Implementation when a caller has performed an insert on the content
1610 * provider, but that call has been rejected for the operation given
1611 * to {@link #setAppOps(int, int)}. The default implementation simply
1612 * returns a dummy URI that is the base URI with a 0 path element
1613 * appended.
1614 */
1615 public Uri rejectInsert(Uri uri, ContentValues values) {
1616 // If not allowed, we need to return some reasonable URI. Maybe the
1617 // content provider should be responsible for this, but for now we
1618 // will just return the base URI with a dummy '0' tagged on to it.
1619 // You shouldn't be able to read if you can't write, anyway, so it
1620 // shouldn't matter much what is returned.
1621 return uri.buildUpon().appendPath("0").build();
1622 }
1623
1624 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001625 * Implement this to handle requests to insert a new row. As a courtesy,
1626 * call
1627 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1628 * notifyChange()} after inserting. This method can be called from multiple
1629 * threads, as described in <a href="
1630 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001631 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001632 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001633 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 * @param values A set of column_name/value pairs to add to the database.
1635 * @return The URI for the newly inserted item.
1636 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001637 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638
1639 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001640 * Implement this to handle requests to insert a new row. As a courtesy,
1641 * call
1642 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1643 * notifyChange()} after inserting. This method can be called from multiple
1644 * threads, as described in <a href="
1645 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1646 * and Threads</a>.
1647 *
1648 * @param uri The content:// URI of the insertion request.
1649 * @param values A set of column_name/value pairs to add to the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001650 * @param extras A Bundle containing additional information necessary for
1651 * the operation. Arguments may include SQL style arguments, such
1652 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1653 * the documentation for each individual provider will indicate
1654 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001655 * @return The URI for the newly inserted item.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001656 * @throws IllegalArgumentException if the provider doesn't support one of
1657 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001658 */
1659 @Override
1660 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1661 @Nullable Bundle extras) {
1662 return insert(uri, values);
1663 }
1664
1665 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001666 * Override this to handle requests to insert a set of new rows, or the
1667 * default implementation will iterate over the values and call
1668 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1670 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001671 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001672 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1673 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 *
1675 * @param uri The content:// URI of the insertion request.
1676 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001677 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 * @return The number of values that were inserted.
1679 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001680 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001681 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 int numValues = values.length;
1683 for (int i = 0; i < numValues; i++) {
1684 insert(uri, values[i]);
1685 }
1686 return numValues;
1687 }
1688
1689 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001690 * Implement this to handle requests to delete one or more rows. The
1691 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001692 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001693 * As a courtesy, call
1694 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1695 * notifyChange()} after deleting. This method can be called from multiple
1696 * threads, as described in <a href="
1697 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001698 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001699 * <p>
1700 * The implementation is responsible for parsing out a row ID at the end of
1701 * the URI, if a specific row is being deleted. That is, the client would
1702 * pass in <code>content://contacts/people/22</code> and the implementation
1703 * is responsible for parsing the record number (22) when creating a SQL
1704 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001706 * @param uri The full URI to query, including a row ID (if a specific
1707 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 * @param selection An optional restriction to apply to rows when deleting.
1709 * @return The number of rows affected.
1710 * @throws SQLException
1711 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001712 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1713 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714
1715 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001716 * Implement this to handle requests to delete one or more rows. The
1717 * implementation should apply the selection clause when performing
1718 * deletion, allowing the operation to affect multiple rows in a directory.
1719 * As a courtesy, call
1720 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1721 * notifyChange()} after deleting. This method can be called from multiple
1722 * threads, as described in <a href="
1723 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1724 * and Threads</a>.
1725 * <p>
1726 * The implementation is responsible for parsing out a row ID at the end of
1727 * the URI, if a specific row is being deleted. That is, the client would
1728 * pass in <code>content://contacts/people/22</code> and the implementation
1729 * is responsible for parsing the record number (22) when creating a SQL
1730 * statement.
1731 *
1732 * @param uri The full URI to query, including a row ID (if a specific
1733 * record is requested).
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001734 * @param extras A Bundle containing additional information necessary for
1735 * the operation. Arguments may include SQL style arguments, such
1736 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1737 * the documentation for each individual provider will indicate
1738 * which arguments they support.
1739 * @throws IllegalArgumentException if the provider doesn't support one of
1740 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001741 * @throws SQLException
1742 */
1743 @Override
1744 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1745 extras = (extras != null) ? extras : Bundle.EMPTY;
1746 return delete(uri,
1747 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1748 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1749 }
1750
1751 /**
1752 * Implement this to handle requests to update one or more rows. The
1753 * implementation should update all rows matching the selection to set the
1754 * columns according to the provided values map. As a courtesy, call
1755 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1756 * notifyChange()} after updating. This method can be called from multiple
1757 * threads, as described in <a href="
1758 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001759 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001761 * @param uri The URI to query. This can potentially have a record ID if
1762 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001763 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 * @param selection An optional filter to match rows to update.
1765 * @return the number of rows affected.
1766 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001767 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001768 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769
1770 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001771 * Implement this to handle requests to update one or more rows. The
1772 * implementation should update all rows matching the selection to set the
1773 * columns according to the provided values map. As a courtesy, call
1774 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1775 * notifyChange()} after updating. This method can be called from multiple
1776 * threads, as described in <a href="
1777 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1778 * and Threads</a>.
1779 *
1780 * @param uri The URI to query. This can potentially have a record ID if
1781 * this is an update request for a specific record.
1782 * @param values A set of column_name/value pairs to update in the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001783 * @param extras A Bundle containing additional information necessary for
1784 * the operation. Arguments may include SQL style arguments, such
1785 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1786 * the documentation for each individual provider will indicate
1787 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001788 * @return the number of rows affected.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001789 * @throws IllegalArgumentException if the provider doesn't support one of
1790 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001791 */
1792 @Override
1793 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1794 @Nullable Bundle extras) {
1795 extras = (extras != null) ? extras : Bundle.EMPTY;
1796 return update(uri, values,
1797 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1798 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1799 }
1800
1801 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001802 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001803 * The default implementation always throws {@link FileNotFoundException}.
1804 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001805 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1806 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001807 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001808 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1809 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001810 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 *
1812 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1813 * their responsibility to close it when done. That is, the implementation
1814 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001815 * <p>
1816 * If opened with the exclusive "r" or "w" modes, the returned
1817 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1818 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1819 * supports seeking.
1820 * <p>
1821 * If you need to detect when the returned ParcelFileDescriptor has been
1822 * closed, or if the remote process has crashed or encountered some other
1823 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1824 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1825 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1826 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001827 * <p>
1828 * If you need to return a large file that isn't backed by a real file on
1829 * disk, such as a file on a network share or cloud storage service,
1830 * consider using
1831 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1832 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001834 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1835 * to return the appropriate MIME type for the data returned here with
1836 * the same URI. This will allow intent resolution to automatically determine the data MIME
1837 * type and select the appropriate matching targets as part of its operation.</p>
1838 *
1839 * <p class="note">For better interoperability with other applications, it is recommended
1840 * that for any URIs that can be opened, you also support queries on them
1841 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1842 * You may also want to support other common columns if you have additional meta-data
1843 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1844 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1845 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 * @param uri The URI whose file is to be opened.
1847 * @param mode Access mode for the file. May be "r" for read-only access,
1848 * "rw" for read and write access, or "rwt" for read and write access
1849 * that truncates any existing file.
1850 *
1851 * @return Returns a new ParcelFileDescriptor which you can use to access
1852 * the file.
1853 *
1854 * @throws FileNotFoundException Throws FileNotFoundException if there is
1855 * no file associated with the given URI or the mode is invalid.
1856 * @throws SecurityException Throws SecurityException if the caller does
1857 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001858 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 * @see #openAssetFile(Uri, String)
1860 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001861 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001862 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001863 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001864 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 throws FileNotFoundException {
1866 throw new FileNotFoundException("No files supported by provider at "
1867 + uri);
1868 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001871 * Override this to handle requests to open a file blob.
1872 * The default implementation always throws {@link FileNotFoundException}.
1873 * This method can be called from multiple threads, as described in
1874 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1875 * and Threads</a>.
1876 *
1877 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1878 * to the caller. This way large data (such as images and documents) can be
1879 * returned without copying the content.
1880 *
1881 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1882 * their responsibility to close it when done. That is, the implementation
1883 * of this method should create a new ParcelFileDescriptor for each call.
1884 * <p>
1885 * If opened with the exclusive "r" or "w" modes, the returned
1886 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1887 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1888 * supports seeking.
1889 * <p>
1890 * If you need to detect when the returned ParcelFileDescriptor has been
1891 * closed, or if the remote process has crashed or encountered some other
1892 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1893 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1894 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1895 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1896 *
1897 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1898 * to return the appropriate MIME type for the data returned here with
1899 * the same URI. This will allow intent resolution to automatically determine the data MIME
1900 * type and select the appropriate matching targets as part of its operation.</p>
1901 *
1902 * <p class="note">For better interoperability with other applications, it is recommended
1903 * that for any URIs that can be opened, you also support queries on them
1904 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1905 * You may also want to support other common columns if you have additional meta-data
1906 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1907 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1908 *
1909 * @param uri The URI whose file is to be opened.
1910 * @param mode Access mode for the file. May be "r" for read-only access,
1911 * "w" for write-only access, "rw" for read and write access, or
1912 * "rwt" for read and write access that truncates any existing
1913 * file.
1914 * @param signal A signal to cancel the operation in progress, or
1915 * {@code null} if none. For example, if you are downloading a
1916 * file from the network to service a "rw" mode request, you
1917 * should periodically call
1918 * {@link CancellationSignal#throwIfCanceled()} to check whether
1919 * the client has canceled the request and abort the download.
1920 *
1921 * @return Returns a new ParcelFileDescriptor which you can use to access
1922 * the file.
1923 *
1924 * @throws FileNotFoundException Throws FileNotFoundException if there is
1925 * no file associated with the given URI or the mode is invalid.
1926 * @throws SecurityException Throws SecurityException if the caller does
1927 * not have permission to access the file.
1928 *
1929 * @see #openAssetFile(Uri, String)
1930 * @see #openFileHelper(Uri, String)
1931 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001932 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001933 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001934 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001935 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1936 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001937 return openFile(uri, mode);
1938 }
1939
1940 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 * This is like {@link #openFile}, but can be implemented by providers
1942 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001943 * inside of their .apk.
1944 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001945 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1946 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001947 *
1948 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001949 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001950 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1952 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1953 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001954 * <p>
1955 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1956 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001957 *
1958 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 * should create the AssetFileDescriptor with
1960 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001961 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001963 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1964 * to return the appropriate MIME type for the data returned here with
1965 * the same URI. This will allow intent resolution to automatically determine the data MIME
1966 * type and select the appropriate matching targets as part of its operation.</p>
1967 *
1968 * <p class="note">For better interoperability with other applications, it is recommended
1969 * that for any URIs that can be opened, you also support queries on them
1970 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1971 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 * @param uri The URI whose file is to be opened.
1973 * @param mode Access mode for the file. May be "r" for read-only access,
1974 * "w" for write-only access (erasing whatever data is currently in
1975 * the file), "wa" for write-only access to append to any existing data,
1976 * "rw" for read and write access on any existing data, and "rwt" for read
1977 * and write access that truncates any existing file.
1978 *
1979 * @return Returns a new AssetFileDescriptor which you can use to access
1980 * the file.
1981 *
1982 * @throws FileNotFoundException Throws FileNotFoundException if there is
1983 * no file associated with the given URI or the mode is invalid.
1984 * @throws SecurityException Throws SecurityException if the caller does
1985 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001986 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 * @see #openFile(Uri, String)
1988 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001989 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001991 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 throws FileNotFoundException {
1993 ParcelFileDescriptor fd = openFile(uri, mode);
1994 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1995 }
1996
1997 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001998 * This is like {@link #openFile}, but can be implemented by providers
1999 * that need to be able to return sub-sections of files, often assets
2000 * inside of their .apk.
2001 * This method can be called from multiple threads, as described in
2002 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2003 * and Threads</a>.
2004 *
2005 * <p>If you implement this, your clients must be able to deal with such
2006 * file slices, either directly with
2007 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
2008 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
2009 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
2010 * methods.
2011 * <p>
2012 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2013 * streaming of data.
2014 *
2015 * <p class="note">If you are implementing this to return a full file, you
2016 * should create the AssetFileDescriptor with
2017 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
2018 * applications that cannot handle sub-sections of files.</p>
2019 *
2020 * <p class="note">For use in Intents, you will want to implement {@link #getType}
2021 * to return the appropriate MIME type for the data returned here with
2022 * the same URI. This will allow intent resolution to automatically determine the data MIME
2023 * type and select the appropriate matching targets as part of its operation.</p>
2024 *
2025 * <p class="note">For better interoperability with other applications, it is recommended
2026 * that for any URIs that can be opened, you also support queries on them
2027 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
2028 *
2029 * @param uri The URI whose file is to be opened.
2030 * @param mode Access mode for the file. May be "r" for read-only access,
2031 * "w" for write-only access (erasing whatever data is currently in
2032 * the file), "wa" for write-only access to append to any existing data,
2033 * "rw" for read and write access on any existing data, and "rwt" for read
2034 * and write access that truncates any existing file.
2035 * @param signal A signal to cancel the operation in progress, or
2036 * {@code null} if none. For example, if you are downloading a
2037 * file from the network to service a "rw" mode request, you
2038 * should periodically call
2039 * {@link CancellationSignal#throwIfCanceled()} to check whether
2040 * the client has canceled the request and abort the download.
2041 *
2042 * @return Returns a new AssetFileDescriptor which you can use to access
2043 * the file.
2044 *
2045 * @throws FileNotFoundException Throws FileNotFoundException if there is
2046 * no file associated with the given URI or the mode is invalid.
2047 * @throws SecurityException Throws SecurityException if the caller does
2048 * not have permission to access the file.
2049 *
2050 * @see #openFile(Uri, String)
2051 * @see #openFileHelper(Uri, String)
2052 * @see #getType(android.net.Uri)
2053 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002054 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002055 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
2056 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002057 return openAssetFile(uri, mode);
2058 }
2059
2060 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 * Convenience for subclasses that wish to implement {@link #openFile}
2062 * by looking up a column named "_data" at the given URI.
2063 *
2064 * @param uri The URI to be opened.
2065 * @param mode The file mode. May be "r" for read-only access,
2066 * "w" for write-only access (erasing whatever data is currently in
2067 * the file), "wa" for write-only access to append to any existing data,
2068 * "rw" for read and write access on any existing data, and "rwt" for read
2069 * and write access that truncates any existing file.
2070 *
2071 * @return Returns a new ParcelFileDescriptor that can be used by the
2072 * client to access the file.
2073 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002074 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
2075 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
2077 int count = (c != null) ? c.getCount() : 0;
2078 if (count != 1) {
2079 // If there is not exactly one result, throw an appropriate
2080 // exception.
2081 if (c != null) {
2082 c.close();
2083 }
2084 if (count == 0) {
2085 throw new FileNotFoundException("No entry for " + uri);
2086 }
2087 throw new FileNotFoundException("Multiple items at " + uri);
2088 }
2089
2090 c.moveToFirst();
2091 int i = c.getColumnIndex("_data");
2092 String path = (i >= 0 ? c.getString(i) : null);
2093 c.close();
2094 if (path == null) {
2095 throw new FileNotFoundException("Column _data not found.");
2096 }
2097
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002098 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 return ParcelFileDescriptor.open(new File(path), modeBits);
2100 }
2101
2102 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002103 * Called by a client to determine the types of data streams that this
2104 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002105 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002106 * of a particular type, return that MIME type if it matches the given
2107 * mimeTypeFilter. If it can perform type conversions, return an array
2108 * of all supported MIME types that match mimeTypeFilter.
2109 *
2110 * @param uri The data in the content provider being queried.
2111 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002112 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002113 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002114 * given mimeTypeFilter. Otherwise returns an array of all available
2115 * concrete MIME types.
2116 *
2117 * @see #getType(Uri)
2118 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002119 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002120 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002121 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002122 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002123 return null;
2124 }
2125
2126 /**
2127 * Called by a client to open a read-only stream containing data of a
2128 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2129 * except the file can only be read-only and the content provider may
2130 * perform data conversions to generate data of the desired type.
2131 *
2132 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002133 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002134 * {@link #openAssetFile(Uri, String)}.
2135 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002136 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002137 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002138 * <p>
2139 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2140 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002141 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002142 * <p class="note">For better interoperability with other applications, it is recommended
2143 * that for any URIs that can be opened, you also support queries on them
2144 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2145 * You may also want to support other common columns if you have additional meta-data
2146 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2147 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2148 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002149 * @param uri The data in the content provider being queried.
2150 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002151 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002152 * requirements; in this case the content provider will pick its best
2153 * type matching the pattern.
2154 * @param opts Additional options from the client. The definitions of
2155 * these are specific to the content provider being called.
2156 *
2157 * @return Returns a new AssetFileDescriptor from which the client can
2158 * read data of the desired type.
2159 *
2160 * @throws FileNotFoundException Throws FileNotFoundException if there is
2161 * no file associated with the given URI or the mode is invalid.
2162 * @throws SecurityException Throws SecurityException if the caller does
2163 * not have permission to access the data.
2164 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2165 * content provider does not support the requested MIME type.
2166 *
2167 * @see #getStreamTypes(Uri, String)
2168 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002169 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002170 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002171 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2172 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002173 if ("*/*".equals(mimeTypeFilter)) {
2174 // If they can take anything, the untyped open call is good enough.
2175 return openAssetFile(uri, "r");
2176 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002177 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002178 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002179 // Use old untyped open call if this provider has a type for this
2180 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002181 return openAssetFile(uri, "r");
2182 }
2183 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2184 }
2185
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002186
2187 /**
2188 * Called by a client to open a read-only stream containing data of a
2189 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2190 * except the file can only be read-only and the content provider may
2191 * perform data conversions to generate data of the desired type.
2192 *
2193 * <p>The default implementation compares the given mimeType against the
2194 * result of {@link #getType(Uri)} and, if they match, simply calls
2195 * {@link #openAssetFile(Uri, String)}.
2196 *
2197 * <p>See {@link ClipData} for examples of the use and implementation
2198 * of this method.
2199 * <p>
2200 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2201 * streaming of data.
2202 *
2203 * <p class="note">For better interoperability with other applications, it is recommended
2204 * that for any URIs that can be opened, you also support queries on them
2205 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2206 * You may also want to support other common columns if you have additional meta-data
2207 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2208 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2209 *
2210 * @param uri The data in the content provider being queried.
2211 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002212 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002213 * requirements; in this case the content provider will pick its best
2214 * type matching the pattern.
2215 * @param opts Additional options from the client. The definitions of
2216 * these are specific to the content provider being called.
2217 * @param signal A signal to cancel the operation in progress, or
2218 * {@code null} if none. For example, if you are downloading a
2219 * file from the network to service a "rw" mode request, you
2220 * should periodically call
2221 * {@link CancellationSignal#throwIfCanceled()} to check whether
2222 * the client has canceled the request and abort the download.
2223 *
2224 * @return Returns a new AssetFileDescriptor from which the client can
2225 * read data of the desired type.
2226 *
2227 * @throws FileNotFoundException Throws FileNotFoundException if there is
2228 * no file associated with the given URI or the mode is invalid.
2229 * @throws SecurityException Throws SecurityException if the caller does
2230 * not have permission to access the data.
2231 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2232 * content provider does not support the requested MIME type.
2233 *
2234 * @see #getStreamTypes(Uri, String)
2235 * @see #openAssetFile(Uri, String)
2236 * @see ClipDescription#compareMimeTypes(String, String)
2237 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002238 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002239 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2240 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2241 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002242 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2243 }
2244
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002245 /**
2246 * Interface to write a stream of data to a pipe. Use with
2247 * {@link ContentProvider#openPipeHelper}.
2248 */
2249 public interface PipeDataWriter<T> {
2250 /**
2251 * Called from a background thread to stream data out to a pipe.
2252 * Note that the pipe is blocking, so this thread can block on
2253 * writes for an arbitrary amount of time if the client is slow
2254 * at reading.
2255 *
2256 * @param output The pipe where data should be written. This will be
2257 * closed for you upon returning from this function.
2258 * @param uri The URI whose data is to be written.
2259 * @param mimeType The desired type of data to be written.
2260 * @param opts Options supplied by caller.
2261 * @param args Your own custom arguments.
2262 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002263 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2264 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002265 }
2266
2267 /**
2268 * A helper function for implementing {@link #openTypedAssetFile}, for
2269 * creating a data pipe and background thread allowing you to stream
2270 * generated data back to the client. This function returns a new
2271 * ParcelFileDescriptor that should be returned to the caller (the caller
2272 * is responsible for closing it).
2273 *
2274 * @param uri The URI whose data is to be written.
2275 * @param mimeType The desired type of data to be written.
2276 * @param opts Options supplied by caller.
2277 * @param args Your own custom arguments.
2278 * @param func Interface implementing the function that will actually
2279 * stream the data.
2280 * @return Returns a new ParcelFileDescriptor holding the read side of
2281 * the pipe. This should be returned to the caller for reading; the caller
2282 * is responsible for closing it when done.
2283 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002284 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2285 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2286 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002287 try {
2288 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2289
2290 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2291 @Override
2292 protected Object doInBackground(Object... params) {
2293 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2294 try {
2295 fds[1].close();
2296 } catch (IOException e) {
2297 Log.w(TAG, "Failure closing pipe", e);
2298 }
2299 return null;
2300 }
2301 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002302 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002303
2304 return fds[0];
2305 } catch (IOException e) {
2306 throw new FileNotFoundException("failure making pipe");
2307 }
2308 }
2309
2310 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 * Returns true if this instance is a temporary content provider.
2312 * @return true if this instance is a temporary content provider
2313 */
2314 protected boolean isTemporary() {
2315 return false;
2316 }
2317
2318 /**
2319 * Returns the Binder object for this provider.
2320 *
2321 * @return the Binder object for this provider
2322 * @hide
2323 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002324 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 public IContentProvider getIContentProvider() {
2326 return mTransport;
2327 }
2328
2329 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002330 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2331 * when directly instantiating the provider for testing.
2332 * @hide
2333 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002334 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002335 public void attachInfoForTesting(Context context, ProviderInfo info) {
2336 attachInfo(context, info, true);
2337 }
2338
2339 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 * After being instantiated, this is called to tell the content provider
2341 * about itself.
2342 *
2343 * @param context The context this provider is running in
2344 * @param info Registered information about this content provider
2345 */
2346 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002347 attachInfo(context, info, false);
2348 }
2349
2350 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002351 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002352 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 /*
2355 * Only allow it to be set once, so after the content service gives
2356 * this to us clients can't change it.
2357 */
2358 if (mContext == null) {
2359 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002360 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002361 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2362 Context.APP_OPS_SERVICE);
2363 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002364 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 if (info != null) {
2366 setReadPermission(info.readPermission);
2367 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002368 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002369 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002370 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002371 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002373 if (Build.IS_DEBUGGABLE) {
2374 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2375 Log.VERBOSE));
2376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 ContentProvider.this.onCreate();
2378 }
2379 }
Fred Quintanace31b232009-05-04 16:01:15 -07002380
2381 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002382 * Override this to handle requests to perform a batch of operations, or the
2383 * default implementation will iterate over the operations and call
2384 * {@link ContentProviderOperation#apply} on each of them.
2385 * If all calls to {@link ContentProviderOperation#apply} succeed
2386 * then a {@link ContentProviderResult} array with as many
2387 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002388 * fail, it is up to the implementation how many of the others take effect.
2389 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002390 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2391 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002392 *
Fred Quintanace31b232009-05-04 16:01:15 -07002393 * @param operations the operations to apply
2394 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002395 * @throws OperationApplicationException thrown if any operation fails.
2396 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002397 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002398 @Override
2399 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2400 @NonNull ArrayList<ContentProviderOperation> operations)
2401 throws OperationApplicationException {
2402 return applyBatch(operations);
2403 }
2404
Jeff Sharkey673db442015-06-11 19:30:57 -07002405 public @NonNull ContentProviderResult[] applyBatch(
2406 @NonNull ArrayList<ContentProviderOperation> operations)
2407 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002408 final int numOperations = operations.size();
2409 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2410 for (int i = 0; i < numOperations; i++) {
2411 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002412 }
2413 return results;
2414 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002415
2416 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002417 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002418 * interfaces that are cheaper and/or unnatural for a table-like
2419 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002420 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002421 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2422 * on this entry into the content provider besides the basic ability for the application
2423 * to get access to the provider at all. For example, it has no idea whether the call
2424 * being executed may read or write data in the provider, so can't enforce those
2425 * individual permissions. Any implementation of this method <strong>must</strong>
2426 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2427 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002428 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2429 * @param arg provider-defined String argument. May be {@code null}.
2430 * @param extras provider-defined Bundle argument. May be {@code null}.
2431 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002432 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002433 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002434 @Override
2435 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2436 @Nullable String arg, @Nullable Bundle extras) {
2437 return call(method, arg, extras);
2438 }
2439
Jeff Sharkey673db442015-06-11 19:30:57 -07002440 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2441 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002442 return null;
2443 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002444
2445 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002446 * Implement this to shut down the ContentProvider instance. You can then
2447 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002448 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002449 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002450 * Android normally handles ContentProvider startup and shutdown
2451 * automatically. You do not need to start up or shut down a
2452 * ContentProvider. When you invoke a test method on a ContentProvider,
2453 * however, a ContentProvider instance is started and keeps running after
2454 * the test finishes, even if a succeeding test instantiates another
2455 * ContentProvider. A conflict develops because the two instances are
2456 * usually running against the same underlying data source (for example, an
2457 * sqlite database).
2458 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002459 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002460 * Implementing shutDown() avoids this conflict by providing a way to
2461 * terminate the ContentProvider. This method can also prevent memory leaks
2462 * from multiple instantiations of the ContentProvider, and it can ensure
2463 * unit test isolation by allowing you to completely clean up the test
2464 * fixture before moving on to the next test.
2465 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002466 */
2467 public void shutdown() {
2468 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2469 "connections are gracefully shutdown");
2470 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002471
2472 /**
2473 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002474 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002475 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002476 * @param fd The raw file descriptor that the dump is being sent to.
2477 * @param writer The PrintWriter to which you should dump your state. This will be
2478 * closed for you after you return.
2479 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002480 */
2481 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2482 writer.println("nothing to dump");
2483 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002484
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002485 private void validateIncomingAuthority(String authority) throws SecurityException {
2486 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2487 String message = "The authority " + authority + " does not match the one of the "
2488 + "contentProvider: ";
2489 if (mAuthority != null) {
2490 message += mAuthority;
2491 } else {
2492 message += Arrays.toString(mAuthorities);
2493 }
2494 throw new SecurityException(message);
2495 }
2496 }
2497
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002498 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002499 @VisibleForTesting
2500 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002501 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002502 if (!mSingleUser) {
2503 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2504 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2505 throw new SecurityException("trying to query a ContentProvider in user "
2506 + mContext.getUserId() + " with a uri belonging to user " + userId);
2507 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002508 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002509 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002510
2511 // Normalize the path by removing any empty path segments, which can be
2512 // a source of security issues.
2513 final String encodedPath = uri.getEncodedPath();
2514 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002515 final Uri normalized = uri.buildUpon()
2516 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2517 Log.w(TAG, "Normalized " + uri + " to " + normalized
2518 + " to avoid possible security issues");
2519 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002520 } else {
2521 return uri;
2522 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002523 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002524
2525 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002526 private Uri maybeGetUriWithoutUserId(Uri uri) {
2527 if (mSingleUser) {
2528 return uri;
2529 }
2530 return getUriWithoutUserId(uri);
2531 }
2532
2533 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002534 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2535 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002536 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002537 if (end == -1) return defaultUserId;
2538 String userIdString = auth.substring(0, end);
2539 try {
2540 return Integer.parseInt(userIdString);
2541 } catch (NumberFormatException e) {
2542 Log.w(TAG, "Error parsing userId.", e);
2543 return UserHandle.USER_NULL;
2544 }
2545 }
2546
2547 /** @hide */
2548 public static int getUserIdFromAuthority(String auth) {
2549 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2550 }
2551
2552 /** @hide */
2553 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2554 if (uri == null) return defaultUserId;
2555 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2556 }
2557
2558 /** @hide */
2559 public static int getUserIdFromUri(Uri uri) {
2560 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2561 }
2562
2563 /**
Alex Kershawba014ac2020-01-20 22:25:02 +00002564 * Returns the user associated with the given URI.
2565 *
2566 * @hide
2567 */
2568 @TestApi
2569 public @NonNull static UserHandle getUserHandleFromUri(@NonNull Uri uri) {
2570 return UserHandle.of(getUserIdFromUri(uri, Process.myUserHandle().getIdentifier()));
2571 }
2572
2573 /**
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002574 * Removes userId part from authority string. Expects format:
2575 * userId@some.authority
2576 * If there is no userId in the authority, it symply returns the argument
2577 * @hide
2578 */
2579 public static String getAuthorityWithoutUserId(String auth) {
2580 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002581 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002582 return auth.substring(end+1);
2583 }
2584
2585 /** @hide */
2586 public static Uri getUriWithoutUserId(Uri uri) {
2587 if (uri == null) return null;
2588 Uri.Builder builder = uri.buildUpon();
2589 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2590 return builder.build();
2591 }
2592
2593 /** @hide */
2594 public static boolean uriHasUserId(Uri uri) {
2595 if (uri == null) return false;
2596 return !TextUtils.isEmpty(uri.getUserInfo());
2597 }
2598
2599 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002600 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002601 public static Uri maybeAddUserId(Uri uri, int userId) {
2602 if (uri == null) return null;
2603 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002604 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002605 if (!uriHasUserId(uri)) {
2606 //We don't add the user Id if there's already one
2607 Uri.Builder builder = uri.buildUpon();
2608 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2609 return builder.build();
2610 }
2611 }
2612 return uri;
2613 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002614}