blob: 8046b5ea70078db1b9ab28205e7de208cb60de56 [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;
39using android::microdroid::ApexSignature;
40using android::microdroid::MicrodroidSignature;
41using android::microdroid::WriteMicrodroidSignature;
42
43using com::android::apex::ApexInfoList;
44using com::android::apex::readApexInfoList;
45
46using cuttlefish::CreateCompositeDisk;
47using cuttlefish::ImagePartition;
48using cuttlefish::kLinuxFilesystem;
49
50Result<uint32_t> GetFileSize(const std::string& path) {
51 struct stat st;
52 if (lstat(path.c_str(), &st) == -1) {
53 return ErrnoError() << "Can't lstat " << path;
54 }
55 return static_cast<uint32_t>(st.st_size);
56}
57
58std::string ToAbsolute(const std::string& path, const std::string& dirname) {
59 bool is_absolute = !path.empty() && path[0] == '/';
60 if (is_absolute) {
61 return path;
62 } else {
63 return dirname + "/" + path;
64 }
65}
66
67// Returns `append` is appended to the end of filename preserving the extension.
68std::string AppendFileName(const std::string& filename, const std::string& append) {
69 size_t pos = filename.find_last_of('.');
70 if (pos == std::string::npos) {
71 return filename + append;
72 } else {
73 return filename.substr(0, pos) + append + filename.substr(pos);
74 }
75}
76
77struct ApexConfig {
78 std::string name; // the apex name
79 std::string path; // the path to the apex file
80 // absolute or relative to the config file
81 std::optional<std::string> public_key;
82 std::optional<std::string> root_digest;
83};
84
85struct Config {
86 std::string dirname; // config file's direname to resolve relative paths in the config
87
88 std::vector<std::string> system_apexes;
89 std::vector<ApexConfig> apexes;
90};
91
92#define DO(expr) \
93 if (auto res = (expr); !res.ok()) return res.error()
94
95Result<void> ParseJson(const Json::Value& value, std::string& s) {
96 if (!value.isString()) {
97 return Error() << "should be a string: " << value;
98 }
99 s = value.asString();
100 return {};
101}
102
103Result<void> ParseJson(const Json::Value& value, std::optional<std::string>& s) {
104 if (value.isNull()) {
105 s.reset();
106 return {};
107 }
108 s.emplace();
109 return ParseJson(value, *s);
110}
111
112Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
113 DO(ParseJson(value["name"], apex_config.name));
114 DO(ParseJson(value["path"], apex_config.path));
115 DO(ParseJson(value["publicKey"], apex_config.public_key));
116 DO(ParseJson(value["rootDigest"], apex_config.root_digest));
117 return {};
118}
119
120template <typename T>
121Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
122 for (const Json::Value& value : values) {
123 T t;
124 DO(ParseJson(value, t));
125 parsed.push_back(std::move(t));
126 }
127 return {};
128}
129
130Result<void> ParseJson(const Json::Value& value, Config& config) {
131 DO(ParseJson(value["system_apexes"], config.system_apexes));
132 DO(ParseJson(value["apexes"], config.apexes));
133 return {};
134}
135
136Result<Config> LoadConfig(const std::string& config_file) {
137 std::ifstream in(config_file);
138 Json::CharReaderBuilder builder;
139 Json::Value root;
140 Json::String errs;
141 if (!parseFromStream(builder, in, &root, &errs)) {
142 return Error() << "bad config: " << errs;
143 }
144
145 Config config;
146 config.dirname = Dirname(config_file);
147 DO(ParseJson(root, config));
148 return config;
149}
150
151#undef DO
152
153Result<void> LoadSystemApexes(Config& config) {
154 static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
155 std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
156 if (!apex_info_list.has_value()) {
157 return Error() << "Failed to read " << kApexInfoListFile;
158 }
159 auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
160 for (const auto& apex_info : apex_info_list->getApexInfo()) {
161 if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
162 return apex_info.getModulePath();
163 }
164 }
165 return std::nullopt;
166 };
167 for (const auto& apex_name : config.system_apexes) {
168 const auto& apex_path = get_apex_path(apex_name);
169 if (!apex_path.has_value()) {
170 return Error() << "Can't find the system apex: " << apex_name;
171 }
172 config.apexes.push_back(ApexConfig{
173 .name = apex_name,
174 .path = *apex_path,
175 .public_key = std::nullopt,
176 .root_digest = std::nullopt,
177 });
178 }
179 return {};
180}
181
182Result<void> MakeSignature(const Config& config, const std::string& filename) {
183 MicrodroidSignature signature;
184 signature.set_version(1);
185
186 for (const auto& apex_config : config.apexes) {
187 ApexSignature* apex_signature = signature.add_apexes();
188
189 // name
190 apex_signature->set_name(apex_config.name);
191
192 // size
193 auto file_size = GetFileSize(ToAbsolute(apex_config.path, config.dirname));
194 if (!file_size.ok()) {
195 return Error() << "I/O error: " << file_size.error();
196 }
197 apex_signature->set_size(file_size.value());
198
199 // publicKey
200 if (apex_config.public_key.has_value()) {
201 apex_signature->set_publickey(apex_config.public_key.value());
202 }
203
204 // rootDigest
205 if (apex_config.root_digest.has_value()) {
206 apex_signature->set_rootdigest(apex_config.root_digest.value());
207 }
208 }
209
210 std::ofstream out(filename);
211 return WriteMicrodroidSignature(signature, out);
212}
213
214Result<void> MakePayload(const Config& config, const std::string& signature_file,
215 const std::string& output_file) {
216 std::vector<ImagePartition> partitions;
217
218 // put signature at the first partition
219 partitions.push_back(ImagePartition{
220 .label = "signature",
221 .image_file_path = signature_file,
222 .type = kLinuxFilesystem,
223 .read_only = true,
224 });
225
226 // put apexes at the subsequent partitions
227 for (size_t i = 0; i < config.apexes.size(); i++) {
228 const auto& apex_config = config.apexes[i];
229 partitions.push_back(ImagePartition{
230 .label = "payload_apex_" + std::to_string(i),
231 .image_file_path = apex_config.path,
232 .type = kLinuxFilesystem,
233 .read_only = true,
234 });
235 }
236
237 const std::string gpt_header = AppendFileName(output_file, "-header");
238 const std::string gpt_footer = AppendFileName(output_file, "-footer");
239 CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
240 return {};
241}
242
243int main(int argc, char** argv) {
244 if (argc != 3) {
245 std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
246 return 1;
247 }
248
249 auto config = LoadConfig(argv[1]);
250 if (!config.ok()) {
251 std::cerr << config.error() << '\n';
252 return 1;
253 }
254
255 if (const auto res = LoadSystemApexes(*config); !res.ok()) {
256 std::cerr << res.error() << '\n';
257 return 1;
258 }
259
260 const std::string output_file(argv[2]);
261 const std::string signature_file = AppendFileName(output_file, "-signature");
262
263 if (const auto res = MakeSignature(*config, signature_file); !res.ok()) {
264 std::cerr << res.error() << '\n';
265 return 1;
266 }
267 if (const auto res = MakePayload(*config, signature_file, output_file); !res.ok()) {
268 std::cerr << res.error() << '\n';
269 return 1;
270 }
271
272 return 0;
273}