summaryrefslogtreecommitdiff
path: root/apexd/apex_database.cpp
blob: d027f95c8d7a2f75a2e0d8ab1811d7882c8c300c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "apexd"

#include "apex_database.h"
#include "apex_constants.h"
#include "apex_file.h"
#include "apexd_utils.h"
#include "string_log.h"

#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/parseint.h>
#include <android-base/result.h>
#include <android-base/strings.h>

#include <filesystem>
#include <fstream>
#include <string>
#include <unordered_map>
#include <utility>

using android::base::ConsumeSuffix;
using android::base::ParseInt;
using android::base::ReadFileToString;
using android::base::Result;
using android::base::Split;
using android::base::StartsWith;
using android::base::Trim;

namespace fs = std::filesystem;

namespace android {
namespace apex {

namespace {

using MountedApexData = MountedApexDatabase::MountedApexData;

enum BlockDeviceType {
  UnknownDevice,
  LoopDevice,
  DeviceMapperDevice,
};

const fs::path kDevBlock = "/dev/block";
const fs::path kSysBlock = "/sys/block";

class BlockDevice {
  std::string name;  // loopN, dm-N, ...
 public:
  explicit BlockDevice(const fs::path& path) { name = path.filename(); }

  BlockDeviceType GetType() const {
    if (StartsWith(name, "loop")) return LoopDevice;
    if (StartsWith(name, "dm-")) return DeviceMapperDevice;
    return UnknownDevice;
  }

  fs::path SysPath() const { return kSysBlock / name; }

  fs::path DevPath() const { return kDevBlock / name; }

  Result<std::string> GetProperty(const std::string& property) const {
    auto propertyFile = SysPath() / property;
    std::string propertyValue;
    if (!ReadFileToString(propertyFile, &propertyValue)) {
      return ErrnoError() << "Fail to read";
    }
    return Trim(propertyValue);
  }

