1 /*
2 * Copyright (C) 2018 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 #include "idmap2/FileUtils.h"
18
19 #include <random>
20 #include <string>
21 #include <string_view>
22
23 #include "android-base/file.h"
24 #include "android-base/macros.h"
25 #include "android-base/strings.h"
26 #include "private/android_filesystem_config.h"
27
28 namespace android::idmap2::utils {
29
30 #ifdef __ANDROID__
UidHasWriteAccessToPath(uid_t uid,const std::string & path)31 bool UidHasWriteAccessToPath(uid_t uid, const std::string& path) {
32 // resolve symlinks and relative paths; the directories must exist
33 std::string canonical_path;
34 if (!base::Realpath(base::Dirname(path), &canonical_path)) {
35 return false;
36 }
37
38 if (base::StartsWith(canonical_path, kIdmapCacheDir) &&
39 (canonical_path.size() == kIdmapCacheDir.size() ||
40 canonical_path[kIdmapCacheDir.size()] == '/')) {
41 // limit access to /data/resource-cache to root and system
42 return uid == AID_ROOT || uid == AID_SYSTEM;
43 }
44 return true;
45 }
46 #else
47 bool UidHasWriteAccessToPath(uid_t uid ATTRIBUTE_UNUSED, const std::string& path ATTRIBUTE_UNUSED) {
48 return true;
49 }
50 #endif
51
RandomStringForPath(size_t length)52 std::string RandomStringForPath(size_t length) {
53 constexpr std::string_view kChars =
54 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
55
56 std::string out_rand;
57 out_rand.resize(length);
58
59 static thread_local std::random_device rd;
60 std::uniform_int_distribution<int> dist(0, kChars.size() - 1);
61 for (size_t i = 0; i < length; i++) {
62 out_rand[i] = kChars[dist(rd)];
63 }
64 return out_rand;
65 }
66
67 } // namespace android::idmap2::utils
68