blob: 085d77d5c1cdd1e3bd8994acbaae7ac47b11218e [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.
Steve McKayea93fe72016-12-02 11:35:35 -0800239 Cursor cursor = ContentProvider.this.query(
240 uri, projection, queryArgs,
241 CancellationSignal.fromTransport(cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700242 if (cursor == null) {
243 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700244 }
245
246 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700247 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800248 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600249 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700250 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700251 try {
252 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800253 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700254 CancellationSignal.fromTransport(cancellationSignal));
255 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700256 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600257 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 }
260
Jeff Brown75ea64f2012-01-25 19:37:13 -0800261 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100263 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100264 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600265 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
266 try {
267 return ContentProvider.this.getType(uri);
268 } finally {
269 Trace.traceEnd(TRACE_TAG_DATABASE);
270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 }
272
Jeff Brown75ea64f2012-01-25 19:37:13 -0800273 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800274 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100275 validateIncomingUri(uri);
276 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100277 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800278 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800279 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800280 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600281 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700282 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700283 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100284 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700285 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700286 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600287 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 }
290
Jeff Brown75ea64f2012-01-25 19:37:13 -0800291 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800292 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100293 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100294 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800295 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800296 return 0;
297 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600298 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700299 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700300 try {
301 return ContentProvider.this.bulkInsert(uri, initialValues);
302 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700303 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600304 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 }
307
Jeff Brown75ea64f2012-01-25 19:37:13 -0800308 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800309 public ContentProviderResult[] applyBatch(String callingPkg,
310 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700311 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100312 int numOperations = operations.size();
313 final int[] userIds = new int[numOperations];
314 for (int i = 0; i < numOperations; i++) {
315 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100316 Uri uri = operation.getUri();
317 validateIncomingUri(uri);
318 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100319 if (userIds[i] != UserHandle.USER_CURRENT) {
320 // Removing the user id from the uri.
321 operation = new ContentProviderOperation(operation, true);
322 operations.set(i, operation);
323 }
Fred Quintana89437372009-05-15 15:10:40 -0700324 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800325 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800326 != AppOpsManager.MODE_ALLOWED) {
327 throw new OperationApplicationException("App op not allowed", 0);
328 }
Fred Quintana89437372009-05-15 15:10:40 -0700329 }
Fred Quintana89437372009-05-15 15:10:40 -0700330 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800331 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800332 != AppOpsManager.MODE_ALLOWED) {
333 throw new OperationApplicationException("App op not allowed", 0);
334 }
Fred Quintana89437372009-05-15 15:10:40 -0700335 }
336 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600337 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700338 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100340 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800341 if (results != null) {
342 for (int i = 0; i < results.length ; i++) {
343 if (userIds[i] != UserHandle.USER_CURRENT) {
344 // Adding the userId to the uri.
345 results[i] = new ContentProviderResult(results[i], userIds[i]);
346 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100347 }
348 }
349 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700350 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700351 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600352 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700353 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700354 }
355
Jeff Brown75ea64f2012-01-25 19:37:13 -0800356 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800357 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100358 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100359 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800360 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800361 return 0;
362 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600363 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700364 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700365 try {
366 return ContentProvider.this.delete(uri, selection, selectionArgs);
367 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700368 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600369 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372
Jeff Brown75ea64f2012-01-25 19:37:13 -0800373 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800374 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100376 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100377 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800378 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800379 return 0;
380 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600381 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700382 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700383 try {
384 return ContentProvider.this.update(uri, values, selection, selectionArgs);
385 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700386 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600387 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 }
390
Jeff Brown75ea64f2012-01-25 19:37:13 -0800391 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700392 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800393 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
394 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100395 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100396 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800397 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600398 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700399 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700400 try {
401 return ContentProvider.this.openFile(
402 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
403 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700404 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600405 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
408
Jeff Brown75ea64f2012-01-25 19:37:13 -0800409 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700410 public AssetFileDescriptor openAssetFile(
411 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100413 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100414 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800415 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600416 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700417 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700418 try {
419 return ContentProvider.this.openAssetFile(
420 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
421 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700422 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600423 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
426
Jeff Brown75ea64f2012-01-25 19:37:13 -0800427 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800428 public Bundle call(
429 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600430 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600431 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700432 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700433 try {
434 return ContentProvider.this.call(method, arg, extras);
435 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700436 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600437 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700438 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800439 }
440
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700441 @Override
442 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100443 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100444 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600445 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
446 try {
447 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
448 } finally {
449 Trace.traceEnd(TRACE_TAG_DATABASE);
450 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700451 }
452
453 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800454 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700455 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600456 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100457 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100458 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800459 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600460 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700461 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700462 try {
463 return ContentProvider.this.openTypedAssetFile(
464 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
465 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700466 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600467 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700468 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700469 }
470
Jeff Brown75ea64f2012-01-25 19:37:13 -0800471 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700472 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800473 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800474 }
475
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700476 @Override
477 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100478 validateIncomingUri(uri);
479 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100480 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800481 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700482 return null;
483 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600484 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700485 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700486 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100487 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700488 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700489 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600490 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700491 }
492 }
493
494 @Override
495 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100496 validateIncomingUri(uri);
497 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100498 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800499 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700500 return null;
501 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600502 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700503 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700504 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100505 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700506 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700507 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600508 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700509 }
510 }
511
Ben Lin1cf454f2016-11-10 13:50:54 -0800512 @Override
513 public boolean refresh(String callingPkg, Uri uri, Bundle args,
514 ICancellationSignal cancellationSignal) throws RemoteException {
515 validateIncomingUri(uri);
516 uri = getUriWithoutUserId(uri);
517 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
518 return false;
519 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600520 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800521 final String original = setCallingPackage(callingPkg);
522 try {
523 return ContentProvider.this.refresh(uri, args,
524 CancellationSignal.fromTransport(cancellationSignal));
525 } finally {
526 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600527 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800528 }
529 }
530
Dianne Hackbornff170242014-11-19 10:59:01 -0800531 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
532 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800533 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800534 if (enforceWritePermission(callingPkg, uri, callerToken)
535 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800536 throw new FileNotFoundException("App op not allowed");
537 }
538 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800539 if (enforceReadPermission(callingPkg, uri, callerToken)
540 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800541 throw new FileNotFoundException("App op not allowed");
542 }
543 }
544 }
545
Dianne Hackbornff170242014-11-19 10:59:01 -0800546 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
547 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700548 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
549 if (mode != MODE_ALLOWED) {
550 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800551 }
Svet Ganov99b60432015-06-27 13:15:22 -0700552
553 if (mReadOp != AppOpsManager.OP_NONE) {
554 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
555 }
556
Dianne Hackborn35654b62013-01-14 17:38:02 -0800557 return AppOpsManager.MODE_ALLOWED;
558 }
559
Dianne Hackbornff170242014-11-19 10:59:01 -0800560 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
561 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700562 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
563 if (mode != MODE_ALLOWED) {
564 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800565 }
Svet Ganov99b60432015-06-27 13:15:22 -0700566
567 if (mWriteOp != AppOpsManager.OP_NONE) {
568 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
569 }
570
Dianne Hackborn35654b62013-01-14 17:38:02 -0800571 return AppOpsManager.MODE_ALLOWED;
572 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700573 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800574
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100575 boolean checkUser(int pid, int uid, Context context) {
576 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700577 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100578 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
579 == PERMISSION_GRANTED;
580 }
581
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700582 /**
583 * Verify that calling app holds both the given permission and any app-op
584 * associated with that permission.
585 */
586 private int checkPermissionAndAppOp(String permission, String callingPkg,
587 IBinder callerToken) {
588 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
589 callerToken) != PERMISSION_GRANTED) {
590 return MODE_ERRORED;
591 }
592
593 final int permOp = AppOpsManager.permissionToOpCode(permission);
594 if (permOp != AppOpsManager.OP_NONE) {
595 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
596 }
597
598 return MODE_ALLOWED;
599 }
600
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700601 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700602 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800603 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700604 final Context context = getContext();
605 final int pid = Binder.getCallingPid();
606 final int uid = Binder.getCallingUid();
607 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700608 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700609
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700610 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700611 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700612 }
613
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100614 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700615 final String componentPerm = getReadPermission();
616 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700617 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
618 if (mode == MODE_ALLOWED) {
619 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700620 } else {
621 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700622 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700623 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700624 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700625
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700626 // track if unprotected read is allowed; any denied
627 // <path-permission> below removes this ability
628 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700629
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700630 final PathPermission[] pps = getPathPermissions();
631 if (pps != null) {
632 final String path = uri.getPath();
633 for (PathPermission pp : pps) {
634 final String pathPerm = pp.getReadPermission();
635 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700636 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
637 if (mode == MODE_ALLOWED) {
638 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700639 } else {
640 // any denied <path-permission> means we lose
641 // default <provider> access.
642 allowDefaultRead = false;
643 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700644 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700645 }
646 }
647 }
648 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700649
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700650 // if we passed <path-permission> checks above, and no default
651 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700652 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700654
655 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800656 final int callingUserId = UserHandle.getUserId(uid);
657 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
658 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800659 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
660 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700661 return MODE_ALLOWED;
662 }
663
664 // If the worst denial we found above was ignored, then pass that
665 // ignored through; otherwise we assume it should be a real error below.
666 if (strongestMode == MODE_IGNORED) {
667 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700668 }
669
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600670 final String suffix;
671 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
672 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
673 } else if (mExported) {
674 suffix = " requires " + missingPerm + ", or grantUriPermission()";
675 } else {
676 suffix = " requires the provider be exported, or grantUriPermission()";
677 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700678 throw new SecurityException("Permission Denial: reading "
679 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600680 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700681 }
682
683 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700684 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800685 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700686 final Context context = getContext();
687 final int pid = Binder.getCallingPid();
688 final int uid = Binder.getCallingUid();
689 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700690 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700691
692 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700693 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700694 }
695
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100696 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700697 final String componentPerm = getWritePermission();
698 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700699 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
700 if (mode == MODE_ALLOWED) {
701 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700702 } else {
703 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700704 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700705 }
706 }
707
708 // track if unprotected write is allowed; any denied
709 // <path-permission> below removes this ability
710 boolean allowDefaultWrite = (componentPerm == null);
711
712 final PathPermission[] pps = getPathPermissions();
713 if (pps != null) {
714 final String path = uri.getPath();
715 for (PathPermission pp : pps) {
716 final String pathPerm = pp.getWritePermission();
717 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700718 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
719 if (mode == MODE_ALLOWED) {
720 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700721 } else {
722 // any denied <path-permission> means we lose
723 // default <provider> access.
724 allowDefaultWrite = false;
725 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700726 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700727 }
728 }
729 }
730 }
731
732 // if we passed <path-permission> checks above, and no default
733 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700734 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700735 }
736
737 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800738 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
739 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700740 return MODE_ALLOWED;
741 }
742
743 // If the worst denial we found above was ignored, then pass that
744 // ignored through; otherwise we assume it should be a real error below.
745 if (strongestMode == MODE_IGNORED) {
746 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700747 }
748
749 final String failReason = mExported
750 ? " requires " + missingPerm + ", or grantUriPermission()"
751 : " requires the provider be exported, or grantUriPermission()";
752 throw new SecurityException("Permission Denial: writing "
753 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
754 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 }
756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700758 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800759 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 * constructor.
761 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700762 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 return mContext;
764 }
765
766 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700767 * Set the calling package, returning the current value (or {@code null})
768 * which can be used later to restore the previous state.
769 */
770 private String setCallingPackage(String callingPackage) {
771 final String original = mCallingPackage.get();
772 mCallingPackage.set(callingPackage);
773 return original;
774 }
775
776 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700777 * Return the package name of the caller that initiated the request being
778 * processed on the current thread. The returned package will have been
779 * verified to belong to the calling UID. Returns {@code null} if not
780 * currently processing a request.
781 * <p>
782 * This will always return {@code null} when processing
783 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
784 *
785 * @see Binder#getCallingUid()
786 * @see Context#grantUriPermission(String, Uri, int)
787 * @throws SecurityException if the calling package doesn't belong to the
788 * calling UID.
789 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700790 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700791 final String pkg = mCallingPackage.get();
792 if (pkg != null) {
793 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
794 }
795 return pkg;
796 }
797
798 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100799 * Change the authorities of the ContentProvider.
800 * This is normally set for you from its manifest information when the provider is first
801 * created.
802 * @hide
803 * @param authorities the semi-colon separated authorities of the ContentProvider.
804 */
805 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100806 if (authorities != null) {
807 if (authorities.indexOf(';') == -1) {
808 mAuthority = authorities;
809 mAuthorities = null;
810 } else {
811 mAuthority = null;
812 mAuthorities = authorities.split(";");
813 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100814 }
815 }
816
817 /** @hide */
818 protected final boolean matchesOurAuthorities(String authority) {
819 if (mAuthority != null) {
820 return mAuthority.equals(authority);
821 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100822 if (mAuthorities != null) {
823 int length = mAuthorities.length;
824 for (int i = 0; i < length; i++) {
825 if (mAuthorities[i].equals(authority)) return true;
826 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100827 }
828 return false;
829 }
830
831
832 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 * Change the permission required to read data from the content
834 * provider. This is normally set for you from its manifest information
835 * when the provider is first created.
836 *
837 * @param permission Name of the permission required for read-only access.
838 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700839 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 mReadPermission = permission;
841 }
842
843 /**
844 * Return the name of the permission required for read-only access to
845 * this content provider. This method can be called from multiple
846 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800847 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
848 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700850 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 return mReadPermission;
852 }
853
854 /**
855 * Change the permission required to read and write data in the content
856 * provider. This is normally set for you from its manifest information
857 * when the provider is first created.
858 *
859 * @param permission Name of the permission required for read/write access.
860 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700861 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 mWritePermission = permission;
863 }
864
865 /**
866 * Return the name of the permission required for read/write access to
867 * this content provider. This method can be called from multiple
868 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800869 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
870 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700872 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 return mWritePermission;
874 }
875
876 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700877 * Change the path-based permission required to read and/or write data in
878 * the content provider. This is normally set for you from its manifest
879 * information when the provider is first created.
880 *
881 * @param permissions Array of path permission descriptions.
882 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700883 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700884 mPathPermissions = permissions;
885 }
886
887 /**
888 * Return the path-based permissions required for read and/or write access to
889 * this content provider. This method can be called from multiple
890 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800891 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
892 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700893 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700894 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700895 return mPathPermissions;
896 }
897
Dianne Hackborn35654b62013-01-14 17:38:02 -0800898 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100899 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -0800900 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800901 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800902 mTransport.mReadOp = readOp;
903 mTransport.mWriteOp = writeOp;
904 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800905 }
906
Dianne Hackborn961321f2013-02-05 17:22:41 -0800907 /** @hide */
908 public AppOpsManager getAppOpsManager() {
909 return mTransport.mAppOpsManager;
910 }
911
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700912 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700913 * Implement this to initialize your content provider on startup.
914 * This method is called for all registered content providers on the
915 * application main thread at application launch time. It must not perform
916 * lengthy operations, or application startup will be delayed.
917 *
918 * <p>You should defer nontrivial initialization (such as opening,
919 * upgrading, and scanning databases) until the content provider is used
920 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
921 * keeps application startup fast, avoids unnecessary work if the provider
922 * turns out not to be needed, and stops database errors (such as a full
923 * disk) from halting application launch.
924 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700925 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700926 * is a helpful utility class that makes it easy to manage databases,
927 * and will automatically defer opening until first use. If you do use
928 * SQLiteOpenHelper, make sure to avoid calling
929 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
930 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
931 * from this method. (Instead, override
932 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
933 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 *
935 * @return true if the provider was successfully loaded, false otherwise
936 */
937 public abstract boolean onCreate();
938
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700939 /**
940 * {@inheritDoc}
941 * This method is always called on the application main thread, and must
942 * not perform lengthy operations.
943 *
944 * <p>The default content provider implementation does nothing.
945 * Override this method to take appropriate action.
946 * (Content providers do not usually care about things like screen
947 * orientation, but may want to know about locale changes.)
948 */
Steve McKayea93fe72016-12-02 11:35:35 -0800949 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 public void onConfigurationChanged(Configuration newConfig) {
951 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700952
953 /**
954 * {@inheritDoc}
955 * This method is always called on the application main thread, and must
956 * not perform lengthy operations.
957 *
958 * <p>The default content provider implementation does nothing.
959 * Subclasses may override this method to take appropriate action.
960 */
Steve McKayea93fe72016-12-02 11:35:35 -0800961 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 public void onLowMemory() {
963 }
964
Steve McKayea93fe72016-12-02 11:35:35 -0800965 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700966 public void onTrimMemory(int level) {
967 }
968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700970 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800971 *
972 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
973 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
974 * implementation of this method.
975 *
976 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800977 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
978 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 * <p>
980 * Example client call:<p>
981 * <pre>// Request a specific record.
982 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000983 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 projection, // Which columns to return.
985 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000986 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 People.NAME + " ASC"); // Sort order.</pre>
988 * Example implementation:<p>
989 * <pre>// SQLiteQueryBuilder is a helper class that creates the
990 // proper SQL syntax for us.
991 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
992
993 // Set the table we're querying.
994 qBuilder.setTables(DATABASE_TABLE_NAME);
995
996 // If the query ends in a specific record number, we're
997 // being asked for a specific record, so set the
998 // WHERE clause in our query.
999 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1000 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1001 }
1002
1003 // Make the query.
1004 Cursor c = qBuilder.query(mDb,
1005 projection,
1006 selection,
1007 selectionArgs,
1008 groupBy,
1009 having,
1010 sortOrder);
1011 c.setNotificationUri(getContext().getContentResolver(), uri);
1012 return c;</pre>
1013 *
1014 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001015 * if the client is requesting a specific record, the URI will end in a record number
1016 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1017 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001019 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001021 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001022 * @param selectionArgs You may include ?s in selection, which will be replaced by
1023 * the values from selectionArgs, in order that they appear in the selection.
1024 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001026 * If {@code null} then the provider is free to define the sort order.
1027 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001029 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1030 @Nullable String selection, @Nullable String[] selectionArgs,
1031 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032
Fred Quintana5bba6322009-10-05 14:21:12 -07001033 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001034 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001035 *
1036 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1037 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1038 *
1039 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001040 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1041 * and Threads</a>.
1042 * <p>
1043 * Example client call:<p>
1044 * <pre>// Request a specific record.
1045 * Cursor managedCursor = managedQuery(
1046 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1047 projection, // Which columns to return.
1048 null, // WHERE clause.
1049 null, // WHERE clause value substitution
1050 People.NAME + " ASC"); // Sort order.</pre>
1051 * Example implementation:<p>
1052 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1053 // proper SQL syntax for us.
1054 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1055
1056 // Set the table we're querying.
1057 qBuilder.setTables(DATABASE_TABLE_NAME);
1058
1059 // If the query ends in a specific record number, we're
1060 // being asked for a specific record, so set the
1061 // WHERE clause in our query.
1062 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1063 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1064 }
1065
1066 // Make the query.
1067 Cursor c = qBuilder.query(mDb,
1068 projection,
1069 selection,
1070 selectionArgs,
1071 groupBy,
1072 having,
1073 sortOrder);
1074 c.setNotificationUri(getContext().getContentResolver(), uri);
1075 return c;</pre>
1076 * <p>
1077 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001078 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1079 * signal to ensure correct operation on older versions of the Android Framework in
1080 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001081 *
1082 * @param uri The URI to query. This will be the full URI sent by the client;
1083 * if the client is requesting a specific record, the URI will end in a record number
1084 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1085 * that _id value.
1086 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001087 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001088 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001089 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001090 * @param selectionArgs You may include ?s in selection, which will be replaced by
1091 * the values from selectionArgs, in order that they appear in the selection.
1092 * The values will be bound as Strings.
1093 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001094 * If {@code null} then the provider is free to define the sort order.
1095 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001096 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001097 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001098 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001099 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001100 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1101 @Nullable String selection, @Nullable String[] selectionArgs,
1102 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001103 return query(uri, projection, selection, selectionArgs, sortOrder);
1104 }
1105
1106 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001107 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1108 * Arguments may include traditional SQL style query arguments. When present these
1109 * should be handled according to the contract established in
1110 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1111 *
1112 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001113 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1114 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1115 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001116 *
Steve McKay76b27702017-04-24 12:07:53 -07001117 * <p>This method can be called from multiple threads, as described in
1118 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1119 * and Threads</a>.
1120 *
1121 * <p>
1122 * Example client call:<p>
1123 * <pre>// Request 20 records starting at row index 30.
1124 Bundle queryArgs = new Bundle();
1125 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1126 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1127
1128 Cursor cursor = getContentResolver().query(
1129 contentUri, // Content Uri is specific to individual content providers.
1130 projection, // String[] describing which columns to return.
1131 queryArgs, // Query arguments.
1132 null); // Cancellation signal.</pre>
1133 *
1134 * Example implementation:<p>
1135 * <pre>
1136
1137 int recordsetSize = 0x1000; // Actual value is implementation specific.
1138 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1139
1140 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1141 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1142
1143 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1144
1145 // Calculate the number of items to include in the cursor.
1146 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1147
1148 // Build the paged result set....
1149 for (int i = offset; i < offset + numItems; i++) {
1150 // populate row from your data.
1151 }
1152
1153 Bundle extras = new Bundle();
1154 c.setExtras(extras);
1155
1156 // Any QUERY_ARG_* key may be included if honored.
1157 // In an actual implementation, include only keys that are both present in queryArgs
1158 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1159 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1160 // then QUERY_ARG_OFFSET should be omitted.
1161 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1162 ContentResolver.QUERY_ARG_OFFSET,
1163 ContentResolver.QUERY_ARG_LIMIT
1164 });
1165
1166 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1167
1168 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1169
1170 return cursor;</pre>
1171 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001172 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1173 * implementation details.
1174 *
1175 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001176 * @param projection The list of columns to put into the cursor.
1177 * If {@code null} provide a default set of columns.
1178 * @param queryArgs A Bundle containing all additional information necessary for the query.
1179 * Values in the Bundle may include SQL style arguments.
1180 * @param cancellationSignal A signal to cancel the operation in progress,
1181 * or {@code null}.
1182 * @return a Cursor or {@code null}.
1183 */
1184 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1185 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1186 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001187
Steve McKayd7ece9f2017-01-12 16:59:59 -08001188 // if client doesn't supply an SQL sort order argument, attempt to build one from
1189 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001190 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001191 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1192 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1193 }
1194
Steve McKayea93fe72016-12-02 11:35:35 -08001195 return query(
1196 uri,
1197 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001198 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1199 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1200 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001201 cancellationSignal);
1202 }
1203
1204 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001205 * Implement this to handle requests for the MIME type of the data at the
1206 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 * <code>vnd.android.cursor.item</code> for a single record,
1208 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001209 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001210 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1211 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001213 * <p>Note that there are no permissions needed for an application to
1214 * access this information; if your content provider requires read and/or
1215 * write permissions, or is not exported, all applications can still call
1216 * this method regardless of their access permissions. This allows them
1217 * to retrieve the MIME type for a URI when dispatching intents.
1218 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001220 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001222 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223
1224 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001225 * Implement this to support canonicalization of URIs that refer to your
1226 * content provider. A canonical URI is one that can be transported across
1227 * devices, backup/restore, and other contexts, and still be able to refer
1228 * to the same data item. Typically this is implemented by adding query
1229 * params to the URI allowing the content provider to verify that an incoming
1230 * canonical URI references the same data as it was originally intended for and,
1231 * if it doesn't, to find that data (if it exists) in the current environment.
1232 *
1233 * <p>For example, if the content provider holds people and a normal URI in it
1234 * is created with a row index into that people database, the cananical representation
1235 * may have an additional query param at the end which specifies the name of the
1236 * person it is intended for. Later calls into the provider with that URI will look
1237 * up the row of that URI's base index and, if it doesn't match or its entry's
1238 * name doesn't match the name in the query param, perform a query on its database
1239 * to find the correct row to operate on.</p>
1240 *
1241 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1242 * URIs (including this one) must perform this verification and recovery of any
1243 * canonical URIs they receive. In addition, you must also implement
1244 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1245 *
1246 * <p>The default implementation of this method returns null, indicating that
1247 * canonical URIs are not supported.</p>
1248 *
1249 * @param url The Uri to canonicalize.
1250 *
1251 * @return Return the canonical representation of <var>url</var>, or null if
1252 * canonicalization of that Uri is not supported.
1253 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001254 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001255 return null;
1256 }
1257
1258 /**
1259 * Remove canonicalization from canonical URIs previously returned by
1260 * {@link #canonicalize}. For example, if your implementation is to add
1261 * a query param to canonicalize a URI, this method can simply trip any
1262 * query params on the URI. The default implementation always returns the
1263 * same <var>url</var> that was passed in.
1264 *
1265 * @param url The Uri to remove any canonicalization from.
1266 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001267 * @return Return the non-canonical representation of <var>url</var>, return
1268 * the <var>url</var> as-is if there is nothing to do, or return null if
1269 * the data identified by the canonical representation can not be found in
1270 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001271 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001272 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001273 return url;
1274 }
1275
1276 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001277 * Implement this to support refresh of content identified by {@code uri}. By default, this
1278 * method returns false; providers who wish to implement this should return true to signal the
1279 * client that the provider has tried refreshing with its own implementation.
1280 * <p>
1281 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1282 * <p>
1283 * Client code should only invoke this method when there is a strong indication (such as a user
1284 * initiated pull to refresh gesture) that the content is stale.
1285 * <p>
1286 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1287 * notifications when content changes.
1288 *
1289 * @param uri The Uri identifying the data to refresh.
1290 * @param args Additional options from the client. The definitions of these are specific to the
1291 * content provider being called.
1292 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1293 * none. For example, if you called refresh on a particular uri, you should call
1294 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1295 * canceled the refresh request.
1296 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001297 */
1298 public boolean refresh(Uri uri, @Nullable Bundle args,
1299 @Nullable CancellationSignal cancellationSignal) {
1300 return false;
1301 }
1302
1303 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001304 * @hide
1305 * Implementation when a caller has performed an insert on the content
1306 * provider, but that call has been rejected for the operation given
1307 * to {@link #setAppOps(int, int)}. The default implementation simply
1308 * returns a dummy URI that is the base URI with a 0 path element
1309 * appended.
1310 */
1311 public Uri rejectInsert(Uri uri, ContentValues values) {
1312 // If not allowed, we need to return some reasonable URI. Maybe the
1313 // content provider should be responsible for this, but for now we
1314 // will just return the base URI with a dummy '0' tagged on to it.
1315 // You shouldn't be able to read if you can't write, anyway, so it
1316 // shouldn't matter much what is returned.
1317 return uri.buildUpon().appendPath("0").build();
1318 }
1319
1320 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001321 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1323 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001324 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001325 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1326 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001327 * @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 -08001328 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001329 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 * @return The URI for the newly inserted item.
1331 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001332 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333
1334 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001335 * Override this to handle requests to insert a set of new rows, or the
1336 * default implementation will iterate over the values and call
1337 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1339 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001340 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001341 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1342 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 *
1344 * @param uri The content:// URI of the insertion request.
1345 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001346 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 * @return The number of values that were inserted.
1348 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001349 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 int numValues = values.length;
1351 for (int i = 0; i < numValues; i++) {
1352 insert(uri, values[i]);
1353 }
1354 return numValues;
1355 }
1356
1357 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001358 * Implement this to handle requests to delete one or more rows.
1359 * The implementation should apply the selection clause when performing
1360 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001361 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001363 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001364 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1365 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 *
1367 * <p>The implementation is responsible for parsing out a row ID at the end
1368 * of the URI, if a specific row is being deleted. That is, the client would
1369 * pass in <code>content://contacts/people/22</code> and the implementation is
1370 * responsible for parsing the record number (22) when creating a SQL statement.
1371 *
1372 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1373 * @param selection An optional restriction to apply to rows when deleting.
1374 * @return The number of rows affected.
1375 * @throws SQLException
1376 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001377 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1378 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
1380 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001381 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001382 * The implementation should update all rows matching the selection
1383 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1385 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001386 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001387 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1388 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 *
1390 * @param uri The URI to query. This can potentially have a record ID if this
1391 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001392 * @param values A set of column_name/value pairs to update in the database.
1393 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 * @param selection An optional filter to match rows to update.
1395 * @return the number of rows affected.
1396 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001397 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001398 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399
1400 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001401 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001402 * The default implementation always throws {@link FileNotFoundException}.
1403 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001404 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1405 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001406 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001407 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1408 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001409 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 *
1411 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1412 * their responsibility to close it when done. That is, the implementation
1413 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001414 * <p>
1415 * If opened with the exclusive "r" or "w" modes, the returned
1416 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1417 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1418 * supports seeking.
1419 * <p>
1420 * If you need to detect when the returned ParcelFileDescriptor has been
1421 * closed, or if the remote process has crashed or encountered some other
1422 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1423 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1424 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1425 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001426 * <p>
1427 * If you need to return a large file that isn't backed by a real file on
1428 * disk, such as a file on a network share or cloud storage service,
1429 * consider using
1430 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1431 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001433 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1434 * to return the appropriate MIME type for the data returned here with
1435 * the same URI. This will allow intent resolution to automatically determine the data MIME
1436 * type and select the appropriate matching targets as part of its operation.</p>
1437 *
1438 * <p class="note">For better interoperability with other applications, it is recommended
1439 * that for any URIs that can be opened, you also support queries on them
1440 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1441 * You may also want to support other common columns if you have additional meta-data
1442 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1443 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1444 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 * @param uri The URI whose file is to be opened.
1446 * @param mode Access mode for the file. May be "r" for read-only access,
1447 * "rw" for read and write access, or "rwt" for read and write access
1448 * that truncates any existing file.
1449 *
1450 * @return Returns a new ParcelFileDescriptor which you can use to access
1451 * the file.
1452 *
1453 * @throws FileNotFoundException Throws FileNotFoundException if there is
1454 * no file associated with the given URI or the mode is invalid.
1455 * @throws SecurityException Throws SecurityException if the caller does
1456 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001457 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 * @see #openAssetFile(Uri, String)
1459 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001460 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001461 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001462 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001463 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 throws FileNotFoundException {
1465 throw new FileNotFoundException("No files supported by provider at "
1466 + uri);
1467 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001470 * Override this to handle requests to open a file blob.
1471 * The default implementation always throws {@link FileNotFoundException}.
1472 * This method can be called from multiple threads, as described in
1473 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1474 * and Threads</a>.
1475 *
1476 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1477 * to the caller. This way large data (such as images and documents) can be
1478 * returned without copying the content.
1479 *
1480 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1481 * their responsibility to close it when done. That is, the implementation
1482 * of this method should create a new ParcelFileDescriptor for each call.
1483 * <p>
1484 * If opened with the exclusive "r" or "w" modes, the returned
1485 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1486 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1487 * supports seeking.
1488 * <p>
1489 * If you need to detect when the returned ParcelFileDescriptor has been
1490 * closed, or if the remote process has crashed or encountered some other
1491 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1492 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1493 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1494 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1495 *
1496 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1497 * to return the appropriate MIME type for the data returned here with
1498 * the same URI. This will allow intent resolution to automatically determine the data MIME
1499 * type and select the appropriate matching targets as part of its operation.</p>
1500 *
1501 * <p class="note">For better interoperability with other applications, it is recommended
1502 * that for any URIs that can be opened, you also support queries on them
1503 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1504 * You may also want to support other common columns if you have additional meta-data
1505 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1506 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1507 *
1508 * @param uri The URI whose file is to be opened.
1509 * @param mode Access mode for the file. May be "r" for read-only access,
1510 * "w" for write-only access, "rw" for read and write access, or
1511 * "rwt" for read and write access that truncates any existing
1512 * file.
1513 * @param signal A signal to cancel the operation in progress, or
1514 * {@code null} if none. For example, if you are downloading a
1515 * file from the network to service a "rw" mode request, you
1516 * should periodically call
1517 * {@link CancellationSignal#throwIfCanceled()} to check whether
1518 * the client has canceled the request and abort the download.
1519 *
1520 * @return Returns a new ParcelFileDescriptor which you can use to access
1521 * the file.
1522 *
1523 * @throws FileNotFoundException Throws FileNotFoundException if there is
1524 * no file associated with the given URI or the mode is invalid.
1525 * @throws SecurityException Throws SecurityException if the caller does
1526 * not have permission to access the file.
1527 *
1528 * @see #openAssetFile(Uri, String)
1529 * @see #openFileHelper(Uri, String)
1530 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001531 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001532 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001533 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1534 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001535 return openFile(uri, mode);
1536 }
1537
1538 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 * This is like {@link #openFile}, but can be implemented by providers
1540 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001541 * inside of their .apk.
1542 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001543 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1544 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001545 *
1546 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001547 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001548 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1550 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1551 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001552 * <p>
1553 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1554 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001555 *
1556 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 * should create the AssetFileDescriptor with
1558 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001559 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001561 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1562 * to return the appropriate MIME type for the data returned here with
1563 * the same URI. This will allow intent resolution to automatically determine the data MIME
1564 * type and select the appropriate matching targets as part of its operation.</p>
1565 *
1566 * <p class="note">For better interoperability with other applications, it is recommended
1567 * that for any URIs that can be opened, you also support queries on them
1568 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1569 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 * @param uri The URI whose file is to be opened.
1571 * @param mode Access mode for the file. May be "r" for read-only access,
1572 * "w" for write-only access (erasing whatever data is currently in
1573 * the file), "wa" for write-only access to append to any existing data,
1574 * "rw" for read and write access on any existing data, and "rwt" for read
1575 * and write access that truncates any existing file.
1576 *
1577 * @return Returns a new AssetFileDescriptor which you can use to access
1578 * the file.
1579 *
1580 * @throws FileNotFoundException Throws FileNotFoundException if there is
1581 * no file associated with the given URI or the mode is invalid.
1582 * @throws SecurityException Throws SecurityException if the caller does
1583 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001584 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 * @see #openFile(Uri, String)
1586 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001587 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001589 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 throws FileNotFoundException {
1591 ParcelFileDescriptor fd = openFile(uri, mode);
1592 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1593 }
1594
1595 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001596 * This is like {@link #openFile}, but can be implemented by providers
1597 * that need to be able to return sub-sections of files, often assets
1598 * inside of their .apk.
1599 * This method can be called from multiple threads, as described in
1600 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1601 * and Threads</a>.
1602 *
1603 * <p>If you implement this, your clients must be able to deal with such
1604 * file slices, either directly with
1605 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1606 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1607 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1608 * methods.
1609 * <p>
1610 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1611 * streaming of data.
1612 *
1613 * <p class="note">If you are implementing this to return a full file, you
1614 * should create the AssetFileDescriptor with
1615 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1616 * applications that cannot handle sub-sections of files.</p>
1617 *
1618 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1619 * to return the appropriate MIME type for the data returned here with
1620 * the same URI. This will allow intent resolution to automatically determine the data MIME
1621 * type and select the appropriate matching targets as part of its operation.</p>
1622 *
1623 * <p class="note">For better interoperability with other applications, it is recommended
1624 * that for any URIs that can be opened, you also support queries on them
1625 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1626 *
1627 * @param uri The URI whose file is to be opened.
1628 * @param mode Access mode for the file. May be "r" for read-only access,
1629 * "w" for write-only access (erasing whatever data is currently in
1630 * the file), "wa" for write-only access to append to any existing data,
1631 * "rw" for read and write access on any existing data, and "rwt" for read
1632 * and write access that truncates any existing file.
1633 * @param signal A signal to cancel the operation in progress, or
1634 * {@code null} if none. For example, if you are downloading a
1635 * file from the network to service a "rw" mode request, you
1636 * should periodically call
1637 * {@link CancellationSignal#throwIfCanceled()} to check whether
1638 * the client has canceled the request and abort the download.
1639 *
1640 * @return Returns a new AssetFileDescriptor which you can use to access
1641 * the file.
1642 *
1643 * @throws FileNotFoundException Throws FileNotFoundException if there is
1644 * no file associated with the given URI or the mode is invalid.
1645 * @throws SecurityException Throws SecurityException if the caller does
1646 * not have permission to access the file.
1647 *
1648 * @see #openFile(Uri, String)
1649 * @see #openFileHelper(Uri, String)
1650 * @see #getType(android.net.Uri)
1651 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001652 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1653 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001654 return openAssetFile(uri, mode);
1655 }
1656
1657 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 * Convenience for subclasses that wish to implement {@link #openFile}
1659 * by looking up a column named "_data" at the given URI.
1660 *
1661 * @param uri The URI to be opened.
1662 * @param mode The file mode. May be "r" for read-only access,
1663 * "w" for write-only access (erasing whatever data is currently in
1664 * the file), "wa" for write-only access to append to any existing data,
1665 * "rw" for read and write access on any existing data, and "rwt" for read
1666 * and write access that truncates any existing file.
1667 *
1668 * @return Returns a new ParcelFileDescriptor that can be used by the
1669 * client to access the file.
1670 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001671 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1672 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1674 int count = (c != null) ? c.getCount() : 0;
1675 if (count != 1) {
1676 // If there is not exactly one result, throw an appropriate
1677 // exception.
1678 if (c != null) {
1679 c.close();
1680 }
1681 if (count == 0) {
1682 throw new FileNotFoundException("No entry for " + uri);
1683 }
1684 throw new FileNotFoundException("Multiple items at " + uri);
1685 }
1686
1687 c.moveToFirst();
1688 int i = c.getColumnIndex("_data");
1689 String path = (i >= 0 ? c.getString(i) : null);
1690 c.close();
1691 if (path == null) {
1692 throw new FileNotFoundException("Column _data not found.");
1693 }
1694
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001695 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 return ParcelFileDescriptor.open(new File(path), modeBits);
1697 }
1698
1699 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001700 * Called by a client to determine the types of data streams that this
1701 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001702 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001703 * of a particular type, return that MIME type if it matches the given
1704 * mimeTypeFilter. If it can perform type conversions, return an array
1705 * of all supported MIME types that match mimeTypeFilter.
1706 *
1707 * @param uri The data in the content provider being queried.
1708 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001709 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001710 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001711 * given mimeTypeFilter. Otherwise returns an array of all available
1712 * concrete MIME types.
1713 *
1714 * @see #getType(Uri)
1715 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001716 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001717 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001718 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001719 return null;
1720 }
1721
1722 /**
1723 * Called by a client to open a read-only stream containing data of a
1724 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1725 * except the file can only be read-only and the content provider may
1726 * perform data conversions to generate data of the desired type.
1727 *
1728 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001729 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001730 * {@link #openAssetFile(Uri, String)}.
1731 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001732 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001733 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001734 * <p>
1735 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1736 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001737 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001738 * <p class="note">For better interoperability with other applications, it is recommended
1739 * that for any URIs that can be opened, you also support queries on them
1740 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1741 * You may also want to support other common columns if you have additional meta-data
1742 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1743 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1744 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001745 * @param uri The data in the content provider being queried.
1746 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001747 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001748 * requirements; in this case the content provider will pick its best
1749 * type matching the pattern.
1750 * @param opts Additional options from the client. The definitions of
1751 * these are specific to the content provider being called.
1752 *
1753 * @return Returns a new AssetFileDescriptor from which the client can
1754 * read data of the desired type.
1755 *
1756 * @throws FileNotFoundException Throws FileNotFoundException if there is
1757 * no file associated with the given URI or the mode is invalid.
1758 * @throws SecurityException Throws SecurityException if the caller does
1759 * not have permission to access the data.
1760 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1761 * content provider does not support the requested MIME type.
1762 *
1763 * @see #getStreamTypes(Uri, String)
1764 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001765 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001766 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001767 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1768 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001769 if ("*/*".equals(mimeTypeFilter)) {
1770 // If they can take anything, the untyped open call is good enough.
1771 return openAssetFile(uri, "r");
1772 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001773 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001774 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001775 // Use old untyped open call if this provider has a type for this
1776 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001777 return openAssetFile(uri, "r");
1778 }
1779 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1780 }
1781
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001782
1783 /**
1784 * Called by a client to open a read-only stream containing data of a
1785 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1786 * except the file can only be read-only and the content provider may
1787 * perform data conversions to generate data of the desired type.
1788 *
1789 * <p>The default implementation compares the given mimeType against the
1790 * result of {@link #getType(Uri)} and, if they match, simply calls
1791 * {@link #openAssetFile(Uri, String)}.
1792 *
1793 * <p>See {@link ClipData} for examples of the use and implementation
1794 * of this method.
1795 * <p>
1796 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1797 * streaming of data.
1798 *
1799 * <p class="note">For better interoperability with other applications, it is recommended
1800 * that for any URIs that can be opened, you also support queries on them
1801 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1802 * You may also want to support other common columns if you have additional meta-data
1803 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1804 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1805 *
1806 * @param uri The data in the content provider being queried.
1807 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001808 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001809 * requirements; in this case the content provider will pick its best
1810 * type matching the pattern.
1811 * @param opts Additional options from the client. The definitions of
1812 * these are specific to the content provider being called.
1813 * @param signal A signal to cancel the operation in progress, or
1814 * {@code null} if none. For example, if you are downloading a
1815 * file from the network to service a "rw" mode request, you
1816 * should periodically call
1817 * {@link CancellationSignal#throwIfCanceled()} to check whether
1818 * the client has canceled the request and abort the download.
1819 *
1820 * @return Returns a new AssetFileDescriptor from which the client can
1821 * read data of the desired type.
1822 *
1823 * @throws FileNotFoundException Throws FileNotFoundException if there is
1824 * no file associated with the given URI or the mode is invalid.
1825 * @throws SecurityException Throws SecurityException if the caller does
1826 * not have permission to access the data.
1827 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1828 * content provider does not support the requested MIME type.
1829 *
1830 * @see #getStreamTypes(Uri, String)
1831 * @see #openAssetFile(Uri, String)
1832 * @see ClipDescription#compareMimeTypes(String, String)
1833 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001834 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1835 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1836 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001837 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1838 }
1839
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001840 /**
1841 * Interface to write a stream of data to a pipe. Use with
1842 * {@link ContentProvider#openPipeHelper}.
1843 */
1844 public interface PipeDataWriter<T> {
1845 /**
1846 * Called from a background thread to stream data out to a pipe.
1847 * Note that the pipe is blocking, so this thread can block on
1848 * writes for an arbitrary amount of time if the client is slow
1849 * at reading.
1850 *
1851 * @param output The pipe where data should be written. This will be
1852 * closed for you upon returning from this function.
1853 * @param uri The URI whose data is to be written.
1854 * @param mimeType The desired type of data to be written.
1855 * @param opts Options supplied by caller.
1856 * @param args Your own custom arguments.
1857 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001858 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1859 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001860 }
1861
1862 /**
1863 * A helper function for implementing {@link #openTypedAssetFile}, for
1864 * creating a data pipe and background thread allowing you to stream
1865 * generated data back to the client. This function returns a new
1866 * ParcelFileDescriptor that should be returned to the caller (the caller
1867 * is responsible for closing it).
1868 *
1869 * @param uri The URI whose data is to be written.
1870 * @param mimeType The desired type of data to be written.
1871 * @param opts Options supplied by caller.
1872 * @param args Your own custom arguments.
1873 * @param func Interface implementing the function that will actually
1874 * stream the data.
1875 * @return Returns a new ParcelFileDescriptor holding the read side of
1876 * the pipe. This should be returned to the caller for reading; the caller
1877 * is responsible for closing it when done.
1878 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001879 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1880 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1881 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001882 try {
1883 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1884
1885 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1886 @Override
1887 protected Object doInBackground(Object... params) {
1888 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1889 try {
1890 fds[1].close();
1891 } catch (IOException e) {
1892 Log.w(TAG, "Failure closing pipe", e);
1893 }
1894 return null;
1895 }
1896 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001897 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001898
1899 return fds[0];
1900 } catch (IOException e) {
1901 throw new FileNotFoundException("failure making pipe");
1902 }
1903 }
1904
1905 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 * Returns true if this instance is a temporary content provider.
1907 * @return true if this instance is a temporary content provider
1908 */
1909 protected boolean isTemporary() {
1910 return false;
1911 }
1912
1913 /**
1914 * Returns the Binder object for this provider.
1915 *
1916 * @return the Binder object for this provider
1917 * @hide
1918 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001919 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 public IContentProvider getIContentProvider() {
1921 return mTransport;
1922 }
1923
1924 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001925 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1926 * when directly instantiating the provider for testing.
1927 * @hide
1928 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001929 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001930 public void attachInfoForTesting(Context context, ProviderInfo info) {
1931 attachInfo(context, info, true);
1932 }
1933
1934 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 * After being instantiated, this is called to tell the content provider
1936 * about itself.
1937 *
1938 * @param context The context this provider is running in
1939 * @param info Registered information about this content provider
1940 */
1941 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001942 attachInfo(context, info, false);
1943 }
1944
1945 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001946 mNoPerms = testing;
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 /*
1949 * Only allow it to be set once, so after the content service gives
1950 * this to us clients can't change it.
1951 */
1952 if (mContext == null) {
1953 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001954 if (context != null) {
1955 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1956 Context.APP_OPS_SERVICE);
1957 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001958 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (info != null) {
1960 setReadPermission(info.readPermission);
1961 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001962 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001963 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001964 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001965 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 ContentProvider.this.onCreate();
1968 }
1969 }
Fred Quintanace31b232009-05-04 16:01:15 -07001970
1971 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001972 * Override this to handle requests to perform a batch of operations, or the
1973 * default implementation will iterate over the operations and call
1974 * {@link ContentProviderOperation#apply} on each of them.
1975 * If all calls to {@link ContentProviderOperation#apply} succeed
1976 * then a {@link ContentProviderResult} array with as many
1977 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001978 * fail, it is up to the implementation how many of the others take effect.
1979 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001980 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1981 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001982 *
Fred Quintanace31b232009-05-04 16:01:15 -07001983 * @param operations the operations to apply
1984 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001985 * @throws OperationApplicationException thrown if any operation fails.
1986 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001987 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001988 public @NonNull ContentProviderResult[] applyBatch(
1989 @NonNull ArrayList<ContentProviderOperation> operations)
1990 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001991 final int numOperations = operations.size();
1992 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1993 for (int i = 0; i < numOperations; i++) {
1994 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001995 }
1996 return results;
1997 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001998
1999 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002000 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002001 * interfaces that are cheaper and/or unnatural for a table-like
2002 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002003 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002004 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2005 * on this entry into the content provider besides the basic ability for the application
2006 * to get access to the provider at all. For example, it has no idea whether the call
2007 * being executed may read or write data in the provider, so can't enforce those
2008 * individual permissions. Any implementation of this method <strong>must</strong>
2009 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2010 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002011 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2012 * @param arg provider-defined String argument. May be {@code null}.
2013 * @param extras provider-defined Bundle argument. May be {@code null}.
2014 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002015 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002016 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002017 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2018 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002019 return null;
2020 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002021
2022 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002023 * Implement this to shut down the ContentProvider instance. You can then
2024 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002025 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002026 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002027 * Android normally handles ContentProvider startup and shutdown
2028 * automatically. You do not need to start up or shut down a
2029 * ContentProvider. When you invoke a test method on a ContentProvider,
2030 * however, a ContentProvider instance is started and keeps running after
2031 * the test finishes, even if a succeeding test instantiates another
2032 * ContentProvider. A conflict develops because the two instances are
2033 * usually running against the same underlying data source (for example, an
2034 * sqlite database).
2035 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002036 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002037 * Implementing shutDown() avoids this conflict by providing a way to
2038 * terminate the ContentProvider. This method can also prevent memory leaks
2039 * from multiple instantiations of the ContentProvider, and it can ensure
2040 * unit test isolation by allowing you to completely clean up the test
2041 * fixture before moving on to the next test.
2042 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002043 */
2044 public void shutdown() {
2045 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2046 "connections are gracefully shutdown");
2047 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002048
2049 /**
2050 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002051 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002052 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002053 * @param fd The raw file descriptor that the dump is being sent to.
2054 * @param writer The PrintWriter to which you should dump your state. This will be
2055 * closed for you after you return.
2056 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002057 */
2058 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2059 writer.println("nothing to dump");
2060 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002061
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002062 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002063 private void validateIncomingUri(Uri uri) throws SecurityException {
2064 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002065 if (!mSingleUser) {
2066 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2067 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2068 throw new SecurityException("trying to query a ContentProvider in user "
2069 + mContext.getUserId() + " with a uri belonging to user " + userId);
2070 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002071 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002072 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2073 String message = "The authority of the uri " + uri + " does not match the one of the "
2074 + "contentProvider: ";
2075 if (mAuthority != null) {
2076 message += mAuthority;
2077 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002078 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002079 }
2080 throw new SecurityException(message);
2081 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002082 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002083
2084 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002085 private Uri maybeGetUriWithoutUserId(Uri uri) {
2086 if (mSingleUser) {
2087 return uri;
2088 }
2089 return getUriWithoutUserId(uri);
2090 }
2091
2092 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002093 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2094 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002095 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002096 if (end == -1) return defaultUserId;
2097 String userIdString = auth.substring(0, end);
2098 try {
2099 return Integer.parseInt(userIdString);
2100 } catch (NumberFormatException e) {
2101 Log.w(TAG, "Error parsing userId.", e);
2102 return UserHandle.USER_NULL;
2103 }
2104 }
2105
2106 /** @hide */
2107 public static int getUserIdFromAuthority(String auth) {
2108 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2109 }
2110
2111 /** @hide */
2112 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2113 if (uri == null) return defaultUserId;
2114 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2115 }
2116
2117 /** @hide */
2118 public static int getUserIdFromUri(Uri uri) {
2119 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2120 }
2121
2122 /**
2123 * Removes userId part from authority string. Expects format:
2124 * userId@some.authority
2125 * If there is no userId in the authority, it symply returns the argument
2126 * @hide
2127 */
2128 public static String getAuthorityWithoutUserId(String auth) {
2129 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002130 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002131 return auth.substring(end+1);
2132 }
2133
2134 /** @hide */
2135 public static Uri getUriWithoutUserId(Uri uri) {
2136 if (uri == null) return null;
2137 Uri.Builder builder = uri.buildUpon();
2138 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2139 return builder.build();
2140 }
2141
2142 /** @hide */
2143 public static boolean uriHasUserId(Uri uri) {
2144 if (uri == null) return false;
2145 return !TextUtils.isEmpty(uri.getUserInfo());
2146 }
2147
2148 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002149 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002150 public static Uri maybeAddUserId(Uri uri, int userId) {
2151 if (uri == null) return null;
2152 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002153 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002154 if (!uriHasUserId(uri)) {
2155 //We don't add the user Id if there's already one
2156 Uri.Builder builder = uri.buildUpon();
2157 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2158 return builder.build();
2159 }
2160 }
2161 return uri;
2162 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002163}