blob: 17f1a07d6e01ccef895cc942a31fc53b4a6ae3b8 [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;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010030import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080031import android.app.AppOpsManager;
Jeff Sharkey9edef252019-05-20 14:00:17 -060032import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070033import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.res.AssetFileDescriptor;
36import android.content.res.Configuration;
37import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070038import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.database.SQLException;
40import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070041import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010043import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070045import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080046import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070047import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070049import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080050import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060051import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060053import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010054import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070055import android.util.Log;
Philip P. Moltmann128b7032019-09-27 08:44:12 -070056import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060058import com.android.internal.annotations.VisibleForTesting;
59
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080061import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070063import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080064import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070065import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080066import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060067import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69/**
70 * Content providers are one of the primary building blocks of Android applications, providing
71 * content to applications. They encapsulate data and provide it to applications through the single
72 * {@link ContentResolver} interface. A content provider is only required if you need to share
73 * data between multiple applications. For example, the contacts data is used by multiple
74 * applications and must be stored in a content provider. If you don't need to share data amongst
75 * multiple applications you can use a database directly via
76 * {@link android.database.sqlite.SQLiteDatabase}.
77 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 * <p>When a request is made via
79 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
80 * request to the content provider registered with the authority. The content provider can interpret
81 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
82 * URIs.</p>
83 *
84 * <p>The primary methods that need to be implemented are:
85 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070086 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 * <li>{@link #query} which returns data to the caller</li>
88 * <li>{@link #insert} which inserts new data into the content provider</li>
89 * <li>{@link #update} which updates existing data in the content provider</li>
90 * <li>{@link #delete} which deletes data from the content provider</li>
91 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
92 * </ul></p>
93 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070094 * <p class="caution">Data access methods (such as {@link #insert} and
95 * {@link #update}) may be called from many threads at once, and must be thread-safe.
96 * Other methods (such as {@link #onCreate}) are only called from the application
97 * main thread, and must avoid performing lengthy operations. See the method
98 * descriptions for their expected thread behavior.</p>
99 *
100 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
101 * ContentProvider instance, so subclasses don't have to worry about the details of
102 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700103 *
104 * <div class="special reference">
105 * <h3>Developer Guides</h3>
106 * <p>For more information about using content providers, read the
107 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
108 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700109 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700111public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800112
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700113 private static final String TAG = "ContentProvider";
114
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900115 /*
116 * Note: if you add methods to ContentProvider, you must add similar methods to
117 * MockContentProvider.
118 */
119
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100120 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700122 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100123
124 // Since most Providers have only one authority, we keep both a String and a String[] to improve
125 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100126 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100127 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100128 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100129 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100130 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100132 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100134 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700135 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700136 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800137 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700138 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700140 private ThreadLocal<Pair<String, String>> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private Transport mTransport = new Transport();
143
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700144 /**
145 * Construct a ContentProvider instance. Content providers must be
146 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
147 * in the manifest</a>, accessed with {@link ContentResolver}, and created
148 * automatically by the system, so applications usually do not create
149 * ContentProvider instances directly.
150 *
151 * <p>At construction time, the object is uninitialized, and most fields and
152 * methods are unavailable. Subclasses should initialize themselves in
153 * {@link #onCreate}, not the constructor.
154 *
155 * <p>Content providers are created on the application main thread at
156 * application launch time. The constructor must not perform lengthy
157 * operations, or application startup will be delayed.
158 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900159 public ContentProvider() {
160 }
161
162 /**
163 * Constructor just for mocking.
164 *
165 * @param context A Context object which should be some mock instance (like the
166 * instance of {@link android.test.mock.MockContext}).
167 * @param readPermission The read permision you want this instance should have in the
168 * test, which is available via {@link #getReadPermission()}.
169 * @param writePermission The write permission you want this instance should have
170 * in the test, which is available via {@link #getWritePermission()}.
171 * @param pathPermissions The PathPermissions you want this instance should have
172 * in the test, which is available via {@link #getPathPermissions()}.
173 * @hide
174 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100175 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900176 public ContentProvider(
177 Context context,
178 String readPermission,
179 String writePermission,
180 PathPermission[] pathPermissions) {
181 mContext = context;
182 mReadPermission = readPermission;
183 mWritePermission = writePermission;
184 mPathPermissions = pathPermissions;
185 }
186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 /**
188 * Given an IContentProvider, try to coerce it back to the real
189 * ContentProvider object if it is running in the local process. This can
190 * be used if you know you are running in the same process as a provider,
191 * and want to get direct access to its implementation details. Most
192 * clients should not nor have a reason to use it.
193 *
194 * @param abstractInterface The ContentProvider interface that is to be
195 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800196 * @return If the IContentProvider is non-{@code null} and local, returns its actual
197 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 * @hide
199 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100200 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 public static ContentProvider coerceToLocalContentProvider(
202 IContentProvider abstractInterface) {
203 if (abstractInterface instanceof Transport) {
204 return ((Transport)abstractInterface).getContentProvider();
205 }
206 return null;
207 }
208
209 /**
210 * Binder object that deals with remoting.
211 *
212 * @hide
213 */
214 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700215 volatile AppOpsManager mAppOpsManager = null;
216 volatile int mReadOp = AppOpsManager.OP_NONE;
217 volatile int mWriteOp = AppOpsManager.OP_NONE;
218 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 ContentProvider getContentProvider() {
221 return ContentProvider.this;
222 }
223
Jeff Brownd2183652011-10-09 12:39:53 -0700224 @Override
225 public String getProviderName() {
226 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 }
228
Jeff Brown75ea64f2012-01-25 19:37:13 -0800229 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700230 public Cursor query(String callingPkg, @Nullable String featureId, Uri uri,
231 @Nullable String[] projection, @Nullable Bundle queryArgs,
232 @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600233 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100234 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700235 if (enforceReadPermission(callingPkg, featureId, uri, null)
236 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700237 // The caller has no access to the data, so return an empty cursor with
238 // the columns in the requested order. The caller may ask for an invalid
239 // column and we would not catch that but this is not a problem in practice.
240 // We do not call ContentProvider#query with a modified where clause since
241 // the implementation is not guaranteed to be backed by a SQL database, hence
242 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700243 if (projection != null) {
244 return new MatrixCursor(projection, 0);
245 }
246
247 // Null projection means all columns but we have no idea which they are.
248 // However, the caller may be expecting to access them my index. Hence,
249 // we have to execute the query as if allowed to get a cursor with the
250 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700251 Cursor cursor;
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700252 final Pair<String, String> original = setCallingPackage(
253 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700254 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700255 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700256 uri, projection, queryArgs,
257 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700258 } catch (RemoteException e) {
259 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700260 } finally {
261 setCallingPackage(original);
262 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700263 if (cursor == null) {
264 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700265 }
266
267 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700268 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800269 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600270 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700271 final Pair<String, String> original = setCallingPackage(
272 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700273 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700274 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800275 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700276 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700277 } catch (RemoteException e) {
278 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700279 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700280 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600281 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284
Jeff Brown75ea64f2012-01-25 19:37:13 -0800285 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700287 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600288 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100289 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600290 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
291 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700292 return mInterface.getType(uri);
293 } catch (RemoteException e) {
294 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600295 } finally {
296 Trace.traceEnd(TRACE_TAG_DATABASE);
297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 }
299
Jeff Brown75ea64f2012-01-25 19:37:13 -0800300 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700301 public Uri insert(String callingPkg, @Nullable String featureId, Uri uri,
302 ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600303 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100304 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100305 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700306 if (enforceWritePermission(callingPkg, featureId, uri, null)
307 != AppOpsManager.MODE_ALLOWED) {
308 final Pair<String, String> original = setCallingPackage(
309 new Pair<>(callingPkg, featureId));
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700310 try {
311 return rejectInsert(uri, initialValues);
312 } finally {
313 setCallingPackage(original);
314 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800315 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600316 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700317 final Pair<String, String> original = setCallingPackage(
318 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700319 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700320 return maybeAddUserId(mInterface.insert(uri, initialValues), userId);
321 } catch (RemoteException e) {
322 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700323 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700324 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600325 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
328
Jeff Brown75ea64f2012-01-25 19:37:13 -0800329 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700330 public int bulkInsert(String callingPkg, @Nullable String featureId, Uri uri,
331 ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600332 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100333 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700334 if (enforceWritePermission(callingPkg, featureId, uri, null)
335 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800336 return 0;
337 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600338 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700339 final Pair<String, String> original = setCallingPackage(
340 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700341 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700342 return mInterface.bulkInsert(uri, initialValues);
343 } catch (RemoteException e) {
344 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700345 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700346 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600347 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 }
350
Jeff Brown75ea64f2012-01-25 19:37:13 -0800351 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700352 public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String featureId,
353 String authority, ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700354 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700355 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100356 int numOperations = operations.size();
357 final int[] userIds = new int[numOperations];
358 for (int i = 0; i < numOperations; i++) {
359 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100360 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600361 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600362 uri = validateIncomingUri(uri);
363 uri = maybeGetUriWithoutUserId(uri);
364 // Rebuild operation if we changed the Uri above
365 if (!Objects.equals(operation.getUri(), uri)) {
366 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100367 operations.set(i, operation);
368 }
Fred Quintana89437372009-05-15 15:10:40 -0700369 if (operation.isReadOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700370 if (enforceReadPermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800371 != AppOpsManager.MODE_ALLOWED) {
372 throw new OperationApplicationException("App op not allowed", 0);
373 }
Fred Quintana89437372009-05-15 15:10:40 -0700374 }
Fred Quintana89437372009-05-15 15:10:40 -0700375 if (operation.isWriteOperation()) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700376 if (enforceWritePermission(callingPkg, featureId, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800377 != AppOpsManager.MODE_ALLOWED) {
378 throw new OperationApplicationException("App op not allowed", 0);
379 }
Fred Quintana89437372009-05-15 15:10:40 -0700380 }
381 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600382 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700383 final Pair<String, String> original = setCallingPackage(
384 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700385 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700386 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700387 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800388 if (results != null) {
389 for (int i = 0; i < results.length ; i++) {
390 if (userIds[i] != UserHandle.USER_CURRENT) {
391 // Adding the userId to the uri.
392 results[i] = new ContentProviderResult(results[i], userIds[i]);
393 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100394 }
395 }
396 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700397 } catch (RemoteException e) {
398 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700399 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700400 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600401 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700402 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700403 }
404
Jeff Brown75ea64f2012-01-25 19:37:13 -0800405 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700406 public int delete(String callingPkg, @Nullable String featureId, Uri uri, String selection,
407 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600408 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100409 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700410 if (enforceWritePermission(callingPkg, featureId, uri, null)
411 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800412 return 0;
413 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600414 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700415 final Pair<String, String> original = setCallingPackage(
416 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700417 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700418 return mInterface.delete(uri, selection, selectionArgs);
419 } catch (RemoteException e) {
420 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700421 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700422 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600423 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
426
Jeff Brown75ea64f2012-01-25 19:37:13 -0800427 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700428 public int update(String callingPkg, @Nullable String featureId, Uri uri,
429 ContentValues values, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600430 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100431 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700432 if (enforceWritePermission(callingPkg, featureId, uri, null)
433 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800434 return 0;
435 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600436 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700437 final Pair<String, String> original = setCallingPackage(
438 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700439 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700440 return mInterface.update(uri, values, selection, selectionArgs);
441 } catch (RemoteException e) {
442 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700443 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600445 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 }
448
Jeff Brown75ea64f2012-01-25 19:37:13 -0800449 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700450 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId,
451 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
452 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600453 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100454 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700455 enforceFilePermission(callingPkg, featureId, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600456 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700457 final Pair<String, String> original = setCallingPackage(
458 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700459 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700460 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700461 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700462 } catch (RemoteException e) {
463 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700464 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700465 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600466 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 }
469
Jeff Brown75ea64f2012-01-25 19:37:13 -0800470 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700471 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
472 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600474 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100475 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700476 enforceFilePermission(callingPkg, featureId, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600477 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700478 final Pair<String, String> original = setCallingPackage(
479 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700480 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700481 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700482 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700483 } catch (RemoteException e) {
484 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700485 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700486 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600487 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490
Jeff Brown75ea64f2012-01-25 19:37:13 -0800491 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700492 public Bundle call(String callingPkg, @Nullable String featureId, String authority,
493 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700494 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600495 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600496 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700497 final Pair<String, String> original = setCallingPackage(
498 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700499 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700500 return mInterface.call(authority, method, arg, extras);
501 } catch (RemoteException e) {
502 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700503 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700504 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600505 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700506 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800507 }
508
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700509 @Override
510 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700511 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600512 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100513 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600514 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
515 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700516 return mInterface.getStreamTypes(uri, mimeTypeFilter);
517 } catch (RemoteException e) {
518 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600519 } finally {
520 Trace.traceEnd(TRACE_TAG_DATABASE);
521 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700522 }
523
524 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700525 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
526 @Nullable String featureId, Uri uri, String mimeType, Bundle opts,
527 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600528 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600529 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100530 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700531 enforceFilePermission(callingPkg, featureId, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600532 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700533 final Pair<String, String> original = setCallingPackage(
534 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700535 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700536 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700537 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700538 } catch (RemoteException e) {
539 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700540 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700541 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600542 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700543 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700544 }
545
Jeff Brown75ea64f2012-01-25 19:37:13 -0800546 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700547 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800548 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800549 }
550
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700551 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700552 public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600553 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100554 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100555 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700556 if (enforceReadPermission(callingPkg, featureId, uri, null)
557 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700558 return null;
559 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600560 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700561 final Pair<String, String> original = setCallingPackage(
562 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700563 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700564 return maybeAddUserId(mInterface.canonicalize(uri), userId);
565 } catch (RemoteException e) {
566 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700567 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700568 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600569 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700570 }
571 }
572
573 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700574 public Uri uncanonicalize(String callingPkg, String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600575 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100576 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100577 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700578 if (enforceReadPermission(callingPkg, featureId, uri, null)
579 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700580 return null;
581 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600582 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700583 final Pair<String, String> original = setCallingPackage(
584 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700585 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700586 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
587 } catch (RemoteException e) {
588 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700589 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700590 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600591 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700592 }
593 }
594
Ben Lin1cf454f2016-11-10 13:50:54 -0800595 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700596 public boolean refresh(String callingPkg, String featureId, Uri uri, Bundle args,
Ben Lin1cf454f2016-11-10 13:50:54 -0800597 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600598 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800599 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700600 if (enforceReadPermission(callingPkg, featureId, uri, null)
601 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800602 return false;
603 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600604 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700605 final Pair<String, String> original = setCallingPackage(
606 new Pair<>(callingPkg, featureId));
Ben Lin1cf454f2016-11-10 13:50:54 -0800607 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700608 return mInterface.refresh(uri, args,
Ben Lin1cf454f2016-11-10 13:50:54 -0800609 CancellationSignal.fromTransport(cancellationSignal));
610 } finally {
611 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600612 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800613 }
614 }
615
Jeff Sharkey9edef252019-05-20 14:00:17 -0600616 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700617 public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri,
618 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600619 uri = validateIncomingUri(uri);
620 uri = maybeGetUriWithoutUserId(uri);
621 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700622 final Pair<String, String> original = setCallingPackage(
623 new Pair<>(callingPkg, featureId));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600624 try {
625 return mInterface.checkUriPermission(uri, uid, modeFlags);
626 } catch (RemoteException e) {
627 throw e.rethrowAsRuntimeException();
628 } finally {
629 setCallingPackage(original);
630 Trace.traceEnd(TRACE_TAG_DATABASE);
631 }
632 }
633
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700634 private void enforceFilePermission(String callingPkg, @Nullable String featureId, Uri uri,
635 String mode, IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800636 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700637 if (enforceWritePermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800638 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800639 throw new FileNotFoundException("App op not allowed");
640 }
641 } else {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700642 if (enforceReadPermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800643 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800644 throw new FileNotFoundException("App op not allowed");
645 }
646 }
647 }
648
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700649 private int enforceReadPermission(String callingPkg, @Nullable String featureId, Uri uri,
650 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800651 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700652 final int mode = enforceReadPermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700653 if (mode != MODE_ALLOWED) {
654 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800655 }
Svet Ganov99b60432015-06-27 13:15:22 -0700656
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700657 return noteProxyOp(callingPkg, featureId, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800658 }
659
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700660 private int enforceWritePermission(String callingPkg, String featureId, Uri uri,
661 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800662 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700663 final int mode = enforceWritePermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700664 if (mode != MODE_ALLOWED) {
665 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800666 }
Svet Ganov99b60432015-06-27 13:15:22 -0700667
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700668 return noteProxyOp(callingPkg, featureId, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700669 }
670
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700671 private int noteProxyOp(String callingPkg, String featureId, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700672 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700673 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
674 featureId, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700675 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700676 }
677
Dianne Hackborn35654b62013-01-14 17:38:02 -0800678 return AppOpsManager.MODE_ALLOWED;
679 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700680 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800681
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100682 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700683 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
684 return true;
685 }
686 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
687 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100688 == PERMISSION_GRANTED;
689 }
690
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700691 /**
692 * Verify that calling app holds both the given permission and any app-op
693 * associated with that permission.
694 */
695 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700696 @Nullable String featureId, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700697 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
698 callerToken) != PERMISSION_GRANTED) {
699 return MODE_ERRORED;
700 }
701
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700702 return mTransport.noteProxyOp(callingPkg, featureId,
703 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700704 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700705
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700706 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700707 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
708 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700709 final Context context = getContext();
710 final int pid = Binder.getCallingPid();
711 final int uid = Binder.getCallingUid();
712 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700713 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700714
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700715 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700716 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700717 }
718
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100719 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700720 final String componentPerm = getReadPermission();
721 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700722 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
723 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700724 if (mode == MODE_ALLOWED) {
725 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700726 } else {
727 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700728 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700729 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700730 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700731
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700732 // track if unprotected read is allowed; any denied
733 // <path-permission> below removes this ability
734 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700735
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700736 final PathPermission[] pps = getPathPermissions();
737 if (pps != null) {
738 final String path = uri.getPath();
739 for (PathPermission pp : pps) {
740 final String pathPerm = pp.getReadPermission();
741 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700742 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
743 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700744 if (mode == MODE_ALLOWED) {
745 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700746 } else {
747 // any denied <path-permission> means we lose
748 // default <provider> access.
749 allowDefaultRead = false;
750 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700751 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700752 }
753 }
754 }
755 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700756
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700757 // if we passed <path-permission> checks above, and no default
758 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700759 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700761
762 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800763 final int callingUserId = UserHandle.getUserId(uid);
764 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
765 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800766 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
767 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700768 return MODE_ALLOWED;
769 }
770
771 // If the worst denial we found above was ignored, then pass that
772 // ignored through; otherwise we assume it should be a real error below.
773 if (strongestMode == MODE_IGNORED) {
774 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700775 }
776
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600777 final String suffix;
778 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
779 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
780 } else if (mExported) {
781 suffix = " requires " + missingPerm + ", or grantUriPermission()";
782 } else {
783 suffix = " requires the provider be exported, or grantUriPermission()";
784 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700785 throw new SecurityException("Permission Denial: reading "
786 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600787 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700788 }
789
790 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700791 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
792 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700793 final Context context = getContext();
794 final int pid = Binder.getCallingPid();
795 final int uid = Binder.getCallingUid();
796 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700797 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700798
799 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700800 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700801 }
802
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100803 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700804 final String componentPerm = getWritePermission();
805 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700806 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
807 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700808 if (mode == MODE_ALLOWED) {
809 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700810 } else {
811 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700812 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700813 }
814 }
815
816 // track if unprotected write is allowed; any denied
817 // <path-permission> below removes this ability
818 boolean allowDefaultWrite = (componentPerm == null);
819
820 final PathPermission[] pps = getPathPermissions();
821 if (pps != null) {
822 final String path = uri.getPath();
823 for (PathPermission pp : pps) {
824 final String pathPerm = pp.getWritePermission();
825 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700826 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
827 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700828 if (mode == MODE_ALLOWED) {
829 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700830 } else {
831 // any denied <path-permission> means we lose
832 // default <provider> access.
833 allowDefaultWrite = false;
834 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700835 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700836 }
837 }
838 }
839 }
840
841 // if we passed <path-permission> checks above, and no default
842 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700843 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700844 }
845
846 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800847 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
848 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700849 return MODE_ALLOWED;
850 }
851
852 // If the worst denial we found above was ignored, then pass that
853 // ignored through; otherwise we assume it should be a real error below.
854 if (strongestMode == MODE_IGNORED) {
855 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700856 }
857
858 final String failReason = mExported
859 ? " requires " + missingPerm + ", or grantUriPermission()"
860 : " requires the provider be exported, or grantUriPermission()";
861 throw new SecurityException("Permission Denial: writing "
862 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
863 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700867 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800868 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 * constructor.
870 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700871 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 return mContext;
873 }
874
875 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700876 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
877 * after {@link #onCreate}. When called before context was created, an IllegalStateException
878 * will be thrown.
879 * <p>
880 * Note A provider must be declared in the manifest and created automatically by the system,
881 * and context is only available after {@link #onCreate} is called.
882 */
883 @NonNull
884 public final Context requireContext() {
885 final Context ctx = getContext();
886 if (ctx == null) {
887 throw new IllegalStateException("Cannot find context from the provider.");
888 }
889 return ctx;
890 }
891
892 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700893 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700894 * which can be used later to restore the previous state.
895 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700896 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
897 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700898 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600899 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700900 return original;
901 }
902
903 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700904 * Return the package name of the caller that initiated the request being
905 * processed on the current thread. The returned package will have been
906 * verified to belong to the calling UID. Returns {@code null} if not
907 * currently processing a request.
908 * <p>
909 * This will always return {@code null} when processing
910 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
911 *
912 * @see Binder#getCallingUid()
913 * @see Context#grantUriPermission(String, Uri, int)
914 * @throws SecurityException if the calling package doesn't belong to the
915 * calling UID.
916 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700917 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700918 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700919 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700920 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
921 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700922 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700923
924 return null;
925 }
926
927 /**
928 * Return the feature in the package of the caller that initiated the request being
929 * processed on the current thread. Returns {@code null} if not currently processing
930 * a request of the request is for the default feature.
931 * <p>
932 * This will always return {@code null} when processing
933 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
934 *
935 * @see #getCallingPackage
936 */
937 public final @Nullable String getCallingFeatureId() {
938 final Pair<String, String> pkg = mCallingPackage.get();
939 if (pkg != null) {
940 return pkg.second;
941 }
942
943 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700944 }
945
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600946 /** {@hide} */
947 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700948 final Pair<String, String> pkg = mCallingPackage.get();
949 if (pkg != null) {
950 return pkg.first;
951 }
952
953 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600954 }
955
956 /** {@hide} */
957 public void onCallingPackageChanged() {
958 }
959
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700960 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600961 * Opaque token representing the identity of an incoming IPC.
962 */
963 public final class CallingIdentity {
964 /** {@hide} */
965 public final long binderToken;
966 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700967 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600968
969 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700970 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600971 this.binderToken = binderToken;
972 this.callingPackage = callingPackage;
973 }
974 }
975
976 /**
977 * Reset the identity of the incoming IPC on the current thread.
978 * <p>
979 * Internally this calls {@link Binder#clearCallingIdentity()} and also
980 * clears any value stored in {@link #getCallingPackage()}.
981 *
982 * @return Returns an opaque token that can be used to restore the original
983 * calling identity by passing it to
984 * {@link #restoreCallingIdentity}.
985 */
986 public final @NonNull CallingIdentity clearCallingIdentity() {
987 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
988 }
989
990 /**
991 * Restore the identity of the incoming IPC on the current thread back to a
992 * previously identity that was returned by {@link #clearCallingIdentity}.
993 * <p>
994 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
995 * also restores any value stored in {@link #getCallingPackage()}.
996 */
997 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
998 Binder.restoreCallingIdentity(identity.binderToken);
999 mCallingPackage.set(identity.callingPackage);
1000 }
1001
1002 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001003 * Change the authorities of the ContentProvider.
1004 * This is normally set for you from its manifest information when the provider is first
1005 * created.
1006 * @hide
1007 * @param authorities the semi-colon separated authorities of the ContentProvider.
1008 */
1009 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001010 if (authorities != null) {
1011 if (authorities.indexOf(';') == -1) {
1012 mAuthority = authorities;
1013 mAuthorities = null;
1014 } else {
1015 mAuthority = null;
1016 mAuthorities = authorities.split(";");
1017 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001018 }
1019 }
1020
1021 /** @hide */
1022 protected final boolean matchesOurAuthorities(String authority) {
1023 if (mAuthority != null) {
1024 return mAuthority.equals(authority);
1025 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001026 if (mAuthorities != null) {
1027 int length = mAuthorities.length;
1028 for (int i = 0; i < length; i++) {
1029 if (mAuthorities[i].equals(authority)) return true;
1030 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001031 }
1032 return false;
1033 }
1034
1035
1036 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 * Change the permission required to read data from the content
1038 * provider. This is normally set for you from its manifest information
1039 * when the provider is first created.
1040 *
1041 * @param permission Name of the permission required for read-only access.
1042 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001043 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 mReadPermission = permission;
1045 }
1046
1047 /**
1048 * Return the name of the permission required for read-only access to
1049 * this content provider. This method can be called from multiple
1050 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001051 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1052 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001054 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 return mReadPermission;
1056 }
1057
1058 /**
1059 * Change the permission required to read and write data in the content
1060 * provider. This is normally set for you from its manifest information
1061 * when the provider is first created.
1062 *
1063 * @param permission Name of the permission required for read/write access.
1064 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001065 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 mWritePermission = permission;
1067 }
1068
1069 /**
1070 * Return the name of the permission required for read/write access to
1071 * this content provider. This method can be called from multiple
1072 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001073 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1074 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001076 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 return mWritePermission;
1078 }
1079
1080 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001081 * Change the path-based permission required to read and/or write data in
1082 * the content provider. This is normally set for you from its manifest
1083 * information when the provider is first created.
1084 *
1085 * @param permissions Array of path permission descriptions.
1086 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001087 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001088 mPathPermissions = permissions;
1089 }
1090
1091 /**
1092 * Return the path-based permissions required for read and/or write access to
1093 * this content provider. This method can be called from multiple
1094 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001095 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1096 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001097 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001098 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001099 return mPathPermissions;
1100 }
1101
Dianne Hackborn35654b62013-01-14 17:38:02 -08001102 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001103 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001104 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001105 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001106 mTransport.mReadOp = readOp;
1107 mTransport.mWriteOp = writeOp;
1108 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001109 }
1110
Dianne Hackborn961321f2013-02-05 17:22:41 -08001111 /** @hide */
1112 public AppOpsManager getAppOpsManager() {
1113 return mTransport.mAppOpsManager;
1114 }
1115
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001116 /** @hide */
1117 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001118 if (mTransport == null) {
1119 return;
1120 }
1121 if (enabled) {
1122 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1123 } else {
1124 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001125 }
1126 }
1127
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001128 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001129 * Implement this to initialize your content provider on startup.
1130 * This method is called for all registered content providers on the
1131 * application main thread at application launch time. It must not perform
1132 * lengthy operations, or application startup will be delayed.
1133 *
1134 * <p>You should defer nontrivial initialization (such as opening,
1135 * upgrading, and scanning databases) until the content provider is used
1136 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1137 * keeps application startup fast, avoids unnecessary work if the provider
1138 * turns out not to be needed, and stops database errors (such as a full
1139 * disk) from halting application launch.
1140 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001141 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001142 * is a helpful utility class that makes it easy to manage databases,
1143 * and will automatically defer opening until first use. If you do use
1144 * SQLiteOpenHelper, make sure to avoid calling
1145 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1146 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1147 * from this method. (Instead, override
1148 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1149 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 *
1151 * @return true if the provider was successfully loaded, false otherwise
1152 */
1153 public abstract boolean onCreate();
1154
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001155 /**
1156 * {@inheritDoc}
1157 * This method is always called on the application main thread, and must
1158 * not perform lengthy operations.
1159 *
1160 * <p>The default content provider implementation does nothing.
1161 * Override this method to take appropriate action.
1162 * (Content providers do not usually care about things like screen
1163 * orientation, but may want to know about locale changes.)
1164 */
Steve McKayea93fe72016-12-02 11:35:35 -08001165 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 public void onConfigurationChanged(Configuration newConfig) {
1167 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001168
1169 /**
1170 * {@inheritDoc}
1171 * This method is always called on the application main thread, and must
1172 * not perform lengthy operations.
1173 *
1174 * <p>The default content provider implementation does nothing.
1175 * Subclasses may override this method to take appropriate action.
1176 */
Steve McKayea93fe72016-12-02 11:35:35 -08001177 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 public void onLowMemory() {
1179 }
1180
Steve McKayea93fe72016-12-02 11:35:35 -08001181 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001182 public void onTrimMemory(int level) {
1183 }
1184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001186 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001187 *
1188 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1189 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1190 * implementation of this method.
1191 *
1192 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001193 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1194 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 * <p>
1196 * Example client call:<p>
1197 * <pre>// Request a specific record.
1198 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001199 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 projection, // Which columns to return.
1201 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001202 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 People.NAME + " ASC"); // Sort order.</pre>
1204 * Example implementation:<p>
1205 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1206 // proper SQL syntax for us.
1207 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1208
1209 // Set the table we're querying.
1210 qBuilder.setTables(DATABASE_TABLE_NAME);
1211
1212 // If the query ends in a specific record number, we're
1213 // being asked for a specific record, so set the
1214 // WHERE clause in our query.
1215 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1216 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1217 }
1218
1219 // Make the query.
1220 Cursor c = qBuilder.query(mDb,
1221 projection,
1222 selection,
1223 selectionArgs,
1224 groupBy,
1225 having,
1226 sortOrder);
1227 c.setNotificationUri(getContext().getContentResolver(), uri);
1228 return c;</pre>
1229 *
1230 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001231 * if the client is requesting a specific record, the URI will end in a record number
1232 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1233 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001235 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001237 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001238 * @param selectionArgs You may include ?s in selection, which will be replaced by
1239 * the values from selectionArgs, in order that they appear in the selection.
1240 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001242 * If {@code null} then the provider is free to define the sort order.
1243 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001245 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1246 @Nullable String selection, @Nullable String[] selectionArgs,
1247 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248
Fred Quintana5bba6322009-10-05 14:21:12 -07001249 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001250 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001251 *
1252 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1253 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1254 *
1255 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001256 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1257 * and Threads</a>.
1258 * <p>
1259 * Example client call:<p>
1260 * <pre>// Request a specific record.
1261 * Cursor managedCursor = managedQuery(
1262 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1263 projection, // Which columns to return.
1264 null, // WHERE clause.
1265 null, // WHERE clause value substitution
1266 People.NAME + " ASC"); // Sort order.</pre>
1267 * Example implementation:<p>
1268 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1269 // proper SQL syntax for us.
1270 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1271
1272 // Set the table we're querying.
1273 qBuilder.setTables(DATABASE_TABLE_NAME);
1274
1275 // If the query ends in a specific record number, we're
1276 // being asked for a specific record, so set the
1277 // WHERE clause in our query.
1278 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1279 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1280 }
1281
1282 // Make the query.
1283 Cursor c = qBuilder.query(mDb,
1284 projection,
1285 selection,
1286 selectionArgs,
1287 groupBy,
1288 having,
1289 sortOrder);
1290 c.setNotificationUri(getContext().getContentResolver(), uri);
1291 return c;</pre>
1292 * <p>
1293 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001294 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1295 * signal to ensure correct operation on older versions of the Android Framework in
1296 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001297 *
1298 * @param uri The URI to query. This will be the full URI sent by the client;
1299 * if the client is requesting a specific record, the URI will end in a record number
1300 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1301 * that _id value.
1302 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001303 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001304 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001305 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001306 * @param selectionArgs You may include ?s in selection, which will be replaced by
1307 * the values from selectionArgs, in order that they appear in the selection.
1308 * The values will be bound as Strings.
1309 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001310 * If {@code null} then the provider is free to define the sort order.
1311 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001312 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001313 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001314 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001315 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001316 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1317 @Nullable String selection, @Nullable String[] selectionArgs,
1318 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001319 return query(uri, projection, selection, selectionArgs, sortOrder);
1320 }
1321
1322 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001323 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1324 * Arguments may include traditional SQL style query arguments. When present these
1325 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001326 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001327 *
1328 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001329 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1330 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1331 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001332 *
Steve McKay76b27702017-04-24 12:07:53 -07001333 * <p>This method can be called from multiple threads, as described in
1334 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1335 * and Threads</a>.
1336 *
1337 * <p>
1338 * Example client call:<p>
1339 * <pre>// Request 20 records starting at row index 30.
1340 Bundle queryArgs = new Bundle();
1341 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1342 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1343
1344 Cursor cursor = getContentResolver().query(
1345 contentUri, // Content Uri is specific to individual content providers.
1346 projection, // String[] describing which columns to return.
1347 queryArgs, // Query arguments.
1348 null); // Cancellation signal.</pre>
1349 *
1350 * Example implementation:<p>
1351 * <pre>
1352
1353 int recordsetSize = 0x1000; // Actual value is implementation specific.
1354 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1355
1356 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1357 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1358
1359 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1360
1361 // Calculate the number of items to include in the cursor.
1362 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1363
1364 // Build the paged result set....
1365 for (int i = offset; i < offset + numItems; i++) {
1366 // populate row from your data.
1367 }
1368
1369 Bundle extras = new Bundle();
1370 c.setExtras(extras);
1371
1372 // Any QUERY_ARG_* key may be included if honored.
1373 // In an actual implementation, include only keys that are both present in queryArgs
1374 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1375 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1376 // then QUERY_ARG_OFFSET should be omitted.
1377 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1378 ContentResolver.QUERY_ARG_OFFSET,
1379 ContentResolver.QUERY_ARG_LIMIT
1380 });
1381
1382 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1383
1384 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1385
1386 return cursor;</pre>
1387 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001388 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1389 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001390 *
1391 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001392 * @param projection The list of columns to put into the cursor.
1393 * If {@code null} provide a default set of columns.
1394 * @param queryArgs A Bundle containing all additional information necessary for the query.
1395 * Values in the Bundle may include SQL style arguments.
1396 * @param cancellationSignal A signal to cancel the operation in progress,
1397 * or {@code null}.
1398 * @return a Cursor or {@code null}.
1399 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001400 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001401 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1402 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1403 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001404
Steve McKayd7ece9f2017-01-12 16:59:59 -08001405 // if client doesn't supply an SQL sort order argument, attempt to build one from
1406 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001407 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001408 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1409 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1410 }
1411
Steve McKayea93fe72016-12-02 11:35:35 -08001412 return query(
1413 uri,
1414 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001415 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1416 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1417 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001418 cancellationSignal);
1419 }
1420
1421 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001422 * Implement this to handle requests for the MIME type of the data at the
1423 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 * <code>vnd.android.cursor.item</code> for a single record,
1425 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001426 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001427 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1428 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001430 * <p>Note that there are no permissions needed for an application to
1431 * access this information; if your content provider requires read and/or
1432 * write permissions, or is not exported, all applications can still call
1433 * this method regardless of their access permissions. This allows them
1434 * to retrieve the MIME type for a URI when dispatching intents.
1435 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001437 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001439 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001440 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441
1442 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001443 * Implement this to support canonicalization of URIs that refer to your
1444 * content provider. A canonical URI is one that can be transported across
1445 * devices, backup/restore, and other contexts, and still be able to refer
1446 * to the same data item. Typically this is implemented by adding query
1447 * params to the URI allowing the content provider to verify that an incoming
1448 * canonical URI references the same data as it was originally intended for and,
1449 * if it doesn't, to find that data (if it exists) in the current environment.
1450 *
1451 * <p>For example, if the content provider holds people and a normal URI in it
1452 * is created with a row index into that people database, the cananical representation
1453 * may have an additional query param at the end which specifies the name of the
1454 * person it is intended for. Later calls into the provider with that URI will look
1455 * up the row of that URI's base index and, if it doesn't match or its entry's
1456 * name doesn't match the name in the query param, perform a query on its database
1457 * to find the correct row to operate on.</p>
1458 *
1459 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1460 * URIs (including this one) must perform this verification and recovery of any
1461 * canonical URIs they receive. In addition, you must also implement
1462 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1463 *
1464 * <p>The default implementation of this method returns null, indicating that
1465 * canonical URIs are not supported.</p>
1466 *
1467 * @param url The Uri to canonicalize.
1468 *
1469 * @return Return the canonical representation of <var>url</var>, or null if
1470 * canonicalization of that Uri is not supported.
1471 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001472 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001473 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001474 return null;
1475 }
1476
1477 /**
1478 * Remove canonicalization from canonical URIs previously returned by
1479 * {@link #canonicalize}. For example, if your implementation is to add
1480 * a query param to canonicalize a URI, this method can simply trip any
1481 * query params on the URI. The default implementation always returns the
1482 * same <var>url</var> that was passed in.
1483 *
1484 * @param url The Uri to remove any canonicalization from.
1485 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001486 * @return Return the non-canonical representation of <var>url</var>, return
1487 * the <var>url</var> as-is if there is nothing to do, or return null if
1488 * the data identified by the canonical representation can not be found in
1489 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001490 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001491 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001492 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001493 return url;
1494 }
1495
1496 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001497 * Implement this to support refresh of content identified by {@code uri}. By default, this
1498 * method returns false; providers who wish to implement this should return true to signal the
1499 * client that the provider has tried refreshing with its own implementation.
1500 * <p>
1501 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1502 * <p>
1503 * Client code should only invoke this method when there is a strong indication (such as a user
1504 * initiated pull to refresh gesture) that the content is stale.
1505 * <p>
1506 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1507 * notifications when content changes.
1508 *
1509 * @param uri The Uri identifying the data to refresh.
1510 * @param args Additional options from the client. The definitions of these are specific to the
1511 * content provider being called.
1512 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1513 * none. For example, if you called refresh on a particular uri, you should call
1514 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1515 * canceled the refresh request.
1516 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001517 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001518 @Override
Ben Lin1cf454f2016-11-10 13:50:54 -08001519 public boolean refresh(Uri uri, @Nullable Bundle args,
1520 @Nullable CancellationSignal cancellationSignal) {
1521 return false;
1522 }
1523
Jeff Sharkey9edef252019-05-20 14:00:17 -06001524 /** {@hide} */
1525 @Override
1526 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1527 return PackageManager.PERMISSION_DENIED;
1528 }
1529
Ben Lin1cf454f2016-11-10 13:50:54 -08001530 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001531 * @hide
1532 * Implementation when a caller has performed an insert on the content
1533 * provider, but that call has been rejected for the operation given
1534 * to {@link #setAppOps(int, int)}. The default implementation simply
1535 * returns a dummy URI that is the base URI with a 0 path element
1536 * appended.
1537 */
1538 public Uri rejectInsert(Uri uri, ContentValues values) {
1539 // If not allowed, we need to return some reasonable URI. Maybe the
1540 // content provider should be responsible for this, but for now we
1541 // will just return the base URI with a dummy '0' tagged on to it.
1542 // You shouldn't be able to read if you can't write, anyway, so it
1543 // shouldn't matter much what is returned.
1544 return uri.buildUpon().appendPath("0").build();
1545 }
1546
1547 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001548 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1550 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001551 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001552 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1553 * and Threads</a>.
Varun Shah8c80a3f2019-10-16 12:21:19 -07001554 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 * @param values A set of column_name/value pairs to add to the database.
1556 * @return The URI for the newly inserted item.
1557 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001558 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001559 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560
1561 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001562 * Override this to handle requests to insert a set of new rows, or the
1563 * default implementation will iterate over the values and call
1564 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1566 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001567 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001568 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1569 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 *
1571 * @param uri The content:// URI of the insertion request.
1572 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001573 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 * @return The number of values that were inserted.
1575 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001576 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001577 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 int numValues = values.length;
1579 for (int i = 0; i < numValues; i++) {
1580 insert(uri, values[i]);
1581 }
1582 return numValues;
1583 }
1584
1585 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001586 * Implement this to handle requests to delete one or more rows.
1587 * The implementation should apply the selection clause when performing
1588 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001589 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001591 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001592 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1593 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 *
1595 * <p>The implementation is responsible for parsing out a row ID at the end
1596 * of the URI, if a specific row is being deleted. That is, the client would
1597 * pass in <code>content://contacts/people/22</code> and the implementation is
1598 * responsible for parsing the record number (22) when creating a SQL statement.
1599 *
1600 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1601 * @param selection An optional restriction to apply to rows when deleting.
1602 * @return The number of rows affected.
1603 * @throws SQLException
1604 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001605 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001606 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1607 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608
1609 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001610 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001611 * The implementation should update all rows matching the selection
1612 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1614 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001615 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001616 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1617 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 *
1619 * @param uri The URI to query. This can potentially have a record ID if this
1620 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001621 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 * @param selection An optional filter to match rows to update.
1623 * @return the number of rows affected.
1624 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001625 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001626 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001627 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628
1629 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001630 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001631 * The default implementation always throws {@link FileNotFoundException}.
1632 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001633 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1634 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001635 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001636 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1637 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001638 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 *
1640 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1641 * their responsibility to close it when done. That is, the implementation
1642 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001643 * <p>
1644 * If opened with the exclusive "r" or "w" modes, the returned
1645 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1646 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1647 * supports seeking.
1648 * <p>
1649 * If you need to detect when the returned ParcelFileDescriptor has been
1650 * closed, or if the remote process has crashed or encountered some other
1651 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1652 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1653 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1654 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001655 * <p>
1656 * If you need to return a large file that isn't backed by a real file on
1657 * disk, such as a file on a network share or cloud storage service,
1658 * consider using
1659 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1660 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001662 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1663 * to return the appropriate MIME type for the data returned here with
1664 * the same URI. This will allow intent resolution to automatically determine the data MIME
1665 * type and select the appropriate matching targets as part of its operation.</p>
1666 *
1667 * <p class="note">For better interoperability with other applications, it is recommended
1668 * that for any URIs that can be opened, you also support queries on them
1669 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1670 * You may also want to support other common columns if you have additional meta-data
1671 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1672 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1673 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 * @param uri The URI whose file is to be opened.
1675 * @param mode Access mode for the file. May be "r" for read-only access,
1676 * "rw" for read and write access, or "rwt" for read and write access
1677 * that truncates any existing file.
1678 *
1679 * @return Returns a new ParcelFileDescriptor which you can use to access
1680 * the file.
1681 *
1682 * @throws FileNotFoundException Throws FileNotFoundException if there is
1683 * no file associated with the given URI or the mode is invalid.
1684 * @throws SecurityException Throws SecurityException if the caller does
1685 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001686 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 * @see #openAssetFile(Uri, String)
1688 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001689 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001690 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001691 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001692 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 throws FileNotFoundException {
1694 throw new FileNotFoundException("No files supported by provider at "
1695 + uri);
1696 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001699 * Override this to handle requests to open a file blob.
1700 * The default implementation always throws {@link FileNotFoundException}.
1701 * This method can be called from multiple threads, as described in
1702 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1703 * and Threads</a>.
1704 *
1705 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1706 * to the caller. This way large data (such as images and documents) can be
1707 * returned without copying the content.
1708 *
1709 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1710 * their responsibility to close it when done. That is, the implementation
1711 * of this method should create a new ParcelFileDescriptor for each call.
1712 * <p>
1713 * If opened with the exclusive "r" or "w" modes, the returned
1714 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1715 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1716 * supports seeking.
1717 * <p>
1718 * If you need to detect when the returned ParcelFileDescriptor has been
1719 * closed, or if the remote process has crashed or encountered some other
1720 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1721 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1722 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1723 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1724 *
1725 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1726 * to return the appropriate MIME type for the data returned here with
1727 * the same URI. This will allow intent resolution to automatically determine the data MIME
1728 * type and select the appropriate matching targets as part of its operation.</p>
1729 *
1730 * <p class="note">For better interoperability with other applications, it is recommended
1731 * that for any URIs that can be opened, you also support queries on them
1732 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1733 * You may also want to support other common columns if you have additional meta-data
1734 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1735 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1736 *
1737 * @param uri The URI whose file is to be opened.
1738 * @param mode Access mode for the file. May be "r" for read-only access,
1739 * "w" for write-only access, "rw" for read and write access, or
1740 * "rwt" for read and write access that truncates any existing
1741 * file.
1742 * @param signal A signal to cancel the operation in progress, or
1743 * {@code null} if none. For example, if you are downloading a
1744 * file from the network to service a "rw" mode request, you
1745 * should periodically call
1746 * {@link CancellationSignal#throwIfCanceled()} to check whether
1747 * the client has canceled the request and abort the download.
1748 *
1749 * @return Returns a new ParcelFileDescriptor which you can use to access
1750 * the file.
1751 *
1752 * @throws FileNotFoundException Throws FileNotFoundException if there is
1753 * no file associated with the given URI or the mode is invalid.
1754 * @throws SecurityException Throws SecurityException if the caller does
1755 * not have permission to access the file.
1756 *
1757 * @see #openAssetFile(Uri, String)
1758 * @see #openFileHelper(Uri, String)
1759 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001760 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001761 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001762 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001763 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1764 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001765 return openFile(uri, mode);
1766 }
1767
1768 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 * This is like {@link #openFile}, but can be implemented by providers
1770 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001771 * inside of their .apk.
1772 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001773 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1774 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001775 *
1776 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001777 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001778 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1780 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1781 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001782 * <p>
1783 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1784 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001785 *
1786 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 * should create the AssetFileDescriptor with
1788 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001789 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001791 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1792 * to return the appropriate MIME type for the data returned here with
1793 * the same URI. This will allow intent resolution to automatically determine the data MIME
1794 * type and select the appropriate matching targets as part of its operation.</p>
1795 *
1796 * <p class="note">For better interoperability with other applications, it is recommended
1797 * that for any URIs that can be opened, you also support queries on them
1798 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1799 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 * @param uri The URI whose file is to be opened.
1801 * @param mode Access mode for the file. May be "r" for read-only access,
1802 * "w" for write-only access (erasing whatever data is currently in
1803 * the file), "wa" for write-only access to append to any existing data,
1804 * "rw" for read and write access on any existing data, and "rwt" for read
1805 * and write access that truncates any existing file.
1806 *
1807 * @return Returns a new AssetFileDescriptor which you can use to access
1808 * the file.
1809 *
1810 * @throws FileNotFoundException Throws FileNotFoundException if there is
1811 * no file associated with the given URI or the mode is invalid.
1812 * @throws SecurityException Throws SecurityException if the caller does
1813 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001814 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 * @see #openFile(Uri, String)
1816 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001817 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001819 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 throws FileNotFoundException {
1821 ParcelFileDescriptor fd = openFile(uri, mode);
1822 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1823 }
1824
1825 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001826 * This is like {@link #openFile}, but can be implemented by providers
1827 * that need to be able to return sub-sections of files, often assets
1828 * inside of their .apk.
1829 * This method can be called from multiple threads, as described in
1830 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1831 * and Threads</a>.
1832 *
1833 * <p>If you implement this, your clients must be able to deal with such
1834 * file slices, either directly with
1835 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1836 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1837 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1838 * methods.
1839 * <p>
1840 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1841 * streaming of data.
1842 *
1843 * <p class="note">If you are implementing this to return a full file, you
1844 * should create the AssetFileDescriptor with
1845 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1846 * applications that cannot handle sub-sections of files.</p>
1847 *
1848 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1849 * to return the appropriate MIME type for the data returned here with
1850 * the same URI. This will allow intent resolution to automatically determine the data MIME
1851 * type and select the appropriate matching targets as part of its operation.</p>
1852 *
1853 * <p class="note">For better interoperability with other applications, it is recommended
1854 * that for any URIs that can be opened, you also support queries on them
1855 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1856 *
1857 * @param uri The URI whose file is to be opened.
1858 * @param mode Access mode for the file. May be "r" for read-only access,
1859 * "w" for write-only access (erasing whatever data is currently in
1860 * the file), "wa" for write-only access to append to any existing data,
1861 * "rw" for read and write access on any existing data, and "rwt" for read
1862 * and write access that truncates any existing file.
1863 * @param signal A signal to cancel the operation in progress, or
1864 * {@code null} if none. For example, if you are downloading a
1865 * file from the network to service a "rw" mode request, you
1866 * should periodically call
1867 * {@link CancellationSignal#throwIfCanceled()} to check whether
1868 * the client has canceled the request and abort the download.
1869 *
1870 * @return Returns a new AssetFileDescriptor which you can use to access
1871 * the file.
1872 *
1873 * @throws FileNotFoundException Throws FileNotFoundException if there is
1874 * no file associated with the given URI or the mode is invalid.
1875 * @throws SecurityException Throws SecurityException if the caller does
1876 * not have permission to access the file.
1877 *
1878 * @see #openFile(Uri, String)
1879 * @see #openFileHelper(Uri, String)
1880 * @see #getType(android.net.Uri)
1881 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001882 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001883 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1884 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001885 return openAssetFile(uri, mode);
1886 }
1887
1888 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 * Convenience for subclasses that wish to implement {@link #openFile}
1890 * by looking up a column named "_data" at the given URI.
1891 *
1892 * @param uri The URI to be opened.
1893 * @param mode The file mode. May be "r" for read-only access,
1894 * "w" for write-only access (erasing whatever data is currently in
1895 * the file), "wa" for write-only access to append to any existing data,
1896 * "rw" for read and write access on any existing data, and "rwt" for read
1897 * and write access that truncates any existing file.
1898 *
1899 * @return Returns a new ParcelFileDescriptor that can be used by the
1900 * client to access the file.
1901 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001902 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1903 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1905 int count = (c != null) ? c.getCount() : 0;
1906 if (count != 1) {
1907 // If there is not exactly one result, throw an appropriate
1908 // exception.
1909 if (c != null) {
1910 c.close();
1911 }
1912 if (count == 0) {
1913 throw new FileNotFoundException("No entry for " + uri);
1914 }
1915 throw new FileNotFoundException("Multiple items at " + uri);
1916 }
1917
1918 c.moveToFirst();
1919 int i = c.getColumnIndex("_data");
1920 String path = (i >= 0 ? c.getString(i) : null);
1921 c.close();
1922 if (path == null) {
1923 throw new FileNotFoundException("Column _data not found.");
1924 }
1925
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001926 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 return ParcelFileDescriptor.open(new File(path), modeBits);
1928 }
1929
1930 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001931 * Called by a client to determine the types of data streams that this
1932 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001933 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001934 * of a particular type, return that MIME type if it matches the given
1935 * mimeTypeFilter. If it can perform type conversions, return an array
1936 * of all supported MIME types that match mimeTypeFilter.
1937 *
1938 * @param uri The data in the content provider being queried.
1939 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001940 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001941 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001942 * given mimeTypeFilter. Otherwise returns an array of all available
1943 * concrete MIME types.
1944 *
1945 * @see #getType(Uri)
1946 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001947 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001948 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001949 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001950 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001951 return null;
1952 }
1953
1954 /**
1955 * Called by a client to open a read-only stream containing data of a
1956 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1957 * except the file can only be read-only and the content provider may
1958 * perform data conversions to generate data of the desired type.
1959 *
1960 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001961 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001962 * {@link #openAssetFile(Uri, String)}.
1963 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001964 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001965 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001966 * <p>
1967 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1968 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001969 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001970 * <p class="note">For better interoperability with other applications, it is recommended
1971 * that for any URIs that can be opened, you also support queries on them
1972 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1973 * You may also want to support other common columns if you have additional meta-data
1974 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1975 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1976 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001977 * @param uri The data in the content provider being queried.
1978 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001979 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001980 * requirements; in this case the content provider will pick its best
1981 * type matching the pattern.
1982 * @param opts Additional options from the client. The definitions of
1983 * these are specific to the content provider being called.
1984 *
1985 * @return Returns a new AssetFileDescriptor from which the client can
1986 * read data of the desired type.
1987 *
1988 * @throws FileNotFoundException Throws FileNotFoundException if there is
1989 * no file associated with the given URI or the mode is invalid.
1990 * @throws SecurityException Throws SecurityException if the caller does
1991 * not have permission to access the data.
1992 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1993 * content provider does not support the requested MIME type.
1994 *
1995 * @see #getStreamTypes(Uri, String)
1996 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001997 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001998 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001999 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2000 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002001 if ("*/*".equals(mimeTypeFilter)) {
2002 // If they can take anything, the untyped open call is good enough.
2003 return openAssetFile(uri, "r");
2004 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002005 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002006 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002007 // Use old untyped open call if this provider has a type for this
2008 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002009 return openAssetFile(uri, "r");
2010 }
2011 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2012 }
2013
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002014
2015 /**
2016 * Called by a client to open a read-only stream containing data of a
2017 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2018 * except the file can only be read-only and the content provider may
2019 * perform data conversions to generate data of the desired type.
2020 *
2021 * <p>The default implementation compares the given mimeType against the
2022 * result of {@link #getType(Uri)} and, if they match, simply calls
2023 * {@link #openAssetFile(Uri, String)}.
2024 *
2025 * <p>See {@link ClipData} for examples of the use and implementation
2026 * of this method.
2027 * <p>
2028 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2029 * streaming of data.
2030 *
2031 * <p class="note">For better interoperability with other applications, it is recommended
2032 * that for any URIs that can be opened, you also support queries on them
2033 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2034 * You may also want to support other common columns if you have additional meta-data
2035 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2036 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2037 *
2038 * @param uri The data in the content provider being queried.
2039 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002040 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002041 * requirements; in this case the content provider will pick its best
2042 * type matching the pattern.
2043 * @param opts Additional options from the client. The definitions of
2044 * these are specific to the content provider being called.
2045 * @param signal A signal to cancel the operation in progress, or
2046 * {@code null} if none. For example, if you are downloading a
2047 * file from the network to service a "rw" mode request, you
2048 * should periodically call
2049 * {@link CancellationSignal#throwIfCanceled()} to check whether
2050 * the client has canceled the request and abort the download.
2051 *
2052 * @return Returns a new AssetFileDescriptor from which the client can
2053 * read data of the desired type.
2054 *
2055 * @throws FileNotFoundException Throws FileNotFoundException if there is
2056 * no file associated with the given URI or the mode is invalid.
2057 * @throws SecurityException Throws SecurityException if the caller does
2058 * not have permission to access the data.
2059 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2060 * content provider does not support the requested MIME type.
2061 *
2062 * @see #getStreamTypes(Uri, String)
2063 * @see #openAssetFile(Uri, String)
2064 * @see ClipDescription#compareMimeTypes(String, String)
2065 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002066 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002067 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2068 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2069 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002070 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2071 }
2072
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002073 /**
2074 * Interface to write a stream of data to a pipe. Use with
2075 * {@link ContentProvider#openPipeHelper}.
2076 */
2077 public interface PipeDataWriter<T> {
2078 /**
2079 * Called from a background thread to stream data out to a pipe.
2080 * Note that the pipe is blocking, so this thread can block on
2081 * writes for an arbitrary amount of time if the client is slow
2082 * at reading.
2083 *
2084 * @param output The pipe where data should be written. This will be
2085 * closed for you upon returning from this function.
2086 * @param uri The URI whose data is to be written.
2087 * @param mimeType The desired type of data to be written.
2088 * @param opts Options supplied by caller.
2089 * @param args Your own custom arguments.
2090 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002091 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2092 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002093 }
2094
2095 /**
2096 * A helper function for implementing {@link #openTypedAssetFile}, for
2097 * creating a data pipe and background thread allowing you to stream
2098 * generated data back to the client. This function returns a new
2099 * ParcelFileDescriptor that should be returned to the caller (the caller
2100 * is responsible for closing it).
2101 *
2102 * @param uri The URI whose data is to be written.
2103 * @param mimeType The desired type of data to be written.
2104 * @param opts Options supplied by caller.
2105 * @param args Your own custom arguments.
2106 * @param func Interface implementing the function that will actually
2107 * stream the data.
2108 * @return Returns a new ParcelFileDescriptor holding the read side of
2109 * the pipe. This should be returned to the caller for reading; the caller
2110 * is responsible for closing it when done.
2111 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002112 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2113 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2114 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002115 try {
2116 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2117
2118 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2119 @Override
2120 protected Object doInBackground(Object... params) {
2121 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2122 try {
2123 fds[1].close();
2124 } catch (IOException e) {
2125 Log.w(TAG, "Failure closing pipe", e);
2126 }
2127 return null;
2128 }
2129 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002130 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002131
2132 return fds[0];
2133 } catch (IOException e) {
2134 throw new FileNotFoundException("failure making pipe");
2135 }
2136 }
2137
2138 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 * Returns true if this instance is a temporary content provider.
2140 * @return true if this instance is a temporary content provider
2141 */
2142 protected boolean isTemporary() {
2143 return false;
2144 }
2145
2146 /**
2147 * Returns the Binder object for this provider.
2148 *
2149 * @return the Binder object for this provider
2150 * @hide
2151 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002152 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 public IContentProvider getIContentProvider() {
2154 return mTransport;
2155 }
2156
2157 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002158 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2159 * when directly instantiating the provider for testing.
2160 * @hide
2161 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002162 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002163 public void attachInfoForTesting(Context context, ProviderInfo info) {
2164 attachInfo(context, info, true);
2165 }
2166
2167 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 * After being instantiated, this is called to tell the content provider
2169 * about itself.
2170 *
2171 * @param context The context this provider is running in
2172 * @param info Registered information about this content provider
2173 */
2174 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002175 attachInfo(context, info, false);
2176 }
2177
2178 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002179 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002180 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 /*
2183 * Only allow it to be set once, so after the content service gives
2184 * this to us clients can't change it.
2185 */
2186 if (mContext == null) {
2187 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002188 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002189 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2190 Context.APP_OPS_SERVICE);
2191 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002192 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 if (info != null) {
2194 setReadPermission(info.readPermission);
2195 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002196 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002197 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002198 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002199 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002201 if (Build.IS_DEBUGGABLE) {
2202 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2203 Log.VERBOSE));
2204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 ContentProvider.this.onCreate();
2206 }
2207 }
Fred Quintanace31b232009-05-04 16:01:15 -07002208
2209 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002210 * Override this to handle requests to perform a batch of operations, or the
2211 * default implementation will iterate over the operations and call
2212 * {@link ContentProviderOperation#apply} on each of them.
2213 * If all calls to {@link ContentProviderOperation#apply} succeed
2214 * then a {@link ContentProviderResult} array with as many
2215 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002216 * fail, it is up to the implementation how many of the others take effect.
2217 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002218 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2219 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002220 *
Fred Quintanace31b232009-05-04 16:01:15 -07002221 * @param operations the operations to apply
2222 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002223 * @throws OperationApplicationException thrown if any operation fails.
2224 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002225 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002226 @Override
2227 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2228 @NonNull ArrayList<ContentProviderOperation> operations)
2229 throws OperationApplicationException {
2230 return applyBatch(operations);
2231 }
2232
Jeff Sharkey673db442015-06-11 19:30:57 -07002233 public @NonNull ContentProviderResult[] applyBatch(
2234 @NonNull ArrayList<ContentProviderOperation> operations)
2235 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002236 final int numOperations = operations.size();
2237 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2238 for (int i = 0; i < numOperations; i++) {
2239 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002240 }
2241 return results;
2242 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002243
2244 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002245 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002246 * interfaces that are cheaper and/or unnatural for a table-like
2247 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002248 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002249 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2250 * on this entry into the content provider besides the basic ability for the application
2251 * to get access to the provider at all. For example, it has no idea whether the call
2252 * being executed may read or write data in the provider, so can't enforce those
2253 * individual permissions. Any implementation of this method <strong>must</strong>
2254 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2255 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002256 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2257 * @param arg provider-defined String argument. May be {@code null}.
2258 * @param extras provider-defined Bundle argument. May be {@code null}.
2259 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002260 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002261 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002262 @Override
2263 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2264 @Nullable String arg, @Nullable Bundle extras) {
2265 return call(method, arg, extras);
2266 }
2267
Jeff Sharkey673db442015-06-11 19:30:57 -07002268 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2269 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002270 return null;
2271 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002272
2273 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002274 * Implement this to shut down the ContentProvider instance. You can then
2275 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002276 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002277 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002278 * Android normally handles ContentProvider startup and shutdown
2279 * automatically. You do not need to start up or shut down a
2280 * ContentProvider. When you invoke a test method on a ContentProvider,
2281 * however, a ContentProvider instance is started and keeps running after
2282 * the test finishes, even if a succeeding test instantiates another
2283 * ContentProvider. A conflict develops because the two instances are
2284 * usually running against the same underlying data source (for example, an
2285 * sqlite database).
2286 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002287 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002288 * Implementing shutDown() avoids this conflict by providing a way to
2289 * terminate the ContentProvider. This method can also prevent memory leaks
2290 * from multiple instantiations of the ContentProvider, and it can ensure
2291 * unit test isolation by allowing you to completely clean up the test
2292 * fixture before moving on to the next test.
2293 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002294 */
2295 public void shutdown() {
2296 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2297 "connections are gracefully shutdown");
2298 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002299
2300 /**
2301 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002302 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002303 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002304 * @param fd The raw file descriptor that the dump is being sent to.
2305 * @param writer The PrintWriter to which you should dump your state. This will be
2306 * closed for you after you return.
2307 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002308 */
2309 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2310 writer.println("nothing to dump");
2311 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002312
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002313 private void validateIncomingAuthority(String authority) throws SecurityException {
2314 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2315 String message = "The authority " + authority + " does not match the one of the "
2316 + "contentProvider: ";
2317 if (mAuthority != null) {
2318 message += mAuthority;
2319 } else {
2320 message += Arrays.toString(mAuthorities);
2321 }
2322 throw new SecurityException(message);
2323 }
2324 }
2325
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002326 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002327 @VisibleForTesting
2328 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002329 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002330 if (!mSingleUser) {
2331 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2332 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2333 throw new SecurityException("trying to query a ContentProvider in user "
2334 + mContext.getUserId() + " with a uri belonging to user " + userId);
2335 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002336 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002337 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002338
2339 // Normalize the path by removing any empty path segments, which can be
2340 // a source of security issues.
2341 final String encodedPath = uri.getEncodedPath();
2342 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002343 final Uri normalized = uri.buildUpon()
2344 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2345 Log.w(TAG, "Normalized " + uri + " to " + normalized
2346 + " to avoid possible security issues");
2347 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002348 } else {
2349 return uri;
2350 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002351 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002352
2353 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002354 private Uri maybeGetUriWithoutUserId(Uri uri) {
2355 if (mSingleUser) {
2356 return uri;
2357 }
2358 return getUriWithoutUserId(uri);
2359 }
2360
2361 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002362 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2363 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002364 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002365 if (end == -1) return defaultUserId;
2366 String userIdString = auth.substring(0, end);
2367 try {
2368 return Integer.parseInt(userIdString);
2369 } catch (NumberFormatException e) {
2370 Log.w(TAG, "Error parsing userId.", e);
2371 return UserHandle.USER_NULL;
2372 }
2373 }
2374
2375 /** @hide */
2376 public static int getUserIdFromAuthority(String auth) {
2377 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2378 }
2379
2380 /** @hide */
2381 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2382 if (uri == null) return defaultUserId;
2383 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2384 }
2385
2386 /** @hide */
2387 public static int getUserIdFromUri(Uri uri) {
2388 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2389 }
2390
2391 /**
2392 * Removes userId part from authority string. Expects format:
2393 * userId@some.authority
2394 * If there is no userId in the authority, it symply returns the argument
2395 * @hide
2396 */
2397 public static String getAuthorityWithoutUserId(String auth) {
2398 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002399 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002400 return auth.substring(end+1);
2401 }
2402
2403 /** @hide */
2404 public static Uri getUriWithoutUserId(Uri uri) {
2405 if (uri == null) return null;
2406 Uri.Builder builder = uri.buildUpon();
2407 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2408 return builder.build();
2409 }
2410
2411 /** @hide */
2412 public static boolean uriHasUserId(Uri uri) {
2413 if (uri == null) return false;
2414 return !TextUtils.isEmpty(uri.getUserInfo());
2415 }
2416
2417 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002418 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002419 public static Uri maybeAddUserId(Uri uri, int userId) {
2420 if (uri == null) return null;
2421 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002422 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002423 if (!uriHasUserId(uri)) {
2424 //We don't add the user Id if there's already one
2425 Uri.Builder builder = uri.buildUpon();
2426 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2427 return builder.build();
2428 }
2429 }
2430 return uri;
2431 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002432}