blob: 98a4ceabdb94c6aa24ad485d5e71a9928f5a067c [file] [log] [blame]
Mårten Kongstad02751232018-04-27 13:16:32 +02001/*
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
Ryan Mitchell52e1f7a2019-04-12 12:31:42 -070017#include "idmap2/FileUtils.h"
18
Mårten Kongstad02751232018-04-27 13:16:32 +020019#include <string>
Mårten Kongstad02751232018-04-27 13:16:32 +020020
Mårten Kongstad1da49dc2019-01-14 10:03:53 +010021#include "android-base/file.h"
22#include "android-base/macros.h"
23#include "android-base/stringprintf.h"
24#include "private/android_filesystem_config.h"
25
Mårten Kongstad0eba72a2018-11-29 08:23:14 +010026namespace android::idmap2::utils {
Mårten Kongstad02751232018-04-27 13:16:32 +020027
Mårten Kongstad1da49dc2019-01-14 10:03:53 +010028#ifdef __ANDROID__
29bool UidHasWriteAccessToPath(uid_t uid, const std::string& path) {
30 // resolve symlinks and relative paths; the directories must exist
31 std::string canonical_path;
32 if (!base::Realpath(base::Dirname(path), &canonical_path)) {
33 return false;
34 }
35
36 const std::string cache_subdir = base::StringPrintf("%s/", kIdmapCacheDir);
37 if (canonical_path == kIdmapCacheDir ||
38 canonical_path.compare(0, cache_subdir.size(), cache_subdir) == 0) {
39 // limit access to /data/resource-cache to root and system
40 return uid == AID_ROOT || uid == AID_SYSTEM;
41 }
42 return true;
43}
44#else
45bool UidHasWriteAccessToPath(uid_t uid ATTRIBUTE_UNUSED, const std::string& path ATTRIBUTE_UNUSED) {
46 return true;
47}
48#endif
49
Ryan Mitchell6a2ca782021-01-19 13:51:15 -080050std::string RandomStringForPath(const size_t length) {
51 constexpr char kChars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
52 constexpr size_t kCharLastIndex = sizeof(kChars) - 1;
53
54 std::string out_rand;
55 out_rand.reserve(length);
56
57 std::random_device rd;
58 std::uniform_int_distribution<int> dist(0, kCharLastIndex);
59 for (size_t i = 0; i < length; i++) {
60 out_rand[i] = kChars[dist(rd) % (kCharLastIndex)];
61 }
62 return out_rand;
63}
64
Mårten Kongstad0eba72a2018-11-29 08:23:14 +010065} // namespace android::idmap2::utils