blob: 9765292c5b4ddf2a420b8e41c37fae9e78b6e8dd [file] [log] [blame]
Alex Buynytskyy175ce292020-02-13 06:52:04 -08001/*
2 * Copyright (C) 2020 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 "incremental.h"
18
Yurii Zubrytskyif64ea4b2020-02-20 15:30:45 -080019#include <android-base/endian.h>
Alex Buynytskyy175ce292020-02-13 06:52:04 -080020#include <android-base/file.h>
21#include <android-base/stringprintf.h>
22#include <openssl/base64.h>
23
24#include "adb_client.h"
25#include "adb_io.h"
26#include "adb_utils.h"
27#include "commandline.h"
28#include "sysdeps.h"
29
Alex Buynytskyy175ce292020-02-13 06:52:04 -080030using namespace std::literals;
31
32namespace incremental {
33
34namespace {
35
36static constexpr auto IDSIG = ".idsig"sv;
37
38using android::base::StringPrintf;
39
40using Size = int64_t;
41
42static inline int32_t read_int32(borrowed_fd fd) {
43 int32_t result;
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -070044 return ReadFdExactly(fd, &result, sizeof(result)) ? result : -1;
Alex Buynytskyy175ce292020-02-13 06:52:04 -080045}
46
Yurii Zubrytskyi09e5e242020-02-19 14:46:16 -080047static inline void append_int(borrowed_fd fd, std::vector<char>* bytes) {
Alex Buynytskyyb70f32a2020-03-13 08:39:31 -070048 int32_t le_val = read_int32(fd);
Yurii Zubrytskyi09e5e242020-02-19 14:46:16 -080049 auto old_size = bytes->size();
Alex Buynytskyyb70f32a2020-03-13 08:39:31 -070050 bytes->resize(old_size + sizeof(le_val));
51 memcpy(bytes->data() + old_size, &le_val, sizeof(le_val));
Yurii Zubrytskyi09e5e242020-02-19 14:46:16 -080052}
53
Alex Buynytskyy175ce292020-02-13 06:52:04 -080054static inline void append_bytes_with_size(borrowed_fd fd, std::vector<char>* bytes) {
Alex Buynytskyyb70f32a2020-03-13 08:39:31 -070055 int32_t le_size = read_int32(fd);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -070056 if (le_size < 0) {
57 return;
58 }
Alex Buynytskyyb70f32a2020-03-13 08:39:31 -070059 int32_t size = int32_t(le32toh(le_size));
Alex Buynytskyy175ce292020-02-13 06:52:04 -080060 auto old_size = bytes->size();
Alex Buynytskyyb70f32a2020-03-13 08:39:31 -070061 bytes->resize(old_size + sizeof(le_size) + size);
62 memcpy(bytes->data() + old_size, &le_size, sizeof(le_size));
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -070063 ReadFdExactly(fd, bytes->data() + old_size + sizeof(le_size), size);
Alex Buynytskyy175ce292020-02-13 06:52:04 -080064}
65
66static inline std::pair<std::vector<char>, int32_t> read_id_sig_headers(borrowed_fd fd) {
67 std::vector<char> result;
Yurii Zubrytskyi09e5e242020-02-19 14:46:16 -080068 append_int(fd, &result); // version
Alex Buynytskyyb70f32a2020-03-13 08:39:31 -070069 append_bytes_with_size(fd, &result); // hashingInfo
70 append_bytes_with_size(fd, &result); // signingInfo
71 auto le_tree_size = read_int32(fd);
72 auto tree_size = int32_t(le32toh(le_tree_size)); // size of the verity tree
Alex Buynytskyy175ce292020-02-13 06:52:04 -080073 return {std::move(result), tree_size};
74}
75
76static inline Size verity_tree_size_for_file(Size fileSize) {
77 constexpr int INCFS_DATA_FILE_BLOCK_SIZE = 4096;
78 constexpr int SHA256_DIGEST_SIZE = 32;
79 constexpr int digest_size = SHA256_DIGEST_SIZE;
80 constexpr int hash_per_block = INCFS_DATA_FILE_BLOCK_SIZE / digest_size;
81
82 Size total_tree_block_count = 0;
83
84 auto block_count = 1 + (fileSize - 1) / INCFS_DATA_FILE_BLOCK_SIZE;
85 auto hash_block_count = block_count;
86 for (auto i = 0; hash_block_count > 1; i++) {
87 hash_block_count = (hash_block_count + hash_per_block - 1) / hash_per_block;
88 total_tree_block_count += hash_block_count;
89 }
90 return total_tree_block_count * INCFS_DATA_FILE_BLOCK_SIZE;
91}
92
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -070093// Read, verify and return the signature bytes. Keeping fd at the position of start of verity tree.
94static std::pair<unique_fd, std::vector<char>> read_signature(Size file_size,
95 std::string signature_file,
96 bool silent) {
Alex Buynytskyy175ce292020-02-13 06:52:04 -080097 signature_file += IDSIG;
98
99 struct stat st;
100 if (stat(signature_file.c_str(), &st)) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700101 if (!silent) {
102 fprintf(stderr, "Failed to stat signature file %s. Abort.\n", signature_file.c_str());
103 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800104 return {};
105 }
106
107 unique_fd fd(adb_open(signature_file.c_str(), O_RDONLY | O_CLOEXEC));
108 if (fd < 0) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700109 if (!silent) {
110 fprintf(stderr, "Failed to open signature file: %s. Abort.\n", signature_file.c_str());
111 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800112 return {};
113 }
114
115 auto [signature, tree_size] = read_id_sig_headers(fd);
116 if (auto expected = verity_tree_size_for_file(file_size); tree_size != expected) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700117 if (!silent) {
118 fprintf(stderr,
119 "Verity tree size mismatch in signature file: %s [was %lld, expected %lld].\n",
120 signature_file.c_str(), (long long)tree_size, (long long)expected);
121 }
122 return {};
123 }
124
125 return {std::move(fd), std::move(signature)};
126}
127
128// Base64-encode signature bytes. Keeping fd at the position of start of verity tree.
129static std::pair<unique_fd, std::string> read_and_encode_signature(Size file_size,
130 std::string signature_file,
131 bool silent) {
132 auto [fd, signature] = read_signature(file_size, std::move(signature_file), silent);
133 if (!fd.ok()) {
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800134 return {};
135 }
136
137 size_t base64_len = 0;
138 if (!EVP_EncodedLength(&base64_len, signature.size())) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700139 if (!silent) {
140 fprintf(stderr, "Fail to estimate base64 encoded length. Abort.\n");
141 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800142 return {};
143 }
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700144 std::string encoded_signature(base64_len, '\0');
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800145 encoded_signature.resize(EVP_EncodeBlock((uint8_t*)encoded_signature.data(),
146 (const uint8_t*)signature.data(), signature.size()));
147
148 return {std::move(fd), std::move(encoded_signature)};
149}
150
151// Send install-incremental to the device along with properly configured file descriptors in
152// streaming format. Once connection established, send all fs-verity tree bytes.
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700153static unique_fd start_install(const Files& files, bool silent) {
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800154 std::vector<std::string> command_args{"package", "install-incremental"};
155
156 // fd's with positions at the beginning of fs-verity
157 std::vector<unique_fd> signature_fds;
158 signature_fds.reserve(files.size());
159 for (int i = 0, size = files.size(); i < size; ++i) {
160 const auto& file = files[i];
161
162 struct stat st;
163 if (stat(file.c_str(), &st)) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700164 if (!silent) {
165 fprintf(stderr, "Failed to stat input file %s. Abort.\n", file.c_str());
166 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800167 return {};
168 }
169
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700170 auto [signature_fd, signature] = read_and_encode_signature(st.st_size, file, silent);
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800171 if (!signature_fd.ok()) {
172 return {};
173 }
174
175 auto file_desc =
176 StringPrintf("%s:%lld:%s:%s", android::base::Basename(file).c_str(),
177 (long long)st.st_size, std::to_string(i).c_str(), signature.c_str());
178 command_args.push_back(std::move(file_desc));
179
180 signature_fds.push_back(std::move(signature_fd));
181 }
182
183 std::string error;
184 auto connection_fd = unique_fd(send_abb_exec_command(command_args, &error));
185 if (connection_fd < 0) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700186 if (!silent) {
187 fprintf(stderr, "Failed to run: %s, error: %s\n",
188 android::base::Join(command_args, " ").c_str(), error.c_str());
189 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800190 return {};
191 }
192
193 // Pushing verity trees for all installation files.
194 for (auto&& local_fd : signature_fds) {
195 if (!copy_to_file(local_fd.get(), connection_fd.get())) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700196 if (!silent) {
197 fprintf(stderr, "Failed to stream tree bytes: %s. Abort.\n", strerror(errno));
198 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800199 return {};
200 }
201 }
202
203 return connection_fd;
204}
205
206} // namespace
207
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700208bool can_install(const Files& files) {
209 for (const auto& file : files) {
210 struct stat st;
211 if (stat(file.c_str(), &st)) {
212 return false;
213 }
214
215 auto [fd, _] = read_signature(st.st_size, file, true);
216 if (!fd.ok()) {
217 return false;
218 }
219 }
220 return true;
221}
222
223std::optional<Process> install(const Files& files, bool silent) {
224 auto connection_fd = start_install(files, silent);
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800225 if (connection_fd < 0) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700226 if (!silent) {
227 fprintf(stderr, "adb: failed to initiate installation on device.\n");
228 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800229 return {};
230 }
231
232 std::string adb_path = android::base::GetExecutablePath();
233
Yurii Zubrytskyi3c0574f2020-03-26 18:16:36 -0700234 auto osh = cast_handle_to_int(adb_get_os_handle(connection_fd.get()));
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800235 auto fd_param = std::to_string(osh);
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800236
Songchun Fandaf826a2020-03-09 11:33:44 -0700237 // pipe for child process to write output
238 int print_fds[2];
239 if (adb_socketpair(print_fds) != 0) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700240 if (!silent) {
241 fprintf(stderr, "Failed to create socket pair for child to print to parent\n");
242 }
Songchun Fandaf826a2020-03-09 11:33:44 -0700243 return {};
244 }
245 auto [pipe_read_fd, pipe_write_fd] = print_fds;
Yurii Zubrytskyi3c0574f2020-03-26 18:16:36 -0700246 auto pipe_write_fd_param = std::to_string(cast_handle_to_int(adb_get_os_handle(pipe_write_fd)));
Songchun Fandaf826a2020-03-09 11:33:44 -0700247 close_on_exec(pipe_read_fd);
248
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800249 std::vector<std::string> args(std::move(files));
Songchun Fandaf826a2020-03-09 11:33:44 -0700250 args.insert(args.begin(), {"inc-server", fd_param, pipe_write_fd_param});
251 auto child =
252 adb_launch_process(adb_path, std::move(args), {connection_fd.get(), pipe_write_fd});
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800253 if (!child) {
Yurii Zubrytskyi39ee3d82020-03-26 18:20:39 -0700254 if (!silent) {
255 fprintf(stderr, "adb: failed to fork: %s\n", strerror(errno));
256 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800257 return {};
258 }
259
Songchun Fandaf826a2020-03-09 11:33:44 -0700260 adb_close(pipe_write_fd);
261
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800262 auto killOnExit = [](Process* p) { p->kill(); };
263 std::unique_ptr<Process, decltype(killOnExit)> serverKiller(&child, killOnExit);
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800264
Songchun Fandaf826a2020-03-09 11:33:44 -0700265 Result result = wait_for_installation(pipe_read_fd);
266 adb_close(pipe_read_fd);
267
268 if (result == Result::Success) {
269 // adb client exits now but inc-server can continue
270 serverKiller.release();
271 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800272 return child;
273}
274
Songchun Fandaf826a2020-03-09 11:33:44 -0700275Result wait_for_installation(int read_fd) {
276 static constexpr int maxMessageSize = 256;
277 std::vector<char> child_stdout(CHUNK_SIZE);
278 int bytes_read;
279 int buf_size = 0;
280 // TODO(b/150865433): optimize child's output parsing
281 while ((bytes_read = adb_read(read_fd, child_stdout.data() + buf_size,
282 child_stdout.size() - buf_size)) > 0) {
283 // print to parent's stdout
284 fprintf(stdout, "%.*s", bytes_read, child_stdout.data() + buf_size);
285
286 buf_size += bytes_read;
287 const std::string_view stdout_str(child_stdout.data(), buf_size);
288 // wait till installation either succeeds or fails
289 if (stdout_str.find("Success") != std::string::npos) {
290 return Result::Success;
291 }
292 // on failure, wait for full message
293 static constexpr auto failure_msg_head = "Failure ["sv;
294 if (const auto begin_itr = stdout_str.find(failure_msg_head);
295 begin_itr != std::string::npos) {
296 if (buf_size >= maxMessageSize) {
297 return Result::Failure;
298 }
299 const auto end_itr = stdout_str.rfind("]");
300 if (end_itr != std::string::npos && end_itr >= begin_itr + failure_msg_head.size()) {
301 return Result::Failure;
302 }
303 }
304 child_stdout.resize(buf_size + CHUNK_SIZE);
305 }
306 return Result::None;
307}
308
Alex Buynytskyy175ce292020-02-13 06:52:04 -0800309} // namespace incremental