1 /*
2  * Copyright (C) 2009 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 #ifndef BINDER_PERMISSION_H
18 #define BINDER_PERMISSION_H
19 
20 #ifndef __ANDROID_VNDK__
21 
22 #include <stdint.h>
23 #include <unistd.h>
24 
25 #include <utils/String16.h>
26 #include <utils/Singleton.h>
27 #include <utils/SortedVector.h>
28 
29 namespace android {
30 // ---------------------------------------------------------------------------
31 
32 /*
33  * PermissionCache caches permission checks for a given uid.
34  *
35  * Currently the cache is not updated when there is a permission change,
36  * for instance when an application is uninstalled.
37  *
38  * IMPORTANT: for the reason stated above, only system permissions are safe
39  * to cache. This restriction may be lifted at a later time.
40  *
41  */
42 
43 class PermissionCache : Singleton<PermissionCache> {
44     struct Entry {
45         String16    name;
46         uid_t       uid;
47         bool        granted;
48         inline bool operator < (const Entry& e) const {
49             return (uid == e.uid) ? (name < e.name) : (uid < e.uid);
50         }
51     };
52     mutable Mutex mLock;
53     // we pool all the permission names we see, as many permissions checks
54     // will have identical names
55     SortedVector< String16 > mPermissionNamesPool;
56     // this is our cache per say. it stores pooled names.
57     SortedVector< Entry > mCache;
58 
59     // free the whole cache, but keep the permission name pool
60     void purge();
61 
62     status_t check(bool* granted,
63             const String16& permission, uid_t uid) const;
64 
65     void cache(const String16& permission, uid_t uid, bool granted);
66 
67 public:
68     PermissionCache();
69 
70     static bool checkCallingPermission(const String16& permission);
71 
72     static bool checkCallingPermission(const String16& permission,
73                                 int32_t* outPid, int32_t* outUid);
74 
75     static bool checkPermission(const String16& permission,
76             pid_t pid, uid_t uid);
77 };
78 
79 // ---------------------------------------------------------------------------
80 }; // namespace android
81 
82 #else // __ANDROID_VNDK__
83 #error "This header is not visible to vendors"
84 #endif // __ANDROID_VNDK__
85 
86 #endif /* BINDER_PERMISSION_H */
87