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 <string>
20 
21 #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 
26 namespace android::idmap2::utils {
27 
28 #ifdef __ANDROID__
UidHasWriteAccessToPath(uid_t uid,const std::string & path)29 bool 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
45 bool UidHasWriteAccessToPath(uid_t uid ATTRIBUTE_UNUSED, const std::string& path ATTRIBUTE_UNUSED) {
46   return true;
47 }
48 #endif
49 
RandomStringForPath(const size_t length)50 std::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 
65 }  // namespace android::idmap2::utils
66