blob: fd608cced7f4d7881e0e3ab60815e2002ac7ef49 [file] [log] [blame]
Alex Buynytskyy96ff54b2020-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 Zubrytskyib6595062020-02-20 15:30:45 -080019#include <android-base/endian.h>
Alex Buynytskyy96ff54b2020-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 Buynytskyy96ff54b2020-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;
44 ReadFully(fd, &result, sizeof(result));
45 return result;
46}
47
Yurii Zubrytskyi516c4412020-02-19 14:46:16 -080048static inline void append_int(borrowed_fd fd, std::vector<char>* bytes) {
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070049 int32_t le_val = read_int32(fd);
Yurii Zubrytskyi516c4412020-02-19 14:46:16 -080050 auto old_size = bytes->size();
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070051 bytes->resize(old_size + sizeof(le_val));
52 memcpy(bytes->data() + old_size, &le_val, sizeof(le_val));
Yurii Zubrytskyi516c4412020-02-19 14:46:16 -080053}
54
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080055static inline void append_bytes_with_size(borrowed_fd fd, std::vector<char>* bytes) {
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070056 int32_t le_size = read_int32(fd);
57 int32_t size = int32_t(le32toh(le_size));
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080058 auto old_size = bytes->size();
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070059 bytes->resize(old_size + sizeof(le_size) + size);
60 memcpy(bytes->data() + old_size, &le_size, sizeof(le_size));
61 ReadFully(fd, bytes->data() + old_size + sizeof(le_size), size);
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080062}
63
64static inline std::pair<std::vector<char>, int32_t> read_id_sig_headers(borrowed_fd fd) {
65 std::vector<char> result;
Yurii Zubrytskyi516c4412020-02-19 14:46:16 -080066 append_int(fd, &result); // version
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070067 append_bytes_with_size(fd, &result); // hashingInfo
68 append_bytes_with_size(fd, &result); // signingInfo
69 auto le_tree_size = read_int32(fd);
70 auto tree_size = int32_t(le32toh(le_tree_size)); // size of the verity tree
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080071 return {std::move(result), tree_size};
72}
73
74static inline Size verity_tree_size_for_file(Size fileSize) {
75 constexpr int INCFS_DATA_FILE_BLOCK_SIZE = 4096;
76 constexpr int SHA256_DIGEST_SIZE = 32;
77 constexpr int digest_size = SHA256_DIGEST_SIZE;
78 constexpr int hash_per_block = INCFS_DATA_FILE_BLOCK_SIZE / digest_size;
79
80 Size total_tree_block_count = 0;
81
82 auto block_count = 1 + (fileSize - 1) / INCFS_DATA_FILE_BLOCK_SIZE;
83 auto hash_block_count = block_count;
84 for (auto i = 0; hash_block_count > 1; i++) {
85 hash_block_count = (hash_block_count + hash_per_block - 1) / hash_per_block;
86 total_tree_block_count += hash_block_count;
87 }
88 return total_tree_block_count * INCFS_DATA_FILE_BLOCK_SIZE;
89}
90
91// Base64-encode signature bytes. Keeping fd at the position of start of verity tree.
92static std::pair<unique_fd, std::string> read_and_encode_signature(Size file_size,
93 std::string signature_file) {
94 signature_file += IDSIG;
95
96 struct stat st;
97 if (stat(signature_file.c_str(), &st)) {
98 fprintf(stderr, "Failed to stat signature file %s. Abort.\n", signature_file.c_str());
99 return {};
100 }
101
102 unique_fd fd(adb_open(signature_file.c_str(), O_RDONLY | O_CLOEXEC));
103 if (fd < 0) {
104 fprintf(stderr, "Failed to open signature file: %s. Abort.\n", signature_file.c_str());
105 return {};
106 }
107
108 auto [signature, tree_size] = read_id_sig_headers(fd);
109 if (auto expected = verity_tree_size_for_file(file_size); tree_size != expected) {
110 fprintf(stderr,
111 "Verity tree size mismatch in signature file: %s [was %lld, expected %lld].\n",
112 signature_file.c_str(), (long long)tree_size, (long long)expected);
113 return {};
114 }
115
116 size_t base64_len = 0;
117 if (!EVP_EncodedLength(&base64_len, signature.size())) {
118 fprintf(stderr, "Fail to estimate base64 encoded length. Abort.\n");
119 return {};
120 }
121 std::string encoded_signature;
122 encoded_signature.resize(base64_len);
123 encoded_signature.resize(EVP_EncodeBlock((uint8_t*)encoded_signature.data(),
124 (const uint8_t*)signature.data(), signature.size()));
125
126 return {std::move(fd), std::move(encoded_signature)};
127}
128
129// Send install-incremental to the device along with properly configured file descriptors in
130// streaming format. Once connection established, send all fs-verity tree bytes.
131static unique_fd start_install(const std::vector<std::string>& files) {
132 std::vector<std::string> command_args{"package", "install-incremental"};
133
134 // fd's with positions at the beginning of fs-verity
135 std::vector<unique_fd> signature_fds;
136 signature_fds.reserve(files.size());
137 for (int i = 0, size = files.size(); i < size; ++i) {
138 const auto& file = files[i];
139
140 struct stat st;
141 if (stat(file.c_str(), &st)) {
142 fprintf(stderr, "Failed to stat input file %s. Abort.\n", file.c_str());
143 return {};
144 }
145
146 auto [signature_fd, signature] = read_and_encode_signature(st.st_size, file);
147 if (!signature_fd.ok()) {
148 return {};
149 }
150
151 auto file_desc =
152 StringPrintf("%s:%lld:%s:%s", android::base::Basename(file).c_str(),
153 (long long)st.st_size, std::to_string(i).c_str(), signature.c_str());
154 command_args.push_back(std::move(file_desc));
155
156 signature_fds.push_back(std::move(signature_fd));
157 }
158
159 std::string error;
160 auto connection_fd = unique_fd(send_abb_exec_command(command_args, &error));
161 if (connection_fd < 0) {
162 fprintf(stderr, "Failed to run: %s, error: %s\n",
163 android::base::Join(command_args, " ").c_str(), error.c_str());
164 return {};
165 }
166
167 // Pushing verity trees for all installation files.
168 for (auto&& local_fd : signature_fds) {
169 if (!copy_to_file(local_fd.get(), connection_fd.get())) {
170 fprintf(stderr, "Failed to stream tree bytes: %s. Abort.\n", strerror(errno));
171 return {};
172 }
173 }
174
175 return connection_fd;
176}
177
178} // namespace
179
180std::optional<Process> install(std::vector<std::string> files) {
181 auto connection_fd = start_install(files);
182 if (connection_fd < 0) {
183 fprintf(stderr, "adb: failed to initiate installation on device.\n");
184 return {};
185 }
186
187 std::string adb_path = android::base::GetExecutablePath();
188
189 auto osh = adb_get_os_handle(connection_fd.get());
190#ifdef _WIN32
191 auto fd_param = std::to_string(reinterpret_cast<intptr_t>(osh));
192#else /* !_WIN32 a.k.a. Unix */
193 auto fd_param = std::to_string(osh);
194#endif
195
Songchun Fan23bd5522020-03-09 11:33:44 -0700196 // pipe for child process to write output
197 int print_fds[2];
198 if (adb_socketpair(print_fds) != 0) {
199 fprintf(stderr, "Failed to create socket pair for child to print to parent\n");
200 return {};
201 }
202 auto [pipe_read_fd, pipe_write_fd] = print_fds;
203 auto pipe_write_fd_param = std::to_string(pipe_write_fd);
204 close_on_exec(pipe_read_fd);
205
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800206 std::vector<std::string> args(std::move(files));
Songchun Fan23bd5522020-03-09 11:33:44 -0700207 args.insert(args.begin(), {"inc-server", fd_param, pipe_write_fd_param});
208 auto child =
209 adb_launch_process(adb_path, std::move(args), {connection_fd.get(), pipe_write_fd});
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800210 if (!child) {
211 fprintf(stderr, "adb: failed to fork: %s\n", strerror(errno));
212 return {};
213 }
214
Songchun Fan23bd5522020-03-09 11:33:44 -0700215 adb_close(pipe_write_fd);
216
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800217 auto killOnExit = [](Process* p) { p->kill(); };
218 std::unique_ptr<Process, decltype(killOnExit)> serverKiller(&child, killOnExit);
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800219
Songchun Fan23bd5522020-03-09 11:33:44 -0700220 Result result = wait_for_installation(pipe_read_fd);
221 adb_close(pipe_read_fd);
222
223 if (result == Result::Success) {
224 // adb client exits now but inc-server can continue
225 serverKiller.release();
226 }
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800227 return child;
228}
229
Songchun Fan23bd5522020-03-09 11:33:44 -0700230Result wait_for_installation(int read_fd) {
231 static constexpr int maxMessageSize = 256;
232 std::vector<char> child_stdout(CHUNK_SIZE);
233 int bytes_read;
234 int buf_size = 0;
235 // TODO(b/150865433): optimize child's output parsing
236 while ((bytes_read = adb_read(read_fd, child_stdout.data() + buf_size,
237 child_stdout.size() - buf_size)) > 0) {
238 // print to parent's stdout
239 fprintf(stdout, "%.*s", bytes_read, child_stdout.data() + buf_size);
240
241 buf_size += bytes_read;
242 const std::string_view stdout_str(child_stdout.data(), buf_size);
243 // wait till installation either succeeds or fails
244 if (stdout_str.find("Success") != std::string::npos) {
245 return Result::Success;
246 }
247 // on failure, wait for full message
248 static constexpr auto failure_msg_head = "Failure ["sv;
249 if (const auto begin_itr = stdout_str.find(failure_msg_head);
250 begin_itr != std::string::npos) {
251 if (buf_size >= maxMessageSize) {
252 return Result::Failure;
253 }
254 const auto end_itr = stdout_str.rfind("]");
255 if (end_itr != std::string::npos && end_itr >= begin_itr + failure_msg_head.size()) {
256 return Result::Failure;
257 }
258 }
259 child_stdout.resize(buf_size + CHUNK_SIZE);
260 }
261 return Result::None;
262}
263
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800264} // namespace incremental