blob: c271e3c66adc8608292daa24dab53a4e29afb908 [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;
Ben Lin1cf454f2016-11-10 13:50:54 -080052import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060053import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070054import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060055import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010056import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070057import android.util.Log;
Philip P. Moltmann128b7032019-09-27 08:44:12 -070058import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060060import com.android.internal.annotations.VisibleForTesting;
61
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080063import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070065import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080066import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070067import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080068import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060069import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71/**
72 * Content providers are one of the primary building blocks of Android applications, providing
73 * content to applications. They encapsulate data and provide it to applications through the single
74 * {@link ContentResolver} interface. A content provider is only required if you need to share
75 * data between multiple applications. For example, the contacts data is used by multiple
76 * applications and must be stored in a content provider. If you don't need to share data amongst
77 * multiple applications you can use a database directly via
78 * {@link android.database.sqlite.SQLiteDatabase}.
79 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 * <p>When a request is made via
81 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
82 * request to the content provider registered with the authority. The content provider can interpret
83 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
84 * URIs.</p>
85 *
86 * <p>The primary methods that need to be implemented are:
87 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070088 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 * <li>{@link #query} which returns data to the caller</li>
90 * <li>{@link #insert} which inserts new data into the content provider</li>
91 * <li>{@link #update} which updates existing data in the content provider</li>
92 * <li>{@link #delete} which deletes data from the content provider</li>
93 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
94 * </ul></p>
95 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070096 * <p class="caution">Data access methods (such as {@link #insert} and
97 * {@link #update}) may be called from many threads at once, and must be thread-safe.
98 * Other methods (such as {@link #onCreate}) are only called from the application
99 * main thread, and must avoid performing lengthy operations. See the method
100 * descriptions for their expected thread behavior.</p>
101 *
102 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
103 * ContentProvider instance, so subclasses don't have to worry about the details of
104 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700105 *
106 * <div class="special reference">
107 * <h3>Developer Guides</h3>
108 * <p>For more information about using content providers, read the
109 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
110 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700111 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700113public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800114
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700115 private static final String TAG = "ContentProvider";
116
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900117 /*
118 * Note: if you add methods to ContentProvider, you must add similar methods to
119 * MockContentProvider.
120 */
121
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100122 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700124 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100125
126 // Since most Providers have only one authority, we keep both a String and a String[] to improve
127 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100128 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100129 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100130 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100131 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100132 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100134 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100136 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700137 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700138 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800139 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700140 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700142 private ThreadLocal<Pair<String, String>> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private Transport mTransport = new Transport();
145
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700146 /**
147 * Construct a ContentProvider instance. Content providers must be
148 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
149 * in the manifest</a>, accessed with {@link ContentResolver}, and created
150 * automatically by the system, so applications usually do not create
151 * ContentProvider instances directly.
152 *
153 * <p>At construction time, the object is uninitialized, and most fields and
154 * methods are unavailable. Subclasses should initialize themselves in
155 * {@link #onCreate}, not the constructor.
156 *
157 * <p>Content providers are created on the application main thread at
158 * application launch time. The constructor must not perform lengthy
159 * operations, or application startup will be delayed.
160 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900161 public ContentProvider() {
162 }
163
164 /**
165 * Constructor just for mocking.
166 *
167 * @param context A Context object which should be some mock instance (like the
168 * instance of {@link android.test.mock.MockContext}).
169 * @param readPermission The read permision you want this instance should have in the
170 * test, which is available via {@link #getReadPermission()}.
171 * @param writePermission The write permission you want this instance should have
172 * in the test, which is available via {@link #getWritePermission()}.
173 * @param pathPermissions The PathPermissions you want this instance should have
174 * in the test, which is available via {@link #getPathPermissions()}.
175 * @hide
176 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100177 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900178 public ContentProvider(
179 Context context,
180 String readPermission,
181 String writePermission,
182 PathPermission[] pathPermissions) {
183 mContext = context;
184 mReadPermission = readPermission;
185 mWritePermission = writePermission;
186 mPathPermissions = pathPermissions;
187 }
188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 /**
190 * Given an IContentProvider, try to coerce it back to the real
191 * ContentProvider object if it is running in the local process. This can
192 * be used if you know you are running in the same process as a provider,
193 * and want to get direct access to its implementation details. Most
194 * clients should not nor have a reason to use it.
195 *
196 * @param abstractInterface The ContentProvider interface that is to be
197 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800198 * @return If the IContentProvider is non-{@code null} and local, returns its actual
199 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 * @hide
201 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100202 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 public static ContentProvider coerceToLocalContentProvider(
204 IContentProvider abstractInterface) {
205 if (abstractInterface instanceof Transport) {
206 return ((Transport)abstractInterface).getContentProvider();
207 }
208 return null;
209 }
210
211 /**
212 * Binder object that deals with remoting.
213 *
214 * @hide
215 */
216 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700217 volatile AppOpsManager mAppOpsManager = null;
218 volatile int mReadOp = AppOpsManager.OP_NONE;
219 volatile int mWriteOp = AppOpsManager.OP_NONE;
220 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 ContentProvider getContentProvider() {
223 return ContentProvider.this;
224 }
225
Jeff Brownd2183652011-10-09 12:39:53 -0700226 @Override
227 public String getProviderName() {
228 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 }
230
Jeff Brown75ea64f2012-01-25 19:37:13 -0800231 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700232 public Cursor query(String callingPkg, @Nullable String featureId, Uri uri,
233 @Nullable String[] projection, @Nullable Bundle queryArgs,
234 @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600235 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100236 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700237 if (enforceReadPermission(callingPkg, featureId, uri, null)
238 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700239 // The caller has no access to the data, so return an empty cursor with
240 // the columns in the requested order. The caller may ask for an invalid
241 // column and we would not catch that but this is not a problem in practice.
242 // We do not call ContentProvider#query with a modified where clause since
243 // the implementation is not guaranteed to be backed by a SQL database, hence
244 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700245 if (projection != null) {
246 return new MatrixCursor(projection, 0);
247 }
248
249 // Null projection means all columns but we have no idea which they are.
250 // However, the caller may be expecting to access them my index. Hence,
251 // we have to execute the query as if allowed to get a cursor with the
252 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700253 Cursor cursor;
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700254 final Pair<String, String> original = setCallingPackage(
255 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700256 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700257 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700258 uri, projection, queryArgs,
259 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700260 } catch (RemoteException e) {
261 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700262 } finally {
263 setCallingPackage(original);
264 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700265 if (cursor == null) {
266 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700267 }
268
269 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700270 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800271 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600272 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700273 final Pair<String, String> original = setCallingPackage(
274 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700275 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700276 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800277 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700278 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700279 } catch (RemoteException e) {
280 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700281 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700282 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600283 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 }
286
Jeff Brown75ea64f2012-01-25 19:37:13 -0800287 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700289 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600290 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100291 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600292 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
293 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700294 return mInterface.getType(uri);
295 } catch (RemoteException e) {
296 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600297 } finally {
298 Trace.traceEnd(TRACE_TAG_DATABASE);
299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 }
301
Jeff Brown75ea64f2012-01-25 19:37:13 -0800302 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700303 public Uri insert(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700304 ContentValues initialValues, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600305 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100306 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100307 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700308 if (enforceWritePermission(callingPkg, featureId, uri, null)
309 != AppOpsManager.MODE_ALLOWED) {
310 final Pair<String, String> original = setCallingPackage(
311 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700312 try {
313 return rejectInsert(uri, initialValues);
314 } finally {
315 setCallingPackage(original);
316 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800317 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600318 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700319 final Pair<String, String> original = setCallingPackage(
320 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700321 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700322 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700323 } catch (RemoteException e) {
324 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700325 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700326 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600327 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 }
330
Jeff Brown75ea64f2012-01-25 19:37:13 -0800331 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700332 public int bulkInsert(String callingPkg, @Nullable String featureId, Uri uri,
333 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600334 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100335 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700336 if (enforceWritePermission(callingPkg, featureId, uri, null)
337 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800338 return 0;
339 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600340 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700341 final Pair<String, String> original = setCallingPackage(
342 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700343 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700344 return mInterface.bulkInsert(uri, initialValues);
345 } catch (RemoteException e) {
346 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700347 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700348 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600349 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
352
Jeff Brown75ea64f2012-01-25 19:37:13 -0800353 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700354 public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String featureId,
355 String authority, ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700356 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700357 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100358 int numOperations = operations.size();
359 final int[] userIds = new int[numOperations];
360 for (int i = 0; i < numOperations; i++) {
361 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100362 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600363 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600364 uri = validateIncomingUri(uri);
365 uri = maybeGetUriWithoutUserId(uri);
366 // Rebuild operation if we changed the Uri above
367 if (!Objects.equals(operation.getUri(), uri)) {
368 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100369 operations.set(i, operation);
370 }
Fred Quintana89437372009-05-15 15:10:40 -0700371 if (operation.isReadOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700372 if (enforceReadPermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800373 != AppOpsManager.MODE_ALLOWED) {
374 throw new OperationApplicationException("App op not allowed", 0);
375 }
Fred Quintana89437372009-05-15 15:10:40 -0700376 }
Fred Quintana89437372009-05-15 15:10:40 -0700377 if (operation.isWriteOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700378 if (enforceWritePermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800379 != AppOpsManager.MODE_ALLOWED) {
380 throw new OperationApplicationException("App op not allowed", 0);
381 }
Fred Quintana89437372009-05-15 15:10:40 -0700382 }
383 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600384 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700385 final Pair<String, String> original = setCallingPackage(
386 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700387 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700388 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700389 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800390 if (results != null) {
391 for (int i = 0; i < results.length ; i++) {
392 if (userIds[i] != UserHandle.USER_CURRENT) {
393 // Adding the userId to the uri.
394 results[i] = new ContentProviderResult(results[i], userIds[i]);
395 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100396 }
397 }
398 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700399 } catch (RemoteException e) {
400 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700402 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600403 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700404 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700405 }
406
Jeff Brown75ea64f2012-01-25 19:37:13 -0800407 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700408 public int delete(String callingPkg, @Nullable String featureId, Uri uri, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600409 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100410 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700411 if (enforceWritePermission(callingPkg, featureId, uri, null)
412 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800413 return 0;
414 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600415 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700416 final Pair<String, String> original = setCallingPackage(
417 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700418 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700419 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700420 } catch (RemoteException e) {
421 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700422 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600424 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 }
427
Jeff Brown75ea64f2012-01-25 19:37:13 -0800428 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700429 public int update(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700430 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600431 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100432 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700433 if (enforceWritePermission(callingPkg, featureId, uri, null)
434 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800435 return 0;
436 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600437 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700438 final Pair<String, String> original = setCallingPackage(
439 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700440 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700441 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700442 } catch (RemoteException e) {
443 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700444 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700445 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600446 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
449
Jeff Brown75ea64f2012-01-25 19:37:13 -0800450 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700451 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId,
452 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
453 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600454 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100455 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700456 enforceFilePermission(callingPkg, featureId, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600457 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700458 final Pair<String, String> original = setCallingPackage(
459 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700460 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700461 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700462 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700463 } catch (RemoteException e) {
464 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700465 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700466 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600467 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
470
Jeff Brown75ea64f2012-01-25 19:37:13 -0800471 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700472 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
473 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600475 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100476 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700477 enforceFilePermission(callingPkg, featureId, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600478 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700479 final Pair<String, String> original = setCallingPackage(
480 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700481 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700482 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700483 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700484 } catch (RemoteException e) {
485 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700486 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700487 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600488 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 }
491
Jeff Brown75ea64f2012-01-25 19:37:13 -0800492 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700493 public Bundle call(String callingPkg, @Nullable String featureId, String authority,
494 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700495 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600496 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600497 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700498 final Pair<String, String> original = setCallingPackage(
499 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700500 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700501 return mInterface.call(authority, method, arg, extras);
502 } catch (RemoteException e) {
503 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700504 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700505 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600506 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700507 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800508 }
509
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700510 @Override
511 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700512 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600513 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100514 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600515 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
516 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700517 return mInterface.getStreamTypes(uri, mimeTypeFilter);
518 } catch (RemoteException e) {
519 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600520 } finally {
521 Trace.traceEnd(TRACE_TAG_DATABASE);
522 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700523 }
524
525 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700526 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
527 @Nullable String featureId, Uri uri, String mimeType, Bundle opts,
528 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600529 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600530 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100531 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700532 enforceFilePermission(callingPkg, featureId, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600533 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700534 final Pair<String, String> original = setCallingPackage(
535 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700536 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700537 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700538 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700539 } catch (RemoteException e) {
540 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700541 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700542 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600543 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700544 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700545 }
546
Jeff Brown75ea64f2012-01-25 19:37:13 -0800547 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700548 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800549 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800550 }
551
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700552 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700553 public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600554 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100555 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100556 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700557 if (enforceReadPermission(callingPkg, featureId, uri, null)
558 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700559 return null;
560 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600561 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700562 final Pair<String, String> original = setCallingPackage(
563 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700564 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700565 return maybeAddUserId(mInterface.canonicalize(uri), userId);
566 } catch (RemoteException e) {
567 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700568 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700569 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600570 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700571 }
572 }
573
574 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700575 public Uri uncanonicalize(String callingPkg, String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600576 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100577 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100578 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700579 if (enforceReadPermission(callingPkg, featureId, uri, null)
580 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700581 return null;
582 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600583 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700584 final Pair<String, String> original = setCallingPackage(
585 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700586 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700587 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
588 } catch (RemoteException e) {
589 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700590 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700591 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600592 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700593 }
594 }
595
Ben Lin1cf454f2016-11-10 13:50:54 -0800596 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700597 public boolean refresh(String callingPkg, String featureId, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800598 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600599 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800600 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700601 if (enforceReadPermission(callingPkg, featureId, uri, null)
602 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800603 return false;
604 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600605 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700606 final Pair<String, String> original = setCallingPackage(
607 new Pair<>(callingPkg, featureId));
Ben Lin1cf454f2016-11-10 13:50:54 -0800608 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700609 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800610 CancellationSignal.fromTransport(cancellationSignal));
611 } finally {
612 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600613 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800614 }
615 }
616
Jeff Sharkey9edef252019-05-20 14:00:17 -0600617 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700618 public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri,
619 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600620 uri = validateIncomingUri(uri);
621 uri = maybeGetUriWithoutUserId(uri);
622 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700623 final Pair<String, String> original = setCallingPackage(
624 new Pair<>(callingPkg, featureId));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600625 try {
626 return mInterface.checkUriPermission(uri, uid, modeFlags);
627 } catch (RemoteException e) {
628 throw e.rethrowAsRuntimeException();
629 } finally {
630 setCallingPackage(original);
631 Trace.traceEnd(TRACE_TAG_DATABASE);
632 }
633 }
634
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700635 private void enforceFilePermission(String callingPkg, @Nullable String featureId, Uri uri,
636 String mode, IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800637 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700638 if (enforceWritePermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800639 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800640 throw new FileNotFoundException("App op not allowed");
641 }
642 } else {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700643 if (enforceReadPermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800644 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800645 throw new FileNotFoundException("App op not allowed");
646 }
647 }
648 }
649
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700650 private int enforceReadPermission(String callingPkg, @Nullable String featureId, Uri uri,
651 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800652 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700653 final int mode = enforceReadPermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700654 if (mode != MODE_ALLOWED) {
655 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800656 }
Svet Ganov99b60432015-06-27 13:15:22 -0700657
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700658 return noteProxyOp(callingPkg, featureId, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800659 }
660
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700661 private int enforceWritePermission(String callingPkg, String featureId, Uri uri,
662 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800663 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700664 final int mode = enforceWritePermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700665 if (mode != MODE_ALLOWED) {
666 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800667 }
Svet Ganov99b60432015-06-27 13:15:22 -0700668
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700669 return noteProxyOp(callingPkg, featureId, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700670 }
671
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700672 private int noteProxyOp(String callingPkg, String featureId, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700673 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700674 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
675 featureId, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700676 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700677 }
678
Dianne Hackborn35654b62013-01-14 17:38:02 -0800679 return AppOpsManager.MODE_ALLOWED;
680 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700681 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800682
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100683 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700684 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
685 return true;
686 }
687 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
688 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100689 == PERMISSION_GRANTED;
690 }
691
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700692 /**
693 * Verify that calling app holds both the given permission and any app-op
694 * associated with that permission.
695 */
696 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700697 @Nullable String featureId, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700698 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
699 callerToken) != PERMISSION_GRANTED) {
700 return MODE_ERRORED;
701 }
702
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700703 return mTransport.noteProxyOp(callingPkg, featureId,
704 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700705 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700706
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700707 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700708 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
709 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700710 final Context context = getContext();
711 final int pid = Binder.getCallingPid();
712 final int uid = Binder.getCallingUid();
713 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700714 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700715
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700716 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700717 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700718 }
719
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100720 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700721 final String componentPerm = getReadPermission();
722 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700723 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
724 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700725 if (mode == MODE_ALLOWED) {
726 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700727 } else {
728 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700729 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700730 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700731 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700732
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700733 // track if unprotected read is allowed; any denied
734 // <path-permission> below removes this ability
735 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700736
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700737 final PathPermission[] pps = getPathPermissions();
738 if (pps != null) {
739 final String path = uri.getPath();
740 for (PathPermission pp : pps) {
741 final String pathPerm = pp.getReadPermission();
742 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700743 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
744 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700745 if (mode == MODE_ALLOWED) {
746 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700747 } else {
748 // any denied <path-permission> means we lose
749 // default <provider> access.
750 allowDefaultRead = false;
751 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700752 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700753 }
754 }
755 }
756 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700757
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700758 // if we passed <path-permission> checks above, and no default
759 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700760 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700762
763 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800764 final int callingUserId = UserHandle.getUserId(uid);
765 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
766 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800767 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
768 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700769 return MODE_ALLOWED;
770 }
771
772 // If the worst denial we found above was ignored, then pass that
773 // ignored through; otherwise we assume it should be a real error below.
774 if (strongestMode == MODE_IGNORED) {
775 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700776 }
777
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600778 final String suffix;
779 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
780 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
781 } else if (mExported) {
782 suffix = " requires " + missingPerm + ", or grantUriPermission()";
783 } else {
784 suffix = " requires the provider be exported, or grantUriPermission()";
785 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700786 throw new SecurityException("Permission Denial: reading "
787 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600788 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700789 }
790
791 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700792 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
793 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700794 final Context context = getContext();
795 final int pid = Binder.getCallingPid();
796 final int uid = Binder.getCallingUid();
797 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700798 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700799
800 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700801 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700802 }
803
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100804 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700805 final String componentPerm = getWritePermission();
806 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700807 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
808 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700809 if (mode == MODE_ALLOWED) {
810 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700811 } else {
812 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700813 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700814 }
815 }
816
817 // track if unprotected write is allowed; any denied
818 // <path-permission> below removes this ability
819 boolean allowDefaultWrite = (componentPerm == null);
820
821 final PathPermission[] pps = getPathPermissions();
822 if (pps != null) {
823 final String path = uri.getPath();
824 for (PathPermission pp : pps) {
825 final String pathPerm = pp.getWritePermission();
826 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700827 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
828 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700829 if (mode == MODE_ALLOWED) {
830 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700831 } else {
832 // any denied <path-permission> means we lose
833 // default <provider> access.
834 allowDefaultWrite = false;
835 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700836 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700837 }
838 }
839 }
840 }
841
842 // if we passed <path-permission> checks above, and no default
843 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700844 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700845 }
846
847 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800848 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
849 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700850 return MODE_ALLOWED;
851 }
852
853 // If the worst denial we found above was ignored, then pass that
854 // ignored through; otherwise we assume it should be a real error below.
855 if (strongestMode == MODE_IGNORED) {
856 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700857 }
858
859 final String failReason = mExported
860 ? " requires " + missingPerm + ", or grantUriPermission()"
861 : " requires the provider be exported, or grantUriPermission()";
862 throw new SecurityException("Permission Denial: writing "
863 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
864 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 }
866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700868 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800869 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 * constructor.
871 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700872 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 return mContext;
874 }
875
876 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700877 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
878 * after {@link #onCreate}. When called before context was created, an IllegalStateException
879 * will be thrown.
880 * <p>
881 * Note A provider must be declared in the manifest and created automatically by the system,
882 * and context is only available after {@link #onCreate} is called.
883 */
884 @NonNull
885 public final Context requireContext() {
886 final Context ctx = getContext();
887 if (ctx == null) {
888 throw new IllegalStateException("Cannot find context from the provider.");
889 }
890 return ctx;
891 }
892
893 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700894 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700895 * which can be used later to restore the previous state.
896 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700897 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
898 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700899 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600900 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700901 return original;
902 }
903
904 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700905 * Return the package name of the caller that initiated the request being
906 * processed on the current thread. The returned package will have been
907 * verified to belong to the calling UID. Returns {@code null} if not
908 * currently processing a request.
909 * <p>
910 * This will always return {@code null} when processing
911 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
912 *
913 * @see Binder#getCallingUid()
914 * @see Context#grantUriPermission(String, Uri, int)
915 * @throws SecurityException if the calling package doesn't belong to the
916 * calling UID.
917 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700918 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700919 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700920 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700921 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
922 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700923 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700924
925 return null;
926 }
927
928 /**
929 * Return the feature in the package of the caller that initiated the request being
930 * processed on the current thread. Returns {@code null} if not currently processing
931 * a request of the request is for the default feature.
932 * <p>
933 * This will always return {@code null} when processing
934 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
935 *
936 * @see #getCallingPackage
937 */
938 public final @Nullable String getCallingFeatureId() {
939 final Pair<String, String> pkg = mCallingPackage.get();
940 if (pkg != null) {
941 return pkg.second;
942 }
943
944 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700945 }
946
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700947 /**
948 * Return the package name of the caller that initiated the request being
949 * processed on the current thread. The returned package will have
950 * <em>not</em> been verified to belong to the calling UID. Returns
951 * {@code null} if not currently processing a request.
952 * <p>
953 * This will always return {@code null} when processing
954 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
955 *
956 * @see Binder#getCallingUid()
957 * @see Context#grantUriPermission(String, Uri, int)
958 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600959 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700960 final Pair<String, String> pkg = mCallingPackage.get();
961 if (pkg != null) {
962 return pkg.first;
963 }
964
965 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600966 }
967
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700968 /**
969 * Called whenever the value of {@link #getCallingPackage()} changes, giving
970 * the provider an opportunity to invalidate any security related caching it
971 * may be performing.
972 * <p>
973 * This typically happens when a {@link ContentProvider} makes a nested call
974 * back into itself when already processing a call from a remote process.
975 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600976 public void onCallingPackageChanged() {
977 }
978
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700979 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600980 * Opaque token representing the identity of an incoming IPC.
981 */
982 public final class CallingIdentity {
983 /** {@hide} */
984 public final long binderToken;
985 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700986 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600987
988 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700989 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600990 this.binderToken = binderToken;
991 this.callingPackage = callingPackage;
992 }
993 }
994
995 /**
996 * Reset the identity of the incoming IPC on the current thread.
997 * <p>
998 * Internally this calls {@link Binder#clearCallingIdentity()} and also
999 * clears any value stored in {@link #getCallingPackage()}.
1000 *
1001 * @return Returns an opaque token that can be used to restore the original
1002 * calling identity by passing it to
1003 * {@link #restoreCallingIdentity}.
1004 */
1005 public final @NonNull CallingIdentity clearCallingIdentity() {
1006 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
1007 }
1008
1009 /**
1010 * Restore the identity of the incoming IPC on the current thread back to a
1011 * previously identity that was returned by {@link #clearCallingIdentity}.
1012 * <p>
1013 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
1014 * also restores any value stored in {@link #getCallingPackage()}.
1015 */
1016 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
1017 Binder.restoreCallingIdentity(identity.binderToken);
1018 mCallingPackage.set(identity.callingPackage);
1019 }
1020
1021 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001022 * Change the authorities of the ContentProvider.
1023 * This is normally set for you from its manifest information when the provider is first
1024 * created.
1025 * @hide
1026 * @param authorities the semi-colon separated authorities of the ContentProvider.
1027 */
1028 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001029 if (authorities != null) {
1030 if (authorities.indexOf(';') == -1) {
1031 mAuthority = authorities;
1032 mAuthorities = null;
1033 } else {
1034 mAuthority = null;
1035 mAuthorities = authorities.split(";");
1036 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001037 }
1038 }
1039
1040 /** @hide */
1041 protected final boolean matchesOurAuthorities(String authority) {
1042 if (mAuthority != null) {
1043 return mAuthority.equals(authority);
1044 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001045 if (mAuthorities != null) {
1046 int length = mAuthorities.length;
1047 for (int i = 0; i < length; i++) {
1048 if (mAuthorities[i].equals(authority)) return true;
1049 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001050 }
1051 return false;
1052 }
1053
1054
1055 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 * Change the permission required to read data from the content
1057 * provider. This is normally set for you from its manifest information
1058 * when the provider is first created.
1059 *
1060 * @param permission Name of the permission required for read-only access.
1061 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001062 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 mReadPermission = permission;
1064 }
1065
1066 /**
1067 * Return the name of the permission required for read-only access to
1068 * this content provider. This method can be called from multiple
1069 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001070 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1071 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001073 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 return mReadPermission;
1075 }
1076
1077 /**
1078 * Change the permission required to read and write data in the content
1079 * provider. This is normally set for you from its manifest information
1080 * when the provider is first created.
1081 *
1082 * @param permission Name of the permission required for read/write access.
1083 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001084 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 mWritePermission = permission;
1086 }
1087
1088 /**
1089 * Return the name of the permission required for read/write access to
1090 * this content provider. This method can be called from multiple
1091 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001092 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1093 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001095 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 return mWritePermission;
1097 }
1098
1099 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001100 * Change the path-based permission required to read and/or write data in
1101 * the content provider. This is normally set for you from its manifest
1102 * information when the provider is first created.
1103 *
1104 * @param permissions Array of path permission descriptions.
1105 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001106 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001107 mPathPermissions = permissions;
1108 }
1109
1110 /**
1111 * Return the path-based permissions required for read and/or write access to
1112 * this content provider. This method can be called from multiple
1113 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001114 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1115 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001116 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001117 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001118 return mPathPermissions;
1119 }
1120
Dianne Hackborn35654b62013-01-14 17:38:02 -08001121 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001122 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001123 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001124 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001125 mTransport.mReadOp = readOp;
1126 mTransport.mWriteOp = writeOp;
1127 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001128 }
1129
Dianne Hackborn961321f2013-02-05 17:22:41 -08001130 /** @hide */
1131 public AppOpsManager getAppOpsManager() {
1132 return mTransport.mAppOpsManager;
1133 }
1134
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001135 /** @hide */
1136 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001137 if (mTransport == null) {
1138 return;
1139 }
1140 if (enabled) {
1141 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1142 } else {
1143 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001144 }
1145 }
1146
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001147 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001148 * Implement this to initialize your content provider on startup.
1149 * This method is called for all registered content providers on the
1150 * application main thread at application launch time. It must not perform
1151 * lengthy operations, or application startup will be delayed.
1152 *
1153 * <p>You should defer nontrivial initialization (such as opening,
1154 * upgrading, and scanning databases) until the content provider is used
1155 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1156 * keeps application startup fast, avoids unnecessary work if the provider
1157 * turns out not to be needed, and stops database errors (such as a full
1158 * disk) from halting application launch.
1159 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001160 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001161 * is a helpful utility class that makes it easy to manage databases,
1162 * and will automatically defer opening until first use. If you do use
1163 * SQLiteOpenHelper, make sure to avoid calling
1164 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1165 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1166 * from this method. (Instead, override
1167 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1168 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 *
1170 * @return true if the provider was successfully loaded, false otherwise
1171 */
1172 public abstract boolean onCreate();
1173
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001174 /**
1175 * {@inheritDoc}
1176 * This method is always called on the application main thread, and must
1177 * not perform lengthy operations.
1178 *
1179 * <p>The default content provider implementation does nothing.
1180 * Override this method to take appropriate action.
1181 * (Content providers do not usually care about things like screen
1182 * orientation, but may want to know about locale changes.)
1183 */
Steve McKayea93fe72016-12-02 11:35:35 -08001184 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 public void onConfigurationChanged(Configuration newConfig) {
1186 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001187
1188 /**
1189 * {@inheritDoc}
1190 * This method is always called on the application main thread, and must
1191 * not perform lengthy operations.
1192 *
1193 * <p>The default content provider implementation does nothing.
1194 * Subclasses may override this method to take appropriate action.
1195 */
Steve McKayea93fe72016-12-02 11:35:35 -08001196 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 public void onLowMemory() {
1198 }
1199
Steve McKayea93fe72016-12-02 11:35:35 -08001200 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001201 public void onTrimMemory(int level) {
1202 }
1203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001205 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001206 *
1207 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1208 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1209 * implementation of this method.
1210 *
1211 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001212 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1213 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 * <p>
1215 * Example client call:<p>
1216 * <pre>// Request a specific record.
1217 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001218 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 projection, // Which columns to return.
1220 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001221 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 People.NAME + " ASC"); // Sort order.</pre>
1223 * Example implementation:<p>
1224 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1225 // proper SQL syntax for us.
1226 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1227
1228 // Set the table we're querying.
1229 qBuilder.setTables(DATABASE_TABLE_NAME);
1230
1231 // If the query ends in a specific record number, we're
1232 // being asked for a specific record, so set the
1233 // WHERE clause in our query.
1234 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1235 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1236 }
1237
1238 // Make the query.
1239 Cursor c = qBuilder.query(mDb,
1240 projection,
1241 selection,
1242 selectionArgs,
1243 groupBy,
1244 having,
1245 sortOrder);
1246 c.setNotificationUri(getContext().getContentResolver(), uri);
1247 return c;</pre>
1248 *
1249 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001250 * if the client is requesting a specific record, the URI will end in a record number
1251 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1252 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001254 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001256 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001257 * @param selectionArgs You may include ?s in selection, which will be replaced by
1258 * the values from selectionArgs, in order that they appear in the selection.
1259 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001261 * If {@code null} then the provider is free to define the sort order.
1262 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001264 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1265 @Nullable String selection, @Nullable String[] selectionArgs,
1266 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267
Fred Quintana5bba6322009-10-05 14:21:12 -07001268 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001269 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001270 *
1271 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1272 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1273 *
1274 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001275 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1276 * and Threads</a>.
1277 * <p>
1278 * Example client call:<p>
1279 * <pre>// Request a specific record.
1280 * Cursor managedCursor = managedQuery(
1281 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1282 projection, // Which columns to return.
1283 null, // WHERE clause.
1284 null, // WHERE clause value substitution
1285 People.NAME + " ASC"); // Sort order.</pre>
1286 * Example implementation:<p>
1287 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1288 // proper SQL syntax for us.
1289 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1290
1291 // Set the table we're querying.
1292 qBuilder.setTables(DATABASE_TABLE_NAME);
1293
1294 // If the query ends in a specific record number, we're
1295 // being asked for a specific record, so set the
1296 // WHERE clause in our query.
1297 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1298 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1299 }
1300
1301 // Make the query.
1302 Cursor c = qBuilder.query(mDb,
1303 projection,
1304 selection,
1305 selectionArgs,
1306 groupBy,
1307 having,
1308 sortOrder);
1309 c.setNotificationUri(getContext().getContentResolver(), uri);
1310 return c;</pre>
1311 * <p>
1312 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001313 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1314 * signal to ensure correct operation on older versions of the Android Framework in
1315 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001316 *
1317 * @param uri The URI to query. This will be the full URI sent by the client;
1318 * if the client is requesting a specific record, the URI will end in a record number
1319 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1320 * that _id value.
1321 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001322 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001323 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001324 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001325 * @param selectionArgs You may include ?s in selection, which will be replaced by
1326 * the values from selectionArgs, in order that they appear in the selection.
1327 * The values will be bound as Strings.
1328 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001329 * If {@code null} then the provider is free to define the sort order.
1330 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001331 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001332 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001333 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001334 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001335 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1336 @Nullable String selection, @Nullable String[] selectionArgs,
1337 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001338 return query(uri, projection, selection, selectionArgs, sortOrder);
1339 }
1340
1341 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001342 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1343 * Arguments may include traditional SQL style query arguments. When present these
1344 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001345 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001346 *
1347 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001348 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1349 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1350 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001351 *
Steve McKay76b27702017-04-24 12:07:53 -07001352 * <p>This method can be called from multiple threads, as described in
1353 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1354 * and Threads</a>.
1355 *
1356 * <p>
1357 * Example client call:<p>
1358 * <pre>// Request 20 records starting at row index 30.
1359 Bundle queryArgs = new Bundle();
1360 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1361 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1362
1363 Cursor cursor = getContentResolver().query(
1364 contentUri, // Content Uri is specific to individual content providers.
1365 projection, // String[] describing which columns to return.
1366 queryArgs, // Query arguments.
1367 null); // Cancellation signal.</pre>
1368 *
1369 * Example implementation:<p>
1370 * <pre>
1371
1372 int recordsetSize = 0x1000; // Actual value is implementation specific.
1373 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1374
1375 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1376 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1377
1378 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1379
1380 // Calculate the number of items to include in the cursor.
1381 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1382
1383 // Build the paged result set....
1384 for (int i = offset; i < offset + numItems; i++) {
1385 // populate row from your data.
1386 }
1387
1388 Bundle extras = new Bundle();
1389 c.setExtras(extras);
1390
1391 // Any QUERY_ARG_* key may be included if honored.
1392 // In an actual implementation, include only keys that are both present in queryArgs
1393 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1394 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1395 // then QUERY_ARG_OFFSET should be omitted.
1396 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1397 ContentResolver.QUERY_ARG_OFFSET,
1398 ContentResolver.QUERY_ARG_LIMIT
1399 });
1400
1401 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1402
1403 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1404
1405 return cursor;</pre>
1406 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001407 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1408 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001409 *
1410 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001411 * @param projection The list of columns to put into the cursor.
1412 * If {@code null} provide a default set of columns.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001413 * @param queryArgs A Bundle containing additional information necessary for
1414 * the operation. Arguments may include SQL style arguments, such
1415 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1416 * the documentation for each individual provider will indicate
1417 * which arguments they support.
Steve McKayea93fe72016-12-02 11:35:35 -08001418 * @param cancellationSignal A signal to cancel the operation in progress,
1419 * or {@code null}.
1420 * @return a Cursor or {@code null}.
1421 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001422 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001423 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1424 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1425 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001426
Steve McKayd7ece9f2017-01-12 16:59:59 -08001427 // if client doesn't supply an SQL sort order argument, attempt to build one from
1428 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001429 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001430 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1431 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1432 }
1433
Steve McKayea93fe72016-12-02 11:35:35 -08001434 return query(
1435 uri,
1436 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001437 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1438 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1439 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001440 cancellationSignal);
1441 }
1442
1443 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001444 * Implement this to handle requests for the MIME type of the data at the
1445 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 * <code>vnd.android.cursor.item</code> for a single record,
1447 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001448 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001449 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1450 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001452 * <p>Note that there are no permissions needed for an application to
1453 * access this information; if your content provider requires read and/or
1454 * write permissions, or is not exported, all applications can still call
1455 * this method regardless of their access permissions. This allows them
1456 * to retrieve the MIME type for a URI when dispatching intents.
1457 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001459 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001461 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001462 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463
1464 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001465 * Implement this to support canonicalization of URIs that refer to your
1466 * content provider. A canonical URI is one that can be transported across
1467 * devices, backup/restore, and other contexts, and still be able to refer
1468 * to the same data item. Typically this is implemented by adding query
1469 * params to the URI allowing the content provider to verify that an incoming
1470 * canonical URI references the same data as it was originally intended for and,
1471 * if it doesn't, to find that data (if it exists) in the current environment.
1472 *
1473 * <p>For example, if the content provider holds people and a normal URI in it
1474 * is created with a row index into that people database, the cananical representation
1475 * may have an additional query param at the end which specifies the name of the
1476 * person it is intended for. Later calls into the provider with that URI will look
1477 * up the row of that URI's base index and, if it doesn't match or its entry's
1478 * name doesn't match the name in the query param, perform a query on its database
1479 * to find the correct row to operate on.</p>
1480 *
1481 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1482 * URIs (including this one) must perform this verification and recovery of any
1483 * canonical URIs they receive. In addition, you must also implement
1484 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1485 *
1486 * <p>The default implementation of this method returns null, indicating that
1487 * canonical URIs are not supported.</p>
1488 *
1489 * @param url The Uri to canonicalize.
1490 *
1491 * @return Return the canonical representation of <var>url</var>, or null if
1492 * canonicalization of that Uri is not supported.
1493 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001494 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001495 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001496 return null;
1497 }
1498
1499 /**
1500 * Remove canonicalization from canonical URIs previously returned by
1501 * {@link #canonicalize}. For example, if your implementation is to add
1502 * a query param to canonicalize a URI, this method can simply trip any
1503 * query params on the URI. The default implementation always returns the
1504 * same <var>url</var> that was passed in.
1505 *
1506 * @param url The Uri to remove any canonicalization from.
1507 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001508 * @return Return the non-canonical representation of <var>url</var>, return
1509 * the <var>url</var> as-is if there is nothing to do, or return null if
1510 * the data identified by the canonical representation can not be found in
1511 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001512 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001513 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001514 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001515 return url;
1516 }
1517
1518 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001519 * Implement this to support refresh of content identified by {@code uri}.
1520 * By default, this method returns false; providers who wish to implement
1521 * this should return true to signal the client that the provider has tried
1522 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001523 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001524 * This allows clients to request an explicit refresh of content identified
1525 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001526 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001527 * Client code should only invoke this method when there is a strong
1528 * indication (such as a user initiated pull to refresh gesture) that the
1529 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001530 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001531 * Remember to send
1532 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001533 * notifications when content changes.
1534 *
1535 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001536 * @param extras Additional options from the client. The definitions of
1537 * these are specific to the content provider being called.
1538 * @param cancellationSignal A signal to cancel the operation in progress,
1539 * or {@code null} if none. For example, if you called refresh on
1540 * a particular uri, you should call
1541 * {@link CancellationSignal#throwIfCanceled()} to check whether
1542 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001543 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001544 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001545 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001546 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001547 @Nullable CancellationSignal cancellationSignal) {
1548 return false;
1549 }
1550
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001551 /**
1552 * Perform a detailed internal check on a {@link Uri} to determine if a UID
1553 * is able to access it with specific mode flags.
1554 * <p>
1555 * This method is typically used when the provider implements more dynamic
1556 * access controls that cannot be expressed with {@code <path-permission>}
1557 * style static rules.
1558 *
1559 * @param uri the {@link Uri} to perform an access check on.
1560 * @param uid the UID to check the permission for.
1561 * @param modeFlags the access flags to use for the access check, such as
1562 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}.
1563 * @return {@link PackageManager#PERMISSION_GRANTED} if access is allowed,
1564 * otherwise {@link PackageManager#PERMISSION_DENIED}.
1565 * @hide
1566 */
Jeff Sharkey9edef252019-05-20 14:00:17 -06001567 @Override
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001568 @SystemApi
Jeff Sharkey9edef252019-05-20 14:00:17 -06001569 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1570 return PackageManager.PERMISSION_DENIED;
1571 }
1572
Ben Lin1cf454f2016-11-10 13:50:54 -08001573 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001574 * @hide
1575 * Implementation when a caller has performed an insert on the content
1576 * provider, but that call has been rejected for the operation given
1577 * to {@link #setAppOps(int, int)}. The default implementation simply
1578 * returns a dummy URI that is the base URI with a 0 path element
1579 * appended.
1580 */
1581 public Uri rejectInsert(Uri uri, ContentValues values) {
1582 // If not allowed, we need to return some reasonable URI. Maybe the
1583 // content provider should be responsible for this, but for now we
1584 // will just return the base URI with a dummy '0' tagged on to it.
1585 // You shouldn't be able to read if you can't write, anyway, so it
1586 // shouldn't matter much what is returned.
1587 return uri.buildUpon().appendPath("0").build();
1588 }
1589
1590 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001591 * Implement this to handle requests to insert a new row. As a courtesy,
1592 * call
1593 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1594 * notifyChange()} after inserting. This method can be called from multiple
1595 * threads, as described in <a href="
1596 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001597 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001598 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001599 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 * @param values A set of column_name/value pairs to add to the database.
1601 * @return The URI for the newly inserted item.
1602 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001603 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604
1605 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001606 * Implement this to handle requests to insert a new row. As a courtesy,
1607 * call
1608 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1609 * notifyChange()} after inserting. This method can be called from multiple
1610 * threads, as described in <a href="
1611 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1612 * and Threads</a>.
1613 *
1614 * @param uri The content:// URI of the insertion request.
1615 * @param values A set of column_name/value pairs to add to the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001616 * @param extras A Bundle containing additional information necessary for
1617 * the operation. Arguments may include SQL style arguments, such
1618 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1619 * the documentation for each individual provider will indicate
1620 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001621 * @return The URI for the newly inserted item.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001622 * @throws IllegalArgumentException if the provider doesn't support one of
1623 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001624 */
1625 @Override
1626 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1627 @Nullable Bundle extras) {
1628 return insert(uri, values);
1629 }
1630
1631 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001632 * Override this to handle requests to insert a set of new rows, or the
1633 * default implementation will iterate over the values and call
1634 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1636 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001637 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001638 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1639 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 *
1641 * @param uri The content:// URI of the insertion request.
1642 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001643 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 * @return The number of values that were inserted.
1645 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001646 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001647 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 int numValues = values.length;
1649 for (int i = 0; i < numValues; i++) {
1650 insert(uri, values[i]);
1651 }
1652 return numValues;
1653 }
1654
1655 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001656 * Implement this to handle requests to delete one or more rows. The
1657 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001658 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001659 * As a courtesy, call
1660 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1661 * notifyChange()} after deleting. This method can be called from multiple
1662 * threads, as described in <a href="
1663 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001664 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001665 * <p>
1666 * The implementation is responsible for parsing out a row ID at the end of
1667 * the URI, if a specific row is being deleted. That is, the client would
1668 * pass in <code>content://contacts/people/22</code> and the implementation
1669 * is responsible for parsing the record number (22) when creating a SQL
1670 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001672 * @param uri The full URI to query, including a row ID (if a specific
1673 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 * @param selection An optional restriction to apply to rows when deleting.
1675 * @return The number of rows affected.
1676 * @throws SQLException
1677 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001678 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1679 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680
1681 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001682 * Implement this to handle requests to delete one or more rows. The
1683 * implementation should apply the selection clause when performing
1684 * deletion, allowing the operation to affect multiple rows in a directory.
1685 * As a courtesy, call
1686 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1687 * notifyChange()} after deleting. This method can be called from multiple
1688 * threads, as described in <a href="
1689 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1690 * and Threads</a>.
1691 * <p>
1692 * The implementation is responsible for parsing out a row ID at the end of
1693 * the URI, if a specific row is being deleted. That is, the client would
1694 * pass in <code>content://contacts/people/22</code> and the implementation
1695 * is responsible for parsing the record number (22) when creating a SQL
1696 * statement.
1697 *
1698 * @param uri The full URI to query, including a row ID (if a specific
1699 * record is requested).
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001700 * @param extras A Bundle containing additional information necessary for
1701 * the operation. Arguments may include SQL style arguments, such
1702 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1703 * the documentation for each individual provider will indicate
1704 * which arguments they support.
1705 * @throws IllegalArgumentException if the provider doesn't support one of
1706 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001707 * @throws SQLException
1708 */
1709 @Override
1710 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1711 extras = (extras != null) ? extras : Bundle.EMPTY;
1712 return delete(uri,
1713 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1714 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1715 }
1716
1717 /**
1718 * Implement this to handle requests to update one or more rows. The
1719 * implementation should update all rows matching the selection to set the
1720 * columns according to the provided values map. As a courtesy, call
1721 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1722 * notifyChange()} after updating. This method can be called from multiple
1723 * threads, as described in <a href="
1724 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001725 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001727 * @param uri The URI to query. This can potentially have a record ID if
1728 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001729 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 * @param selection An optional filter to match rows to update.
1731 * @return the number of rows affected.
1732 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001733 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001734 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735
1736 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001737 * Implement this to handle requests to update one or more rows. The
1738 * implementation should update all rows matching the selection to set the
1739 * columns according to the provided values map. As a courtesy, call
1740 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1741 * notifyChange()} after updating. This method can be called from multiple
1742 * threads, as described in <a href="
1743 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1744 * and Threads</a>.
1745 *
1746 * @param uri The URI to query. This can potentially have a record ID if
1747 * this is an update request for a specific record.
1748 * @param values A set of column_name/value pairs to update in the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001749 * @param extras A Bundle containing additional information necessary for
1750 * the operation. Arguments may include SQL style arguments, such
1751 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1752 * the documentation for each individual provider will indicate
1753 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001754 * @return the number of rows affected.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001755 * @throws IllegalArgumentException if the provider doesn't support one of
1756 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001757 */
1758 @Override
1759 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1760 @Nullable Bundle extras) {
1761 extras = (extras != null) ? extras : Bundle.EMPTY;
1762 return update(uri, values,
1763 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1764 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1765 }
1766
1767 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001768 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001769 * The default implementation always throws {@link FileNotFoundException}.
1770 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001771 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1772 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001773 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001774 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1775 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001776 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 *
1778 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1779 * their responsibility to close it when done. That is, the implementation
1780 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001781 * <p>
1782 * If opened with the exclusive "r" or "w" modes, the returned
1783 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1784 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1785 * supports seeking.
1786 * <p>
1787 * If you need to detect when the returned ParcelFileDescriptor has been
1788 * closed, or if the remote process has crashed or encountered some other
1789 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1790 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1791 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1792 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001793 * <p>
1794 * If you need to return a large file that isn't backed by a real file on
1795 * disk, such as a file on a network share or cloud storage service,
1796 * consider using
1797 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1798 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001800 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1801 * to return the appropriate MIME type for the data returned here with
1802 * the same URI. This will allow intent resolution to automatically determine the data MIME
1803 * type and select the appropriate matching targets as part of its operation.</p>
1804 *
1805 * <p class="note">For better interoperability with other applications, it is recommended
1806 * that for any URIs that can be opened, you also support queries on them
1807 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1808 * You may also want to support other common columns if you have additional meta-data
1809 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1810 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1811 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 * @param uri The URI whose file is to be opened.
1813 * @param mode Access mode for the file. May be "r" for read-only access,
1814 * "rw" for read and write access, or "rwt" for read and write access
1815 * that truncates any existing file.
1816 *
1817 * @return Returns a new ParcelFileDescriptor which you can use to access
1818 * the file.
1819 *
1820 * @throws FileNotFoundException Throws FileNotFoundException if there is
1821 * no file associated with the given URI or the mode is invalid.
1822 * @throws SecurityException Throws SecurityException if the caller does
1823 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001824 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 * @see #openAssetFile(Uri, String)
1826 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001827 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001828 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001829 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001830 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 throws FileNotFoundException {
1832 throw new FileNotFoundException("No files supported by provider at "
1833 + uri);
1834 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001837 * Override this to handle requests to open a file blob.
1838 * The default implementation always throws {@link FileNotFoundException}.
1839 * This method can be called from multiple threads, as described in
1840 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1841 * and Threads</a>.
1842 *
1843 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1844 * to the caller. This way large data (such as images and documents) can be
1845 * returned without copying the content.
1846 *
1847 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1848 * their responsibility to close it when done. That is, the implementation
1849 * of this method should create a new ParcelFileDescriptor for each call.
1850 * <p>
1851 * If opened with the exclusive "r" or "w" modes, the returned
1852 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1853 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1854 * supports seeking.
1855 * <p>
1856 * If you need to detect when the returned ParcelFileDescriptor has been
1857 * closed, or if the remote process has crashed or encountered some other
1858 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1859 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1860 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1861 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1862 *
1863 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1864 * to return the appropriate MIME type for the data returned here with
1865 * the same URI. This will allow intent resolution to automatically determine the data MIME
1866 * type and select the appropriate matching targets as part of its operation.</p>
1867 *
1868 * <p class="note">For better interoperability with other applications, it is recommended
1869 * that for any URIs that can be opened, you also support queries on them
1870 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1871 * You may also want to support other common columns if you have additional meta-data
1872 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1873 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1874 *
1875 * @param uri The URI whose file is to be opened.
1876 * @param mode Access mode for the file. May be "r" for read-only access,
1877 * "w" for write-only access, "rw" for read and write access, or
1878 * "rwt" for read and write access that truncates any existing
1879 * file.
1880 * @param signal A signal to cancel the operation in progress, or
1881 * {@code null} if none. For example, if you are downloading a
1882 * file from the network to service a "rw" mode request, you
1883 * should periodically call
1884 * {@link CancellationSignal#throwIfCanceled()} to check whether
1885 * the client has canceled the request and abort the download.
1886 *
1887 * @return Returns a new ParcelFileDescriptor which you can use to access
1888 * the file.
1889 *
1890 * @throws FileNotFoundException Throws FileNotFoundException if there is
1891 * no file associated with the given URI or the mode is invalid.
1892 * @throws SecurityException Throws SecurityException if the caller does
1893 * not have permission to access the file.
1894 *
1895 * @see #openAssetFile(Uri, String)
1896 * @see #openFileHelper(Uri, String)
1897 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001898 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001899 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001900 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001901 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1902 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001903 return openFile(uri, mode);
1904 }
1905
1906 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 * This is like {@link #openFile}, but can be implemented by providers
1908 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001909 * inside of their .apk.
1910 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001911 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1912 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001913 *
1914 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001915 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001916 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1918 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1919 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001920 * <p>
1921 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1922 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001923 *
1924 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 * should create the AssetFileDescriptor with
1926 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001927 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001929 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1930 * to return the appropriate MIME type for the data returned here with
1931 * the same URI. This will allow intent resolution to automatically determine the data MIME
1932 * type and select the appropriate matching targets as part of its operation.</p>
1933 *
1934 * <p class="note">For better interoperability with other applications, it is recommended
1935 * that for any URIs that can be opened, you also support queries on them
1936 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1937 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 * @param uri The URI whose file is to be opened.
1939 * @param mode Access mode for the file. May be "r" for read-only access,
1940 * "w" for write-only access (erasing whatever data is currently in
1941 * the file), "wa" for write-only access to append to any existing data,
1942 * "rw" for read and write access on any existing data, and "rwt" for read
1943 * and write access that truncates any existing file.
1944 *
1945 * @return Returns a new AssetFileDescriptor which you can use to access
1946 * the file.
1947 *
1948 * @throws FileNotFoundException Throws FileNotFoundException if there is
1949 * no file associated with the given URI or the mode is invalid.
1950 * @throws SecurityException Throws SecurityException if the caller does
1951 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001952 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 * @see #openFile(Uri, String)
1954 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001955 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001957 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 throws FileNotFoundException {
1959 ParcelFileDescriptor fd = openFile(uri, mode);
1960 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1961 }
1962
1963 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001964 * This is like {@link #openFile}, but can be implemented by providers
1965 * that need to be able to return sub-sections of files, often assets
1966 * inside of their .apk.
1967 * This method can be called from multiple threads, as described in
1968 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1969 * and Threads</a>.
1970 *
1971 * <p>If you implement this, your clients must be able to deal with such
1972 * file slices, either directly with
1973 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1974 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1975 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1976 * methods.
1977 * <p>
1978 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1979 * streaming of data.
1980 *
1981 * <p class="note">If you are implementing this to return a full file, you
1982 * should create the AssetFileDescriptor with
1983 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1984 * applications that cannot handle sub-sections of files.</p>
1985 *
1986 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1987 * to return the appropriate MIME type for the data returned here with
1988 * the same URI. This will allow intent resolution to automatically determine the data MIME
1989 * type and select the appropriate matching targets as part of its operation.</p>
1990 *
1991 * <p class="note">For better interoperability with other applications, it is recommended
1992 * that for any URIs that can be opened, you also support queries on them
1993 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1994 *
1995 * @param uri The URI whose file is to be opened.
1996 * @param mode Access mode for the file. May be "r" for read-only access,
1997 * "w" for write-only access (erasing whatever data is currently in
1998 * the file), "wa" for write-only access to append to any existing data,
1999 * "rw" for read and write access on any existing data, and "rwt" for read
2000 * and write access that truncates any existing file.
2001 * @param signal A signal to cancel the operation in progress, or
2002 * {@code null} if none. For example, if you are downloading a
2003 * file from the network to service a "rw" mode request, you
2004 * should periodically call
2005 * {@link CancellationSignal#throwIfCanceled()} to check whether
2006 * the client has canceled the request and abort the download.
2007 *
2008 * @return Returns a new AssetFileDescriptor which you can use to access
2009 * the file.
2010 *
2011 * @throws FileNotFoundException Throws FileNotFoundException if there is
2012 * no file associated with the given URI or the mode is invalid.
2013 * @throws SecurityException Throws SecurityException if the caller does
2014 * not have permission to access the file.
2015 *
2016 * @see #openFile(Uri, String)
2017 * @see #openFileHelper(Uri, String)
2018 * @see #getType(android.net.Uri)
2019 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002020 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002021 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
2022 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002023 return openAssetFile(uri, mode);
2024 }
2025
2026 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 * Convenience for subclasses that wish to implement {@link #openFile}
2028 * by looking up a column named "_data" at the given URI.
2029 *
2030 * @param uri The URI to be opened.
2031 * @param mode The file mode. May be "r" for read-only access,
2032 * "w" for write-only access (erasing whatever data is currently in
2033 * the file), "wa" for write-only access to append to any existing data,
2034 * "rw" for read and write access on any existing data, and "rwt" for read
2035 * and write access that truncates any existing file.
2036 *
2037 * @return Returns a new ParcelFileDescriptor that can be used by the
2038 * client to access the file.
2039 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002040 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
2041 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
2043 int count = (c != null) ? c.getCount() : 0;
2044 if (count != 1) {
2045 // If there is not exactly one result, throw an appropriate
2046 // exception.
2047 if (c != null) {
2048 c.close();
2049 }
2050 if (count == 0) {
2051 throw new FileNotFoundException("No entry for " + uri);
2052 }
2053 throw new FileNotFoundException("Multiple items at " + uri);
2054 }
2055
2056 c.moveToFirst();
2057 int i = c.getColumnIndex("_data");
2058 String path = (i >= 0 ? c.getString(i) : null);
2059 c.close();
2060 if (path == null) {
2061 throw new FileNotFoundException("Column _data not found.");
2062 }
2063
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002064 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 return ParcelFileDescriptor.open(new File(path), modeBits);
2066 }
2067
2068 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002069 * Called by a client to determine the types of data streams that this
2070 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002071 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002072 * of a particular type, return that MIME type if it matches the given
2073 * mimeTypeFilter. If it can perform type conversions, return an array
2074 * of all supported MIME types that match mimeTypeFilter.
2075 *
2076 * @param uri The data in the content provider being queried.
2077 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002078 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002079 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002080 * given mimeTypeFilter. Otherwise returns an array of all available
2081 * concrete MIME types.
2082 *
2083 * @see #getType(Uri)
2084 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002085 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002086 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002087 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002088 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002089 return null;
2090 }
2091
2092 /**
2093 * Called by a client to open a read-only stream containing data of a
2094 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2095 * except the file can only be read-only and the content provider may
2096 * perform data conversions to generate data of the desired type.
2097 *
2098 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002099 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002100 * {@link #openAssetFile(Uri, String)}.
2101 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002102 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002103 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002104 * <p>
2105 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2106 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002107 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002108 * <p class="note">For better interoperability with other applications, it is recommended
2109 * that for any URIs that can be opened, you also support queries on them
2110 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2111 * You may also want to support other common columns if you have additional meta-data
2112 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2113 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2114 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002115 * @param uri The data in the content provider being queried.
2116 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002117 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002118 * requirements; in this case the content provider will pick its best
2119 * type matching the pattern.
2120 * @param opts Additional options from the client. The definitions of
2121 * these are specific to the content provider being called.
2122 *
2123 * @return Returns a new AssetFileDescriptor from which the client can
2124 * read data of the desired type.
2125 *
2126 * @throws FileNotFoundException Throws FileNotFoundException if there is
2127 * no file associated with the given URI or the mode is invalid.
2128 * @throws SecurityException Throws SecurityException if the caller does
2129 * not have permission to access the data.
2130 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2131 * content provider does not support the requested MIME type.
2132 *
2133 * @see #getStreamTypes(Uri, String)
2134 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002135 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002136 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002137 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2138 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002139 if ("*/*".equals(mimeTypeFilter)) {
2140 // If they can take anything, the untyped open call is good enough.
2141 return openAssetFile(uri, "r");
2142 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002143 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002144 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002145 // Use old untyped open call if this provider has a type for this
2146 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002147 return openAssetFile(uri, "r");
2148 }
2149 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2150 }
2151
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002152
2153 /**
2154 * Called by a client to open a read-only stream containing data of a
2155 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2156 * except the file can only be read-only and the content provider may
2157 * perform data conversions to generate data of the desired type.
2158 *
2159 * <p>The default implementation compares the given mimeType against the
2160 * result of {@link #getType(Uri)} and, if they match, simply calls
2161 * {@link #openAssetFile(Uri, String)}.
2162 *
2163 * <p>See {@link ClipData} for examples of the use and implementation
2164 * of this method.
2165 * <p>
2166 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2167 * streaming of data.
2168 *
2169 * <p class="note">For better interoperability with other applications, it is recommended
2170 * that for any URIs that can be opened, you also support queries on them
2171 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2172 * You may also want to support other common columns if you have additional meta-data
2173 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2174 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2175 *
2176 * @param uri The data in the content provider being queried.
2177 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002178 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002179 * requirements; in this case the content provider will pick its best
2180 * type matching the pattern.
2181 * @param opts Additional options from the client. The definitions of
2182 * these are specific to the content provider being called.
2183 * @param signal A signal to cancel the operation in progress, or
2184 * {@code null} if none. For example, if you are downloading a
2185 * file from the network to service a "rw" mode request, you
2186 * should periodically call
2187 * {@link CancellationSignal#throwIfCanceled()} to check whether
2188 * the client has canceled the request and abort the download.
2189 *
2190 * @return Returns a new AssetFileDescriptor from which the client can
2191 * read data of the desired type.
2192 *
2193 * @throws FileNotFoundException Throws FileNotFoundException if there is
2194 * no file associated with the given URI or the mode is invalid.
2195 * @throws SecurityException Throws SecurityException if the caller does
2196 * not have permission to access the data.
2197 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2198 * content provider does not support the requested MIME type.
2199 *
2200 * @see #getStreamTypes(Uri, String)
2201 * @see #openAssetFile(Uri, String)
2202 * @see ClipDescription#compareMimeTypes(String, String)
2203 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002204 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002205 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2206 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2207 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002208 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2209 }
2210
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002211 /**
2212 * Interface to write a stream of data to a pipe. Use with
2213 * {@link ContentProvider#openPipeHelper}.
2214 */
2215 public interface PipeDataWriter<T> {
2216 /**
2217 * Called from a background thread to stream data out to a pipe.
2218 * Note that the pipe is blocking, so this thread can block on
2219 * writes for an arbitrary amount of time if the client is slow
2220 * at reading.
2221 *
2222 * @param output The pipe where data should be written. This will be
2223 * closed for you upon returning from this function.
2224 * @param uri The URI whose data is to be written.
2225 * @param mimeType The desired type of data to be written.
2226 * @param opts Options supplied by caller.
2227 * @param args Your own custom arguments.
2228 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002229 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2230 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002231 }
2232
2233 /**
2234 * A helper function for implementing {@link #openTypedAssetFile}, for
2235 * creating a data pipe and background thread allowing you to stream
2236 * generated data back to the client. This function returns a new
2237 * ParcelFileDescriptor that should be returned to the caller (the caller
2238 * is responsible for closing it).
2239 *
2240 * @param uri The URI whose data is to be written.
2241 * @param mimeType The desired type of data to be written.
2242 * @param opts Options supplied by caller.
2243 * @param args Your own custom arguments.
2244 * @param func Interface implementing the function that will actually
2245 * stream the data.
2246 * @return Returns a new ParcelFileDescriptor holding the read side of
2247 * the pipe. This should be returned to the caller for reading; the caller
2248 * is responsible for closing it when done.
2249 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002250 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2251 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2252 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002253 try {
2254 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2255
2256 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2257 @Override
2258 protected Object doInBackground(Object... params) {
2259 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2260 try {
2261 fds[1].close();
2262 } catch (IOException e) {
2263 Log.w(TAG, "Failure closing pipe", e);
2264 }
2265 return null;
2266 }
2267 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002268 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002269
2270 return fds[0];
2271 } catch (IOException e) {
2272 throw new FileNotFoundException("failure making pipe");
2273 }
2274 }
2275
2276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 * Returns true if this instance is a temporary content provider.
2278 * @return true if this instance is a temporary content provider
2279 */
2280 protected boolean isTemporary() {
2281 return false;
2282 }
2283
2284 /**
2285 * Returns the Binder object for this provider.
2286 *
2287 * @return the Binder object for this provider
2288 * @hide
2289 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002290 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 public IContentProvider getIContentProvider() {
2292 return mTransport;
2293 }
2294
2295 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002296 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2297 * when directly instantiating the provider for testing.
2298 * @hide
2299 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002300 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002301 public void attachInfoForTesting(Context context, ProviderInfo info) {
2302 attachInfo(context, info, true);
2303 }
2304
2305 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 * After being instantiated, this is called to tell the content provider
2307 * about itself.
2308 *
2309 * @param context The context this provider is running in
2310 * @param info Registered information about this content provider
2311 */
2312 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002313 attachInfo(context, info, false);
2314 }
2315
2316 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002317 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002318 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 /*
2321 * Only allow it to be set once, so after the content service gives
2322 * this to us clients can't change it.
2323 */
2324 if (mContext == null) {
2325 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002326 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002327 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2328 Context.APP_OPS_SERVICE);
2329 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002330 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 if (info != null) {
2332 setReadPermission(info.readPermission);
2333 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002334 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002335 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002336 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002337 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002339 if (Build.IS_DEBUGGABLE) {
2340 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2341 Log.VERBOSE));
2342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 ContentProvider.this.onCreate();
2344 }
2345 }
Fred Quintanace31b232009-05-04 16:01:15 -07002346
2347 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002348 * Override this to handle requests to perform a batch of operations, or the
2349 * default implementation will iterate over the operations and call
2350 * {@link ContentProviderOperation#apply} on each of them.
2351 * If all calls to {@link ContentProviderOperation#apply} succeed
2352 * then a {@link ContentProviderResult} array with as many
2353 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002354 * fail, it is up to the implementation how many of the others take effect.
2355 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002356 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2357 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002358 *
Fred Quintanace31b232009-05-04 16:01:15 -07002359 * @param operations the operations to apply
2360 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002361 * @throws OperationApplicationException thrown if any operation fails.
2362 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002363 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002364 @Override
2365 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2366 @NonNull ArrayList<ContentProviderOperation> operations)
2367 throws OperationApplicationException {
2368 return applyBatch(operations);
2369 }
2370
Jeff Sharkey673db442015-06-11 19:30:57 -07002371 public @NonNull ContentProviderResult[] applyBatch(
2372 @NonNull ArrayList<ContentProviderOperation> operations)
2373 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002374 final int numOperations = operations.size();
2375 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2376 for (int i = 0; i < numOperations; i++) {
2377 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002378 }
2379 return results;
2380 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002381
2382 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002383 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002384 * interfaces that are cheaper and/or unnatural for a table-like
2385 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002386 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002387 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2388 * on this entry into the content provider besides the basic ability for the application
2389 * to get access to the provider at all. For example, it has no idea whether the call
2390 * being executed may read or write data in the provider, so can't enforce those
2391 * individual permissions. Any implementation of this method <strong>must</strong>
2392 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2393 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002394 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2395 * @param arg provider-defined String argument. May be {@code null}.
2396 * @param extras provider-defined Bundle argument. May be {@code null}.
2397 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002398 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002399 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002400 @Override
2401 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2402 @Nullable String arg, @Nullable Bundle extras) {
2403 return call(method, arg, extras);
2404 }
2405
Jeff Sharkey673db442015-06-11 19:30:57 -07002406 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2407 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002408 return null;
2409 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002410
2411 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002412 * Implement this to shut down the ContentProvider instance. You can then
2413 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002414 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002415 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002416 * Android normally handles ContentProvider startup and shutdown
2417 * automatically. You do not need to start up or shut down a
2418 * ContentProvider. When you invoke a test method on a ContentProvider,
2419 * however, a ContentProvider instance is started and keeps running after
2420 * the test finishes, even if a succeeding test instantiates another
2421 * ContentProvider. A conflict develops because the two instances are
2422 * usually running against the same underlying data source (for example, an
2423 * sqlite database).
2424 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002425 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002426 * Implementing shutDown() avoids this conflict by providing a way to
2427 * terminate the ContentProvider. This method can also prevent memory leaks
2428 * from multiple instantiations of the ContentProvider, and it can ensure
2429 * unit test isolation by allowing you to completely clean up the test
2430 * fixture before moving on to the next test.
2431 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002432 */
2433 public void shutdown() {
2434 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2435 "connections are gracefully shutdown");
2436 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002437
2438 /**
2439 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002440 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002441 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002442 * @param fd The raw file descriptor that the dump is being sent to.
2443 * @param writer The PrintWriter to which you should dump your state. This will be
2444 * closed for you after you return.
2445 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002446 */
2447 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2448 writer.println("nothing to dump");
2449 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002450
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002451 private void validateIncomingAuthority(String authority) throws SecurityException {
2452 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2453 String message = "The authority " + authority + " does not match the one of the "
2454 + "contentProvider: ";
2455 if (mAuthority != null) {
2456 message += mAuthority;
2457 } else {
2458 message += Arrays.toString(mAuthorities);
2459 }
2460 throw new SecurityException(message);
2461 }
2462 }
2463
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002464 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002465 @VisibleForTesting
2466 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002467 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002468 if (!mSingleUser) {
2469 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2470 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2471 throw new SecurityException("trying to query a ContentProvider in user "
2472 + mContext.getUserId() + " with a uri belonging to user " + userId);
2473 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002474 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002475 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002476
2477 // Normalize the path by removing any empty path segments, which can be
2478 // a source of security issues.
2479 final String encodedPath = uri.getEncodedPath();
2480 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002481 final Uri normalized = uri.buildUpon()
2482 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2483 Log.w(TAG, "Normalized " + uri + " to " + normalized
2484 + " to avoid possible security issues");
2485 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002486 } else {
2487 return uri;
2488 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002489 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002490
2491 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002492 private Uri maybeGetUriWithoutUserId(Uri uri) {
2493 if (mSingleUser) {
2494 return uri;
2495 }
2496 return getUriWithoutUserId(uri);
2497 }
2498
2499 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002500 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2501 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002502 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002503 if (end == -1) return defaultUserId;
2504 String userIdString = auth.substring(0, end);
2505 try {
2506 return Integer.parseInt(userIdString);
2507 } catch (NumberFormatException e) {
2508 Log.w(TAG, "Error parsing userId.", e);
2509 return UserHandle.USER_NULL;
2510 }
2511 }
2512
2513 /** @hide */
2514 public static int getUserIdFromAuthority(String auth) {
2515 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2516 }
2517
2518 /** @hide */
2519 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2520 if (uri == null) return defaultUserId;
2521 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2522 }
2523
2524 /** @hide */
2525 public static int getUserIdFromUri(Uri uri) {
2526 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2527 }
2528
2529 /**
Alex Kershawba014ac2020-01-20 22:25:02 +00002530 * Returns the user associated with the given URI.
2531 *
2532 * @hide
2533 */
2534 @TestApi
2535 public @NonNull static UserHandle getUserHandleFromUri(@NonNull Uri uri) {
2536 return UserHandle.of(getUserIdFromUri(uri, Process.myUserHandle().getIdentifier()));
2537 }
2538
2539 /**
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002540 * Removes userId part from authority string. Expects format:
2541 * userId@some.authority
2542 * If there is no userId in the authority, it symply returns the argument
2543 * @hide
2544 */
2545 public static String getAuthorityWithoutUserId(String auth) {
2546 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002547 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002548 return auth.substring(end+1);
2549 }
2550
2551 /** @hide */
2552 public static Uri getUriWithoutUserId(Uri uri) {
2553 if (uri == null) return null;
2554 Uri.Builder builder = uri.buildUpon();
2555 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2556 return builder.build();
2557 }
2558
2559 /** @hide */
2560 public static boolean uriHasUserId(Uri uri) {
2561 if (uri == null) return false;
2562 return !TextUtils.isEmpty(uri.getUserInfo());
2563 }
2564
2565 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002566 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002567 public static Uri maybeAddUserId(Uri uri, int userId) {
2568 if (uri == null) return null;
2569 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002570 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002571 if (!uriHasUserId(uri)) {
2572 //We don't add the user Id if there's already one
2573 Uri.Builder builder = uri.buildUpon();
2574 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2575 return builder.build();
2576 }
2577 }
2578 return uri;
2579 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002580}