blob: ee042a1744bc064370f0a18cad861dcc48f09b26 [file] [log] [blame]
Idries Hamadi1ecee442018-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 Hamadi78330f02018-09-13 18:00:25 +010017#include "fastdeploy.h"
18
Henry Daitxe4cc4d92018-12-12 10:40:57 +000019#include <string.h>
Idries Hamadi1ecee442018-01-29 16:30:36 +000020#include <algorithm>
Idries Hamadi7919be22018-08-28 12:58:09 +010021#include <array>
Idries Hamadi78330f02018-09-13 18:00:25 +010022#include <memory>
Idries Hamadi1ecee442018-01-29 16:30:36 +000023
Idries Hamadi7919be22018-08-28 12:58:09 +010024#include "android-base/file.h"
25#include "android-base/strings.h"
Idries Hamadi78330f02018-09-13 18:00:25 +010026#include "androidfw/ResourceTypes.h"
27#include "androidfw/ZipFileRO.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000028#include "client/file_sync_client.h"
29#include "commandline.h"
Joshua Gilpatrick0d384112019-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 Buynytskyy1af550e2019-09-16 12:10:54 -070033#include "fastdeploy/deploypatchgenerator/patch_utils.h"
34#include "fastdeploy/proto/ApkEntry.pb.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000035#include "fastdeploycallbacks.h"
Elliott Hughese64126b2018-10-19 13:59:44 -070036#include "sysdeps.h"
Elliott Hughes0119a912018-10-22 17:02:51 -070037
Elliott Hughese76e5ef2024-06-25 21:43:49 +000038#include "adb_client.h"
Elliott Hughes0119a912018-10-22 17:02:51 -070039#include "adb_utils.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000040
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070041static constexpr long kRequiredAgentVersion = 0x00000003;
Idries Hamadi1ecee442018-01-29 16:30:36 +000042
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070043static constexpr int kPackageMissing = 3;
44static constexpr int kInvalidAgentVersion = 4;
45
Joshua Gilpatrick0d384112019-07-19 09:42:12 -070046static constexpr const char* kDeviceAgentFile = "/data/local/tmp/deployagent.jar";
47static constexpr const char* kDeviceAgentScript = "/data/local/tmp/deployagent";
Idries Hamadi1ecee442018-01-29 16:30:36 +000048
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070049static constexpr bool g_verbose_timings = false;
50static FastDeploy_AgentUpdateStrategy g_agent_update_strategy =
51 FastDeploy_AgentUpdateDifferentVersion;
Idries Hamadi7919be22018-08-28 12:58:09 +010052
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070053using APKMetaData = com::android::fastdeploy::APKMetaData;
Idries Hamadi1ecee442018-01-29 16:30:36 +000054
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070055namespace {
Idries Hamadi1ecee442018-01-29 16:30:36 +000056
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070057struct TimeReporter {
58 TimeReporter(const char* label) : label_(label) {}
59 ~TimeReporter() {
60 if (g_verbose_timings) {
61 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
62 std::chrono::steady_clock::now() - start_);
63 fprintf(stderr, "%s finished in %lldms\n", label_,
64 static_cast<long long>(duration.count()));
65 }
Idries Hamadi1ecee442018-01-29 16:30:36 +000066 }
67
Alex Buynytskyy1af550e2019-09-16 12:10:54 -070068 private:
69 const char* label_;
70 std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now();
71};
72#define REPORT_FUNC_TIME() TimeReporter reporter(__func__)
73
74struct FileDeleter {
75 FileDeleter(const char* path) : path_(path) {}
76 ~FileDeleter() { adb_unlink(path_); }
77
78 private:
79 const char* const path_;
80};
81
82} // namespace
Idries Hamadi1ecee442018-01-29 16:30:36 +000083
84int get_device_api_level() {
Alex Buynytskyy175ce292020-02-13 06:52:04 -080085 static const int api_level = [] {
86 REPORT_FUNC_TIME();
87 std::vector<char> sdk_version_output_buffer;
88 std::vector<char> sdk_version_error_buffer;
89 int api_level = -1;
Idries Hamadi1ecee442018-01-29 16:30:36 +000090
Alex Buynytskyy175ce292020-02-13 06:52:04 -080091 int status_code =
92 capture_shell_command("getprop ro.build.version.sdk", &sdk_version_output_buffer,
93 &sdk_version_error_buffer);
94 if (status_code == 0 && sdk_version_output_buffer.size() > 0) {
95 api_level = strtol((char*)sdk_version_output_buffer.data(), nullptr, 10);
96 }
Idries Hamadi1ecee442018-01-29 16:30:36 +000097
Alex Buynytskyy175ce292020-02-13 06:52:04 -080098 return api_level;
99 }();
Idries Hamadi1ecee442018-01-29 16:30:36 +0000100 return api_level;
101}
102
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700103void fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy) {
104 g_agent_update_strategy = agent_update_strategy;
Idries Hamadi7919be22018-08-28 12:58:09 +0100105}
106
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700107static void push_to_device(const void* data, size_t byte_count, const char* dst, bool sync) {
Idries Hamadi1ecee442018-01-29 16:30:36 +0000108 std::vector<const char*> srcs;
Elliott Hughes22c15072019-11-07 15:38:00 -0800109 TemporaryFile tf;
110 android::base::WriteFully(tf.fd, data, byte_count);
111 srcs.push_back(tf.path);
112 // On Windows, the file needs to be flushed before pushing to device,
113 // but can't be removed until after the push.
114 unix_close(tf.release());
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700115
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700116 if (!do_sync_push(srcs, dst, sync, CompressionType::Any, false, false)) {
Joshua Gilpatrick0d384112019-07-19 09:42:12 -0700117 error_exit("Failed to push fastdeploy agent to device.");
118 }
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700119}
120
121static bool deploy_agent(bool check_time_stamps) {
122 REPORT_FUNC_TIME();
123
124 push_to_device(kDeployAgent, sizeof(kDeployAgent), kDeviceAgentFile, check_time_stamps);
125 push_to_device(kDeployAgentScript, sizeof(kDeployAgentScript), kDeviceAgentScript,
126 check_time_stamps);
127
Joshua Gilpatrick0d384112019-07-19 09:42:12 -0700128 // on windows the shell script might have lost execute permission
129 // so need to set this explicitly
130 const char* kChmodCommandPattern = "chmod 777 %s";
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700131 std::string chmod_command =
Joshua Gilpatrick0d384112019-07-19 09:42:12 -0700132 android::base::StringPrintf(kChmodCommandPattern, kDeviceAgentScript);
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700133 int ret = send_shell_command(chmod_command);
Joshua Gilpatrick0d384112019-07-19 09:42:12 -0700134 if (ret != 0) {
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700135 error_exit("Error executing %s returncode: %d", chmod_command.c_str(), ret);
Idries Hamadi1ecee442018-01-29 16:30:36 +0000136 }
Idries Hamadib1702db2018-09-06 18:42:39 +0100137
138 return true;
Idries Hamadi1ecee442018-01-29 16:30:36 +0000139}
140
Idries Hamadi78330f02018-09-13 18:00:25 +0100141static std::string get_string_from_utf16(const char16_t* input, int input_len) {
142 ssize_t utf8_length = utf16_to_utf8_length(input, input_len);
143 if (utf8_length <= 0) {
144 return {};
Idries Hamadi1ecee442018-01-29 16:30:36 +0000145 }
Idries Hamadi78330f02018-09-13 18:00:25 +0100146 std::string utf8;
147 utf8.resize(utf8_length);
148 utf16_to_utf8(input, input_len, &*utf8.begin(), utf8_length + 1);
149 return utf8;
Idries Hamadi7919be22018-08-28 12:58:09 +0100150}
151
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700152static std::string get_package_name_from_apk(const char* apk_path) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700153#undef open
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700154 std::unique_ptr<android::ZipFileRO> zip_file((android::ZipFileRO::open)(apk_path));
Elliott Hughese64126b2018-10-19 13:59:44 -0700155#define open ___xxx_unix_open
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700156 if (zip_file == nullptr) {
157 perror_exit("Could not open %s", apk_path);
Idries Hamadi1ecee442018-01-29 16:30:36 +0000158 }
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700159 android::ZipEntryRO entry = zip_file->findEntryByName("AndroidManifest.xml");
Idries Hamadi78330f02018-09-13 18:00:25 +0100160 if (entry == nullptr) {
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700161 error_exit("Could not find AndroidManifest.xml inside %s", apk_path);
Idries Hamadi78330f02018-09-13 18:00:25 +0100162 }
163 uint32_t manifest_len = 0;
Pawan Wagh40a36812024-06-03 21:48:37 +0000164 if (!zip_file->getEntryInfo(entry, nullptr, &manifest_len, nullptr, nullptr, nullptr, nullptr,
165 nullptr)) {
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700166 error_exit("Could not read AndroidManifest.xml inside %s", apk_path);
Idries Hamadi78330f02018-09-13 18:00:25 +0100167 }
168 std::vector<char> manifest_data(manifest_len);
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700169 if (!zip_file->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
170 error_exit("Could not uncompress AndroidManifest.xml inside %s", apk_path);
Idries Hamadi78330f02018-09-13 18:00:25 +0100171 }
172 android::ResXMLTree tree;
173 android::status_t setto_status = tree.setTo(manifest_data.data(), manifest_len, true);
174 if (setto_status != android::OK) {
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700175 error_exit("Could not parse AndroidManifest.xml inside %s", apk_path);
Idries Hamadi78330f02018-09-13 18:00:25 +0100176 }
177 android::ResXMLParser::event_code_t code;
178 while ((code = tree.next()) != android::ResXMLParser::BAD_DOCUMENT &&
179 code != android::ResXMLParser::END_DOCUMENT) {
180 switch (code) {
181 case android::ResXMLParser::START_TAG: {
182 size_t element_name_length;
183 const char16_t* element_name = tree.getElementName(&element_name_length);
184 if (element_name == nullptr) {
185 continue;
186 }
187 std::u16string element_name_string(element_name, element_name_length);
188 if (element_name_string == u"manifest") {
189 for (size_t i = 0; i < tree.getAttributeCount(); i++) {
190 size_t attribute_name_length;
191 const char16_t* attribute_name_text =
192 tree.getAttributeName(i, &attribute_name_length);
193 if (attribute_name_text == nullptr) {
194 continue;
195 }
196 std::u16string attribute_name_string(attribute_name_text,
197 attribute_name_length);
198 if (attribute_name_string == u"package") {
199 size_t attribute_value_length;
200 const char16_t* attribute_value_text =
201 tree.getAttributeStringValue(i, &attribute_value_length);
202 if (attribute_value_text == nullptr) {
203 continue;
204 }
205 return get_string_from_utf16(attribute_value_text,
206 attribute_value_length);
207 }
208 }
209 }
210 break;
211 }
212 default:
213 break;
214 }
215 }
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700216 error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apk_path);
Idries Hamadi1ecee442018-01-29 16:30:36 +0000217}
218
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700219static long parse_agent_version(const std::vector<char>& version_buffer) {
220 long version = -1;
221 if (!version_buffer.empty()) {
222 version = strtol((char*)version_buffer.data(), NULL, 16);
223 }
224 return version;
225}
Idries Hamadi1ecee442018-01-29 16:30:36 +0000226
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700227static void update_agent_if_necessary() {
228 switch (g_agent_update_strategy) {
229 case FastDeploy_AgentUpdateAlways:
230 deploy_agent(/*check_time_stamps=*/false);
231 break;
232 case FastDeploy_AgentUpdateNewerTimeStamp:
233 deploy_agent(/*check_time_stamps=*/true);
234 break;
235 default:
236 break;
237 }
238}
239
240std::optional<APKMetaData> extract_metadata(const char* apk_path) {
241 // Update agent if there is a command line argument forcing to do so.
242 update_agent_if_necessary();
243
244 REPORT_FUNC_TIME();
245
246 std::string package_name = get_package_name_from_apk(apk_path);
247
248 // Dump apk command checks the required vs current agent version and if they match then returns
249 // the APK dump for package. Doing this in a single call saves round-trip and agent launch time.
250 constexpr const char* kAgentDumpCommandPattern = "/data/local/tmp/deployagent dump %ld %s";
251 std::string dump_command = android::base::StringPrintf(
252 kAgentDumpCommandPattern, kRequiredAgentVersion, package_name.c_str());
253
254 std::vector<char> dump_out_buffer;
255 std::vector<char> dump_error_buffer;
256 int returnCode =
257 capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
258 if (returnCode >= kInvalidAgentVersion) {
259 // Agent has wrong version or missing.
260 long agent_version = parse_agent_version(dump_out_buffer);
261 if (agent_version < 0) {
262 printf("Could not detect agent on device, deploying\n");
263 } else {
264 printf("Device agent version is (%ld), (%ld) is required, re-deploying\n",
265 agent_version, kRequiredAgentVersion);
266 }
267 deploy_agent(/*check_time_stamps=*/false);
268
269 // Retry with new agent.
270 dump_out_buffer.clear();
271 dump_error_buffer.clear();
272 returnCode =
273 capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
274 }
Idries Hamadi78330f02018-09-13 18:00:25 +0100275 if (returnCode != 0) {
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700276 if (returnCode == kInvalidAgentVersion) {
277 long agent_version = parse_agent_version(dump_out_buffer);
278 error_exit(
279 "After update agent version remains incorrect! Expected %ld but version is %ld",
280 kRequiredAgentVersion, agent_version);
281 }
282 if (returnCode == kPackageMissing) {
283 fprintf(stderr, "Package %s not found, falling back to install\n",
284 package_name.c_str());
285 return {};
286 }
287 fprintf(stderr, "Executing %s returned %d\n", dump_command.c_str(), returnCode);
288 fprintf(stderr, "%*s\n", int(dump_error_buffer.size()), dump_error_buffer.data());
Henry Daitx61bf7482018-11-30 18:02:43 +0000289 error_exit("Aborting");
Idries Hamadi1ecee442018-01-29 16:30:36 +0000290 }
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700291
292 com::android::fastdeploy::APKDump dump;
293 if (!dump.ParseFromArray(dump_out_buffer.data(), dump_out_buffer.size())) {
294 fprintf(stderr, "Can't parse output of %s\n", dump_command.c_str());
295 error_exit("Aborting");
296 }
297
298 return PatchUtils::GetDeviceAPKMetaData(dump);
Idries Hamadi1ecee442018-01-29 16:30:36 +0000299}
300
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700301unique_fd install_patch(int argc, const char** argv) {
302 REPORT_FUNC_TIME();
303 constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -pm %s";
Idries Hamadi1ecee442018-01-29 16:30:36 +0000304
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700305 std::vector<unsigned char> apply_output_buffer;
306 std::vector<unsigned char> apply_error_buffer;
Idries Hamadi1ecee442018-01-29 16:30:36 +0000307 std::string argsString;
308
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000309 bool rSwitchPresent = false;
Idries Hamadi1ecee442018-01-29 16:30:36 +0000310 for (int i = 0; i < argc; i++) {
311 argsString.append(argv[i]);
312 argsString.append(" ");
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000313 if (!strcmp(argv[i], "-r")) {
314 rSwitchPresent = true;
315 }
316 }
317 if (!rSwitchPresent) {
318 argsString.append("-r");
Idries Hamadi1ecee442018-01-29 16:30:36 +0000319 }
320
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700321 std::string error;
322 std::string apply_patch_service_string =
323 android::base::StringPrintf(kAgentApplyServicePattern, argsString.c_str());
324 unique_fd fd{adb_connect(apply_patch_service_string, &error)};
325 if (fd < 0) {
326 error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
327 }
328 return fd;
329}
330
331unique_fd apply_patch_on_device(const char* output_path) {
332 REPORT_FUNC_TIME();
333 constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -o %s";
334
335 std::string error;
336 std::string apply_patch_service_string =
337 android::base::StringPrintf(kAgentApplyServicePattern, output_path);
338 unique_fd fd{adb_connect(apply_patch_service_string, &error)};
339 if (fd < 0) {
340 error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
341 }
342 return fd;
343}
344
345static void create_patch(const char* apk_path, APKMetaData metadata, borrowed_fd patch_fd) {
346 REPORT_FUNC_TIME();
347 DeployPatchGenerator generator(/*is_verbose=*/false);
348 bool success = generator.CreatePatch(apk_path, std::move(metadata), patch_fd);
349 if (!success) {
350 error_exit("Failed to create patch for %s", apk_path);
Idries Hamadi78330f02018-09-13 18:00:25 +0100351 }
Idries Hamadi1ecee442018-01-29 16:30:36 +0000352}
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000353
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700354int stream_patch(const char* apk_path, APKMetaData metadata, unique_fd patch_fd) {
355 create_patch(apk_path, std::move(metadata), patch_fd);
356
357 REPORT_FUNC_TIME();
358 return read_and_dump(patch_fd.get());
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000359}