1 /*
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 
17 #include "fastdeploy.h"
18 
19 #include <string.h>
20 #include <algorithm>
21 #include <array>
22 #include <memory>
23 
24 #include "android-base/file.h"
25 #include "android-base/strings.h"
26 #include "androidfw/ResourceTypes.h"
27 #include "androidfw/ZipFileRO.h"
28 #include "client/file_sync_client.h"
29 #include "commandline.h"
30 #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"
33 #include "fastdeploy/deploypatchgenerator/patch_utils.h"
34 #include "fastdeploy/proto/ApkEntry.pb.h"
35 #include "fastdeploycallbacks.h"
36 #include "sysdeps.h"
37 
38 #include "adb_client.h"
39 #include "adb_utils.h"
40 
41 static constexpr long kRequiredAgentVersion = 0x00000003;
42 
43 static constexpr int kPackageMissing = 3;
44 static constexpr int kInvalidAgentVersion = 4;
45 
46 static constexpr const char* kDeviceAgentFile = "/data/local/tmp/deployagent.jar";
47 static constexpr const char* kDeviceAgentScript = "/data/local/tmp/deployagent";
48 
49 static constexpr bool g_verbose_timings = false;
50 static FastDeploy_AgentUpdateStrategy g_agent_update_strategy =
51         FastDeploy_AgentUpdateDifferentVersion;
52 
53 using APKMetaData = com::android::fastdeploy::APKMetaData;
54 
55 namespace {
56 
57 struct TimeReporter {
TimeReporter__anon0381ddfb0111::TimeReporter58     TimeReporter(const char* label) : label_(label) {}
~TimeReporter__anon0381ddfb0111::TimeReporter59     ~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         }
66     }
67 
68   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 
74 struct FileDeleter {
FileDeleter__anon0381ddfb0111::FileDeleter75     FileDeleter(const char* path) : path_(path) {}
~FileDeleter__anon0381ddfb0111::FileDeleter76     ~FileDeleter() { adb_unlink(path_); }
77 
78   private:
79     const char* const path_;
80 };
81 
82 }  // namespace
83 
get_device_api_level()84 int get_device_api_level() {
85     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;
90 
91         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         }
97 
98         return api_level;
99     }();
100     return api_level;
101 }
102 
fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy)103 void fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy) {
104     g_agent_update_strategy = agent_update_strategy;
105 }
106 
push_to_device(const void * data,size_t byte_count,const char * dst,bool sync)107 static void push_to_device(const void* data, size_t byte_count, const char* dst, bool sync) {
108     std::vector<const char*> srcs;
109     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());
115 
116     if (!do_sync_push(srcs, dst, sync, CompressionType::Any, false, false)) {
117         error_exit("Failed to push fastdeploy agent to device.");
118     }
119 }
120 
deploy_agent(bool check_time_stamps)121 static 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 
128     // on windows the shell script might have lost execute permission
129     // so need to set this explicitly
130     const char* kChmodCommandPattern = "chmod 777 %s";
131     std::string chmod_command =
132             android::base::StringPrintf(kChmodCommandPattern, kDeviceAgentScript);
133     int ret = send_shell_command(chmod_command);
134     if (ret != 0) {
135         error_exit("Error executing %s returncode: %d", chmod_command.c_str(), ret);
136     }
137 
138     return true;
139 }
140 
get_string_from_utf16(const char16_t * input,int input_len)141 static 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 {};
145     }
146     std::string utf8;
147     utf8.resize(utf8_length);
148     utf16_to_utf8(input, input_len, &*utf8.begin(), utf8_length + 1);
149     return utf8;
150 }
151 
get_package_name_from_apk(const char * apk_path)152 static std::string get_package_name_from_apk(const char* apk_path) {
153 #undef open
154     std::unique_ptr<android::ZipFileRO> zip_file((android::ZipFileRO::open)(apk_path));
155 #define open ___xxx_unix_open
156     if (zip_file == nullptr) {
157         perror_exit("Could not open %s", apk_path);
158     }
159     android::ZipEntryRO entry = zip_file->findEntryByName("AndroidManifest.xml");
160     if (entry == nullptr) {
161         error_exit("Could not find AndroidManifest.xml inside %s", apk_path);
162     }
163     uint32_t manifest_len = 0;
164     if (!zip_file->getEntryInfo(entry, nullptr, &manifest_len, nullptr, nullptr, nullptr, nullptr,
165                                 nullptr)) {
166         error_exit("Could not read AndroidManifest.xml inside %s", apk_path);
167     }
168     std::vector<char> manifest_data(manifest_len);
169     if (!zip_file->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
170         error_exit("Could not uncompress AndroidManifest.xml inside %s", apk_path);
171     }
172     android::ResXMLTree tree;
173     android::status_t setto_status = tree.setTo(manifest_data.data(), manifest_len, true);
174     if (setto_status != android::OK) {
175         error_exit("Could not parse AndroidManifest.xml inside %s", apk_path);
176     }
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     }
216     error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apk_path);
217 }
218 
parse_agent_version(const std::vector<char> & version_buffer)219 static 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 }
226 
update_agent_if_necessary()227 static 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 
extract_metadata(const char * apk_path)240 std::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     }
275     if (returnCode != 0) {
276         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());
289         error_exit("Aborting");
290     }
291 
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);
299 }
300 
install_patch(int argc,const char ** argv)301 unique_fd install_patch(int argc, const char** argv) {
302     REPORT_FUNC_TIME();
303     constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -pm %s";
304 
305     std::vector<unsigned char> apply_output_buffer;
306     std::vector<unsigned char> apply_error_buffer;
307     std::string argsString;
308 
309     bool rSwitchPresent = false;
310     for (int i = 0; i < argc; i++) {
311         argsString.append(argv[i]);
312         argsString.append(" ");
313         if (!strcmp(argv[i], "-r")) {
314             rSwitchPresent = true;
315         }
316     }
317     if (!rSwitchPresent) {
318         argsString.append("-r");
319     }
320 
321     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 
apply_patch_on_device(const char * output_path)331 unique_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 
create_patch(const char * apk_path,APKMetaData metadata,borrowed_fd patch_fd)345 static 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);
351     }
352 }
353 
stream_patch(const char * apk_path,APKMetaData metadata,unique_fd patch_fd)354 int 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());
359 }
360