blob: a3501d4bd1940f1d063c13295ec29e864779f2b3 [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;
Jooyung Han57d895e2021-05-13 21:58:41 +090041using android::microdroid::ApkSignature;
Jooyung Han017916b2021-04-20 03:57:19 +090042using android::microdroid::MicrodroidSignature;
43using android::microdroid::WriteMicrodroidSignature;
44
45using com::android::apex::ApexInfoList;
46using com::android::apex::readApexInfoList;
47
Jooyung Hana54dcaf2021-05-13 21:57:02 +090048using cuttlefish::AlignToPartitionSize;
Jooyung Han017916b2021-04-20 03:57:19 +090049using cuttlefish::CreateCompositeDisk;
Jooyung Han017916b2021-04-20 03:57:19 +090050using cuttlefish::kLinuxFilesystem;
Jooyung Hana54dcaf2021-05-13 21:57:02 +090051using cuttlefish::MultipleImagePartition;
Jooyung Han017916b2021-04-20 03:57:19 +090052
53Result<uint32_t> GetFileSize(const std::string& path) {
54 struct stat st;
55 if (lstat(path.c_str(), &st) == -1) {
56 return ErrnoError() << "Can't lstat " << path;
57 }
58 return static_cast<uint32_t>(st.st_size);
59}
60
61std::string ToAbsolute(const std::string& path, const std::string& dirname) {
62 bool is_absolute = !path.empty() && path[0] == '/';
63 if (is_absolute) {
64 return path;
65 } else {
66 return dirname + "/" + path;
67 }
68}
69
70// Returns `append` is appended to the end of filename preserving the extension.
71std::string AppendFileName(const std::string& filename, const std::string& append) {
72 size_t pos = filename.find_last_of('.');
73 if (pos == std::string::npos) {
74 return filename + append;
75 } else {
76 return filename.substr(0, pos) + append + filename.substr(pos);
77 }
78}
79
80struct ApexConfig {
81 std::string name; // the apex name
82 std::string path; // the path to the apex file
83 // absolute or relative to the config file
84 std::optional<std::string> public_key;
85 std::optional<std::string> root_digest;
86};
87
Jooyung Han57d895e2021-05-13 21:58:41 +090088struct ApkConfig {
89 std::string name;
90 // TODO(jooyung): find path/idsig with name
91 std::string path;
92};
93
Jooyung Han017916b2021-04-20 03:57:19 +090094struct Config {
95 std::string dirname; // config file's direname to resolve relative paths in the config
96
97 std::vector<std::string> system_apexes;
98 std::vector<ApexConfig> apexes;
Jooyung Han57d895e2021-05-13 21:58:41 +090099 std::optional<ApkConfig> apk;
Jooyung Han017916b2021-04-20 03:57:19 +0900100};
101
102#define DO(expr) \
103 if (auto res = (expr); !res.ok()) return res.error()
104
105Result<void> ParseJson(const Json::Value& value, std::string& s) {
106 if (!value.isString()) {
107 return Error() << "should be a string: " << value;
108 }
109 s = value.asString();
110 return {};
111}
112
Jooyung Han57d895e2021-05-13 21:58:41 +0900113template <typename T>
114Result<void> ParseJson(const Json::Value& value, std::optional<T>& s) {
Jooyung Han017916b2021-04-20 03:57:19 +0900115 if (value.isNull()) {
116 s.reset();
117 return {};
118 }
119 s.emplace();
120 return ParseJson(value, *s);
121}
122
123Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
124 DO(ParseJson(value["name"], apex_config.name));
125 DO(ParseJson(value["path"], apex_config.path));
126 DO(ParseJson(value["publicKey"], apex_config.public_key));
127 DO(ParseJson(value["rootDigest"], apex_config.root_digest));
128 return {};
129}
130
Jooyung Han57d895e2021-05-13 21:58:41 +0900131Result<void> ParseJson(const Json::Value& value, ApkConfig& apk_config) {
132 DO(ParseJson(value["name"], apk_config.name));
133 DO(ParseJson(value["path"], apk_config.path));
134 return {};
135}
136
Jooyung Han017916b2021-04-20 03:57:19 +0900137template <typename T>
138Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
139 for (const Json::Value& value : values) {
140 T t;
141 DO(ParseJson(value, t));
142 parsed.push_back(std::move(t));
143 }
144 return {};
145}
146
147Result<void> ParseJson(const Json::Value& value, Config& config) {
148 DO(ParseJson(value["system_apexes"], config.system_apexes));
149 DO(ParseJson(value["apexes"], config.apexes));
Jooyung Han57d895e2021-05-13 21:58:41 +0900150 DO(ParseJson(value["apk"], config.apk));
Jooyung Han017916b2021-04-20 03:57:19 +0900151 return {};
152}
153
154Result<Config> LoadConfig(const std::string& config_file) {
155 std::ifstream in(config_file);
156 Json::CharReaderBuilder builder;
157 Json::Value root;
158 Json::String errs;
159 if (!parseFromStream(builder, in, &root, &errs)) {
160 return Error() << "bad config: " << errs;
161 }
162
163 Config config;
164 config.dirname = Dirname(config_file);
165 DO(ParseJson(root, config));
166 return config;
167}
168
169#undef DO
170
171Result<void> LoadSystemApexes(Config& config) {
172 static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
173 std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
174 if (!apex_info_list.has_value()) {
175 return Error() << "Failed to read " << kApexInfoListFile;
176 }
177 auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
178 for (const auto& apex_info : apex_info_list->getApexInfo()) {
179 if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
180 return apex_info.getModulePath();
181 }
182 }
183 return std::nullopt;
184 };
185 for (const auto& apex_name : config.system_apexes) {
186 const auto& apex_path = get_apex_path(apex_name);
187 if (!apex_path.has_value()) {
188 return Error() << "Can't find the system apex: " << apex_name;
189 }
190 config.apexes.push_back(ApexConfig{
191 .name = apex_name,
192 .path = *apex_path,
193 .public_key = std::nullopt,
194 .root_digest = std::nullopt,
195 });
196 }
197 return {};
198}
199
200Result<void> MakeSignature(const Config& config, const std::string& filename) {
201 MicrodroidSignature signature;
202 signature.set_version(1);
203
204 for (const auto& apex_config : config.apexes) {
205 ApexSignature* apex_signature = signature.add_apexes();
206
207 // name
208 apex_signature->set_name(apex_config.name);
209
210 // size
211 auto file_size = GetFileSize(ToAbsolute(apex_config.path, config.dirname));
212 if (!file_size.ok()) {
213 return Error() << "I/O error: " << file_size.error();
214 }
215 apex_signature->set_size(file_size.value());
216
217 // publicKey
218 if (apex_config.public_key.has_value()) {
219 apex_signature->set_publickey(apex_config.public_key.value());
220 }
221
222 // rootDigest
223 if (apex_config.root_digest.has_value()) {
224 apex_signature->set_rootdigest(apex_config.root_digest.value());
225 }
226 }
227
Jooyung Han57d895e2021-05-13 21:58:41 +0900228 if (config.apk.has_value()) {
229 ApkSignature* apk_signature = signature.mutable_apk();
230 apk_signature->set_name(config.apk->name);
231 apk_signature->set_payload_partition_name("microdroid-apk");
232 // TODO(jooyung): set idsig partition as well
233 }
234
Jooyung Han017916b2021-04-20 03:57:19 +0900235 std::ofstream out(filename);
236 return WriteMicrodroidSignature(signature, out);
237}
238
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900239Result<void> GenerateFiller(const std::string& file_path, const std::string& filler_path) {
240 auto file_size = GetFileSize(file_path);
241 if (!file_size.ok()) {
242 return file_size.error();
243 }
244 auto disk_size = AlignToPartitionSize(*file_size + sizeof(uint32_t));
245
246 unique_fd fd(TEMP_FAILURE_RETRY(open(filler_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600)));
247 if (fd.get() == -1) {
248 return ErrnoError() << "open(" << filler_path << ") failed.";
249 }
250 uint32_t size = htobe32(static_cast<uint32_t>(*file_size));
251 if (ftruncate(fd.get(), disk_size - *file_size) == -1) {
252 return ErrnoError() << "ftruncate(" << filler_path << ") failed.";
253 }
254 if (lseek(fd.get(), -sizeof(size), SEEK_END) == -1) {
255 return ErrnoError() << "lseek(" << filler_path << ") failed.";
256 }
257 if (write(fd.get(), &size, sizeof(size)) <= 0) {
258 return ErrnoError() << "write(" << filler_path << ") failed.";
259 }
260 return {};
261}
262
Jooyung Han017916b2021-04-20 03:57:19 +0900263Result<void> MakePayload(const Config& config, const std::string& signature_file,
264 const std::string& output_file) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900265 std::vector<MultipleImagePartition> partitions;
Jooyung Han017916b2021-04-20 03:57:19 +0900266
267 // put signature at the first partition
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900268 partitions.push_back(MultipleImagePartition{
Jooyung Han017916b2021-04-20 03:57:19 +0900269 .label = "signature",
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900270 .image_file_paths = {signature_file},
Jooyung Han017916b2021-04-20 03:57:19 +0900271 .type = kLinuxFilesystem,
272 .read_only = true,
273 });
274
Jooyung Han57d895e2021-05-13 21:58:41 +0900275 int filler_count = 0;
276 auto add_partition = [&](auto partition_name, auto file_path) -> Result<void> {
277 std::string filler_path = output_file + "." + std::to_string(filler_count++);
278 if (auto ret = GenerateFiller(file_path, filler_path); !ret.ok()) {
279 return ret.error();
280 }
281 partitions.push_back(MultipleImagePartition{
282 .label = partition_name,
283 .image_file_paths = {file_path, filler_path},
284 .type = kLinuxFilesystem,
285 .read_only = true,
286 });
287 return {};
288 };
289
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900290 // put apexes at the subsequent partitions with "size" filler
Jooyung Han017916b2021-04-20 03:57:19 +0900291 for (size_t i = 0; i < config.apexes.size(); i++) {
292 const auto& apex_config = config.apexes[i];
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900293 std::string apex_path = ToAbsolute(apex_config.path, config.dirname);
Jooyung Han57d895e2021-05-13 21:58:41 +0900294 if (auto ret = add_partition("microdroid-apex-" + std::to_string(i), apex_path);
295 !ret.ok()) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900296 return ret.error();
297 }
Jooyung Han57d895e2021-05-13 21:58:41 +0900298 }
299 // put apk with "size" filler if necessary.
300 // TODO(jooyung): partition name("microdroid-apk") is TBD
301 if (config.apk.has_value()) {
302 std::string apk_path = ToAbsolute(config.apk->path, config.dirname);
303 if (auto ret = add_partition("microdroid-apk", apk_path); !ret.ok()) {
304 return ret.error();
305 }
Jooyung Han017916b2021-04-20 03:57:19 +0900306 }
307
308 const std::string gpt_header = AppendFileName(output_file, "-header");
309 const std::string gpt_footer = AppendFileName(output_file, "-footer");
310 CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
311 return {};
312}
313
314int main(int argc, char** argv) {
315 if (argc != 3) {
316 std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
317 return 1;
318 }
319
320 auto config = LoadConfig(argv[1]);
321 if (!config.ok()) {
322 std::cerr << config.error() << '\n';
323 return 1;
324 }
325
326 if (const auto res = LoadSystemApexes(*config); !res.ok()) {
327 std::cerr << res.error() << '\n';
328 return 1;
329 }
330
331 const std::string output_file(argv[2]);
332 const std::string signature_file = AppendFileName(output_file, "-signature");
333
334 if (const auto res = MakeSignature(*config, signature_file); !res.ok()) {
335 std::cerr << res.error() << '\n';
336 return 1;
337 }
338 if (const auto res = MakePayload(*config, signature_file, output_file); !res.ok()) {
339 std::cerr << res.error() << '\n';
340 return 1;
341 }
342
343 return 0;
344}