blob: 9caf78877bf0547050a05b9f84533e41d07c8d1f [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 Han347d9f22021-05-28 00:05:14 +0900100 std::optional<std::string> payload_config_path;
Jooyung Han017916b2021-04-20 03:57:19 +0900101};
102
103#define DO(expr) \
104 if (auto res = (expr); !res.ok()) return res.error()
105
106Result<void> ParseJson(const Json::Value& value, std::string& s) {
107 if (!value.isString()) {
108 return Error() << "should be a string: " << value;
109 }
110 s = value.asString();
111 return {};
112}
113
Jooyung Han57d895e2021-05-13 21:58:41 +0900114template <typename T>
115Result<void> ParseJson(const Json::Value& value, std::optional<T>& s) {
Jooyung Han017916b2021-04-20 03:57:19 +0900116 if (value.isNull()) {
117 s.reset();
118 return {};
119 }
120 s.emplace();
121 return ParseJson(value, *s);
122}
123
Jooyung Han347d9f22021-05-28 00:05:14 +0900124template <typename T>
125Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
126 for (const Json::Value& value : values) {
127 T t;
128 DO(ParseJson(value, t));
129 parsed.push_back(std::move(t));
130 }
131 return {};
132}
133
Jooyung Han017916b2021-04-20 03:57:19 +0900134Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
135 DO(ParseJson(value["name"], apex_config.name));
136 DO(ParseJson(value["path"], apex_config.path));
137 DO(ParseJson(value["publicKey"], apex_config.public_key));
138 DO(ParseJson(value["rootDigest"], apex_config.root_digest));
139 return {};
140}
141
Jooyung Han57d895e2021-05-13 21:58:41 +0900142Result<void> ParseJson(const Json::Value& value, ApkConfig& apk_config) {
143 DO(ParseJson(value["name"], apk_config.name));
144 DO(ParseJson(value["path"], apk_config.path));
145 return {};
146}
147
Jooyung Han017916b2021-04-20 03:57:19 +0900148Result<void> ParseJson(const Json::Value& value, Config& config) {
149 DO(ParseJson(value["system_apexes"], config.system_apexes));
150 DO(ParseJson(value["apexes"], config.apexes));
Jooyung Han57d895e2021-05-13 21:58:41 +0900151 DO(ParseJson(value["apk"], config.apk));
Jooyung Han347d9f22021-05-28 00:05:14 +0900152 DO(ParseJson(value["payload_config_path"], config.payload_config_path));
Jooyung Han017916b2021-04-20 03:57:19 +0900153 return {};
154}
155
156Result<Config> LoadConfig(const std::string& config_file) {
157 std::ifstream in(config_file);
158 Json::CharReaderBuilder builder;
159 Json::Value root;
160 Json::String errs;
161 if (!parseFromStream(builder, in, &root, &errs)) {
162 return Error() << "bad config: " << errs;
163 }
164
165 Config config;
166 config.dirname = Dirname(config_file);
167 DO(ParseJson(root, config));
168 return config;
169}
170
171#undef DO
172
173Result<void> LoadSystemApexes(Config& config) {
174 static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
175 std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
176 if (!apex_info_list.has_value()) {
177 return Error() << "Failed to read " << kApexInfoListFile;
178 }
179 auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
180 for (const auto& apex_info : apex_info_list->getApexInfo()) {
181 if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
182 return apex_info.getModulePath();
183 }
184 }
185 return std::nullopt;
186 };
187 for (const auto& apex_name : config.system_apexes) {
188 const auto& apex_path = get_apex_path(apex_name);
189 if (!apex_path.has_value()) {
190 return Error() << "Can't find the system apex: " << apex_name;
191 }
192 config.apexes.push_back(ApexConfig{
193 .name = apex_name,
194 .path = *apex_path,
195 .public_key = std::nullopt,
196 .root_digest = std::nullopt,
197 });
198 }
199 return {};
200}
201
202Result<void> MakeSignature(const Config& config, const std::string& filename) {
203 MicrodroidSignature signature;
204 signature.set_version(1);
205
206 for (const auto& apex_config : config.apexes) {
207 ApexSignature* apex_signature = signature.add_apexes();
208
209 // name
210 apex_signature->set_name(apex_config.name);
211
212 // size
213 auto file_size = GetFileSize(ToAbsolute(apex_config.path, config.dirname));
214 if (!file_size.ok()) {
215 return Error() << "I/O error: " << file_size.error();
216 }
217 apex_signature->set_size(file_size.value());
218
219 // publicKey
220 if (apex_config.public_key.has_value()) {
221 apex_signature->set_publickey(apex_config.public_key.value());
222 }
223
224 // rootDigest
225 if (apex_config.root_digest.has_value()) {
226 apex_signature->set_rootdigest(apex_config.root_digest.value());
227 }
228 }
229
Jooyung Han57d895e2021-05-13 21:58:41 +0900230 if (config.apk.has_value()) {
231 ApkSignature* apk_signature = signature.mutable_apk();
232 apk_signature->set_name(config.apk->name);
233 apk_signature->set_payload_partition_name("microdroid-apk");
234 // TODO(jooyung): set idsig partition as well
235 }
236
Jooyung Han347d9f22021-05-28 00:05:14 +0900237 if (config.payload_config_path.has_value()) {
238 *signature.mutable_payload_config_path() = config.payload_config_path.value();
239 }
240
Jooyung Han017916b2021-04-20 03:57:19 +0900241 std::ofstream out(filename);
242 return WriteMicrodroidSignature(signature, out);
243}
244
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900245Result<void> GenerateFiller(const std::string& file_path, const std::string& filler_path) {
246 auto file_size = GetFileSize(file_path);
247 if (!file_size.ok()) {
248 return file_size.error();
249 }
250 auto disk_size = AlignToPartitionSize(*file_size + sizeof(uint32_t));
251
252 unique_fd fd(TEMP_FAILURE_RETRY(open(filler_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600)));
253 if (fd.get() == -1) {
254 return ErrnoError() << "open(" << filler_path << ") failed.";
255 }
256 uint32_t size = htobe32(static_cast<uint32_t>(*file_size));
257 if (ftruncate(fd.get(), disk_size - *file_size) == -1) {
258 return ErrnoError() << "ftruncate(" << filler_path << ") failed.";
259 }
260 if (lseek(fd.get(), -sizeof(size), SEEK_END) == -1) {
261 return ErrnoError() << "lseek(" << filler_path << ") failed.";
262 }
263 if (write(fd.get(), &size, sizeof(size)) <= 0) {
264 return ErrnoError() << "write(" << filler_path << ") failed.";
265 }
266 return {};
267}
268
Jooyung Han017916b2021-04-20 03:57:19 +0900269Result<void> MakePayload(const Config& config, const std::string& signature_file,
270 const std::string& output_file) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900271 std::vector<MultipleImagePartition> partitions;
Jooyung Han017916b2021-04-20 03:57:19 +0900272
273 // put signature at the first partition
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900274 partitions.push_back(MultipleImagePartition{
Jooyung Han017916b2021-04-20 03:57:19 +0900275 .label = "signature",
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900276 .image_file_paths = {signature_file},
Jooyung Han017916b2021-04-20 03:57:19 +0900277 .type = kLinuxFilesystem,
278 .read_only = true,
279 });
280
Jooyung Han57d895e2021-05-13 21:58:41 +0900281 int filler_count = 0;
282 auto add_partition = [&](auto partition_name, auto file_path) -> Result<void> {
283 std::string filler_path = output_file + "." + std::to_string(filler_count++);
284 if (auto ret = GenerateFiller(file_path, filler_path); !ret.ok()) {
285 return ret.error();
286 }
287 partitions.push_back(MultipleImagePartition{
288 .label = partition_name,
289 .image_file_paths = {file_path, filler_path},
290 .type = kLinuxFilesystem,
291 .read_only = true,
292 });
293 return {};
294 };
295
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900296 // put apexes at the subsequent partitions with "size" filler
Jooyung Han017916b2021-04-20 03:57:19 +0900297 for (size_t i = 0; i < config.apexes.size(); i++) {
298 const auto& apex_config = config.apexes[i];
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900299 std::string apex_path = ToAbsolute(apex_config.path, config.dirname);
Jooyung Han57d895e2021-05-13 21:58:41 +0900300 if (auto ret = add_partition("microdroid-apex-" + std::to_string(i), apex_path);
301 !ret.ok()) {
Jooyung Hana54dcaf2021-05-13 21:57:02 +0900302 return ret.error();
303 }
Jooyung Han57d895e2021-05-13 21:58:41 +0900304 }
305 // put apk with "size" filler if necessary.
306 // TODO(jooyung): partition name("microdroid-apk") is TBD
307 if (config.apk.has_value()) {
308 std::string apk_path = ToAbsolute(config.apk->path, config.dirname);
309 if (auto ret = add_partition("microdroid-apk", apk_path); !ret.ok()) {
310 return ret.error();
311 }
Jooyung Han017916b2021-04-20 03:57:19 +0900312 }
313
314 const std::string gpt_header = AppendFileName(output_file, "-header");
315 const std::string gpt_footer = AppendFileName(output_file, "-footer");
316 CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
317 return {};
318}
319
320int main(int argc, char** argv) {
321 if (argc != 3) {
322 std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
323 return 1;
324 }
325
326 auto config = LoadConfig(argv[1]);
327 if (!config.ok()) {
328 std::cerr << config.error() << '\n';
329 return 1;
330 }
331
332 if (const auto res = LoadSystemApexes(*config); !res.ok()) {
333 std::cerr << res.error() << '\n';
334 return 1;
335 }
336
337 const std::string output_file(argv[2]);
338 const std::string signature_file = AppendFileName(output_file, "-signature");
339
340 if (const auto res = MakeSignature(*config, signature_file); !res.ok()) {
341 std::cerr << res.error() << '\n';
342 return 1;
343 }
344 if (const auto res = MakePayload(*config, signature_file, output_file); !res.ok()) {
345 std::cerr << res.error() << '\n';
346 return 1;
347 }
348
349 return 0;
350}