blob: 24f9f7f94dfd51c7f902832d59d0f8350392d9a7 [file] [log] [blame]
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001/*
2 * Copyright (C) 2020 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
17#pragma once
18
19#include <android-base/stringprintf.h>
20#include <binder/IPCThreadState.h>
21#include <binder/PermissionCache.h>
22#include <binder/PermissionController.h>
23#include <binder/Status.h>
24
25namespace android::incremental {
26
27inline binder::Status Ok() {
28 return binder::Status::ok();
29}
30
31inline binder::Status Exception(uint32_t code, const std::string& msg) {
32 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
33}
34
35inline int fromBinderStatus(const binder::Status& status) {
36 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
37 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
38 : status.serviceSpecificErrorCode() == 0
39 ? -EFAULT
40 : status.serviceSpecificErrorCode()
41 : -EIO;
42}
43
44inline binder::Status CheckPermissionForDataDelivery(const char* permission, const char* operation) {
45 using android::base::StringPrintf;
46
47 int32_t pid;
48 int32_t uid;
49
50 if (!PermissionCache::checkCallingPermission(String16(permission), &pid, &uid)) {
51 return Exception(binder::Status::EX_SECURITY,
52 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
53 }
54
55 // Caller must also have op granted.
56 PermissionController pc;
57 // Package is a required parameter. Need to obtain one.
58 Vector<String16> packages;
59 pc.getPackagesForUid(uid, packages);
60 if (packages.empty()) {
61 return Exception(binder::Status::EX_SECURITY,
62 StringPrintf("UID %d / PID %d has no packages", uid, pid));
63 }
64 switch (auto result = pc.noteOp(String16(operation), uid, packages[0]); result) {
65 case PermissionController::MODE_ALLOWED:
66 case PermissionController::MODE_DEFAULT:
67 return binder::Status::ok();
68 default:
69 return Exception(binder::Status::EX_SECURITY,
70 StringPrintf("UID %d / PID %d lacks app-op %s, error %d", uid, pid,
71 operation, result));
72 }
73}
74
75} // namespace android::incremental