xref: /aosp_15_r20/system/apex/apexd/apex_database.cpp (revision 33f3758387333dbd2962d7edbd98681940d895da)
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 "apex_database.h"
18 #include "apex_constants.h"
19 #include "apex_file.h"
20 #include "apexd_utils.h"
21 #include "string_log.h"
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/parseint.h>
26 #include <android-base/result.h>
27 #include <android-base/strings.h>
28 
29 #include <filesystem>
30 #include <fstream>
31 #include <string>
32 #include <unordered_map>
33 #include <utility>
34 
35 using android::base::ConsumeSuffix;
36 using android::base::EndsWith;
37 using android::base::ErrnoError;
38 using android::base::Error;
39 using android::base::ParseInt;
40 using android::base::ReadFileToString;
41 using android::base::Result;
42 using android::base::Split;
43 using android::base::StartsWith;
44 using android::base::Trim;
45 
46 namespace fs = std::filesystem;
47 
48 namespace android {
49 namespace apex {
50 
51 namespace {
52 
53 using MountedApexData = MountedApexDatabase::MountedApexData;
54 
55 enum BlockDeviceType {
56   UnknownDevice,
57   LoopDevice,
58   DeviceMapperDevice,
59 };
60 
61 const fs::path kDevBlock = "/dev/block";
62 const fs::path kSysBlock = "/sys/block";
63 
64 class BlockDevice {
65   std::string name;  // loopN, dm-N, ...
66  public:
BlockDevice(const fs::path & path)67   explicit BlockDevice(const fs::path& path) { name = path.filename(); }
68 
GetType() const69   BlockDeviceType GetType() const {
70     if (StartsWith(name, "loop")) return LoopDevice;
71     if (StartsWith(name, "dm-")) return DeviceMapperDevice;
72     return UnknownDevice;
73   }
74 
SysPath() const75   fs::path SysPath() const { return kSysBlock / name; }
76 
DevPath() const77   fs::path DevPath() const { return kDevBlock / name; }
78 
GetProperty(const std::string & property) const79   Result<std::string> GetProperty(const std::string& property) const {
80     auto property_file = SysPath() / property;
81     std::string property_value;
82     if (!ReadFileToString(property_file, &property_value)) {
83       return ErrnoError() << "Fail to read";
84     }
85     return Trim(property_value);
86   }
87 
GetSlaves() const88   std::vector<BlockDevice> GetSlaves() const {
89     std::vector<BlockDevice> slaves;
90     std::error_code ec;
91     auto status = WalkDir(SysPath() / "slaves", [&](const auto& entry) {
92       BlockDevice dev(entry);
93       if (fs::is_block_file(dev.DevPath(), ec)) {
94         slaves.push_back(dev);
95       }
96     });
97     if (!status.ok()) {
98       LOG(WARNING) << status.error();
99     }
100     return slaves;
101   }
102 };
103 
ParseMountInfo(const std::string & mount_info)104 std::pair<fs::path, fs::path> ParseMountInfo(const std::string& mount_info) {
105   const auto& tokens = Split(mount_info, " ");
106   if (tokens.size() < 2) {
107     return std::make_pair("", "");
108   }
109   return std::make_pair(tokens[0], tokens[1]);
110 }
111 
ParseMountPoint(const std::string & mount_point)112 std::pair<std::string, int> ParseMountPoint(const std::string& mount_point) {
113   auto package_id = fs::path(mount_point).filename();
114   auto split = Split(package_id, "@");
115   if (split.size() == 2) {
116     int version;
117     if (!ParseInt(split[1], &version)) {
118       version = -1;
119     }
120     return std::make_pair(split[0], version);
121   }
122   return std::make_pair(package_id, -1);
123 }
124 
IsActiveMountPoint(const std::string & mount_point)125 bool IsActiveMountPoint(const std::string& mount_point) {
126   return (mount_point.find('@') == std::string::npos);
127 }
128 
IsTempMountPoint(const std::string & mount_point)129 bool IsTempMountPoint(const std::string& mount_point) {
130   return EndsWith(mount_point, ".tmp");
131 }
132 
PopulateLoopInfo(const BlockDevice & top_device,const std::vector<std::string> & data_dirs,MountedApexData * apex_data)133 Result<void> PopulateLoopInfo(const BlockDevice& top_device,
134                               const std::vector<std::string>& data_dirs,
135                               MountedApexData* apex_data) {
136   std::vector<BlockDevice> slaves = top_device.GetSlaves();
137   if (slaves.size() != 1) {
138     return Error() << "dm device " << top_device.DevPath()
139                    << " has unexpected number of slaves (should be 1) : "
140                    << slaves.size();
141   }
142   if (slaves[0].GetType() != LoopDevice) {
143     return Error() << slaves[0].DevPath() << " is not a loop device";
144   }
145   std::string backing_file =
146       OR_RETURN(slaves[0].GetProperty("loop/backing_file"));
147   bool is_data_loop_device = std::any_of(
148       data_dirs.begin(), data_dirs.end(),
149       [&](const std::string& dir) { return StartsWith(backing_file, dir); });
150   if (!is_data_loop_device) {
151     return Error() << "Data loop device " << slaves[0].DevPath()
152                    << " has unexpected backing file " << backing_file;
153   }
154   apex_data->loop_name = slaves[0].DevPath();
155   apex_data->full_path = backing_file;
156   return {};
157 }
158 
159 // This is not the right place to do this normalization, but proper solution
160 // will require some refactoring first. :(
161 // TODO(b/158469911): introduce MountedApexDataBuilder and delegate all
162 //  building/normalization logic to it.
NormalizeIfDeleted(MountedApexData * apex_data)163 void NormalizeIfDeleted(MountedApexData* apex_data) {
164   std::string_view full_path = apex_data->full_path;
165   if (ConsumeSuffix(&full_path, "(deleted)")) {
166     apex_data->deleted = true;
167     auto it = full_path.rbegin();
168     while (it != full_path.rend() && isspace(*it)) {
169       it++;
170     }
171     full_path.remove_suffix(it - full_path.rbegin());
172   } else {
173     apex_data->deleted = false;
174   }
175   apex_data->full_path = full_path;
176 }
177 
ResolveMountInfo(const BlockDevice & block,const std::string & mount_point,const std::vector<std::string> & data_dirs)178 Result<MountedApexData> ResolveMountInfo(
179     const BlockDevice& block, const std::string& mount_point,
180     const std::vector<std::string>& data_dirs) {
181   // Now, see if it is dm-verity or loop mounted
182   switch (block.GetType()) {
183     case LoopDevice: {
184       auto backing_file = block.GetProperty("loop/backing_file");
185       if (!backing_file.ok()) {
186         return backing_file.error();
187       }
188       MountedApexData result;
189       result.loop_name = block.DevPath();
190       result.full_path = *backing_file;
191       result.mount_point = mount_point;
192       NormalizeIfDeleted(&result);
193       return result;
194     }
195     case DeviceMapperDevice: {
196       auto name = block.GetProperty("dm/name");
197       if (!name.ok()) {
198         return name.error();
199       }
200       MountedApexData result;
201       result.mount_point = mount_point;
202       result.device_name = *name;
203       auto status = PopulateLoopInfo(block, data_dirs, &result);
204       if (!status.ok()) {
205         return status.error();
206       }
207       NormalizeIfDeleted(&result);
208       return result;
209     }
210     case UnknownDevice: {
211       return Errorf("Can't resolve {}", block.DevPath().string());
212     }
213   }
214 }
215 
216 }  // namespace
217 
218 // On startup, APEX database is populated from /proc/mounts.
219 
220 // /apex/<package-id> can be mounted from
221 // - /dev/block/loopX : loop device
222 // - /dev/block/dm-X : dm-verity
223 
224 // In case of loop device, the original APEX file can be tracked
225 // by /sys/block/loopX/loop/backing_file.
226 
227 // In case of dm-verity, it is mapped to a loop device.
228 // This mapped loop device can be traced by
229 // /sys/block/dm-X/slaves/ directory which contains
230 // a symlink to /sys/block/loopY, which leads to
231 // the original APEX file.
232 // Device name can be retrieved from
233 // /sys/block/dm-Y/dm/name.
234 
235 // Need to read /proc/mounts on startup since apexd can start
236 // at any time (It's a lazy service).
PopulateFromMounts(const std::vector<std::string> & data_dirs)237 void MountedApexDatabase::PopulateFromMounts(
238     const std::vector<std::string>& data_dirs)
239     REQUIRES(!mounted_apexes_mutex_) {
240   LOG(INFO) << "Populating APEX database from mounts...";
241 
242   std::ifstream mounts("/proc/mounts");
243   std::string line;
244   std::lock_guard lock(mounted_apexes_mutex_);
245   while (std::getline(mounts, line)) {
246     auto [block, mount_point] = ParseMountInfo(line);
247     // TODO(b/158469914): distinguish between temp and non-temp mounts
248     if (fs::path(mount_point).parent_path() != kApexRoot) {
249       continue;
250     }
251     if (IsActiveMountPoint(mount_point)) {
252       continue;
253     }
254     if (IsTempMountPoint(mount_point)) {
255       continue;
256     }
257     auto mount_data =
258         ResolveMountInfo(BlockDevice(block), mount_point, data_dirs);
259     if (!mount_data.ok()) {
260       LOG(WARNING) << "Can't resolve mount info " << mount_data.error();
261       continue;
262     }
263 
264     auto [package, version] = ParseMountPoint(mount_point);
265     mount_data->version = version;
266     AddMountedApexLocked(package, *mount_data);
267 
268     LOG(INFO) << "Found " << mount_point << " backed by"
269               << (mount_data->deleted ? " deleted " : " ") << "file "
270               << mount_data->full_path;
271   }
272 
273   LOG(INFO) << mounted_apexes_.size() << " packages restored.";
274 }
275 
276 }  // namespace apex
277 }  // namespace android
278