blob: e1942da8ac7fefea60a724bf121ec43a734ff518 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Nicolas Prevot504d78e2014-06-26 10:07:33 +010019import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Varun Shahaf8cfe32019-08-16 16:11:24 -070020import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070021import static android.app.AppOpsManager.MODE_ALLOWED;
Eugene Susla93519852018-06-13 16:44:31 -070022import static android.app.AppOpsManager.MODE_DEFAULT;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070023import static android.app.AppOpsManager.MODE_ERRORED;
24import static android.app.AppOpsManager.MODE_IGNORED;
25import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060026import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070027
Jeff Sharkey673db442015-06-11 19:30:57 -070028import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080029import android.annotation.Nullable;
Jeff Sharkey197fe1f2020-01-07 22:06:37 -070030import android.annotation.SystemApi;
Alex Kershawba014ac2020-01-20 22:25:02 +000031import android.annotation.TestApi;
Dianne Hackborn35654b62013-01-14 17:38:02 -080032import android.app.AppOpsManager;
Artur Satayeve23a0eb2019-12-10 17:47:52 +000033import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey9edef252019-05-20 14:00:17 -060034import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070035import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.pm.ProviderInfo;
37import android.content.res.AssetFileDescriptor;
38import android.content.res.Configuration;
39import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070040import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.database.SQLException;
42import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070043import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010045import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080046import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070047import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080048import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070049import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070051import android.os.Process;
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -080052import android.os.RemoteCallback;
Ben Lin1cf454f2016-11-10 13:50:54 -080053import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060054import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070055import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060056import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010057import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070058import android.util.Log;
Philip P. Moltmann128b7032019-09-27 08:44:12 -070059import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060061import com.android.internal.annotations.VisibleForTesting;
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080064import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070066import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080067import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070068import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080069import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060070import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72/**
73 * Content providers are one of the primary building blocks of Android applications, providing
74 * content to applications. They encapsulate data and provide it to applications through the single
75 * {@link ContentResolver} interface. A content provider is only required if you need to share
76 * data between multiple applications. For example, the contacts data is used by multiple
77 * applications and must be stored in a content provider. If you don't need to share data amongst
78 * multiple applications you can use a database directly via
79 * {@link android.database.sqlite.SQLiteDatabase}.
80 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 * <p>When a request is made via
82 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
83 * request to the content provider registered with the authority. The content provider can interpret
84 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
85 * URIs.</p>
86 *
87 * <p>The primary methods that need to be implemented are:
88 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070089 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 * <li>{@link #query} which returns data to the caller</li>
91 * <li>{@link #insert} which inserts new data into the content provider</li>
92 * <li>{@link #update} which updates existing data in the content provider</li>
93 * <li>{@link #delete} which deletes data from the content provider</li>
94 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
95 * </ul></p>
96 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070097 * <p class="caution">Data access methods (such as {@link #insert} and
98 * {@link #update}) may be called from many threads at once, and must be thread-safe.
99 * Other methods (such as {@link #onCreate}) are only called from the application
100 * main thread, and must avoid performing lengthy operations. See the method
101 * descriptions for their expected thread behavior.</p>
102 *
103 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
104 * ContentProvider instance, so subclasses don't have to worry about the details of
105 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700106 *
107 * <div class="special reference">
108 * <h3>Developer Guides</h3>
109 * <p>For more information about using content providers, read the
110 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
111 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700112 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700114public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800115
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700116 private static final String TAG = "ContentProvider";
117
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900118 /*
119 * Note: if you add methods to ContentProvider, you must add similar methods to
120 * MockContentProvider.
121 */
122
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100123 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700125 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100126
127 // Since most Providers have only one authority, we keep both a String and a String[] to improve
128 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100130 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100131 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100132 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100133 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100135 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100137 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700138 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700139 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800140 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700141 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700143 private ThreadLocal<Pair<String, String>> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private Transport mTransport = new Transport();
146
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700147 /**
148 * Construct a ContentProvider instance. Content providers must be
149 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
150 * in the manifest</a>, accessed with {@link ContentResolver}, and created
151 * automatically by the system, so applications usually do not create
152 * ContentProvider instances directly.
153 *
154 * <p>At construction time, the object is uninitialized, and most fields and
155 * methods are unavailable. Subclasses should initialize themselves in
156 * {@link #onCreate}, not the constructor.
157 *
158 * <p>Content providers are created on the application main thread at
159 * application launch time. The constructor must not perform lengthy
160 * operations, or application startup will be delayed.
161 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900162 public ContentProvider() {
163 }
164
165 /**
166 * Constructor just for mocking.
167 *
168 * @param context A Context object which should be some mock instance (like the
169 * instance of {@link android.test.mock.MockContext}).
170 * @param readPermission The read permision you want this instance should have in the
171 * test, which is available via {@link #getReadPermission()}.
172 * @param writePermission The write permission you want this instance should have
173 * in the test, which is available via {@link #getWritePermission()}.
174 * @param pathPermissions The PathPermissions you want this instance should have
175 * in the test, which is available via {@link #getPathPermissions()}.
176 * @hide
177 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900179 public ContentProvider(
180 Context context,
181 String readPermission,
182 String writePermission,
183 PathPermission[] pathPermissions) {
184 mContext = context;
185 mReadPermission = readPermission;
186 mWritePermission = writePermission;
187 mPathPermissions = pathPermissions;
188 }
189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 /**
191 * Given an IContentProvider, try to coerce it back to the real
192 * ContentProvider object if it is running in the local process. This can
193 * be used if you know you are running in the same process as a provider,
194 * and want to get direct access to its implementation details. Most
195 * clients should not nor have a reason to use it.
196 *
197 * @param abstractInterface The ContentProvider interface that is to be
198 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800199 * @return If the IContentProvider is non-{@code null} and local, returns its actual
200 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 * @hide
202 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100203 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 public static ContentProvider coerceToLocalContentProvider(
205 IContentProvider abstractInterface) {
206 if (abstractInterface instanceof Transport) {
207 return ((Transport)abstractInterface).getContentProvider();
208 }
209 return null;
210 }
211
212 /**
213 * Binder object that deals with remoting.
214 *
215 * @hide
216 */
217 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700218 volatile AppOpsManager mAppOpsManager = null;
219 volatile int mReadOp = AppOpsManager.OP_NONE;
220 volatile int mWriteOp = AppOpsManager.OP_NONE;
221 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 ContentProvider getContentProvider() {
224 return ContentProvider.this;
225 }
226
Jeff Brownd2183652011-10-09 12:39:53 -0700227 @Override
228 public String getProviderName() {
229 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 }
231
Jeff Brown75ea64f2012-01-25 19:37:13 -0800232 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700233 public Cursor query(String callingPkg, @Nullable String featureId, Uri uri,
234 @Nullable String[] projection, @Nullable Bundle queryArgs,
235 @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600236 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100237 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700238 if (enforceReadPermission(callingPkg, featureId, uri, null)
239 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700240 // The caller has no access to the data, so return an empty cursor with
241 // the columns in the requested order. The caller may ask for an invalid
242 // column and we would not catch that but this is not a problem in practice.
243 // We do not call ContentProvider#query with a modified where clause since
244 // the implementation is not guaranteed to be backed by a SQL database, hence
245 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700246 if (projection != null) {
247 return new MatrixCursor(projection, 0);
248 }
249
250 // Null projection means all columns but we have no idea which they are.
251 // However, the caller may be expecting to access them my index. Hence,
252 // we have to execute the query as if allowed to get a cursor with the
253 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700254 Cursor cursor;
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700255 final Pair<String, String> original = setCallingPackage(
256 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700257 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700258 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700259 uri, projection, queryArgs,
260 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700261 } catch (RemoteException e) {
262 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700263 } finally {
264 setCallingPackage(original);
265 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700266 if (cursor == null) {
267 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700268 }
269
270 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700271 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800272 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600273 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700274 final Pair<String, String> original = setCallingPackage(
275 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700276 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700277 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800278 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700279 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700280 } catch (RemoteException e) {
281 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700282 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700283 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600284 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287
Jeff Brown75ea64f2012-01-25 19:37:13 -0800288 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700290 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600291 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100292 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600293 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
294 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700295 return mInterface.getType(uri);
296 } catch (RemoteException e) {
297 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600298 } finally {
299 Trace.traceEnd(TRACE_TAG_DATABASE);
300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
Jeff Brown75ea64f2012-01-25 19:37:13 -0800303 @Override
Dmitri Plotnikovd55a3872020-01-16 17:00:02 -0800304 public void getTypeAsync(Uri uri, RemoteCallback callback) {
305 final Bundle result = new Bundle();
306 result.putString(ContentResolver.REMOTE_CALLBACK_RESULT, getType(uri));
307 callback.sendResult(result);
308 }
309
310 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700311 public Uri insert(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700312 ContentValues initialValues, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600313 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100314 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100315 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700316 if (enforceWritePermission(callingPkg, featureId, uri, null)
317 != AppOpsManager.MODE_ALLOWED) {
318 final Pair<String, String> original = setCallingPackage(
319 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700320 try {
321 return rejectInsert(uri, initialValues);
322 } finally {
323 setCallingPackage(original);
324 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800325 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600326 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700327 final Pair<String, String> original = setCallingPackage(
328 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700329 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700330 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700331 } catch (RemoteException e) {
332 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700333 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700334 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600335 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
338
Jeff Brown75ea64f2012-01-25 19:37:13 -0800339 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700340 public int bulkInsert(String callingPkg, @Nullable String featureId, Uri uri,
341 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600342 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100343 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700344 if (enforceWritePermission(callingPkg, featureId, uri, null)
345 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800346 return 0;
347 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600348 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700349 final Pair<String, String> original = setCallingPackage(
350 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700351 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700352 return mInterface.bulkInsert(uri, initialValues);
353 } catch (RemoteException e) {
354 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700356 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600357 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 }
360
Jeff Brown75ea64f2012-01-25 19:37:13 -0800361 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700362 public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String featureId,
363 String authority, ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700364 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700365 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100366 int numOperations = operations.size();
367 final int[] userIds = new int[numOperations];
368 for (int i = 0; i < numOperations; i++) {
369 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100370 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600371 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600372 uri = validateIncomingUri(uri);
373 uri = maybeGetUriWithoutUserId(uri);
374 // Rebuild operation if we changed the Uri above
375 if (!Objects.equals(operation.getUri(), uri)) {
376 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100377 operations.set(i, operation);
378 }
Fred Quintana89437372009-05-15 15:10:40 -0700379 if (operation.isReadOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700380 if (enforceReadPermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800381 != AppOpsManager.MODE_ALLOWED) {
382 throw new OperationApplicationException("App op not allowed", 0);
383 }
Fred Quintana89437372009-05-15 15:10:40 -0700384 }
Fred Quintana89437372009-05-15 15:10:40 -0700385 if (operation.isWriteOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700386 if (enforceWritePermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800387 != AppOpsManager.MODE_ALLOWED) {
388 throw new OperationApplicationException("App op not allowed", 0);
389 }
Fred Quintana89437372009-05-15 15:10:40 -0700390 }
391 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600392 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700393 final Pair<String, String> original = setCallingPackage(
394 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700395 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700396 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700397 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800398 if (results != null) {
399 for (int i = 0; i < results.length ; i++) {
400 if (userIds[i] != UserHandle.USER_CURRENT) {
401 // Adding the userId to the uri.
402 results[i] = new ContentProviderResult(results[i], userIds[i]);
403 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100404 }
405 }
406 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700407 } catch (RemoteException e) {
408 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700409 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700410 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600411 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700412 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700413 }
414
Jeff Brown75ea64f2012-01-25 19:37:13 -0800415 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700416 public int delete(String callingPkg, @Nullable String featureId, Uri uri, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600417 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100418 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700419 if (enforceWritePermission(callingPkg, featureId, uri, null)
420 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800421 return 0;
422 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600423 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700424 final Pair<String, String> original = setCallingPackage(
425 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700426 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700427 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700428 } catch (RemoteException e) {
429 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700430 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700431 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600432 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435
Jeff Brown75ea64f2012-01-25 19:37:13 -0800436 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700437 public int update(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700438 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600439 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100440 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700441 if (enforceWritePermission(callingPkg, featureId, uri, null)
442 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800443 return 0;
444 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600445 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700446 final Pair<String, String> original = setCallingPackage(
447 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700448 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700449 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700450 } catch (RemoteException e) {
451 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700452 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700453 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600454 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 }
457
Jeff Brown75ea64f2012-01-25 19:37:13 -0800458 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700459 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId,
460 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
461 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600462 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100463 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700464 enforceFilePermission(callingPkg, featureId, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600465 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700466 final Pair<String, String> original = setCallingPackage(
467 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700468 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700469 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700470 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700471 } catch (RemoteException e) {
472 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700473 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700474 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600475 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478
Jeff Brown75ea64f2012-01-25 19:37:13 -0800479 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700480 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
481 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600483 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100484 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700485 enforceFilePermission(callingPkg, featureId, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600486 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700487 final Pair<String, String> original = setCallingPackage(
488 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700489 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700490 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700491 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700492 } catch (RemoteException e) {
493 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700494 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700495 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600496 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
499
Jeff Brown75ea64f2012-01-25 19:37:13 -0800500 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700501 public Bundle call(String callingPkg, @Nullable String featureId, String authority,
502 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700503 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600504 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600505 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700506 final Pair<String, String> original = setCallingPackage(
507 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700508 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700509 return mInterface.call(authority, method, arg, extras);
510 } catch (RemoteException e) {
511 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700512 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700513 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600514 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700515 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800516 }
517
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700518 @Override
519 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700520 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600521 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100522 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600523 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
524 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700525 return mInterface.getStreamTypes(uri, mimeTypeFilter);
526 } catch (RemoteException e) {
527 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600528 } finally {
529 Trace.traceEnd(TRACE_TAG_DATABASE);
530 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700531 }
532
533 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700534 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
535 @Nullable String featureId, Uri uri, String mimeType, Bundle opts,
536 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600537 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600538 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100539 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700540 enforceFilePermission(callingPkg, featureId, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600541 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700542 final Pair<String, String> original = setCallingPackage(
543 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700544 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700545 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700546 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700547 } catch (RemoteException e) {
548 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700549 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700550 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600551 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700552 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700553 }
554
Jeff Brown75ea64f2012-01-25 19:37:13 -0800555 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700556 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800557 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800558 }
559
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700560 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700561 public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600562 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100563 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100564 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700565 if (enforceReadPermission(callingPkg, featureId, uri, null)
566 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700567 return null;
568 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600569 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700570 final Pair<String, String> original = setCallingPackage(
571 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700572 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700573 return maybeAddUserId(mInterface.canonicalize(uri), userId);
574 } catch (RemoteException e) {
575 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700576 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700577 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600578 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700579 }
580 }
581
582 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700583 public Uri uncanonicalize(String callingPkg, String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600584 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100585 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100586 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700587 if (enforceReadPermission(callingPkg, featureId, uri, null)
588 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700589 return null;
590 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600591 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700592 final Pair<String, String> original = setCallingPackage(
593 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700594 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700595 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
596 } catch (RemoteException e) {
597 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700598 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700599 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600600 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700601 }
602 }
603
Ben Lin1cf454f2016-11-10 13:50:54 -0800604 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700605 public boolean refresh(String callingPkg, String featureId, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800606 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600607 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800608 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700609 if (enforceReadPermission(callingPkg, featureId, uri, null)
610 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800611 return false;
612 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600613 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700614 final Pair<String, String> original = setCallingPackage(
615 new Pair<>(callingPkg, featureId));
Ben Lin1cf454f2016-11-10 13:50:54 -0800616 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700617 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800618 CancellationSignal.fromTransport(cancellationSignal));
619 } finally {
620 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600621 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800622 }
623 }
624
Jeff Sharkey9edef252019-05-20 14:00:17 -0600625 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700626 public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri,
627 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600628 uri = validateIncomingUri(uri);
629 uri = maybeGetUriWithoutUserId(uri);
630 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700631 final Pair<String, String> original = setCallingPackage(
632 new Pair<>(callingPkg, featureId));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600633 try {
634 return mInterface.checkUriPermission(uri, uid, modeFlags);
635 } catch (RemoteException e) {
636 throw e.rethrowAsRuntimeException();
637 } finally {
638 setCallingPackage(original);
639 Trace.traceEnd(TRACE_TAG_DATABASE);
640 }
641 }
642
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700643 private void enforceFilePermission(String callingPkg, @Nullable String featureId, Uri uri,
644 String mode, IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800645 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700646 if (enforceWritePermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800647 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800648 throw new FileNotFoundException("App op not allowed");
649 }
650 } else {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700651 if (enforceReadPermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800652 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800653 throw new FileNotFoundException("App op not allowed");
654 }
655 }
656 }
657
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700658 private int enforceReadPermission(String callingPkg, @Nullable String featureId, Uri uri,
659 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800660 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700661 final int mode = enforceReadPermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700662 if (mode != MODE_ALLOWED) {
663 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800664 }
Svet Ganov99b60432015-06-27 13:15:22 -0700665
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700666 return noteProxyOp(callingPkg, featureId, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800667 }
668
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700669 private int enforceWritePermission(String callingPkg, String featureId, Uri uri,
670 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800671 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700672 final int mode = enforceWritePermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700673 if (mode != MODE_ALLOWED) {
674 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800675 }
Svet Ganov99b60432015-06-27 13:15:22 -0700676
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700677 return noteProxyOp(callingPkg, featureId, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700678 }
679
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700680 private int noteProxyOp(String callingPkg, String featureId, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700681 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700682 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
683 featureId, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700684 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700685 }
686
Dianne Hackborn35654b62013-01-14 17:38:02 -0800687 return AppOpsManager.MODE_ALLOWED;
688 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700689 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800690
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100691 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700692 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
693 return true;
694 }
695 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
696 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100697 == PERMISSION_GRANTED;
698 }
699
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700700 /**
701 * Verify that calling app holds both the given permission and any app-op
702 * associated with that permission.
703 */
704 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700705 @Nullable String featureId, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700706 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
707 callerToken) != PERMISSION_GRANTED) {
708 return MODE_ERRORED;
709 }
710
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700711 return mTransport.noteProxyOp(callingPkg, featureId,
712 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700713 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700714
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700715 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700716 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
717 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700718 final Context context = getContext();
719 final int pid = Binder.getCallingPid();
720 final int uid = Binder.getCallingUid();
721 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700722 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700723
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700724 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700725 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700726 }
727
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100728 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700729 final String componentPerm = getReadPermission();
730 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700731 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
732 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700733 if (mode == MODE_ALLOWED) {
734 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700735 } else {
736 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700737 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700738 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700739 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700740
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700741 // track if unprotected read is allowed; any denied
742 // <path-permission> below removes this ability
743 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700744
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700745 final PathPermission[] pps = getPathPermissions();
746 if (pps != null) {
747 final String path = uri.getPath();
748 for (PathPermission pp : pps) {
749 final String pathPerm = pp.getReadPermission();
750 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700751 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
752 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700753 if (mode == MODE_ALLOWED) {
754 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700755 } else {
756 // any denied <path-permission> means we lose
757 // default <provider> access.
758 allowDefaultRead = false;
759 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700760 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700761 }
762 }
763 }
764 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700765
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700766 // if we passed <path-permission> checks above, and no default
767 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700768 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700770
771 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800772 final int callingUserId = UserHandle.getUserId(uid);
773 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
774 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800775 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
776 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700777 return MODE_ALLOWED;
778 }
779
780 // If the worst denial we found above was ignored, then pass that
781 // ignored through; otherwise we assume it should be a real error below.
782 if (strongestMode == MODE_IGNORED) {
783 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700784 }
785
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600786 final String suffix;
787 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
788 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
789 } else if (mExported) {
790 suffix = " requires " + missingPerm + ", or grantUriPermission()";
791 } else {
792 suffix = " requires the provider be exported, or grantUriPermission()";
793 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700794 throw new SecurityException("Permission Denial: reading "
795 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600796 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700797 }
798
799 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700800 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
801 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700802 final Context context = getContext();
803 final int pid = Binder.getCallingPid();
804 final int uid = Binder.getCallingUid();
805 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700806 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700807
808 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700809 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700810 }
811
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100812 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700813 final String componentPerm = getWritePermission();
814 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700815 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
816 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700817 if (mode == MODE_ALLOWED) {
818 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700819 } else {
820 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700821 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700822 }
823 }
824
825 // track if unprotected write is allowed; any denied
826 // <path-permission> below removes this ability
827 boolean allowDefaultWrite = (componentPerm == null);
828
829 final PathPermission[] pps = getPathPermissions();
830 if (pps != null) {
831 final String path = uri.getPath();
832 for (PathPermission pp : pps) {
833 final String pathPerm = pp.getWritePermission();
834 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700835 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
836 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700837 if (mode == MODE_ALLOWED) {
838 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700839 } else {
840 // any denied <path-permission> means we lose
841 // default <provider> access.
842 allowDefaultWrite = false;
843 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700844 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700845 }
846 }
847 }
848 }
849
850 // if we passed <path-permission> checks above, and no default
851 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700852 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700853 }
854
855 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800856 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
857 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700858 return MODE_ALLOWED;
859 }
860
861 // If the worst denial we found above was ignored, then pass that
862 // ignored through; otherwise we assume it should be a real error below.
863 if (strongestMode == MODE_IGNORED) {
864 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700865 }
866
867 final String failReason = mExported
868 ? " requires " + missingPerm + ", or grantUriPermission()"
869 : " requires the provider be exported, or grantUriPermission()";
870 throw new SecurityException("Permission Denial: writing "
871 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
872 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700876 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800877 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 * constructor.
879 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700880 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 return mContext;
882 }
883
884 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700885 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
886 * after {@link #onCreate}. When called before context was created, an IllegalStateException
887 * will be thrown.
888 * <p>
889 * Note A provider must be declared in the manifest and created automatically by the system,
890 * and context is only available after {@link #onCreate} is called.
891 */
892 @NonNull
893 public final Context requireContext() {
894 final Context ctx = getContext();
895 if (ctx == null) {
896 throw new IllegalStateException("Cannot find context from the provider.");
897 }
898 return ctx;
899 }
900
901 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700902 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700903 * which can be used later to restore the previous state.
904 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700905 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
906 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700907 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600908 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700909 return original;
910 }
911
912 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700913 * Return the package name of the caller that initiated the request being
914 * processed on the current thread. The returned package will have been
915 * verified to belong to the calling UID. Returns {@code null} if not
916 * currently processing a request.
917 * <p>
918 * This will always return {@code null} when processing
919 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
920 *
921 * @see Binder#getCallingUid()
922 * @see Context#grantUriPermission(String, Uri, int)
923 * @throws SecurityException if the calling package doesn't belong to the
924 * calling UID.
925 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700926 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700927 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700928 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700929 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
930 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700931 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700932
933 return null;
934 }
935
936 /**
937 * Return the feature in the package of the caller that initiated the request being
938 * processed on the current thread. Returns {@code null} if not currently processing
939 * a request of the request is for the default feature.
940 * <p>
941 * This will always return {@code null} when processing
942 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
943 *
944 * @see #getCallingPackage
945 */
946 public final @Nullable String getCallingFeatureId() {
947 final Pair<String, String> pkg = mCallingPackage.get();
948 if (pkg != null) {
949 return pkg.second;
950 }
951
952 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700953 }
954
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700955 /**
956 * Return the package name of the caller that initiated the request being
957 * processed on the current thread. The returned package will have
958 * <em>not</em> been verified to belong to the calling UID. Returns
959 * {@code null} if not currently processing a request.
960 * <p>
961 * This will always return {@code null} when processing
962 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
963 *
964 * @see Binder#getCallingUid()
965 * @see Context#grantUriPermission(String, Uri, int)
966 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600967 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700968 final Pair<String, String> pkg = mCallingPackage.get();
969 if (pkg != null) {
970 return pkg.first;
971 }
972
973 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600974 }
975
Jeff Sharkey197fe1f2020-01-07 22:06:37 -0700976 /**
977 * Called whenever the value of {@link #getCallingPackage()} changes, giving
978 * the provider an opportunity to invalidate any security related caching it
979 * may be performing.
980 * <p>
981 * This typically happens when a {@link ContentProvider} makes a nested call
982 * back into itself when already processing a call from a remote process.
983 */
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600984 public void onCallingPackageChanged() {
985 }
986
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700987 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600988 * Opaque token representing the identity of an incoming IPC.
989 */
990 public final class CallingIdentity {
991 /** {@hide} */
992 public final long binderToken;
993 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700994 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600995
996 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700997 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600998 this.binderToken = binderToken;
999 this.callingPackage = callingPackage;
1000 }
1001 }
1002
1003 /**
1004 * Reset the identity of the incoming IPC on the current thread.
1005 * <p>
1006 * Internally this calls {@link Binder#clearCallingIdentity()} and also
1007 * clears any value stored in {@link #getCallingPackage()}.
1008 *
1009 * @return Returns an opaque token that can be used to restore the original
1010 * calling identity by passing it to
1011 * {@link #restoreCallingIdentity}.
1012 */
1013 public final @NonNull CallingIdentity clearCallingIdentity() {
1014 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
1015 }
1016
1017 /**
1018 * Restore the identity of the incoming IPC on the current thread back to a
1019 * previously identity that was returned by {@link #clearCallingIdentity}.
1020 * <p>
1021 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
1022 * also restores any value stored in {@link #getCallingPackage()}.
1023 */
1024 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
1025 Binder.restoreCallingIdentity(identity.binderToken);
1026 mCallingPackage.set(identity.callingPackage);
1027 }
1028
1029 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001030 * Change the authorities of the ContentProvider.
1031 * This is normally set for you from its manifest information when the provider is first
1032 * created.
1033 * @hide
1034 * @param authorities the semi-colon separated authorities of the ContentProvider.
1035 */
1036 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001037 if (authorities != null) {
1038 if (authorities.indexOf(';') == -1) {
1039 mAuthority = authorities;
1040 mAuthorities = null;
1041 } else {
1042 mAuthority = null;
1043 mAuthorities = authorities.split(";");
1044 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001045 }
1046 }
1047
1048 /** @hide */
1049 protected final boolean matchesOurAuthorities(String authority) {
1050 if (mAuthority != null) {
1051 return mAuthority.equals(authority);
1052 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001053 if (mAuthorities != null) {
1054 int length = mAuthorities.length;
1055 for (int i = 0; i < length; i++) {
1056 if (mAuthorities[i].equals(authority)) return true;
1057 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001058 }
1059 return false;
1060 }
1061
1062
1063 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 * Change the permission required to read data from the content
1065 * provider. This is normally set for you from its manifest information
1066 * when the provider is first created.
1067 *
1068 * @param permission Name of the permission required for read-only access.
1069 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001070 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 mReadPermission = permission;
1072 }
1073
1074 /**
1075 * Return the name of the permission required for read-only access to
1076 * this content provider. This method can be called from multiple
1077 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001078 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1079 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001081 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 return mReadPermission;
1083 }
1084
1085 /**
1086 * Change the permission required to read and write data in the content
1087 * provider. This is normally set for you from its manifest information
1088 * when the provider is first created.
1089 *
1090 * @param permission Name of the permission required for read/write access.
1091 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001092 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 mWritePermission = permission;
1094 }
1095
1096 /**
1097 * Return the name of the permission required for read/write access to
1098 * this content provider. This method can be called from multiple
1099 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001100 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1101 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001103 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 return mWritePermission;
1105 }
1106
1107 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001108 * Change the path-based permission required to read and/or write data in
1109 * the content provider. This is normally set for you from its manifest
1110 * information when the provider is first created.
1111 *
1112 * @param permissions Array of path permission descriptions.
1113 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001114 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001115 mPathPermissions = permissions;
1116 }
1117
1118 /**
1119 * Return the path-based permissions required for read and/or write access to
1120 * this content provider. This method can be called from multiple
1121 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001122 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1123 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001124 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001125 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001126 return mPathPermissions;
1127 }
1128
Dianne Hackborn35654b62013-01-14 17:38:02 -08001129 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001130 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001131 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001132 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001133 mTransport.mReadOp = readOp;
1134 mTransport.mWriteOp = writeOp;
1135 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001136 }
1137
Dianne Hackborn961321f2013-02-05 17:22:41 -08001138 /** @hide */
1139 public AppOpsManager getAppOpsManager() {
1140 return mTransport.mAppOpsManager;
1141 }
1142
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001143 /** @hide */
1144 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001145 if (mTransport == null) {
1146 return;
1147 }
1148 if (enabled) {
1149 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1150 } else {
1151 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001152 }
1153 }
1154
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001155 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001156 * Implement this to initialize your content provider on startup.
1157 * This method is called for all registered content providers on the
1158 * application main thread at application launch time. It must not perform
1159 * lengthy operations, or application startup will be delayed.
1160 *
1161 * <p>You should defer nontrivial initialization (such as opening,
1162 * upgrading, and scanning databases) until the content provider is used
1163 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1164 * keeps application startup fast, avoids unnecessary work if the provider
1165 * turns out not to be needed, and stops database errors (such as a full
1166 * disk) from halting application launch.
1167 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001168 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001169 * is a helpful utility class that makes it easy to manage databases,
1170 * and will automatically defer opening until first use. If you do use
1171 * SQLiteOpenHelper, make sure to avoid calling
1172 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1173 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1174 * from this method. (Instead, override
1175 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1176 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 *
1178 * @return true if the provider was successfully loaded, false otherwise
1179 */
1180 public abstract boolean onCreate();
1181
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001182 /**
1183 * {@inheritDoc}
1184 * This method is always called on the application main thread, and must
1185 * not perform lengthy operations.
1186 *
1187 * <p>The default content provider implementation does nothing.
1188 * Override this method to take appropriate action.
1189 * (Content providers do not usually care about things like screen
1190 * orientation, but may want to know about locale changes.)
1191 */
Steve McKayea93fe72016-12-02 11:35:35 -08001192 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 public void onConfigurationChanged(Configuration newConfig) {
1194 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001195
1196 /**
1197 * {@inheritDoc}
1198 * This method is always called on the application main thread, and must
1199 * not perform lengthy operations.
1200 *
1201 * <p>The default content provider implementation does nothing.
1202 * Subclasses may override this method to take appropriate action.
1203 */
Steve McKayea93fe72016-12-02 11:35:35 -08001204 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 public void onLowMemory() {
1206 }
1207
Steve McKayea93fe72016-12-02 11:35:35 -08001208 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001209 public void onTrimMemory(int level) {
1210 }
1211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001213 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001214 *
1215 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1216 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1217 * implementation of this method.
1218 *
1219 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001220 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1221 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 * <p>
1223 * Example client call:<p>
1224 * <pre>// Request a specific record.
1225 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001226 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 projection, // Which columns to return.
1228 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001229 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 People.NAME + " ASC"); // Sort order.</pre>
1231 * Example implementation:<p>
1232 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1233 // proper SQL syntax for us.
1234 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1235
1236 // Set the table we're querying.
1237 qBuilder.setTables(DATABASE_TABLE_NAME);
1238
1239 // If the query ends in a specific record number, we're
1240 // being asked for a specific record, so set the
1241 // WHERE clause in our query.
1242 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1243 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1244 }
1245
1246 // Make the query.
1247 Cursor c = qBuilder.query(mDb,
1248 projection,
1249 selection,
1250 selectionArgs,
1251 groupBy,
1252 having,
1253 sortOrder);
1254 c.setNotificationUri(getContext().getContentResolver(), uri);
1255 return c;</pre>
1256 *
1257 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001258 * if the client is requesting a specific record, the URI will end in a record number
1259 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1260 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001262 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001264 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001265 * @param selectionArgs You may include ?s in selection, which will be replaced by
1266 * the values from selectionArgs, in order that they appear in the selection.
1267 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001269 * If {@code null} then the provider is free to define the sort order.
1270 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001272 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1273 @Nullable String selection, @Nullable String[] selectionArgs,
1274 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275
Fred Quintana5bba6322009-10-05 14:21:12 -07001276 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001277 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001278 *
1279 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1280 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1281 *
1282 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001283 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1284 * and Threads</a>.
1285 * <p>
1286 * Example client call:<p>
1287 * <pre>// Request a specific record.
1288 * Cursor managedCursor = managedQuery(
1289 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1290 projection, // Which columns to return.
1291 null, // WHERE clause.
1292 null, // WHERE clause value substitution
1293 People.NAME + " ASC"); // Sort order.</pre>
1294 * Example implementation:<p>
1295 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1296 // proper SQL syntax for us.
1297 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1298
1299 // Set the table we're querying.
1300 qBuilder.setTables(DATABASE_TABLE_NAME);
1301
1302 // If the query ends in a specific record number, we're
1303 // being asked for a specific record, so set the
1304 // WHERE clause in our query.
1305 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1306 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1307 }
1308
1309 // Make the query.
1310 Cursor c = qBuilder.query(mDb,
1311 projection,
1312 selection,
1313 selectionArgs,
1314 groupBy,
1315 having,
1316 sortOrder);
1317 c.setNotificationUri(getContext().getContentResolver(), uri);
1318 return c;</pre>
1319 * <p>
1320 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001321 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1322 * signal to ensure correct operation on older versions of the Android Framework in
1323 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001324 *
1325 * @param uri The URI to query. This will be the full URI sent by the client;
1326 * if the client is requesting a specific record, the URI will end in a record number
1327 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1328 * that _id value.
1329 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001330 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001331 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001332 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001333 * @param selectionArgs You may include ?s in selection, which will be replaced by
1334 * the values from selectionArgs, in order that they appear in the selection.
1335 * The values will be bound as Strings.
1336 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001337 * If {@code null} then the provider is free to define the sort order.
1338 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001339 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001340 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001341 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001342 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001343 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1344 @Nullable String selection, @Nullable String[] selectionArgs,
1345 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001346 return query(uri, projection, selection, selectionArgs, sortOrder);
1347 }
1348
1349 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001350 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1351 * Arguments may include traditional SQL style query arguments. When present these
1352 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001353 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001354 *
1355 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001356 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1357 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1358 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001359 *
Steve McKay76b27702017-04-24 12:07:53 -07001360 * <p>This method can be called from multiple threads, as described in
1361 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1362 * and Threads</a>.
1363 *
1364 * <p>
1365 * Example client call:<p>
1366 * <pre>// Request 20 records starting at row index 30.
1367 Bundle queryArgs = new Bundle();
1368 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1369 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1370
1371 Cursor cursor = getContentResolver().query(
1372 contentUri, // Content Uri is specific to individual content providers.
1373 projection, // String[] describing which columns to return.
1374 queryArgs, // Query arguments.
1375 null); // Cancellation signal.</pre>
1376 *
1377 * Example implementation:<p>
1378 * <pre>
1379
1380 int recordsetSize = 0x1000; // Actual value is implementation specific.
1381 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1382
1383 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1384 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1385
1386 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1387
1388 // Calculate the number of items to include in the cursor.
1389 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1390
1391 // Build the paged result set....
1392 for (int i = offset; i < offset + numItems; i++) {
1393 // populate row from your data.
1394 }
1395
1396 Bundle extras = new Bundle();
1397 c.setExtras(extras);
1398
1399 // Any QUERY_ARG_* key may be included if honored.
1400 // In an actual implementation, include only keys that are both present in queryArgs
1401 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1402 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1403 // then QUERY_ARG_OFFSET should be omitted.
1404 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1405 ContentResolver.QUERY_ARG_OFFSET,
1406 ContentResolver.QUERY_ARG_LIMIT
1407 });
1408
1409 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1410
1411 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1412
1413 return cursor;</pre>
1414 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001415 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1416 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001417 *
1418 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001419 * @param projection The list of columns to put into the cursor.
1420 * If {@code null} provide a default set of columns.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001421 * @param queryArgs A Bundle containing additional information necessary for
1422 * the operation. Arguments may include SQL style arguments, such
1423 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1424 * the documentation for each individual provider will indicate
1425 * which arguments they support.
Steve McKayea93fe72016-12-02 11:35:35 -08001426 * @param cancellationSignal A signal to cancel the operation in progress,
1427 * or {@code null}.
1428 * @return a Cursor or {@code null}.
1429 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001430 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001431 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1432 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1433 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001434
Steve McKayd7ece9f2017-01-12 16:59:59 -08001435 // if client doesn't supply an SQL sort order argument, attempt to build one from
1436 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001437 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001438 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1439 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1440 }
1441
Steve McKayea93fe72016-12-02 11:35:35 -08001442 return query(
1443 uri,
1444 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001445 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1446 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1447 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001448 cancellationSignal);
1449 }
1450
1451 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001452 * Implement this to handle requests for the MIME type of the data at the
1453 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 * <code>vnd.android.cursor.item</code> for a single record,
1455 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001456 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001457 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1458 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001460 * <p>Note that there are no permissions needed for an application to
1461 * access this information; if your content provider requires read and/or
1462 * write permissions, or is not exported, all applications can still call
1463 * this method regardless of their access permissions. This allows them
1464 * to retrieve the MIME type for a URI when dispatching intents.
1465 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001467 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001469 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001470 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471
1472 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001473 * Implement this to support canonicalization of URIs that refer to your
1474 * content provider. A canonical URI is one that can be transported across
1475 * devices, backup/restore, and other contexts, and still be able to refer
1476 * to the same data item. Typically this is implemented by adding query
1477 * params to the URI allowing the content provider to verify that an incoming
1478 * canonical URI references the same data as it was originally intended for and,
1479 * if it doesn't, to find that data (if it exists) in the current environment.
1480 *
1481 * <p>For example, if the content provider holds people and a normal URI in it
1482 * is created with a row index into that people database, the cananical representation
1483 * may have an additional query param at the end which specifies the name of the
1484 * person it is intended for. Later calls into the provider with that URI will look
1485 * up the row of that URI's base index and, if it doesn't match or its entry's
1486 * name doesn't match the name in the query param, perform a query on its database
1487 * to find the correct row to operate on.</p>
1488 *
1489 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1490 * URIs (including this one) must perform this verification and recovery of any
1491 * canonical URIs they receive. In addition, you must also implement
1492 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1493 *
1494 * <p>The default implementation of this method returns null, indicating that
1495 * canonical URIs are not supported.</p>
1496 *
1497 * @param url The Uri to canonicalize.
1498 *
1499 * @return Return the canonical representation of <var>url</var>, or null if
1500 * canonicalization of that Uri is not supported.
1501 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001502 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001503 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001504 return null;
1505 }
1506
1507 /**
1508 * Remove canonicalization from canonical URIs previously returned by
1509 * {@link #canonicalize}. For example, if your implementation is to add
1510 * a query param to canonicalize a URI, this method can simply trip any
1511 * query params on the URI. The default implementation always returns the
1512 * same <var>url</var> that was passed in.
1513 *
1514 * @param url The Uri to remove any canonicalization from.
1515 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001516 * @return Return the non-canonical representation of <var>url</var>, return
1517 * the <var>url</var> as-is if there is nothing to do, or return null if
1518 * the data identified by the canonical representation can not be found in
1519 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001520 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001521 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001522 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001523 return url;
1524 }
1525
1526 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001527 * Implement this to support refresh of content identified by {@code uri}.
1528 * By default, this method returns false; providers who wish to implement
1529 * this should return true to signal the client that the provider has tried
1530 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001531 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001532 * This allows clients to request an explicit refresh of content identified
1533 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001534 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001535 * Client code should only invoke this method when there is a strong
1536 * indication (such as a user initiated pull to refresh gesture) that the
1537 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001538 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001539 * Remember to send
1540 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001541 * notifications when content changes.
1542 *
1543 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001544 * @param extras Additional options from the client. The definitions of
1545 * these are specific to the content provider being called.
1546 * @param cancellationSignal A signal to cancel the operation in progress,
1547 * or {@code null} if none. For example, if you called refresh on
1548 * a particular uri, you should call
1549 * {@link CancellationSignal#throwIfCanceled()} to check whether
1550 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001551 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001552 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001553 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001554 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001555 @Nullable CancellationSignal cancellationSignal) {
1556 return false;
1557 }
1558
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001559 /**
1560 * Perform a detailed internal check on a {@link Uri} to determine if a UID
1561 * is able to access it with specific mode flags.
1562 * <p>
1563 * This method is typically used when the provider implements more dynamic
1564 * access controls that cannot be expressed with {@code <path-permission>}
1565 * style static rules.
1566 *
1567 * @param uri the {@link Uri} to perform an access check on.
1568 * @param uid the UID to check the permission for.
1569 * @param modeFlags the access flags to use for the access check, such as
1570 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}.
1571 * @return {@link PackageManager#PERMISSION_GRANTED} if access is allowed,
1572 * otherwise {@link PackageManager#PERMISSION_DENIED}.
1573 * @hide
1574 */
Jeff Sharkey9edef252019-05-20 14:00:17 -06001575 @Override
Jeff Sharkey197fe1f2020-01-07 22:06:37 -07001576 @SystemApi
Jeff Sharkey9edef252019-05-20 14:00:17 -06001577 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1578 return PackageManager.PERMISSION_DENIED;
1579 }
1580
Ben Lin1cf454f2016-11-10 13:50:54 -08001581 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001582 * @hide
1583 * Implementation when a caller has performed an insert on the content
1584 * provider, but that call has been rejected for the operation given
1585 * to {@link #setAppOps(int, int)}. The default implementation simply
1586 * returns a dummy URI that is the base URI with a 0 path element
1587 * appended.
1588 */
1589 public Uri rejectInsert(Uri uri, ContentValues values) {
1590 // If not allowed, we need to return some reasonable URI. Maybe the
1591 // content provider should be responsible for this, but for now we
1592 // will just return the base URI with a dummy '0' tagged on to it.
1593 // You shouldn't be able to read if you can't write, anyway, so it
1594 // shouldn't matter much what is returned.
1595 return uri.buildUpon().appendPath("0").build();
1596 }
1597
1598 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001599 * Implement this to handle requests to insert a new row. As a courtesy,
1600 * call
1601 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1602 * notifyChange()} after inserting. This method can be called from multiple
1603 * threads, as described in <a href="
1604 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001605 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001606 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001607 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 * @param values A set of column_name/value pairs to add to the database.
1609 * @return The URI for the newly inserted item.
1610 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001611 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612
1613 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001614 * Implement this to handle requests to insert a new row. As a courtesy,
1615 * call
1616 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1617 * notifyChange()} after inserting. This method can be called from multiple
1618 * threads, as described in <a href="
1619 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1620 * and Threads</a>.
1621 *
1622 * @param uri The content:// URI of the insertion request.
1623 * @param values A set of column_name/value pairs to add to the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001624 * @param extras A Bundle containing additional information necessary for
1625 * the operation. Arguments may include SQL style arguments, such
1626 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1627 * the documentation for each individual provider will indicate
1628 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001629 * @return The URI for the newly inserted item.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001630 * @throws IllegalArgumentException if the provider doesn't support one of
1631 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001632 */
1633 @Override
1634 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1635 @Nullable Bundle extras) {
1636 return insert(uri, values);
1637 }
1638
1639 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001640 * Override this to handle requests to insert a set of new rows, or the
1641 * default implementation will iterate over the values and call
1642 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1644 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001645 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001646 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1647 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 *
1649 * @param uri The content:// URI of the insertion request.
1650 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001651 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 * @return The number of values that were inserted.
1653 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001654 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001655 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 int numValues = values.length;
1657 for (int i = 0; i < numValues; i++) {
1658 insert(uri, values[i]);
1659 }
1660 return numValues;
1661 }
1662
1663 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001664 * Implement this to handle requests to delete one or more rows. The
1665 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001666 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001667 * As a courtesy, call
1668 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1669 * notifyChange()} after deleting. This method can be called from multiple
1670 * threads, as described in <a href="
1671 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001672 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001673 * <p>
1674 * The implementation is responsible for parsing out a row ID at the end of
1675 * the URI, if a specific row is being deleted. That is, the client would
1676 * pass in <code>content://contacts/people/22</code> and the implementation
1677 * is responsible for parsing the record number (22) when creating a SQL
1678 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001680 * @param uri The full URI to query, including a row ID (if a specific
1681 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 * @param selection An optional restriction to apply to rows when deleting.
1683 * @return The number of rows affected.
1684 * @throws SQLException
1685 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001686 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1687 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688
1689 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001690 * Implement this to handle requests to delete one or more rows. The
1691 * implementation should apply the selection clause when performing
1692 * deletion, allowing the operation to affect multiple rows in a directory.
1693 * As a courtesy, call
1694 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1695 * notifyChange()} after deleting. This method can be called from multiple
1696 * threads, as described in <a href="
1697 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1698 * and Threads</a>.
1699 * <p>
1700 * The implementation is responsible for parsing out a row ID at the end of
1701 * the URI, if a specific row is being deleted. That is, the client would
1702 * pass in <code>content://contacts/people/22</code> and the implementation
1703 * is responsible for parsing the record number (22) when creating a SQL
1704 * statement.
1705 *
1706 * @param uri The full URI to query, including a row ID (if a specific
1707 * record is requested).
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001708 * @param extras A Bundle containing additional information necessary for
1709 * the operation. Arguments may include SQL style arguments, such
1710 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1711 * the documentation for each individual provider will indicate
1712 * which arguments they support.
1713 * @throws IllegalArgumentException if the provider doesn't support one of
1714 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001715 * @throws SQLException
1716 */
1717 @Override
1718 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1719 extras = (extras != null) ? extras : Bundle.EMPTY;
1720 return delete(uri,
1721 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1722 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1723 }
1724
1725 /**
1726 * Implement this to handle requests to update one or more rows. The
1727 * implementation should update all rows matching the selection to set the
1728 * columns according to the provided values map. As a courtesy, call
1729 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1730 * notifyChange()} after updating. This method can be called from multiple
1731 * threads, as described in <a href="
1732 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001733 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001735 * @param uri The URI to query. This can potentially have a record ID if
1736 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001737 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 * @param selection An optional filter to match rows to update.
1739 * @return the number of rows affected.
1740 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001741 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001742 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743
1744 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001745 * Implement this to handle requests to update one or more rows. The
1746 * implementation should update all rows matching the selection to set the
1747 * columns according to the provided values map. As a courtesy, call
1748 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1749 * notifyChange()} after updating. This method can be called from multiple
1750 * threads, as described in <a href="
1751 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1752 * and Threads</a>.
1753 *
1754 * @param uri The URI to query. This can potentially have a record ID if
1755 * this is an update request for a specific record.
1756 * @param values A set of column_name/value pairs to update in the database.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001757 * @param extras A Bundle containing additional information necessary for
1758 * the operation. Arguments may include SQL style arguments, such
1759 * as {@link ContentResolver#QUERY_ARG_SQL_LIMIT}, but note that
1760 * the documentation for each individual provider will indicate
1761 * which arguments they support.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001762 * @return the number of rows affected.
Jeff Sharkeyc192ca5a2020-01-08 11:00:23 -07001763 * @throws IllegalArgumentException if the provider doesn't support one of
1764 * the requested Bundle arguments.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001765 */
1766 @Override
1767 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1768 @Nullable Bundle extras) {
1769 extras = (extras != null) ? extras : Bundle.EMPTY;
1770 return update(uri, values,
1771 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1772 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1773 }
1774
1775 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001776 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001777 * The default implementation always throws {@link FileNotFoundException}.
1778 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001779 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1780 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001781 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001782 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1783 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001784 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 *
1786 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1787 * their responsibility to close it when done. That is, the implementation
1788 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001789 * <p>
1790 * If opened with the exclusive "r" or "w" modes, the returned
1791 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1792 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1793 * supports seeking.
1794 * <p>
1795 * If you need to detect when the returned ParcelFileDescriptor has been
1796 * closed, or if the remote process has crashed or encountered some other
1797 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1798 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1799 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1800 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001801 * <p>
1802 * If you need to return a large file that isn't backed by a real file on
1803 * disk, such as a file on a network share or cloud storage service,
1804 * consider using
1805 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1806 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001808 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1809 * to return the appropriate MIME type for the data returned here with
1810 * the same URI. This will allow intent resolution to automatically determine the data MIME
1811 * type and select the appropriate matching targets as part of its operation.</p>
1812 *
1813 * <p class="note">For better interoperability with other applications, it is recommended
1814 * that for any URIs that can be opened, you also support queries on them
1815 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1816 * You may also want to support other common columns if you have additional meta-data
1817 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1818 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1819 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 * @param uri The URI whose file is to be opened.
1821 * @param mode Access mode for the file. May be "r" for read-only access,
1822 * "rw" for read and write access, or "rwt" for read and write access
1823 * that truncates any existing file.
1824 *
1825 * @return Returns a new ParcelFileDescriptor which you can use to access
1826 * the file.
1827 *
1828 * @throws FileNotFoundException Throws FileNotFoundException if there is
1829 * no file associated with the given URI or the mode is invalid.
1830 * @throws SecurityException Throws SecurityException if the caller does
1831 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001832 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 * @see #openAssetFile(Uri, String)
1834 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001835 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001836 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001837 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001838 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 throws FileNotFoundException {
1840 throw new FileNotFoundException("No files supported by provider at "
1841 + uri);
1842 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001845 * Override this to handle requests to open a file blob.
1846 * The default implementation always throws {@link FileNotFoundException}.
1847 * This method can be called from multiple threads, as described in
1848 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1849 * and Threads</a>.
1850 *
1851 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1852 * to the caller. This way large data (such as images and documents) can be
1853 * returned without copying the content.
1854 *
1855 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1856 * their responsibility to close it when done. That is, the implementation
1857 * of this method should create a new ParcelFileDescriptor for each call.
1858 * <p>
1859 * If opened with the exclusive "r" or "w" modes, the returned
1860 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1861 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1862 * supports seeking.
1863 * <p>
1864 * If you need to detect when the returned ParcelFileDescriptor has been
1865 * closed, or if the remote process has crashed or encountered some other
1866 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1867 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1868 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1869 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1870 *
1871 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1872 * to return the appropriate MIME type for the data returned here with
1873 * the same URI. This will allow intent resolution to automatically determine the data MIME
1874 * type and select the appropriate matching targets as part of its operation.</p>
1875 *
1876 * <p class="note">For better interoperability with other applications, it is recommended
1877 * that for any URIs that can be opened, you also support queries on them
1878 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1879 * You may also want to support other common columns if you have additional meta-data
1880 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1881 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1882 *
1883 * @param uri The URI whose file is to be opened.
1884 * @param mode Access mode for the file. May be "r" for read-only access,
1885 * "w" for write-only access, "rw" for read and write access, or
1886 * "rwt" for read and write access that truncates any existing
1887 * file.
1888 * @param signal A signal to cancel the operation in progress, or
1889 * {@code null} if none. For example, if you are downloading a
1890 * file from the network to service a "rw" mode request, you
1891 * should periodically call
1892 * {@link CancellationSignal#throwIfCanceled()} to check whether
1893 * the client has canceled the request and abort the download.
1894 *
1895 * @return Returns a new ParcelFileDescriptor which you can use to access
1896 * the file.
1897 *
1898 * @throws FileNotFoundException Throws FileNotFoundException if there is
1899 * no file associated with the given URI or the mode is invalid.
1900 * @throws SecurityException Throws SecurityException if the caller does
1901 * not have permission to access the file.
1902 *
1903 * @see #openAssetFile(Uri, String)
1904 * @see #openFileHelper(Uri, String)
1905 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001906 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001907 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001908 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001909 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1910 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001911 return openFile(uri, mode);
1912 }
1913
1914 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 * This is like {@link #openFile}, but can be implemented by providers
1916 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001917 * inside of their .apk.
1918 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001919 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1920 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001921 *
1922 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001923 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001924 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1926 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1927 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001928 * <p>
1929 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1930 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001931 *
1932 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 * should create the AssetFileDescriptor with
1934 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001935 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001937 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1938 * to return the appropriate MIME type for the data returned here with
1939 * the same URI. This will allow intent resolution to automatically determine the data MIME
1940 * type and select the appropriate matching targets as part of its operation.</p>
1941 *
1942 * <p class="note">For better interoperability with other applications, it is recommended
1943 * that for any URIs that can be opened, you also support queries on them
1944 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1945 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 * @param uri The URI whose file is to be opened.
1947 * @param mode Access mode for the file. May be "r" for read-only access,
1948 * "w" for write-only access (erasing whatever data is currently in
1949 * the file), "wa" for write-only access to append to any existing data,
1950 * "rw" for read and write access on any existing data, and "rwt" for read
1951 * and write access that truncates any existing file.
1952 *
1953 * @return Returns a new AssetFileDescriptor which you can use to access
1954 * the file.
1955 *
1956 * @throws FileNotFoundException Throws FileNotFoundException if there is
1957 * no file associated with the given URI or the mode is invalid.
1958 * @throws SecurityException Throws SecurityException if the caller does
1959 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001960 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 * @see #openFile(Uri, String)
1962 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001963 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001965 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 throws FileNotFoundException {
1967 ParcelFileDescriptor fd = openFile(uri, mode);
1968 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1969 }
1970
1971 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001972 * This is like {@link #openFile}, but can be implemented by providers
1973 * that need to be able to return sub-sections of files, often assets
1974 * inside of their .apk.
1975 * This method can be called from multiple threads, as described in
1976 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1977 * and Threads</a>.
1978 *
1979 * <p>If you implement this, your clients must be able to deal with such
1980 * file slices, either directly with
1981 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1982 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1983 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1984 * methods.
1985 * <p>
1986 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1987 * streaming of data.
1988 *
1989 * <p class="note">If you are implementing this to return a full file, you
1990 * should create the AssetFileDescriptor with
1991 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1992 * applications that cannot handle sub-sections of files.</p>
1993 *
1994 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1995 * to return the appropriate MIME type for the data returned here with
1996 * the same URI. This will allow intent resolution to automatically determine the data MIME
1997 * type and select the appropriate matching targets as part of its operation.</p>
1998 *
1999 * <p class="note">For better interoperability with other applications, it is recommended
2000 * that for any URIs that can be opened, you also support queries on them
2001 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
2002 *
2003 * @param uri The URI whose file is to be opened.
2004 * @param mode Access mode for the file. May be "r" for read-only access,
2005 * "w" for write-only access (erasing whatever data is currently in
2006 * the file), "wa" for write-only access to append to any existing data,
2007 * "rw" for read and write access on any existing data, and "rwt" for read
2008 * and write access that truncates any existing file.
2009 * @param signal A signal to cancel the operation in progress, or
2010 * {@code null} if none. For example, if you are downloading a
2011 * file from the network to service a "rw" mode request, you
2012 * should periodically call
2013 * {@link CancellationSignal#throwIfCanceled()} to check whether
2014 * the client has canceled the request and abort the download.
2015 *
2016 * @return Returns a new AssetFileDescriptor which you can use to access
2017 * the file.
2018 *
2019 * @throws FileNotFoundException Throws FileNotFoundException if there is
2020 * no file associated with the given URI or the mode is invalid.
2021 * @throws SecurityException Throws SecurityException if the caller does
2022 * not have permission to access the file.
2023 *
2024 * @see #openFile(Uri, String)
2025 * @see #openFileHelper(Uri, String)
2026 * @see #getType(android.net.Uri)
2027 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002028 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002029 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
2030 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002031 return openAssetFile(uri, mode);
2032 }
2033
2034 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 * Convenience for subclasses that wish to implement {@link #openFile}
2036 * by looking up a column named "_data" at the given URI.
2037 *
2038 * @param uri The URI to be opened.
2039 * @param mode The file mode. May be "r" for read-only access,
2040 * "w" for write-only access (erasing whatever data is currently in
2041 * the file), "wa" for write-only access to append to any existing data,
2042 * "rw" for read and write access on any existing data, and "rwt" for read
2043 * and write access that truncates any existing file.
2044 *
2045 * @return Returns a new ParcelFileDescriptor that can be used by the
2046 * client to access the file.
2047 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002048 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
2049 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
2051 int count = (c != null) ? c.getCount() : 0;
2052 if (count != 1) {
2053 // If there is not exactly one result, throw an appropriate
2054 // exception.
2055 if (c != null) {
2056 c.close();
2057 }
2058 if (count == 0) {
2059 throw new FileNotFoundException("No entry for " + uri);
2060 }
2061 throw new FileNotFoundException("Multiple items at " + uri);
2062 }
2063
2064 c.moveToFirst();
2065 int i = c.getColumnIndex("_data");
2066 String path = (i >= 0 ? c.getString(i) : null);
2067 c.close();
2068 if (path == null) {
2069 throw new FileNotFoundException("Column _data not found.");
2070 }
2071
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002072 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 return ParcelFileDescriptor.open(new File(path), modeBits);
2074 }
2075
2076 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002077 * Called by a client to determine the types of data streams that this
2078 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002079 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002080 * of a particular type, return that MIME type if it matches the given
2081 * mimeTypeFilter. If it can perform type conversions, return an array
2082 * of all supported MIME types that match mimeTypeFilter.
2083 *
2084 * @param uri The data in the content provider being queried.
2085 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002086 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002087 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002088 * given mimeTypeFilter. Otherwise returns an array of all available
2089 * concrete MIME types.
2090 *
2091 * @see #getType(Uri)
2092 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002093 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002094 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002095 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002096 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002097 return null;
2098 }
2099
2100 /**
2101 * Called by a client to open a read-only stream containing data of a
2102 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2103 * except the file can only be read-only and the content provider may
2104 * perform data conversions to generate data of the desired type.
2105 *
2106 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002107 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002108 * {@link #openAssetFile(Uri, String)}.
2109 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002110 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002111 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002112 * <p>
2113 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2114 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002115 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002116 * <p class="note">For better interoperability with other applications, it is recommended
2117 * that for any URIs that can be opened, you also support queries on them
2118 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2119 * You may also want to support other common columns if you have additional meta-data
2120 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2121 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2122 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002123 * @param uri The data in the content provider being queried.
2124 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002125 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002126 * requirements; in this case the content provider will pick its best
2127 * type matching the pattern.
2128 * @param opts Additional options from the client. The definitions of
2129 * these are specific to the content provider being called.
2130 *
2131 * @return Returns a new AssetFileDescriptor from which the client can
2132 * read data of the desired type.
2133 *
2134 * @throws FileNotFoundException Throws FileNotFoundException if there is
2135 * no file associated with the given URI or the mode is invalid.
2136 * @throws SecurityException Throws SecurityException if the caller does
2137 * not have permission to access the data.
2138 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2139 * content provider does not support the requested MIME type.
2140 *
2141 * @see #getStreamTypes(Uri, String)
2142 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002143 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002144 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002145 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2146 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002147 if ("*/*".equals(mimeTypeFilter)) {
2148 // If they can take anything, the untyped open call is good enough.
2149 return openAssetFile(uri, "r");
2150 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002151 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002152 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002153 // Use old untyped open call if this provider has a type for this
2154 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002155 return openAssetFile(uri, "r");
2156 }
2157 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2158 }
2159
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002160
2161 /**
2162 * Called by a client to open a read-only stream containing data of a
2163 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2164 * except the file can only be read-only and the content provider may
2165 * perform data conversions to generate data of the desired type.
2166 *
2167 * <p>The default implementation compares the given mimeType against the
2168 * result of {@link #getType(Uri)} and, if they match, simply calls
2169 * {@link #openAssetFile(Uri, String)}.
2170 *
2171 * <p>See {@link ClipData} for examples of the use and implementation
2172 * of this method.
2173 * <p>
2174 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2175 * streaming of data.
2176 *
2177 * <p class="note">For better interoperability with other applications, it is recommended
2178 * that for any URIs that can be opened, you also support queries on them
2179 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2180 * You may also want to support other common columns if you have additional meta-data
2181 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2182 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2183 *
2184 * @param uri The data in the content provider being queried.
2185 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002186 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002187 * requirements; in this case the content provider will pick its best
2188 * type matching the pattern.
2189 * @param opts Additional options from the client. The definitions of
2190 * these are specific to the content provider being called.
2191 * @param signal A signal to cancel the operation in progress, or
2192 * {@code null} if none. For example, if you are downloading a
2193 * file from the network to service a "rw" mode request, you
2194 * should periodically call
2195 * {@link CancellationSignal#throwIfCanceled()} to check whether
2196 * the client has canceled the request and abort the download.
2197 *
2198 * @return Returns a new AssetFileDescriptor from which the client can
2199 * read data of the desired type.
2200 *
2201 * @throws FileNotFoundException Throws FileNotFoundException if there is
2202 * no file associated with the given URI or the mode is invalid.
2203 * @throws SecurityException Throws SecurityException if the caller does
2204 * not have permission to access the data.
2205 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2206 * content provider does not support the requested MIME type.
2207 *
2208 * @see #getStreamTypes(Uri, String)
2209 * @see #openAssetFile(Uri, String)
2210 * @see ClipDescription#compareMimeTypes(String, String)
2211 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002212 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002213 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2214 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2215 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002216 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2217 }
2218
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002219 /**
2220 * Interface to write a stream of data to a pipe. Use with
2221 * {@link ContentProvider#openPipeHelper}.
2222 */
2223 public interface PipeDataWriter<T> {
2224 /**
2225 * Called from a background thread to stream data out to a pipe.
2226 * Note that the pipe is blocking, so this thread can block on
2227 * writes for an arbitrary amount of time if the client is slow
2228 * at reading.
2229 *
2230 * @param output The pipe where data should be written. This will be
2231 * closed for you upon returning from this function.
2232 * @param uri The URI whose data is to be written.
2233 * @param mimeType The desired type of data to be written.
2234 * @param opts Options supplied by caller.
2235 * @param args Your own custom arguments.
2236 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002237 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2238 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002239 }
2240
2241 /**
2242 * A helper function for implementing {@link #openTypedAssetFile}, for
2243 * creating a data pipe and background thread allowing you to stream
2244 * generated data back to the client. This function returns a new
2245 * ParcelFileDescriptor that should be returned to the caller (the caller
2246 * is responsible for closing it).
2247 *
2248 * @param uri The URI whose data is to be written.
2249 * @param mimeType The desired type of data to be written.
2250 * @param opts Options supplied by caller.
2251 * @param args Your own custom arguments.
2252 * @param func Interface implementing the function that will actually
2253 * stream the data.
2254 * @return Returns a new ParcelFileDescriptor holding the read side of
2255 * the pipe. This should be returned to the caller for reading; the caller
2256 * is responsible for closing it when done.
2257 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002258 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2259 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2260 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002261 try {
2262 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2263
2264 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2265 @Override
2266 protected Object doInBackground(Object... params) {
2267 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2268 try {
2269 fds[1].close();
2270 } catch (IOException e) {
2271 Log.w(TAG, "Failure closing pipe", e);
2272 }
2273 return null;
2274 }
2275 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002276 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002277
2278 return fds[0];
2279 } catch (IOException e) {
2280 throw new FileNotFoundException("failure making pipe");
2281 }
2282 }
2283
2284 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 * Returns true if this instance is a temporary content provider.
2286 * @return true if this instance is a temporary content provider
2287 */
2288 protected boolean isTemporary() {
2289 return false;
2290 }
2291
2292 /**
2293 * Returns the Binder object for this provider.
2294 *
2295 * @return the Binder object for this provider
2296 * @hide
2297 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002298 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 public IContentProvider getIContentProvider() {
2300 return mTransport;
2301 }
2302
2303 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002304 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2305 * when directly instantiating the provider for testing.
2306 * @hide
2307 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002308 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002309 public void attachInfoForTesting(Context context, ProviderInfo info) {
2310 attachInfo(context, info, true);
2311 }
2312
2313 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 * After being instantiated, this is called to tell the content provider
2315 * about itself.
2316 *
2317 * @param context The context this provider is running in
2318 * @param info Registered information about this content provider
2319 */
2320 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002321 attachInfo(context, info, false);
2322 }
2323
2324 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002325 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002326 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 /*
2329 * Only allow it to be set once, so after the content service gives
2330 * this to us clients can't change it.
2331 */
2332 if (mContext == null) {
2333 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002334 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002335 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2336 Context.APP_OPS_SERVICE);
2337 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002338 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 if (info != null) {
2340 setReadPermission(info.readPermission);
2341 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002342 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002343 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002344 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002345 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002347 if (Build.IS_DEBUGGABLE) {
2348 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2349 Log.VERBOSE));
2350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 ContentProvider.this.onCreate();
2352 }
2353 }
Fred Quintanace31b232009-05-04 16:01:15 -07002354
2355 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002356 * Override this to handle requests to perform a batch of operations, or the
2357 * default implementation will iterate over the operations and call
2358 * {@link ContentProviderOperation#apply} on each of them.
2359 * If all calls to {@link ContentProviderOperation#apply} succeed
2360 * then a {@link ContentProviderResult} array with as many
2361 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002362 * fail, it is up to the implementation how many of the others take effect.
2363 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002364 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2365 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002366 *
Fred Quintanace31b232009-05-04 16:01:15 -07002367 * @param operations the operations to apply
2368 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002369 * @throws OperationApplicationException thrown if any operation fails.
2370 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002371 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002372 @Override
2373 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2374 @NonNull ArrayList<ContentProviderOperation> operations)
2375 throws OperationApplicationException {
2376 return applyBatch(operations);
2377 }
2378
Jeff Sharkey673db442015-06-11 19:30:57 -07002379 public @NonNull ContentProviderResult[] applyBatch(
2380 @NonNull ArrayList<ContentProviderOperation> operations)
2381 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002382 final int numOperations = operations.size();
2383 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2384 for (int i = 0; i < numOperations; i++) {
2385 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002386 }
2387 return results;
2388 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002389
2390 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002391 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002392 * interfaces that are cheaper and/or unnatural for a table-like
2393 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002394 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002395 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2396 * on this entry into the content provider besides the basic ability for the application
2397 * to get access to the provider at all. For example, it has no idea whether the call
2398 * being executed may read or write data in the provider, so can't enforce those
2399 * individual permissions. Any implementation of this method <strong>must</strong>
2400 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2401 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002402 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2403 * @param arg provider-defined String argument. May be {@code null}.
2404 * @param extras provider-defined Bundle argument. May be {@code null}.
2405 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002406 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002407 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002408 @Override
2409 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2410 @Nullable String arg, @Nullable Bundle extras) {
2411 return call(method, arg, extras);
2412 }
2413
Jeff Sharkey673db442015-06-11 19:30:57 -07002414 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2415 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002416 return null;
2417 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002418
2419 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002420 * Implement this to shut down the ContentProvider instance. You can then
2421 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002422 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002423 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002424 * Android normally handles ContentProvider startup and shutdown
2425 * automatically. You do not need to start up or shut down a
2426 * ContentProvider. When you invoke a test method on a ContentProvider,
2427 * however, a ContentProvider instance is started and keeps running after
2428 * the test finishes, even if a succeeding test instantiates another
2429 * ContentProvider. A conflict develops because the two instances are
2430 * usually running against the same underlying data source (for example, an
2431 * sqlite database).
2432 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002433 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002434 * Implementing shutDown() avoids this conflict by providing a way to
2435 * terminate the ContentProvider. This method can also prevent memory leaks
2436 * from multiple instantiations of the ContentProvider, and it can ensure
2437 * unit test isolation by allowing you to completely clean up the test
2438 * fixture before moving on to the next test.
2439 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002440 */
2441 public void shutdown() {
2442 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2443 "connections are gracefully shutdown");
2444 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002445
2446 /**
2447 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002448 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002449 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002450 * @param fd The raw file descriptor that the dump is being sent to.
2451 * @param writer The PrintWriter to which you should dump your state. This will be
2452 * closed for you after you return.
2453 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002454 */
2455 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2456 writer.println("nothing to dump");
2457 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002458
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002459 private void validateIncomingAuthority(String authority) throws SecurityException {
2460 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2461 String message = "The authority " + authority + " does not match the one of the "
2462 + "contentProvider: ";
2463 if (mAuthority != null) {
2464 message += mAuthority;
2465 } else {
2466 message += Arrays.toString(mAuthorities);
2467 }
2468 throw new SecurityException(message);
2469 }
2470 }
2471
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002472 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002473 @VisibleForTesting
2474 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002475 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002476 if (!mSingleUser) {
2477 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2478 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2479 throw new SecurityException("trying to query a ContentProvider in user "
2480 + mContext.getUserId() + " with a uri belonging to user " + userId);
2481 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002482 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002483 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002484
2485 // Normalize the path by removing any empty path segments, which can be
2486 // a source of security issues.
2487 final String encodedPath = uri.getEncodedPath();
2488 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002489 final Uri normalized = uri.buildUpon()
2490 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2491 Log.w(TAG, "Normalized " + uri + " to " + normalized
2492 + " to avoid possible security issues");
2493 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002494 } else {
2495 return uri;
2496 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002497 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002498
2499 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002500 private Uri maybeGetUriWithoutUserId(Uri uri) {
2501 if (mSingleUser) {
2502 return uri;
2503 }
2504 return getUriWithoutUserId(uri);
2505 }
2506
2507 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002508 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2509 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002510 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002511 if (end == -1) return defaultUserId;
2512 String userIdString = auth.substring(0, end);
2513 try {
2514 return Integer.parseInt(userIdString);
2515 } catch (NumberFormatException e) {
2516 Log.w(TAG, "Error parsing userId.", e);
2517 return UserHandle.USER_NULL;
2518 }
2519 }
2520
2521 /** @hide */
2522 public static int getUserIdFromAuthority(String auth) {
2523 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2524 }
2525
2526 /** @hide */
2527 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2528 if (uri == null) return defaultUserId;
2529 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2530 }
2531
2532 /** @hide */
2533 public static int getUserIdFromUri(Uri uri) {
2534 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2535 }
2536
2537 /**
Alex Kershawba014ac2020-01-20 22:25:02 +00002538 * Returns the user associated with the given URI.
2539 *
2540 * @hide
2541 */
2542 @TestApi
2543 public @NonNull static UserHandle getUserHandleFromUri(@NonNull Uri uri) {
2544 return UserHandle.of(getUserIdFromUri(uri, Process.myUserHandle().getIdentifier()));
2545 }
2546
2547 /**
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002548 * Removes userId part from authority string. Expects format:
2549 * userId@some.authority
2550 * If there is no userId in the authority, it symply returns the argument
2551 * @hide
2552 */
2553 public static String getAuthorityWithoutUserId(String auth) {
2554 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002555 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002556 return auth.substring(end+1);
2557 }
2558
2559 /** @hide */
2560 public static Uri getUriWithoutUserId(Uri uri) {
2561 if (uri == null) return null;
2562 Uri.Builder builder = uri.buildUpon();
2563 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2564 return builder.build();
2565 }
2566
2567 /** @hide */
2568 public static boolean uriHasUserId(Uri uri) {
2569 if (uri == null) return false;
2570 return !TextUtils.isEmpty(uri.getUserInfo());
2571 }
2572
2573 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002574 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002575 public static Uri maybeAddUserId(Uri uri, int userId) {
2576 if (uri == null) return null;
2577 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002578 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002579 if (!uriHasUserId(uri)) {
2580 //We don't add the user Id if there's already one
2581 Uri.Builder builder = uri.buildUpon();
2582 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2583 return builder.build();
2584 }
2585 }
2586 return uri;
2587 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002588}