xref: /aosp_15_r20/system/server_configurable_flags/aconfigd/aconfigd_util.cpp (revision 207333786ba243bc7d4d69ef6b05487aa7071806)
1 /*
2  * Copyright (C) 2024 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 <memory>
18 #include <sys/sendfile.h>
19 #include <dirent.h>
20 #include <stdio.h>
21 #include <openssl/sha.h>
22 #include <fstream>
23 #include <sstream>
24 
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/unique_fd.h>
28 
29 #include <aconfigd.pb.h>
30 #include "aconfigd_util.h"
31 
32 using namespace android::base;
33 
34 namespace android {
35 namespace aconfigd {
36 
37 /// Remove all files in a dir
RemoveFilesInDir(const std::string & dir)38 Result<void> RemoveFilesInDir(const std::string& dir) {
39   auto dir_ptr = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(dir.c_str()), closedir);
40   if (!dir_ptr) {
41     return ErrnoError() << "failed to open dir " << dir;
42   }
43 
44   struct dirent* entry;
45   while ((entry = readdir(dir_ptr.get())) != nullptr) {
46     if (entry->d_type != DT_REG) {
47       continue;
48     }
49     auto file = dir + "/" + entry->d_name;
50     if (unlink(file.c_str()) == -1) {
51       return ErrnoError() << "unlink() failed for " << file;
52     }
53   }
54 
55   return {};
56 }
57 
58 /// Copy file
CopyFile(const std::string & src,const std::string & dst,mode_t mode)59 Result<void> CopyFile(const std::string& src, const std::string& dst, mode_t mode) {
60   android::base::unique_fd src_fd(
61       TEMP_FAILURE_RETRY(open(src.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
62   if (src_fd == -1) {
63     return ErrnoError() << "open() failed for " << src;
64   }
65 
66   if (FileExists(dst.c_str())) {
67     if (chmod(dst.c_str(), 0644) == -1) {
68       return ErrnoError() << "chmod() failed for " << dst;
69     }
70   }
71 
72   android::base::unique_fd dst_fd(TEMP_FAILURE_RETRY(
73       open(dst.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644)));
74   if (dst_fd == -1) {
75     return ErrnoError() << "open() failed for " << dst;
76   }
77 
78   struct stat st;
79   if (fstat(src_fd.get(), &st) == -1) {
80     return ErrnoError() << "fstat() failed";
81   }
82   auto len = st.st_size;
83 
84   if (sendfile(dst_fd, src_fd, nullptr, len) == -1) {
85     return ErrnoError() << "sendfile() failed";
86   }
87 
88   if (chmod(dst.c_str(), mode) == -1) {
89     return ErrnoError() << "chmod() failed";
90   }
91 
92   return {};
93 }
94 
95 /// Get a file's timestamp in nano second
GetFileTimeStamp(const std::string & file)96 Result<uint64_t> GetFileTimeStamp(const std::string& file) {
97   struct stat st;
98   int result = stat(file.c_str(), &st);
99   if (result == -1) {
100     return ErrnoError() << "stat() failed";
101   }
102   uint64_t timestamp = st.st_mtim.tv_sec*1000000000 + st.st_mtim.tv_nsec;
103   return timestamp;
104 }
105 
FileExists(const std::string & file)106 bool FileExists(const std::string& file) {
107   struct stat st;
108   return stat(file.c_str(), &st) == 0 ? true : false;
109 }
110 
FileNonZeroSize(const std::string & file)111 bool FileNonZeroSize(const std::string& file) {
112   struct stat st;
113   return stat(file.c_str(), &st) == 0 ? st.st_size > 0 : false;
114 }
115 
GetFilesDigest(const std::vector<std::string> & files)116 Result<std::string> GetFilesDigest(const std::vector<std::string>& files) {
117   SHA512_CTX ctx;
118   SHA512_Init(&ctx);
119 
120   for (const auto& file : files) {
121     std::ifstream stream(file, std::ios::binary);
122     if (stream.bad()) {
123       return Error() << "Failed to open " << file;
124     }
125 
126     char buf[1024];
127     while (!stream.eof()) {
128       stream.read(buf, 1024);
129       if (stream.bad()) {
130         return Error() << "Failed to read " << file;
131       }
132       int bytes_read = stream.gcount();
133       SHA512_Update(&ctx, buf, bytes_read);
134     }
135   }
136 
137   uint8_t hash[SHA512_DIGEST_LENGTH];
138   SHA512_Final(hash, &ctx);
139   std::stringstream ss;
140   ss << std::hex;
141   for (int i = 0; i < SHA512_DIGEST_LENGTH; i++) {
142     ss << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
143   }
144   return ss.str();
145 }
146 
147 /// convert override type enum to string
OverrideTypeToStr(const StorageRequestMessage::FlagOverrideType & override_type)148 std::string OverrideTypeToStr(
149     const StorageRequestMessage::FlagOverrideType& override_type) {
150   switch (override_type) {
151     case StorageRequestMessage::LOCAL_IMMEDIATE: {
152       return "local immediate";
153     }
154     case StorageRequestMessage::LOCAL_ON_REBOOT: {
155       return "local on reboot";
156     }
157     case StorageRequestMessage::SERVER_ON_REBOOT: {
158       return "server on reboot";
159     }
160     default: {
161       return "unknown";
162     }
163   }
164 }
165 
166 } // namespace aconfig
167 } // namespace android
168