blob: d3393b9193ce41ea519c3a13595e70ca73c28d23 [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;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070020import static android.app.AppOpsManager.MODE_ALLOWED;
21import static android.app.AppOpsManager.MODE_ERRORED;
22import static android.app.AppOpsManager.MODE_IGNORED;
23import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070024
Jeff Sharkey673db442015-06-11 19:30:57 -070025import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080026import android.annotation.Nullable;
Mathew Inwood1c77a112018-08-14 14:06:26 +010027import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080028import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070029import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.pm.ProviderInfo;
31import android.content.res.AssetFileDescriptor;
32import android.content.res.Configuration;
33import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070034import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.SQLException;
36import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070037import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Binder;
Mathew Inwood45d2c252018-09-14 12:35:36 +010039import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080040import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070041import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080042import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070043import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070045import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080046import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060048import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010049import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070050import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
52import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080053import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070055import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080056import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070057import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080058import java.util.Arrays;
Jeff Sharkey35f31cb2018-09-24 13:23:57 -060059import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
61/**
62 * Content providers are one of the primary building blocks of Android applications, providing
63 * content to applications. They encapsulate data and provide it to applications through the single
64 * {@link ContentResolver} interface. A content provider is only required if you need to share
65 * data between multiple applications. For example, the contacts data is used by multiple
66 * applications and must be stored in a content provider. If you don't need to share data amongst
67 * multiple applications you can use a database directly via
68 * {@link android.database.sqlite.SQLiteDatabase}.
69 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * <p>When a request is made via
71 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
72 * request to the content provider registered with the authority. The content provider can interpret
73 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
74 * URIs.</p>
75 *
76 * <p>The primary methods that need to be implemented are:
77 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070078 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 * <li>{@link #query} which returns data to the caller</li>
80 * <li>{@link #insert} which inserts new data into the content provider</li>
81 * <li>{@link #update} which updates existing data in the content provider</li>
82 * <li>{@link #delete} which deletes data from the content provider</li>
83 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
84 * </ul></p>
85 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070086 * <p class="caution">Data access methods (such as {@link #insert} and
87 * {@link #update}) may be called from many threads at once, and must be thread-safe.
88 * Other methods (such as {@link #onCreate}) are only called from the application
89 * main thread, and must avoid performing lengthy operations. See the method
90 * descriptions for their expected thread behavior.</p>
91 *
92 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
93 * ContentProvider instance, so subclasses don't have to worry about the details of
94 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070095 *
96 * <div class="special reference">
97 * <h3>Developer Guides</h3>
98 * <p>For more information about using content providers, read the
99 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
100 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700102public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800103
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700104 private static final String TAG = "ContentProvider";
105
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900106 /*
107 * Note: if you add methods to ContentProvider, you must add similar methods to
108 * MockContentProvider.
109 */
110
Mathew Inwood1c77a112018-08-14 14:06:26 +0100111 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700113 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100114
115 // Since most Providers have only one authority, we keep both a String and a String[] to improve
116 // performance.
Mathew Inwood1c77a112018-08-14 14:06:26 +0100117 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100118 private String mAuthority;
Mathew Inwood1c77a112018-08-14 14:06:26 +0100119 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100120 private String[] mAuthorities;
Mathew Inwood1c77a112018-08-14 14:06:26 +0100121 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private String mReadPermission;
Mathew Inwood1c77a112018-08-14 14:06:26 +0100123 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private String mWritePermission;
Mathew Inwood1c77a112018-08-14 14:06:26 +0100125 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700126 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700127 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800128 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700129 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130
Steve McKayea93fe72016-12-02 11:35:35 -0800131 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private Transport mTransport = new Transport();
134
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700135 /**
136 * Construct a ContentProvider instance. Content providers must be
137 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
138 * in the manifest</a>, accessed with {@link ContentResolver}, and created
139 * automatically by the system, so applications usually do not create
140 * ContentProvider instances directly.
141 *
142 * <p>At construction time, the object is uninitialized, and most fields and
143 * methods are unavailable. Subclasses should initialize themselves in
144 * {@link #onCreate}, not the constructor.
145 *
146 * <p>Content providers are created on the application main thread at
147 * application launch time. The constructor must not perform lengthy
148 * operations, or application startup will be delayed.
149 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900150 public ContentProvider() {
151 }
152
153 /**
154 * Constructor just for mocking.
155 *
156 * @param context A Context object which should be some mock instance (like the
157 * instance of {@link android.test.mock.MockContext}).
158 * @param readPermission The read permision you want this instance should have in the
159 * test, which is available via {@link #getReadPermission()}.
160 * @param writePermission The write permission you want this instance should have
161 * in the test, which is available via {@link #getWritePermission()}.
162 * @param pathPermissions The PathPermissions you want this instance should have
163 * in the test, which is available via {@link #getPathPermissions()}.
164 * @hide
165 */
Mathew Inwood45d2c252018-09-14 12:35:36 +0100166 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900167 public ContentProvider(
168 Context context,
169 String readPermission,
170 String writePermission,
171 PathPermission[] pathPermissions) {
172 mContext = context;
173 mReadPermission = readPermission;
174 mWritePermission = writePermission;
175 mPathPermissions = pathPermissions;
176 }
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 /**
179 * Given an IContentProvider, try to coerce it back to the real
180 * ContentProvider object if it is running in the local process. This can
181 * be used if you know you are running in the same process as a provider,
182 * and want to get direct access to its implementation details. Most
183 * clients should not nor have a reason to use it.
184 *
185 * @param abstractInterface The ContentProvider interface that is to be
186 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800187 * @return If the IContentProvider is non-{@code null} and local, returns its actual
188 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 * @hide
190 */
Mathew Inwood1c77a112018-08-14 14:06:26 +0100191 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 public static ContentProvider coerceToLocalContentProvider(
193 IContentProvider abstractInterface) {
194 if (abstractInterface instanceof Transport) {
195 return ((Transport)abstractInterface).getContentProvider();
196 }
197 return null;
198 }
199
200 /**
201 * Binder object that deals with remoting.
202 *
203 * @hide
204 */
205 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800206 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800207 int mReadOp = AppOpsManager.OP_NONE;
208 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 ContentProvider getContentProvider() {
211 return ContentProvider.this;
212 }
213
Jeff Brownd2183652011-10-09 12:39:53 -0700214 @Override
215 public String getProviderName() {
216 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 }
218
Jeff Brown75ea64f2012-01-25 19:37:13 -0800219 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800220 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
221 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600222 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100223 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800224 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700225 // The caller has no access to the data, so return an empty cursor with
226 // the columns in the requested order. The caller may ask for an invalid
227 // column and we would not catch that but this is not a problem in practice.
228 // We do not call ContentProvider#query with a modified where clause since
229 // the implementation is not guaranteed to be backed by a SQL database, hence
230 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700231 if (projection != null) {
232 return new MatrixCursor(projection, 0);
233 }
234
235 // Null projection means all columns but we have no idea which they are.
236 // However, the caller may be expecting to access them my index. Hence,
237 // we have to execute the query as if allowed to get a cursor with the
238 // columns. We then use the column names to return an empty cursor.
Steve McKayea93fe72016-12-02 11:35:35 -0800239 Cursor cursor = ContentProvider.this.query(
240 uri, projection, queryArgs,
241 CancellationSignal.fromTransport(cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700242 if (cursor == null) {
243 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700244 }
245
246 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700247 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800248 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700249 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700250 try {
251 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800252 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700253 CancellationSignal.fromTransport(cancellationSignal));
254 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700255 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 }
258
Jeff Brown75ea64f2012-01-25 19:37:13 -0800259 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 public String getType(Uri uri) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600261 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100262 uri = maybeGetUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 return ContentProvider.this.getType(uri);
264 }
265
Jeff Brown75ea64f2012-01-25 19:37:13 -0800266 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800267 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600268 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100269 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100270 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800271 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800272 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800273 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700274 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700275 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100276 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700277 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700278 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281
Jeff Brown75ea64f2012-01-25 19:37:13 -0800282 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800283 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600284 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100285 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800286 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800287 return 0;
288 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700289 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700290 try {
291 return ContentProvider.this.bulkInsert(uri, initialValues);
292 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700293 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 }
296
Jeff Brown75ea64f2012-01-25 19:37:13 -0800297 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800298 public ContentProviderResult[] applyBatch(String callingPkg,
299 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700300 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100301 int numOperations = operations.size();
302 final int[] userIds = new int[numOperations];
303 for (int i = 0; i < numOperations; i++) {
304 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100305 Uri uri = operation.getUri();
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100306 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600307 uri = validateIncomingUri(uri);
308 uri = maybeGetUriWithoutUserId(uri);
309 // Rebuild operation if we changed the Uri above
310 if (!Objects.equals(operation.getUri(), uri)) {
311 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100312 operations.set(i, operation);
313 }
Fred Quintana89437372009-05-15 15:10:40 -0700314 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800315 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800316 != AppOpsManager.MODE_ALLOWED) {
317 throw new OperationApplicationException("App op not allowed", 0);
318 }
Fred Quintana89437372009-05-15 15:10:40 -0700319 }
Fred Quintana89437372009-05-15 15:10:40 -0700320 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800321 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800322 != AppOpsManager.MODE_ALLOWED) {
323 throw new OperationApplicationException("App op not allowed", 0);
324 }
Fred Quintana89437372009-05-15 15:10:40 -0700325 }
326 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100329 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800330 if (results != null) {
331 for (int i = 0; i < results.length ; i++) {
332 if (userIds[i] != UserHandle.USER_CURRENT) {
333 // Adding the userId to the uri.
334 results[i] = new ContentProviderResult(results[i], userIds[i]);
335 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100336 }
337 }
338 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700340 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700341 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700342 }
343
Jeff Brown75ea64f2012-01-25 19:37:13 -0800344 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800345 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600346 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100347 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800348 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800349 return 0;
350 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700351 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700352 try {
353 return ContentProvider.this.delete(uri, selection, selectionArgs);
354 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700355 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 }
358
Jeff Brown75ea64f2012-01-25 19:37:13 -0800359 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800360 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 String[] selectionArgs) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600362 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100363 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800364 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800365 return 0;
366 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700367 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700368 try {
369 return ContentProvider.this.update(uri, values, selection, selectionArgs);
370 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700371 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 }
374
Jeff Brown75ea64f2012-01-25 19:37:13 -0800375 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700376 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800377 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
378 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600379 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100380 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800381 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700382 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700383 try {
384 return ContentProvider.this.openFile(
385 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
386 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700387 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 }
390
Jeff Brown75ea64f2012-01-25 19:37:13 -0800391 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700392 public AssetFileDescriptor openAssetFile(
393 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 throws FileNotFoundException {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600395 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100396 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800397 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700398 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700399 try {
400 return ContentProvider.this.openAssetFile(
401 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
402 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700403 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406
Jeff Brown75ea64f2012-01-25 19:37:13 -0800407 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800408 public Bundle call(
409 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600410 Bundle.setDefusable(extras, true);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700411 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700412 try {
413 return ContentProvider.this.call(method, arg, extras);
414 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700415 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700416 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800417 }
418
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700419 @Override
420 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600421 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100422 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700423 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
424 }
425
426 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800427 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700428 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600429 Bundle.setDefusable(opts, true);
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600430 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100431 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800432 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700433 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700434 try {
435 return ContentProvider.this.openTypedAssetFile(
436 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
437 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700438 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700439 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700440 }
441
Jeff Brown75ea64f2012-01-25 19:37:13 -0800442 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700443 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800444 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800445 }
446
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700447 @Override
448 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600449 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100450 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100451 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800452 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700453 return null;
454 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700455 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700456 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100457 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700458 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700459 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700460 }
461 }
462
463 @Override
464 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600465 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100466 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100467 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800468 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700469 return null;
470 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700471 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700472 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100473 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700474 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700475 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700476 }
477 }
478
Ben Lin1cf454f2016-11-10 13:50:54 -0800479 @Override
480 public boolean refresh(String callingPkg, Uri uri, Bundle args,
481 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkey35f31cb2018-09-24 13:23:57 -0600482 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800483 uri = getUriWithoutUserId(uri);
484 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
485 return false;
486 }
487 final String original = setCallingPackage(callingPkg);
488 try {
489 return ContentProvider.this.refresh(uri, args,
490 CancellationSignal.fromTransport(cancellationSignal));
491 } finally {
492 setCallingPackage(original);
493 }
494 }
495
Dianne Hackbornff170242014-11-19 10:59:01 -0800496 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
497 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800498 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800499 if (enforceWritePermission(callingPkg, uri, callerToken)
500 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800501 throw new FileNotFoundException("App op not allowed");
502 }
503 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800504 if (enforceReadPermission(callingPkg, uri, callerToken)
505 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800506 throw new FileNotFoundException("App op not allowed");
507 }
508 }
509 }
510
Dianne Hackbornff170242014-11-19 10:59:01 -0800511 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
512 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700513 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
514 if (mode != MODE_ALLOWED) {
515 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800516 }
Svet Ganov99b60432015-06-27 13:15:22 -0700517
518 if (mReadOp != AppOpsManager.OP_NONE) {
519 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
520 }
521
Dianne Hackborn35654b62013-01-14 17:38:02 -0800522 return AppOpsManager.MODE_ALLOWED;
523 }
524
Dianne Hackbornff170242014-11-19 10:59:01 -0800525 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
526 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700527 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
528 if (mode != MODE_ALLOWED) {
529 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800530 }
Svet Ganov99b60432015-06-27 13:15:22 -0700531
532 if (mWriteOp != AppOpsManager.OP_NONE) {
533 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
534 }
535
Dianne Hackborn35654b62013-01-14 17:38:02 -0800536 return AppOpsManager.MODE_ALLOWED;
537 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700538 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800539
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100540 boolean checkUser(int pid, int uid, Context context) {
541 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700542 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100543 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
544 == PERMISSION_GRANTED;
545 }
546
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700547 /**
548 * Verify that calling app holds both the given permission and any app-op
549 * associated with that permission.
550 */
551 private int checkPermissionAndAppOp(String permission, String callingPkg,
552 IBinder callerToken) {
553 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
554 callerToken) != PERMISSION_GRANTED) {
555 return MODE_ERRORED;
556 }
557
558 final int permOp = AppOpsManager.permissionToOpCode(permission);
559 if (permOp != AppOpsManager.OP_NONE) {
560 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
561 }
562
563 return MODE_ALLOWED;
564 }
565
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700566 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700567 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800568 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700569 final Context context = getContext();
570 final int pid = Binder.getCallingPid();
571 final int uid = Binder.getCallingUid();
572 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700573 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700574
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700575 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700576 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700577 }
578
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100579 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700580 final String componentPerm = getReadPermission();
581 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700582 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
583 if (mode == MODE_ALLOWED) {
584 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700585 } else {
586 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700587 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700588 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700589 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700590
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700591 // track if unprotected read is allowed; any denied
592 // <path-permission> below removes this ability
593 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700594
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700595 final PathPermission[] pps = getPathPermissions();
596 if (pps != null) {
597 final String path = uri.getPath();
598 for (PathPermission pp : pps) {
599 final String pathPerm = pp.getReadPermission();
600 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700601 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
602 if (mode == MODE_ALLOWED) {
603 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700604 } else {
605 // any denied <path-permission> means we lose
606 // default <provider> access.
607 allowDefaultRead = false;
608 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700609 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700610 }
611 }
612 }
613 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700614
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700615 // if we passed <path-permission> checks above, and no default
616 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700617 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700619
620 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800621 final int callingUserId = UserHandle.getUserId(uid);
622 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
623 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800624 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
625 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700626 return MODE_ALLOWED;
627 }
628
629 // If the worst denial we found above was ignored, then pass that
630 // ignored through; otherwise we assume it should be a real error below.
631 if (strongestMode == MODE_IGNORED) {
632 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700633 }
634
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600635 final String suffix;
636 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
637 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
638 } else if (mExported) {
639 suffix = " requires " + missingPerm + ", or grantUriPermission()";
640 } else {
641 suffix = " requires the provider be exported, or grantUriPermission()";
642 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700643 throw new SecurityException("Permission Denial: reading "
644 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600645 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700646 }
647
648 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700649 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800650 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700651 final Context context = getContext();
652 final int pid = Binder.getCallingPid();
653 final int uid = Binder.getCallingUid();
654 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700655 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700656
657 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700658 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700659 }
660
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100661 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700662 final String componentPerm = getWritePermission();
663 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700664 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
665 if (mode == MODE_ALLOWED) {
666 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700667 } else {
668 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700669 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700670 }
671 }
672
673 // track if unprotected write is allowed; any denied
674 // <path-permission> below removes this ability
675 boolean allowDefaultWrite = (componentPerm == null);
676
677 final PathPermission[] pps = getPathPermissions();
678 if (pps != null) {
679 final String path = uri.getPath();
680 for (PathPermission pp : pps) {
681 final String pathPerm = pp.getWritePermission();
682 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700683 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
684 if (mode == MODE_ALLOWED) {
685 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700686 } else {
687 // any denied <path-permission> means we lose
688 // default <provider> access.
689 allowDefaultWrite = false;
690 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700691 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700692 }
693 }
694 }
695 }
696
697 // if we passed <path-permission> checks above, and no default
698 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700699 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700700 }
701
702 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800703 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
704 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700705 return MODE_ALLOWED;
706 }
707
708 // If the worst denial we found above was ignored, then pass that
709 // ignored through; otherwise we assume it should be a real error below.
710 if (strongestMode == MODE_IGNORED) {
711 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700712 }
713
714 final String failReason = mExported
715 ? " requires " + missingPerm + ", or grantUriPermission()"
716 : " requires the provider be exported, or grantUriPermission()";
717 throw new SecurityException("Permission Denial: writing "
718 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
719 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700723 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800724 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 * constructor.
726 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700727 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 return mContext;
729 }
730
731 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700732 * Set the calling package, returning the current value (or {@code null})
733 * which can be used later to restore the previous state.
734 */
735 private String setCallingPackage(String callingPackage) {
736 final String original = mCallingPackage.get();
737 mCallingPackage.set(callingPackage);
738 return original;
739 }
740
741 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700742 * Return the package name of the caller that initiated the request being
743 * processed on the current thread. The returned package will have been
744 * verified to belong to the calling UID. Returns {@code null} if not
745 * currently processing a request.
746 * <p>
747 * This will always return {@code null} when processing
748 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
749 *
750 * @see Binder#getCallingUid()
751 * @see Context#grantUriPermission(String, Uri, int)
752 * @throws SecurityException if the calling package doesn't belong to the
753 * calling UID.
754 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700755 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700756 final String pkg = mCallingPackage.get();
757 if (pkg != null) {
758 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
759 }
760 return pkg;
761 }
762
763 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100764 * Change the authorities of the ContentProvider.
765 * This is normally set for you from its manifest information when the provider is first
766 * created.
767 * @hide
768 * @param authorities the semi-colon separated authorities of the ContentProvider.
769 */
770 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100771 if (authorities != null) {
772 if (authorities.indexOf(';') == -1) {
773 mAuthority = authorities;
774 mAuthorities = null;
775 } else {
776 mAuthority = null;
777 mAuthorities = authorities.split(";");
778 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100779 }
780 }
781
782 /** @hide */
783 protected final boolean matchesOurAuthorities(String authority) {
784 if (mAuthority != null) {
785 return mAuthority.equals(authority);
786 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100787 if (mAuthorities != null) {
788 int length = mAuthorities.length;
789 for (int i = 0; i < length; i++) {
790 if (mAuthorities[i].equals(authority)) return true;
791 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100792 }
793 return false;
794 }
795
796
797 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 * Change the permission required to read data from the content
799 * provider. This is normally set for you from its manifest information
800 * when the provider is first created.
801 *
802 * @param permission Name of the permission required for read-only access.
803 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700804 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 mReadPermission = permission;
806 }
807
808 /**
809 * Return the name of the permission required for read-only access to
810 * this content provider. This method can be called from multiple
811 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800812 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
813 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700815 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 return mReadPermission;
817 }
818
819 /**
820 * Change the permission required to read and write data in the content
821 * provider. This is normally set for you from its manifest information
822 * when the provider is first created.
823 *
824 * @param permission Name of the permission required for read/write access.
825 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700826 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 mWritePermission = permission;
828 }
829
830 /**
831 * Return the name of the permission required for read/write access to
832 * this content provider. This method can be called from multiple
833 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800834 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
835 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700837 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 return mWritePermission;
839 }
840
841 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700842 * Change the path-based permission required to read and/or write data in
843 * the content provider. This is normally set for you from its manifest
844 * information when the provider is first created.
845 *
846 * @param permissions Array of path permission descriptions.
847 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700848 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700849 mPathPermissions = permissions;
850 }
851
852 /**
853 * Return the path-based permissions required for read and/or write access to
854 * this content provider. This method can be called from multiple
855 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800856 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
857 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700858 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700859 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700860 return mPathPermissions;
861 }
862
Dianne Hackborn35654b62013-01-14 17:38:02 -0800863 /** @hide */
Mathew Inwood1c77a112018-08-14 14:06:26 +0100864 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800865 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800866 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800867 mTransport.mReadOp = readOp;
868 mTransport.mWriteOp = writeOp;
869 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800870 }
871
Dianne Hackborn961321f2013-02-05 17:22:41 -0800872 /** @hide */
873 public AppOpsManager getAppOpsManager() {
874 return mTransport.mAppOpsManager;
875 }
876
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700877 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700878 * Implement this to initialize your content provider on startup.
879 * This method is called for all registered content providers on the
880 * application main thread at application launch time. It must not perform
881 * lengthy operations, or application startup will be delayed.
882 *
883 * <p>You should defer nontrivial initialization (such as opening,
884 * upgrading, and scanning databases) until the content provider is used
885 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
886 * keeps application startup fast, avoids unnecessary work if the provider
887 * turns out not to be needed, and stops database errors (such as a full
888 * disk) from halting application launch.
889 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700890 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700891 * is a helpful utility class that makes it easy to manage databases,
892 * and will automatically defer opening until first use. If you do use
893 * SQLiteOpenHelper, make sure to avoid calling
894 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
895 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
896 * from this method. (Instead, override
897 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
898 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 *
900 * @return true if the provider was successfully loaded, false otherwise
901 */
902 public abstract boolean onCreate();
903
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700904 /**
905 * {@inheritDoc}
906 * This method is always called on the application main thread, and must
907 * not perform lengthy operations.
908 *
909 * <p>The default content provider implementation does nothing.
910 * Override this method to take appropriate action.
911 * (Content providers do not usually care about things like screen
912 * orientation, but may want to know about locale changes.)
913 */
Steve McKayea93fe72016-12-02 11:35:35 -0800914 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 public void onConfigurationChanged(Configuration newConfig) {
916 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700917
918 /**
919 * {@inheritDoc}
920 * This method is always called on the application main thread, and must
921 * not perform lengthy operations.
922 *
923 * <p>The default content provider implementation does nothing.
924 * Subclasses may override this method to take appropriate action.
925 */
Steve McKayea93fe72016-12-02 11:35:35 -0800926 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 public void onLowMemory() {
928 }
929
Steve McKayea93fe72016-12-02 11:35:35 -0800930 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700931 public void onTrimMemory(int level) {
932 }
933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700935 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800936 *
937 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
938 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
939 * implementation of this method.
940 *
941 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800942 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
943 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 * <p>
945 * Example client call:<p>
946 * <pre>// Request a specific record.
947 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000948 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 projection, // Which columns to return.
950 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000951 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 People.NAME + " ASC"); // Sort order.</pre>
953 * Example implementation:<p>
954 * <pre>// SQLiteQueryBuilder is a helper class that creates the
955 // proper SQL syntax for us.
956 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
957
958 // Set the table we're querying.
959 qBuilder.setTables(DATABASE_TABLE_NAME);
960
961 // If the query ends in a specific record number, we're
962 // being asked for a specific record, so set the
963 // WHERE clause in our query.
964 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
965 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
966 }
967
968 // Make the query.
969 Cursor c = qBuilder.query(mDb,
970 projection,
971 selection,
972 selectionArgs,
973 groupBy,
974 having,
975 sortOrder);
976 c.setNotificationUri(getContext().getContentResolver(), uri);
977 return c;</pre>
978 *
979 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000980 * if the client is requesting a specific record, the URI will end in a record number
981 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
982 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800984 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800986 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000987 * @param selectionArgs You may include ?s in selection, which will be replaced by
988 * the values from selectionArgs, in order that they appear in the selection.
989 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800991 * If {@code null} then the provider is free to define the sort order.
992 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700994 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
995 @Nullable String selection, @Nullable String[] selectionArgs,
996 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
Fred Quintana5bba6322009-10-05 14:21:12 -0700998 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800999 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001000 *
1001 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1002 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1003 *
1004 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001005 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1006 * and Threads</a>.
1007 * <p>
1008 * Example client call:<p>
1009 * <pre>// Request a specific record.
1010 * Cursor managedCursor = managedQuery(
1011 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1012 projection, // Which columns to return.
1013 null, // WHERE clause.
1014 null, // WHERE clause value substitution
1015 People.NAME + " ASC"); // Sort order.</pre>
1016 * Example implementation:<p>
1017 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1018 // proper SQL syntax for us.
1019 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1020
1021 // Set the table we're querying.
1022 qBuilder.setTables(DATABASE_TABLE_NAME);
1023
1024 // If the query ends in a specific record number, we're
1025 // being asked for a specific record, so set the
1026 // WHERE clause in our query.
1027 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1028 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1029 }
1030
1031 // Make the query.
1032 Cursor c = qBuilder.query(mDb,
1033 projection,
1034 selection,
1035 selectionArgs,
1036 groupBy,
1037 having,
1038 sortOrder);
1039 c.setNotificationUri(getContext().getContentResolver(), uri);
1040 return c;</pre>
1041 * <p>
1042 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001043 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1044 * signal to ensure correct operation on older versions of the Android Framework in
1045 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001046 *
1047 * @param uri The URI to query. This will be the full URI sent by the client;
1048 * if the client is requesting a specific record, the URI will end in a record number
1049 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1050 * that _id value.
1051 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001052 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001053 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001054 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001055 * @param selectionArgs You may include ?s in selection, which will be replaced by
1056 * the values from selectionArgs, in order that they appear in the selection.
1057 * The values will be bound as Strings.
1058 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001059 * If {@code null} then the provider is free to define the sort order.
1060 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001061 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001062 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001063 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001064 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001065 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1066 @Nullable String selection, @Nullable String[] selectionArgs,
1067 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001068 return query(uri, projection, selection, selectionArgs, sortOrder);
1069 }
1070
1071 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001072 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1073 * Arguments may include traditional SQL style query arguments. When present these
1074 * should be handled according to the contract established in
1075 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1076 *
1077 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001078 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1079 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1080 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001081 *
Steve McKay76b27702017-04-24 12:07:53 -07001082 * <p>This method can be called from multiple threads, as described in
1083 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1084 * and Threads</a>.
1085 *
1086 * <p>
1087 * Example client call:<p>
1088 * <pre>// Request 20 records starting at row index 30.
1089 Bundle queryArgs = new Bundle();
1090 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1091 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1092
1093 Cursor cursor = getContentResolver().query(
1094 contentUri, // Content Uri is specific to individual content providers.
1095 projection, // String[] describing which columns to return.
1096 queryArgs, // Query arguments.
1097 null); // Cancellation signal.</pre>
1098 *
1099 * Example implementation:<p>
1100 * <pre>
1101
1102 int recordsetSize = 0x1000; // Actual value is implementation specific.
1103 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1104
1105 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1106 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1107
1108 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1109
1110 // Calculate the number of items to include in the cursor.
1111 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1112
1113 // Build the paged result set....
1114 for (int i = offset; i < offset + numItems; i++) {
1115 // populate row from your data.
1116 }
1117
1118 Bundle extras = new Bundle();
1119 c.setExtras(extras);
1120
1121 // Any QUERY_ARG_* key may be included if honored.
1122 // In an actual implementation, include only keys that are both present in queryArgs
1123 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1124 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1125 // then QUERY_ARG_OFFSET should be omitted.
1126 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1127 ContentResolver.QUERY_ARG_OFFSET,
1128 ContentResolver.QUERY_ARG_LIMIT
1129 });
1130
1131 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1132
1133 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1134
1135 return cursor;</pre>
1136 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001137 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1138 * implementation details.
1139 *
1140 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001141 * @param projection The list of columns to put into the cursor.
1142 * If {@code null} provide a default set of columns.
1143 * @param queryArgs A Bundle containing all additional information necessary for the query.
1144 * Values in the Bundle may include SQL style arguments.
1145 * @param cancellationSignal A signal to cancel the operation in progress,
1146 * or {@code null}.
1147 * @return a Cursor or {@code null}.
1148 */
1149 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1150 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1151 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001152
Steve McKayd7ece9f2017-01-12 16:59:59 -08001153 // if client doesn't supply an SQL sort order argument, attempt to build one from
1154 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001155 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001156 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1157 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1158 }
1159
Steve McKayea93fe72016-12-02 11:35:35 -08001160 return query(
1161 uri,
1162 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001163 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1164 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1165 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001166 cancellationSignal);
1167 }
1168
1169 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001170 * Implement this to handle requests for the MIME type of the data at the
1171 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 * <code>vnd.android.cursor.item</code> for a single record,
1173 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001174 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001175 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1176 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001178 * <p>Note that there are no permissions needed for an application to
1179 * access this information; if your content provider requires read and/or
1180 * write permissions, or is not exported, all applications can still call
1181 * this method regardless of their access permissions. This allows them
1182 * to retrieve the MIME type for a URI when dispatching intents.
1183 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001185 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001187 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188
1189 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001190 * Implement this to support canonicalization of URIs that refer to your
1191 * content provider. A canonical URI is one that can be transported across
1192 * devices, backup/restore, and other contexts, and still be able to refer
1193 * to the same data item. Typically this is implemented by adding query
1194 * params to the URI allowing the content provider to verify that an incoming
1195 * canonical URI references the same data as it was originally intended for and,
1196 * if it doesn't, to find that data (if it exists) in the current environment.
1197 *
1198 * <p>For example, if the content provider holds people and a normal URI in it
1199 * is created with a row index into that people database, the cananical representation
1200 * may have an additional query param at the end which specifies the name of the
1201 * person it is intended for. Later calls into the provider with that URI will look
1202 * up the row of that URI's base index and, if it doesn't match or its entry's
1203 * name doesn't match the name in the query param, perform a query on its database
1204 * to find the correct row to operate on.</p>
1205 *
1206 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1207 * URIs (including this one) must perform this verification and recovery of any
1208 * canonical URIs they receive. In addition, you must also implement
1209 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1210 *
1211 * <p>The default implementation of this method returns null, indicating that
1212 * canonical URIs are not supported.</p>
1213 *
1214 * @param url The Uri to canonicalize.
1215 *
1216 * @return Return the canonical representation of <var>url</var>, or null if
1217 * canonicalization of that Uri is not supported.
1218 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001219 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001220 return null;
1221 }
1222
1223 /**
1224 * Remove canonicalization from canonical URIs previously returned by
1225 * {@link #canonicalize}. For example, if your implementation is to add
1226 * a query param to canonicalize a URI, this method can simply trip any
1227 * query params on the URI. The default implementation always returns the
1228 * same <var>url</var> that was passed in.
1229 *
1230 * @param url The Uri to remove any canonicalization from.
1231 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001232 * @return Return the non-canonical representation of <var>url</var>, return
1233 * the <var>url</var> as-is if there is nothing to do, or return null if
1234 * the data identified by the canonical representation can not be found in
1235 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001236 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001237 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001238 return url;
1239 }
1240
1241 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001242 * Implement this to support refresh of content identified by {@code uri}. By default, this
1243 * method returns false; providers who wish to implement this should return true to signal the
1244 * client that the provider has tried refreshing with its own implementation.
1245 * <p>
1246 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1247 * <p>
1248 * Client code should only invoke this method when there is a strong indication (such as a user
1249 * initiated pull to refresh gesture) that the content is stale.
1250 * <p>
1251 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1252 * notifications when content changes.
1253 *
1254 * @param uri The Uri identifying the data to refresh.
1255 * @param args Additional options from the client. The definitions of these are specific to the
1256 * content provider being called.
1257 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1258 * none. For example, if you called refresh on a particular uri, you should call
1259 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1260 * canceled the refresh request.
1261 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001262 */
1263 public boolean refresh(Uri uri, @Nullable Bundle args,
1264 @Nullable CancellationSignal cancellationSignal) {
1265 return false;
1266 }
1267
1268 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001269 * @hide
1270 * Implementation when a caller has performed an insert on the content
1271 * provider, but that call has been rejected for the operation given
1272 * to {@link #setAppOps(int, int)}. The default implementation simply
1273 * returns a dummy URI that is the base URI with a 0 path element
1274 * appended.
1275 */
1276 public Uri rejectInsert(Uri uri, ContentValues values) {
1277 // If not allowed, we need to return some reasonable URI. Maybe the
1278 // content provider should be responsible for this, but for now we
1279 // will just return the base URI with a dummy '0' tagged on to it.
1280 // You shouldn't be able to read if you can't write, anyway, so it
1281 // shouldn't matter much what is returned.
1282 return uri.buildUpon().appendPath("0").build();
1283 }
1284
1285 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001286 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1288 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001289 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001290 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1291 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001292 * @param uri The content:// URI of the insertion request. This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001294 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 * @return The URI for the newly inserted item.
1296 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001297 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298
1299 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001300 * Override this to handle requests to insert a set of new rows, or the
1301 * default implementation will iterate over the values and call
1302 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1304 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001305 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001306 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1307 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 *
1309 * @param uri The content:// URI of the insertion request.
1310 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001311 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 * @return The number of values that were inserted.
1313 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001314 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 int numValues = values.length;
1316 for (int i = 0; i < numValues; i++) {
1317 insert(uri, values[i]);
1318 }
1319 return numValues;
1320 }
1321
1322 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001323 * Implement this to handle requests to delete one or more rows.
1324 * The implementation should apply the selection clause when performing
1325 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001326 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001328 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001329 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1330 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 *
1332 * <p>The implementation is responsible for parsing out a row ID at the end
1333 * of the URI, if a specific row is being deleted. That is, the client would
1334 * pass in <code>content://contacts/people/22</code> and the implementation is
1335 * responsible for parsing the record number (22) when creating a SQL statement.
1336 *
1337 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1338 * @param selection An optional restriction to apply to rows when deleting.
1339 * @return The number of rows affected.
1340 * @throws SQLException
1341 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001342 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1343 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344
1345 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001346 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001347 * The implementation should update all rows matching the selection
1348 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1350 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001351 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001352 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1353 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 *
1355 * @param uri The URI to query. This can potentially have a record ID if this
1356 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001357 * @param values A set of column_name/value pairs to update in the database.
1358 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 * @param selection An optional filter to match rows to update.
1360 * @return the number of rows affected.
1361 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001362 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001363 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364
1365 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001366 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001367 * The default implementation always throws {@link FileNotFoundException}.
1368 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001369 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1370 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001371 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001372 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1373 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001374 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 *
1376 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1377 * their responsibility to close it when done. That is, the implementation
1378 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001379 * <p>
1380 * If opened with the exclusive "r" or "w" modes, the returned
1381 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1382 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1383 * supports seeking.
1384 * <p>
1385 * If you need to detect when the returned ParcelFileDescriptor has been
1386 * closed, or if the remote process has crashed or encountered some other
1387 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1388 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1389 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1390 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001391 * <p>
1392 * If you need to return a large file that isn't backed by a real file on
1393 * disk, such as a file on a network share or cloud storage service,
1394 * consider using
1395 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1396 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001398 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1399 * to return the appropriate MIME type for the data returned here with
1400 * the same URI. This will allow intent resolution to automatically determine the data MIME
1401 * type and select the appropriate matching targets as part of its operation.</p>
1402 *
1403 * <p class="note">For better interoperability with other applications, it is recommended
1404 * that for any URIs that can be opened, you also support queries on them
1405 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1406 * You may also want to support other common columns if you have additional meta-data
1407 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1408 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1409 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 * @param uri The URI whose file is to be opened.
1411 * @param mode Access mode for the file. May be "r" for read-only access,
1412 * "rw" for read and write access, or "rwt" for read and write access
1413 * that truncates any existing file.
1414 *
1415 * @return Returns a new ParcelFileDescriptor which you can use to access
1416 * the file.
1417 *
1418 * @throws FileNotFoundException Throws FileNotFoundException if there is
1419 * no file associated with the given URI or the mode is invalid.
1420 * @throws SecurityException Throws SecurityException if the caller does
1421 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001422 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 * @see #openAssetFile(Uri, String)
1424 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001425 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001426 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001427 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001428 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 throws FileNotFoundException {
1430 throw new FileNotFoundException("No files supported by provider at "
1431 + uri);
1432 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001435 * Override this to handle requests to open a file blob.
1436 * The default implementation always throws {@link FileNotFoundException}.
1437 * This method can be called from multiple threads, as described in
1438 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1439 * and Threads</a>.
1440 *
1441 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1442 * to the caller. This way large data (such as images and documents) can be
1443 * returned without copying the content.
1444 *
1445 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1446 * their responsibility to close it when done. That is, the implementation
1447 * of this method should create a new ParcelFileDescriptor for each call.
1448 * <p>
1449 * If opened with the exclusive "r" or "w" modes, the returned
1450 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1451 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1452 * supports seeking.
1453 * <p>
1454 * If you need to detect when the returned ParcelFileDescriptor has been
1455 * closed, or if the remote process has crashed or encountered some other
1456 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1457 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1458 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1459 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1460 *
1461 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1462 * to return the appropriate MIME type for the data returned here with
1463 * the same URI. This will allow intent resolution to automatically determine the data MIME
1464 * type and select the appropriate matching targets as part of its operation.</p>
1465 *
1466 * <p class="note">For better interoperability with other applications, it is recommended
1467 * that for any URIs that can be opened, you also support queries on them
1468 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1469 * You may also want to support other common columns if you have additional meta-data
1470 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1471 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1472 *
1473 * @param uri The URI whose file is to be opened.
1474 * @param mode Access mode for the file. May be "r" for read-only access,
1475 * "w" for write-only access, "rw" for read and write access, or
1476 * "rwt" for read and write access that truncates any existing
1477 * file.
1478 * @param signal A signal to cancel the operation in progress, or
1479 * {@code null} if none. For example, if you are downloading a
1480 * file from the network to service a "rw" mode request, you
1481 * should periodically call
1482 * {@link CancellationSignal#throwIfCanceled()} to check whether
1483 * the client has canceled the request and abort the download.
1484 *
1485 * @return Returns a new ParcelFileDescriptor which you can use to access
1486 * the file.
1487 *
1488 * @throws FileNotFoundException Throws FileNotFoundException if there is
1489 * no file associated with the given URI or the mode is invalid.
1490 * @throws SecurityException Throws SecurityException if the caller does
1491 * not have permission to access the file.
1492 *
1493 * @see #openAssetFile(Uri, String)
1494 * @see #openFileHelper(Uri, String)
1495 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001496 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001497 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001498 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1499 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001500 return openFile(uri, mode);
1501 }
1502
1503 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 * This is like {@link #openFile}, but can be implemented by providers
1505 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001506 * inside of their .apk.
1507 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001508 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1509 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001510 *
1511 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001512 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001513 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1515 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1516 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001517 * <p>
1518 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1519 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001520 *
1521 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 * should create the AssetFileDescriptor with
1523 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001524 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001526 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1527 * to return the appropriate MIME type for the data returned here with
1528 * the same URI. This will allow intent resolution to automatically determine the data MIME
1529 * type and select the appropriate matching targets as part of its operation.</p>
1530 *
1531 * <p class="note">For better interoperability with other applications, it is recommended
1532 * that for any URIs that can be opened, you also support queries on them
1533 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1534 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 * @param uri The URI whose file is to be opened.
1536 * @param mode Access mode for the file. May be "r" for read-only access,
1537 * "w" for write-only access (erasing whatever data is currently in
1538 * the file), "wa" for write-only access to append to any existing data,
1539 * "rw" for read and write access on any existing data, and "rwt" for read
1540 * and write access that truncates any existing file.
1541 *
1542 * @return Returns a new AssetFileDescriptor which you can use to access
1543 * the file.
1544 *
1545 * @throws FileNotFoundException Throws FileNotFoundException if there is
1546 * no file associated with the given URI or the mode is invalid.
1547 * @throws SecurityException Throws SecurityException if the caller does
1548 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001549 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 * @see #openFile(Uri, String)
1551 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001552 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001554 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 throws FileNotFoundException {
1556 ParcelFileDescriptor fd = openFile(uri, mode);
1557 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1558 }
1559
1560 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001561 * This is like {@link #openFile}, but can be implemented by providers
1562 * that need to be able to return sub-sections of files, often assets
1563 * inside of their .apk.
1564 * This method can be called from multiple threads, as described in
1565 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1566 * and Threads</a>.
1567 *
1568 * <p>If you implement this, your clients must be able to deal with such
1569 * file slices, either directly with
1570 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1571 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1572 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1573 * methods.
1574 * <p>
1575 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1576 * streaming of data.
1577 *
1578 * <p class="note">If you are implementing this to return a full file, you
1579 * should create the AssetFileDescriptor with
1580 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1581 * applications that cannot handle sub-sections of files.</p>
1582 *
1583 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1584 * to return the appropriate MIME type for the data returned here with
1585 * the same URI. This will allow intent resolution to automatically determine the data MIME
1586 * type and select the appropriate matching targets as part of its operation.</p>
1587 *
1588 * <p class="note">For better interoperability with other applications, it is recommended
1589 * that for any URIs that can be opened, you also support queries on them
1590 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1591 *
1592 * @param uri The URI whose file is to be opened.
1593 * @param mode Access mode for the file. May be "r" for read-only access,
1594 * "w" for write-only access (erasing whatever data is currently in
1595 * the file), "wa" for write-only access to append to any existing data,
1596 * "rw" for read and write access on any existing data, and "rwt" for read
1597 * and write access that truncates any existing file.
1598 * @param signal A signal to cancel the operation in progress, or
1599 * {@code null} if none. For example, if you are downloading a
1600 * file from the network to service a "rw" mode request, you
1601 * should periodically call
1602 * {@link CancellationSignal#throwIfCanceled()} to check whether
1603 * the client has canceled the request and abort the download.
1604 *
1605 * @return Returns a new AssetFileDescriptor which you can use to access
1606 * the file.
1607 *
1608 * @throws FileNotFoundException Throws FileNotFoundException if there is
1609 * no file associated with the given URI or the mode is invalid.
1610 * @throws SecurityException Throws SecurityException if the caller does
1611 * not have permission to access the file.
1612 *
1613 * @see #openFile(Uri, String)
1614 * @see #openFileHelper(Uri, String)
1615 * @see #getType(android.net.Uri)
1616 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001617 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1618 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001619 return openAssetFile(uri, mode);
1620 }
1621
1622 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 * Convenience for subclasses that wish to implement {@link #openFile}
1624 * by looking up a column named "_data" at the given URI.
1625 *
1626 * @param uri The URI to be opened.
1627 * @param mode The file mode. May be "r" for read-only access,
1628 * "w" for write-only access (erasing whatever data is currently in
1629 * the file), "wa" for write-only access to append to any existing data,
1630 * "rw" for read and write access on any existing data, and "rwt" for read
1631 * and write access that truncates any existing file.
1632 *
1633 * @return Returns a new ParcelFileDescriptor that can be used by the
1634 * client to access the file.
1635 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001636 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1637 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1639 int count = (c != null) ? c.getCount() : 0;
1640 if (count != 1) {
1641 // If there is not exactly one result, throw an appropriate
1642 // exception.
1643 if (c != null) {
1644 c.close();
1645 }
1646 if (count == 0) {
1647 throw new FileNotFoundException("No entry for " + uri);
1648 }
1649 throw new FileNotFoundException("Multiple items at " + uri);
1650 }
1651
1652 c.moveToFirst();
1653 int i = c.getColumnIndex("_data");
1654 String path = (i >= 0 ? c.getString(i) : null);
1655 c.close();
1656 if (path == null) {
1657 throw new FileNotFoundException("Column _data not found.");
1658 }
1659
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001660 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 return ParcelFileDescriptor.open(new File(path), modeBits);
1662 }
1663
1664 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001665 * Called by a client to determine the types of data streams that this
1666 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001667 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001668 * of a particular type, return that MIME type if it matches the given
1669 * mimeTypeFilter. If it can perform type conversions, return an array
1670 * of all supported MIME types that match mimeTypeFilter.
1671 *
1672 * @param uri The data in the content provider being queried.
1673 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001674 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001675 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001676 * given mimeTypeFilter. Otherwise returns an array of all available
1677 * concrete MIME types.
1678 *
1679 * @see #getType(Uri)
1680 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001681 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001682 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001683 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001684 return null;
1685 }
1686
1687 /**
1688 * Called by a client to open a read-only stream containing data of a
1689 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1690 * except the file can only be read-only and the content provider may
1691 * perform data conversions to generate data of the desired type.
1692 *
1693 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001694 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001695 * {@link #openAssetFile(Uri, String)}.
1696 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001697 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001698 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001699 * <p>
1700 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1701 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001702 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001703 * <p class="note">For better interoperability with other applications, it is recommended
1704 * that for any URIs that can be opened, you also support queries on them
1705 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1706 * You may also want to support other common columns if you have additional meta-data
1707 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1708 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1709 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001710 * @param uri The data in the content provider being queried.
1711 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001712 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001713 * requirements; in this case the content provider will pick its best
1714 * type matching the pattern.
1715 * @param opts Additional options from the client. The definitions of
1716 * these are specific to the content provider being called.
1717 *
1718 * @return Returns a new AssetFileDescriptor from which the client can
1719 * read data of the desired type.
1720 *
1721 * @throws FileNotFoundException Throws FileNotFoundException if there is
1722 * no file associated with the given URI or the mode is invalid.
1723 * @throws SecurityException Throws SecurityException if the caller does
1724 * not have permission to access the data.
1725 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1726 * content provider does not support the requested MIME type.
1727 *
1728 * @see #getStreamTypes(Uri, String)
1729 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001730 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001731 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001732 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1733 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001734 if ("*/*".equals(mimeTypeFilter)) {
1735 // If they can take anything, the untyped open call is good enough.
1736 return openAssetFile(uri, "r");
1737 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001738 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001739 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001740 // Use old untyped open call if this provider has a type for this
1741 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001742 return openAssetFile(uri, "r");
1743 }
1744 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1745 }
1746
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001747
1748 /**
1749 * Called by a client to open a read-only stream containing data of a
1750 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1751 * except the file can only be read-only and the content provider may
1752 * perform data conversions to generate data of the desired type.
1753 *
1754 * <p>The default implementation compares the given mimeType against the
1755 * result of {@link #getType(Uri)} and, if they match, simply calls
1756 * {@link #openAssetFile(Uri, String)}.
1757 *
1758 * <p>See {@link ClipData} for examples of the use and implementation
1759 * of this method.
1760 * <p>
1761 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1762 * streaming of data.
1763 *
1764 * <p class="note">For better interoperability with other applications, it is recommended
1765 * that for any URIs that can be opened, you also support queries on them
1766 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1767 * You may also want to support other common columns if you have additional meta-data
1768 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1769 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1770 *
1771 * @param uri The data in the content provider being queried.
1772 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001773 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001774 * requirements; in this case the content provider will pick its best
1775 * type matching the pattern.
1776 * @param opts Additional options from the client. The definitions of
1777 * these are specific to the content provider being called.
1778 * @param signal A signal to cancel the operation in progress, or
1779 * {@code null} if none. For example, if you are downloading a
1780 * file from the network to service a "rw" mode request, you
1781 * should periodically call
1782 * {@link CancellationSignal#throwIfCanceled()} to check whether
1783 * the client has canceled the request and abort the download.
1784 *
1785 * @return Returns a new AssetFileDescriptor from which the client can
1786 * read data of the desired type.
1787 *
1788 * @throws FileNotFoundException Throws FileNotFoundException if there is
1789 * no file associated with the given URI or the mode is invalid.
1790 * @throws SecurityException Throws SecurityException if the caller does
1791 * not have permission to access the data.
1792 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1793 * content provider does not support the requested MIME type.
1794 *
1795 * @see #getStreamTypes(Uri, String)
1796 * @see #openAssetFile(Uri, String)
1797 * @see ClipDescription#compareMimeTypes(String, String)
1798 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001799 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1800 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1801 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001802 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1803 }
1804
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001805 /**
1806 * Interface to write a stream of data to a pipe. Use with
1807 * {@link ContentProvider#openPipeHelper}.
1808 */
1809 public interface PipeDataWriter<T> {
1810 /**
1811 * Called from a background thread to stream data out to a pipe.
1812 * Note that the pipe is blocking, so this thread can block on
1813 * writes for an arbitrary amount of time if the client is slow
1814 * at reading.
1815 *
1816 * @param output The pipe where data should be written. This will be
1817 * closed for you upon returning from this function.
1818 * @param uri The URI whose data is to be written.
1819 * @param mimeType The desired type of data to be written.
1820 * @param opts Options supplied by caller.
1821 * @param args Your own custom arguments.
1822 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001823 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1824 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001825 }
1826
1827 /**
1828 * A helper function for implementing {@link #openTypedAssetFile}, for
1829 * creating a data pipe and background thread allowing you to stream
1830 * generated data back to the client. This function returns a new
1831 * ParcelFileDescriptor that should be returned to the caller (the caller
1832 * is responsible for closing it).
1833 *
1834 * @param uri The URI whose data is to be written.
1835 * @param mimeType The desired type of data to be written.
1836 * @param opts Options supplied by caller.
1837 * @param args Your own custom arguments.
1838 * @param func Interface implementing the function that will actually
1839 * stream the data.
1840 * @return Returns a new ParcelFileDescriptor holding the read side of
1841 * the pipe. This should be returned to the caller for reading; the caller
1842 * is responsible for closing it when done.
1843 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001844 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1845 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1846 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001847 try {
1848 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1849
1850 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1851 @Override
1852 protected Object doInBackground(Object... params) {
1853 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1854 try {
1855 fds[1].close();
1856 } catch (IOException e) {
1857 Log.w(TAG, "Failure closing pipe", e);
1858 }
1859 return null;
1860 }
1861 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001862 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001863
1864 return fds[0];
1865 } catch (IOException e) {
1866 throw new FileNotFoundException("failure making pipe");
1867 }
1868 }
1869
1870 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 * Returns true if this instance is a temporary content provider.
1872 * @return true if this instance is a temporary content provider
1873 */
1874 protected boolean isTemporary() {
1875 return false;
1876 }
1877
1878 /**
1879 * Returns the Binder object for this provider.
1880 *
1881 * @return the Binder object for this provider
1882 * @hide
1883 */
Mathew Inwood1c77a112018-08-14 14:06:26 +01001884 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 public IContentProvider getIContentProvider() {
1886 return mTransport;
1887 }
1888
1889 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001890 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1891 * when directly instantiating the provider for testing.
1892 * @hide
1893 */
Mathew Inwood1c77a112018-08-14 14:06:26 +01001894 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001895 public void attachInfoForTesting(Context context, ProviderInfo info) {
1896 attachInfo(context, info, true);
1897 }
1898
1899 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 * After being instantiated, this is called to tell the content provider
1901 * about itself.
1902 *
1903 * @param context The context this provider is running in
1904 * @param info Registered information about this content provider
1905 */
1906 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001907 attachInfo(context, info, false);
1908 }
1909
1910 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001911 mNoPerms = testing;
1912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 /*
1914 * Only allow it to be set once, so after the content service gives
1915 * this to us clients can't change it.
1916 */
1917 if (mContext == null) {
1918 mContext = context;
Jeff Sharkey35f31cb2018-09-24 13:23:57 -06001919 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001920 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1921 Context.APP_OPS_SERVICE);
1922 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001923 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 if (info != null) {
1925 setReadPermission(info.readPermission);
1926 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001927 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001928 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001929 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001930 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932 ContentProvider.this.onCreate();
1933 }
1934 }
Fred Quintanace31b232009-05-04 16:01:15 -07001935
1936 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001937 * Override this to handle requests to perform a batch of operations, or the
1938 * default implementation will iterate over the operations and call
1939 * {@link ContentProviderOperation#apply} on each of them.
1940 * If all calls to {@link ContentProviderOperation#apply} succeed
1941 * then a {@link ContentProviderResult} array with as many
1942 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001943 * fail, it is up to the implementation how many of the others take effect.
1944 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001945 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1946 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001947 *
Fred Quintanace31b232009-05-04 16:01:15 -07001948 * @param operations the operations to apply
1949 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001950 * @throws OperationApplicationException thrown if any operation fails.
1951 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001952 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001953 public @NonNull ContentProviderResult[] applyBatch(
1954 @NonNull ArrayList<ContentProviderOperation> operations)
1955 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001956 final int numOperations = operations.size();
1957 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1958 for (int i = 0; i < numOperations; i++) {
1959 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001960 }
1961 return results;
1962 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001963
1964 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001965 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001966 * interfaces that are cheaper and/or unnatural for a table-like
1967 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001968 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001969 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1970 * on this entry into the content provider besides the basic ability for the application
1971 * to get access to the provider at all. For example, it has no idea whether the call
1972 * being executed may read or write data in the provider, so can't enforce those
1973 * individual permissions. Any implementation of this method <strong>must</strong>
1974 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1975 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001976 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1977 * @param arg provider-defined String argument. May be {@code null}.
1978 * @param extras provider-defined Bundle argument. May be {@code null}.
1979 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001980 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001981 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001982 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1983 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001984 return null;
1985 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001986
1987 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001988 * Implement this to shut down the ContentProvider instance. You can then
1989 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08001990 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001991 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001992 * Android normally handles ContentProvider startup and shutdown
1993 * automatically. You do not need to start up or shut down a
1994 * ContentProvider. When you invoke a test method on a ContentProvider,
1995 * however, a ContentProvider instance is started and keeps running after
1996 * the test finishes, even if a succeeding test instantiates another
1997 * ContentProvider. A conflict develops because the two instances are
1998 * usually running against the same underlying data source (for example, an
1999 * sqlite database).
2000 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002001 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002002 * Implementing shutDown() avoids this conflict by providing a way to
2003 * terminate the ContentProvider. This method can also prevent memory leaks
2004 * from multiple instantiations of the ContentProvider, and it can ensure
2005 * unit test isolation by allowing you to completely clean up the test
2006 * fixture before moving on to the next test.
2007 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002008 */
2009 public void shutdown() {
2010 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2011 "connections are gracefully shutdown");
2012 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002013
2014 /**
2015 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002016 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002017 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002018 * @param fd The raw file descriptor that the dump is being sent to.
2019 * @param writer The PrintWriter to which you should dump your state. This will be
2020 * closed for you after you return.
2021 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002022 */
2023 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2024 writer.println("nothing to dump");
2025 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002026
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002027 /** @hide */
Jeff Sharkey35f31cb2018-09-24 13:23:57 -06002028 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002029 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002030 if (!mSingleUser) {
2031 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2032 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2033 throw new SecurityException("trying to query a ContentProvider in user "
2034 + mContext.getUserId() + " with a uri belonging to user " + userId);
2035 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002036 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002037 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2038 String message = "The authority of the uri " + uri + " does not match the one of the "
2039 + "contentProvider: ";
2040 if (mAuthority != null) {
2041 message += mAuthority;
2042 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002043 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002044 }
2045 throw new SecurityException(message);
2046 }
Jeff Sharkey35f31cb2018-09-24 13:23:57 -06002047
2048 // Normalize the path by removing any empty path segments, which can be
2049 // a source of security issues.
2050 final String encodedPath = uri.getEncodedPath();
2051 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
2052 final Uri normalized = uri.buildUpon()
2053 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2054 Log.w(TAG, "Normalized " + uri + " to " + normalized
2055 + " to avoid possible security issues");
2056 return normalized;
2057 } else {
2058 return uri;
2059 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002060 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002061
2062 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002063 private Uri maybeGetUriWithoutUserId(Uri uri) {
2064 if (mSingleUser) {
2065 return uri;
2066 }
2067 return getUriWithoutUserId(uri);
2068 }
2069
2070 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002071 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2072 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002073 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002074 if (end == -1) return defaultUserId;
2075 String userIdString = auth.substring(0, end);
2076 try {
2077 return Integer.parseInt(userIdString);
2078 } catch (NumberFormatException e) {
2079 Log.w(TAG, "Error parsing userId.", e);
2080 return UserHandle.USER_NULL;
2081 }
2082 }
2083
2084 /** @hide */
2085 public static int getUserIdFromAuthority(String auth) {
2086 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2087 }
2088
2089 /** @hide */
2090 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2091 if (uri == null) return defaultUserId;
2092 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2093 }
2094
2095 /** @hide */
2096 public static int getUserIdFromUri(Uri uri) {
2097 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2098 }
2099
2100 /**
2101 * Removes userId part from authority string. Expects format:
2102 * userId@some.authority
2103 * If there is no userId in the authority, it symply returns the argument
2104 * @hide
2105 */
2106 public static String getAuthorityWithoutUserId(String auth) {
2107 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002108 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002109 return auth.substring(end+1);
2110 }
2111
2112 /** @hide */
2113 public static Uri getUriWithoutUserId(Uri uri) {
2114 if (uri == null) return null;
2115 Uri.Builder builder = uri.buildUpon();
2116 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2117 return builder.build();
2118 }
2119
2120 /** @hide */
2121 public static boolean uriHasUserId(Uri uri) {
2122 if (uri == null) return false;
2123 return !TextUtils.isEmpty(uri.getUserInfo());
2124 }
2125
2126 /** @hide */
Mathew Inwood1c77a112018-08-14 14:06:26 +01002127 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002128 public static Uri maybeAddUserId(Uri uri, int userId) {
2129 if (uri == null) return null;
2130 if (userId != UserHandle.USER_CURRENT
2131 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
2132 if (!uriHasUserId(uri)) {
2133 //We don't add the user Id if there's already one
2134 Uri.Builder builder = uri.buildUpon();
2135 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2136 return builder.build();
2137 }
2138 }
2139 return uri;
2140 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002141}