blob: f5339efb8d606fe40e9ad7e362e9022a9a47ed69 [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 Sharkey9664ff52018-08-03 17:08:04 -060024import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070025
Jeff Sharkey673db442015-06-11 19:30:57 -070026import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080027import android.annotation.Nullable;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010028import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080029import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070030import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.pm.ProviderInfo;
32import android.content.res.AssetFileDescriptor;
33import android.content.res.Configuration;
34import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070035import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.database.SQLException;
37import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070038import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.Binder;
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;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060047import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060049import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010050import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070051import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
53import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080054import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070056import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080057import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070058import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080059import java.util.Arrays;
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 Inwood5c0d3542018-08-14 13:54:31 +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 Inwood5c0d3542018-08-14 13:54:31 +0100117 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100118 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100119 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100120 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100121 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100123 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +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 Inwood5c0d3542018-08-14 13:54:31 +0100166 @UnsupportedAppUsage
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 Inwood5c0d3542018-08-14 13:54:31 +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) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100222 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.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700239 Cursor cursor;
240 final String original = setCallingPackage(callingPkg);
241 try {
242 cursor = ContentProvider.this.query(
243 uri, projection, queryArgs,
244 CancellationSignal.fromTransport(cancellationSignal));
245 } finally {
246 setCallingPackage(original);
247 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700248 if (cursor == null) {
249 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700250 }
251
252 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700253 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800254 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600255 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700256 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700257 try {
258 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800259 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700260 CancellationSignal.fromTransport(cancellationSignal));
261 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700262 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600263 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 }
266
Jeff Brown75ea64f2012-01-25 19:37:13 -0800267 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700269 // getCallingPackage() isn't available in getType(), as the javadoc states.
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100270 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100271 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600272 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
273 try {
274 return ContentProvider.this.getType(uri);
275 } finally {
276 Trace.traceEnd(TRACE_TAG_DATABASE);
277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 }
279
Jeff Brown75ea64f2012-01-25 19:37:13 -0800280 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800281 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100282 validateIncomingUri(uri);
283 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100284 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800285 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700286 final String original = setCallingPackage(callingPkg);
287 try {
288 return rejectInsert(uri, initialValues);
289 } finally {
290 setCallingPackage(original);
291 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800292 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600293 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700294 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700295 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100296 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700297 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700298 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600299 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
Jeff Brown75ea64f2012-01-25 19:37:13 -0800303 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100305 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100306 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800307 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800308 return 0;
309 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600310 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700311 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700312 try {
313 return ContentProvider.this.bulkInsert(uri, initialValues);
314 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700315 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600316 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319
Jeff Brown75ea64f2012-01-25 19:37:13 -0800320 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800321 public ContentProviderResult[] applyBatch(String callingPkg,
322 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700323 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100324 int numOperations = operations.size();
325 final int[] userIds = new int[numOperations];
326 for (int i = 0; i < numOperations; i++) {
327 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100328 Uri uri = operation.getUri();
329 validateIncomingUri(uri);
330 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100331 if (userIds[i] != UserHandle.USER_CURRENT) {
332 // Removing the user id from the uri.
333 operation = new ContentProviderOperation(operation, true);
334 operations.set(i, operation);
335 }
Fred Quintana89437372009-05-15 15:10:40 -0700336 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800337 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800338 != AppOpsManager.MODE_ALLOWED) {
339 throw new OperationApplicationException("App op not allowed", 0);
340 }
Fred Quintana89437372009-05-15 15:10:40 -0700341 }
Fred Quintana89437372009-05-15 15:10:40 -0700342 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800343 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800344 != AppOpsManager.MODE_ALLOWED) {
345 throw new OperationApplicationException("App op not allowed", 0);
346 }
Fred Quintana89437372009-05-15 15:10:40 -0700347 }
348 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600349 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700350 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700351 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100352 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800353 if (results != null) {
354 for (int i = 0; i < results.length ; i++) {
355 if (userIds[i] != UserHandle.USER_CURRENT) {
356 // Adding the userId to the uri.
357 results[i] = new ContentProviderResult(results[i], userIds[i]);
358 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100359 }
360 }
361 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700362 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700363 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600364 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700365 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700366 }
367
Jeff Brown75ea64f2012-01-25 19:37:13 -0800368 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800369 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100370 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100371 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800372 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800373 return 0;
374 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600375 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700376 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700377 try {
378 return ContentProvider.this.delete(uri, selection, selectionArgs);
379 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700380 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600381 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 }
384
Jeff Brown75ea64f2012-01-25 19:37:13 -0800385 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800386 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100388 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100389 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800390 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800391 return 0;
392 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600393 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700394 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700395 try {
396 return ContentProvider.this.update(uri, values, selection, selectionArgs);
397 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700398 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600399 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 }
402
Jeff Brown75ea64f2012-01-25 19:37:13 -0800403 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700404 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800405 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
406 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100407 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100408 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800409 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600410 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
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.openFile(
414 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
415 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700416 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600417 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
420
Jeff Brown75ea64f2012-01-25 19:37:13 -0800421 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700422 public AssetFileDescriptor openAssetFile(
423 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100425 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100426 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800427 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600428 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700429 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700430 try {
431 return ContentProvider.this.openAssetFile(
432 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
433 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700434 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600435 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 }
438
Jeff Brown75ea64f2012-01-25 19:37:13 -0800439 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800440 public Bundle call(
441 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600442 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600443 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700445 try {
446 return ContentProvider.this.call(method, arg, extras);
447 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700448 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600449 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700450 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800451 }
452
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700453 @Override
454 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700455 // getCallingPackage() isn't available in getType(), as the javadoc states.
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100456 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100457 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600458 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
459 try {
460 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
461 } finally {
462 Trace.traceEnd(TRACE_TAG_DATABASE);
463 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700464 }
465
466 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800467 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700468 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600469 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100470 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100471 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800472 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600473 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700474 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700475 try {
476 return ContentProvider.this.openTypedAssetFile(
477 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
478 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700479 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600480 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700481 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700482 }
483
Jeff Brown75ea64f2012-01-25 19:37:13 -0800484 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700485 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800486 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800487 }
488
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700489 @Override
490 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100491 validateIncomingUri(uri);
492 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100493 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800494 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700495 return null;
496 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600497 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700498 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700499 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100500 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700501 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700502 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600503 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700504 }
505 }
506
507 @Override
508 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100509 validateIncomingUri(uri);
510 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100511 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800512 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700513 return null;
514 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600515 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700516 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700517 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100518 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700519 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700520 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600521 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700522 }
523 }
524
Ben Lin1cf454f2016-11-10 13:50:54 -0800525 @Override
526 public boolean refresh(String callingPkg, Uri uri, Bundle args,
527 ICancellationSignal cancellationSignal) throws RemoteException {
528 validateIncomingUri(uri);
529 uri = getUriWithoutUserId(uri);
530 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
531 return false;
532 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600533 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800534 final String original = setCallingPackage(callingPkg);
535 try {
536 return ContentProvider.this.refresh(uri, args,
537 CancellationSignal.fromTransport(cancellationSignal));
538 } finally {
539 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600540 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800541 }
542 }
543
Dianne Hackbornff170242014-11-19 10:59:01 -0800544 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
545 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800546 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800547 if (enforceWritePermission(callingPkg, uri, callerToken)
548 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800549 throw new FileNotFoundException("App op not allowed");
550 }
551 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800552 if (enforceReadPermission(callingPkg, uri, callerToken)
553 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800554 throw new FileNotFoundException("App op not allowed");
555 }
556 }
557 }
558
Dianne Hackbornff170242014-11-19 10:59:01 -0800559 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
560 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700561 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
562 if (mode != MODE_ALLOWED) {
563 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800564 }
Svet Ganov99b60432015-06-27 13:15:22 -0700565
566 if (mReadOp != AppOpsManager.OP_NONE) {
567 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
568 }
569
Dianne Hackborn35654b62013-01-14 17:38:02 -0800570 return AppOpsManager.MODE_ALLOWED;
571 }
572
Dianne Hackbornff170242014-11-19 10:59:01 -0800573 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
574 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700575 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
576 if (mode != MODE_ALLOWED) {
577 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800578 }
Svet Ganov99b60432015-06-27 13:15:22 -0700579
580 if (mWriteOp != AppOpsManager.OP_NONE) {
581 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
582 }
583
Dianne Hackborn35654b62013-01-14 17:38:02 -0800584 return AppOpsManager.MODE_ALLOWED;
585 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700586 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800587
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100588 boolean checkUser(int pid, int uid, Context context) {
589 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700590 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100591 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
592 == PERMISSION_GRANTED;
593 }
594
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700595 /**
596 * Verify that calling app holds both the given permission and any app-op
597 * associated with that permission.
598 */
599 private int checkPermissionAndAppOp(String permission, String callingPkg,
600 IBinder callerToken) {
601 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
602 callerToken) != PERMISSION_GRANTED) {
603 return MODE_ERRORED;
604 }
605
606 final int permOp = AppOpsManager.permissionToOpCode(permission);
607 if (permOp != AppOpsManager.OP_NONE) {
608 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
609 }
610
611 return MODE_ALLOWED;
612 }
613
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700614 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700615 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800616 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700617 final Context context = getContext();
618 final int pid = Binder.getCallingPid();
619 final int uid = Binder.getCallingUid();
620 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700621 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700622
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700623 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700624 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700625 }
626
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100627 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700628 final String componentPerm = getReadPermission();
629 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700630 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
631 if (mode == MODE_ALLOWED) {
632 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700633 } else {
634 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700635 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700636 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700637 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700638
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700639 // track if unprotected read is allowed; any denied
640 // <path-permission> below removes this ability
641 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700642
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700643 final PathPermission[] pps = getPathPermissions();
644 if (pps != null) {
645 final String path = uri.getPath();
646 for (PathPermission pp : pps) {
647 final String pathPerm = pp.getReadPermission();
648 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700649 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
650 if (mode == MODE_ALLOWED) {
651 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700652 } else {
653 // any denied <path-permission> means we lose
654 // default <provider> access.
655 allowDefaultRead = false;
656 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700657 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700658 }
659 }
660 }
661 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700662
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700663 // if we passed <path-permission> checks above, and no default
664 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700665 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700667
668 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800669 final int callingUserId = UserHandle.getUserId(uid);
670 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
671 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800672 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
673 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700674 return MODE_ALLOWED;
675 }
676
677 // If the worst denial we found above was ignored, then pass that
678 // ignored through; otherwise we assume it should be a real error below.
679 if (strongestMode == MODE_IGNORED) {
680 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700681 }
682
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600683 final String suffix;
684 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
685 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
686 } else if (mExported) {
687 suffix = " requires " + missingPerm + ", or grantUriPermission()";
688 } else {
689 suffix = " requires the provider be exported, or grantUriPermission()";
690 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700691 throw new SecurityException("Permission Denial: reading "
692 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600693 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700694 }
695
696 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700697 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800698 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700699 final Context context = getContext();
700 final int pid = Binder.getCallingPid();
701 final int uid = Binder.getCallingUid();
702 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700703 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700704
705 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700706 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700707 }
708
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100709 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700710 final String componentPerm = getWritePermission();
711 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700712 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
713 if (mode == MODE_ALLOWED) {
714 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700715 } else {
716 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700717 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700718 }
719 }
720
721 // track if unprotected write is allowed; any denied
722 // <path-permission> below removes this ability
723 boolean allowDefaultWrite = (componentPerm == null);
724
725 final PathPermission[] pps = getPathPermissions();
726 if (pps != null) {
727 final String path = uri.getPath();
728 for (PathPermission pp : pps) {
729 final String pathPerm = pp.getWritePermission();
730 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700731 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
732 if (mode == MODE_ALLOWED) {
733 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700734 } else {
735 // any denied <path-permission> means we lose
736 // default <provider> access.
737 allowDefaultWrite = false;
738 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700739 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700740 }
741 }
742 }
743 }
744
745 // if we passed <path-permission> checks above, and no default
746 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700747 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700748 }
749
750 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800751 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
752 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700753 return MODE_ALLOWED;
754 }
755
756 // If the worst denial we found above was ignored, then pass that
757 // ignored through; otherwise we assume it should be a real error below.
758 if (strongestMode == MODE_IGNORED) {
759 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700760 }
761
762 final String failReason = mExported
763 ? " requires " + missingPerm + ", or grantUriPermission()"
764 : " requires the provider be exported, or grantUriPermission()";
765 throw new SecurityException("Permission Denial: writing "
766 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
767 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700771 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800772 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 * constructor.
774 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700775 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 return mContext;
777 }
778
779 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700780 * Set the calling package, returning the current value (or {@code null})
781 * which can be used later to restore the previous state.
782 */
783 private String setCallingPackage(String callingPackage) {
784 final String original = mCallingPackage.get();
785 mCallingPackage.set(callingPackage);
786 return original;
787 }
788
789 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700790 * Return the package name of the caller that initiated the request being
791 * processed on the current thread. The returned package will have been
792 * verified to belong to the calling UID. Returns {@code null} if not
793 * currently processing a request.
794 * <p>
795 * This will always return {@code null} when processing
796 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
797 *
798 * @see Binder#getCallingUid()
799 * @see Context#grantUriPermission(String, Uri, int)
800 * @throws SecurityException if the calling package doesn't belong to the
801 * calling UID.
802 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700803 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700804 final String pkg = mCallingPackage.get();
805 if (pkg != null) {
806 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
807 }
808 return pkg;
809 }
810
811 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100812 * Change the authorities of the ContentProvider.
813 * This is normally set for you from its manifest information when the provider is first
814 * created.
815 * @hide
816 * @param authorities the semi-colon separated authorities of the ContentProvider.
817 */
818 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100819 if (authorities != null) {
820 if (authorities.indexOf(';') == -1) {
821 mAuthority = authorities;
822 mAuthorities = null;
823 } else {
824 mAuthority = null;
825 mAuthorities = authorities.split(";");
826 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100827 }
828 }
829
830 /** @hide */
831 protected final boolean matchesOurAuthorities(String authority) {
832 if (mAuthority != null) {
833 return mAuthority.equals(authority);
834 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100835 if (mAuthorities != null) {
836 int length = mAuthorities.length;
837 for (int i = 0; i < length; i++) {
838 if (mAuthorities[i].equals(authority)) return true;
839 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100840 }
841 return false;
842 }
843
844
845 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 * Change the permission required to read data from the content
847 * provider. This is normally set for you from its manifest information
848 * when the provider is first created.
849 *
850 * @param permission Name of the permission required for read-only access.
851 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700852 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 mReadPermission = permission;
854 }
855
856 /**
857 * Return the name of the permission required for read-only access to
858 * this content provider. This method can be called from multiple
859 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800860 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
861 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700863 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 return mReadPermission;
865 }
866
867 /**
868 * Change the permission required to read and write data in the content
869 * provider. This is normally set for you from its manifest information
870 * when the provider is first created.
871 *
872 * @param permission Name of the permission required for read/write access.
873 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700874 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 mWritePermission = permission;
876 }
877
878 /**
879 * Return the name of the permission required for read/write access to
880 * this content provider. This method can be called from multiple
881 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800882 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
883 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700885 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 return mWritePermission;
887 }
888
889 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700890 * Change the path-based permission required to read and/or write data in
891 * the content provider. This is normally set for you from its manifest
892 * information when the provider is first created.
893 *
894 * @param permissions Array of path permission descriptions.
895 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700896 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700897 mPathPermissions = permissions;
898 }
899
900 /**
901 * Return the path-based permissions required for read and/or write access to
902 * this content provider. This method can be called from multiple
903 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800904 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
905 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700906 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700907 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700908 return mPathPermissions;
909 }
910
Dianne Hackborn35654b62013-01-14 17:38:02 -0800911 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100912 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800913 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800914 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800915 mTransport.mReadOp = readOp;
916 mTransport.mWriteOp = writeOp;
917 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800918 }
919
Dianne Hackborn961321f2013-02-05 17:22:41 -0800920 /** @hide */
921 public AppOpsManager getAppOpsManager() {
922 return mTransport.mAppOpsManager;
923 }
924
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700925 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700926 * Implement this to initialize your content provider on startup.
927 * This method is called for all registered content providers on the
928 * application main thread at application launch time. It must not perform
929 * lengthy operations, or application startup will be delayed.
930 *
931 * <p>You should defer nontrivial initialization (such as opening,
932 * upgrading, and scanning databases) until the content provider is used
933 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
934 * keeps application startup fast, avoids unnecessary work if the provider
935 * turns out not to be needed, and stops database errors (such as a full
936 * disk) from halting application launch.
937 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700938 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700939 * is a helpful utility class that makes it easy to manage databases,
940 * and will automatically defer opening until first use. If you do use
941 * SQLiteOpenHelper, make sure to avoid calling
942 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
943 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
944 * from this method. (Instead, override
945 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
946 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 *
948 * @return true if the provider was successfully loaded, false otherwise
949 */
950 public abstract boolean onCreate();
951
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700952 /**
953 * {@inheritDoc}
954 * This method is always called on the application main thread, and must
955 * not perform lengthy operations.
956 *
957 * <p>The default content provider implementation does nothing.
958 * Override this method to take appropriate action.
959 * (Content providers do not usually care about things like screen
960 * orientation, but may want to know about locale changes.)
961 */
Steve McKayea93fe72016-12-02 11:35:35 -0800962 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 public void onConfigurationChanged(Configuration newConfig) {
964 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700965
966 /**
967 * {@inheritDoc}
968 * This method is always called on the application main thread, and must
969 * not perform lengthy operations.
970 *
971 * <p>The default content provider implementation does nothing.
972 * Subclasses may override this method to take appropriate action.
973 */
Steve McKayea93fe72016-12-02 11:35:35 -0800974 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 public void onLowMemory() {
976 }
977
Steve McKayea93fe72016-12-02 11:35:35 -0800978 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700979 public void onTrimMemory(int level) {
980 }
981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700983 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800984 *
985 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
986 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
987 * implementation of this method.
988 *
989 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800990 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
991 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 * <p>
993 * Example client call:<p>
994 * <pre>// Request a specific record.
995 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000996 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 projection, // Which columns to return.
998 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000999 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 People.NAME + " ASC"); // Sort order.</pre>
1001 * Example implementation:<p>
1002 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1003 // proper SQL syntax for us.
1004 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1005
1006 // Set the table we're querying.
1007 qBuilder.setTables(DATABASE_TABLE_NAME);
1008
1009 // If the query ends in a specific record number, we're
1010 // being asked for a specific record, so set the
1011 // WHERE clause in our query.
1012 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1013 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1014 }
1015
1016 // Make the query.
1017 Cursor c = qBuilder.query(mDb,
1018 projection,
1019 selection,
1020 selectionArgs,
1021 groupBy,
1022 having,
1023 sortOrder);
1024 c.setNotificationUri(getContext().getContentResolver(), uri);
1025 return c;</pre>
1026 *
1027 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001028 * if the client is requesting a specific record, the URI will end in a record number
1029 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1030 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001032 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001034 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001035 * @param selectionArgs You may include ?s in selection, which will be replaced by
1036 * the values from selectionArgs, in order that they appear in the selection.
1037 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001039 * If {@code null} then the provider is free to define the sort order.
1040 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001042 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1043 @Nullable String selection, @Nullable String[] selectionArgs,
1044 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045
Fred Quintana5bba6322009-10-05 14:21:12 -07001046 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001047 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001048 *
1049 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1050 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1051 *
1052 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001053 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1054 * and Threads</a>.
1055 * <p>
1056 * Example client call:<p>
1057 * <pre>// Request a specific record.
1058 * Cursor managedCursor = managedQuery(
1059 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1060 projection, // Which columns to return.
1061 null, // WHERE clause.
1062 null, // WHERE clause value substitution
1063 People.NAME + " ASC"); // Sort order.</pre>
1064 * Example implementation:<p>
1065 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1066 // proper SQL syntax for us.
1067 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1068
1069 // Set the table we're querying.
1070 qBuilder.setTables(DATABASE_TABLE_NAME);
1071
1072 // If the query ends in a specific record number, we're
1073 // being asked for a specific record, so set the
1074 // WHERE clause in our query.
1075 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1076 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1077 }
1078
1079 // Make the query.
1080 Cursor c = qBuilder.query(mDb,
1081 projection,
1082 selection,
1083 selectionArgs,
1084 groupBy,
1085 having,
1086 sortOrder);
1087 c.setNotificationUri(getContext().getContentResolver(), uri);
1088 return c;</pre>
1089 * <p>
1090 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001091 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1092 * signal to ensure correct operation on older versions of the Android Framework in
1093 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001094 *
1095 * @param uri The URI to query. This will be the full URI sent by the client;
1096 * if the client is requesting a specific record, the URI will end in a record number
1097 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1098 * that _id value.
1099 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001100 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001101 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001102 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001103 * @param selectionArgs You may include ?s in selection, which will be replaced by
1104 * the values from selectionArgs, in order that they appear in the selection.
1105 * The values will be bound as Strings.
1106 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001107 * If {@code null} then the provider is free to define the sort order.
1108 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001109 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001110 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001111 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001112 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001113 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1114 @Nullable String selection, @Nullable String[] selectionArgs,
1115 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001116 return query(uri, projection, selection, selectionArgs, sortOrder);
1117 }
1118
1119 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001120 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1121 * Arguments may include traditional SQL style query arguments. When present these
1122 * should be handled according to the contract established in
1123 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1124 *
1125 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001126 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1127 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1128 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001129 *
Steve McKay76b27702017-04-24 12:07:53 -07001130 * <p>This method can be called from multiple threads, as described in
1131 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1132 * and Threads</a>.
1133 *
1134 * <p>
1135 * Example client call:<p>
1136 * <pre>// Request 20 records starting at row index 30.
1137 Bundle queryArgs = new Bundle();
1138 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1139 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1140
1141 Cursor cursor = getContentResolver().query(
1142 contentUri, // Content Uri is specific to individual content providers.
1143 projection, // String[] describing which columns to return.
1144 queryArgs, // Query arguments.
1145 null); // Cancellation signal.</pre>
1146 *
1147 * Example implementation:<p>
1148 * <pre>
1149
1150 int recordsetSize = 0x1000; // Actual value is implementation specific.
1151 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1152
1153 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1154 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1155
1156 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1157
1158 // Calculate the number of items to include in the cursor.
1159 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1160
1161 // Build the paged result set....
1162 for (int i = offset; i < offset + numItems; i++) {
1163 // populate row from your data.
1164 }
1165
1166 Bundle extras = new Bundle();
1167 c.setExtras(extras);
1168
1169 // Any QUERY_ARG_* key may be included if honored.
1170 // In an actual implementation, include only keys that are both present in queryArgs
1171 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1172 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1173 // then QUERY_ARG_OFFSET should be omitted.
1174 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1175 ContentResolver.QUERY_ARG_OFFSET,
1176 ContentResolver.QUERY_ARG_LIMIT
1177 });
1178
1179 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1180
1181 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1182
1183 return cursor;</pre>
1184 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001185 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1186 * implementation details.
1187 *
1188 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001189 * @param projection The list of columns to put into the cursor.
1190 * If {@code null} provide a default set of columns.
1191 * @param queryArgs A Bundle containing all additional information necessary for the query.
1192 * Values in the Bundle may include SQL style arguments.
1193 * @param cancellationSignal A signal to cancel the operation in progress,
1194 * or {@code null}.
1195 * @return a Cursor or {@code null}.
1196 */
1197 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1198 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1199 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001200
Steve McKayd7ece9f2017-01-12 16:59:59 -08001201 // if client doesn't supply an SQL sort order argument, attempt to build one from
1202 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001203 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001204 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1205 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1206 }
1207
Steve McKayea93fe72016-12-02 11:35:35 -08001208 return query(
1209 uri,
1210 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001211 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1212 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1213 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001214 cancellationSignal);
1215 }
1216
1217 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001218 * Implement this to handle requests for the MIME type of the data at the
1219 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 * <code>vnd.android.cursor.item</code> for a single record,
1221 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001222 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001223 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1224 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001226 * <p>Note that there are no permissions needed for an application to
1227 * access this information; if your content provider requires read and/or
1228 * write permissions, or is not exported, all applications can still call
1229 * this method regardless of their access permissions. This allows them
1230 * to retrieve the MIME type for a URI when dispatching intents.
1231 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001233 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001235 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236
1237 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001238 * Implement this to support canonicalization of URIs that refer to your
1239 * content provider. A canonical URI is one that can be transported across
1240 * devices, backup/restore, and other contexts, and still be able to refer
1241 * to the same data item. Typically this is implemented by adding query
1242 * params to the URI allowing the content provider to verify that an incoming
1243 * canonical URI references the same data as it was originally intended for and,
1244 * if it doesn't, to find that data (if it exists) in the current environment.
1245 *
1246 * <p>For example, if the content provider holds people and a normal URI in it
1247 * is created with a row index into that people database, the cananical representation
1248 * may have an additional query param at the end which specifies the name of the
1249 * person it is intended for. Later calls into the provider with that URI will look
1250 * up the row of that URI's base index and, if it doesn't match or its entry's
1251 * name doesn't match the name in the query param, perform a query on its database
1252 * to find the correct row to operate on.</p>
1253 *
1254 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1255 * URIs (including this one) must perform this verification and recovery of any
1256 * canonical URIs they receive. In addition, you must also implement
1257 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1258 *
1259 * <p>The default implementation of this method returns null, indicating that
1260 * canonical URIs are not supported.</p>
1261 *
1262 * @param url The Uri to canonicalize.
1263 *
1264 * @return Return the canonical representation of <var>url</var>, or null if
1265 * canonicalization of that Uri is not supported.
1266 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001267 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001268 return null;
1269 }
1270
1271 /**
1272 * Remove canonicalization from canonical URIs previously returned by
1273 * {@link #canonicalize}. For example, if your implementation is to add
1274 * a query param to canonicalize a URI, this method can simply trip any
1275 * query params on the URI. The default implementation always returns the
1276 * same <var>url</var> that was passed in.
1277 *
1278 * @param url The Uri to remove any canonicalization from.
1279 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001280 * @return Return the non-canonical representation of <var>url</var>, return
1281 * the <var>url</var> as-is if there is nothing to do, or return null if
1282 * the data identified by the canonical representation can not be found in
1283 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001284 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001285 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001286 return url;
1287 }
1288
1289 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001290 * Implement this to support refresh of content identified by {@code uri}. By default, this
1291 * method returns false; providers who wish to implement this should return true to signal the
1292 * client that the provider has tried refreshing with its own implementation.
1293 * <p>
1294 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1295 * <p>
1296 * Client code should only invoke this method when there is a strong indication (such as a user
1297 * initiated pull to refresh gesture) that the content is stale.
1298 * <p>
1299 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1300 * notifications when content changes.
1301 *
1302 * @param uri The Uri identifying the data to refresh.
1303 * @param args Additional options from the client. The definitions of these are specific to the
1304 * content provider being called.
1305 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1306 * none. For example, if you called refresh on a particular uri, you should call
1307 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1308 * canceled the refresh request.
1309 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001310 */
1311 public boolean refresh(Uri uri, @Nullable Bundle args,
1312 @Nullable CancellationSignal cancellationSignal) {
1313 return false;
1314 }
1315
1316 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001317 * @hide
1318 * Implementation when a caller has performed an insert on the content
1319 * provider, but that call has been rejected for the operation given
1320 * to {@link #setAppOps(int, int)}. The default implementation simply
1321 * returns a dummy URI that is the base URI with a 0 path element
1322 * appended.
1323 */
1324 public Uri rejectInsert(Uri uri, ContentValues values) {
1325 // If not allowed, we need to return some reasonable URI. Maybe the
1326 // content provider should be responsible for this, but for now we
1327 // will just return the base URI with a dummy '0' tagged on to it.
1328 // You shouldn't be able to read if you can't write, anyway, so it
1329 // shouldn't matter much what is returned.
1330 return uri.buildUpon().appendPath("0").build();
1331 }
1332
1333 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001334 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1336 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001337 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001338 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1339 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001340 * @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 -08001341 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001342 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 * @return The URI for the newly inserted item.
1344 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001345 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346
1347 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001348 * Override this to handle requests to insert a set of new rows, or the
1349 * default implementation will iterate over the values and call
1350 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1352 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001353 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001354 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1355 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 *
1357 * @param uri The content:// URI of the insertion request.
1358 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001359 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 * @return The number of values that were inserted.
1361 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001362 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 int numValues = values.length;
1364 for (int i = 0; i < numValues; i++) {
1365 insert(uri, values[i]);
1366 }
1367 return numValues;
1368 }
1369
1370 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001371 * Implement this to handle requests to delete one or more rows.
1372 * The implementation should apply the selection clause when performing
1373 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001374 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001376 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001377 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1378 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 *
1380 * <p>The implementation is responsible for parsing out a row ID at the end
1381 * of the URI, if a specific row is being deleted. That is, the client would
1382 * pass in <code>content://contacts/people/22</code> and the implementation is
1383 * responsible for parsing the record number (22) when creating a SQL statement.
1384 *
1385 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1386 * @param selection An optional restriction to apply to rows when deleting.
1387 * @return The number of rows affected.
1388 * @throws SQLException
1389 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001390 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1391 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392
1393 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001394 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001395 * The implementation should update all rows matching the selection
1396 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1398 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001399 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001400 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1401 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 *
1403 * @param uri The URI to query. This can potentially have a record ID if this
1404 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001405 * @param values A set of column_name/value pairs to update in the database.
1406 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 * @param selection An optional filter to match rows to update.
1408 * @return the number of rows affected.
1409 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001410 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001411 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412
1413 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001414 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001415 * The default implementation always throws {@link FileNotFoundException}.
1416 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001417 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1418 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001419 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001420 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1421 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001422 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 *
1424 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1425 * their responsibility to close it when done. That is, the implementation
1426 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001427 * <p>
1428 * If opened with the exclusive "r" or "w" modes, the returned
1429 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1430 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1431 * supports seeking.
1432 * <p>
1433 * If you need to detect when the returned ParcelFileDescriptor has been
1434 * closed, or if the remote process has crashed or encountered some other
1435 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1436 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1437 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1438 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001439 * <p>
1440 * If you need to return a large file that isn't backed by a real file on
1441 * disk, such as a file on a network share or cloud storage service,
1442 * consider using
1443 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1444 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001446 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1447 * to return the appropriate MIME type for the data returned here with
1448 * the same URI. This will allow intent resolution to automatically determine the data MIME
1449 * type and select the appropriate matching targets as part of its operation.</p>
1450 *
1451 * <p class="note">For better interoperability with other applications, it is recommended
1452 * that for any URIs that can be opened, you also support queries on them
1453 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1454 * You may also want to support other common columns if you have additional meta-data
1455 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1456 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1457 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 * @param uri The URI whose file is to be opened.
1459 * @param mode Access mode for the file. May be "r" for read-only access,
1460 * "rw" for read and write access, or "rwt" for read and write access
1461 * that truncates any existing file.
1462 *
1463 * @return Returns a new ParcelFileDescriptor which you can use to access
1464 * the file.
1465 *
1466 * @throws FileNotFoundException Throws FileNotFoundException if there is
1467 * no file associated with the given URI or the mode is invalid.
1468 * @throws SecurityException Throws SecurityException if the caller does
1469 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001470 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 * @see #openAssetFile(Uri, String)
1472 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001473 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001474 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001475 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001476 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 throws FileNotFoundException {
1478 throw new FileNotFoundException("No files supported by provider at "
1479 + uri);
1480 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001483 * Override this to handle requests to open a file blob.
1484 * The default implementation always throws {@link FileNotFoundException}.
1485 * This method can be called from multiple threads, as described in
1486 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1487 * and Threads</a>.
1488 *
1489 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1490 * to the caller. This way large data (such as images and documents) can be
1491 * returned without copying the content.
1492 *
1493 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1494 * their responsibility to close it when done. That is, the implementation
1495 * of this method should create a new ParcelFileDescriptor for each call.
1496 * <p>
1497 * If opened with the exclusive "r" or "w" modes, the returned
1498 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1499 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1500 * supports seeking.
1501 * <p>
1502 * If you need to detect when the returned ParcelFileDescriptor has been
1503 * closed, or if the remote process has crashed or encountered some other
1504 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1505 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1506 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1507 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1508 *
1509 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1510 * to return the appropriate MIME type for the data returned here with
1511 * the same URI. This will allow intent resolution to automatically determine the data MIME
1512 * type and select the appropriate matching targets as part of its operation.</p>
1513 *
1514 * <p class="note">For better interoperability with other applications, it is recommended
1515 * that for any URIs that can be opened, you also support queries on them
1516 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1517 * You may also want to support other common columns if you have additional meta-data
1518 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1519 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1520 *
1521 * @param uri The URI whose file is to be opened.
1522 * @param mode Access mode for the file. May be "r" for read-only access,
1523 * "w" for write-only access, "rw" for read and write access, or
1524 * "rwt" for read and write access that truncates any existing
1525 * file.
1526 * @param signal A signal to cancel the operation in progress, or
1527 * {@code null} if none. For example, if you are downloading a
1528 * file from the network to service a "rw" mode request, you
1529 * should periodically call
1530 * {@link CancellationSignal#throwIfCanceled()} to check whether
1531 * the client has canceled the request and abort the download.
1532 *
1533 * @return Returns a new ParcelFileDescriptor which you can use to access
1534 * the file.
1535 *
1536 * @throws FileNotFoundException Throws FileNotFoundException if there is
1537 * no file associated with the given URI or the mode is invalid.
1538 * @throws SecurityException Throws SecurityException if the caller does
1539 * not have permission to access the file.
1540 *
1541 * @see #openAssetFile(Uri, String)
1542 * @see #openFileHelper(Uri, String)
1543 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001544 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001545 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001546 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1547 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001548 return openFile(uri, mode);
1549 }
1550
1551 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 * This is like {@link #openFile}, but can be implemented by providers
1553 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001554 * inside of their .apk.
1555 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001556 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1557 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001558 *
1559 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001560 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001561 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1563 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1564 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001565 * <p>
1566 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1567 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001568 *
1569 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 * should create the AssetFileDescriptor with
1571 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001572 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001574 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1575 * to return the appropriate MIME type for the data returned here with
1576 * the same URI. This will allow intent resolution to automatically determine the data MIME
1577 * type and select the appropriate matching targets as part of its operation.</p>
1578 *
1579 * <p class="note">For better interoperability with other applications, it is recommended
1580 * that for any URIs that can be opened, you also support queries on them
1581 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1582 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 * @param uri The URI whose file is to be opened.
1584 * @param mode Access mode for the file. May be "r" for read-only access,
1585 * "w" for write-only access (erasing whatever data is currently in
1586 * the file), "wa" for write-only access to append to any existing data,
1587 * "rw" for read and write access on any existing data, and "rwt" for read
1588 * and write access that truncates any existing file.
1589 *
1590 * @return Returns a new AssetFileDescriptor which you can use to access
1591 * the file.
1592 *
1593 * @throws FileNotFoundException Throws FileNotFoundException if there is
1594 * no file associated with the given URI or the mode is invalid.
1595 * @throws SecurityException Throws SecurityException if the caller does
1596 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001597 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 * @see #openFile(Uri, String)
1599 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001600 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001602 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 throws FileNotFoundException {
1604 ParcelFileDescriptor fd = openFile(uri, mode);
1605 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1606 }
1607
1608 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001609 * This is like {@link #openFile}, but can be implemented by providers
1610 * that need to be able to return sub-sections of files, often assets
1611 * inside of their .apk.
1612 * This method can be called from multiple threads, as described in
1613 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1614 * and Threads</a>.
1615 *
1616 * <p>If you implement this, your clients must be able to deal with such
1617 * file slices, either directly with
1618 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1619 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1620 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1621 * methods.
1622 * <p>
1623 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1624 * streaming of data.
1625 *
1626 * <p class="note">If you are implementing this to return a full file, you
1627 * should create the AssetFileDescriptor with
1628 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1629 * applications that cannot handle sub-sections of files.</p>
1630 *
1631 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1632 * to return the appropriate MIME type for the data returned here with
1633 * the same URI. This will allow intent resolution to automatically determine the data MIME
1634 * type and select the appropriate matching targets as part of its operation.</p>
1635 *
1636 * <p class="note">For better interoperability with other applications, it is recommended
1637 * that for any URIs that can be opened, you also support queries on them
1638 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1639 *
1640 * @param uri The URI whose file is to be opened.
1641 * @param mode Access mode for the file. May be "r" for read-only access,
1642 * "w" for write-only access (erasing whatever data is currently in
1643 * the file), "wa" for write-only access to append to any existing data,
1644 * "rw" for read and write access on any existing data, and "rwt" for read
1645 * and write access that truncates any existing file.
1646 * @param signal A signal to cancel the operation in progress, or
1647 * {@code null} if none. For example, if you are downloading a
1648 * file from the network to service a "rw" mode request, you
1649 * should periodically call
1650 * {@link CancellationSignal#throwIfCanceled()} to check whether
1651 * the client has canceled the request and abort the download.
1652 *
1653 * @return Returns a new AssetFileDescriptor which you can use to access
1654 * the file.
1655 *
1656 * @throws FileNotFoundException Throws FileNotFoundException if there is
1657 * no file associated with the given URI or the mode is invalid.
1658 * @throws SecurityException Throws SecurityException if the caller does
1659 * not have permission to access the file.
1660 *
1661 * @see #openFile(Uri, String)
1662 * @see #openFileHelper(Uri, String)
1663 * @see #getType(android.net.Uri)
1664 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001665 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1666 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001667 return openAssetFile(uri, mode);
1668 }
1669
1670 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 * Convenience for subclasses that wish to implement {@link #openFile}
1672 * by looking up a column named "_data" at the given URI.
1673 *
1674 * @param uri The URI to be opened.
1675 * @param mode The file mode. May be "r" for read-only access,
1676 * "w" for write-only access (erasing whatever data is currently in
1677 * the file), "wa" for write-only access to append to any existing data,
1678 * "rw" for read and write access on any existing data, and "rwt" for read
1679 * and write access that truncates any existing file.
1680 *
1681 * @return Returns a new ParcelFileDescriptor that can be used by the
1682 * client to access the file.
1683 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001684 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1685 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1687 int count = (c != null) ? c.getCount() : 0;
1688 if (count != 1) {
1689 // If there is not exactly one result, throw an appropriate
1690 // exception.
1691 if (c != null) {
1692 c.close();
1693 }
1694 if (count == 0) {
1695 throw new FileNotFoundException("No entry for " + uri);
1696 }
1697 throw new FileNotFoundException("Multiple items at " + uri);
1698 }
1699
1700 c.moveToFirst();
1701 int i = c.getColumnIndex("_data");
1702 String path = (i >= 0 ? c.getString(i) : null);
1703 c.close();
1704 if (path == null) {
1705 throw new FileNotFoundException("Column _data not found.");
1706 }
1707
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001708 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 return ParcelFileDescriptor.open(new File(path), modeBits);
1710 }
1711
1712 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001713 * Called by a client to determine the types of data streams that this
1714 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001715 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001716 * of a particular type, return that MIME type if it matches the given
1717 * mimeTypeFilter. If it can perform type conversions, return an array
1718 * of all supported MIME types that match mimeTypeFilter.
1719 *
1720 * @param uri The data in the content provider being queried.
1721 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001722 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001723 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001724 * given mimeTypeFilter. Otherwise returns an array of all available
1725 * concrete MIME types.
1726 *
1727 * @see #getType(Uri)
1728 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001729 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001730 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001731 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001732 return null;
1733 }
1734
1735 /**
1736 * Called by a client to open a read-only stream containing data of a
1737 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1738 * except the file can only be read-only and the content provider may
1739 * perform data conversions to generate data of the desired type.
1740 *
1741 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001742 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001743 * {@link #openAssetFile(Uri, String)}.
1744 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001745 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001746 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001747 * <p>
1748 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1749 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001750 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001751 * <p class="note">For better interoperability with other applications, it is recommended
1752 * that for any URIs that can be opened, you also support queries on them
1753 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1754 * You may also want to support other common columns if you have additional meta-data
1755 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1756 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1757 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001758 * @param uri The data in the content provider being queried.
1759 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001760 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001761 * requirements; in this case the content provider will pick its best
1762 * type matching the pattern.
1763 * @param opts Additional options from the client. The definitions of
1764 * these are specific to the content provider being called.
1765 *
1766 * @return Returns a new AssetFileDescriptor from which the client can
1767 * read data of the desired type.
1768 *
1769 * @throws FileNotFoundException Throws FileNotFoundException if there is
1770 * no file associated with the given URI or the mode is invalid.
1771 * @throws SecurityException Throws SecurityException if the caller does
1772 * not have permission to access the data.
1773 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1774 * content provider does not support the requested MIME type.
1775 *
1776 * @see #getStreamTypes(Uri, String)
1777 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001778 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001779 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001780 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1781 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001782 if ("*/*".equals(mimeTypeFilter)) {
1783 // If they can take anything, the untyped open call is good enough.
1784 return openAssetFile(uri, "r");
1785 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001786 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001787 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001788 // Use old untyped open call if this provider has a type for this
1789 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001790 return openAssetFile(uri, "r");
1791 }
1792 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1793 }
1794
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001795
1796 /**
1797 * Called by a client to open a read-only stream containing data of a
1798 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1799 * except the file can only be read-only and the content provider may
1800 * perform data conversions to generate data of the desired type.
1801 *
1802 * <p>The default implementation compares the given mimeType against the
1803 * result of {@link #getType(Uri)} and, if they match, simply calls
1804 * {@link #openAssetFile(Uri, String)}.
1805 *
1806 * <p>See {@link ClipData} for examples of the use and implementation
1807 * of this method.
1808 * <p>
1809 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1810 * streaming of data.
1811 *
1812 * <p class="note">For better interoperability with other applications, it is recommended
1813 * that for any URIs that can be opened, you also support queries on them
1814 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1815 * You may also want to support other common columns if you have additional meta-data
1816 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1817 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1818 *
1819 * @param uri The data in the content provider being queried.
1820 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001821 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001822 * requirements; in this case the content provider will pick its best
1823 * type matching the pattern.
1824 * @param opts Additional options from the client. The definitions of
1825 * these are specific to the content provider being called.
1826 * @param signal A signal to cancel the operation in progress, or
1827 * {@code null} if none. For example, if you are downloading a
1828 * file from the network to service a "rw" mode request, you
1829 * should periodically call
1830 * {@link CancellationSignal#throwIfCanceled()} to check whether
1831 * the client has canceled the request and abort the download.
1832 *
1833 * @return Returns a new AssetFileDescriptor from which the client can
1834 * read data of the desired type.
1835 *
1836 * @throws FileNotFoundException Throws FileNotFoundException if there is
1837 * no file associated with the given URI or the mode is invalid.
1838 * @throws SecurityException Throws SecurityException if the caller does
1839 * not have permission to access the data.
1840 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1841 * content provider does not support the requested MIME type.
1842 *
1843 * @see #getStreamTypes(Uri, String)
1844 * @see #openAssetFile(Uri, String)
1845 * @see ClipDescription#compareMimeTypes(String, String)
1846 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001847 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1848 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1849 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001850 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1851 }
1852
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001853 /**
1854 * Interface to write a stream of data to a pipe. Use with
1855 * {@link ContentProvider#openPipeHelper}.
1856 */
1857 public interface PipeDataWriter<T> {
1858 /**
1859 * Called from a background thread to stream data out to a pipe.
1860 * Note that the pipe is blocking, so this thread can block on
1861 * writes for an arbitrary amount of time if the client is slow
1862 * at reading.
1863 *
1864 * @param output The pipe where data should be written. This will be
1865 * closed for you upon returning from this function.
1866 * @param uri The URI whose data is to be written.
1867 * @param mimeType The desired type of data to be written.
1868 * @param opts Options supplied by caller.
1869 * @param args Your own custom arguments.
1870 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001871 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1872 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001873 }
1874
1875 /**
1876 * A helper function for implementing {@link #openTypedAssetFile}, for
1877 * creating a data pipe and background thread allowing you to stream
1878 * generated data back to the client. This function returns a new
1879 * ParcelFileDescriptor that should be returned to the caller (the caller
1880 * is responsible for closing it).
1881 *
1882 * @param uri The URI whose data is to be written.
1883 * @param mimeType The desired type of data to be written.
1884 * @param opts Options supplied by caller.
1885 * @param args Your own custom arguments.
1886 * @param func Interface implementing the function that will actually
1887 * stream the data.
1888 * @return Returns a new ParcelFileDescriptor holding the read side of
1889 * the pipe. This should be returned to the caller for reading; the caller
1890 * is responsible for closing it when done.
1891 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001892 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1893 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1894 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001895 try {
1896 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1897
1898 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1899 @Override
1900 protected Object doInBackground(Object... params) {
1901 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1902 try {
1903 fds[1].close();
1904 } catch (IOException e) {
1905 Log.w(TAG, "Failure closing pipe", e);
1906 }
1907 return null;
1908 }
1909 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001910 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001911
1912 return fds[0];
1913 } catch (IOException e) {
1914 throw new FileNotFoundException("failure making pipe");
1915 }
1916 }
1917
1918 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 * Returns true if this instance is a temporary content provider.
1920 * @return true if this instance is a temporary content provider
1921 */
1922 protected boolean isTemporary() {
1923 return false;
1924 }
1925
1926 /**
1927 * Returns the Binder object for this provider.
1928 *
1929 * @return the Binder object for this provider
1930 * @hide
1931 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001932 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 public IContentProvider getIContentProvider() {
1934 return mTransport;
1935 }
1936
1937 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001938 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1939 * when directly instantiating the provider for testing.
1940 * @hide
1941 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001942 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001943 public void attachInfoForTesting(Context context, ProviderInfo info) {
1944 attachInfo(context, info, true);
1945 }
1946
1947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 * After being instantiated, this is called to tell the content provider
1949 * about itself.
1950 *
1951 * @param context The context this provider is running in
1952 * @param info Registered information about this content provider
1953 */
1954 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001955 attachInfo(context, info, false);
1956 }
1957
1958 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001959 mNoPerms = testing;
1960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 /*
1962 * Only allow it to be set once, so after the content service gives
1963 * this to us clients can't change it.
1964 */
1965 if (mContext == null) {
1966 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001967 if (context != null) {
1968 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1969 Context.APP_OPS_SERVICE);
1970 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001971 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 if (info != null) {
1973 setReadPermission(info.readPermission);
1974 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001975 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001976 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001977 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001978 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
1980 ContentProvider.this.onCreate();
1981 }
1982 }
Fred Quintanace31b232009-05-04 16:01:15 -07001983
1984 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001985 * Override this to handle requests to perform a batch of operations, or the
1986 * default implementation will iterate over the operations and call
1987 * {@link ContentProviderOperation#apply} on each of them.
1988 * If all calls to {@link ContentProviderOperation#apply} succeed
1989 * then a {@link ContentProviderResult} array with as many
1990 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001991 * fail, it is up to the implementation how many of the others take effect.
1992 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001993 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1994 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001995 *
Fred Quintanace31b232009-05-04 16:01:15 -07001996 * @param operations the operations to apply
1997 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001998 * @throws OperationApplicationException thrown if any operation fails.
1999 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002000 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002001 public @NonNull ContentProviderResult[] applyBatch(
2002 @NonNull ArrayList<ContentProviderOperation> operations)
2003 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002004 final int numOperations = operations.size();
2005 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2006 for (int i = 0; i < numOperations; i++) {
2007 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002008 }
2009 return results;
2010 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002011
2012 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002013 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002014 * interfaces that are cheaper and/or unnatural for a table-like
2015 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002016 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002017 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2018 * on this entry into the content provider besides the basic ability for the application
2019 * to get access to the provider at all. For example, it has no idea whether the call
2020 * being executed may read or write data in the provider, so can't enforce those
2021 * individual permissions. Any implementation of this method <strong>must</strong>
2022 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2023 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002024 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2025 * @param arg provider-defined String argument. May be {@code null}.
2026 * @param extras provider-defined Bundle argument. May be {@code null}.
2027 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002028 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002029 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002030 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2031 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002032 return null;
2033 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002034
2035 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002036 * Implement this to shut down the ContentProvider instance. You can then
2037 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002038 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002039 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002040 * Android normally handles ContentProvider startup and shutdown
2041 * automatically. You do not need to start up or shut down a
2042 * ContentProvider. When you invoke a test method on a ContentProvider,
2043 * however, a ContentProvider instance is started and keeps running after
2044 * the test finishes, even if a succeeding test instantiates another
2045 * ContentProvider. A conflict develops because the two instances are
2046 * usually running against the same underlying data source (for example, an
2047 * sqlite database).
2048 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002049 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002050 * Implementing shutDown() avoids this conflict by providing a way to
2051 * terminate the ContentProvider. This method can also prevent memory leaks
2052 * from multiple instantiations of the ContentProvider, and it can ensure
2053 * unit test isolation by allowing you to completely clean up the test
2054 * fixture before moving on to the next test.
2055 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002056 */
2057 public void shutdown() {
2058 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2059 "connections are gracefully shutdown");
2060 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002061
2062 /**
2063 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002064 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002065 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002066 * @param fd The raw file descriptor that the dump is being sent to.
2067 * @param writer The PrintWriter to which you should dump your state. This will be
2068 * closed for you after you return.
2069 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002070 */
2071 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2072 writer.println("nothing to dump");
2073 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002074
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002075 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002076 private void validateIncomingUri(Uri uri) throws SecurityException {
2077 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002078 if (!mSingleUser) {
2079 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2080 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2081 throw new SecurityException("trying to query a ContentProvider in user "
2082 + mContext.getUserId() + " with a uri belonging to user " + userId);
2083 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002084 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002085 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2086 String message = "The authority of the uri " + uri + " does not match the one of the "
2087 + "contentProvider: ";
2088 if (mAuthority != null) {
2089 message += mAuthority;
2090 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002091 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002092 }
2093 throw new SecurityException(message);
2094 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002095 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002096
2097 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002098 private Uri maybeGetUriWithoutUserId(Uri uri) {
2099 if (mSingleUser) {
2100 return uri;
2101 }
2102 return getUriWithoutUserId(uri);
2103 }
2104
2105 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002106 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2107 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002108 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002109 if (end == -1) return defaultUserId;
2110 String userIdString = auth.substring(0, end);
2111 try {
2112 return Integer.parseInt(userIdString);
2113 } catch (NumberFormatException e) {
2114 Log.w(TAG, "Error parsing userId.", e);
2115 return UserHandle.USER_NULL;
2116 }
2117 }
2118
2119 /** @hide */
2120 public static int getUserIdFromAuthority(String auth) {
2121 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2122 }
2123
2124 /** @hide */
2125 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2126 if (uri == null) return defaultUserId;
2127 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2128 }
2129
2130 /** @hide */
2131 public static int getUserIdFromUri(Uri uri) {
2132 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2133 }
2134
2135 /**
2136 * Removes userId part from authority string. Expects format:
2137 * userId@some.authority
2138 * If there is no userId in the authority, it symply returns the argument
2139 * @hide
2140 */
2141 public static String getAuthorityWithoutUserId(String auth) {
2142 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002143 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002144 return auth.substring(end+1);
2145 }
2146
2147 /** @hide */
2148 public static Uri getUriWithoutUserId(Uri uri) {
2149 if (uri == null) return null;
2150 Uri.Builder builder = uri.buildUpon();
2151 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2152 return builder.build();
2153 }
2154
2155 /** @hide */
2156 public static boolean uriHasUserId(Uri uri) {
2157 if (uri == null) return false;
2158 return !TextUtils.isEmpty(uri.getUserInfo());
2159 }
2160
2161 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002162 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002163 public static Uri maybeAddUserId(Uri uri, int userId) {
2164 if (uri == null) return null;
2165 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002166 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002167 if (!uriHasUserId(uri)) {
2168 //We don't add the user Id if there's already one
2169 Uri.Builder builder = uri.buildUpon();
2170 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2171 return builder.build();
2172 }
2173 }
2174 return uri;
2175 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002176}