1 /*
2  * Copyright (C) 2019 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 "util.h"
18 
19 #include <dirent.h>
20 #include <sys/ioctl.h>
21 #include <sys/types.h>
22 
23 #include <thread>
24 
25 #include <android-base/stringprintf.h>
26 #include <android-base/unique_fd.h>
27 #include <linux/fs.h>
28 
29 namespace android {
30 namespace fs_mgr {
31 
NibbleValue(const char & c,uint8_t * value)32 bool NibbleValue(const char& c, uint8_t* value) {
33     CHECK(value != nullptr);
34 
35     switch (c) {
36         case '0' ... '9':
37             *value = c - '0';
38             break;
39         case 'a' ... 'f':
40             *value = c - 'a' + 10;
41             break;
42         case 'A' ... 'F':
43             *value = c - 'A' + 10;
44             break;
45         default:
46             return false;
47     }
48 
49     return true;
50 }
51 
HexToBytes(uint8_t * bytes,size_t bytes_len,const std::string & hex)52 bool HexToBytes(uint8_t* bytes, size_t bytes_len, const std::string& hex) {
53     CHECK(bytes != nullptr);
54 
55     if (hex.size() % 2 != 0) {
56         return false;
57     }
58     if (hex.size() / 2 > bytes_len) {
59         return false;
60     }
61     for (size_t i = 0, j = 0, n = hex.size(); i < n; i += 2, ++j) {
62         uint8_t high;
63         if (!NibbleValue(hex[i], &high)) {
64             return false;
65         }
66         uint8_t low;
67         if (!NibbleValue(hex[i + 1], &low)) {
68             return false;
69         }
70         bytes[j] = (high << 4) | low;
71     }
72     return true;
73 }
74 
BytesToHex(const uint8_t * bytes,size_t bytes_len)75 std::string BytesToHex(const uint8_t* bytes, size_t bytes_len) {
76     CHECK(bytes != nullptr);
77 
78     static const char* hex_digits = "0123456789abcdef";
79     std::string hex;
80 
81     for (size_t i = 0; i < bytes_len; i++) {
82         hex.push_back(hex_digits[(bytes[i] & 0xF0) >> 4]);
83         hex.push_back(hex_digits[bytes[i] & 0x0F]);
84     }
85     return hex;
86 }
87 
88 // TODO: remove duplicate code with fs_mgr_wait_for_file
WaitForFile(const std::string & filename,const std::chrono::milliseconds relative_timeout,FileWaitMode file_wait_mode)89 bool WaitForFile(const std::string& filename, const std::chrono::milliseconds relative_timeout,
90                  FileWaitMode file_wait_mode) {
91     auto start_time = std::chrono::steady_clock::now();
92 
93     while (true) {
94         int rv = access(filename.c_str(), F_OK);
95         if (file_wait_mode == FileWaitMode::Exists) {
96             if (!rv || errno != ENOENT) return true;
97         } else if (file_wait_mode == FileWaitMode::DoesNotExist) {
98             if (rv && errno == ENOENT) return true;
99         }
100 
101         std::this_thread::sleep_for(50ms);
102 
103         auto now = std::chrono::steady_clock::now();
104         auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
105         if (time_elapsed > relative_timeout) return false;
106     }
107 }
108 
IsDeviceUnlocked()109 bool IsDeviceUnlocked() {
110     std::string verified_boot_state;
111 
112     if (fs_mgr_get_boot_config("verifiedbootstate", &verified_boot_state)) {
113         return verified_boot_state == "orange";
114     }
115     return false;
116 }
117 
SetBlockDeviceReadOnly(const std::string & blockdev)118 bool SetBlockDeviceReadOnly(const std::string& blockdev) {
119     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blockdev.c_str(), O_RDONLY | O_CLOEXEC)));
120     if (fd < 0) {
121         return false;
122     }
123 
124     int ON = 1;
125     return ioctl(fd, BLKROSET, &ON) == 0;
126 }
127 
ListFiles(const std::string & dir)128 Result<std::vector<std::string>> ListFiles(const std::string& dir) {
129     struct dirent* de;
130     std::vector<std::string> files;
131 
132     std::unique_ptr<DIR, int (*)(DIR*)> dirp(opendir(dir.c_str()), closedir);
133     if (!dirp) {
134         return ErrnoError() << "Failed to opendir: " << dir;
135     }
136 
137     while ((de = readdir(dirp.get()))) {
138         if (de->d_type != DT_REG) continue;
139         std::string full_path = android::base::StringPrintf("%s/%s", dir.c_str(), de->d_name);
140         files.emplace_back(std::move(full_path));
141     }
142 
143     return files;
144 }
145 
146 }  // namespace fs_mgr
147 }  // namespace android
148