blob: 33a1a37ba153ce89d9a9f5f0eae581a519b5da1c [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;
Yurii Zubrytskyi2488c212020-03-18 15:49:45 -070044 return ReadFdExactly(fd, &result, sizeof(result)) ? result : -1;
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080045}
46
Yurii Zubrytskyi516c4412020-02-19 14:46:16 -080047static inline void append_int(borrowed_fd fd, std::vector<char>* bytes) {
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070048 int32_t le_val = read_int32(fd);
Yurii Zubrytskyi516c4412020-02-19 14:46:16 -080049 auto old_size = bytes->size();
Alex Buynytskyyeebf9f72020-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 Zubrytskyi516c4412020-02-19 14:46:16 -080052}
53
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080054static inline void append_bytes_with_size(borrowed_fd fd, std::vector<char>* bytes) {
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070055 int32_t le_size = read_int32(fd);
Yurii Zubrytskyi2488c212020-03-18 15:49:45 -070056 if (le_size < 0) {
57 return;
58 }
Alex Buynytskyyeebf9f72020-03-13 08:39:31 -070059 int32_t size = int32_t(le32toh(le_size));
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080060 auto old_size = bytes->size();
Alex Buynytskyyeebf9f72020-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 Zubrytskyi2488c212020-03-18 15:49:45 -070063 ReadFdExactly(fd, bytes->data() + old_size + sizeof(le_size), size);
Alex Buynytskyy96ff54b2020-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 Zubrytskyi516c4412020-02-19 14:46:16 -080068 append_int(fd, &result); // version
Alex Buynytskyyeebf9f72020-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 Buynytskyy96ff54b2020-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
93// Base64-encode signature bytes. Keeping fd at the position of start of verity tree.
94static std::pair<unique_fd, std::string> read_and_encode_signature(Size file_size,
95 std::string signature_file) {
96 signature_file += IDSIG;
97
98 struct stat st;
99 if (stat(signature_file.c_str(), &st)) {
100 fprintf(stderr, "Failed to stat signature file %s. Abort.\n", signature_file.c_str());
101 return {};
102 }
103
104 unique_fd fd(adb_open(signature_file.c_str(), O_RDONLY | O_CLOEXEC));
105 if (fd < 0) {
106 fprintf(stderr, "Failed to open signature file: %s. Abort.\n", signature_file.c_str());
107 return {};
108 }
109
110 auto [signature, tree_size] = read_id_sig_headers(fd);
111 if (auto expected = verity_tree_size_for_file(file_size); tree_size != expected) {
112 fprintf(stderr,
113 "Verity tree size mismatch in signature file: %s [was %lld, expected %lld].\n",
114 signature_file.c_str(), (long long)tree_size, (long long)expected);
115 return {};
116 }
117
118 size_t base64_len = 0;
119 if (!EVP_EncodedLength(&base64_len, signature.size())) {
120 fprintf(stderr, "Fail to estimate base64 encoded length. Abort.\n");
121 return {};
122 }
123 std::string encoded_signature;
124 encoded_signature.resize(base64_len);
125 encoded_signature.resize(EVP_EncodeBlock((uint8_t*)encoded_signature.data(),
126 (const uint8_t*)signature.data(), signature.size()));
127
128 return {std::move(fd), std::move(encoded_signature)};
129}
130
131// Send install-incremental to the device along with properly configured file descriptors in
132// streaming format. Once connection established, send all fs-verity tree bytes.
133static unique_fd start_install(const std::vector<std::string>& files) {
134 std::vector<std::string> command_args{"package", "install-incremental"};
135
136 // fd's with positions at the beginning of fs-verity
137 std::vector<unique_fd> signature_fds;
138 signature_fds.reserve(files.size());
139 for (int i = 0, size = files.size(); i < size; ++i) {
140 const auto& file = files[i];
141
142 struct stat st;
143 if (stat(file.c_str(), &st)) {
144 fprintf(stderr, "Failed to stat input file %s. Abort.\n", file.c_str());
145 return {};
146 }
147
148 auto [signature_fd, signature] = read_and_encode_signature(st.st_size, file);
149 if (!signature_fd.ok()) {
150 return {};
151 }
152
153 auto file_desc =
154 StringPrintf("%s:%lld:%s:%s", android::base::Basename(file).c_str(),
155 (long long)st.st_size, std::to_string(i).c_str(), signature.c_str());
156 command_args.push_back(std::move(file_desc));
157
158 signature_fds.push_back(std::move(signature_fd));
159 }
160
161 std::string error;
162 auto connection_fd = unique_fd(send_abb_exec_command(command_args, &error));
163 if (connection_fd < 0) {
164 fprintf(stderr, "Failed to run: %s, error: %s\n",
165 android::base::Join(command_args, " ").c_str(), error.c_str());
166 return {};
167 }
168
169 // Pushing verity trees for all installation files.
170 for (auto&& local_fd : signature_fds) {
171 if (!copy_to_file(local_fd.get(), connection_fd.get())) {
172 fprintf(stderr, "Failed to stream tree bytes: %s. Abort.\n", strerror(errno));
173 return {};
174 }
175 }
176
177 return connection_fd;
178}
179
180} // namespace
181
182std::optional<Process> install(std::vector<std::string> files) {
183 auto connection_fd = start_install(files);
184 if (connection_fd < 0) {
185 fprintf(stderr, "adb: failed to initiate installation on device.\n");
186 return {};
187 }
188
189 std::string adb_path = android::base::GetExecutablePath();
190
Yurii Zubrytskyie3e64b82020-03-26 18:16:36 -0700191 auto osh = cast_handle_to_int(adb_get_os_handle(connection_fd.get()));
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800192 auto fd_param = std::to_string(osh);
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800193
Songchun Fan23bd5522020-03-09 11:33:44 -0700194 // pipe for child process to write output
195 int print_fds[2];
196 if (adb_socketpair(print_fds) != 0) {
197 fprintf(stderr, "Failed to create socket pair for child to print to parent\n");
198 return {};
199 }
200 auto [pipe_read_fd, pipe_write_fd] = print_fds;
Yurii Zubrytskyie3e64b82020-03-26 18:16:36 -0700201 auto pipe_write_fd_param = std::to_string(cast_handle_to_int(adb_get_os_handle(pipe_write_fd)));
Songchun Fan23bd5522020-03-09 11:33:44 -0700202 close_on_exec(pipe_read_fd);
203
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800204 std::vector<std::string> args(std::move(files));
Songchun Fan23bd5522020-03-09 11:33:44 -0700205 args.insert(args.begin(), {"inc-server", fd_param, pipe_write_fd_param});
206 auto child =
207 adb_launch_process(adb_path, std::move(args), {connection_fd.get(), pipe_write_fd});
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800208 if (!child) {
209 fprintf(stderr, "adb: failed to fork: %s\n", strerror(errno));
210 return {};
211 }
212
Songchun Fan23bd5522020-03-09 11:33:44 -0700213 adb_close(pipe_write_fd);
214
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800215 auto killOnExit = [](Process* p) { p->kill(); };
216 std::unique_ptr<Process, decltype(killOnExit)> serverKiller(&child, killOnExit);
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800217
Songchun Fan23bd5522020-03-09 11:33:44 -0700218 Result result = wait_for_installation(pipe_read_fd);
219 adb_close(pipe_read_fd);
220
221 if (result == Result::Success) {
222 // adb client exits now but inc-server can continue
223 serverKiller.release();
224 }
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800225 return child;
226}
227
Songchun Fan23bd5522020-03-09 11:33:44 -0700228Result wait_for_installation(int read_fd) {
229 static constexpr int maxMessageSize = 256;
230 std::vector<char> child_stdout(CHUNK_SIZE);
231 int bytes_read;
232 int buf_size = 0;
233 // TODO(b/150865433): optimize child's output parsing
234 while ((bytes_read = adb_read(read_fd, child_stdout.data() + buf_size,
235 child_stdout.size() - buf_size)) > 0) {
236 // print to parent's stdout
237 fprintf(stdout, "%.*s", bytes_read, child_stdout.data() + buf_size);
238
239 buf_size += bytes_read;
240 const std::string_view stdout_str(child_stdout.data(), buf_size);
241 // wait till installation either succeeds or fails
242 if (stdout_str.find("Success") != std::string::npos) {
243 return Result::Success;
244 }
245 // on failure, wait for full message
246 static constexpr auto failure_msg_head = "Failure ["sv;
247 if (const auto begin_itr = stdout_str.find(failure_msg_head);
248 begin_itr != std::string::npos) {
249 if (buf_size >= maxMessageSize) {
250 return Result::Failure;
251 }
252 const auto end_itr = stdout_str.rfind("]");
253 if (end_itr != std::string::npos && end_itr >= begin_itr + failure_msg_head.size()) {
254 return Result::Failure;
255 }
256 }
257 child_stdout.resize(buf_size + CHUNK_SIZE);
258 }
259 return Result::None;
260}
261
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -0800262} // namespace incremental