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_utils.h"
39 
40 static constexpr long kRequiredAgentVersion = 0x00000003;
41 
42 static constexpr int kPackageMissing = 3;
43 static constexpr int kInvalidAgentVersion = 4;
44 
45 static constexpr const char* kDeviceAgentFile = "/data/local/tmp/deployagent.jar";
46 static constexpr const char* kDeviceAgentScript = "/data/local/tmp/deployagent";
47 
48 static constexpr bool g_verbose_timings = false;
49 static FastDeploy_AgentUpdateStrategy g_agent_update_strategy =
50         FastDeploy_AgentUpdateDifferentVersion;
51 
52 using APKMetaData = com::android::fastdeploy::APKMetaData;
53 
54 namespace {
55 
56 struct TimeReporter {
TimeReporter__anon7053af450111::TimeReporter57     TimeReporter(const char* label) : label_(label) {}
~TimeReporter__anon7053af450111::TimeReporter58     ~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         }
65     }
66 
67   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 
73 struct FileDeleter {
FileDeleter__anon7053af450111::FileDeleter74     FileDeleter(const char* path) : path_(path) {}
~FileDeleter__anon7053af450111::FileDeleter75     ~FileDeleter() { adb_unlink(path_); }
76 
77   private:
78     const char* const path_;
79 };
80 
81 }  // namespace
82 
get_device_api_level()83 int get_device_api_level() {
84     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;
89 
90         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         }
96 
97         return api_level;
98     }();
99     return api_level;
100 }
101 
fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy)102 void fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy) {
103     g_agent_update_strategy = agent_update_strategy;
104 }
105 
push_to_device(const void * data,size_t byte_count,const char * dst,bool sync)106 static void push_to_device(const void* data, size_t byte_count, const char* dst, bool sync) {
107     std::vector<const char*> srcs;
108     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());
114 
115     if (!do_sync_push(srcs, dst, sync, CompressionType::Any, false, false)) {
116         error_exit("Failed to push fastdeploy agent to device.");
117     }
118 }
119 
deploy_agent(bool check_time_stamps)120 static 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 
127     // on windows the shell script might have lost execute permission
128     // so need to set this explicitly
129     const char* kChmodCommandPattern = "chmod 777 %s";
130     std::string chmod_command =
131             android::base::StringPrintf(kChmodCommandPattern, kDeviceAgentScript);
132     int ret = send_shell_command(chmod_command);
133     if (ret != 0) {
134         error_exit("Error executing %s returncode: %d", chmod_command.c_str(), ret);
135     }
136 
137     return true;
138 }
139 
get_string_from_utf16(const char16_t * input,int input_len)140 static 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 {};
144     }
145     std::string utf8;
146     utf8.resize(utf8_length);
147     utf16_to_utf8(input, input_len, &*utf8.begin(), utf8_length + 1);
148     return utf8;
149 }
150 
get_package_name_from_apk(const char * apk_path)151 static std::string get_package_name_from_apk(const char* apk_path) {
152 #undef open
153     std::unique_ptr<android::ZipFileRO> zip_file((android::ZipFileRO::open)(apk_path));
154 #define open ___xxx_unix_open
155     if (zip_file == nullptr) {
156         perror_exit("Could not open %s", apk_path);
157     }
158     android::ZipEntryRO entry = zip_file->findEntryByName("AndroidManifest.xml");
159     if (entry == nullptr) {
160         error_exit("Could not find AndroidManifest.xml inside %s", apk_path);
161     }
162     uint32_t manifest_len = 0;
163     if (!zip_file->getEntryInfo(entry, nullptr, &manifest_len, nullptr, nullptr, nullptr, nullptr,
164                                 nullptr)) {
165         error_exit("Could not read AndroidManifest.xml inside %s", apk_path);
166     }
167     std::vector<char> manifest_data(manifest_len);
168     if (!zip_file->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
169         error_exit("Could not uncompress AndroidManifest.xml inside %s", apk_path);
170     }
171     android::ResXMLTree tree;
172     android::status_t setto_status = tree.setTo(manifest_data.data(), manifest_len, true);
173     if (setto_status != android::OK) {
174         error_exit("Could not parse AndroidManifest.xml inside %s", apk_path);
175     }
176     android::ResXMLParser::event_code_t code;
177     while ((code = tree.next()) != android::ResXMLParser::BAD_DOCUMENT &&
178            code != android::ResXMLParser::END_DOCUMENT) {
179         switch (code) {
180             case android::ResXMLParser::START_TAG: {
181                 size_t element_name_length;
182                 const char16_t* element_name = tree.getElementName(&element_name_length);
183                 if (element_name == nullptr) {
184                     continue;
185                 }
186                 std::u16string element_name_string(element_name, element_name_length);
187                 if (element_name_string == u"manifest") {
188                     for (size_t i = 0; i < tree.getAttributeCount(); i++) {
189                         size_t attribute_name_length;
190                         const char16_t* attribute_name_text =
191                                 tree.getAttributeName(i, &attribute_name_length);
192                         if (attribute_name_text == nullptr) {
193                             continue;
194                         }
195                         std::u16string attribute_name_string(attribute_name_text,
196                                                              attribute_name_length);
197                         if (attribute_name_string == u"package") {
198                             size_t attribute_value_length;
199                             const char16_t* attribute_value_text =
200                                     tree.getAttributeStringValue(i, &attribute_value_length);
201                             if (attribute_value_text == nullptr) {
202                                 continue;
203                             }
204                             return get_string_from_utf16(attribute_value_text,
205                                                          attribute_value_length);
206                         }
207                     }
208                 }
209                 break;
210             }
211             default:
212                 break;
213         }
214     }
215     error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apk_path);
216 }
217 
parse_agent_version(const std::vector<char> & version_buffer)218 static long parse_agent_version(const std::vector<char>& version_buffer) {
219     long version = -1;
220     if (!version_buffer.empty()) {
221         version = strtol((char*)version_buffer.data(), NULL, 16);
222     }
223     return version;
224 }
225 
update_agent_if_necessary()226 static void update_agent_if_necessary() {
227     switch (g_agent_update_strategy) {
228         case FastDeploy_AgentUpdateAlways:
229             deploy_agent(/*check_time_stamps=*/false);
230             break;
231         case FastDeploy_AgentUpdateNewerTimeStamp:
232             deploy_agent(/*check_time_stamps=*/true);
233             break;
234         default:
235             break;
236     }
237 }
238 
extract_metadata(const char * apk_path)239 std::optional<APKMetaData> extract_metadata(const char* apk_path) {
240     // Update agent if there is a command line argument forcing to do so.
241     update_agent_if_necessary();
242 
243     REPORT_FUNC_TIME();
244 
245     std::string package_name = get_package_name_from_apk(apk_path);
246 
247     // Dump apk command checks the required vs current agent version and if they match then returns
248     // the APK dump for package. Doing this in a single call saves round-trip and agent launch time.
249     constexpr const char* kAgentDumpCommandPattern = "/data/local/tmp/deployagent dump %ld %s";
250     std::string dump_command = android::base::StringPrintf(
251             kAgentDumpCommandPattern, kRequiredAgentVersion, package_name.c_str());
252 
253     std::vector<char> dump_out_buffer;
254     std::vector<char> dump_error_buffer;
255     int returnCode =
256             capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
257     if (returnCode >= kInvalidAgentVersion) {
258         // Agent has wrong version or missing.
259         long agent_version = parse_agent_version(dump_out_buffer);
260         if (agent_version < 0) {
261             printf("Could not detect agent on device, deploying\n");
262         } else {
263             printf("Device agent version is (%ld), (%ld) is required, re-deploying\n",
264                    agent_version, kRequiredAgentVersion);
265         }
266         deploy_agent(/*check_time_stamps=*/false);
267 
268         // Retry with new agent.
269         dump_out_buffer.clear();
270         dump_error_buffer.clear();
271         returnCode =
272                 capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
273     }
274     if (returnCode != 0) {
275         if (returnCode == kInvalidAgentVersion) {
276             long agent_version = parse_agent_version(dump_out_buffer);
277             error_exit(
278                     "After update agent version remains incorrect! Expected %ld but version is %ld",
279                     kRequiredAgentVersion, agent_version);
280         }
281         if (returnCode == kPackageMissing) {
282             fprintf(stderr, "Package %s not found, falling back to install\n",
283                     package_name.c_str());
284             return {};
285         }
286         fprintf(stderr, "Executing %s returned %d\n", dump_command.c_str(), returnCode);
287         fprintf(stderr, "%*s\n", int(dump_error_buffer.size()), dump_error_buffer.data());
288         error_exit("Aborting");
289     }
290 
291     com::android::fastdeploy::APKDump dump;
292     if (!dump.ParseFromArray(dump_out_buffer.data(), dump_out_buffer.size())) {
293         fprintf(stderr, "Can't parse output of %s\n", dump_command.c_str());
294         error_exit("Aborting");
295     }
296 
297     return PatchUtils::GetDeviceAPKMetaData(dump);
298 }
299 
install_patch(int argc,const char ** argv)300 unique_fd install_patch(int argc, const char** argv) {
301     REPORT_FUNC_TIME();
302     constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -pm %s";
303 
304     std::vector<unsigned char> apply_output_buffer;
305     std::vector<unsigned char> apply_error_buffer;
306     std::string argsString;
307 
308     bool rSwitchPresent = false;
309     for (int i = 0; i < argc; i++) {
310         argsString.append(argv[i]);
311         argsString.append(" ");
312         if (!strcmp(argv[i], "-r")) {
313             rSwitchPresent = true;
314         }
315     }
316     if (!rSwitchPresent) {
317         argsString.append("-r");
318     }
319 
320     std::string error;
321     std::string apply_patch_service_string =
322             android::base::StringPrintf(kAgentApplyServicePattern, argsString.c_str());
323     unique_fd fd{adb_connect(apply_patch_service_string, &error)};
324     if (fd < 0) {
325         error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
326     }
327     return fd;
328 }
329 
apply_patch_on_device(const char * output_path)330 unique_fd apply_patch_on_device(const char* output_path) {
331     REPORT_FUNC_TIME();
332     constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -o %s";
333 
334     std::string error;
335     std::string apply_patch_service_string =
336             android::base::StringPrintf(kAgentApplyServicePattern, output_path);
337     unique_fd fd{adb_connect(apply_patch_service_string, &error)};
338     if (fd < 0) {
339         error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
340     }
341     return fd;
342 }
343 
create_patch(const char * apk_path,APKMetaData metadata,borrowed_fd patch_fd)344 static void create_patch(const char* apk_path, APKMetaData metadata, borrowed_fd patch_fd) {
345     REPORT_FUNC_TIME();
346     DeployPatchGenerator generator(/*is_verbose=*/false);
347     bool success = generator.CreatePatch(apk_path, std::move(metadata), patch_fd);
348     if (!success) {
349         error_exit("Failed to create patch for %s", apk_path);
350     }
351 }
352 
stream_patch(const char * apk_path,APKMetaData metadata,unique_fd patch_fd)353 int stream_patch(const char* apk_path, APKMetaData metadata, unique_fd patch_fd) {
354     create_patch(apk_path, std::move(metadata), patch_fd);
355 
356     REPORT_FUNC_TIME();
357     return read_and_dump(patch_fd.get());
358 }
359