  std::vector<BlockDevice> GetSlaves() const {
    std::vector<BlockDevice> slaves;
    std::error_code ec;
    auto status = WalkDir(SysPath() / "slaves", [&](const auto& entry) {
      BlockDevice dev(entry);
      if (fs::is_block_file(dev.DevPath(), ec)) {
        slaves.push_back(dev);
      }
    });
    if (!status.ok()) {
      LOG(WARNING) << status.error();
    }
    return slaves;
  }
};

std::pair<fs::path, fs::path> parseMountInfo(const std::string& mountInfo) {
  const auto& tokens = Split(mountInfo, " ");
  if (tokens.size() < 2) {
    return std::make_pair("", "");
  }
  return std::make_pair(tokens[0], tokens[1]);
}

std::pair<std::string, int> parseMountPoint(const std::string& mountPoint) {
  auto packageId = fs::path(mountPoint).filename();
  auto split = Split(packageId, "@");
  if (split.size() == 2) {
    int version;
    if (!ParseInt(split[1], &version)) {
      version = -1;
    }
    return std::make_pair(split[0], version);
  }
  return std::make_pair(packageId, -1);
}

bool isActiveMountPoint(const std::string& mountPoint) {
  return (mountPoint.find('@') == std::string::npos);
}

Result<void> PopulateLoopInfo(const BlockDevice& top_device,
                              MountedApexData* apex_data) {
  std::vector<BlockDevice> slaves = top_device.GetSlaves();
  if (slaves.size() != 1 && slaves.size() != 2) {
    return Error() << "dm device " << top_device.DevPath()
                   << " has unexpected number of slaves : " << slaves.size();
  }
  std::vector<std::string> backing_files;
  backing_files.reserve(slaves.size());
  for (const auto& dev : slaves) {
    if (dev.GetType() != LoopDevice) {
      return Error() << dev.DevPath() << " is not a loop device";
    }
    auto backing_file = dev.GetProperty("loop/backing_file");
    if (!backing_file.ok()) {
      return backing_file.error();
    }
    backing_files.push_back(std::move(*backing_file));
  }
  // Enforce following invariant:
  //  * slaves[0] always represents a data loop device
  //  * if size = 2 then slaves[1] represents an external hashtree loop device
  if (slaves.size() == 2) {
    if (!StartsWith(backing_files[0], kActiveApexPackagesDataDir)) {
      std::swap(slaves[0], slaves[1]);
      std::swap(backing_files[0], backing_files[1]);
    }
  }
  if (!StartsWith(backing_files[0], kActiveApexPackagesDataDir)) {
    return Error() << "Data loop device " << slaves[0].DevPath()
                   << " has unexpected backing file " << backing_files[0];
  }
  if (slaves.size() == 2) {
    if (!StartsWith(backing_files[1], kApexHashTreeDir)) {
      return Error() << "Hashtree loop device " << slaves[1].DevPath()
                     << " has unexpected backing file " << backing_files[1];
    }
    apex_data->hashtree_loop_name = slaves[1].DevPath();
  }
  apex_data->loop_name = slaves[0].DevPath();
  apex_data->full_path = backing_files[0];
  return {};
}

// This is not the right place to do this normalization, but proper solution
// will require some refactoring first. :(
// TODO(ioffe): introduce MountedApexDataBuilder and delegate all
//  building/normalization logic to it.
void NormalizeIfDeleted(MountedApexData* apex_data) {
  std::string_view full_path = apex_data->full_path;
  if (ConsumeSuffix(&full_path, "(deleted)")) {
    apex_data->deleted = true;
    auto it = full_path.rbegin();
    while (it != full_path.rend() && isspace(*it)) {
      it++;
    }
    full_path.remove_suffix(it - full_path.rbegin());
  } else {
    apex_data->deleted = false;
  }
  apex_data->full_path = full_path;
}

Result<MountedApexData> resolveMountInfo(const BlockDevice& block,
                                         const std::string& mountPoint) {
  // Now, see if it is dm-verity or loop mounted
  switch (block.GetType()) {
    case LoopDevice: {
      auto backingFile = block.GetProperty("loop/backing_file");
      if (!backingFile.ok()) {
        return backingFile.error();
      }
      auto result = MountedApexData(block.DevPath(), *backingFile, mountPoint,
                                    /* device_name= */ "",
                                    /* hashtree_loop_name= */ "");
      NormalizeIfDeleted(&result);
      return result;
    }
    case DeviceMapperDevice: {
      auto name = block.GetProperty("dm/name");
      if (!name.ok()) {
        return name.error();
      }
      MountedApexData result;
      result.mount_point = mountPoint;
      result.device_name = *name;
      if (auto status = PopulateLoopInfo(block, &result); !status.ok()) {
        return status.error();
      }
      NormalizeIfDeleted(&result);
      return result;
    }
    case UnknownDevice: {
      return Errorf("Can't resolve {}", block.DevPath().string());
    }
  }
}

}  // namespace

// On startup, APEX database is populated from /proc/mounts.

// /apex/<package-id> can be mounted from
// - /dev/block/loopX : loop device
// - /dev/block/dm-X : dm-verity

// In case of loop device, it is from a non-flattened
// APEX file. This original APEX file can be tracked
// by /sys/block/loopX/loop/backing_file.

// In case of dm-verity, it is mapped to a loop device.
// This mapped loop device can be traced by
// /sys/block/dm-X/slaves/ directory which contains
// a symlink to /sys/block/loopY, which leads to
// the original APEX file.
// Device name can be retrieved from
// /sys/block/dm-Y/dm/name.

// By synchronizing the mounts info with Database on startup,
// Apexd serves the correct package list even on the devices
// which are not ro.apex.updatable.
void MountedApexDatabase::PopulateFromMounts() {
  LOG(INFO) << "Populating APEX database from mounts...";

  std::unordered_map<std::string, int> activeVersions;

  std::ifstream mounts("/proc/mounts");
  std::string line;
  while (std::getline(mounts, line)) {
    auto [block, mountPoint] = parseMountInfo(line);
    // TODO(jooyung): ignore tmp mount?
    if (fs::path(mountPoint).parent_path() != kApexRoot) {
      continue;
    }
    if (isActiveMountPoint(mountPoint)) {
      continue;
    }

    auto mountData = resolveMountInfo(BlockDevice(block), mountPoint);
    if (!mountData.ok()) {
      LOG(WARNING) << "Can't resolve mount info " << mountData.error();
      continue;
    }

    auto [package, version] = parseMountPoint(mountPoint);
    AddMountedApex(package, false, *mountData);

    auto active = activeVersions[package] < version;
    if (active) {
      activeVersions[package] = version;
      SetLatest(package, mountData->full_path);
    }
    LOG(INFO) << "Found " << mountPoint << " backed by"
              << (mountData->deleted ? " deleted " : " ") << "file "
              << mountData->full_path;
  }

  LOG(INFO) << mounted_apexes_.size() << " packages restored.";
}

}  // namespace apex
}  // namespace android