Example usage for android.os Binder getCallingUid

List of usage examples for android.os Binder getCallingUid

Introduction

In this page you can find the example usage for android.os Binder getCallingUid.

Prototype

public static final native int getCallingUid();

Source Link

Document

Return the Linux uid assigned to the process that sent you the current transaction that is being processed.

Usage

From source file:net.sf.xfd.provider.PublicProvider.java

final boolean checkAccess(Uri uri, String grantMode, String necessaryMode) {
    try {//from ww  w .jav a  2s .  c om
        verifyMac(uri, grantMode, necessaryMode);

        return true;
    } catch (FileNotFoundException fnfe) {
        final Context context = getContext();

        assert context != null;

        ObjectIntMap<String> decisions = null;

        final String caller = getCallingPackage();

        if (!TextUtils.isEmpty(caller)) {
            decisions = accessCache.get(uri.getPath());
            if (decisions == null) {
                decisions = new ObjectIntHashMap<>();
            } else {
                //noinspection SynchronizationOnLocalVariableOrMethodParameter
                synchronized (decisions) {
                    final int decision = decisions.get(caller);

                    switch (decision) {
                    case RESPONSE_ALLOW:
                        return true;
                    }
                }
            }
        }

        final ArrayBlockingQueue<Bundle> queue = new ArrayBlockingQueue<>(1);

        //noinspection RestrictedApi
        final ResultReceiver receiver = new ResultReceiver(new Handler(Looper.getMainLooper())) {
            @Override
            protected void onReceiveResult(int resultCode, Bundle resultData) {
                try {
                    queue.offer(resultData, 4, TimeUnit.SECONDS);
                } catch (InterruptedException ignored) {
                }
            }
        };

        try {
            final Intent intent = authActivityIntent(context);

            if (intent == null)
                return false;

            final Bundle result;

            final CharSequence resolved = base.resolve(uri.getPath());

            // try to ensure, that no more than one dialog can appear at once
            uxLock.lockInterruptibly();
            try {
                context.startActivity(intent.putExtra(EXTRA_MODE, necessaryMode).putExtra(EXTRA_CALLER, caller)
                        .putExtra(EXTRA_UID, Binder.getCallingUid()).putExtra(EXTRA_CALLBACK, receiver)
                        .putExtra(EXTRA_PATH, resolved));

                result = queue.poll(10, TimeUnit.SECONDS);
            } finally {
                uxLock.unlock();
            }

            int decision = RESPONSE_DENY;

            if (result != null) {
                decision = result.getInt(EXTRA_RESPONSE, -1);
            }

            if (decision == RESPONSE_ALLOW) {
                if (decisions != null) {
                    //noinspection SynchronizationOnLocalVariableOrMethodParameter
                    synchronized (decisions) {
                        decisions.put(caller, RESPONSE_ALLOW);

                        accessCache.put(uri.getPath(), decisions);
                    }
                }

                return true;
            }
        } catch (InterruptedException ignored) {
        }
    }

    return false;
}

From source file:net.sf.xfd.provider.PublicProvider.java

final void verifyMac(Uri path, String grantMode, String requested) throws FileNotFoundException {
    if (Process.myUid() == Binder.getCallingUid()) {
        return;//  w w  w . j  av a 2  s. co  m
    }

    final int requestedMode = ParcelFileDescriptor.parseMode(requested);

    final String cookie = path.getQueryParameter(URI_ARG_COOKIE);
    final String expiry = path.getQueryParameter(URI_ARG_EXPIRY);

    if (TextUtils.isEmpty(cookie) || TextUtils.isEmpty(expiry)) {
        throw new FileNotFoundException("Invalid uri: MAC and expiry date are missing");
    }

    final long l;
    try {
        l = Long.parseLong(expiry);
    } catch (NumberFormatException nfe) {
        throw new FileNotFoundException("Invalid uri: unable to parse expiry date");
    }

    final Key key = getSalt(getContext());
    if (key == null) {
        throw new FileNotFoundException("Unable to verify hash: failed to produce key");
    }

    final int modeInt = ParcelFileDescriptor.parseMode(grantMode);

    if ((requestedMode & modeInt) != requestedMode) {
        throw new FileNotFoundException("Requested mode " + requested + " but limited to " + grantMode);
    }

    final byte[] encoded;
    final Mac hash;
    try {
        hash = Mac.getInstance("HmacSHA1");
        hash.init(key);

        final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16),
                (byte) (modeInt >> 8), (byte) modeInt, };
        hash.update(modeBits);

        final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40),
                (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, };
        hash.update(expiryDate);

        encoded = hash.doFinal(path.getPath().getBytes());

        final String sample = Base64.encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING);

        if (!cookie.equals(sample)) {
            throw new FileNotFoundException("Expired uri");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new FileNotFoundException("Unable to verify hash: missing HmacSHA1");
    } catch (InvalidKeyException e) {
        throw new FileNotFoundException("Unable to verify hash: corrupted key?!");
    }
}

From source file:com.fututel.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;/*from w  w  w. jav  a 2  s  .c  o m*/
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

    c.setNotificationUri(getContext().getContentResolver(), regUri);
    return c;
}

From source file:com.skubit.android.billing.BillingServiceBinder.java

private int validatePackageIsOwnedByCaller(String packageName) {
    String[] packages = mPackageManager.getPackagesForUid(Binder.getCallingUid());
    if (packages != null) {
        for (String pack : packages) {
            if (packageName.equals(pack)) {
                return BillingResponseCodes.RESULT_OK;
            }/*from   w w w.  j av  a2 s  .  c o  m*/
        }
    }
    return BillingResponseCodes.RESULT_DEVELOPER_ERROR;
}

