blob: 85826fd4e6699bd3cf3c57e9d7420e278bd4ac50 [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;
Dianne Hackborn35654b62013-01-14 17:38:02 -080031import android.app.AppOpsManager;
Artur Satayeve23a0eb2019-12-10 17:47:52 +000032import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey9edef252019-05-20 14:00:17 -060033import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070034import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.pm.ProviderInfo;
36import android.content.res.AssetFileDescriptor;
37import android.content.res.Configuration;
38import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070039import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.database.SQLException;
41import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070042import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010044import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070046import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080047import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070048import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070050import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080051import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060052import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070053import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060054import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010055import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070056import android.util.Log;
Philip P. Moltmann128b7032019-09-27 08:44:12 -070057import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060059import com.android.internal.annotations.VisibleForTesting;
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080062import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070064import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080065import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070066import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080067import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060068import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70/**
71 * Content providers are one of the primary building blocks of Android applications, providing
72 * content to applications. They encapsulate data and provide it to applications through the single
73 * {@link ContentResolver} interface. A content provider is only required if you need to share
74 * data between multiple applications. For example, the contacts data is used by multiple
75 * applications and must be stored in a content provider. If you don't need to share data amongst
76 * multiple applications you can use a database directly via
77 * {@link android.database.sqlite.SQLiteDatabase}.
78 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 * <p>When a request is made via
80 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
81 * request to the content provider registered with the authority. The content provider can interpret
82 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
83 * URIs.</p>
84 *
85 * <p>The primary methods that need to be implemented are:
86 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070087 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 * <li>{@link #query} which returns data to the caller</li>
89 * <li>{@link #insert} which inserts new data into the content provider</li>
90 * <li>{@link #update} which updates existing data in the content provider</li>
91 * <li>{@link #delete} which deletes data from the content provider</li>
92 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
93 * </ul></p>
94 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070095 * <p class="caution">Data access methods (such as {@link #insert} and
96 * {@link #update}) may be called from many threads at once, and must be thread-safe.
97 * Other methods (such as {@link #onCreate}) are only called from the application
98 * main thread, and must avoid performing lengthy operations. See the method
99 * descriptions for their expected thread behavior.</p>
100 *
101 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
102 * ContentProvider instance, so subclasses don't have to worry about the details of
103 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700104 *
105 * <div class="special reference">
106 * <h3>Developer Guides</h3>
107 * <p>For more information about using content providers, read the
108 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
109 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700110 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700112public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800113
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700114 private static final String TAG = "ContentProvider";
115
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900116 /*
117 * Note: if you add methods to ContentProvider, you must add similar methods to
118 * MockContentProvider.
119 */
120
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100121 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700123 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100124
125 // Since most Providers have only one authority, we keep both a String and a String[] to improve
126 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100127 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100128 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100130 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100131 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100133 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100135 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700136 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700137 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800138 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700139 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700141 private ThreadLocal<Pair<String, String>> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 private Transport mTransport = new Transport();
144
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700145 /**
146 * Construct a ContentProvider instance. Content providers must be
147 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
148 * in the manifest</a>, accessed with {@link ContentResolver}, and created
149 * automatically by the system, so applications usually do not create
150 * ContentProvider instances directly.
151 *
152 * <p>At construction time, the object is uninitialized, and most fields and
153 * methods are unavailable. Subclasses should initialize themselves in
154 * {@link #onCreate}, not the constructor.
155 *
156 * <p>Content providers are created on the application main thread at
157 * application launch time. The constructor must not perform lengthy
158 * operations, or application startup will be delayed.
159 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900160 public ContentProvider() {
161 }
162
163 /**
164 * Constructor just for mocking.
165 *
166 * @param context A Context object which should be some mock instance (like the
167 * instance of {@link android.test.mock.MockContext}).
168 * @param readPermission The read permision you want this instance should have in the
169 * test, which is available via {@link #getReadPermission()}.
170 * @param writePermission The write permission you want this instance should have
171 * in the test, which is available via {@link #getWritePermission()}.
172 * @param pathPermissions The PathPermissions you want this instance should have
173 * in the test, which is available via {@link #getPathPermissions()}.
174 * @hide
175 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100176 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900177 public ContentProvider(
178 Context context,
179 String readPermission,
180 String writePermission,
181 PathPermission[] pathPermissions) {
182 mContext = context;
183 mReadPermission = readPermission;
184 mWritePermission = writePermission;
185 mPathPermissions = pathPermissions;
186 }
187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 /**
189 * Given an IContentProvider, try to coerce it back to the real
190 * ContentProvider object if it is running in the local process. This can
191 * be used if you know you are running in the same process as a provider,
192 * and want to get direct access to its implementation details. Most
193 * clients should not nor have a reason to use it.
194 *
195 * @param abstractInterface The ContentProvider interface that is to be
196 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800197 * @return If the IContentProvider is non-{@code null} and local, returns its actual
198 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 * @hide
200 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100201 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 public static ContentProvider coerceToLocalContentProvider(
203 IContentProvider abstractInterface) {
204 if (abstractInterface instanceof Transport) {
205 return ((Transport)abstractInterface).getContentProvider();
206 }
207 return null;
208 }
209
210 /**
211 * Binder object that deals with remoting.
212 *
213 * @hide
214 */
215 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700216 volatile AppOpsManager mAppOpsManager = null;
217 volatile int mReadOp = AppOpsManager.OP_NONE;
218 volatile int mWriteOp = AppOpsManager.OP_NONE;
219 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 ContentProvider getContentProvider() {
222 return ContentProvider.this;
223 }
224
Jeff Brownd2183652011-10-09 12:39:53 -0700225 @Override
226 public String getProviderName() {
227 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 }
229
Jeff Brown75ea64f2012-01-25 19:37:13 -0800230 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700231 public Cursor query(String callingPkg, @Nullable String featureId, Uri uri,
232 @Nullable String[] projection, @Nullable Bundle queryArgs,
233 @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600234 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100235 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700236 if (enforceReadPermission(callingPkg, featureId, uri, null)
237 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700238 // The caller has no access to the data, so return an empty cursor with
239 // the columns in the requested order. The caller may ask for an invalid
240 // column and we would not catch that but this is not a problem in practice.
241 // We do not call ContentProvider#query with a modified where clause since
242 // the implementation is not guaranteed to be backed by a SQL database, hence
243 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700244 if (projection != null) {
245 return new MatrixCursor(projection, 0);
246 }
247
248 // Null projection means all columns but we have no idea which they are.
249 // However, the caller may be expecting to access them my index. Hence,
250 // we have to execute the query as if allowed to get a cursor with the
251 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700252 Cursor cursor;
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700253 final Pair<String, String> original = setCallingPackage(
254 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700255 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700256 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700257 uri, projection, queryArgs,
258 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700259 } catch (RemoteException e) {
260 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700261 } finally {
262 setCallingPackage(original);
263 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700264 if (cursor == null) {
265 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700266 }
267
268 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700269 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800270 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600271 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700272 final Pair<String, String> original = setCallingPackage(
273 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700274 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700275 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800276 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700277 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700278 } catch (RemoteException e) {
279 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700280 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700281 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600282 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285
Jeff Brown75ea64f2012-01-25 19:37:13 -0800286 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700288 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600289 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100290 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600291 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
292 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700293 return mInterface.getType(uri);
294 } catch (RemoteException e) {
295 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600296 } finally {
297 Trace.traceEnd(TRACE_TAG_DATABASE);
298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300
Jeff Brown75ea64f2012-01-25 19:37:13 -0800301 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700302 public Uri insert(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700303 ContentValues initialValues, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600304 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100305 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100306 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700307 if (enforceWritePermission(callingPkg, featureId, uri, null)
308 != AppOpsManager.MODE_ALLOWED) {
309 final Pair<String, String> original = setCallingPackage(
310 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700311 try {
312 return rejectInsert(uri, initialValues);
313 } finally {
314 setCallingPackage(original);
315 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800316 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600317 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700318 final Pair<String, String> original = setCallingPackage(
319 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700320 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700321 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700322 } catch (RemoteException e) {
323 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700324 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700325 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600326 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329
Jeff Brown75ea64f2012-01-25 19:37:13 -0800330 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700331 public int bulkInsert(String callingPkg, @Nullable String featureId, Uri uri,
332 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600333 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100334 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700335 if (enforceWritePermission(callingPkg, featureId, uri, null)
336 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800337 return 0;
338 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600339 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700340 final Pair<String, String> original = setCallingPackage(
341 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700342 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700343 return mInterface.bulkInsert(uri, initialValues);
344 } catch (RemoteException e) {
345 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700346 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700347 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600348 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 }
351
Jeff Brown75ea64f2012-01-25 19:37:13 -0800352 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700353 public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String featureId,
354 String authority, ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700355 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700356 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100357 int numOperations = operations.size();
358 final int[] userIds = new int[numOperations];
359 for (int i = 0; i < numOperations; i++) {
360 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100361 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600362 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600363 uri = validateIncomingUri(uri);
364 uri = maybeGetUriWithoutUserId(uri);
365 // Rebuild operation if we changed the Uri above
366 if (!Objects.equals(operation.getUri(), uri)) {
367 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100368 operations.set(i, operation);
369 }
Fred Quintana89437372009-05-15 15:10:40 -0700370 if (operation.isReadOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700371 if (enforceReadPermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800372 != AppOpsManager.MODE_ALLOWED) {
373 throw new OperationApplicationException("App op not allowed", 0);
374 }
Fred Quintana89437372009-05-15 15:10:40 -0700375 }
Fred Quintana89437372009-05-15 15:10:40 -0700376 if (operation.isWriteOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700377 if (enforceWritePermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800378 != AppOpsManager.MODE_ALLOWED) {
379 throw new OperationApplicationException("App op not allowed", 0);
380 }
Fred Quintana89437372009-05-15 15:10:40 -0700381 }
382 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600383 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700384 final Pair<String, String> original = setCallingPackage(
385 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700387 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700388 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800389 if (results != null) {
390 for (int i = 0; i < results.length ; i++) {
391 if (userIds[i] != UserHandle.USER_CURRENT) {
392 // Adding the userId to the uri.
393 results[i] = new ContentProviderResult(results[i], userIds[i]);
394 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100395 }
396 }
397 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700398 } catch (RemoteException e) {
399 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700400 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700401 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600402 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700403 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700404 }
405
Jeff Brown75ea64f2012-01-25 19:37:13 -0800406 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700407 public int delete(String callingPkg, @Nullable String featureId, Uri uri, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600408 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100409 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700410 if (enforceWritePermission(callingPkg, featureId, uri, null)
411 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800412 return 0;
413 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600414 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700415 final Pair<String, String> original = setCallingPackage(
416 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700417 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700418 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700419 } catch (RemoteException e) {
420 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700421 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700422 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600423 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
426
Jeff Brown75ea64f2012-01-25 19:37:13 -0800427 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700428 public int update(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700429 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600430 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100431 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700432 if (enforceWritePermission(callingPkg, featureId, uri, null)
433 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800434 return 0;
435 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600436 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700437 final Pair<String, String> original = setCallingPackage(
438 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700439 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700440 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700441 } catch (RemoteException e) {
442 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700443 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600445 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 }
448
Jeff Brown75ea64f2012-01-25 19:37:13 -0800449 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700450 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId,
451 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
452 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600453 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100454 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700455 enforceFilePermission(callingPkg, featureId, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600456 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700457 final Pair<String, String> original = setCallingPackage(
458 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700459 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700460 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700461 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700462 } catch (RemoteException e) {
463 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700464 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700465 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600466 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 }
469
Jeff Brown75ea64f2012-01-25 19:37:13 -0800470 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700471 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
472 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600474 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100475 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700476 enforceFilePermission(callingPkg, featureId, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600477 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700478 final Pair<String, String> original = setCallingPackage(
479 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700480 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700481 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700482 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700483 } catch (RemoteException e) {
484 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700485 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700486 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600487 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490
Jeff Brown75ea64f2012-01-25 19:37:13 -0800491 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700492 public Bundle call(String callingPkg, @Nullable String featureId, String authority,
493 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700494 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600495 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600496 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700497 final Pair<String, String> original = setCallingPackage(
498 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700499 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700500 return mInterface.call(authority, method, arg, extras);
501 } catch (RemoteException e) {
502 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700503 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700504 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600505 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700506 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800507 }
508
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700509 @Override
510 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700511 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600512 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100513 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600514 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
515 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700516 return mInterface.getStreamTypes(uri, mimeTypeFilter);
517 } catch (RemoteException e) {
518 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600519 } finally {
520 Trace.traceEnd(TRACE_TAG_DATABASE);
521 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700522 }
523
524 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700525 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
526 @Nullable String featureId, Uri uri, String mimeType, Bundle opts,
527 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600528 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600529 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100530 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700531 enforceFilePermission(callingPkg, featureId, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600532 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700533 final Pair<String, String> original = setCallingPackage(
534 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700535 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700536 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700537 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700538 } catch (RemoteException e) {
539 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700540 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700541 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600542 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700543 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700544 }
545
Jeff Brown75ea64f2012-01-25 19:37:13 -0800546 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700547 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800548 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800549 }
550
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700551 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700552 public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600553 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100554 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100555 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700556 if (enforceReadPermission(callingPkg, featureId, uri, null)
557 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700558 return null;
559 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600560 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700561 final Pair<String, String> original = setCallingPackage(
562 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700563 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700564 return maybeAddUserId(mInterface.canonicalize(uri), userId);
565 } catch (RemoteException e) {
566 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700567 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700568 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600569 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700570 }
571 }
572
573 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700574 public Uri uncanonicalize(String callingPkg, String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600575 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100576 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100577 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700578 if (enforceReadPermission(callingPkg, featureId, uri, null)
579 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700580 return null;
581 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600582 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700583 final Pair<String, String> original = setCallingPackage(
584 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700585 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700586 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
587 } catch (RemoteException e) {
588 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700589 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700590 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600591 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700592 }
593 }
594
Ben Lin1cf454f2016-11-10 13:50:54 -0800595 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700596 public boolean refresh(String callingPkg, String featureId, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800597 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600598 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800599 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700600 if (enforceReadPermission(callingPkg, featureId, uri, null)
601 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800602 return false;
603 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600604 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700605 final Pair<String, String> original = setCallingPackage(
606 new Pair<>(callingPkg, featureId));
Ben Lin1cf454f2016-11-10 13:50:54 -0800607 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700608 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800609 CancellationSignal.fromTransport(cancellationSignal));
610 } finally {
611 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600612 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800613 }
614 }
615
Jeff Sharkey9edef252019-05-20 14:00:17 -0600616 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700617 public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri,
618 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600619 uri = validateIncomingUri(uri);
620 uri = maybeGetUriWithoutUserId(uri);
621 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700622 final Pair<String, String> original = setCallingPackage(
623 new Pair<>(callingPkg, featureId));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600624 try {
625 return mInterface.checkUriPermission(uri, uid, modeFlags);
626 } catch (RemoteException e) {
627 throw e.rethrowAsRuntimeException();
628 } finally {
629 setCallingPackage(original);
630 Trace.traceEnd(TRACE_TAG_DATABASE);
631 }
632 }
633
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700634 private void enforceFilePermission(String callingPkg, @Nullable String featureId, Uri uri,
635 String mode, IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800636 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700637 if (enforceWritePermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800638 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800639 throw new FileNotFoundException("App op not allowed");
640 }
641 } else {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700642 if (enforceReadPermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800643 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800644 throw new FileNotFoundException("App op not allowed");
645 }
646 }
647 }
648
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700649 private int enforceReadPermission(String callingPkg, @Nullable String featureId, Uri uri,
650 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800651 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700652 final int mode = enforceReadPermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700653 if (mode != MODE_ALLOWED) {
654 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800655 }
Svet Ganov99b60432015-06-27 13:15:22 -0700656
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700657 return noteProxyOp(callingPkg, featureId, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800658 }
659
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700660 private int enforceWritePermission(String callingPkg, String featureId, Uri uri,
661 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800662 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700663 final int mode = enforceWritePermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700664 if (mode != MODE_ALLOWED) {
665 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800666 }
Svet Ganov99b60432015-06-27 13:15:22 -0700667
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700668 return noteProxyOp(callingPkg, featureId, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700669 }
670
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700671 private int noteProxyOp(String callingPkg, String featureId, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700672 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700673 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
674 featureId, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700675 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700676 }
677
Dianne Hackborn35654b62013-01-14 17:38:02 -0800678 return AppOpsManager.MODE_ALLOWED;
679 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700680 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800681
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100682 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700683 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
684 return true;
685 }
686 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
687 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100688 == PERMISSION_GRANTED;
689 }
690
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700691 /**
692 * Verify that calling app holds both the given permission and any app-op
693 * associated with that permission.
694 */
695 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700696 @Nullable String featureId, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700697 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
698 callerToken) != PERMISSION_GRANTED) {
699 return MODE_ERRORED;
700 }
701
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700702 return mTransport.noteProxyOp(callingPkg, featureId,
703 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700704 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700705
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700706 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700707 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
708 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700709 final Context context = getContext();
710 final int pid = Binder.getCallingPid();
711 final int uid = Binder.getCallingUid();
712 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700713 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700714
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700715 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700716 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700717 }
718
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100719 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700720 final String componentPerm = getReadPermission();
721 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700722 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
723 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700724 if (mode == MODE_ALLOWED) {
725 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700726 } else {
727 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700728 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700729 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700730 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700731
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700732 // track if unprotected read is allowed; any denied
733 // <path-permission> below removes this ability
734 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700735
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700736 final PathPermission[] pps = getPathPermissions();
737 if (pps != null) {
738 final String path = uri.getPath();
739 for (PathPermission pp : pps) {
740 final String pathPerm = pp.getReadPermission();
741 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700742 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
743 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700744 if (mode == MODE_ALLOWED) {
745 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700746 } else {
747 // any denied <path-permission> means we lose
748 // default <provider> access.
749 allowDefaultRead = false;
750 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700751 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700752 }
753 }
754 }
755 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700756
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700757 // if we passed <path-permission> checks above, and no default
758 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700759 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700761
762 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800763 final int callingUserId = UserHandle.getUserId(uid);
764 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
765 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800766 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
767 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700768 return MODE_ALLOWED;
769 }
770
771 // If the worst denial we found above was ignored, then pass that
772 // ignored through; otherwise we assume it should be a real error below.
773 if (strongestMode == MODE_IGNORED) {
774 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700775 }
776
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600777 final String suffix;
778 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
779 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
780 } else if (mExported) {
781 suffix = " requires " + missingPerm + ", or grantUriPermission()";
782 } else {
783 suffix = " requires the provider be exported, or grantUriPermission()";
784 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700785 throw new SecurityException("Permission Denial: reading "
786 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600787 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700788 }
789
790 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700791 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
792 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700793 final Context context = getContext();
794 final int pid = Binder.getCallingPid();
795 final int uid = Binder.getCallingUid();
796 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700797 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700798
799 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700800 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700801 }
802
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100803 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700804 final String componentPerm = getWritePermission();
805 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700806 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
807 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700808 if (mode == MODE_ALLOWED) {
809 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700810 } else {
811 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700812 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700813 }
814 }
815
816 // track if unprotected write is allowed; any denied
817 // <path-permission> below removes this ability
818 boolean allowDefaultWrite = (componentPerm == null);
819
820 final PathPermission[] pps = getPathPermissions();
821 if (pps != null) {
822 final String path = uri.getPath();
823 for (PathPermission pp : pps) {
824 final String pathPerm = pp.getWritePermission();
825 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700826 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
827 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700828 if (mode == MODE_ALLOWED) {
829 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700830 } else {
831 // any denied <path-permission> means we lose
832 // default <provider> access.
833 allowDefaultWrite = false;
834 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700835 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700836 }
837 }
838 }
839 }
840
841 // if we passed <path-permission> checks above, and no default
842 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700843 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700844 }
845
846 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800847 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
848 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700849 return MODE_ALLOWED;
850 }
851
852 // If the worst denial we found above was ignored, then pass that
853 // ignored through; otherwise we assume it should be a real error below.
854 if (strongestMode == MODE_IGNORED) {
855 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700856 }
857
858 final String failReason = mExported
859 ? " requires " + missingPerm + ", or grantUriPermission()"
860 : " requires the provider be exported, or grantUriPermission()";
861 throw new SecurityException("Permission Denial: writing "
862 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
863 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700867 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800868 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 * constructor.
870 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700871 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 return mContext;
873 }
874
875 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700876 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
877 * after {@link #onCreate}. When called before context was created, an IllegalStateException
878 * will be thrown.
879 * <p>
880 * Note A provider must be declared in the manifest and created automatically by the system,
881 * and context is only available after {@link #onCreate} is called.
882 */
883 @NonNull
884 public final Context requireContext() {
885 final Context ctx = getContext();
886 if (ctx == null) {
887 throw new IllegalStateException("Cannot find context from the provider.");
888 }
889 return ctx;
890 }
891
892 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700893 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700894 * which can be used later to restore the previous state.
895 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700896 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
897 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700898 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600899 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700900 return original;
901 }
902
903 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700904 * Return the package name of the caller that initiated the request being
905 * processed on the current thread. The returned package will have been
906 * verified to belong to the calling UID. Returns {@code null} if not
907 * currently processing a request.
908 * <p>
909 * This will always return {@code null} when processing
910 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
911 *
912 * @see Binder#getCallingUid()
913 * @see Context#grantUriPermission(String, Uri, int)
914 * @throws SecurityException if the calling package doesn't belong to the
915 * calling UID.
916 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700917 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700918 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700919 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700920 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
921 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700922 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700923
924 return null;
925 }
926
927 /**
928 * Return the feature in the package of the caller that initiated the request being
929 * processed on the current thread. Returns {@code null} if not currently processing
930 * a request of the request is for the default feature.
931 * <p>
932 * This will always return {@code null} when processing
933 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
934 *
935 * @see #getCallingPackage
936 */
937 public final @Nullable String getCallingFeatureId() {
938 final Pair<String, String> pkg = mCallingPackage.get();
939 if (pkg != null) {
940 return pkg.second;
941 }
942
943 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700944 }
945
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700946 /**
947 * Return the package name of the caller that initiated the request being
948 * processed on the current thread. The returned package will have
949 * <em>not</em> been verified to belong to the calling UID. Returns
950 * {@code null} if not currently processing a request.
951 * <p>
952 * This will always return {@code null} when processing
953 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
954 *
955 * @see Binder#getCallingUid()
956 * @see Context#grantUriPermission(String, Uri, int)
957 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600958 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700959 final Pair<String, String> pkg = mCallingPackage.get();
960 if (pkg != null) {
961 return pkg.first;
962 }
963
964 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600965 }
966
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700967 /**
968 * Called whenever the value of {@link #getCallingPackage()} changes, giving
969 * the provider an opportunity to invalidate any security related caching it
970 * may be performing.
971 * <p>
972 * This typically happens when a {@link ContentProvider} makes a nested call
973 * back into itself when already processing a call from a remote process.
974 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600975 public void onCallingPackageChanged() {
976 }
977
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700978 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600979 * Opaque token representing the identity of an incoming IPC.
980 */
981 public final class CallingIdentity {
982 /** {@hide} */
983 public final long binderToken;
984 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700985 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600986
987 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700988 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600989 this.binderToken = binderToken;
990 this.callingPackage = callingPackage;
991 }
992 }
993
994 /**
995 * Reset the identity of the incoming IPC on the current thread.
996 * <p>
997 * Internally this calls {@link Binder#clearCallingIdentity()} and also
998 * clears any value stored in {@link #getCallingPackage()}.
999 *
1000 * @return Returns an opaque token that can be used to restore the original
1001 * calling identity by passing it to
1002 * {@link #restoreCallingIdentity}.
1003 */
1004 public final @NonNull CallingIdentity clearCallingIdentity() {
1005 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
1006 }
1007
1008 /**
1009 * Restore the identity of the incoming IPC on the current thread back to a
1010 * previously identity that was returned by {@link #clearCallingIdentity}.
1011 * <p>
1012 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
1013 * also restores any value stored in {@link #getCallingPackage()}.
1014 */
1015 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
1016 Binder.restoreCallingIdentity(identity.binderToken);
1017 mCallingPackage.set(identity.callingPackage);
1018 }
1019
1020 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001021 * Change the authorities of the ContentProvider.
1022 * This is normally set for you from its manifest information when the provider is first
1023 * created.
1024 * @hide
1025 * @param authorities the semi-colon separated authorities of the ContentProvider.
1026 */
1027 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001028 if (authorities != null) {
1029 if (authorities.indexOf(';') == -1) {
1030 mAuthority = authorities;
1031 mAuthorities = null;
1032 } else {
1033 mAuthority = null;
1034 mAuthorities = authorities.split(";");
1035 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001036 }
1037 }
1038
1039 /** @hide */
1040 protected final boolean matchesOurAuthorities(String authority) {
1041 if (mAuthority != null) {
1042 return mAuthority.equals(authority);
1043 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001044 if (mAuthorities != null) {
1045 int length = mAuthorities.length;
1046 for (int i = 0; i < length; i++) {
1047 if (mAuthorities[i].equals(authority)) return true;
1048 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001049 }
1050 return false;
1051 }
1052
1053
1054 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 * Change the permission required to read data from the content
1056 * provider. This is normally set for you from its manifest information
1057 * when the provider is first created.
1058 *
1059 * @param permission Name of the permission required for read-only access.
1060 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001061 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 mReadPermission = permission;
1063 }
1064
1065 /**
1066 * Return the name of the permission required for read-only access to
1067 * this content provider. This method can be called from multiple
1068 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001069 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1070 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001072 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 return mReadPermission;
1074 }
1075
1076 /**
1077 * Change the permission required to read and write data in the content
1078 * provider. This is normally set for you from its manifest information
1079 * when the provider is first created.
1080 *
1081 * @param permission Name of the permission required for read/write access.
1082 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001083 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 mWritePermission = permission;
1085 }
1086
1087 /**
1088 * Return the name of the permission required for read/write access to
1089 * this content provider. This method can be called from multiple
1090 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001091 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1092 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001094 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 return mWritePermission;
1096 }
1097
1098 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001099 * Change the path-based permission required to read and/or write data in
1100 * the content provider. This is normally set for you from its manifest
1101 * information when the provider is first created.
1102 *
1103 * @param permissions Array of path permission descriptions.
1104 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001105 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001106 mPathPermissions = permissions;
1107 }
1108
1109 /**
1110 * Return the path-based permissions required for read and/or write access to
1111 * this content provider. This method can be called from multiple
1112 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001113 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1114 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001115 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001116 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001117 return mPathPermissions;
1118 }
1119
Dianne Hackborn35654b62013-01-14 17:38:02 -08001120 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001121 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001122 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001123 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001124 mTransport.mReadOp = readOp;
1125 mTransport.mWriteOp = writeOp;
1126 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001127 }
1128
Dianne Hackborn961321f2013-02-05 17:22:41 -08001129 /** @hide */
1130 public AppOpsManager getAppOpsManager() {
1131 return mTransport.mAppOpsManager;
1132 }
1133
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001134 /** @hide */
1135 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001136 if (mTransport == null) {
1137 return;
1138 }
1139 if (enabled) {
1140 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1141 } else {
1142 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001143 }
1144 }
1145
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001146 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001147 * Implement this to initialize your content provider on startup.
1148 * This method is called for all registered content providers on the
1149 * application main thread at application launch time. It must not perform
1150 * lengthy operations, or application startup will be delayed.
1151 *
1152 * <p>You should defer nontrivial initialization (such as opening,
1153 * upgrading, and scanning databases) until the content provider is used
1154 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1155 * keeps application startup fast, avoids unnecessary work if the provider
1156 * turns out not to be needed, and stops database errors (such as a full
1157 * disk) from halting application launch.
1158 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001159 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001160 * is a helpful utility class that makes it easy to manage databases,
1161 * and will automatically defer opening until first use. If you do use
1162 * SQLiteOpenHelper, make sure to avoid calling
1163 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1164 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1165 * from this method. (Instead, override
1166 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1167 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 *
1169 * @return true if the provider was successfully loaded, false otherwise
1170 */
1171 public abstract boolean onCreate();
1172
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001173 /**
1174 * {@inheritDoc}
1175 * This method is always called on the application main thread, and must
1176 * not perform lengthy operations.
1177 *
1178 * <p>The default content provider implementation does nothing.
1179 * Override this method to take appropriate action.
1180 * (Content providers do not usually care about things like screen
1181 * orientation, but may want to know about locale changes.)
1182 */
Steve McKayea93fe72016-12-02 11:35:35 -08001183 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 public void onConfigurationChanged(Configuration newConfig) {
1185 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001186
1187 /**
1188 * {@inheritDoc}
1189 * This method is always called on the application main thread, and must
1190 * not perform lengthy operations.
1191 *
1192 * <p>The default content provider implementation does nothing.
1193 * Subclasses may override this method to take appropriate action.
1194 */
Steve McKayea93fe72016-12-02 11:35:35 -08001195 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 public void onLowMemory() {
1197 }
1198
Steve McKayea93fe72016-12-02 11:35:35 -08001199 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001200 public void onTrimMemory(int level) {
1201 }
1202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001204 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001205 *
1206 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1207 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1208 * implementation of this method.
1209 *
1210 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001211 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1212 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 * <p>
1214 * Example client call:<p>
1215 * <pre>// Request a specific record.
1216 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001217 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 projection, // Which columns to return.
1219 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001220 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 People.NAME + " ASC"); // Sort order.</pre>
1222 * Example implementation:<p>
1223 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1224 // proper SQL syntax for us.
1225 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1226
1227 // Set the table we're querying.
1228 qBuilder.setTables(DATABASE_TABLE_NAME);
1229
1230 // If the query ends in a specific record number, we're
1231 // being asked for a specific record, so set the
1232 // WHERE clause in our query.
1233 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1234 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1235 }
1236
1237 // Make the query.
1238 Cursor c = qBuilder.query(mDb,
1239 projection,
1240 selection,
1241 selectionArgs,
1242 groupBy,
1243 having,
1244 sortOrder);
1245 c.setNotificationUri(getContext().getContentResolver(), uri);
1246 return c;</pre>
1247 *
1248 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001249 * if the client is requesting a specific record, the URI will end in a record number
1250 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1251 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001253 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001255 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001256 * @param selectionArgs You may include ?s in selection, which will be replaced by
1257 * the values from selectionArgs, in order that they appear in the selection.
1258 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001260 * If {@code null} then the provider is free to define the sort order.
1261 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001263 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1264 @Nullable String selection, @Nullable String[] selectionArgs,
1265 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266
Fred Quintana5bba6322009-10-05 14:21:12 -07001267 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001268 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001269 *
1270 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1271 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1272 *
1273 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001274 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1275 * and Threads</a>.
1276 * <p>
1277 * Example client call:<p>
1278 * <pre>// Request a specific record.
1279 * Cursor managedCursor = managedQuery(
1280 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1281 projection, // Which columns to return.
1282 null, // WHERE clause.
1283 null, // WHERE clause value substitution
1284 People.NAME + " ASC"); // Sort order.</pre>
1285 * Example implementation:<p>
1286 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1287 // proper SQL syntax for us.
1288 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1289
1290 // Set the table we're querying.
1291 qBuilder.setTables(DATABASE_TABLE_NAME);
1292
1293 // If the query ends in a specific record number, we're
1294 // being asked for a specific record, so set the
1295 // WHERE clause in our query.
1296 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1297 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1298 }
1299
1300 // Make the query.
1301 Cursor c = qBuilder.query(mDb,
1302 projection,
1303 selection,
1304 selectionArgs,
1305 groupBy,
1306 having,
1307 sortOrder);
1308 c.setNotificationUri(getContext().getContentResolver(), uri);
1309 return c;</pre>
1310 * <p>
1311 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001312 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1313 * signal to ensure correct operation on older versions of the Android Framework in
1314 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001315 *
1316 * @param uri The URI to query. This will be the full URI sent by the client;
1317 * if the client is requesting a specific record, the URI will end in a record number
1318 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1319 * that _id value.
1320 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001321 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001322 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001323 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001324 * @param selectionArgs You may include ?s in selection, which will be replaced by
1325 * the values from selectionArgs, in order that they appear in the selection.
1326 * The values will be bound as Strings.
1327 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001328 * If {@code null} then the provider is free to define the sort order.
1329 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001330 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001331 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001332 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001333 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001334 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1335 @Nullable String selection, @Nullable String[] selectionArgs,
1336 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001337 return query(uri, projection, selection, selectionArgs, sortOrder);
1338 }
1339
1340 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001341 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1342 * Arguments may include traditional SQL style query arguments. When present these
1343 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001344 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001345 *
1346 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001347 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1348 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1349 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001350 *
Steve McKay76b27702017-04-24 12:07:53 -07001351 * <p>This method can be called from multiple threads, as described in
1352 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1353 * and Threads</a>.
1354 *
1355 * <p>
1356 * Example client call:<p>
1357 * <pre>// Request 20 records starting at row index 30.
1358 Bundle queryArgs = new Bundle();
1359 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1360 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1361
1362 Cursor cursor = getContentResolver().query(
1363 contentUri, // Content Uri is specific to individual content providers.
1364 projection, // String[] describing which columns to return.
1365 queryArgs, // Query arguments.
1366 null); // Cancellation signal.</pre>
1367 *
1368 * Example implementation:<p>
1369 * <pre>
1370
1371 int recordsetSize = 0x1000; // Actual value is implementation specific.
1372 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1373
1374 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1375 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1376
1377 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1378
1379 // Calculate the number of items to include in the cursor.
1380 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1381
1382 // Build the paged result set....
1383 for (int i = offset; i < offset + numItems; i++) {
1384 // populate row from your data.
1385 }
1386
1387 Bundle extras = new Bundle();
1388 c.setExtras(extras);
1389
1390 // Any QUERY_ARG_* key may be included if honored.
1391 // In an actual implementation, include only keys that are both present in queryArgs
1392 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1393 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1394 // then QUERY_ARG_OFFSET should be omitted.
1395 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1396 ContentResolver.QUERY_ARG_OFFSET,
1397 ContentResolver.QUERY_ARG_LIMIT
1398 });
1399
1400 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1401
1402 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1403
1404 return cursor;</pre>
1405 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001406 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1407 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001408 *
1409 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001410 * @param projection The list of columns to put into the cursor.
1411 * If {@code null} provide a default set of columns.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001412 * @param queryArgs A Bundle containing additional information necessary for
1413 * the operation. Arguments may include SQL style arguments, such
1414 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1415 * the documentation for each individual provider will indicate
1416 * which arguments they support.
Steve McKayea93fe72016-12-02 11:35:35 -08001417 * @param cancellationSignal A signal to cancel the operation in progress,
1418 * or {@code null}.
1419 * @return a Cursor or {@code null}.
1420 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001421 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001422 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1423 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1424 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001425
Steve McKayd7ece9f2017-01-12 16:59:59 -08001426 // if client doesn't supply an SQL sort order argument, attempt to build one from
1427 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001428 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001429 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1430 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1431 }
1432
Steve McKayea93fe72016-12-02 11:35:35 -08001433 return query(
1434 uri,
1435 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001436 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1437 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1438 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001439 cancellationSignal);
1440 }
1441
1442 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001443 * Implement this to handle requests for the MIME type of the data at the
1444 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 * <code>vnd.android.cursor.item</code> for a single record,
1446 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001447 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001448 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1449 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001451 * <p>Note that there are no permissions needed for an application to
1452 * access this information; if your content provider requires read and/or
1453 * write permissions, or is not exported, all applications can still call
1454 * this method regardless of their access permissions. This allows them
1455 * to retrieve the MIME type for a URI when dispatching intents.
1456 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001458 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001460 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001461 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462
1463 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001464 * Implement this to support canonicalization of URIs that refer to your
1465 * content provider. A canonical URI is one that can be transported across
1466 * devices, backup/restore, and other contexts, and still be able to refer
1467 * to the same data item. Typically this is implemented by adding query
1468 * params to the URI allowing the content provider to verify that an incoming
1469 * canonical URI references the same data as it was originally intended for and,
1470 * if it doesn't, to find that data (if it exists) in the current environment.
1471 *
1472 * <p>For example, if the content provider holds people and a normal URI in it
1473 * is created with a row index into that people database, the cananical representation
1474 * may have an additional query param at the end which specifies the name of the
1475 * person it is intended for. Later calls into the provider with that URI will look
1476 * up the row of that URI's base index and, if it doesn't match or its entry's
1477 * name doesn't match the name in the query param, perform a query on its database
1478 * to find the correct row to operate on.</p>
1479 *
1480 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1481 * URIs (including this one) must perform this verification and recovery of any
1482 * canonical URIs they receive. In addition, you must also implement
1483 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1484 *
1485 * <p>The default implementation of this method returns null, indicating that
1486 * canonical URIs are not supported.</p>
1487 *
1488 * @param url The Uri to canonicalize.
1489 *
1490 * @return Return the canonical representation of <var>url</var>, or null if
1491 * canonicalization of that Uri is not supported.
1492 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001493 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001494 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001495 return null;
1496 }
1497
1498 /**
1499 * Remove canonicalization from canonical URIs previously returned by
1500 * {@link #canonicalize}. For example, if your implementation is to add
1501 * a query param to canonicalize a URI, this method can simply trip any
1502 * query params on the URI. The default implementation always returns the
1503 * same <var>url</var> that was passed in.
1504 *
1505 * @param url The Uri to remove any canonicalization from.
1506 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001507 * @return Return the non-canonical representation of <var>url</var>, return
1508 * the <var>url</var> as-is if there is nothing to do, or return null if
1509 * the data identified by the canonical representation can not be found in
1510 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001511 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001512 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001513 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001514 return url;
1515 }
1516
1517 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001518 * Implement this to support refresh of content identified by {@code uri}.
1519 * By default, this method returns false; providers who wish to implement
1520 * this should return true to signal the client that the provider has tried
1521 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001522 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001523 * This allows clients to request an explicit refresh of content identified
1524 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001525 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001526 * Client code should only invoke this method when there is a strong
1527 * indication (such as a user initiated pull to refresh gesture) that the
1528 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001529 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001530 * Remember to send
1531 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001532 * notifications when content changes.
1533 *
1534 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001535 * @param extras Additional options from the client. The definitions of
1536 * these are specific to the content provider being called.
1537 * @param cancellationSignal A signal to cancel the operation in progress,
1538 * or {@code null} if none. For example, if you called refresh on
1539 * a particular uri, you should call
1540 * {@link CancellationSignal#throwIfCanceled()} to check whether
1541 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001542 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001543 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001544 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001545 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001546 @Nullable CancellationSignal cancellationSignal) {
1547 return false;
1548 }
1549
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001550 /**
1551 * Perform a detailed internal check on a {@link Uri} to determine if a UID
1552 * is able to access it with specific mode flags.
1553 * <p>
1554 * This method is typically used when the provider implements more dynamic
1555 * access controls that cannot be expressed with {@code <path-permission>}
1556 * style static rules.
1557 *
1558 * @param uri the {@link Uri} to perform an access check on.
1559 * @param uid the UID to check the permission for.
1560 * @param modeFlags the access flags to use for the access check, such as
1561 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}.
1562 * @return {@link PackageManager#PERMISSION_GRANTED} if access is allowed,
1563 * otherwise {@link PackageManager#PERMISSION_DENIED}.
1564 * @hide
1565 */
Jeff Sharkey9edef252019-05-20 14:00:17 -06001566 @Override
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001567 @SystemApi
Jeff Sharkey9edef252019-05-20 14:00:17 -06001568 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1569 return PackageManager.PERMISSION_DENIED;
1570 }
1571
Ben Lin1cf454f2016-11-10 13:50:54 -08001572 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001573 * @hide
1574 * Implementation when a caller has performed an insert on the content
1575 * provider, but that call has been rejected for the operation given
1576 * to {@link #setAppOps(int, int)}. The default implementation simply
1577 * returns a dummy URI that is the base URI with a 0 path element
1578 * appended.
1579 */
1580 public Uri rejectInsert(Uri uri, ContentValues values) {
1581 // If not allowed, we need to return some reasonable URI. Maybe the
1582 // content provider should be responsible for this, but for now we
1583 // will just return the base URI with a dummy '0' tagged on to it.
1584 // You shouldn't be able to read if you can't write, anyway, so it
1585 // shouldn't matter much what is returned.
1586 return uri.buildUpon().appendPath("0").build();
1587 }
1588
1589 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001590 * Implement this to handle requests to insert a new row. As a courtesy,
1591 * call
1592 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1593 * notifyChange()} after inserting. This method can be called from multiple
1594 * threads, as described in <a href="
1595 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001596 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001597 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001598 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 * @param values A set of column_name/value pairs to add to the database.
1600 * @return The URI for the newly inserted item.
1601 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001602 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603
1604 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001605 * Implement this to handle requests to insert a new row. As a courtesy,
1606 * call
1607 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1608 * notifyChange()} after inserting. This method can be called from multiple
1609 * threads, as described in <a href="
1610 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1611 * and Threads</a>.
1612 *
1613 * @param uri The content:// URI of the insertion request.
1614 * @param values A set of column_name/value pairs to add to the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001615 * @param extras A Bundle containing additional information necessary for
1616 * the operation. Arguments may include SQL style arguments, such
1617 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1618 * the documentation for each individual provider will indicate
1619 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001620 * @return The URI for the newly inserted item.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001621 * @throws IllegalArgumentException if the provider doesn't support one of
1622 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001623 */
1624 @Override
1625 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1626 @Nullable Bundle extras) {
1627 return insert(uri, values);
1628 }
1629
1630 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001631 * Override this to handle requests to insert a set of new rows, or the
1632 * default implementation will iterate over the values and call
1633 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1635 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001636 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001637 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1638 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 *
1640 * @param uri The content:// URI of the insertion request.
1641 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001642 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 * @return The number of values that were inserted.
1644 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001645 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001646 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 int numValues = values.length;
1648 for (int i = 0; i < numValues; i++) {
1649 insert(uri, values[i]);
1650 }
1651 return numValues;
1652 }
1653
1654 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001655 * Implement this to handle requests to delete one or more rows. The
1656 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001657 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001658 * As a courtesy, call
1659 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1660 * notifyChange()} after deleting. This method can be called from multiple
1661 * threads, as described in <a href="
1662 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001663 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001664 * <p>
1665 * The implementation is responsible for parsing out a row ID at the end of
1666 * the URI, if a specific row is being deleted. That is, the client would
1667 * pass in <code>content://contacts/people/22</code> and the implementation
1668 * is responsible for parsing the record number (22) when creating a SQL
1669 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001671 * @param uri The full URI to query, including a row ID (if a specific
1672 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 * @param selection An optional restriction to apply to rows when deleting.
1674 * @return The number of rows affected.
1675 * @throws SQLException
1676 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001677 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1678 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679
1680 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001681 * Implement this to handle requests to delete one or more rows. The
1682 * implementation should apply the selection clause when performing
1683 * deletion, allowing the operation to affect multiple rows in a directory.
1684 * As a courtesy, call
1685 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1686 * notifyChange()} after deleting. This method can be called from multiple
1687 * threads, as described in <a href="
1688 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1689 * and Threads</a>.
1690 * <p>
1691 * The implementation is responsible for parsing out a row ID at the end of
1692 * the URI, if a specific row is being deleted. That is, the client would
1693 * pass in <code>content://contacts/people/22</code> and the implementation
1694 * is responsible for parsing the record number (22) when creating a SQL
1695 * statement.
1696 *
1697 * @param uri The full URI to query, including a row ID (if a specific
1698 * record is requested).
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001699 * @param extras A Bundle containing additional information necessary for
1700 * the operation. Arguments may include SQL style arguments, such
1701 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1702 * the documentation for each individual provider will indicate
1703 * which arguments they support.
1704 * @throws IllegalArgumentException if the provider doesn't support one of
1705 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001706 * @throws SQLException
1707 */
1708 @Override
1709 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1710 extras = (extras != null) ? extras : Bundle.EMPTY;
1711 return delete(uri,
1712 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1713 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1714 }
1715
1716 /**
1717 * Implement this to handle requests to update one or more rows. The
1718 * implementation should update all rows matching the selection to set the
1719 * columns according to the provided values map. As a courtesy, call
1720 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1721 * notifyChange()} after updating. This method can be called from multiple
1722 * threads, as described in <a href="
1723 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001724 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001726 * @param uri The URI to query. This can potentially have a record ID if
1727 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001728 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 * @param selection An optional filter to match rows to update.
1730 * @return the number of rows affected.
1731 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001732 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001733 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734
1735 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001736 * Implement this to handle requests to update one or more rows. The
1737 * implementation should update all rows matching the selection to set the
1738 * columns according to the provided values map. As a courtesy, call
1739 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1740 * notifyChange()} after updating. This method can be called from multiple
1741 * threads, as described in <a href="
1742 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1743 * and Threads</a>.
1744 *
1745 * @param uri The URI to query. This can potentially have a record ID if
1746 * this is an update request for a specific record.
1747 * @param values A set of column_name/value pairs to update in the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001748 * @param extras A Bundle containing additional information necessary for
1749 * the operation. Arguments may include SQL style arguments, such
1750 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1751 * the documentation for each individual provider will indicate
1752 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001753 * @return the number of rows affected.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001754 * @throws IllegalArgumentException if the provider doesn't support one of
1755 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001756 */
1757 @Override
1758 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1759 @Nullable Bundle extras) {
1760 extras = (extras != null) ? extras : Bundle.EMPTY;
1761 return update(uri, values,
1762 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1763 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1764 }
1765
1766 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001767 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001768 * The default implementation always throws {@link FileNotFoundException}.
1769 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001770 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1771 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001772 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001773 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1774 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001775 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 *
1777 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1778 * their responsibility to close it when done. That is, the implementation
1779 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001780 * <p>
1781 * If opened with the exclusive "r" or "w" modes, the returned
1782 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1783 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1784 * supports seeking.
1785 * <p>
1786 * If you need to detect when the returned ParcelFileDescriptor has been
1787 * closed, or if the remote process has crashed or encountered some other
1788 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1789 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1790 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1791 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001792 * <p>
1793 * If you need to return a large file that isn't backed by a real file on
1794 * disk, such as a file on a network share or cloud storage service,
1795 * consider using
1796 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1797 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001799 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1800 * to return the appropriate MIME type for the data returned here with
1801 * the same URI. This will allow intent resolution to automatically determine the data MIME
1802 * type and select the appropriate matching targets as part of its operation.</p>
1803 *
1804 * <p class="note">For better interoperability with other applications, it is recommended
1805 * that for any URIs that can be opened, you also support queries on them
1806 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1807 * You may also want to support other common columns if you have additional meta-data
1808 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1809 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1810 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 * @param uri The URI whose file is to be opened.
1812 * @param mode Access mode for the file. May be "r" for read-only access,
1813 * "rw" for read and write access, or "rwt" for read and write access
1814 * that truncates any existing file.
1815 *
1816 * @return Returns a new ParcelFileDescriptor which you can use to access
1817 * the file.
1818 *
1819 * @throws FileNotFoundException Throws FileNotFoundException if there is
1820 * no file associated with the given URI or the mode is invalid.
1821 * @throws SecurityException Throws SecurityException if the caller does
1822 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001823 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 * @see #openAssetFile(Uri, String)
1825 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001826 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001827 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001828 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001829 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 throws FileNotFoundException {
1831 throw new FileNotFoundException("No files supported by provider at "
1832 + uri);
1833 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001836 * Override this to handle requests to open a file blob.
1837 * The default implementation always throws {@link FileNotFoundException}.
1838 * This method can be called from multiple threads, as described in
1839 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1840 * and Threads</a>.
1841 *
1842 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1843 * to the caller. This way large data (such as images and documents) can be
1844 * returned without copying the content.
1845 *
1846 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1847 * their responsibility to close it when done. That is, the implementation
1848 * of this method should create a new ParcelFileDescriptor for each call.
1849 * <p>
1850 * If opened with the exclusive "r" or "w" modes, the returned
1851 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1852 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1853 * supports seeking.
1854 * <p>
1855 * If you need to detect when the returned ParcelFileDescriptor has been
1856 * closed, or if the remote process has crashed or encountered some other
1857 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1858 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1859 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1860 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1861 *
1862 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1863 * to return the appropriate MIME type for the data returned here with
1864 * the same URI. This will allow intent resolution to automatically determine the data MIME
1865 * type and select the appropriate matching targets as part of its operation.</p>
1866 *
1867 * <p class="note">For better interoperability with other applications, it is recommended
1868 * that for any URIs that can be opened, you also support queries on them
1869 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1870 * You may also want to support other common columns if you have additional meta-data
1871 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1872 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1873 *
1874 * @param uri The URI whose file is to be opened.
1875 * @param mode Access mode for the file. May be "r" for read-only access,
1876 * "w" for write-only access, "rw" for read and write access, or
1877 * "rwt" for read and write access that truncates any existing
1878 * file.
1879 * @param signal A signal to cancel the operation in progress, or
1880 * {@code null} if none. For example, if you are downloading a
1881 * file from the network to service a "rw" mode request, you
1882 * should periodically call
1883 * {@link CancellationSignal#throwIfCanceled()} to check whether
1884 * the client has canceled the request and abort the download.
1885 *
1886 * @return Returns a new ParcelFileDescriptor which you can use to access
1887 * the file.
1888 *
1889 * @throws FileNotFoundException Throws FileNotFoundException if there is
1890 * no file associated with the given URI or the mode is invalid.
1891 * @throws SecurityException Throws SecurityException if the caller does
1892 * not have permission to access the file.
1893 *
1894 * @see #openAssetFile(Uri, String)
1895 * @see #openFileHelper(Uri, String)
1896 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001897 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001898 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001899 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001900 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1901 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001902 return openFile(uri, mode);
1903 }
1904
1905 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 * This is like {@link #openFile}, but can be implemented by providers
1907 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001908 * inside of their .apk.
1909 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001910 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1911 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001912 *
1913 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001914 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001915 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1917 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1918 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001919 * <p>
1920 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1921 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001922 *
1923 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 * should create the AssetFileDescriptor with
1925 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001926 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001928 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1929 * to return the appropriate MIME type for the data returned here with
1930 * the same URI. This will allow intent resolution to automatically determine the data MIME
1931 * type and select the appropriate matching targets as part of its operation.</p>
1932 *
1933 * <p class="note">For better interoperability with other applications, it is recommended
1934 * that for any URIs that can be opened, you also support queries on them
1935 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1936 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 * @param uri The URI whose file is to be opened.
1938 * @param mode Access mode for the file. May be "r" for read-only access,
1939 * "w" for write-only access (erasing whatever data is currently in
1940 * the file), "wa" for write-only access to append to any existing data,
1941 * "rw" for read and write access on any existing data, and "rwt" for read
1942 * and write access that truncates any existing file.
1943 *
1944 * @return Returns a new AssetFileDescriptor which you can use to access
1945 * the file.
1946 *
1947 * @throws FileNotFoundException Throws FileNotFoundException if there is
1948 * no file associated with the given URI or the mode is invalid.
1949 * @throws SecurityException Throws SecurityException if the caller does
1950 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001951 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 * @see #openFile(Uri, String)
1953 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001954 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001956 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 throws FileNotFoundException {
1958 ParcelFileDescriptor fd = openFile(uri, mode);
1959 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1960 }
1961
1962 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001963 * This is like {@link #openFile}, but can be implemented by providers
1964 * that need to be able to return sub-sections of files, often assets
1965 * inside of their .apk.
1966 * This method can be called from multiple threads, as described in
1967 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1968 * and Threads</a>.
1969 *
1970 * <p>If you implement this, your clients must be able to deal with such
1971 * file slices, either directly with
1972 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1973 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1974 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1975 * methods.
1976 * <p>
1977 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1978 * streaming of data.
1979 *
1980 * <p class="note">If you are implementing this to return a full file, you
1981 * should create the AssetFileDescriptor with
1982 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1983 * applications that cannot handle sub-sections of files.</p>
1984 *
1985 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1986 * to return the appropriate MIME type for the data returned here with
1987 * the same URI. This will allow intent resolution to automatically determine the data MIME
1988 * type and select the appropriate matching targets as part of its operation.</p>
1989 *
1990 * <p class="note">For better interoperability with other applications, it is recommended
1991 * that for any URIs that can be opened, you also support queries on them
1992 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1993 *
1994 * @param uri The URI whose file is to be opened.
1995 * @param mode Access mode for the file. May be "r" for read-only access,
1996 * "w" for write-only access (erasing whatever data is currently in
1997 * the file), "wa" for write-only access to append to any existing data,
1998 * "rw" for read and write access on any existing data, and "rwt" for read
1999 * and write access that truncates any existing file.
2000 * @param signal A signal to cancel the operation in progress, or
2001 * {@code null} if none. For example, if you are downloading a
2002 * file from the network to service a "rw" mode request, you
2003 * should periodically call
2004 * {@link CancellationSignal#throwIfCanceled()} to check whether
2005 * the client has canceled the request and abort the download.
2006 *
2007 * @return Returns a new AssetFileDescriptor which you can use to access
2008 * the file.
2009 *
2010 * @throws FileNotFoundException Throws FileNotFoundException if there is
2011 * no file associated with the given URI or the mode is invalid.
2012 * @throws SecurityException Throws SecurityException if the caller does
2013 * not have permission to access the file.
2014 *
2015 * @see #openFile(Uri, String)
2016 * @see #openFileHelper(Uri, String)
2017 * @see #getType(android.net.Uri)
2018 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002019 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002020 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
2021 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002022 return openAssetFile(uri, mode);
2023 }
2024
2025 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 * Convenience for subclasses that wish to implement {@link #openFile}
2027 * by looking up a column named "_data" at the given URI.
2028 *
2029 * @param uri The URI to be opened.
2030 * @param mode The file mode. May be "r" for read-only access,
2031 * "w" for write-only access (erasing whatever data is currently in
2032 * the file), "wa" for write-only access to append to any existing data,
2033 * "rw" for read and write access on any existing data, and "rwt" for read
2034 * and write access that truncates any existing file.
2035 *
2036 * @return Returns a new ParcelFileDescriptor that can be used by the
2037 * client to access the file.
2038 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002039 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
2040 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
2042 int count = (c != null) ? c.getCount() : 0;
2043 if (count != 1) {
2044 // If there is not exactly one result, throw an appropriate
2045 // exception.
2046 if (c != null) {
2047 c.close();
2048 }
2049 if (count == 0) {
2050 throw new FileNotFoundException("No entry for " + uri);
2051 }
2052 throw new FileNotFoundException("Multiple items at " + uri);
2053 }
2054
2055 c.moveToFirst();
2056 int i = c.getColumnIndex("_data");
2057 String path = (i >= 0 ? c.getString(i) : null);
2058 c.close();
2059 if (path == null) {
2060 throw new FileNotFoundException("Column _data not found.");
2061 }
2062
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002063 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 return ParcelFileDescriptor.open(new File(path), modeBits);
2065 }
2066
2067 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002068 * Called by a client to determine the types of data streams that this
2069 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002070 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002071 * of a particular type, return that MIME type if it matches the given
2072 * mimeTypeFilter. If it can perform type conversions, return an array
2073 * of all supported MIME types that match mimeTypeFilter.
2074 *
2075 * @param uri The data in the content provider being queried.
2076 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002077 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002078 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002079 * given mimeTypeFilter. Otherwise returns an array of all available
2080 * concrete MIME types.
2081 *
2082 * @see #getType(Uri)
2083 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002084 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002085 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002086 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002087 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002088 return null;
2089 }
2090
2091 /**
2092 * Called by a client to open a read-only stream containing data of a
2093 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2094 * except the file can only be read-only and the content provider may
2095 * perform data conversions to generate data of the desired type.
2096 *
2097 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002098 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002099 * {@link #openAssetFile(Uri, String)}.
2100 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002101 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002102 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002103 * <p>
2104 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2105 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002106 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002107 * <p class="note">For better interoperability with other applications, it is recommended
2108 * that for any URIs that can be opened, you also support queries on them
2109 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2110 * You may also want to support other common columns if you have additional meta-data
2111 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2112 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2113 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002114 * @param uri The data in the content provider being queried.
2115 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002116 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002117 * requirements; in this case the content provider will pick its best
2118 * type matching the pattern.
2119 * @param opts Additional options from the client. The definitions of
2120 * these are specific to the content provider being called.
2121 *
2122 * @return Returns a new AssetFileDescriptor from which the client can
2123 * read data of the desired type.
2124 *
2125 * @throws FileNotFoundException Throws FileNotFoundException if there is
2126 * no file associated with the given URI or the mode is invalid.
2127 * @throws SecurityException Throws SecurityException if the caller does
2128 * not have permission to access the data.
2129 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2130 * content provider does not support the requested MIME type.
2131 *
2132 * @see #getStreamTypes(Uri, String)
2133 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002134 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002135 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002136 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2137 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002138 if ("*/*".equals(mimeTypeFilter)) {
2139 // If they can take anything, the untyped open call is good enough.
2140 return openAssetFile(uri, "r");
2141 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002142 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002143 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002144 // Use old untyped open call if this provider has a type for this
2145 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002146 return openAssetFile(uri, "r");
2147 }
2148 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2149 }
2150
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002151
2152 /**
2153 * Called by a client to open a read-only stream containing data of a
2154 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2155 * except the file can only be read-only and the content provider may
2156 * perform data conversions to generate data of the desired type.
2157 *
2158 * <p>The default implementation compares the given mimeType against the
2159 * result of {@link #getType(Uri)} and, if they match, simply calls
2160 * {@link #openAssetFile(Uri, String)}.
2161 *
2162 * <p>See {@link ClipData} for examples of the use and implementation
2163 * of this method.
2164 * <p>
2165 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2166 * streaming of data.
2167 *
2168 * <p class="note">For better interoperability with other applications, it is recommended
2169 * that for any URIs that can be opened, you also support queries on them
2170 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2171 * You may also want to support other common columns if you have additional meta-data
2172 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2173 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2174 *
2175 * @param uri The data in the content provider being queried.
2176 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002177 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002178 * requirements; in this case the content provider will pick its best
2179 * type matching the pattern.
2180 * @param opts Additional options from the client. The definitions of
2181 * these are specific to the content provider being called.
2182 * @param signal A signal to cancel the operation in progress, or
2183 * {@code null} if none. For example, if you are downloading a
2184 * file from the network to service a "rw" mode request, you
2185 * should periodically call
2186 * {@link CancellationSignal#throwIfCanceled()} to check whether
2187 * the client has canceled the request and abort the download.
2188 *
2189 * @return Returns a new AssetFileDescriptor from which the client can
2190 * read data of the desired type.
2191 *
2192 * @throws FileNotFoundException Throws FileNotFoundException if there is
2193 * no file associated with the given URI or the mode is invalid.
2194 * @throws SecurityException Throws SecurityException if the caller does
2195 * not have permission to access the data.
2196 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2197 * content provider does not support the requested MIME type.
2198 *
2199 * @see #getStreamTypes(Uri, String)
2200 * @see #openAssetFile(Uri, String)
2201 * @see ClipDescription#compareMimeTypes(String, String)
2202 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002203 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002204 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2205 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2206 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002207 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2208 }
2209
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002210 /**
2211 * Interface to write a stream of data to a pipe. Use with
2212 * {@link ContentProvider#openPipeHelper}.
2213 */
2214 public interface PipeDataWriter<T> {
2215 /**
2216 * Called from a background thread to stream data out to a pipe.
2217 * Note that the pipe is blocking, so this thread can block on
2218 * writes for an arbitrary amount of time if the client is slow
2219 * at reading.
2220 *
2221 * @param output The pipe where data should be written. This will be
2222 * closed for you upon returning from this function.
2223 * @param uri The URI whose data is to be written.
2224 * @param mimeType The desired type of data to be written.
2225 * @param opts Options supplied by caller.
2226 * @param args Your own custom arguments.
2227 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002228 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2229 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002230 }
2231
2232 /**
2233 * A helper function for implementing {@link #openTypedAssetFile}, for
2234 * creating a data pipe and background thread allowing you to stream
2235 * generated data back to the client. This function returns a new
2236 * ParcelFileDescriptor that should be returned to the caller (the caller
2237 * is responsible for closing it).
2238 *
2239 * @param uri The URI whose data is to be written.
2240 * @param mimeType The desired type of data to be written.
2241 * @param opts Options supplied by caller.
2242 * @param args Your own custom arguments.
2243 * @param func Interface implementing the function that will actually
2244 * stream the data.
2245 * @return Returns a new ParcelFileDescriptor holding the read side of
2246 * the pipe. This should be returned to the caller for reading; the caller
2247 * is responsible for closing it when done.
2248 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002249 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2250 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2251 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002252 try {
2253 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2254
2255 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2256 @Override
2257 protected Object doInBackground(Object... params) {
2258 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2259 try {
2260 fds[1].close();
2261 } catch (IOException e) {
2262 Log.w(TAG, "Failure closing pipe", e);
2263 }
2264 return null;
2265 }
2266 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002267 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002268
2269 return fds[0];
2270 } catch (IOException e) {
2271 throw new FileNotFoundException("failure making pipe");
2272 }
2273 }
2274
2275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 * Returns true if this instance is a temporary content provider.
2277 * @return true if this instance is a temporary content provider
2278 */
2279 protected boolean isTemporary() {
2280 return false;
2281 }
2282
2283 /**
2284 * Returns the Binder object for this provider.
2285 *
2286 * @return the Binder object for this provider
2287 * @hide
2288 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002289 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 public IContentProvider getIContentProvider() {
2291 return mTransport;
2292 }
2293
2294 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002295 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2296 * when directly instantiating the provider for testing.
2297 * @hide
2298 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002299 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002300 public void attachInfoForTesting(Context context, ProviderInfo info) {
2301 attachInfo(context, info, true);
2302 }
2303
2304 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 * After being instantiated, this is called to tell the content provider
2306 * about itself.
2307 *
2308 * @param context The context this provider is running in
2309 * @param info Registered information about this content provider
2310 */
2311 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002312 attachInfo(context, info, false);
2313 }
2314
2315 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002316 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002317 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 /*
2320 * Only allow it to be set once, so after the content service gives
2321 * this to us clients can't change it.
2322 */
2323 if (mContext == null) {
2324 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002325 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002326 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2327 Context.APP_OPS_SERVICE);
2328 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002329 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 if (info != null) {
2331 setReadPermission(info.readPermission);
2332 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002333 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002334 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002335 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002336 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002338 if (Build.IS_DEBUGGABLE) {
2339 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2340 Log.VERBOSE));
2341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 ContentProvider.this.onCreate();
2343 }
2344 }
Fred Quintanace31b232009-05-04 16:01:15 -07002345
2346 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002347 * Override this to handle requests to perform a batch of operations, or the
2348 * default implementation will iterate over the operations and call
2349 * {@link ContentProviderOperation#apply} on each of them.
2350 * If all calls to {@link ContentProviderOperation#apply} succeed
2351 * then a {@link ContentProviderResult} array with as many
2352 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002353 * fail, it is up to the implementation how many of the others take effect.
2354 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002355 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2356 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002357 *
Fred Quintanace31b232009-05-04 16:01:15 -07002358 * @param operations the operations to apply
2359 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002360 * @throws OperationApplicationException thrown if any operation fails.
2361 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002362 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002363 @Override
2364 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2365 @NonNull ArrayList<ContentProviderOperation> operations)
2366 throws OperationApplicationException {
2367 return applyBatch(operations);
2368 }
2369
Jeff Sharkey673db442015-06-11 19:30:57 -07002370 public @NonNull ContentProviderResult[] applyBatch(
2371 @NonNull ArrayList<ContentProviderOperation> operations)
2372 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002373 final int numOperations = operations.size();
2374 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2375 for (int i = 0; i < numOperations; i++) {
2376 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002377 }
2378 return results;
2379 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002380
2381 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002382 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002383 * interfaces that are cheaper and/or unnatural for a table-like
2384 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002385 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002386 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2387 * on this entry into the content provider besides the basic ability for the application
2388 * to get access to the provider at all. For example, it has no idea whether the call
2389 * being executed may read or write data in the provider, so can't enforce those
2390 * individual permissions. Any implementation of this method <strong>must</strong>
2391 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2392 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002393 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2394 * @param arg provider-defined String argument. May be {@code null}.
2395 * @param extras provider-defined Bundle argument. May be {@code null}.
2396 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002397 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002398 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002399 @Override
2400 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2401 @Nullable String arg, @Nullable Bundle extras) {
2402 return call(method, arg, extras);
2403 }
2404
Jeff Sharkey673db442015-06-11 19:30:57 -07002405 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2406 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002407 return null;
2408 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002409
2410 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002411 * Implement this to shut down the ContentProvider instance. You can then
2412 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002413 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002414 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002415 * Android normally handles ContentProvider startup and shutdown
2416 * automatically. You do not need to start up or shut down a
2417 * ContentProvider. When you invoke a test method on a ContentProvider,
2418 * however, a ContentProvider instance is started and keeps running after
2419 * the test finishes, even if a succeeding test instantiates another
2420 * ContentProvider. A conflict develops because the two instances are
2421 * usually running against the same underlying data source (for example, an
2422 * sqlite database).
2423 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002424 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002425 * Implementing shutDown() avoids this conflict by providing a way to
2426 * terminate the ContentProvider. This method can also prevent memory leaks
2427 * from multiple instantiations of the ContentProvider, and it can ensure
2428 * unit test isolation by allowing you to completely clean up the test
2429 * fixture before moving on to the next test.
2430 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002431 */
2432 public void shutdown() {
2433 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2434 "connections are gracefully shutdown");
2435 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002436
2437 /**
2438 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002439 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002440 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002441 * @param fd The raw file descriptor that the dump is being sent to.
2442 * @param writer The PrintWriter to which you should dump your state. This will be
2443 * closed for you after you return.
2444 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002445 */
2446 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2447 writer.println("nothing to dump");
2448 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002449
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002450 private void validateIncomingAuthority(String authority) throws SecurityException {
2451 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2452 String message = "The authority " + authority + " does not match the one of the "
2453 + "contentProvider: ";
2454 if (mAuthority != null) {
2455 message += mAuthority;
2456 } else {
2457 message += Arrays.toString(mAuthorities);
2458 }
2459 throw new SecurityException(message);
2460 }
2461 }
2462
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002463 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002464 @VisibleForTesting
2465 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002466 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002467 if (!mSingleUser) {
2468 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2469 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2470 throw new SecurityException("trying to query a ContentProvider in user "
2471 + mContext.getUserId() + " with a uri belonging to user " + userId);
2472 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002473 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002474 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002475
2476 // Normalize the path by removing any empty path segments, which can be
2477 // a source of security issues.
2478 final String encodedPath = uri.getEncodedPath();
2479 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002480 final Uri normalized = uri.buildUpon()
2481 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2482 Log.w(TAG, "Normalized " + uri + " to " + normalized
2483 + " to avoid possible security issues");
2484 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002485 } else {
2486 return uri;
2487 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002488 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002489
2490 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002491 private Uri maybeGetUriWithoutUserId(Uri uri) {
2492 if (mSingleUser) {
2493 return uri;
2494 }
2495 return getUriWithoutUserId(uri);
2496 }
2497
2498 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002499 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2500 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002501 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002502 if (end == -1) return defaultUserId;
2503 String userIdString = auth.substring(0, end);
2504 try {
2505 return Integer.parseInt(userIdString);
2506 } catch (NumberFormatException e) {
2507 Log.w(TAG, "Error parsing userId.", e);
2508 return UserHandle.USER_NULL;
2509 }
2510 }
2511
2512 /** @hide */
2513 public static int getUserIdFromAuthority(String auth) {
2514 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2515 }
2516
2517 /** @hide */
2518 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2519 if (uri == null) return defaultUserId;
2520 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2521 }
2522
2523 /** @hide */
2524 public static int getUserIdFromUri(Uri uri) {
2525 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2526 }
2527
2528 /**
2529 * Removes userId part from authority string. Expects format:
2530 * userId@some.authority
2531 * If there is no userId in the authority, it symply returns the argument
2532 * @hide
2533 */
2534 public static String getAuthorityWithoutUserId(String auth) {
2535 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002536 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002537 return auth.substring(end+1);
2538 }
2539
2540 /** @hide */
2541 public static Uri getUriWithoutUserId(Uri uri) {
2542 if (uri == null) return null;
2543 Uri.Builder builder = uri.buildUpon();
2544 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2545 return builder.build();
2546 }
2547
2548 /** @hide */
2549 public static boolean uriHasUserId(Uri uri) {
2550 if (uri == null) return false;
2551 return !TextUtils.isEmpty(uri.getUserInfo());
2552 }
2553
2554 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002555 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002556 public static Uri maybeAddUserId(Uri uri, int userId) {
2557 if (uri == null) return null;
2558 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002559 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002560 if (!uriHasUserId(uri)) {
2561 //We don't add the user Id if there's already one
2562 Uri.Builder builder = uri.buildUpon();
2563 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2564 return builder.build();
2565 }
2566 }
2567 return uri;
2568 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002569}