@TargetApi(19) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= Build.VERSION_CODES.KITKAT) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class); int property = (Integer) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); return AppOpsManager.MODE_ALLOWED == property; } catch (Exception e) { e.printStackTrace(); } } return false; }
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) throws Exception { List<String> segments = uri.getPathSegments(); int accountId = Integer.parseInt(segments.get(1)); /* * This method below calls Account.getStats() which uses EmailProvider to do its work. * For this to work we need to clear the calling identity. Otherwise accessing * EmailProvider will fail because it's not exported so third-party apps can't access it * directly. */ long identityToken = Binder.clearCallingIdentity(); try { return getAccountUnread(accountId); } finally { Binder.restoreCallingIdentity(identityToken); } }
@Override protected void after(XParam param) throws Throwable { String key = (param.args.length > 0 ? (String) param.args[0] : null); if (key != null) if (mPropertyName.startsWith("%") ? key.contains(mPropertyName.substring(1)) : key.equals(mPropertyName)) if (mMethod == Methods.get) { if (param.getResult() != null && isRestrictedExtra(param, mPropertyName, key)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), mPropertyName)); } else if (param.args.length > 1) { if (isRestrictedExtra(param, mPropertyName, key)) param.setResult(param.args[1]); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } else { Log.e(TAG, "Below API 19 cannot invoke!"); } return false; }
@Override public Cursor queryChildDocuments(String docId, String[] projection, String sortOrder) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); // Delegate to real provider final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { Query query = new Query(); DownloadManagerUtils.setOnlyIncludeVisibleInDownloadsUi(query); //query.setOnlyIncludeVisibleInDownloadsUi(true); query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL); //query.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_FAILED); cursor = mDm.query(query);//.setOnlyIncludeVisibleInDownloadsUi(true) //.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL)); //copyNotificationUri(result, cursor); while (cursor.moveToNext()) { includeDownloadFromCursor(result, cursor); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } return result; }
private static void createService(Service service, Intent intent) { if (intent.hasExtra(ApkConstant.EXTRA_APK_PATH)) { String apkPath = ApkComponentModifier.getPath(intent); String className = ApkComponentModifier.getClassName(intent); String key = ApkComponentModifier.getKey(intent); if (!mRealServices.containsKey(service) || !mRealServices.get(service).containsKey(key)) { try { Object realToken = new Binder(); Service rawService = handleCreateService(realToken, service, apkPath, className); if (mRealServices.containsKey(service)) { mRealServices.get(service).put(key, rawService); } else { Map<String, Service> serviceMap = new HashMap<>(); serviceMap.put(key, rawService); mRealServices.put(service, serviceMap); } } catch (Exception e) { } } } }
@Override public void asyncGetService(String serviceName, IServiceCallback callback) throws RemoteException { LogControler.info("ServiceManagerServer", "[svcmgr server] asyncGetService name = " + serviceName + " , callingpid = " + Binder.getCallingPid()); IBinder service = clientServiceContainer.get(serviceName); if(service == null) { service = BinderQuerier.query(serviceName); } if(service == null){ asyncClientServiceContainer.put(serviceName, IServiceCallbackProxy.proxy(serviceName,callback)); } else { callback.callback(service); } }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } else { Log.e("", "Below API 19 cannot invoke!"); } return false; }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } else { Log.e(TAG, "Below API 19 cannot invoke!"); } return false; }
@Override public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal) throws FileNotFoundException { if (!"r".equals(mode)) { throw new IllegalArgumentException("Media is read-only"); } final Uri target = getUriForDocumentId(docId); // Delegate to real provider final long token = Binder.clearCallingIdentity(); try { return getContext().getContentResolver().openFileDescriptor(target, mode); } finally { Binder.restoreCallingIdentity(token); } }
@Override public void addService(String serviceName, IBinder service) throws RemoteException { LogControler.info("ServiceManagerServer", "[svcmgr server] addService name = " + serviceName + " , service = " + service+ " , callingpid = " + Binder.getCallingPid()); service.linkToDeath(new BinderServiceDeathRecipient(serviceName),0); clientServiceContainer.put(serviceName, service); //查看是否有listen这个服务的 IServiceCallbackProxy serviceCallback = asyncClientServiceContainer.get(serviceName); if(serviceCallback!=null){ try { LogControler.info("ServiceManagerServer", "[svcmgr server] addService onReady"); serviceCallback.callback(service); } catch(Exception e){ e.printStackTrace(); } } else { LogControler.info("ServiceManagerServer", "[svcmgr server] addService serviceCallback not found"); } }
@Override protected void after(XParam param) throws Throwable { if (mMethod == Methods.getDetailedState) { if (param.getResult() != null && isRestricted(param)) param.setResult(NetworkInfo.DetailedState.DISCONNECTED); } else if (mMethod == Methods.getExtraInfo) { if (param.getResult() != null && isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), "ExtraInfo")); } else if (mMethod == Methods.getState) { if (param.getResult() != null && isRestricted(param)) param.setResult(NetworkInfo.State.DISCONNECTED); } else if (mMethod == Methods.isConnected || mMethod == Methods.isConnectedOrConnecting) { if (isRestricted(param)) param.setResult(false); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); }
@Override public void deleteDocument(String docId) throws FileNotFoundException { final String packageName = getPackageForDocId(docId); final long token = Binder.clearCallingIdentity(); try { if (docId.startsWith(ROOT_ID_USER_APP)) { PackageManagerUtils.uninstallApp(getContext(), packageName); } else if(docId.startsWith(ROOT_ID_PROCESS)) { activityManager.killBackgroundProcesses(getPackageForDocId(docId)); } notifyDocumentsChanged(docId); } finally { Binder.restoreCallingIdentity(token); } }
@Override public Cursor queryChildDocumentsForManage( String parentDocumentId, String[] projection, String sortOrder) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); // Delegate to real provider final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { cursor = mDm.query( new DownloadManager.Query());//.setOnlyIncludeVisibleInDownloadsUi(true)); //copyNotificationUri(result, cursor); while (cursor.moveToNext()) { includeDownloadFromCursor(result, cursor); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } return result; }
@Override public Cursor queryChildDocuments(String docId, String[] projection, String sortOrder) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); final Ident ident = getIdentForDocId(docId); final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { if (TYPE_DOCUMENT_ROOT.equals(ident.type)) { queryFile(resolver, cursor, result, DOCUMENT_MIMES, "text"); } else if (TYPE_ARCHIVE_ROOT.equals(ident.type)) { queryFile(resolver, cursor, result, ARCHIVE_MIMES); } else if (TYPE_APK_ROOT.equals(ident.type)) { queryFile(resolver, cursor, result, APK_MIMES); } else { throw new UnsupportedOperationException("Unsupported document " + docId); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } return result; }
@Override public Cursor queryRecentDocuments(String rootId, String[] projection) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { if (TYPE_DOCUMENT_ROOT.equals(rootId)) { queryRecentFile(resolver, cursor, result, DOCUMENT_MIMES); } else { throw new UnsupportedOperationException("Unsupported root " + rootId); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } return result; }
private boolean isEmpty(Uri uri, String type) { final ContentResolver resolver = getContext().getContentResolver(); final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { String[] mimeType; if (TYPE_DOCUMENT_ROOT.equals(type)) { mimeType = DOCUMENT_MIMES; } else if (TYPE_ARCHIVE_ROOT.equals(type)) { mimeType = ARCHIVE_MIMES; } else if (TYPE_APK_ROOT.equals(type)) { mimeType = APK_MIMES; } else { return true; } cursor = resolver.query(FILE_URI, FileQuery.PROJECTION, FileColumns.MIME_TYPE + " IN "+ "("+toString(mimeType)+")" , null, null); return (cursor == null) || (cursor.getCount() == 0); } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } }
@Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.next) { // Do nothing } else if (mMethod == Methods.handleReceiver) { if (param.args.length > 0 && param.args[0] != null) { Field fieldIntent = param.args[0].getClass().getDeclaredField("intent"); fieldIntent.setAccessible(true); Intent intent = (Intent) fieldIntent.get(param.args[0]); if (intent != null) { if (checkIntent(Binder.getCallingUid(), intent)) { finish(param); param.setResult(null); } } } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); }
@Override public void onDataSetChanged() { if (data != null) { data.close(); } // This method is called by the app hosting the widget (e.g., the launcher) // However, our ContentProvider is not exported so it doesn't have access to the // data. Therefore we need to clear (and finally restore) the calling identity so // that calls use our process and permission final long identityToken = Binder.clearCallingIdentity(); data = mContext.getContentResolver().query(ArticleContract.ArticleEntry.CONTENT_URI, null, null, null, null); Binder.restoreCallingIdentity(identityToken); }
private boolean validatePostMessageOriginInternal(final CustomTabsSessionToken session) { if (!mWarmupHasBeenCalled.get()) return false; if (!isCallerForegroundOrSelf()) return false; final int uid = Binder.getCallingUid(); ThreadUtils.postOnUiThread(new Runnable() { @Override public void run() { // If the API is not enabled, we don't set the post message origin, which will // avoid PostMessageHandler initialization and disallow postMessage calls. if (!ChromeFeatureList.isEnabled(ChromeFeatureList.CCT_POST_MESSAGE_API)) return; mClientManager.setPostMessageOriginForSession( session, acquireOriginForSession(session, uid)); } }); return true; }
public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); if (shouldNotBlockOtherInfo()) { return IntentMatcher.resolveActivityIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags); } List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); List<ResolveInfo> infos = new ArrayList(); for (String pkg : pkgs) { intent.setPackage(pkg); infos.addAll(IntentMatcher.resolveActivityIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags)); } if (infos != null) { if (infos.size() > 0) { return infos; } } return null; } catch (Exception e) { handleException(e); } }
public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); if (shouldNotBlockOtherInfo()) { IntentMatcher.resolveServiceIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags); } else { List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); List<ResolveInfo> infos = new ArrayList(); for (String pkg : pkgs) { intent.setPackage(pkg); infos.addAll(IntentMatcher.resolveServiceIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags)); } if (infos != null) { if (infos.size() > 0) { return infos; } } } } catch (Exception e) { handleException(e); } return null; }
public List<ResolveInfo> queryIntentContentProviders(Intent intent, String resolvedType, int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); if (shouldNotBlockOtherInfo()) { return IntentMatcher.resolveProviderIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags); } List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); List<ResolveInfo> infos = new ArrayList(); for (String pkg : pkgs) { intent.setPackage(pkg); infos.addAll(IntentMatcher.resolveProviderIntent(this.mContext, this.mPluginCache, intent, resolvedType, flags)); } if (infos != null) { if (infos.size() > 0) { return infos; } } return null; } catch (Exception e) { handleException(e); } }
public List<ApplicationInfo> getInstalledApplications(int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); List<ApplicationInfo> infos = new ArrayList(this.mPluginCache.size()); if (shouldNotBlockOtherInfo()) { for (PluginPackageParser pluginPackageParser : this.mPluginCache.values()) { infos.add(pluginPackageParser.getApplicationInfo(flags)); } return infos; } List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); for (PluginPackageParser pluginPackageParser2 : this.mPluginCache.values()) { if (pkgs.contains(pluginPackageParser2.getPackageName())) { infos.add(pluginPackageParser2.getApplicationInfo(flags)); } } return infos; } catch (Exception e) { handleException(e); return null; } }
@Override public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); if (shouldNotBlockOtherInfo()) { return IntentMatcher.resolveReceiverIntent(mContext, mPluginCache, intent, resolvedType, flags); } else { List<String> pkgs = mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); List<ResolveInfo> infos = new ArrayList<ResolveInfo>(); for (String pkg : pkgs) { intent.setPackage(pkg); List<ResolveInfo> list = IntentMatcher.resolveReceiverIntent(mContext, mPluginCache, intent, resolvedType, flags); infos.addAll(list); } if (infos != null && infos.size() > 0) { return infos; } } } catch (Exception e) { handleException(e); } return null; }
@Override public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); if (shouldNotBlockOtherInfo()) { return IntentMatcher.resolveServiceIntent(mContext, mPluginCache, intent, resolvedType, flags); } else { List<String> pkgs = mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); List<ResolveInfo> infos = new ArrayList<ResolveInfo>(); for (String pkg : pkgs) { intent.setPackage(pkg); List<ResolveInfo> list = IntentMatcher.resolveServiceIntent(mContext, mPluginCache, intent, resolvedType, flags); infos.addAll(list); } if (infos != null && infos.size() > 0) { return infos; } } } catch (Exception e) { handleException(e); } return null; }
public ProviderInfo resolveContentProvider(String name, int flags) throws RemoteException { waitForReadyInner(); try { enforcePluginFileExists(); if (shouldNotBlockOtherInfo()) { for (PluginPackageParser pluginPackageParser : this.mPluginCache.values()) { for (ProviderInfo providerInfo : pluginPackageParser.getProviders()) { if (TextUtils.equals(providerInfo.authority, name)) { return providerInfo; } } } } List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid()); for (PluginPackageParser pluginPackageParser2 : this.mPluginCache.values()) { for (ProviderInfo providerInfo2 : pluginPackageParser2.getProviders()) { if (TextUtils.equals(providerInfo2.authority, name) && pkgs.contains(providerInfo2.packageName)) { return providerInfo2; } } } } catch (Exception e) { handleException(e); } return null; }
@Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getDeviceId: if (param.args.length > 0 && param.args[0] instanceof String) { if (isRestrictedExtra(param, (String) param.args[0])) param.setResult(0); } else { if (isRestricted(param)) param.setResult(0); } break; case getDeviceName: case getSerialNumber: if (param.getResult() != null && isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), "USB")); break; } }
@Override public Cursor queryDocument(String docId, String[] projection) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); if (DOC_ID_ROOT.equals(docId)) { includeDefaultDocument(result); } else { // Delegate to real provider final long token = Binder.clearCallingIdentity(); Cursor cursor = null; try { cursor = mDm.query(new Query().setFilterById(Long.parseLong(docId))); //copyNotificationUri(result, cursor); if (cursor.moveToFirst()) { includeDownloadFromCursor(result, cursor); } } finally { IoUtils.closeQuietly(cursor); Binder.restoreCallingIdentity(token); } } return result; }
@Override protected void after(XParam param) throws Throwable { switch (mMethod) { case addGeofences: case removeGeofences: // Do nothing break; case getLastLocation: Location location = (Location) param.getResult(); if (location != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedLocation(Binder.getCallingUid(), location)); break; case removeLocationUpdates: // Do nothing break; case requestLocationUpdates: // Do nothing break; } }
@Override protected void after(XParam param) throws Throwable { int uid = Binder.getCallingUid(); switch (mMethod) { case getAddress: case Srv_getAddress: if (param.getResult() != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(uid, "MAC")); break; case Srv_getName: if (param.getResult() != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(uid, "BTName")); break; case getBondedDevices: if (param.getResult() != null && isRestricted(param)) param.setResult(new HashSet<BluetoothDevice>()); break; } }
@Override public Object call(Object who, Method method, Object... args) throws Throwable { int uid = (int) args[0]; int callingUid = Binder.getCallingUid(); if (uid == VirtualCore.get().myUid()) { uid = getBaseVUid(); } String[] callingPkgs = VPackageManager.get().getPackagesForUid(callingUid); String[] targetPkgs = VPackageManager.get().getPackagesForUid(uid); String[] selfPkgs = VPackageManager.get().getPackagesForUid(Process.myUid()); Set<String> pkgList = new ArraySet<>(2); if (callingPkgs != null && callingPkgs.length > 0) { pkgList.addAll(Arrays.asList(callingPkgs)); } if (targetPkgs != null && targetPkgs.length > 0) { pkgList.addAll(Arrays.asList(targetPkgs)); } if (selfPkgs != null && selfPkgs.length > 0) { pkgList.addAll(Arrays.asList(selfPkgs)); } return pkgList.toArray(new String[pkgList.size()]); }
@Override public void onDataSetChanged() { long identityToken = Binder.clearCallingIdentity(); try { loadMessageList(); } finally { Binder.restoreCallingIdentity(identityToken); } }
@Override public IBinder onBind(Intent arg0) { return new Binder() { @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) { final SharedPreferences preferences = getSharedPreferences(OpenUDID_manager.PREFS_NAME, Context.MODE_PRIVATE); reply.writeInt(data.readInt()); //Return to the sender the input random number reply.writeString(preferences.getString(OpenUDID_manager.PREF_KEY, null)); return true; } }; }