blob: 2240823ebe923e32722d70053390e7e1dffe0f95 [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,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700302 ContentValues initialValues, Bundle extras) {
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 Sharkeye9fe1522019-11-15 12:45:15 -0700320 return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700321 } 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
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700406 public int delete(String callingPkg, @Nullable String featureId, Uri uri, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600407 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100408 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700409 if (enforceWritePermission(callingPkg, featureId, uri, null)
410 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800411 return 0;
412 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600413 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700414 final Pair<String, String> original = setCallingPackage(
415 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700416 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700417 return mInterface.delete(uri, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700418 } catch (RemoteException e) {
419 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700420 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700421 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600422 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 }
425
Jeff Brown75ea64f2012-01-25 19:37:13 -0800426 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700427 public int update(String callingPkg, @Nullable String featureId, Uri uri,
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700428 ContentValues values, Bundle extras) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600429 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100430 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700431 if (enforceWritePermission(callingPkg, featureId, uri, null)
432 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800433 return 0;
434 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600435 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700436 final Pair<String, String> original = setCallingPackage(
437 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700438 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700439 return mInterface.update(uri, values, extras);
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700440 } catch (RemoteException e) {
441 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700442 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700443 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600444 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 }
447
Jeff Brown75ea64f2012-01-25 19:37:13 -0800448 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700449 public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId,
450 Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
451 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600452 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100453 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700454 enforceFilePermission(callingPkg, featureId, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600455 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700456 final Pair<String, String> original = setCallingPackage(
457 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700458 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700459 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700460 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700461 } catch (RemoteException e) {
462 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700463 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700464 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600465 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 }
468
Jeff Brown75ea64f2012-01-25 19:37:13 -0800469 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700470 public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
471 Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600473 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100474 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700475 enforceFilePermission(callingPkg, featureId, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600476 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700477 final Pair<String, String> original = setCallingPackage(
478 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700479 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700480 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700481 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700482 } catch (RemoteException e) {
483 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700484 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700485 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600486 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 }
489
Jeff Brown75ea64f2012-01-25 19:37:13 -0800490 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700491 public Bundle call(String callingPkg, @Nullable String featureId, String authority,
492 String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700493 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600494 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600495 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700496 final Pair<String, String> original = setCallingPackage(
497 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700498 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700499 return mInterface.call(authority, method, arg, extras);
500 } catch (RemoteException e) {
501 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700502 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700503 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600504 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700505 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800506 }
507
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700508 @Override
509 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700510 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600511 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100512 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600513 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
514 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700515 return mInterface.getStreamTypes(uri, mimeTypeFilter);
516 } catch (RemoteException e) {
517 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600518 } finally {
519 Trace.traceEnd(TRACE_TAG_DATABASE);
520 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700521 }
522
523 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700524 public AssetFileDescriptor openTypedAssetFile(String callingPkg,
525 @Nullable String featureId, Uri uri, String mimeType, Bundle opts,
526 ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600527 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600528 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100529 uri = maybeGetUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700530 enforceFilePermission(callingPkg, featureId, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600531 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700532 final Pair<String, String> original = setCallingPackage(
533 new Pair<>(callingPkg, featureId));
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700534 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700535 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700536 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700537 } catch (RemoteException e) {
538 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700539 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700540 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600541 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700542 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700543 }
544
Jeff Brown75ea64f2012-01-25 19:37:13 -0800545 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700546 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800547 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800548 }
549
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700550 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700551 public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600552 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100553 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100554 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700555 if (enforceReadPermission(callingPkg, featureId, uri, null)
556 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700557 return null;
558 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600559 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700560 final Pair<String, String> original = setCallingPackage(
561 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700562 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700563 return maybeAddUserId(mInterface.canonicalize(uri), userId);
564 } catch (RemoteException e) {
565 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700566 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700567 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600568 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700569 }
570 }
571
572 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700573 public Uri uncanonicalize(String callingPkg, String featureId, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600574 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100575 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100576 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700577 if (enforceReadPermission(callingPkg, featureId, uri, null)
578 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700579 return null;
580 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600581 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700582 final Pair<String, String> original = setCallingPackage(
583 new Pair<>(callingPkg, featureId));
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700584 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700585 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
586 } catch (RemoteException e) {
587 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700588 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700589 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600590 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700591 }
592 }
593
Ben Lin1cf454f2016-11-10 13:50:54 -0800594 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700595 public boolean refresh(String callingPkg, String featureId, Uri uri, Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800596 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600597 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800598 uri = getUriWithoutUserId(uri);
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700599 if (enforceReadPermission(callingPkg, featureId, uri, null)
600 != AppOpsManager.MODE_ALLOWED) {
Ben Lin1cf454f2016-11-10 13:50:54 -0800601 return false;
602 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600603 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700604 final Pair<String, String> original = setCallingPackage(
605 new Pair<>(callingPkg, featureId));
Ben Lin1cf454f2016-11-10 13:50:54 -0800606 try {
Jeff Sharkeye9fe1522019-11-15 12:45:15 -0700607 return mInterface.refresh(uri, extras,
Ben Lin1cf454f2016-11-10 13:50:54 -0800608 CancellationSignal.fromTransport(cancellationSignal));
609 } finally {
610 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600611 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800612 }
613 }
614
Jeff Sharkey9edef252019-05-20 14:00:17 -0600615 @Override
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700616 public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri,
617 int uid, int modeFlags) {
Jeff Sharkey9edef252019-05-20 14:00:17 -0600618 uri = validateIncomingUri(uri);
619 uri = maybeGetUriWithoutUserId(uri);
620 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700621 final Pair<String, String> original = setCallingPackage(
622 new Pair<>(callingPkg, featureId));
Jeff Sharkey9edef252019-05-20 14:00:17 -0600623 try {
624 return mInterface.checkUriPermission(uri, uid, modeFlags);
625 } catch (RemoteException e) {
626 throw e.rethrowAsRuntimeException();
627 } finally {
628 setCallingPackage(original);
629 Trace.traceEnd(TRACE_TAG_DATABASE);
630 }
631 }
632
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700633 private void enforceFilePermission(String callingPkg, @Nullable String featureId, Uri uri,
634 String mode, IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800635 if (mode != null && mode.indexOf('w') != -1) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700636 if (enforceWritePermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800637 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800638 throw new FileNotFoundException("App op not allowed");
639 }
640 } else {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700641 if (enforceReadPermission(callingPkg, featureId, uri, callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800642 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800643 throw new FileNotFoundException("App op not allowed");
644 }
645 }
646 }
647
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700648 private int enforceReadPermission(String callingPkg, @Nullable String featureId, Uri uri,
649 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800650 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700651 final int mode = enforceReadPermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700652 if (mode != MODE_ALLOWED) {
653 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800654 }
Svet Ganov99b60432015-06-27 13:15:22 -0700655
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700656 return noteProxyOp(callingPkg, featureId, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800657 }
658
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700659 private int enforceWritePermission(String callingPkg, String featureId, Uri uri,
660 IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800661 throws SecurityException {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700662 final int mode = enforceWritePermissionInner(uri, callingPkg, featureId, callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700663 if (mode != MODE_ALLOWED) {
664 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800665 }
Svet Ganov99b60432015-06-27 13:15:22 -0700666
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700667 return noteProxyOp(callingPkg, featureId, mWriteOp);
Eugene Susla93519852018-06-13 16:44:31 -0700668 }
669
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700670 private int noteProxyOp(String callingPkg, String featureId, int op) {
Eugene Susla93519852018-06-13 16:44:31 -0700671 if (op != AppOpsManager.OP_NONE) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700672 int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
673 featureId, null);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700674 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700675 }
676
Dianne Hackborn35654b62013-01-14 17:38:02 -0800677 return AppOpsManager.MODE_ALLOWED;
678 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700679 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800680
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100681 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700682 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
683 return true;
684 }
685 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
686 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100687 == PERMISSION_GRANTED;
688 }
689
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700690 /**
691 * Verify that calling app holds both the given permission and any app-op
692 * associated with that permission.
693 */
694 private int checkPermissionAndAppOp(String permission, String callingPkg,
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700695 @Nullable String featureId, IBinder callerToken) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700696 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
697 callerToken) != PERMISSION_GRANTED) {
698 return MODE_ERRORED;
699 }
700
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700701 return mTransport.noteProxyOp(callingPkg, featureId,
702 AppOpsManager.permissionToOpCode(permission));
Eugene Susla93519852018-06-13 16:44:31 -0700703 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700704
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700705 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700706 protected int enforceReadPermissionInner(Uri uri, String callingPkg,
707 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700708 final Context context = getContext();
709 final int pid = Binder.getCallingPid();
710 final int uid = Binder.getCallingUid();
711 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700712 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700713
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700714 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700715 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700716 }
717
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100718 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700719 final String componentPerm = getReadPermission();
720 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700721 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
722 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700723 if (mode == MODE_ALLOWED) {
724 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700725 } else {
726 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700727 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700728 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700729 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700730
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700731 // track if unprotected read is allowed; any denied
732 // <path-permission> below removes this ability
733 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700734
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700735 final PathPermission[] pps = getPathPermissions();
736 if (pps != null) {
737 final String path = uri.getPath();
738 for (PathPermission pp : pps) {
739 final String pathPerm = pp.getReadPermission();
740 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700741 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
742 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700743 if (mode == MODE_ALLOWED) {
744 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700745 } else {
746 // any denied <path-permission> means we lose
747 // default <provider> access.
748 allowDefaultRead = false;
749 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700750 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700751 }
752 }
753 }
754 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700755
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700756 // if we passed <path-permission> checks above, and no default
757 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700758 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700760
761 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800762 final int callingUserId = UserHandle.getUserId(uid);
763 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
764 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800765 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
766 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700767 return MODE_ALLOWED;
768 }
769
770 // If the worst denial we found above was ignored, then pass that
771 // ignored through; otherwise we assume it should be a real error below.
772 if (strongestMode == MODE_IGNORED) {
773 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700774 }
775
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600776 final String suffix;
777 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
778 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
779 } else if (mExported) {
780 suffix = " requires " + missingPerm + ", or grantUriPermission()";
781 } else {
782 suffix = " requires the provider be exported, or grantUriPermission()";
783 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700784 throw new SecurityException("Permission Denial: reading "
785 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600786 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700787 }
788
789 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700790 protected int enforceWritePermissionInner(Uri uri, String callingPkg,
791 @Nullable String featureId, IBinder callerToken) throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700792 final Context context = getContext();
793 final int pid = Binder.getCallingPid();
794 final int uid = Binder.getCallingUid();
795 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700796 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700797
798 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700799 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700800 }
801
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100802 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700803 final String componentPerm = getWritePermission();
804 if (componentPerm != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700805 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
806 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700807 if (mode == MODE_ALLOWED) {
808 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700809 } else {
810 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700811 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700812 }
813 }
814
815 // track if unprotected write is allowed; any denied
816 // <path-permission> below removes this ability
817 boolean allowDefaultWrite = (componentPerm == null);
818
819 final PathPermission[] pps = getPathPermissions();
820 if (pps != null) {
821 final String path = uri.getPath();
822 for (PathPermission pp : pps) {
823 final String pathPerm = pp.getWritePermission();
824 if (pathPerm != null && pp.match(path)) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700825 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
826 callerToken);
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700827 if (mode == MODE_ALLOWED) {
828 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700829 } else {
830 // any denied <path-permission> means we lose
831 // default <provider> access.
832 allowDefaultWrite = false;
833 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700834 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700835 }
836 }
837 }
838 }
839
840 // if we passed <path-permission> checks above, and no default
841 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700842 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700843 }
844
845 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800846 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
847 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700848 return MODE_ALLOWED;
849 }
850
851 // If the worst denial we found above was ignored, then pass that
852 // ignored through; otherwise we assume it should be a real error below.
853 if (strongestMode == MODE_IGNORED) {
854 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700855 }
856
857 final String failReason = mExported
858 ? " requires " + missingPerm + ", or grantUriPermission()"
859 : " requires the provider be exported, or grantUriPermission()";
860 throw new SecurityException("Permission Denial: writing "
861 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
862 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700866 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800867 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 * constructor.
869 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700870 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 return mContext;
872 }
873
874 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700875 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
876 * after {@link #onCreate}. When called before context was created, an IllegalStateException
877 * will be thrown.
878 * <p>
879 * Note A provider must be declared in the manifest and created automatically by the system,
880 * and context is only available after {@link #onCreate} is called.
881 */
882 @NonNull
883 public final Context requireContext() {
884 final Context ctx = getContext();
885 if (ctx == null) {
886 throw new IllegalStateException("Cannot find context from the provider.");
887 }
888 return ctx;
889 }
890
891 /**
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700892 * Set the calling package/feature, returning the current value (or {@code null})
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700893 * which can be used later to restore the previous state.
894 */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700895 private Pair<String, String> setCallingPackage(Pair<String, String> callingPackage) {
896 final Pair<String, String> original = mCallingPackage.get();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700897 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600898 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700899 return original;
900 }
901
902 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700903 * Return the package name of the caller that initiated the request being
904 * processed on the current thread. The returned package will have been
905 * verified to belong to the calling UID. Returns {@code null} if not
906 * currently processing a request.
907 * <p>
908 * This will always return {@code null} when processing
909 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
910 *
911 * @see Binder#getCallingUid()
912 * @see Context#grantUriPermission(String, Uri, int)
913 * @throws SecurityException if the calling package doesn't belong to the
914 * calling UID.
915 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700916 public final @Nullable String getCallingPackage() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700917 final Pair<String, String> pkg = mCallingPackage.get();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700918 if (pkg != null) {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700919 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg.first);
920 return pkg.first;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700921 }
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700922
923 return null;
924 }
925
926 /**
927 * Return the feature in the package of the caller that initiated the request being
928 * processed on the current thread. Returns {@code null} if not currently processing
929 * a request of the request is for the default feature.
930 * <p>
931 * This will always return {@code null} when processing
932 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
933 *
934 * @see #getCallingPackage
935 */
936 public final @Nullable String getCallingFeatureId() {
937 final Pair<String, String> pkg = mCallingPackage.get();
938 if (pkg != null) {
939 return pkg.second;
940 }
941
942 return null;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700943 }
944
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600945 /** {@hide} */
946 public final @Nullable String getCallingPackageUnchecked() {
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700947 final Pair<String, String> pkg = mCallingPackage.get();
948 if (pkg != null) {
949 return pkg.first;
950 }
951
952 return null;
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600953 }
954
955 /** {@hide} */
956 public void onCallingPackageChanged() {
957 }
958
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700959 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600960 * Opaque token representing the identity of an incoming IPC.
961 */
962 public final class CallingIdentity {
963 /** {@hide} */
964 public final long binderToken;
965 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700966 public final Pair<String, String> callingPackage;
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600967
968 /** {@hide} */
Philip P. Moltmann128b7032019-09-27 08:44:12 -0700969 public CallingIdentity(long binderToken, Pair<String, String> callingPackage) {
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600970 this.binderToken = binderToken;
971 this.callingPackage = callingPackage;
972 }
973 }
974
975 /**
976 * Reset the identity of the incoming IPC on the current thread.
977 * <p>
978 * Internally this calls {@link Binder#clearCallingIdentity()} and also
979 * clears any value stored in {@link #getCallingPackage()}.
980 *
981 * @return Returns an opaque token that can be used to restore the original
982 * calling identity by passing it to
983 * {@link #restoreCallingIdentity}.
984 */
985 public final @NonNull CallingIdentity clearCallingIdentity() {
986 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
987 }
988
989 /**
990 * Restore the identity of the incoming IPC on the current thread back to a
991 * previously identity that was returned by {@link #clearCallingIdentity}.
992 * <p>
993 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
994 * also restores any value stored in {@link #getCallingPackage()}.
995 */
996 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
997 Binder.restoreCallingIdentity(identity.binderToken);
998 mCallingPackage.set(identity.callingPackage);
999 }
1000
1001 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001002 * Change the authorities of the ContentProvider.
1003 * This is normally set for you from its manifest information when the provider is first
1004 * created.
1005 * @hide
1006 * @param authorities the semi-colon separated authorities of the ContentProvider.
1007 */
1008 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001009 if (authorities != null) {
1010 if (authorities.indexOf(';') == -1) {
1011 mAuthority = authorities;
1012 mAuthorities = null;
1013 } else {
1014 mAuthority = null;
1015 mAuthorities = authorities.split(";");
1016 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001017 }
1018 }
1019
1020 /** @hide */
1021 protected final boolean matchesOurAuthorities(String authority) {
1022 if (mAuthority != null) {
1023 return mAuthority.equals(authority);
1024 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +01001025 if (mAuthorities != null) {
1026 int length = mAuthorities.length;
1027 for (int i = 0; i < length; i++) {
1028 if (mAuthorities[i].equals(authority)) return true;
1029 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001030 }
1031 return false;
1032 }
1033
1034
1035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 * Change the permission required to read data from the content
1037 * provider. This is normally set for you from its manifest information
1038 * when the provider is first created.
1039 *
1040 * @param permission Name of the permission required for read-only access.
1041 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001042 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 mReadPermission = permission;
1044 }
1045
1046 /**
1047 * Return the name of the permission required for read-only access to
1048 * this content provider. This method can be called from multiple
1049 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001050 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1051 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001053 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 return mReadPermission;
1055 }
1056
1057 /**
1058 * Change the permission required to read and write data in the content
1059 * provider. This is normally set for you from its manifest information
1060 * when the provider is first created.
1061 *
1062 * @param permission Name of the permission required for read/write access.
1063 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001064 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 mWritePermission = permission;
1066 }
1067
1068 /**
1069 * Return the name of the permission required for read/write access to
1070 * this content provider. This method can be called from multiple
1071 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001072 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1073 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001075 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return mWritePermission;
1077 }
1078
1079 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001080 * Change the path-based permission required to read and/or write data in
1081 * the content provider. This is normally set for you from its manifest
1082 * information when the provider is first created.
1083 *
1084 * @param permissions Array of path permission descriptions.
1085 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001086 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001087 mPathPermissions = permissions;
1088 }
1089
1090 /**
1091 * Return the path-based permissions required for read and/or write access to
1092 * this content provider. This method can be called from multiple
1093 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001094 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1095 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001096 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001097 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001098 return mPathPermissions;
1099 }
1100
Dianne Hackborn35654b62013-01-14 17:38:02 -08001101 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001102 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001103 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001104 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001105 mTransport.mReadOp = readOp;
1106 mTransport.mWriteOp = writeOp;
1107 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001108 }
1109
Dianne Hackborn961321f2013-02-05 17:22:41 -08001110 /** @hide */
1111 public AppOpsManager getAppOpsManager() {
1112 return mTransport.mAppOpsManager;
1113 }
1114
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001115 /** @hide */
1116 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001117 if (mTransport == null) {
1118 return;
1119 }
1120 if (enabled) {
1121 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1122 } else {
1123 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001124 }
1125 }
1126
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001127 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001128 * Implement this to initialize your content provider on startup.
1129 * This method is called for all registered content providers on the
1130 * application main thread at application launch time. It must not perform
1131 * lengthy operations, or application startup will be delayed.
1132 *
1133 * <p>You should defer nontrivial initialization (such as opening,
1134 * upgrading, and scanning databases) until the content provider is used
1135 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1136 * keeps application startup fast, avoids unnecessary work if the provider
1137 * turns out not to be needed, and stops database errors (such as a full
1138 * disk) from halting application launch.
1139 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001140 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001141 * is a helpful utility class that makes it easy to manage databases,
1142 * and will automatically defer opening until first use. If you do use
1143 * SQLiteOpenHelper, make sure to avoid calling
1144 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1145 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1146 * from this method. (Instead, override
1147 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1148 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 *
1150 * @return true if the provider was successfully loaded, false otherwise
1151 */
1152 public abstract boolean onCreate();
1153
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001154 /**
1155 * {@inheritDoc}
1156 * This method is always called on the application main thread, and must
1157 * not perform lengthy operations.
1158 *
1159 * <p>The default content provider implementation does nothing.
1160 * Override this method to take appropriate action.
1161 * (Content providers do not usually care about things like screen
1162 * orientation, but may want to know about locale changes.)
1163 */
Steve McKayea93fe72016-12-02 11:35:35 -08001164 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 public void onConfigurationChanged(Configuration newConfig) {
1166 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001167
1168 /**
1169 * {@inheritDoc}
1170 * This method is always called on the application main thread, and must
1171 * not perform lengthy operations.
1172 *
1173 * <p>The default content provider implementation does nothing.
1174 * Subclasses may override this method to take appropriate action.
1175 */
Steve McKayea93fe72016-12-02 11:35:35 -08001176 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 public void onLowMemory() {
1178 }
1179
Steve McKayea93fe72016-12-02 11:35:35 -08001180 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001181 public void onTrimMemory(int level) {
1182 }
1183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001185 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001186 *
1187 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1188 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1189 * implementation of this method.
1190 *
1191 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001192 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1193 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 * <p>
1195 * Example client call:<p>
1196 * <pre>// Request a specific record.
1197 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001198 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 projection, // Which columns to return.
1200 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001201 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 People.NAME + " ASC"); // Sort order.</pre>
1203 * Example implementation:<p>
1204 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1205 // proper SQL syntax for us.
1206 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1207
1208 // Set the table we're querying.
1209 qBuilder.setTables(DATABASE_TABLE_NAME);
1210
1211 // If the query ends in a specific record number, we're
1212 // being asked for a specific record, so set the
1213 // WHERE clause in our query.
1214 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1215 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1216 }
1217
1218 // Make the query.
1219 Cursor c = qBuilder.query(mDb,
1220 projection,
1221 selection,
1222 selectionArgs,
1223 groupBy,
1224 having,
1225 sortOrder);
1226 c.setNotificationUri(getContext().getContentResolver(), uri);
1227 return c;</pre>
1228 *
1229 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001230 * if the client is requesting a specific record, the URI will end in a record number
1231 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1232 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001234 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001236 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001237 * @param selectionArgs You may include ?s in selection, which will be replaced by
1238 * the values from selectionArgs, in order that they appear in the selection.
1239 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001241 * If {@code null} then the provider is free to define the sort order.
1242 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001244 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1245 @Nullable String selection, @Nullable String[] selectionArgs,
1246 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247
Fred Quintana5bba6322009-10-05 14:21:12 -07001248 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001249 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001250 *
1251 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1252 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1253 *
1254 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001255 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1256 * and Threads</a>.
1257 * <p>
1258 * Example client call:<p>
1259 * <pre>// Request a specific record.
1260 * Cursor managedCursor = managedQuery(
1261 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1262 projection, // Which columns to return.
1263 null, // WHERE clause.
1264 null, // WHERE clause value substitution
1265 People.NAME + " ASC"); // Sort order.</pre>
1266 * Example implementation:<p>
1267 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1268 // proper SQL syntax for us.
1269 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1270
1271 // Set the table we're querying.
1272 qBuilder.setTables(DATABASE_TABLE_NAME);
1273
1274 // If the query ends in a specific record number, we're
1275 // being asked for a specific record, so set the
1276 // WHERE clause in our query.
1277 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1278 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1279 }
1280
1281 // Make the query.
1282 Cursor c = qBuilder.query(mDb,
1283 projection,
1284 selection,
1285 selectionArgs,
1286 groupBy,
1287 having,
1288 sortOrder);
1289 c.setNotificationUri(getContext().getContentResolver(), uri);
1290 return c;</pre>
1291 * <p>
1292 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001293 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1294 * signal to ensure correct operation on older versions of the Android Framework in
1295 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001296 *
1297 * @param uri The URI to query. This will be the full URI sent by the client;
1298 * if the client is requesting a specific record, the URI will end in a record number
1299 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1300 * that _id value.
1301 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001302 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001303 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001304 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001305 * @param selectionArgs You may include ?s in selection, which will be replaced by
1306 * the values from selectionArgs, in order that they appear in the selection.
1307 * The values will be bound as Strings.
1308 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001309 * If {@code null} then the provider is free to define the sort order.
1310 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001311 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001312 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001313 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001314 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001315 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1316 @Nullable String selection, @Nullable String[] selectionArgs,
1317 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001318 return query(uri, projection, selection, selectionArgs, sortOrder);
1319 }
1320
1321 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001322 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1323 * Arguments may include traditional SQL style query arguments. When present these
1324 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001325 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001326 *
1327 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001328 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1329 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1330 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001331 *
Steve McKay76b27702017-04-24 12:07:53 -07001332 * <p>This method can be called from multiple threads, as described in
1333 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1334 * and Threads</a>.
1335 *
1336 * <p>
1337 * Example client call:<p>
1338 * <pre>// Request 20 records starting at row index 30.
1339 Bundle queryArgs = new Bundle();
1340 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1341 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1342
1343 Cursor cursor = getContentResolver().query(
1344 contentUri, // Content Uri is specific to individual content providers.
1345 projection, // String[] describing which columns to return.
1346 queryArgs, // Query arguments.
1347 null); // Cancellation signal.</pre>
1348 *
1349 * Example implementation:<p>
1350 * <pre>
1351
1352 int recordsetSize = 0x1000; // Actual value is implementation specific.
1353 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1354
1355 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1356 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1357
1358 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1359
1360 // Calculate the number of items to include in the cursor.
1361 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1362
1363 // Build the paged result set....
1364 for (int i = offset; i < offset + numItems; i++) {
1365 // populate row from your data.
1366 }
1367
1368 Bundle extras = new Bundle();
1369 c.setExtras(extras);
1370
1371 // Any QUERY_ARG_* key may be included if honored.
1372 // In an actual implementation, include only keys that are both present in queryArgs
1373 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1374 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1375 // then QUERY_ARG_OFFSET should be omitted.
1376 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1377 ContentResolver.QUERY_ARG_OFFSET,
1378 ContentResolver.QUERY_ARG_LIMIT
1379 });
1380
1381 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1382
1383 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1384
1385 return cursor;</pre>
1386 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001387 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1388 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001389 *
1390 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001391 * @param projection The list of columns to put into the cursor.
1392 * If {@code null} provide a default set of columns.
1393 * @param queryArgs A Bundle containing all additional information necessary for the query.
1394 * Values in the Bundle may include SQL style arguments.
1395 * @param cancellationSignal A signal to cancel the operation in progress,
1396 * or {@code null}.
1397 * @return a Cursor or {@code null}.
1398 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001399 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001400 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1401 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1402 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001403
Steve McKayd7ece9f2017-01-12 16:59:59 -08001404 // if client doesn't supply an SQL sort order argument, attempt to build one from
1405 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001406 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001407 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1408 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1409 }
1410
Steve McKayea93fe72016-12-02 11:35:35 -08001411 return query(
1412 uri,
1413 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001414 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1415 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1416 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001417 cancellationSignal);
1418 }
1419
1420 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001421 * Implement this to handle requests for the MIME type of the data at the
1422 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 * <code>vnd.android.cursor.item</code> for a single record,
1424 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001425 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001426 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1427 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001429 * <p>Note that there are no permissions needed for an application to
1430 * access this information; if your content provider requires read and/or
1431 * write permissions, or is not exported, all applications can still call
1432 * this method regardless of their access permissions. This allows them
1433 * to retrieve the MIME type for a URI when dispatching intents.
1434 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001436 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001438 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001439 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440
1441 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001442 * Implement this to support canonicalization of URIs that refer to your
1443 * content provider. A canonical URI is one that can be transported across
1444 * devices, backup/restore, and other contexts, and still be able to refer
1445 * to the same data item. Typically this is implemented by adding query
1446 * params to the URI allowing the content provider to verify that an incoming
1447 * canonical URI references the same data as it was originally intended for and,
1448 * if it doesn't, to find that data (if it exists) in the current environment.
1449 *
1450 * <p>For example, if the content provider holds people and a normal URI in it
1451 * is created with a row index into that people database, the cananical representation
1452 * may have an additional query param at the end which specifies the name of the
1453 * person it is intended for. Later calls into the provider with that URI will look
1454 * up the row of that URI's base index and, if it doesn't match or its entry's
1455 * name doesn't match the name in the query param, perform a query on its database
1456 * to find the correct row to operate on.</p>
1457 *
1458 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1459 * URIs (including this one) must perform this verification and recovery of any
1460 * canonical URIs they receive. In addition, you must also implement
1461 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1462 *
1463 * <p>The default implementation of this method returns null, indicating that
1464 * canonical URIs are not supported.</p>
1465 *
1466 * @param url The Uri to canonicalize.
1467 *
1468 * @return Return the canonical representation of <var>url</var>, or null if
1469 * canonicalization of that Uri is not supported.
1470 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001471 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001472 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001473 return null;
1474 }
1475
1476 /**
1477 * Remove canonicalization from canonical URIs previously returned by
1478 * {@link #canonicalize}. For example, if your implementation is to add
1479 * a query param to canonicalize a URI, this method can simply trip any
1480 * query params on the URI. The default implementation always returns the
1481 * same <var>url</var> that was passed in.
1482 *
1483 * @param url The Uri to remove any canonicalization from.
1484 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001485 * @return Return the non-canonical representation of <var>url</var>, return
1486 * the <var>url</var> as-is if there is nothing to do, or return null if
1487 * the data identified by the canonical representation can not be found in
1488 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001489 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001490 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001491 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001492 return url;
1493 }
1494
1495 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001496 * Implement this to support refresh of content identified by {@code uri}.
1497 * By default, this method returns false; providers who wish to implement
1498 * this should return true to signal the client that the provider has tried
1499 * refreshing with its own implementation.
Ben Lin1cf454f2016-11-10 13:50:54 -08001500 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001501 * This allows clients to request an explicit refresh of content identified
1502 * by {@code uri}.
Ben Lin1cf454f2016-11-10 13:50:54 -08001503 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001504 * Client code should only invoke this method when there is a strong
1505 * indication (such as a user initiated pull to refresh gesture) that the
1506 * content is stale.
Ben Lin1cf454f2016-11-10 13:50:54 -08001507 * <p>
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001508 * Remember to send
1509 * {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
Ben Lin1cf454f2016-11-10 13:50:54 -08001510 * notifications when content changes.
1511 *
1512 * @param uri The Uri identifying the data to refresh.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001513 * @param extras Additional options from the client. The definitions of
1514 * these are specific to the content provider being called.
1515 * @param cancellationSignal A signal to cancel the operation in progress,
1516 * or {@code null} if none. For example, if you called refresh on
1517 * a particular uri, you should call
1518 * {@link CancellationSignal#throwIfCanceled()} to check whether
1519 * the client has canceled the refresh request.
Ben Lin1cf454f2016-11-10 13:50:54 -08001520 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001521 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001522 @Override
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001523 public boolean refresh(Uri uri, @Nullable Bundle extras,
Ben Lin1cf454f2016-11-10 13:50:54 -08001524 @Nullable CancellationSignal cancellationSignal) {
1525 return false;
1526 }
1527
Jeff Sharkey9edef252019-05-20 14:00:17 -06001528 /** {@hide} */
1529 @Override
1530 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1531 return PackageManager.PERMISSION_DENIED;
1532 }
1533
Ben Lin1cf454f2016-11-10 13:50:54 -08001534 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001535 * @hide
1536 * Implementation when a caller has performed an insert on the content
1537 * provider, but that call has been rejected for the operation given
1538 * to {@link #setAppOps(int, int)}. The default implementation simply
1539 * returns a dummy URI that is the base URI with a 0 path element
1540 * appended.
1541 */
1542 public Uri rejectInsert(Uri uri, ContentValues values) {
1543 // If not allowed, we need to return some reasonable URI. Maybe the
1544 // content provider should be responsible for this, but for now we
1545 // will just return the base URI with a dummy '0' tagged on to it.
1546 // You shouldn't be able to read if you can't write, anyway, so it
1547 // shouldn't matter much what is returned.
1548 return uri.buildUpon().appendPath("0").build();
1549 }
1550
1551 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001552 * Implement this to handle requests to insert a new row. As a courtesy,
1553 * call
1554 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1555 * notifyChange()} after inserting. This method can be called from multiple
1556 * threads, as described in <a href="
1557 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001558 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001559 *
Varun Shah8c80a3f2019-10-16 12:21:19 -07001560 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 * @param values A set of column_name/value pairs to add to the database.
1562 * @return The URI for the newly inserted item.
1563 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001564 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
1566 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001567 * Implement this to handle requests to insert a new row. As a courtesy,
1568 * call
1569 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1570 * notifyChange()} after inserting. This method can be called from multiple
1571 * threads, as described in <a href="
1572 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1573 * and Threads</a>.
1574 *
1575 * @param uri The content:// URI of the insertion request.
1576 * @param values A set of column_name/value pairs to add to the database.
1577 * @param extras A Bundle containing all additional information necessary
1578 * for the insert.
1579 * @return The URI for the newly inserted item.
1580 */
1581 @Override
1582 public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values,
1583 @Nullable Bundle extras) {
1584 return insert(uri, values);
1585 }
1586
1587 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001588 * Override this to handle requests to insert a set of new rows, or the
1589 * default implementation will iterate over the values and call
1590 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1592 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001593 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001594 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1595 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 *
1597 * @param uri The content:// URI of the insertion request.
1598 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001599 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 * @return The number of values that were inserted.
1601 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001602 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001603 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 int numValues = values.length;
1605 for (int i = 0; i < numValues; i++) {
1606 insert(uri, values[i]);
1607 }
1608 return numValues;
1609 }
1610
1611 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001612 * Implement this to handle requests to delete one or more rows. The
1613 * implementation should apply the selection clause when performing
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001614 * deletion, allowing the operation to affect multiple rows in a directory.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001615 * As a courtesy, call
1616 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1617 * notifyChange()} after deleting. This method can be called from multiple
1618 * threads, as described in <a href="
1619 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001620 * and Threads</a>.
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001621 * <p>
1622 * The implementation is responsible for parsing out a row ID at the end of
1623 * the URI, if a specific row is being deleted. That is, the client would
1624 * pass in <code>content://contacts/people/22</code> and the implementation
1625 * is responsible for parsing the record number (22) when creating a SQL
1626 * statement.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001628 * @param uri The full URI to query, including a row ID (if a specific
1629 * record is requested).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 * @param selection An optional restriction to apply to rows when deleting.
1631 * @return The number of rows affected.
1632 * @throws SQLException
1633 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001634 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1635 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636
1637 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001638 * Implement this to handle requests to delete one or more rows. The
1639 * implementation should apply the selection clause when performing
1640 * deletion, allowing the operation to affect multiple rows in a directory.
1641 * As a courtesy, call
1642 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1643 * notifyChange()} after deleting. This method can be called from multiple
1644 * threads, as described in <a href="
1645 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1646 * and Threads</a>.
1647 * <p>
1648 * The implementation is responsible for parsing out a row ID at the end of
1649 * the URI, if a specific row is being deleted. That is, the client would
1650 * pass in <code>content://contacts/people/22</code> and the implementation
1651 * is responsible for parsing the record number (22) when creating a SQL
1652 * statement.
1653 *
1654 * @param uri The full URI to query, including a row ID (if a specific
1655 * record is requested).
1656 * @param extras A Bundle containing all additional information necessary
1657 * for the delete. Values in the Bundle may include SQL style
1658 * arguments.
1659 * @return The number of rows affected.
1660 * @throws SQLException
1661 */
1662 @Override
1663 public int delete(@NonNull Uri uri, @Nullable Bundle extras) {
1664 extras = (extras != null) ? extras : Bundle.EMPTY;
1665 return delete(uri,
1666 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1667 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1668 }
1669
1670 /**
1671 * Implement this to handle requests to update one or more rows. The
1672 * implementation should update all rows matching the selection to set the
1673 * columns according to the provided values map. As a courtesy, call
1674 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1675 * notifyChange()} after updating. This method can be called from multiple
1676 * threads, as described in <a href="
1677 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
Scott Main7aee61f2011-02-08 11:25:01 -08001678 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 *
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001680 * @param uri The URI to query. This can potentially have a record ID if
1681 * this is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001682 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 * @param selection An optional filter to match rows to update.
1684 * @return the number of rows affected.
1685 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001686 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001687 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688
1689 /**
Jeff Sharkeye9fe1522019-11-15 12:45:15 -07001690 * Implement this to handle requests to update one or more rows. The
1691 * implementation should update all rows matching the selection to set the
1692 * columns according to the provided values map. As a courtesy, call
1693 * {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver)
1694 * notifyChange()} after updating. This method can be called from multiple
1695 * threads, as described in <a href="
1696 * {@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1697 * and Threads</a>.
1698 *
1699 * @param uri The URI to query. This can potentially have a record ID if
1700 * this is an update request for a specific record.
1701 * @param values A set of column_name/value pairs to update in the database.
1702 * @param extras A Bundle containing all additional information necessary
1703 * for the update. Values in the Bundle may include SQL style
1704 * arguments.
1705 * @return the number of rows affected.
1706 */
1707 @Override
1708 public int update(@NonNull Uri uri, @Nullable ContentValues values,
1709 @Nullable Bundle extras) {
1710 extras = (extras != null) ? extras : Bundle.EMPTY;
1711 return update(uri, values,
1712 extras.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1713 extras.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS));
1714 }
1715
1716 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001717 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001718 * The default implementation always throws {@link FileNotFoundException}.
1719 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001720 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1721 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001722 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001723 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1724 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001725 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 *
1727 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1728 * their responsibility to close it when done. That is, the implementation
1729 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001730 * <p>
1731 * If opened with the exclusive "r" or "w" modes, the returned
1732 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1733 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1734 * supports seeking.
1735 * <p>
1736 * If you need to detect when the returned ParcelFileDescriptor has been
1737 * closed, or if the remote process has crashed or encountered some other
1738 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1739 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1740 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1741 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001742 * <p>
1743 * If you need to return a large file that isn't backed by a real file on
1744 * disk, such as a file on a network share or cloud storage service,
1745 * consider using
1746 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1747 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001749 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1750 * to return the appropriate MIME type for the data returned here with
1751 * the same URI. This will allow intent resolution to automatically determine the data MIME
1752 * type and select the appropriate matching targets as part of its operation.</p>
1753 *
1754 * <p class="note">For better interoperability with other applications, it is recommended
1755 * that for any URIs that can be opened, you also support queries on them
1756 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1757 * You may also want to support other common columns if you have additional meta-data
1758 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1759 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1760 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 * @param uri The URI whose file is to be opened.
1762 * @param mode Access mode for the file. May be "r" for read-only access,
1763 * "rw" for read and write access, or "rwt" for read and write access
1764 * that truncates any existing file.
1765 *
1766 * @return Returns a new ParcelFileDescriptor which you can use to access
1767 * the file.
1768 *
1769 * @throws FileNotFoundException Throws FileNotFoundException if there is
1770 * no file associated with the given URI or the mode is invalid.
1771 * @throws SecurityException Throws SecurityException if the caller does
1772 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001773 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 * @see #openAssetFile(Uri, String)
1775 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001776 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001777 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001778 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001779 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 throws FileNotFoundException {
1781 throw new FileNotFoundException("No files supported by provider at "
1782 + uri);
1783 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001786 * Override this to handle requests to open a file blob.
1787 * The default implementation always throws {@link FileNotFoundException}.
1788 * This method can be called from multiple threads, as described in
1789 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1790 * and Threads</a>.
1791 *
1792 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1793 * to the caller. This way large data (such as images and documents) can be
1794 * returned without copying the content.
1795 *
1796 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1797 * their responsibility to close it when done. That is, the implementation
1798 * of this method should create a new ParcelFileDescriptor for each call.
1799 * <p>
1800 * If opened with the exclusive "r" or "w" modes, the returned
1801 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1802 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1803 * supports seeking.
1804 * <p>
1805 * If you need to detect when the returned ParcelFileDescriptor has been
1806 * closed, or if the remote process has crashed or encountered some other
1807 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1808 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1809 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1810 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1811 *
1812 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1813 * to return the appropriate MIME type for the data returned here with
1814 * the same URI. This will allow intent resolution to automatically determine the data MIME
1815 * type and select the appropriate matching targets as part of its operation.</p>
1816 *
1817 * <p class="note">For better interoperability with other applications, it is recommended
1818 * that for any URIs that can be opened, you also support queries on them
1819 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1820 * You may also want to support other common columns if you have additional meta-data
1821 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1822 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1823 *
1824 * @param uri The URI whose file is to be opened.
1825 * @param mode Access mode for the file. May be "r" for read-only access,
1826 * "w" for write-only access, "rw" for read and write access, or
1827 * "rwt" for read and write access that truncates any existing
1828 * file.
1829 * @param signal A signal to cancel the operation in progress, or
1830 * {@code null} if none. For example, if you are downloading a
1831 * file from the network to service a "rw" mode request, you
1832 * should periodically call
1833 * {@link CancellationSignal#throwIfCanceled()} to check whether
1834 * the client has canceled the request and abort the download.
1835 *
1836 * @return Returns a new ParcelFileDescriptor which you can use to access
1837 * the file.
1838 *
1839 * @throws FileNotFoundException Throws FileNotFoundException if there is
1840 * no file associated with the given URI or the mode is invalid.
1841 * @throws SecurityException Throws SecurityException if the caller does
1842 * not have permission to access the file.
1843 *
1844 * @see #openAssetFile(Uri, String)
1845 * @see #openFileHelper(Uri, String)
1846 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001847 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001848 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001849 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001850 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1851 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001852 return openFile(uri, mode);
1853 }
1854
1855 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 * This is like {@link #openFile}, but can be implemented by providers
1857 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001858 * inside of their .apk.
1859 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001860 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1861 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001862 *
1863 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001864 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001865 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1867 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1868 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001869 * <p>
1870 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1871 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001872 *
1873 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 * should create the AssetFileDescriptor with
1875 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001876 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001878 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1879 * to return the appropriate MIME type for the data returned here with
1880 * the same URI. This will allow intent resolution to automatically determine the data MIME
1881 * type and select the appropriate matching targets as part of its operation.</p>
1882 *
1883 * <p class="note">For better interoperability with other applications, it is recommended
1884 * that for any URIs that can be opened, you also support queries on them
1885 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1886 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 * @param uri The URI whose file is to be opened.
1888 * @param mode Access mode for the file. May be "r" for read-only access,
1889 * "w" for write-only access (erasing whatever data is currently in
1890 * the file), "wa" for write-only access to append to any existing data,
1891 * "rw" for read and write access on any existing data, and "rwt" for read
1892 * and write access that truncates any existing file.
1893 *
1894 * @return Returns a new AssetFileDescriptor which you can use to access
1895 * the file.
1896 *
1897 * @throws FileNotFoundException Throws FileNotFoundException if there is
1898 * no file associated with the given URI or the mode is invalid.
1899 * @throws SecurityException Throws SecurityException if the caller does
1900 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001901 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 * @see #openFile(Uri, String)
1903 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001904 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001906 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 throws FileNotFoundException {
1908 ParcelFileDescriptor fd = openFile(uri, mode);
1909 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1910 }
1911
1912 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001913 * This is like {@link #openFile}, but can be implemented by providers
1914 * that need to be able to return sub-sections of files, often assets
1915 * inside of their .apk.
1916 * This method can be called from multiple threads, as described in
1917 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1918 * and Threads</a>.
1919 *
1920 * <p>If you implement this, your clients must be able to deal with such
1921 * file slices, either directly with
1922 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1923 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1924 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1925 * methods.
1926 * <p>
1927 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1928 * streaming of data.
1929 *
1930 * <p class="note">If you are implementing this to return a full file, you
1931 * should create the AssetFileDescriptor with
1932 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1933 * applications that cannot handle sub-sections of files.</p>
1934 *
1935 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1936 * to return the appropriate MIME type for the data returned here with
1937 * the same URI. This will allow intent resolution to automatically determine the data MIME
1938 * type and select the appropriate matching targets as part of its operation.</p>
1939 *
1940 * <p class="note">For better interoperability with other applications, it is recommended
1941 * that for any URIs that can be opened, you also support queries on them
1942 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1943 *
1944 * @param uri The URI whose file is to be opened.
1945 * @param mode Access mode for the file. May be "r" for read-only access,
1946 * "w" for write-only access (erasing whatever data is currently in
1947 * the file), "wa" for write-only access to append to any existing data,
1948 * "rw" for read and write access on any existing data, and "rwt" for read
1949 * and write access that truncates any existing file.
1950 * @param signal A signal to cancel the operation in progress, or
1951 * {@code null} if none. For example, if you are downloading a
1952 * file from the network to service a "rw" mode request, you
1953 * should periodically call
1954 * {@link CancellationSignal#throwIfCanceled()} to check whether
1955 * the client has canceled the request and abort the download.
1956 *
1957 * @return Returns a new AssetFileDescriptor which you can use to access
1958 * the file.
1959 *
1960 * @throws FileNotFoundException Throws FileNotFoundException if there is
1961 * no file associated with the given URI or the mode is invalid.
1962 * @throws SecurityException Throws SecurityException if the caller does
1963 * not have permission to access the file.
1964 *
1965 * @see #openFile(Uri, String)
1966 * @see #openFileHelper(Uri, String)
1967 * @see #getType(android.net.Uri)
1968 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001969 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001970 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1971 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001972 return openAssetFile(uri, mode);
1973 }
1974
1975 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 * Convenience for subclasses that wish to implement {@link #openFile}
1977 * by looking up a column named "_data" at the given URI.
1978 *
1979 * @param uri The URI to be opened.
1980 * @param mode The file mode. May be "r" for read-only access,
1981 * "w" for write-only access (erasing whatever data is currently in
1982 * the file), "wa" for write-only access to append to any existing data,
1983 * "rw" for read and write access on any existing data, and "rwt" for read
1984 * and write access that truncates any existing file.
1985 *
1986 * @return Returns a new ParcelFileDescriptor that can be used by the
1987 * client to access the file.
1988 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001989 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1990 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1992 int count = (c != null) ? c.getCount() : 0;
1993 if (count != 1) {
1994 // If there is not exactly one result, throw an appropriate
1995 // exception.
1996 if (c != null) {
1997 c.close();
1998 }
1999 if (count == 0) {
2000 throw new FileNotFoundException("No entry for " + uri);
2001 }
2002 throw new FileNotFoundException("Multiple items at " + uri);
2003 }
2004
2005 c.moveToFirst();
2006 int i = c.getColumnIndex("_data");
2007 String path = (i >= 0 ? c.getString(i) : null);
2008 c.close();
2009 if (path == null) {
2010 throw new FileNotFoundException("Column _data not found.");
2011 }
2012
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07002013 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 return ParcelFileDescriptor.open(new File(path), modeBits);
2015 }
2016
2017 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002018 * Called by a client to determine the types of data streams that this
2019 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002020 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002021 * of a particular type, return that MIME type if it matches the given
2022 * mimeTypeFilter. If it can perform type conversions, return an array
2023 * of all supported MIME types that match mimeTypeFilter.
2024 *
2025 * @param uri The data in the content provider being queried.
2026 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002027 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002028 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002029 * given mimeTypeFilter. Otherwise returns an array of all available
2030 * concrete MIME types.
2031 *
2032 * @see #getType(Uri)
2033 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002034 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002035 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002036 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002037 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002038 return null;
2039 }
2040
2041 /**
2042 * Called by a client to open a read-only stream containing data of a
2043 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2044 * except the file can only be read-only and the content provider may
2045 * perform data conversions to generate data of the desired type.
2046 *
2047 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08002048 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002049 * {@link #openAssetFile(Uri, String)}.
2050 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002051 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002052 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002053 * <p>
2054 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2055 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002056 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08002057 * <p class="note">For better interoperability with other applications, it is recommended
2058 * that for any URIs that can be opened, you also support queries on them
2059 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2060 * You may also want to support other common columns if you have additional meta-data
2061 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2062 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2063 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002064 * @param uri The data in the content provider being queried.
2065 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002066 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002067 * requirements; in this case the content provider will pick its best
2068 * type matching the pattern.
2069 * @param opts Additional options from the client. The definitions of
2070 * these are specific to the content provider being called.
2071 *
2072 * @return Returns a new AssetFileDescriptor from which the client can
2073 * read data of the desired type.
2074 *
2075 * @throws FileNotFoundException Throws FileNotFoundException if there is
2076 * no file associated with the given URI or the mode is invalid.
2077 * @throws SecurityException Throws SecurityException if the caller does
2078 * not have permission to access the data.
2079 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2080 * content provider does not support the requested MIME type.
2081 *
2082 * @see #getStreamTypes(Uri, String)
2083 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002084 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002085 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002086 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2087 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002088 if ("*/*".equals(mimeTypeFilter)) {
2089 // If they can take anything, the untyped open call is good enough.
2090 return openAssetFile(uri, "r");
2091 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002092 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07002093 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07002094 // Use old untyped open call if this provider has a type for this
2095 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002096 return openAssetFile(uri, "r");
2097 }
2098 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
2099 }
2100
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002101
2102 /**
2103 * Called by a client to open a read-only stream containing data of a
2104 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
2105 * except the file can only be read-only and the content provider may
2106 * perform data conversions to generate data of the desired type.
2107 *
2108 * <p>The default implementation compares the given mimeType against the
2109 * result of {@link #getType(Uri)} and, if they match, simply calls
2110 * {@link #openAssetFile(Uri, String)}.
2111 *
2112 * <p>See {@link ClipData} for examples of the use and implementation
2113 * of this method.
2114 * <p>
2115 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
2116 * streaming of data.
2117 *
2118 * <p class="note">For better interoperability with other applications, it is recommended
2119 * that for any URIs that can be opened, you also support queries on them
2120 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
2121 * You may also want to support other common columns if you have additional meta-data
2122 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
2123 * in {@link android.provider.MediaStore.MediaColumns}.</p>
2124 *
2125 * @param uri The data in the content provider being queried.
2126 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05002127 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002128 * requirements; in this case the content provider will pick its best
2129 * type matching the pattern.
2130 * @param opts Additional options from the client. The definitions of
2131 * these are specific to the content provider being called.
2132 * @param signal A signal to cancel the operation in progress, or
2133 * {@code null} if none. For example, if you are downloading a
2134 * file from the network to service a "rw" mode request, you
2135 * should periodically call
2136 * {@link CancellationSignal#throwIfCanceled()} to check whether
2137 * the client has canceled the request and abort the download.
2138 *
2139 * @return Returns a new AssetFileDescriptor from which the client can
2140 * read data of the desired type.
2141 *
2142 * @throws FileNotFoundException Throws FileNotFoundException if there is
2143 * no file associated with the given URI or the mode is invalid.
2144 * @throws SecurityException Throws SecurityException if the caller does
2145 * not have permission to access the data.
2146 * @throws IllegalArgumentException Throws IllegalArgumentException if the
2147 * content provider does not support the requested MIME type.
2148 *
2149 * @see #getStreamTypes(Uri, String)
2150 * @see #openAssetFile(Uri, String)
2151 * @see ClipDescription#compareMimeTypes(String, String)
2152 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002153 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002154 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2155 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2156 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002157 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2158 }
2159
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002160 /**
2161 * Interface to write a stream of data to a pipe. Use with
2162 * {@link ContentProvider#openPipeHelper}.
2163 */
2164 public interface PipeDataWriter<T> {
2165 /**
2166 * Called from a background thread to stream data out to a pipe.
2167 * Note that the pipe is blocking, so this thread can block on
2168 * writes for an arbitrary amount of time if the client is slow
2169 * at reading.
2170 *
2171 * @param output The pipe where data should be written. This will be
2172 * closed for you upon returning from this function.
2173 * @param uri The URI whose data is to be written.
2174 * @param mimeType The desired type of data to be written.
2175 * @param opts Options supplied by caller.
2176 * @param args Your own custom arguments.
2177 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002178 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2179 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002180 }
2181
2182 /**
2183 * A helper function for implementing {@link #openTypedAssetFile}, for
2184 * creating a data pipe and background thread allowing you to stream
2185 * generated data back to the client. This function returns a new
2186 * ParcelFileDescriptor that should be returned to the caller (the caller
2187 * is responsible for closing it).
2188 *
2189 * @param uri The URI whose data is to be written.
2190 * @param mimeType The desired type of data to be written.
2191 * @param opts Options supplied by caller.
2192 * @param args Your own custom arguments.
2193 * @param func Interface implementing the function that will actually
2194 * stream the data.
2195 * @return Returns a new ParcelFileDescriptor holding the read side of
2196 * the pipe. This should be returned to the caller for reading; the caller
2197 * is responsible for closing it when done.
2198 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002199 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2200 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2201 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002202 try {
2203 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2204
2205 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2206 @Override
2207 protected Object doInBackground(Object... params) {
2208 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2209 try {
2210 fds[1].close();
2211 } catch (IOException e) {
2212 Log.w(TAG, "Failure closing pipe", e);
2213 }
2214 return null;
2215 }
2216 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002217 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002218
2219 return fds[0];
2220 } catch (IOException e) {
2221 throw new FileNotFoundException("failure making pipe");
2222 }
2223 }
2224
2225 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 * Returns true if this instance is a temporary content provider.
2227 * @return true if this instance is a temporary content provider
2228 */
2229 protected boolean isTemporary() {
2230 return false;
2231 }
2232
2233 /**
2234 * Returns the Binder object for this provider.
2235 *
2236 * @return the Binder object for this provider
2237 * @hide
2238 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002239 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 public IContentProvider getIContentProvider() {
2241 return mTransport;
2242 }
2243
2244 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002245 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2246 * when directly instantiating the provider for testing.
2247 * @hide
2248 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002249 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002250 public void attachInfoForTesting(Context context, ProviderInfo info) {
2251 attachInfo(context, info, true);
2252 }
2253
2254 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 * After being instantiated, this is called to tell the content provider
2256 * about itself.
2257 *
2258 * @param context The context this provider is running in
2259 * @param info Registered information about this content provider
2260 */
2261 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002262 attachInfo(context, info, false);
2263 }
2264
2265 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002266 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002267 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 /*
2270 * Only allow it to be set once, so after the content service gives
2271 * this to us clients can't change it.
2272 */
2273 if (mContext == null) {
2274 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002275 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002276 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2277 Context.APP_OPS_SERVICE);
2278 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002279 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 if (info != null) {
2281 setReadPermission(info.readPermission);
2282 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002283 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002284 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002285 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002286 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002288 if (Build.IS_DEBUGGABLE) {
2289 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2290 Log.VERBOSE));
2291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 ContentProvider.this.onCreate();
2293 }
2294 }
Fred Quintanace31b232009-05-04 16:01:15 -07002295
2296 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002297 * Override this to handle requests to perform a batch of operations, or the
2298 * default implementation will iterate over the operations and call
2299 * {@link ContentProviderOperation#apply} on each of them.
2300 * If all calls to {@link ContentProviderOperation#apply} succeed
2301 * then a {@link ContentProviderResult} array with as many
2302 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002303 * fail, it is up to the implementation how many of the others take effect.
2304 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002305 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2306 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002307 *
Fred Quintanace31b232009-05-04 16:01:15 -07002308 * @param operations the operations to apply
2309 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002310 * @throws OperationApplicationException thrown if any operation fails.
2311 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002312 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002313 @Override
2314 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2315 @NonNull ArrayList<ContentProviderOperation> operations)
2316 throws OperationApplicationException {
2317 return applyBatch(operations);
2318 }
2319
Jeff Sharkey673db442015-06-11 19:30:57 -07002320 public @NonNull ContentProviderResult[] applyBatch(
2321 @NonNull ArrayList<ContentProviderOperation> operations)
2322 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002323 final int numOperations = operations.size();
2324 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2325 for (int i = 0; i < numOperations; i++) {
2326 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002327 }
2328 return results;
2329 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002330
2331 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002332 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002333 * interfaces that are cheaper and/or unnatural for a table-like
2334 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002335 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002336 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2337 * on this entry into the content provider besides the basic ability for the application
2338 * to get access to the provider at all. For example, it has no idea whether the call
2339 * being executed may read or write data in the provider, so can't enforce those
2340 * individual permissions. Any implementation of this method <strong>must</strong>
2341 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2342 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002343 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2344 * @param arg provider-defined String argument. May be {@code null}.
2345 * @param extras provider-defined Bundle argument. May be {@code null}.
2346 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002347 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002348 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002349 @Override
2350 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2351 @Nullable String arg, @Nullable Bundle extras) {
2352 return call(method, arg, extras);
2353 }
2354
Jeff Sharkey673db442015-06-11 19:30:57 -07002355 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2356 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002357 return null;
2358 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002359
2360 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002361 * Implement this to shut down the ContentProvider instance. You can then
2362 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002363 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002364 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002365 * Android normally handles ContentProvider startup and shutdown
2366 * automatically. You do not need to start up or shut down a
2367 * ContentProvider. When you invoke a test method on a ContentProvider,
2368 * however, a ContentProvider instance is started and keeps running after
2369 * the test finishes, even if a succeeding test instantiates another
2370 * ContentProvider. A conflict develops because the two instances are
2371 * usually running against the same underlying data source (for example, an
2372 * sqlite database).
2373 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002374 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002375 * Implementing shutDown() avoids this conflict by providing a way to
2376 * terminate the ContentProvider. This method can also prevent memory leaks
2377 * from multiple instantiations of the ContentProvider, and it can ensure
2378 * unit test isolation by allowing you to completely clean up the test
2379 * fixture before moving on to the next test.
2380 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002381 */
2382 public void shutdown() {
2383 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2384 "connections are gracefully shutdown");
2385 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002386
2387 /**
2388 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002389 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002390 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002391 * @param fd The raw file descriptor that the dump is being sent to.
2392 * @param writer The PrintWriter to which you should dump your state. This will be
2393 * closed for you after you return.
2394 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002395 */
2396 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2397 writer.println("nothing to dump");
2398 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002399
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002400 private void validateIncomingAuthority(String authority) throws SecurityException {
2401 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2402 String message = "The authority " + authority + " does not match the one of the "
2403 + "contentProvider: ";
2404 if (mAuthority != null) {
2405 message += mAuthority;
2406 } else {
2407 message += Arrays.toString(mAuthorities);
2408 }
2409 throw new SecurityException(message);
2410 }
2411 }
2412
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002413 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002414 @VisibleForTesting
2415 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002416 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002417 if (!mSingleUser) {
2418 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2419 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2420 throw new SecurityException("trying to query a ContentProvider in user "
2421 + mContext.getUserId() + " with a uri belonging to user " + userId);
2422 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002423 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002424 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002425
2426 // Normalize the path by removing any empty path segments, which can be
2427 // a source of security issues.
2428 final String encodedPath = uri.getEncodedPath();
2429 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002430 final Uri normalized = uri.buildUpon()
2431 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2432 Log.w(TAG, "Normalized " + uri + " to " + normalized
2433 + " to avoid possible security issues");
2434 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002435 } else {
2436 return uri;
2437 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002438 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002439
2440 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002441 private Uri maybeGetUriWithoutUserId(Uri uri) {
2442 if (mSingleUser) {
2443 return uri;
2444 }
2445 return getUriWithoutUserId(uri);
2446 }
2447
2448 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002449 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2450 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002451 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002452 if (end == -1) return defaultUserId;
2453 String userIdString = auth.substring(0, end);
2454 try {
2455 return Integer.parseInt(userIdString);
2456 } catch (NumberFormatException e) {
2457 Log.w(TAG, "Error parsing userId.", e);
2458 return UserHandle.USER_NULL;
2459 }
2460 }
2461
2462 /** @hide */
2463 public static int getUserIdFromAuthority(String auth) {
2464 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2465 }
2466
2467 /** @hide */
2468 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2469 if (uri == null) return defaultUserId;
2470 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2471 }
2472
2473 /** @hide */
2474 public static int getUserIdFromUri(Uri uri) {
2475 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2476 }
2477
2478 /**
2479 * Removes userId part from authority string. Expects format:
2480 * userId@some.authority
2481 * If there is no userId in the authority, it symply returns the argument
2482 * @hide
2483 */
2484 public static String getAuthorityWithoutUserId(String auth) {
2485 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002486 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002487 return auth.substring(end+1);
2488 }
2489
2490 /** @hide */
2491 public static Uri getUriWithoutUserId(Uri uri) {
2492 if (uri == null) return null;
2493 Uri.Builder builder = uri.buildUpon();
2494 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2495 return builder.build();
2496 }
2497
2498 /** @hide */
2499 public static boolean uriHasUserId(Uri uri) {
2500 if (uri == null) return false;
2501 return !TextUtils.isEmpty(uri.getUserInfo());
2502 }
2503
2504 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002505 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002506 public static Uri maybeAddUserId(Uri uri, int userId) {
2507 if (uri == null) return null;
2508 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002509 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002510 if (!uriHasUserId(uri)) {
2511 //We don't add the user Id if there's already one
2512 Uri.Builder builder = uri.buildUpon();
2513 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2514 return builder.build();
2515 }
2516 }
2517 return uri;
2518 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002519}