PageRenderTime 63ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/core/java/android/content/ContentProvider.java

https://gitlab.com/amardeep434/nitro_base
Java | 1153 lines | 576 code | 89 blank | 488 comment | 120 complexity | da98de39f07ada702841157e674ea000 MD5 | raw file
  1. /*
  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. package android.content;
  17. import static android.Manifest.permission.INTERACT_ACROSS_USERS;
  18. import static android.app.AppOpsManager.MODE_ALLOWED;
  19. import static android.app.AppOpsManager.MODE_ERRORED;
  20. import static android.app.AppOpsManager.MODE_IGNORED;
  21. import static android.content.pm.PackageManager.PERMISSION_GRANTED;
  22. import android.annotation.NonNull;
  23. import android.annotation.Nullable;
  24. import android.app.AppOpsManager;
  25. import android.content.pm.PathPermission;
  26. import android.content.pm.ProviderInfo;
  27. import android.content.res.AssetFileDescriptor;
  28. import android.content.res.Configuration;
  29. import android.database.Cursor;
  30. import android.database.MatrixCursor;
  31. import android.database.SQLException;
  32. import android.net.Uri;
  33. import android.os.AsyncTask;
  34. import android.os.Binder;
  35. import android.os.Bundle;
  36. import android.os.CancellationSignal;
  37. import android.os.IBinder;
  38. import android.os.ICancellationSignal;
  39. import android.os.OperationCanceledException;
  40. import android.os.ParcelFileDescriptor;
  41. import android.os.Process;
  42. import android.os.UserHandle;
  43. import android.text.TextUtils;
  44. import android.util.Log;
  45. import java.io.File;
  46. import java.io.FileDescriptor;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.io.PrintWriter;
  50. import java.util.ArrayList;
  51. import java.util.Arrays;
  52. /**
  53. * Content providers are one of the primary building blocks of Android applications, providing
  54. * content to applications. They encapsulate data and provide it to applications through the single
  55. * {@link ContentResolver} interface. A content provider is only required if you need to share
  56. * data between multiple applications. For example, the contacts data is used by multiple
  57. * applications and must be stored in a content provider. If you don't need to share data amongst
  58. * multiple applications you can use a database directly via
  59. * {@link android.database.sqlite.SQLiteDatabase}.
  60. *
  61. * <p>When a request is made via
  62. * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
  63. * request to the content provider registered with the authority. The content provider can interpret
  64. * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
  65. * URIs.</p>
  66. *
  67. * <p>The primary methods that need to be implemented are:
  68. * <ul>
  69. * <li>{@link #onCreate} which is called to initialize the provider</li>
  70. * <li>{@link #query} which returns data to the caller</li>
  71. * <li>{@link #insert} which inserts new data into the content provider</li>
  72. * <li>{@link #update} which updates existing data in the content provider</li>
  73. * <li>{@link #delete} which deletes data from the content provider</li>
  74. * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
  75. * </ul></p>
  76. *
  77. * <p class="caution">Data access methods (such as {@link #insert} and
  78. * {@link #update}) may be called from many threads at once, and must be thread-safe.
  79. * Other methods (such as {@link #onCreate}) are only called from the application
  80. * main thread, and must avoid performing lengthy operations. See the method
  81. * descriptions for their expected thread behavior.</p>
  82. *
  83. * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
  84. * ContentProvider instance, so subclasses don't have to worry about the details of
  85. * cross-process calls.</p>
  86. *
  87. * <div class="special reference">
  88. * <h3>Developer Guides</h3>
  89. * <p>For more information about using content providers, read the
  90. * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
  91. * developer guide.</p>
  92. */
  93. public abstract class ContentProvider implements ComponentCallbacks2 {
  94. private static final String TAG = "ContentProvider";
  95. /*
  96. * Note: if you add methods to ContentProvider, you must add similar methods to
  97. * MockContentProvider.
  98. */
  99. private Context mContext = null;
  100. private int mMyUid;
  101. // Since most Providers have only one authority, we keep both a String and a String[] to improve
  102. // performance.
  103. private String mAuthority;
  104. private String[] mAuthorities;
  105. private String mReadPermission;
  106. private String mWritePermission;
  107. private PathPermission[] mPathPermissions;
  108. private boolean mExported;
  109. private boolean mNoPerms;
  110. private boolean mSingleUser;
  111. private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
  112. private Transport mTransport = new Transport();
  113. /**
  114. * Construct a ContentProvider instance. Content providers must be
  115. * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
  116. * in the manifest</a>, accessed with {@link ContentResolver}, and created
  117. * automatically by the system, so applications usually do not create
  118. * ContentProvider instances directly.
  119. *
  120. * <p>At construction time, the object is uninitialized, and most fields and
  121. * methods are unavailable. Subclasses should initialize themselves in
  122. * {@link #onCreate}, not the constructor.
  123. *
  124. * <p>Content providers are created on the application main thread at
  125. * application launch time. The constructor must not perform lengthy
  126. * operations, or application startup will be delayed.
  127. */
  128. public ContentProvider() {
  129. }
  130. /**
  131. * Constructor just for mocking.
  132. *
  133. * @param context A Context object which should be some mock instance (like the
  134. * instance of {@link android.test.mock.MockContext}).
  135. * @param readPermission The read permision you want this instance should have in the
  136. * test, which is available via {@link #getReadPermission()}.
  137. * @param writePermission The write permission you want this instance should have
  138. * in the test, which is available via {@link #getWritePermission()}.
  139. * @param pathPermissions The PathPermissions you want this instance should have
  140. * in the test, which is available via {@link #getPathPermissions()}.
  141. * @hide
  142. */
  143. public ContentProvider(
  144. Context context,
  145. String readPermission,
  146. String writePermission,
  147. PathPermission[] pathPermissions) {
  148. mContext = context;
  149. mReadPermission = readPermission;
  150. mWritePermission = writePermission;
  151. mPathPermissions = pathPermissions;
  152. }
  153. /**
  154. * Given an IContentProvider, try to coerce it back to the real
  155. * ContentProvider object if it is running in the local process. This can
  156. * be used if you know you are running in the same process as a provider,
  157. * and want to get direct access to its implementation details. Most
  158. * clients should not nor have a reason to use it.
  159. *
  160. * @param abstractInterface The ContentProvider interface that is to be
  161. * coerced.
  162. * @return If the IContentProvider is non-{@code null} and local, returns its actual
  163. * ContentProvider instance. Otherwise returns {@code null}.
  164. * @hide
  165. */
  166. public static ContentProvider coerceToLocalContentProvider(
  167. IContentProvider abstractInterface) {
  168. if (abstractInterface instanceof Transport) {
  169. return ((Transport)abstractInterface).getContentProvider();
  170. }
  171. return null;
  172. }
  173. /**
  174. * Binder object that deals with remoting.
  175. *
  176. * @hide
  177. */
  178. class Transport extends ContentProviderNative {
  179. AppOpsManager mAppOpsManager = null;
  180. int mReadOp = AppOpsManager.OP_NONE;
  181. int mWriteOp = AppOpsManager.OP_NONE;
  182. ContentProvider getContentProvider() {
  183. return ContentProvider.this;
  184. }
  185. @Override
  186. public String getProviderName() {
  187. return getContentProvider().getClass().getName();
  188. }
  189. @Override
  190. public Cursor query(String callingPkg, Uri uri, String[] projection,
  191. String selection, String[] selectionArgs, String sortOrder,
  192. ICancellationSignal cancellationSignal) {
  193. validateIncomingUri(uri);
  194. uri = getUriWithoutUserId(uri);
  195. if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  196. // The caller has no access to the data, so return an empty cursor with
  197. // the columns in the requested order. The caller may ask for an invalid
  198. // column and we would not catch that but this is not a problem in practice.
  199. // We do not call ContentProvider#query with a modified where clause since
  200. // the implementation is not guaranteed to be backed by a SQL database, hence
  201. // it may not handle properly the tautology where clause we would have created.
  202. if (projection != null) {
  203. return new MatrixCursor(projection, 0);
  204. }
  205. // Null projection means all columns but we have no idea which they are.
  206. // However, the caller may be expecting to access them my index. Hence,
  207. // we have to execute the query as if allowed to get a cursor with the
  208. // columns. We then use the column names to return an empty cursor.
  209. Cursor cursor = ContentProvider.this.query(uri, projection, selection,
  210. selectionArgs, sortOrder, CancellationSignal.fromTransport(
  211. cancellationSignal));
  212. if (cursor == null) {
  213. return null;
  214. }
  215. // Return an empty cursor for all columns.
  216. return new MatrixCursor(cursor.getColumnNames(), 0);
  217. }
  218. final String original = setCallingPackage(callingPkg);
  219. try {
  220. return ContentProvider.this.query(
  221. uri, projection, selection, selectionArgs, sortOrder,
  222. CancellationSignal.fromTransport(cancellationSignal));
  223. } finally {
  224. setCallingPackage(original);
  225. }
  226. }
  227. @Override
  228. public String getType(Uri uri) {
  229. validateIncomingUri(uri);
  230. uri = getUriWithoutUserId(uri);
  231. return ContentProvider.this.getType(uri);
  232. }
  233. @Override
  234. public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
  235. validateIncomingUri(uri);
  236. int userId = getUserIdFromUri(uri);
  237. uri = getUriWithoutUserId(uri);
  238. if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  239. return rejectInsert(uri, initialValues);
  240. }
  241. final String original = setCallingPackage(callingPkg);
  242. try {
  243. return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
  244. } finally {
  245. setCallingPackage(original);
  246. }
  247. }
  248. @Override
  249. public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
  250. validateIncomingUri(uri);
  251. uri = getUriWithoutUserId(uri);
  252. if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  253. return 0;
  254. }
  255. final String original = setCallingPackage(callingPkg);
  256. try {
  257. return ContentProvider.this.bulkInsert(uri, initialValues);
  258. } finally {
  259. setCallingPackage(original);
  260. }
  261. }
  262. @Override
  263. public ContentProviderResult[] applyBatch(String callingPkg,
  264. ArrayList<ContentProviderOperation> operations)
  265. throws OperationApplicationException {
  266. int numOperations = operations.size();
  267. final int[] userIds = new int[numOperations];
  268. for (int i = 0; i < numOperations; i++) {
  269. ContentProviderOperation operation = operations.get(i);
  270. Uri uri = operation.getUri();
  271. validateIncomingUri(uri);
  272. userIds[i] = getUserIdFromUri(uri);
  273. if (userIds[i] != UserHandle.USER_CURRENT) {
  274. // Removing the user id from the uri.
  275. operation = new ContentProviderOperation(operation, true);
  276. operations.set(i, operation);
  277. }
  278. if (operation.isReadOperation()) {
  279. if (enforceReadPermission(callingPkg, uri, null)
  280. != AppOpsManager.MODE_ALLOWED) {
  281. throw new OperationApplicationException("App op not allowed", 0);
  282. }
  283. }
  284. if (operation.isWriteOperation()) {
  285. if (enforceWritePermission(callingPkg, uri, null)
  286. != AppOpsManager.MODE_ALLOWED) {
  287. throw new OperationApplicationException("App op not allowed", 0);
  288. }
  289. }
  290. }
  291. final String original = setCallingPackage(callingPkg);
  292. try {
  293. ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
  294. if (results != null) {
  295. for (int i = 0; i < results.length ; i++) {
  296. if (userIds[i] != UserHandle.USER_CURRENT) {
  297. // Adding the userId to the uri.
  298. results[i] = new ContentProviderResult(results[i], userIds[i]);
  299. }
  300. }
  301. }
  302. return results;
  303. } finally {
  304. setCallingPackage(original);
  305. }
  306. }
  307. @Override
  308. public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
  309. validateIncomingUri(uri);
  310. uri = getUriWithoutUserId(uri);
  311. if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  312. return 0;
  313. }
  314. final String original = setCallingPackage(callingPkg);
  315. try {
  316. return ContentProvider.this.delete(uri, selection, selectionArgs);
  317. } finally {
  318. setCallingPackage(original);
  319. }
  320. }
  321. @Override
  322. public int update(String callingPkg, Uri uri, ContentValues values, String selection,
  323. String[] selectionArgs) {
  324. validateIncomingUri(uri);
  325. uri = getUriWithoutUserId(uri);
  326. if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  327. return 0;
  328. }
  329. final String original = setCallingPackage(callingPkg);
  330. try {
  331. return ContentProvider.this.update(uri, values, selection, selectionArgs);
  332. } finally {
  333. setCallingPackage(original);
  334. }
  335. }
  336. @Override
  337. public ParcelFileDescriptor openFile(
  338. String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
  339. IBinder callerToken) throws FileNotFoundException {
  340. validateIncomingUri(uri);
  341. uri = getUriWithoutUserId(uri);
  342. enforceFilePermission(callingPkg, uri, mode, callerToken);
  343. final String original = setCallingPackage(callingPkg);
  344. try {
  345. return ContentProvider.this.openFile(
  346. uri, mode, CancellationSignal.fromTransport(cancellationSignal));
  347. } finally {
  348. setCallingPackage(original);
  349. }
  350. }
  351. @Override
  352. public AssetFileDescriptor openAssetFile(
  353. String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
  354. throws FileNotFoundException {
  355. validateIncomingUri(uri);
  356. uri = getUriWithoutUserId(uri);
  357. enforceFilePermission(callingPkg, uri, mode, null);
  358. final String original = setCallingPackage(callingPkg);
  359. try {
  360. return ContentProvider.this.openAssetFile(
  361. uri, mode, CancellationSignal.fromTransport(cancellationSignal));
  362. } finally {
  363. setCallingPackage(original);
  364. }
  365. }
  366. @Override
  367. public Bundle call(
  368. String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
  369. Bundle.setDefusable(extras, true);
  370. final String original = setCallingPackage(callingPkg);
  371. try {
  372. return ContentProvider.this.call(method, arg, extras);
  373. } finally {
  374. setCallingPackage(original);
  375. }
  376. }
  377. @Override
  378. public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
  379. validateIncomingUri(uri);
  380. uri = getUriWithoutUserId(uri);
  381. return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
  382. }
  383. @Override
  384. public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
  385. Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
  386. Bundle.setDefusable(opts, true);
  387. validateIncomingUri(uri);
  388. uri = getUriWithoutUserId(uri);
  389. enforceFilePermission(callingPkg, uri, "r", null);
  390. final String original = setCallingPackage(callingPkg);
  391. try {
  392. return ContentProvider.this.openTypedAssetFile(
  393. uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
  394. } finally {
  395. setCallingPackage(original);
  396. }
  397. }
  398. @Override
  399. public ICancellationSignal createCancellationSignal() {
  400. return CancellationSignal.createTransport();
  401. }
  402. @Override
  403. public Uri canonicalize(String callingPkg, Uri uri) {
  404. validateIncomingUri(uri);
  405. int userId = getUserIdFromUri(uri);
  406. uri = getUriWithoutUserId(uri);
  407. if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  408. return null;
  409. }
  410. final String original = setCallingPackage(callingPkg);
  411. try {
  412. return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
  413. } finally {
  414. setCallingPackage(original);
  415. }
  416. }
  417. @Override
  418. public Uri uncanonicalize(String callingPkg, Uri uri) {
  419. validateIncomingUri(uri);
  420. int userId = getUserIdFromUri(uri);
  421. uri = getUriWithoutUserId(uri);
  422. if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
  423. return null;
  424. }
  425. final String original = setCallingPackage(callingPkg);
  426. try {
  427. return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
  428. } finally {
  429. setCallingPackage(original);
  430. }
  431. }
  432. private void enforceFilePermission(String callingPkg, Uri uri, String mode,
  433. IBinder callerToken) throws FileNotFoundException, SecurityException {
  434. if (mode != null && mode.indexOf('w') != -1) {
  435. if (enforceWritePermission(callingPkg, uri, callerToken)
  436. != AppOpsManager.MODE_ALLOWED) {
  437. throw new FileNotFoundException("App op not allowed");
  438. }
  439. } else {
  440. if (enforceReadPermission(callingPkg, uri, callerToken)
  441. != AppOpsManager.MODE_ALLOWED) {
  442. throw new FileNotFoundException("App op not allowed");
  443. }
  444. }
  445. }
  446. private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
  447. throws SecurityException {
  448. final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
  449. if (mode != MODE_ALLOWED) {
  450. return mode;
  451. }
  452. if (mReadOp != AppOpsManager.OP_NONE) {
  453. return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
  454. }
  455. return AppOpsManager.MODE_ALLOWED;
  456. }
  457. private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
  458. throws SecurityException {
  459. final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
  460. if (mode != MODE_ALLOWED) {
  461. return mode;
  462. }
  463. if (mWriteOp != AppOpsManager.OP_NONE) {
  464. return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
  465. }
  466. return AppOpsManager.MODE_ALLOWED;
  467. }
  468. }
  469. boolean checkUser(int pid, int uid, Context context) {
  470. return UserHandle.getUserId(uid) == context.getUserId()
  471. || mSingleUser
  472. || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
  473. == PERMISSION_GRANTED;
  474. }
  475. /**
  476. * Verify that calling app holds both the given permission and any app-op
  477. * associated with that permission.
  478. */
  479. private int checkPermissionAndAppOp(String permission, String callingPkg,
  480. IBinder callerToken) {
  481. if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
  482. callerToken) != PERMISSION_GRANTED) {
  483. return MODE_ERRORED;
  484. }
  485. final int permOp = AppOpsManager.permissionToOpCode(permission);
  486. if (permOp != AppOpsManager.OP_NONE) {
  487. return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
  488. }
  489. return MODE_ALLOWED;
  490. }
  491. /** {@hide} */
  492. protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
  493. throws SecurityException {
  494. final Context context = getContext();
  495. final int pid = Binder.getCallingPid();
  496. final int uid = Binder.getCallingUid();
  497. String missingPerm = null;
  498. int strongestMode = MODE_ALLOWED;
  499. if (UserHandle.isSameApp(uid, mMyUid)) {
  500. return MODE_ALLOWED;
  501. }
  502. if (mExported && checkUser(pid, uid, context)) {
  503. final String componentPerm = getReadPermission();
  504. if (componentPerm != null) {
  505. final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
  506. if (mode == MODE_ALLOWED) {
  507. return MODE_ALLOWED;
  508. } else {
  509. missingPerm = componentPerm;
  510. strongestMode = Math.max(strongestMode, mode);
  511. }
  512. }
  513. // track if unprotected read is allowed; any denied
  514. // <path-permission> below removes this ability
  515. boolean allowDefaultRead = (componentPerm == null);
  516. final PathPermission[] pps = getPathPermissions();
  517. if (pps != null) {
  518. final String path = uri.getPath();
  519. for (PathPermission pp : pps) {
  520. final String pathPerm = pp.getReadPermission();
  521. if (pathPerm != null && pp.match(path)) {
  522. final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
  523. if (mode == MODE_ALLOWED) {
  524. return MODE_ALLOWED;
  525. } else {
  526. // any denied <path-permission> means we lose
  527. // default <provider> access.
  528. allowDefaultRead = false;
  529. missingPerm = pathPerm;
  530. strongestMode = Math.max(strongestMode, mode);
  531. }
  532. }
  533. }
  534. }
  535. // if we passed <path-permission> checks above, and no default
  536. // <provider> permission, then allow access.
  537. if (allowDefaultRead) return MODE_ALLOWED;
  538. }
  539. // last chance, check against any uri grants
  540. final int callingUserId = UserHandle.getUserId(uid);
  541. final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
  542. ? maybeAddUserId(uri, callingUserId) : uri;
  543. if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
  544. callerToken) == PERMISSION_GRANTED) {
  545. return MODE_ALLOWED;
  546. }
  547. // If the worst denial we found above was ignored, then pass that
  548. // ignored through; otherwise we assume it should be a real error below.
  549. if (strongestMode == MODE_IGNORED) {
  550. return MODE_IGNORED;
  551. }
  552. final String failReason = mExported
  553. ? " requires " + missingPerm + ", or grantUriPermission()"
  554. : " requires the provider be exported, or grantUriPermission()";
  555. throw new SecurityException("Permission Denial: reading "
  556. + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
  557. + ", uid=" + uid + failReason);
  558. }
  559. /** {@hide} */
  560. protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
  561. throws SecurityException {
  562. final Context context = getContext();
  563. final int pid = Binder.getCallingPid();
  564. final int uid = Binder.getCallingUid();
  565. String missingPerm = null;
  566. int strongestMode = MODE_ALLOWED;
  567. if (UserHandle.isSameApp(uid, mMyUid)) {
  568. return MODE_ALLOWED;
  569. }
  570. if (mExported && checkUser(pid, uid, context)) {
  571. final String componentPerm = getWritePermission();
  572. if (componentPerm != null) {
  573. final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
  574. if (mode == MODE_ALLOWED) {
  575. return MODE_ALLOWED;
  576. } else {
  577. missingPerm = componentPerm;
  578. strongestMode = Math.max(strongestMode, mode);
  579. }
  580. }
  581. // track if unprotected write is allowed; any denied
  582. // <path-permission> below removes this ability
  583. boolean allowDefaultWrite = (componentPerm == null);
  584. final PathPermission[] pps = getPathPermissions();
  585. if (pps != null) {
  586. final String path = uri.getPath();
  587. for (PathPermission pp : pps) {
  588. final String pathPerm = pp.getWritePermission();
  589. if (pathPerm != null && pp.match(path)) {
  590. final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
  591. if (mode == MODE_ALLOWED) {
  592. return MODE_ALLOWED;
  593. } else {
  594. // any denied <path-permission> means we lose
  595. // default <provider> access.
  596. allowDefaultWrite = false;
  597. missingPerm = pathPerm;
  598. strongestMode = Math.max(strongestMode, mode);
  599. }
  600. }
  601. }
  602. }
  603. // if we passed <path-permission> checks above, and no default
  604. // <provider> permission, then allow access.
  605. if (allowDefaultWrite) return MODE_ALLOWED;
  606. }
  607. // last chance, check against any uri grants
  608. if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
  609. callerToken) == PERMISSION_GRANTED) {
  610. return MODE_ALLOWED;
  611. }
  612. // If the worst denial we found above was ignored, then pass that
  613. // ignored through; otherwise we assume it should be a real error below.
  614. if (strongestMode == MODE_IGNORED) {
  615. return MODE_IGNORED;
  616. }
  617. final String failReason = mExported
  618. ? " requires " + missingPerm + ", or grantUriPermission()"
  619. : " requires the provider be exported, or grantUriPermission()";
  620. throw new SecurityException("Permission Denial: writing "
  621. + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
  622. + ", uid=" + uid + failReason);
  623. }
  624. /**
  625. * Retrieves the Context this provider is running in. Only available once
  626. * {@link #onCreate} has been called -- this will return {@code null} in the
  627. * constructor.
  628. */
  629. public final @Nullable Context getContext() {
  630. return mContext;
  631. }
  632. /**
  633. * Set the calling package, returning the current value (or {@code null})
  634. * which can be used later to restore the previous state.
  635. */
  636. private String setCallingPackage(String callingPackage) {
  637. final String original = mCallingPackage.get();
  638. mCallingPackage.set(callingPackage);
  639. return original;
  640. }
  641. /**
  642. * Return the package name of the caller that initiated the request being
  643. * processed on the current thread. The returned package will have been
  644. * verified to belong to the calling UID. Returns {@code null} if not
  645. * currently processing a request.
  646. * <p>
  647. * This will always return {@code null} when processing
  648. * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
  649. *
  650. * @see Binder#getCallingUid()
  651. * @see Context#grantUriPermission(String, Uri, int)
  652. * @throws SecurityException if the calling package doesn't belong to the
  653. * calling UID.
  654. */
  655. public final @Nullable String getCallingPackage() {
  656. final String pkg = mCallingPackage.get();
  657. if (pkg != null) {
  658. mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
  659. }
  660. return pkg;
  661. }
  662. /**
  663. * Change the authorities of the ContentProvider.
  664. * This is normally set for you from its manifest information when the provider is first
  665. * created.
  666. * @hide
  667. * @param authorities the semi-colon separated authorities of the ContentProvider.
  668. */
  669. protected final void setAuthorities(String authorities) {
  670. if (authorities != null) {
  671. if (authorities.indexOf(';') == -1) {
  672. mAuthority = authorities;
  673. mAuthorities = null;
  674. } else {
  675. mAuthority = null;
  676. mAuthorities = authorities.split(";");
  677. }
  678. }
  679. }
  680. /** @hide */
  681. protected final boolean matchesOurAuthorities(String authority) {
  682. if (mAuthority != null) {
  683. return mAuthority.equals(authority);
  684. }
  685. if (mAuthorities != null) {
  686. int length = mAuthorities.length;
  687. for (int i = 0; i < length; i++) {
  688. if (mAuthorities[i].equals(authority)) return true;
  689. }
  690. }
  691. return false;
  692. }
  693. /**
  694. * Change the permission required to read data from the content
  695. * provider. This is normally set for you from its manifest information
  696. * when the provider is first created.
  697. *
  698. * @param permission Name of the permission required for read-only access.
  699. */
  700. protected final void setReadPermission(@Nullable String permission) {
  701. mReadPermission = permission;
  702. }
  703. /**
  704. * Return the name of the permission required for read-only access to
  705. * this content provider. This method can be called from multiple
  706. * threads, as described in
  707. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  708. * and Threads</a>.
  709. */
  710. public final @Nullable String getReadPermission() {
  711. return mReadPermission;
  712. }
  713. /**
  714. * Change the permission required to read and write data in the content
  715. * provider. This is normally set for you from its manifest information
  716. * when the provider is first created.
  717. *
  718. * @param permission Name of the permission required for read/write access.
  719. */
  720. protected final void setWritePermission(@Nullable String permission) {
  721. mWritePermission = permission;
  722. }
  723. /**
  724. * Return the name of the permission required for read/write access to
  725. * this content provider. This method can be called from multiple
  726. * threads, as described in
  727. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  728. * and Threads</a>.
  729. */
  730. public final @Nullable String getWritePermission() {
  731. return mWritePermission;
  732. }
  733. /**
  734. * Change the path-based permission required to read and/or write data in
  735. * the content provider. This is normally set for you from its manifest
  736. * information when the provider is first created.
  737. *
  738. * @param permissions Array of path permission descriptions.
  739. */
  740. protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
  741. mPathPermissions = permissions;
  742. }
  743. /**
  744. * Return the path-based permissions required for read and/or write access to
  745. * this content provider. This method can be called from multiple
  746. * threads, as described in
  747. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  748. * and Threads</a>.
  749. */
  750. public final @Nullable PathPermission[] getPathPermissions() {
  751. return mPathPermissions;
  752. }
  753. /** @hide */
  754. public final void setAppOps(int readOp, int writeOp) {
  755. if (!mNoPerms) {
  756. mTransport.mReadOp = readOp;
  757. mTransport.mWriteOp = writeOp;
  758. }
  759. }
  760. /** @hide */
  761. public AppOpsManager getAppOpsManager() {
  762. return mTransport.mAppOpsManager;
  763. }
  764. /**
  765. * Implement this to initialize your content provider on startup.
  766. * This method is called for all registered content providers on the
  767. * application main thread at application launch time. It must not perform
  768. * lengthy operations, or application startup will be delayed.
  769. *
  770. * <p>You should defer nontrivial initialization (such as opening,
  771. * upgrading, and scanning databases) until the content provider is used
  772. * (via {@link #query}, {@link #insert}, etc). Deferred initialization
  773. * keeps application startup fast, avoids unnecessary work if the provider
  774. * turns out not to be needed, and stops database errors (such as a full
  775. * disk) from halting application launch.
  776. *
  777. * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
  778. * is a helpful utility class that makes it easy to manage databases,
  779. * and will automatically defer opening until first use. If you do use
  780. * SQLiteOpenHelper, make sure to avoid calling
  781. * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
  782. * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
  783. * from this method. (Instead, override
  784. * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
  785. * database when it is first opened.)
  786. *
  787. * @return true if the provider was successfully loaded, false otherwise
  788. */
  789. public abstract boolean onCreate();
  790. /**
  791. * {@inheritDoc}
  792. * This method is always called on the application main thread, and must
  793. * not perform lengthy operations.
  794. *
  795. * <p>The default content provider implementation does nothing.
  796. * Override this method to take appropriate action.
  797. * (Content providers do not usually care about things like screen
  798. * orientation, but may want to know about locale changes.)
  799. */
  800. public void onConfigurationChanged(Configuration newConfig) {
  801. }
  802. /**
  803. * {@inheritDoc}
  804. * This method is always called on the application main thread, and must
  805. * not perform lengthy operations.
  806. *
  807. * <p>The default content provider implementation does nothing.
  808. * Subclasses may override this method to take appropriate action.
  809. */
  810. public void onLowMemory() {
  811. }
  812. public void onTrimMemory(int level) {
  813. }
  814. /**
  815. * Implement this to handle query requests from clients.
  816. * This method can be called from multiple threads, as described in
  817. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  818. * and Threads</a>.
  819. * <p>
  820. * Example client call:<p>
  821. * <pre>// Request a specific record.
  822. * Cursor managedCursor = managedQuery(
  823. ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
  824. projection, // Which columns to return.
  825. null, // WHERE clause.
  826. null, // WHERE clause value substitution
  827. People.NAME + " ASC"); // Sort order.</pre>
  828. * Example implementation:<p>
  829. * <pre>// SQLiteQueryBuilder is a helper class that creates the
  830. // proper SQL syntax for us.
  831. SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
  832. // Set the table we're querying.
  833. qBuilder.setTables(DATABASE_TABLE_NAME);
  834. // If the query ends in a specific record number, we're
  835. // being asked for a specific record, so set the
  836. // WHERE clause in our query.
  837. if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
  838. qBuilder.appendWhere("_id=" + uri.getPathLeafId());
  839. }
  840. // Make the query.
  841. Cursor c = qBuilder.query(mDb,
  842. projection,
  843. selection,
  844. selectionArgs,
  845. groupBy,
  846. having,
  847. sortOrder);
  848. c.setNotificationUri(getContext().getContentResolver(), uri);
  849. return c;</pre>
  850. *
  851. * @param uri The URI to query. This will be the full URI sent by the client;
  852. * if the client is requesting a specific record, the URI will end in a record number
  853. * that the implementation should parse and add to a WHERE or HAVING clause, specifying
  854. * that _id value.
  855. * @param projection The list of columns to put into the cursor. If
  856. * {@code null} all columns are included.
  857. * @param selection A selection criteria to apply when filtering rows.
  858. * If {@code null} then all rows are included.
  859. * @param selectionArgs You may include ?s in selection, which will be replaced by
  860. * the values from selectionArgs, in order that they appear in the selection.
  861. * The values will be bound as Strings.
  862. * @param sortOrder How the rows in the cursor should be sorted.
  863. * If {@code null} then the provider is free to define the sort order.
  864. * @return a Cursor or {@code null}.
  865. */
  866. public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
  867. @Nullable String selection, @Nullable String[] selectionArgs,
  868. @Nullable String sortOrder);
  869. /**
  870. * Implement this to handle query requests from clients with support for cancellation.
  871. * This method can be called from multiple threads, as described in
  872. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  873. * and Threads</a>.
  874. * <p>
  875. * Example client call:<p>
  876. * <pre>// Request a specific record.
  877. * Cursor managedCursor = managedQuery(
  878. ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
  879. projection, // Which columns to return.
  880. null, // WHERE clause.
  881. null, // WHERE clause value substitution
  882. People.NAME + " ASC"); // Sort order.</pre>
  883. * Example implementation:<p>
  884. * <pre>// SQLiteQueryBuilder is a helper class that creates the
  885. // proper SQL syntax for us.
  886. SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
  887. // Set the table we're querying.
  888. qBuilder.setTables(DATABASE_TABLE_NAME);
  889. // If the query ends in a specific record number, we're
  890. // being asked for a specific record, so set the
  891. // WHERE clause in our query.
  892. if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
  893. qBuilder.appendWhere("_id=" + uri.getPathLeafId());
  894. }
  895. // Make the query.
  896. Cursor c = qBuilder.query(mDb,
  897. projection,
  898. selection,
  899. selectionArgs,
  900. groupBy,
  901. having,
  902. sortOrder);
  903. c.setNotificationUri(getContext().getContentResolver(), uri);
  904. return c;</pre>
  905. * <p>
  906. * If you implement this method then you must also implement the version of
  907. * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
  908. * signal to ensure correct operation on older versions of the Android Framework in
  909. * which the cancellation signal overload was not available.
  910. *
  911. * @param uri The URI to query. This will be the full URI sent by the client;
  912. * if the client is requesting a specific record, the URI will end in a record number
  913. * that the implementation should parse and add to a WHERE or HAVING clause, specifying
  914. * that _id value.
  915. * @param projection The list of columns to put into the cursor. If
  916. * {@code null} all columns are included.
  917. * @param selection A selection criteria to apply when filtering rows.
  918. * If {@code null} then all rows are included.
  919. * @param selectionArgs You may include ?s in selection, which will be replaced by
  920. * the values from selectionArgs, in order that they appear in the selection.
  921. * The values will be bound as Strings.
  922. * @param sortOrder How the rows in the cursor should be sorted.
  923. * If {@code null} then the provider is free to define the sort order.
  924. * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
  925. * If the operation is canceled, then {@link OperationCanceledException} will be thrown
  926. * when the query is executed.
  927. * @return a Cursor or {@code null}.
  928. */
  929. public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
  930. @Nullable String selection, @Nullable String[] selectionArgs,
  931. @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
  932. return query(uri, projection, selection, selectionArgs, sortOrder);
  933. }
  934. /**
  935. * Implement this to handle requests for the MIME type of the data at the
  936. * given URI. The returned MIME type should start with
  937. * <code>vnd.android.cursor.item</code> for a single record,
  938. * or <code>vnd.android.cursor.dir/</code> for multiple items.
  939. * This method can be called from multiple threads, as described in
  940. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  941. * and Threads</a>.
  942. *
  943. * <p>Note that there are no permissions needed for an application to
  944. * access this information; if your content provider requires read and/or
  945. * write permissions, or is not exported, all applications can still call
  946. * this method regardless of their access permissions. This allows them
  947. * to retrieve the MIME type for a URI when dispatching intents.
  948. *
  949. * @param uri the URI to query.
  950. * @return a MIME type string, or {@code null} if there is no type.
  951. */
  952. public abstract @Nullable String getType(@NonNull Uri uri);
  953. /**
  954. * Implement this to support canonicalization of URIs that refer to your
  955. * content provider. A canonical URI is one that can be transported across
  956. * devices, backup/restore, and other contexts, and still be able to refer
  957. * to the same data item. Typically this is implemented by adding query
  958. * params to the URI allowing the content provider to verify that an incoming
  959. * canonical URI references the same data as it was originally intended for and,
  960. * if it doesn't, to find that data (if it exists) in the current environment.
  961. *
  962. * <p>For example, if the content provider holds people and a normal URI in it
  963. * is created with a row index into that people database, the cananical representation
  964. * may have an additional query param at the end which specifies the name of the
  965. * person it is intended for. Later calls into the provider with that URI will look
  966. * up the row of that URI's base index and, if it doesn't match or its entry's
  967. * name doesn't match the name in the query param, perform a query on its database
  968. * to find the correct row to operate on.</p>
  969. *
  970. * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
  971. * URIs (including this one) must perform this verification and recovery of any
  972. * canonical URIs they receive. In addition, you must also implement
  973. * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
  974. *
  975. * <p>The default implementation of this method returns null, indicating that
  976. * canonical URIs are not supported.</p>
  977. *
  978. * @param url The Uri to canonicalize.
  979. *
  980. * @return Return the canonical representation of <var>url</var>, or null if
  981. * canonicalization of that Uri is not supported.
  982. */
  983. public @Nullable Uri canonicalize(@NonNull Uri url) {
  984. return null;
  985. }
  986. /**
  987. * Remove canonicalization from canonical URIs previously returned by
  988. * {@link #canonicalize}. For example, if your implementation is to add
  989. * a query param to canonicalize a URI, this method can simply trip any
  990. * query params on the URI. The default implementation always returns the
  991. * same <var>url</var> that was passed in.
  992. *
  993. * @param url The Uri to remove any canonicalization from.
  994. *
  995. * @return Return the non-canonical representation of <var>url</var>, return
  996. * the <var>url</var> as-is if there is nothing to do, or return null if
  997. * the data identified by the canonical representation can not be found in
  998. * the current environment.
  999. */
  1000. public @Nullable Uri uncanonicalize(@NonNull Uri url) {
  1001. return url;
  1002. }
  1003. /**
  1004. * @hide
  1005. * Implementation when a caller has performed an insert on the content
  1006. * provider, but that call has been rejected for the operation given
  1007. * to {@link #setAppOps(int, int)}. The default implementation simply
  1008. * returns a dummy URI that is the base URI with a 0 path element
  1009. * appended.
  1010. */
  1011. public Uri rejectInsert(Uri uri, ContentValues values) {
  1012. // If not allowed, we need to return some reasonable URI. Maybe the
  1013. // content provider should be responsible for this, but for now we
  1014. // will just return the base URI with a dummy '0' tagged on to it.
  1015. // You shouldn't be able to read if you can't write, anyway, so it
  1016. // shouldn't matter much what is returned.
  1017. return uri.buildUpon().appendPath("0").build();
  1018. }
  1019. /**
  1020. * Implement this to handle requests to insert a new row.
  1021. * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
  1022. * after inserting.
  1023. * This method can be called from multiple threads, as described in
  1024. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  1025. * and Threads</a>.
  1026. * @param uri The content:// URI of the insertion request. This must not be {@code null}.
  1027. * @param values A set of column_name/value pairs to add to the database.
  1028. * This must not be {@code null}.
  1029. * @return The URI for the newly inserted item.
  1030. */
  1031. public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
  1032. /**
  1033. * Override this to handle requests to insert a set of new rows, or the
  1034. * default implementation will iterate over the values and call
  1035. * {@link #insert} on each of them.
  1036. * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
  1037. * after inserting.
  1038. * This method can be called from multiple threads, as described in
  1039. * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
  1040. * and Threads</a>.
  1041. *
  1042. * @param uri The content:// URI of the insertion request.
  1043. * @param values An array of sets of column_name/value pairs to add to the database.
  1044. * This must not be {@code null}.
  1045. * @return The number of values that were inserted.
  1046. */
  1047. public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
  1048. int numValues = values.length;
  1049. for (int i = 0; i < numValues; i++) {
  1050. insert(uri, values[i]);
  1051. }
  1052. return numValues;
  1053. }
  1054. /**
  1055. * Implement this to handle requests to delete one or more rows.
  1056. * The implementation should apply the selection clause when performing
  1057. * deletion, allowing the operation to affect multiple rows in a directory.
  1058. * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserv