blob: c5fc12f0ac7e6ab86f9c464cda3ddc0fd84976c2 [file] [log] [blame]
Idries Hamadied409ea2018-01-29 16:30:36 +00001/*
2 * Copyright (C) 2018 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
Idries Hamadi269a4b42018-09-13 18:00:25 +010017#include "fastdeploy.h"
18
Henry Daitxee01c802018-12-12 10:40:57 +000019#include <string.h>
Idries Hamadied409ea2018-01-29 16:30:36 +000020#include <algorithm>
Idries Hamadi5b6bf942018-08-28 12:58:09 +010021#include <array>
Idries Hamadi269a4b42018-09-13 18:00:25 +010022#include <memory>
Idries Hamadied409ea2018-01-29 16:30:36 +000023
Idries Hamadi5b6bf942018-08-28 12:58:09 +010024#include "android-base/file.h"
25#include "android-base/strings.h"
Idries Hamadi269a4b42018-09-13 18:00:25 +010026#include "androidfw/ResourceTypes.h"
27#include "androidfw/ZipFileRO.h"
Idries Hamadied409ea2018-01-29 16:30:36 +000028#include "client/file_sync_client.h"
29#include "commandline.h"
Joshua Gilpatrickaf3ce082019-07-19 09:42:12 -070030#include "deployagent.inc" // Generated include via build rule.
31#include "deployagentscript.inc" // Generated include via build rule.
32#include "fastdeploy/deploypatchgenerator/deploy_patch_generator.h"
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070033#include "fastdeploy/deploypatchgenerator/patch_utils.h"
34#include "fastdeploy/proto/ApkEntry.pb.h"
Idries Hamadied409ea2018-01-29 16:30:36 +000035#include "fastdeploycallbacks.h"
Elliott Hughes4679a392018-10-19 13:59:44 -070036#include "sysdeps.h"
Elliott Hughesd2aaede2018-10-22 17:02:51 -070037
38#include "adb_utils.h"
Idries Hamadied409ea2018-01-29 16:30:36 +000039
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070040static constexpr long kRequiredAgentVersion = 0x00000003;
Idries Hamadied409ea2018-01-29 16:30:36 +000041
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070042static constexpr int kPackageMissing = 3;
43static constexpr int kInvalidAgentVersion = 4;
44
Joshua Gilpatrickaf3ce082019-07-19 09:42:12 -070045static constexpr const char* kDeviceAgentFile = "/data/local/tmp/deployagent.jar";
46static constexpr const char* kDeviceAgentScript = "/data/local/tmp/deployagent";
Idries Hamadied409ea2018-01-29 16:30:36 +000047
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070048static constexpr bool g_verbose_timings = false;
49static FastDeploy_AgentUpdateStrategy g_agent_update_strategy =
50 FastDeploy_AgentUpdateDifferentVersion;
Idries Hamadi5b6bf942018-08-28 12:58:09 +010051
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070052using APKMetaData = com::android::fastdeploy::APKMetaData;
Idries Hamadied409ea2018-01-29 16:30:36 +000053
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070054namespace {
Idries Hamadied409ea2018-01-29 16:30:36 +000055
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070056struct TimeReporter {
57 TimeReporter(const char* label) : label_(label) {}
58 ~TimeReporter() {
59 if (g_verbose_timings) {
60 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
61 std::chrono::steady_clock::now() - start_);
62 fprintf(stderr, "%s finished in %lldms\n", label_,
63 static_cast<long long>(duration.count()));
64 }
Idries Hamadied409ea2018-01-29 16:30:36 +000065 }
66
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -070067 private:
68 const char* label_;
69 std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now();
70};
71#define REPORT_FUNC_TIME() TimeReporter reporter(__func__)
72
73struct FileDeleter {
74 FileDeleter(const char* path) : path_(path) {}
75 ~FileDeleter() { adb_unlink(path_); }
76
77 private:
78 const char* const path_;
79};
80
81} // namespace
Idries Hamadied409ea2018-01-29 16:30:36 +000082
83int get_device_api_level() {
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080084 static const int api_level = [] {
85 REPORT_FUNC_TIME();
86 std::vector<char> sdk_version_output_buffer;
87 std::vector<char> sdk_version_error_buffer;
88 int api_level = -1;
Idries Hamadied409ea2018-01-29 16:30:36 +000089
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080090 int status_code =
91 capture_shell_command("getprop ro.build.version.sdk", &sdk_version_output_buffer,
92 &sdk_version_error_buffer);
93 if (status_code == 0 && sdk_version_output_buffer.size() > 0) {
94 api_level = strtol((char*)sdk_version_output_buffer.data(), nullptr, 10);
95 }
Idries Hamadied409ea2018-01-29 16:30:36 +000096
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -080097 return api_level;
98 }();
Idries Hamadied409ea2018-01-29 16:30:36 +000099 return api_level;
100}
101
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700102void fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy) {
103 g_agent_update_strategy = agent_update_strategy;
Idries Hamadi5b6bf942018-08-28 12:58:09 +0100104}
105
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700106static void push_to_device(const void* data, size_t byte_count, const char* dst, bool sync) {
Idries Hamadied409ea2018-01-29 16:30:36 +0000107 std::vector<const char*> srcs;
Elliott Hughes74f0fc62019-11-07 15:38:00 -0800108 TemporaryFile tf;
109 android::base::WriteFully(tf.fd, data, byte_count);
110 srcs.push_back(tf.path);
111 // On Windows, the file needs to be flushed before pushing to device,
112 // but can't be removed until after the push.
113 unix_close(tf.release());
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700114
115 if (!do_sync_push(srcs, dst, sync)) {
Joshua Gilpatrickaf3ce082019-07-19 09:42:12 -0700116 error_exit("Failed to push fastdeploy agent to device.");
117 }
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700118}
119
120static bool deploy_agent(bool check_time_stamps) {
121 REPORT_FUNC_TIME();
122
123 push_to_device(kDeployAgent, sizeof(kDeployAgent), kDeviceAgentFile, check_time_stamps);
124 push_to_device(kDeployAgentScript, sizeof(kDeployAgentScript), kDeviceAgentScript,
125 check_time_stamps);
126
Joshua Gilpatrickaf3ce082019-07-19 09:42:12 -0700127 // on windows the shell script might have lost execute permission
128 // so need to set this explicitly
129 const char* kChmodCommandPattern = "chmod 777 %s";
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700130 std::string chmod_command =
Joshua Gilpatrickaf3ce082019-07-19 09:42:12 -0700131 android::base::StringPrintf(kChmodCommandPattern, kDeviceAgentScript);
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700132 int ret = send_shell_command(chmod_command);
Joshua Gilpatrickaf3ce082019-07-19 09:42:12 -0700133 if (ret != 0) {
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700134 error_exit("Error executing %s returncode: %d", chmod_command.c_str(), ret);
Idries Hamadied409ea2018-01-29 16:30:36 +0000135 }
Idries Hamadi4af6ee42018-09-06 18:42:39 +0100136
137 return true;
Idries Hamadied409ea2018-01-29 16:30:36 +0000138}
139
Idries Hamadi269a4b42018-09-13 18:00:25 +0100140static std::string get_string_from_utf16(const char16_t* input, int input_len) {
141 ssize_t utf8_length = utf16_to_utf8_length(input, input_len);
142 if (utf8_length <= 0) {
143 return {};
Idries Hamadied409ea2018-01-29 16:30:36 +0000144 }
Idries Hamadi269a4b42018-09-13 18:00:25 +0100145 std::string utf8;
146 utf8.resize(utf8_length);
147 utf16_to_utf8(input, input_len, &*utf8.begin(), utf8_length + 1);
148 return utf8;
Idries Hamadi5b6bf942018-08-28 12:58:09 +0100149}
150
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700151static std::string get_package_name_from_apk(const char* apk_path) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700152#undef open
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700153 std::unique_ptr<android::ZipFileRO> zip_file((android::ZipFileRO::open)(apk_path));
Elliott Hughes4679a392018-10-19 13:59:44 -0700154#define open ___xxx_unix_open
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700155 if (zip_file == nullptr) {
156 perror_exit("Could not open %s", apk_path);
Idries Hamadied409ea2018-01-29 16:30:36 +0000157 }
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700158 android::ZipEntryRO entry = zip_file->findEntryByName("AndroidManifest.xml");
Idries Hamadi269a4b42018-09-13 18:00:25 +0100159 if (entry == nullptr) {
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700160 error_exit("Could not find AndroidManifest.xml inside %s", apk_path);
Idries Hamadi269a4b42018-09-13 18:00:25 +0100161 }
162 uint32_t manifest_len = 0;
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700163 if (!zip_file->getEntryInfo(entry, NULL, &manifest_len, NULL, NULL, NULL, NULL)) {
164 error_exit("Could not read AndroidManifest.xml inside %s", apk_path);
Idries Hamadi269a4b42018-09-13 18:00:25 +0100165 }
166 std::vector<char> manifest_data(manifest_len);
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700167 if (!zip_file->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
168 error_exit("Could not uncompress AndroidManifest.xml inside %s", apk_path);
Idries Hamadi269a4b42018-09-13 18:00:25 +0100169 }
170 android::ResXMLTree tree;
171 android::status_t setto_status = tree.setTo(manifest_data.data(), manifest_len, true);
172 if (setto_status != android::OK) {
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700173 error_exit("Could not parse AndroidManifest.xml inside %s", apk_path);
Idries Hamadi269a4b42018-09-13 18:00:25 +0100174 }
175 android::ResXMLParser::event_code_t code;
176 while ((code = tree.next()) != android::ResXMLParser::BAD_DOCUMENT &&
177 code != android::ResXMLParser::END_DOCUMENT) {
178 switch (code) {
179 case android::ResXMLParser::START_TAG: {
180 size_t element_name_length;
181 const char16_t* element_name = tree.getElementName(&element_name_length);
182 if (element_name == nullptr) {
183 continue;
184 }
185 std::u16string element_name_string(element_name, element_name_length);
186 if (element_name_string == u"manifest") {
187 for (size_t i = 0; i < tree.getAttributeCount(); i++) {
188 size_t attribute_name_length;
189 const char16_t* attribute_name_text =
190 tree.getAttributeName(i, &attribute_name_length);
191 if (attribute_name_text == nullptr) {
192 continue;
193 }
194 std::u16string attribute_name_string(attribute_name_text,
195 attribute_name_length);
196 if (attribute_name_string == u"package") {
197 size_t attribute_value_length;
198 const char16_t* attribute_value_text =
199 tree.getAttributeStringValue(i, &attribute_value_length);
200 if (attribute_value_text == nullptr) {
201 continue;
202 }
203 return get_string_from_utf16(attribute_value_text,
204 attribute_value_length);
205 }
206 }
207 }
208 break;
209 }
210 default:
211 break;
212 }
213 }
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700214 error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apk_path);
Idries Hamadied409ea2018-01-29 16:30:36 +0000215}
216
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700217static long parse_agent_version(const std::vector<char>& version_buffer) {
218 long version = -1;
219 if (!version_buffer.empty()) {
220 version = strtol((char*)version_buffer.data(), NULL, 16);
221 }
222 return version;
223}
Idries Hamadied409ea2018-01-29 16:30:36 +0000224
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700225static void update_agent_if_necessary() {
226 switch (g_agent_update_strategy) {
227 case FastDeploy_AgentUpdateAlways:
228 deploy_agent(/*check_time_stamps=*/false);
229 break;
230 case FastDeploy_AgentUpdateNewerTimeStamp:
231 deploy_agent(/*check_time_stamps=*/true);
232 break;
233 default:
234 break;
235 }
236}
237
238std::optional<APKMetaData> extract_metadata(const char* apk_path) {
239 // Update agent if there is a command line argument forcing to do so.
240 update_agent_if_necessary();
241
242 REPORT_FUNC_TIME();
243
244 std::string package_name = get_package_name_from_apk(apk_path);
245
246 // Dump apk command checks the required vs current agent version and if they match then returns
247 // the APK dump for package. Doing this in a single call saves round-trip and agent launch time.
248 constexpr const char* kAgentDumpCommandPattern = "/data/local/tmp/deployagent dump %ld %s";
249 std::string dump_command = android::base::StringPrintf(
250 kAgentDumpCommandPattern, kRequiredAgentVersion, package_name.c_str());
251
252 std::vector<char> dump_out_buffer;
253 std::vector<char> dump_error_buffer;
254 int returnCode =
255 capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
256 if (returnCode >= kInvalidAgentVersion) {
257 // Agent has wrong version or missing.
258 long agent_version = parse_agent_version(dump_out_buffer);
259 if (agent_version < 0) {
260 printf("Could not detect agent on device, deploying\n");
261 } else {
262 printf("Device agent version is (%ld), (%ld) is required, re-deploying\n",
263 agent_version, kRequiredAgentVersion);
264 }
265 deploy_agent(/*check_time_stamps=*/false);
266
267 // Retry with new agent.
268 dump_out_buffer.clear();
269 dump_error_buffer.clear();
270 returnCode =
271 capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
272 }
Idries Hamadi269a4b42018-09-13 18:00:25 +0100273 if (returnCode != 0) {
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700274 if (returnCode == kInvalidAgentVersion) {
275 long agent_version = parse_agent_version(dump_out_buffer);
276 error_exit(
277 "After update agent version remains incorrect! Expected %ld but version is %ld",
278 kRequiredAgentVersion, agent_version);
279 }
280 if (returnCode == kPackageMissing) {
281 fprintf(stderr, "Package %s not found, falling back to install\n",
282 package_name.c_str());
283 return {};
284 }
285 fprintf(stderr, "Executing %s returned %d\n", dump_command.c_str(), returnCode);
286 fprintf(stderr, "%*s\n", int(dump_error_buffer.size()), dump_error_buffer.data());
Henry Daitxf21edf32018-11-30 18:02:43 +0000287 error_exit("Aborting");
Idries Hamadied409ea2018-01-29 16:30:36 +0000288 }
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700289
290 com::android::fastdeploy::APKDump dump;
291 if (!dump.ParseFromArray(dump_out_buffer.data(), dump_out_buffer.size())) {
292 fprintf(stderr, "Can't parse output of %s\n", dump_command.c_str());
293 error_exit("Aborting");
294 }
295
296 return PatchUtils::GetDeviceAPKMetaData(dump);
Idries Hamadied409ea2018-01-29 16:30:36 +0000297}
298
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700299unique_fd install_patch(int argc, const char** argv) {
300 REPORT_FUNC_TIME();
301 constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -pm %s";
Idries Hamadied409ea2018-01-29 16:30:36 +0000302
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700303 std::vector<unsigned char> apply_output_buffer;
304 std::vector<unsigned char> apply_error_buffer;
Idries Hamadied409ea2018-01-29 16:30:36 +0000305 std::string argsString;
306
Henry Daitxee01c802018-12-12 10:40:57 +0000307 bool rSwitchPresent = false;
Idries Hamadied409ea2018-01-29 16:30:36 +0000308 for (int i = 0; i < argc; i++) {
309 argsString.append(argv[i]);
310 argsString.append(" ");
Henry Daitxee01c802018-12-12 10:40:57 +0000311 if (!strcmp(argv[i], "-r")) {
312 rSwitchPresent = true;
313 }
314 }
315 if (!rSwitchPresent) {
316 argsString.append("-r");
Idries Hamadied409ea2018-01-29 16:30:36 +0000317 }
318
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700319 std::string error;
320 std::string apply_patch_service_string =
321 android::base::StringPrintf(kAgentApplyServicePattern, argsString.c_str());
322 unique_fd fd{adb_connect(apply_patch_service_string, &error)};
323 if (fd < 0) {
324 error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
325 }
326 return fd;
327}
328
329unique_fd apply_patch_on_device(const char* output_path) {
330 REPORT_FUNC_TIME();
331 constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -o %s";
332
333 std::string error;
334 std::string apply_patch_service_string =
335 android::base::StringPrintf(kAgentApplyServicePattern, output_path);
336 unique_fd fd{adb_connect(apply_patch_service_string, &error)};
337 if (fd < 0) {
338 error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
339 }
340 return fd;
341}
342
343static void create_patch(const char* apk_path, APKMetaData metadata, borrowed_fd patch_fd) {
344 REPORT_FUNC_TIME();
345 DeployPatchGenerator generator(/*is_verbose=*/false);
346 bool success = generator.CreatePatch(apk_path, std::move(metadata), patch_fd);
347 if (!success) {
348 error_exit("Failed to create patch for %s", apk_path);
Idries Hamadi269a4b42018-09-13 18:00:25 +0100349 }
Idries Hamadied409ea2018-01-29 16:30:36 +0000350}
Henry Daitxee01c802018-12-12 10:40:57 +0000351
Alex Buynytskyy665f3ff2019-09-16 12:10:54 -0700352int stream_patch(const char* apk_path, APKMetaData metadata, unique_fd patch_fd) {
353 create_patch(apk_path, std::move(metadata), patch_fd);
354
355 REPORT_FUNC_TIME();
356 return read_and_dump(patch_fd.get());
Henry Daitxee01c802018-12-12 10:40:57 +0000357}