blob: 0ea4d2cf7912af8401358b3aead7e9ee7689454f [file] [log] [blame]
Jooyung Han017916b2021-04-20 03:57:19 +09001/*
2 * Copyright (C) 2021 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 <sys/stat.h>
18#include <sys/types.h>
19#include <unistd.h>
20
21#include <fstream>
22#include <iostream>
23#include <optional>
24#include <string>
25#include <vector>
26
27#include <android-base/file.h>
28#include <android-base/result.h>
29#include <com_android_apex.h>
30#include <image_aggregator.h>
31#include <json/json.h>
32
33#include "microdroid/signature.h"
34
35using android::base::Dirname;
36using android::base::ErrnoError;
37using android::base::Error;
38using android::base::Result;
Jooyung Hana54dcaf2021-05-13 21:57:02 +090039using android::base::unique_fd;
Jooyung Han017916b2021-04-20 03:57:19 +090040using android::microdroid::ApexSignature;
41using android::microdroid::MicrodroidSignature;
42using android::microdroid::WriteMicrodroidSignature;
43
44using com::android::apex::ApexInfoList;
45using com::android::apex::readApexInfoList;
46
Jooyung Hana54dcaf2021-05-13 21:57:02 +090047using cuttlefish::AlignToPartitionSize;
Jooyung Han017916b2021-04-20 03:57:19 +090048using cuttlefish::CreateCompositeDisk;
Jooyung Han017916b2021-04-20 03:57:19 +090049using cuttlefish::kLinuxFilesystem;
Jooyung Hana54dcaf2021-05-13 21:57:02 +090050using cuttlefish::MultipleImagePartition;
Jooyung Han017916b2021-04-20 03:57:19 +090051
52Result<uint32_t> GetFileSize(const std::string& path) {
53 struct stat st;
54 if (lstat(path.c_str(), &st) == -1) {
55 return ErrnoError() << "Can't lstat " << path;
56 }
57 return static_cast<uint32_t>(st.st_size);
58}
59
60std::string ToAbsolute(const std::string& path, const std::string& dirname) {
61 bool is_absolute = !path.empty() && path[0] == '/';
62 if (is_absolute) {
63 return path;
64 } else {
65 return dirname + "/" + path;
66 }
67}
68
69// Returns `append` is appended to the end of filename preserving the extension.
70std::string AppendFileName(const std::string& filename, const std::string& append) {
71 size_t pos = filename.find_last_of('.');
72 if (pos == std::string::npos) {
73 return filename + append;
74 } else {
75 return filename.substr(0, pos) + append + filename.substr(pos);
76 }
77}
78
79struct ApexConfig {
80 std::string name; // the apex name
81 std::string path; // the path to the apex file
82 // absolute or relative to the config file
83 std::optional<std::string> public_key;
84 std::optional<std::string> root_digest;
85};
86
87struct Config {
88 std::string dirname; // config file's direname to resolve relative paths in the config
89
90 std::vector<std::string> system_apexes;
91 std::vector<ApexConfig> apexes;
92};
93
94#define DO(expr) \
95 if (auto res = (expr); !res.ok()) return res.error()
96
97Result<void> ParseJson(const Json::Value& value, std::string& s) {
98 if (!value.isString()) {
99 return Error() << "should be a string: " << value;
100 }
101 s = value.asString();
102 return {};
103}
104
105Result<void> ParseJson(const Json::Value& value, std::optional<std::string>& s) {
106 if (value.isNull()) {
107 s.reset();
108 return {};
109 }
110 s.emplace();
111 return ParseJson(value, *s);
112}
113
114Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
115 DO(ParseJson(value["name"], apex_config.name));
116 DO(ParseJson(value["path"], apex_config.path));
117 DO(ParseJson(value["publicKey"], apex_config.public_key));
118 DO(ParseJson(value["rootDigest"], apex_config.root_digest));
119 return {};
120}
121
122template <typename T>
123Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
124 for (const Json::Value& value : values) {
125 T t;
126 DO(ParseJson(value, t));
127 parsed.push_back(std::move(t));
128 }
129 return {};
130}
131
132Result<void> ParseJson(const Json::Value& value, Config& config) {
133 DO(ParseJson(value["system_apexes"], config.system_apexes));
134 DO(ParseJson(value["apexes"], config.apexes));
135 return {};
136}
137
138Result<Config> LoadConfig(const std::string& config_file) {
139 std::ifstream in(config_file);
140 Json::CharReaderBuilder builder;
141 Json::Value root;
142 Json::String errs;
143 if (!parseFromStream(builder, in, &root, &errs)) {
144 return Error() << "bad config: " << errs;
145 }
146
147 Config config;
148 config.dirname = Dirname(config_file);
149 DO(ParseJson(root, config));
150 return config;
151}
152
153#undef DO
154
155Result<void> LoadSystemApexes(Config& config) {
156 static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
157 std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
158 if (!apex_info_list.has_value()) {
159 return Error() << "Failed to read " << kApexInfoListFile;
160 }
161 auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
162 for (const auto& apex_info : apex_info_list->getApexInfo()) {
163 if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
164 return apex_info.getModulePath();
165 }
166 }
167 return std::nullopt;
168 };
169 for (const auto& apex_name : config.system_apexes) {
170 const auto& apex_path = get_apex_path(apex_name);
171 if (!apex_path.has_value()) {
172 return Error() << "Can't find the system apex: " << apex_name;
173 }
174 config.apexes.push_back(ApexConfig{
175 .name = apex_name,
176 .path = *apex_path,
177 .public_key = std::nullopt,
178 .root_digest = std::nullopt,
179 });
180 }
181 return {};
182}
183
184Result<void> MakeSignature(const Config& config, const std::string& filename) {
185 MicrodroidSignature signature;
186 signature.set_version(1);
187
188 for (const auto& apex_config : config.apexes) {
189 ApexSignature* apex_signature = signature.add_apexes();
190
191 // name
192 apex_signature->set_name(apex_config.name);
193
194 // size
195 auto file_size = GetFileSize(ToAbsolute(apex_config.path, config.dirname));
196 if (!file_size.ok()) {
197 return Error() << "I/O error: " << file_size.error();
198 }
199 apex_signature->set_size(file_size.value());
200
201 // publicKey
202 if (apex_config.public_key.has_value()) {
203 apex_signature->set_publickey(apex_config.public_key.value());
204 }
205
206 // rootDigest
207 if (apex_config.root_digest.has_value()) {
208 apex_signature->set_rootdigest(apex_config.root_digest.value());
209 }
210 }
211
212 std::ofstream out(filename);
213 return WriteMicrodroidSignature(signature, out);
214}
215
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900216Result<void> GenerateFiller(const std::string& file_path, const std::string& filler_path) {
217 auto file_size = GetFileSize(file_path);
218 if (!file_size.ok()) {
219 return file_size.error();
220 }
221 auto disk_size = AlignToPartitionSize(*file_size + sizeof(uint32_t));
222
223 unique_fd fd(TEMP_FAILURE_RETRY(open(filler_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600)));
224 if (fd.get() == -1) {
225 return ErrnoError() << "open(" << filler_path << ") failed.";
226 }
227 uint32_t size = htobe32(static_cast<uint32_t>(*file_size));
228 if (ftruncate(fd.get(), disk_size - *file_size) == -1) {
229 return ErrnoError() << "ftruncate(" << filler_path << ") failed.";
230 }
231 if (lseek(fd.get(), -sizeof(size), SEEK_END) == -1) {
232 return ErrnoError() << "lseek(" << filler_path << ") failed.";
233 }
234 if (write(fd.get(), &size, sizeof(size)) <= 0) {
235 return ErrnoError() << "write(" << filler_path << ") failed.";
236 }
237 return {};
238}
239
Jooyung Han017916b2021-04-20 03:57:19 +0900240Result<void> MakePayload(const Config& config, const std::string& signature_file,
241 const std::string& output_file) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900242 std::vector<MultipleImagePartition> partitions;
Jooyung Han017916b2021-04-20 03:57:19 +0900243
244 // put signature at the first partition
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900245 partitions.push_back(MultipleImagePartition{
Jooyung Han017916b2021-04-20 03:57:19 +0900246 .label = "signature",
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900247 .image_file_paths = {signature_file},
Jooyung Han017916b2021-04-20 03:57:19 +0900248 .type = kLinuxFilesystem,
249 .read_only = true,
250 });
251
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900252 // put apexes at the subsequent partitions with "size" filler
Jooyung Han017916b2021-04-20 03:57:19 +0900253 for (size_t i = 0; i < config.apexes.size(); i++) {
254 const auto& apex_config = config.apexes[i];
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900255 std::string apex_path = ToAbsolute(apex_config.path, config.dirname);
256 std::string filler_path = output_file + "." + std::to_string(i);
257 if (auto ret = GenerateFiller(apex_path, filler_path); !ret.ok()) {
258 return ret.error();
259 }
260 partitions.push_back(MultipleImagePartition{
261 .label = "microdroid-apex-" + std::to_string(i),
262 .image_file_paths = {apex_path, filler_path},
Jooyung Han017916b2021-04-20 03:57:19 +0900263 .type = kLinuxFilesystem,
264 .read_only = true,
265 });
266 }
267
268 const std::string gpt_header = AppendFileName(output_file, "-header");
269 const std::string gpt_footer = AppendFileName(output_file, "-footer");
270 CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
271 return {};
272}
273
274int main(int argc, char** argv) {
275 if (argc != 3) {
276 std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
277 return 1;
278 }
279
280 auto config = LoadConfig(argv[1]);
281 if (!config.ok()) {
282 std::cerr << config.error() << '\n';
283 return 1;
284 }
285
286 if (const auto res = LoadSystemApexes(*config); !res.ok()) {
287 std::cerr << res.error() << '\n';
288 return 1;
289 }
290
291 const std::string output_file(argv[2]);
292 const std::string signature_file = AppendFileName(output_file, "-signature");
293
294 if (const auto res = MakeSignature(*config, signature_file); !res.ok()) {
295 std::cerr << res.error() << '\n';
296 return 1;
297 }
298 if (const auto res = MakePayload(*config, signature_file, output_file); !res.ok()) {
299 std::cerr << res.error() << '\n';
300 return 1;
301 }
302
303 return 0;
304}