• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "fastdeploycallbacks.h"
31 #include "sysdeps.h"
32 
33 #include "adb_utils.h"
34 
35 static constexpr long kRequiredAgentVersion = 0x00000002;
36 
37 static constexpr const char* kDeviceAgentPath = "/data/local/tmp/";
38 
39 static bool g_use_localagent = false;
40 
get_agent_version()41 long get_agent_version() {
42     std::vector<char> versionOutputBuffer;
43     std::vector<char> versionErrorBuffer;
44 
45     int statusCode = capture_shell_command("/data/local/tmp/deployagent version",
46                                            &versionOutputBuffer, &versionErrorBuffer);
47     long version = -1;
48 
49     if (statusCode == 0 && versionOutputBuffer.size() > 0) {
50         version = strtol((char*)versionOutputBuffer.data(), NULL, 16);
51     }
52 
53     return version;
54 }
55 
get_device_api_level()56 int get_device_api_level() {
57     std::vector<char> sdkVersionOutputBuffer;
58     std::vector<char> sdkVersionErrorBuffer;
59     int api_level = -1;
60 
61     int statusCode = capture_shell_command("getprop ro.build.version.sdk", &sdkVersionOutputBuffer,
62                                            &sdkVersionErrorBuffer);
63     if (statusCode == 0 && sdkVersionOutputBuffer.size() > 0) {
64         api_level = strtol((char*)sdkVersionOutputBuffer.data(), NULL, 10);
65     }
66 
67     return api_level;
68 }
69 
fastdeploy_set_local_agent(bool use_localagent)70 void fastdeploy_set_local_agent(bool use_localagent) {
71     g_use_localagent = use_localagent;
72 }
73 
74 // local_path - must start with a '/' and be relative to $ANDROID_PRODUCT_OUT
get_agent_component_host_path(const char * local_path,const char * sdk_path)75 static std::string get_agent_component_host_path(const char* local_path, const char* sdk_path) {
76     std::string adb_dir = android::base::GetExecutableDirectory();
77     if (adb_dir.empty()) {
78         error_exit("Could not determine location of adb!");
79     }
80 
81     if (g_use_localagent) {
82         const char* product_out = getenv("ANDROID_PRODUCT_OUT");
83         if (product_out == nullptr) {
84             error_exit("Could not locate %s because $ANDROID_PRODUCT_OUT is not defined",
85                        local_path);
86         }
87         return android::base::StringPrintf("%s%s", product_out, local_path);
88     } else {
89         return adb_dir + sdk_path;
90     }
91 }
92 
deploy_agent(bool checkTimeStamps)93 static bool deploy_agent(bool checkTimeStamps) {
94     std::vector<const char*> srcs;
95     std::string jar_path =
96             get_agent_component_host_path("/system/framework/deployagent.jar", "/deployagent.jar");
97     std::string script_path =
98             get_agent_component_host_path("/system/bin/deployagent", "/deployagent");
99     srcs.push_back(jar_path.c_str());
100     srcs.push_back(script_path.c_str());
101 
102     if (do_sync_push(srcs, kDeviceAgentPath, checkTimeStamps)) {
103         // on windows the shell script might have lost execute permission
104         // so need to set this explicitly
105         const char* kChmodCommandPattern = "chmod 777 %sdeployagent";
106         std::string chmodCommand =
107                 android::base::StringPrintf(kChmodCommandPattern, kDeviceAgentPath);
108         int ret = send_shell_command(chmodCommand);
109         if (ret != 0) {
110             error_exit("Error executing %s returncode: %d", chmodCommand.c_str(), ret);
111         }
112     } else {
113         error_exit("Error pushing agent files to device");
114     }
115 
116     return true;
117 }
118 
update_agent(FastDeploy_AgentUpdateStrategy agentUpdateStrategy)119 void update_agent(FastDeploy_AgentUpdateStrategy agentUpdateStrategy) {
120     long agent_version = get_agent_version();
121     switch (agentUpdateStrategy) {
122         case FastDeploy_AgentUpdateAlways:
123             deploy_agent(false);
124             break;
125         case FastDeploy_AgentUpdateNewerTimeStamp:
126             deploy_agent(true);
127             break;
128         case FastDeploy_AgentUpdateDifferentVersion:
129             if (agent_version != kRequiredAgentVersion) {
130                 if (agent_version < 0) {
131                     printf("Could not detect agent on device, deploying\n");
132                 } else {
133                     printf("Device agent version is (%ld), (%ld) is required, re-deploying\n",
134                            agent_version, kRequiredAgentVersion);
135                 }
136                 deploy_agent(false);
137             }
138             break;
139     }
140 
141     agent_version = get_agent_version();
142     if (agent_version != kRequiredAgentVersion) {
143         error_exit("After update agent version remains incorrect! Expected %ld but version is %ld",
144                    kRequiredAgentVersion, agent_version);
145     }
146 }
147 
get_string_from_utf16(const char16_t * input,int input_len)148 static std::string get_string_from_utf16(const char16_t* input, int input_len) {
149     ssize_t utf8_length = utf16_to_utf8_length(input, input_len);
150     if (utf8_length <= 0) {
151         return {};
152     }
153     std::string utf8;
154     utf8.resize(utf8_length);
155     utf16_to_utf8(input, input_len, &*utf8.begin(), utf8_length + 1);
156     return utf8;
157 }
158 
get_packagename_from_apk(const char * apkPath)159 static std::string get_packagename_from_apk(const char* apkPath) {
160 #undef open
161     std::unique_ptr<android::ZipFileRO> zipFile(android::ZipFileRO::open(apkPath));
162 #define open ___xxx_unix_open
163     if (zipFile == nullptr) {
164         perror_exit("Could not open %s", apkPath);
165     }
166     android::ZipEntryRO entry = zipFile->findEntryByName("AndroidManifest.xml");
167     if (entry == nullptr) {
168         error_exit("Could not find AndroidManifest.xml inside %s", apkPath);
169     }
170     uint32_t manifest_len = 0;
171     if (!zipFile->getEntryInfo(entry, NULL, &manifest_len, NULL, NULL, NULL, NULL)) {
172         error_exit("Could not read AndroidManifest.xml inside %s", apkPath);
173     }
174     std::vector<char> manifest_data(manifest_len);
175     if (!zipFile->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
176         error_exit("Could not uncompress AndroidManifest.xml inside %s", apkPath);
177     }
178     android::ResXMLTree tree;
179     android::status_t setto_status = tree.setTo(manifest_data.data(), manifest_len, true);
180     if (setto_status != android::OK) {
181         error_exit("Could not parse AndroidManifest.xml inside %s", apkPath);
182     }
183     android::ResXMLParser::event_code_t code;
184     while ((code = tree.next()) != android::ResXMLParser::BAD_DOCUMENT &&
185            code != android::ResXMLParser::END_DOCUMENT) {
186         switch (code) {
187             case android::ResXMLParser::START_TAG: {
188                 size_t element_name_length;
189                 const char16_t* element_name = tree.getElementName(&element_name_length);
190                 if (element_name == nullptr) {
191                     continue;
192                 }
193                 std::u16string element_name_string(element_name, element_name_length);
194                 if (element_name_string == u"manifest") {
195                     for (size_t i = 0; i < tree.getAttributeCount(); i++) {
196                         size_t attribute_name_length;
197                         const char16_t* attribute_name_text =
198                                 tree.getAttributeName(i, &attribute_name_length);
199                         if (attribute_name_text == nullptr) {
200                             continue;
201                         }
202                         std::u16string attribute_name_string(attribute_name_text,
203                                                              attribute_name_length);
204                         if (attribute_name_string == u"package") {
205                             size_t attribute_value_length;
206                             const char16_t* attribute_value_text =
207                                     tree.getAttributeStringValue(i, &attribute_value_length);
208                             if (attribute_value_text == nullptr) {
209                                 continue;
210                             }
211                             return get_string_from_utf16(attribute_value_text,
212                                                          attribute_value_length);
213                         }
214                     }
215                 }
216                 break;
217             }
218             default:
219                 break;
220         }
221     }
222     error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apkPath);
223 }
224 
extract_metadata(const char * apkPath,FILE * outputFp)225 void extract_metadata(const char* apkPath, FILE* outputFp) {
226     std::string packageName = get_packagename_from_apk(apkPath);
227     const char* kAgentExtractCommandPattern = "/data/local/tmp/deployagent extract %s";
228     std::string extractCommand =
229             android::base::StringPrintf(kAgentExtractCommandPattern, packageName.c_str());
230 
231     std::vector<char> extractErrorBuffer;
232     DeployAgentFileCallback cb(outputFp, &extractErrorBuffer);
233     int returnCode = send_shell_command(extractCommand, false, &cb);
234     if (returnCode != 0) {
235         fprintf(stderr, "Executing %s returned %d\n", extractCommand.c_str(), returnCode);
236         fprintf(stderr, "%*s\n", int(extractErrorBuffer.size()), extractErrorBuffer.data());
237         error_exit("Aborting");
238     }
239 }
240 
get_patch_generator_command()241 static std::string get_patch_generator_command() {
242     if (g_use_localagent) {
243         // This should never happen on a Windows machine
244         const char* host_out = getenv("ANDROID_HOST_OUT");
245         if (host_out == nullptr) {
246             error_exit(
247                     "Could not locate deploypatchgenerator.jar because $ANDROID_HOST_OUT "
248                     "is not defined");
249         }
250         return android::base::StringPrintf("java -jar %s/framework/deploypatchgenerator.jar",
251                                            host_out);
252     }
253 
254     std::string adb_dir = android::base::GetExecutableDirectory();
255     if (adb_dir.empty()) {
256         error_exit("Could not locate deploypatchgenerator.jar");
257     }
258     return android::base::StringPrintf(R"(java -jar "%s/deploypatchgenerator.jar")",
259                                        adb_dir.c_str());
260 }
261 
create_patch(const char * apkPath,const char * metadataPath,const char * patchPath)262 void create_patch(const char* apkPath, const char* metadataPath, const char* patchPath) {
263     std::string generatePatchCommand = android::base::StringPrintf(
264             R"(%s "%s" "%s" > "%s")", get_patch_generator_command().c_str(), apkPath, metadataPath,
265             patchPath);
266     int returnCode = system(generatePatchCommand.c_str());
267     if (returnCode != 0) {
268         error_exit("Executing %s returned %d", generatePatchCommand.c_str(), returnCode);
269     }
270 }
271 
get_patch_path(const char * apkPath)272 std::string get_patch_path(const char* apkPath) {
273     std::string packageName = get_packagename_from_apk(apkPath);
274     std::string patchDevicePath =
275             android::base::StringPrintf("%s%s.patch", kDeviceAgentPath, packageName.c_str());
276     return patchDevicePath;
277 }
278 
apply_patch_on_device(const char * apkPath,const char * patchPath,const char * outputPath)279 void apply_patch_on_device(const char* apkPath, const char* patchPath, const char* outputPath) {
280     const std::string kAgentApplyCommandPattern = "/data/local/tmp/deployagent apply %s %s -o %s";
281     std::string packageName = get_packagename_from_apk(apkPath);
282     std::string patchDevicePath = get_patch_path(apkPath);
283 
284     std::vector<const char*> srcs = {patchPath};
285     bool push_ok = do_sync_push(srcs, patchDevicePath.c_str(), false);
286     if (!push_ok) {
287         error_exit("Error pushing %s to %s returned", patchPath, patchDevicePath.c_str());
288     }
289 
290     std::string applyPatchCommand =
291             android::base::StringPrintf(kAgentApplyCommandPattern.c_str(), packageName.c_str(),
292                                         patchDevicePath.c_str(), outputPath);
293 
294     int returnCode = send_shell_command(applyPatchCommand);
295     if (returnCode != 0) {
296         error_exit("Executing %s returned %d", applyPatchCommand.c_str(), returnCode);
297     }
298 }
299 
install_patch(const char * apkPath,const char * patchPath,int argc,const char ** argv)300 void install_patch(const char* apkPath, const char* patchPath, int argc, const char** argv) {
301     const std::string kAgentApplyCommandPattern = "/data/local/tmp/deployagent apply %s %s -pm %s";
302     std::string packageName = get_packagename_from_apk(apkPath);
303 
304     std::string patchDevicePath =
305             android::base::StringPrintf("%s%s.patch", kDeviceAgentPath, packageName.c_str());
306 
307     std::vector<const char*> srcs{patchPath};
308     bool push_ok = do_sync_push(srcs, patchDevicePath.c_str(), false);
309     if (!push_ok) {
310         error_exit("Error pushing %s to %s returned", patchPath, patchDevicePath.c_str());
311     }
312 
313     std::vector<unsigned char> applyOutputBuffer;
314     std::vector<unsigned char> applyErrorBuffer;
315     std::string argsString;
316 
317     bool rSwitchPresent = false;
318     for (int i = 0; i < argc; i++) {
319         argsString.append(argv[i]);
320         argsString.append(" ");
321         if (!strcmp(argv[i], "-r")) {
322             rSwitchPresent = true;
323         }
324     }
325     if (!rSwitchPresent) {
326         argsString.append("-r");
327     }
328 
329     std::string applyPatchCommand =
330             android::base::StringPrintf(kAgentApplyCommandPattern.c_str(), packageName.c_str(),
331                                         patchDevicePath.c_str(), argsString.c_str());
332     int returnCode = send_shell_command(applyPatchCommand);
333     if (returnCode != 0) {
334         error_exit("Executing %s returned %d", applyPatchCommand.c_str(), returnCode);
335     }
336 }
337 
find_package(const char * apkPath)338 bool find_package(const char* apkPath) {
339     const std::string findCommand =
340             "/data/local/tmp/deployagent find " + get_packagename_from_apk(apkPath);
341     return !send_shell_command(findCommand);
342 }
343