From source file:com.sonetel.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;/*from  www . ja v a 2s  .  c  o  m*/
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    case ACCESSNO:
        qb.setTables(SipProfile.ACCESS_NUMS_TABLE_NAME);

        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

    c.setNotificationUri(getContext().getContentResolver(), regUri);
    return c;
}

From source file:org.mariotaku.twidere.provider.TwidereDataProvider.java

private void checkWritePermission(final int id, final String table) {
    switch (id) {
    case TABLE_ID_ACCOUNTS: {
        // Writing to accounts database is not allowed for third-party
        // applications.
        if (!mPermissionsManager.checkSignature(Binder.getCallingUid()))
            throw new SecurityException(
                    "Writing to accounts database is not allowed for third-party applications");
        break;/*  w  w w.j a v a 2  s.  c  o  m*/
    }
    case TABLE_ID_DIRECT_MESSAGES:
    case TABLE_ID_DIRECT_MESSAGES_INBOX:
    case TABLE_ID_DIRECT_MESSAGES_OUTBOX:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRY: {
        if (!checkPermission(PERMISSION_DIRECT_MESSAGES))
            throw new SecurityException(
                    "Access database " + table + " requires level PERMISSION_LEVEL_DIRECT_MESSAGES");
        break;
    }
    case TABLE_ID_STATUSES:
    case TABLE_ID_MENTIONS:
    case TABLE_ID_TABS:
    case TABLE_ID_DRAFTS:
    case TABLE_ID_CACHED_USERS:
    case TABLE_ID_FILTERED_USERS:
    case TABLE_ID_FILTERED_KEYWORDS:
    case TABLE_ID_FILTERED_SOURCES:
    case TABLE_ID_FILTERED_LINKS:
    case TABLE_ID_TRENDS_LOCAL:
    case TABLE_ID_CACHED_STATUSES:
    case TABLE_ID_CACHED_HASHTAGS: {
        if (!checkPermission(PERMISSION_WRITE))
            throw new SecurityException("Access database " + table + " requires level PERMISSION_LEVEL_WRITE");
        break;
    }
    }
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;/*www .  j  a  v  a 2 s .  c  o  m*/
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    // Security check to avoid data retrieval from outside
    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }
    // Security check to avoid project of invalid fields or lazy projection
    List<String> possibles = getPossibleFieldsForType(type);
    if (possibles == null) {
        throw new SecurityException("You are asking wrong values " + type);
    }
    checkProjection(possibles, projection);
    checkSelection(possibles, selection);

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

    c.setNotificationUri(getContext().getContentResolver(), regUri);
    return c;
}

From source file:com.google.android.apps.dashclock.DashClockService.java

private void enforceCallingPermission(String permission) throws SecurityException {
    // We need to check that any of the packages of the caller has
    // the request permission
    final PackageManager pm = getPackageManager();
    try {/*ww  w . ja va2s  .com*/
        String[] packages = pm.getPackagesForUid(Binder.getCallingUid());
        if (packages != null) {
            for (String pkg : packages) {
                PackageInfo pi = pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS);
                if (pi.requestedPermissions != null) {
                    for (String requestedPermission : pi.requestedPermissions) {
                        if (requestedPermission.equals(permission)) {
                            // The caller has the request permission
                            return;
                        }
                    }
                }
            }
        }
    } catch (PackageManager.NameNotFoundException ex) {
        // Ignore. Package wasn't found
    }
    throw new SecurityException("Caller doesn't have the request permission \"" + permission + "\"");
}

From source file:net.sf.xfd.provider.PublicProvider.java

@Override
public Uri canonicalize(@NonNull Uri uri) {
    try {//from   w ww .ja  va  2  s  .co  m
        base.assertAbsolute(uri);

        String grantMode = uri.getQueryParameter(URI_ARG_MODE);
        if (TextUtils.isEmpty(grantMode)) {
            grantMode = "r";
        }

        verifyMac(uri, grantMode, grantMode);

        final int flags = ParcelFileDescriptor.parseMode(grantMode);

        final Context context = getContext();
        assert context != null;

        final String packageName = context.getPackageName();

        final Uri canon = DocumentsContract.buildDocumentUri(packageName + FileProvider.AUTHORITY_SUFFIX,
                canonString(uri.getPath()));

        final int callerUid = Binder.getCallingUid();

        if (callerUid != Process.myUid()) {
            int grantFlags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;

            if ((flags & ParcelFileDescriptor.MODE_READ_ONLY) == flags) {
                grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
            } else if ((flags & ParcelFileDescriptor.MODE_WRITE_ONLY) == flags)
                grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            else {
                grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
            }

            final String[] packages;

            final String caller = getCallingPackage();
            if (caller != null) {
                packages = new String[] { caller };
            } else {
                final PackageManager pm = context.getPackageManager();
                packages = pm.getPackagesForUid(callerUid);
            }

            if (packages != null) {
                for (String pkg : packages) {
                    context.grantUriPermission(pkg, canon, grantFlags);
                }
            }
        }

        return canon;
    } catch (FileNotFoundException e) {
        return null;
    }
}

From source file:com.android.server.MaybeService.java

private String getCallerPackageName() {
    return mContext.getPackageManager().getNameForUid(Binder.getCallingUid());
}