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_util.h"
30 
31 using namespace android::base;
32 
33 namespace android {
34 namespace aconfigd {
35 
36 /// Remove all files in a dir
RemoveFilesInDir(const std::string & dir)37 Result<void> RemoveFilesInDir(const std::string& dir) {
38   auto dir_ptr = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(dir.c_str()), closedir);
39   if (!dir_ptr) {
40     return ErrnoError() << "failed to open dir " << dir;
41   }
42 
43   struct dirent* entry;
44   while ((entry = readdir(dir_ptr.get())) != nullptr) {
45     if (entry->d_type != DT_REG) {
46       continue;
47     }
48     auto file = dir + "/" + entry->d_name;
49     if (unlink(file.c_str()) == -1) {
50       return ErrnoError() << "unlink() failed for " << file;
51     }
52   }
53 
54   return {};
55 }
56 
57 /// Copy file
CopyFile(const std::string & src,const std::string & dst,mode_t mode)58 Result<void> CopyFile(const std::string& src, const std::string& dst, mode_t mode) {
59   android::base::unique_fd src_fd(
60       TEMP_FAILURE_RETRY(open(src.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
61   if (src_fd == -1) {
62     return ErrnoError() << "open() failed for " << src;
63   }
64 
65   if (FileExists(dst.c_str())) {
66     if (chmod(dst.c_str(), 0644) == -1) {
67       return ErrnoError() << "chmod() failed for " << dst;
68     }
69   }
70 
71   android::base::unique_fd dst_fd(TEMP_FAILURE_RETRY(
72       open(dst.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644)));
73   if (dst_fd == -1) {
74     return ErrnoError() << "open() failed for " << dst;
75   }
76 
77   struct stat st;
78   if (fstat(src_fd.get(), &st) == -1) {
79     return ErrnoError() << "fstat() failed";
80   }
81   auto len = st.st_size;
82 
83   if (sendfile(dst_fd, src_fd, nullptr, len) == -1) {
84     return ErrnoError() << "sendfile() failed";
85   }
86 
87   if (chmod(dst.c_str(), mode) == -1) {
88     return ErrnoError() << "chmod() failed";
89   }
90 
91   return {};
92 }
93 
94 /// Get a file's timestamp in nano second
GetFileTimeStamp(const std::string & file)95 Result<uint64_t> GetFileTimeStamp(const std::string& file) {
96   struct stat st;
97   int result = stat(file.c_str(), &st);
98   if (result == -1) {
99     return ErrnoError() << "stat() failed";
100   }
101   uint64_t timestamp = st.st_mtim.tv_sec*1000000000 + st.st_mtim.tv_nsec;
102   return timestamp;
103 }
104 
FileExists(const std::string & file)105 bool FileExists(const std::string& file) {
106   struct stat st;
107   return stat(file.c_str(), &st) == 0 ? true : false;
108 }
109 
FileNonZeroSize(const std::string & file)110 bool FileNonZeroSize(const std::string& file) {
111   struct stat st;
112   return stat(file.c_str(), &st) == 0 ? st.st_size > 0 : false;
113 }
114 
GetFilesDigest(const std::vector<std::string> & files)115 Result<std::string> GetFilesDigest(const std::vector<std::string>& files) {
116   SHA512_CTX ctx;
117   SHA512_Init(&ctx);
118 
119   for (const auto& file : files) {
120     std::ifstream stream(file, std::ios::binary);
121     if (stream.bad()) {
122       return Error() << "Failed to open " << file;
123     }
124 
125     char buf[1024];
126     while (!stream.eof()) {
127       stream.read(buf, 1024);
128       if (stream.bad()) {
129         return Error() << "Failed to read " << file;
130       }
131       int bytes_read = stream.gcount();
132       SHA512_Update(&ctx, buf, bytes_read);
133     }
134   }
135 
136   uint8_t hash[SHA512_DIGEST_LENGTH];
137   SHA512_Final(hash, &ctx);
138   std::stringstream ss;
139   ss << std::hex;
140   for (int i = 0; i < SHA512_DIGEST_LENGTH; i++) {
141     ss << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
142   }
143   return ss.str();
144 }
145 
146 } // namespace aconfig
147 } // namespace android
148