blob: 2266127f25be6532449e0a3ca132e3a374a731a7 [file] [log] [blame]
Doug Zongker9931f7f2009-06-10 14:11:53 -07001/*
2 * Copyright (C) 2009 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
Tao Bao0c7839a2016-10-10 15:48:37 -070017#include "updater/install.h"
18
Doug Zongkerfbf3c102009-06-24 09:36:20 -070019#include <ctype.h>
Doug Zongker9931f7f2009-06-10 14:11:53 -070020#include <errno.h>
Tao Bao361342c2016-02-08 11:15:50 -080021#include <fcntl.h>
22#include <ftw.h>
23#include <inttypes.h>
Doug Zongker9931f7f2009-06-10 14:11:53 -070024#include <stdarg.h>
Doug Zongkerfbf3c102009-06-24 09:36:20 -070025#include <stdio.h>
Doug Zongker9931f7f2009-06-10 14:11:53 -070026#include <stdlib.h>
27#include <string.h>
Tao Bao361342c2016-02-08 11:15:50 -080028#include <sys/capability.h>
Doug Zongker9931f7f2009-06-10 14:11:53 -070029#include <sys/mount.h>
30#include <sys/stat.h>
31#include <sys/types.h>
Doug Zongkera3f89ea2009-09-10 14:10:48 -070032#include <sys/wait.h>
Nick Kralevich5dbdef02013-09-07 14:41:06 -070033#include <sys/xattr.h>
Tao Bao361342c2016-02-08 11:15:50 -080034#include <time.h>
35#include <unistd.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070036#include <utime.h>
Doug Zongker9931f7f2009-06-10 14:11:53 -070037
Yabin Cui64be2132016-02-03 18:16:02 -080038#include <memory>
Tao Bao1bf17722016-11-03 23:52:01 -070039#include <string>
Yabin Cui64be2132016-02-03 18:16:02 -080040#include <vector>
41
Tao Bao1bf17722016-11-03 23:52:01 -070042#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080043#include <android-base/logging.h>
Tianjie Xu5fe280a2016-10-17 18:15:20 -070044#include <android-base/parsedouble.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070046#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080047#include <android-base/stringprintf.h>
Tao Baod0f30882016-11-03 23:52:01 -070048#include <android-base/strings.h>
Tao Bao0d3f84f2016-12-28 15:09:20 -080049#include <applypatch/applypatch.h>
50#include <bootloader_message/bootloader_message.h>
Tao Bao0c7839a2016-10-10 15:48:37 -070051#include <cutils/android_reboot.h>
Tao Baode40ba52016-10-05 23:17:01 -070052#include <ext4_utils/wipe.h>
Tao Bao361342c2016-02-08 11:15:50 -080053#include <openssl/sha.h>
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070054#include <selinux/label.h>
55#include <selinux/selinux.h>
Tao Bao09e468f2017-09-29 14:39:33 -070056#include <tune2fs.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070057#include <ziparchive/zip_archive.h>
Tao Bao1107d962015-09-09 17:16:55 -070058
Doug Zongker9931f7f2009-06-10 14:11:53 -070059#include "edify/expr.h"
Elliott Hughes63a31922016-06-09 17:41:22 -070060#include "mounts.h"
Ethan Yonker8373cfe2017-09-08 06:50:54 -050061
Doug Zongker512536a2010-02-17 16:11:44 -080062#include "applypatch/applypatch.h"
Dees_Troy512376c2013-09-03 19:39:41 +000063#include "flashutils/flashutils.h"
Doug Zongkerc9d6e4f2014-02-24 16:02:50 -080064#include "install.h"
Ethan Yonker7e1b9862015-03-19 14:10:01 -050065#ifdef HAVE_LIBTUNE2FS
Michael Rungeb278c252014-11-21 00:12:28 -080066#include "tune2fs.h"
Ethan Yonker7e1b9862015-03-19 14:10:01 -050067#endif
Doug Zongker8edb00c2009-06-11 17:21:44 -070068
Doug Zongker3d177d02010-07-01 09:18:44 -070069#ifdef USE_EXT4
70#include "make_ext4fs.h"
Doug Zongkerc9d6e4f2014-02-24 16:02:50 -080071#include "wipe.h"
Doug Zongker3d177d02010-07-01 09:18:44 -070072#endif
73
Tom Marshall981118e2017-10-25 20:27:08 +020074#include "otautil/ZipUtil.h"
Tao Baod33b2f82017-09-28 21:29:11 -070075#include "otafault/ota_io.h"
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070076#include "otautil/DirUtil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070077#include "otautil/error_code.h"
Tao Bao09e468f2017-09-29 14:39:33 -070078#include "otautil/print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070079#include "updater/updater.h"
Doug Zongker52b40362014-02-10 15:30:30 -080080
Tao Bao1107d962015-09-09 17:16:55 -070081// Send over the buffer to recovery though the command pipe.
82static void uiPrint(State* state, const std::string& buffer) {
Tao Bao039f2da2016-11-22 16:29:50 -080083 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
Tao Baob6918c72015-05-19 17:02:16 -070084
Tao Bao039f2da2016-11-22 16:29:50 -080085 // "line1\nline2\n" will be split into 3 tokens: "line1", "line2" and "".
86 // So skip sending empty strings to UI.
87 std::vector<std::string> lines = android::base::Split(buffer, "\n");
88 for (auto& line : lines) {
89 if (!line.empty()) {
90 fprintf(ui->cmd_pipe, "ui_print %s\n", line.c_str());
Michael Runge75480252014-10-22 19:48:41 -070091 }
Tao Bao039f2da2016-11-22 16:29:50 -080092 }
Tao Bao1107d962015-09-09 17:16:55 -070093
Tao Bao039f2da2016-11-22 16:29:50 -080094 // On the updater side, we need to dump the contents to stderr (which has
95 // been redirected to the log file). Because the recovery will only print
96 // the contents to screen when processing pipe command ui_print.
97 LOG(INFO) << buffer;
Michael Runge75480252014-10-22 19:48:41 -070098}
99
Simon Shields2e9747f2018-08-09 01:17:21 +1000100static bool is_dir(const std::string& dirpath) {
101 struct stat st;
102 return stat(dirpath.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
103}
104
105// Create all parent directories of name, if necessary.
106static bool make_parents(const std::string& name) {
107 size_t prev_end = 0;
108 while (prev_end < name.size()) {
109 size_t next_end = name.find('/', prev_end + 1);
110 if (next_end == std::string::npos) {
111 break;
112 }
113 std::string dir_path = name.substr(0, next_end);
114 if (!is_dir(dir_path)) {
115 int result = mkdir(dir_path.c_str(), 0700);
116 if (result != 0) {
117 PLOG(ERROR) << "failed to mkdir " << dir_path << " when make parents for " << name;
118 return false;
119 }
120
121 LOG(INFO) << "created [" << dir_path << "]";
122 }
123 prev_end = next_end;
124 }
125 return true;
126}
127
Elliott Hughes83ce7552016-06-30 09:28:42 -0700128void uiPrintf(State* _Nonnull state, const char* _Nonnull format, ...) {
Tao Bao039f2da2016-11-22 16:29:50 -0800129 std::string error_msg;
Tao Bao1107d962015-09-09 17:16:55 -0700130
Tao Bao039f2da2016-11-22 16:29:50 -0800131 va_list ap;
132 va_start(ap, format);
133 android::base::StringAppendV(&error_msg, format, ap);
134 va_end(ap);
Tao Bao1107d962015-09-09 17:16:55 -0700135
Tao Bao039f2da2016-11-22 16:29:50 -0800136 uiPrint(state, error_msg);
Michael Runge75480252014-10-22 19:48:41 -0700137}
138
Tianjie Xu5419ad32018-02-02 16:49:15 -0800139// This is the updater side handler for ui_print() in edify script. Contents will be sent over to
140// the recovery side for on-screen display.
141Value* UIPrintFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
142 std::vector<std::string> args;
143 if (!ReadArgs(state, argv, &args)) {
144 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name);
145 }
146
147 std::string buffer = android::base::Join(args, "");
148 uiPrint(state, buffer);
149 return StringValue(buffer);
Doug Zongker8edb00c2009-06-11 17:21:44 -0700150}
151
Tianjie Xu5419ad32018-02-02 16:49:15 -0800152// package_extract_file(package_file[, dest_file])
153// Extracts a single package_file from the update package and writes it to dest_file,
154// overwriting existing files if necessary. Without the dest_file argument, returns the
155// contents of the package file as a binary blob.
156Value* PackageExtractFileFn(const char* name, State* state,
157 const std::vector<std::unique_ptr<Expr>>& argv) {
158 if (argv.size() < 1 || argv.size() > 2) {
159 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 or 2 args, got %zu", name,
160 argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800161 }
Tianjie Xu5419ad32018-02-02 16:49:15 -0800162
163 if (argv.size() == 2) {
164 // The two-argument version extracts to a file.
165
166 std::vector<std::string> args;
167 if (!ReadArgs(state, argv, &args)) {
168 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse %zu args", name,
169 argv.size());
170 }
171 const std::string& zip_path = args[0];
172 const std::string& dest_path = args[1];
173
174 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip;
175 ZipString zip_string_path(zip_path.c_str());
176 ZipEntry entry;
177 if (FindEntry(za, zip_string_path, &entry) != 0) {
178 LOG(ERROR) << name << ": no " << zip_path << " in package";
179 return StringValue("");
180 }
181
182 unique_fd fd(TEMP_FAILURE_RETRY(
183 ota_open(dest_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)));
184 if (fd == -1) {
185 PLOG(ERROR) << name << ": can't open " << dest_path << " for write";
186 return StringValue("");
187 }
188
189 bool success = true;
190 int32_t ret = ExtractEntryToFile(za, &entry, fd);
191 if (ret != 0) {
192 LOG(ERROR) << name << ": Failed to extract entry \"" << zip_path << "\" ("
193 << entry.uncompressed_length << " bytes) to \"" << dest_path
194 << "\": " << ErrorCodeString(ret);
195 success = false;
196 }
197 if (ota_fsync(fd) == -1) {
198 PLOG(ERROR) << "fsync of \"" << dest_path << "\" failed";
199 success = false;
200 }
201 if (ota_close(fd) == -1) {
202 PLOG(ERROR) << "close of \"" << dest_path << "\" failed";
203 success = false;
204 }
205
206 return StringValue(success ? "t" : "");
207 } else {
208 // The one-argument version returns the contents of the file as the result.
209
210 std::vector<std::string> args;
211 if (!ReadArgs(state, argv, &args)) {
212 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse %zu args", name,
213 argv.size());
214 }
215 const std::string& zip_path = args[0];
216
217 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip;
218 ZipString zip_string_path(zip_path.c_str());
219 ZipEntry entry;
220 if (FindEntry(za, zip_string_path, &entry) != 0) {
221 return ErrorAbort(state, kPackageExtractFileFailure, "%s(): no %s in package", name,
222 zip_path.c_str());
223 }
224
225 std::string buffer;
226 buffer.resize(entry.uncompressed_length);
227
228 int32_t ret =
229 ExtractToMemory(za, &entry, reinterpret_cast<uint8_t*>(&buffer[0]), buffer.size());
230 if (ret != 0) {
231 return ErrorAbort(state, kPackageExtractFileFailure,
232 "%s: Failed to extract entry \"%s\" (%zu bytes) to memory: %s", name,
233 zip_path.c_str(), buffer.size(), ErrorCodeString(ret));
234 }
235
236 return new Value(VAL_BLOB, buffer);
237 }
238}
239
240// apply_patch(src_file, tgt_file, tgt_sha1, tgt_size, patch1_sha1, patch1_blob, [...])
241// Applies a binary patch to the src_file to produce the tgt_file. If the desired target is the
242// same as the source, pass "-" for tgt_file. tgt_sha1 and tgt_size are the expected final SHA1
243// hash and size of the target file. The remaining arguments must come in pairs: a SHA1 hash (a
244// 40-character hex string) and a blob. The blob is the patch to be applied when the source
245// file's current contents have the given SHA1.
246//
247// The patching is done in a safe manner that guarantees the target file either has the desired
248// SHA1 hash and size, or it is untouched -- it will not be left in an unrecoverable intermediate
249// state. If the process is interrupted during patching, the target file may be in an intermediate
250// state; a copy exists in the cache partition so restarting the update can successfully update
251// the file.
252Value* ApplyPatchFn(const char* name, State* state,
253 const std::vector<std::unique_ptr<Expr>>& argv) {
254 if (argv.size() < 6 || (argv.size() % 2) == 1) {
255 return ErrorAbort(state, kArgsParsingFailure,
256 "%s(): expected at least 6 args and an "
257 "even number, got %zu",
258 name, argv.size());
259 }
260
261 std::vector<std::string> args;
262 if (!ReadArgs(state, argv, &args, 0, 4)) {
263 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
264 }
265 const std::string& source_filename = args[0];
266 const std::string& target_filename = args[1];
267 const std::string& target_sha1 = args[2];
268 const std::string& target_size_str = args[3];
269
270 size_t target_size;
271 if (!android::base::ParseUint(target_size_str.c_str(), &target_size)) {
272 return ErrorAbort(state, kArgsParsingFailure, "%s(): can't parse \"%s\" as byte count", name,
273 target_size_str.c_str());
274 }
275
276 int patchcount = (argv.size() - 4) / 2;
277 std::vector<std::unique_ptr<Value>> arg_values;
278 if (!ReadValueArgs(state, argv, &arg_values, 4, argv.size() - 4)) {
279 return nullptr;
280 }
281
282 for (int i = 0; i < patchcount; ++i) {
283 if (arg_values[i * 2]->type != VAL_STRING) {
284 return ErrorAbort(state, kArgsParsingFailure, "%s(): sha-1 #%d is not string", name, i * 2);
285 }
286 if (arg_values[i * 2 + 1]->type != VAL_BLOB) {
287 return ErrorAbort(state, kArgsParsingFailure, "%s(): patch #%d is not blob", name, i * 2 + 1);
288 }
289 }
290
291 std::vector<std::string> patch_sha_str;
292 std::vector<std::unique_ptr<Value>> patches;
293 for (int i = 0; i < patchcount; ++i) {
294 patch_sha_str.push_back(arg_values[i * 2]->data);
295 patches.push_back(std::move(arg_values[i * 2 + 1]));
296 }
297
298 int result = applypatch(source_filename.c_str(), target_filename.c_str(), target_sha1.c_str(),
299 target_size, patch_sha_str, patches, nullptr);
300
301 return StringValue(result == 0 ? "t" : "");
302}
303
304// apply_patch_check(filename, [sha1, ...])
305// Returns true if the contents of filename or the temporary copy in the cache partition (if
306// present) have a SHA-1 checksum equal to one of the given sha1 values. sha1 values are
307// specified as 40 hex digits. This function differs from sha1_check(read_file(filename),
308// sha1 [, ...]) in that it knows to check the cache partition copy, so apply_patch_check() will
309// succeed even if the file was corrupted by an interrupted apply_patch() update.
310Value* ApplyPatchCheckFn(const char* name, State* state,
311 const std::vector<std::unique_ptr<Expr>>& argv) {
312 if (argv.size() < 1) {
313 return ErrorAbort(state, kArgsParsingFailure, "%s(): expected at least 1 arg, got %zu", name,
314 argv.size());
315 }
316
317 std::vector<std::string> args;
318 if (!ReadArgs(state, argv, &args, 0, 1)) {
319 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
320 }
321 const std::string& filename = args[0];
322
323 std::vector<std::string> sha1s;
324 if (argv.size() > 1 && !ReadArgs(state, argv, &sha1s, 1, argv.size() - 1)) {
325 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
326 }
327 int result = applypatch_check(filename.c_str(), sha1s);
328
329 return StringValue(result == 0 ? "t" : "");
330}
331
332// sha1_check(data)
333// to return the sha1 of the data (given in the format returned by
334// read_file).
335//
336// sha1_check(data, sha1_hex, [sha1_hex, ...])
337// returns the sha1 of the file if it matches any of the hex
338// strings passed, or "" if it does not equal any of them.
339//
340Value* Sha1CheckFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
341 if (argv.size() < 1) {
342 return ErrorAbort(state, kArgsParsingFailure, "%s() expects at least 1 arg", name);
343 }
344
345 std::vector<std::unique_ptr<Value>> args;
346 if (!ReadValueArgs(state, argv, &args)) {
347 return nullptr;
348 }
349
350 if (args[0]->type == VAL_INVALID) {
351 return StringValue("");
352 }
353 uint8_t digest[SHA_DIGEST_LENGTH];
354 SHA1(reinterpret_cast<const uint8_t*>(args[0]->data.c_str()), args[0]->data.size(), digest);
355
356 if (argv.size() == 1) {
357 return StringValue(print_sha1(digest));
358 }
359
360 for (size_t i = 1; i < argv.size(); ++i) {
361 uint8_t arg_digest[SHA_DIGEST_LENGTH];
362 if (args[i]->type != VAL_STRING) {
363 LOG(ERROR) << name << "(): arg " << i << " is not a string; skipping";
364 } else if (ParseSha1(args[i]->data.c_str(), arg_digest) != 0) {
365 // Warn about bad args and skip them.
366 LOG(ERROR) << name << "(): error parsing \"" << args[i]->data << "\" as sha-1; skipping";
367 } else if (memcmp(digest, arg_digest, SHA_DIGEST_LENGTH) == 0) {
368 // Found a match.
369 return args[i].release();
370 }
371 }
372
373 // Didn't match any of the hex strings; return false.
374 return StringValue("");
Doug Zongkera23075f2012-08-06 16:19:09 -0700375}
Doug Zongker8edb00c2009-06-11 17:21:44 -0700376
Doug Zongker9931f7f2009-06-10 14:11:53 -0700377// mount(fs_type, partition_type, location, mount_point)
Tao Bao0831d0b2016-11-03 23:25:04 -0700378// mount(fs_type, partition_type, location, mount_point, mount_options)
Doug Zongker9931f7f2009-06-10 14:11:53 -0700379
Doug Zongker9931f7f2009-06-10 14:11:53 -0700380// fs_type="ext4" partition_type="EMMC" location=device
Tianjie Xuc4447322017-03-06 14:44:59 -0800381Value* MountFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
382 if (argv.size() != 4 && argv.size() != 5) {
383 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 4-5 args, got %zu", name,
384 argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800385 }
386
387 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800388 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800389 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
390 }
391 const std::string& fs_type = args[0];
392 const std::string& partition_type = args[1];
393 const std::string& location = args[2];
394 const std::string& mount_point = args[3];
395 std::string mount_options;
396
Tianjie Xuc4447322017-03-06 14:44:59 -0800397 if (argv.size() == 5) {
Tao Bao039f2da2016-11-22 16:29:50 -0800398 mount_options = args[4];
399 }
400
401 if (fs_type.empty()) {
402 return ErrorAbort(state, kArgsParsingFailure, "fs_type argument to %s() can't be empty", name);
403 }
404 if (partition_type.empty()) {
405 return ErrorAbort(state, kArgsParsingFailure, "partition_type argument to %s() can't be empty",
406 name);
407 }
408 if (location.empty()) {
409 return ErrorAbort(state, kArgsParsingFailure, "location argument to %s() can't be empty", name);
410 }
411 if (mount_point.empty()) {
412 return ErrorAbort(state, kArgsParsingFailure, "mount_point argument to %s() can't be empty",
413 name);
414 }
415
416 {
417 char* secontext = nullptr;
418
419 if (sehandle) {
420 selabel_lookup(sehandle, &secontext, mount_point.c_str(), 0755);
421 setfscreatecon(secontext);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700422 }
423
Tao Bao039f2da2016-11-22 16:29:50 -0800424 mkdir(mount_point.c_str(), 0755);
Tianjie Xu5fe280a2016-10-17 18:15:20 -0700425
Tao Bao039f2da2016-11-22 16:29:50 -0800426 if (secontext) {
427 freecon(secontext);
428 setfscreatecon(nullptr);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700429 }
Tao Bao039f2da2016-11-22 16:29:50 -0800430 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700431
Tao Bao039f2da2016-11-22 16:29:50 -0800432 if (mount(location.c_str(), mount_point.c_str(), fs_type.c_str(),
433 MS_NOATIME | MS_NODEV | MS_NODIRATIME, mount_options.c_str()) < 0) {
Tao Bao0bbc7642017-03-29 23:57:47 -0700434 uiPrintf(state, "%s: Failed to mount %s at %s: %s", name, location.c_str(), mount_point.c_str(),
435 strerror(errno));
Tao Bao039f2da2016-11-22 16:29:50 -0800436 return StringValue("");
437 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700438
Tao Bao039f2da2016-11-22 16:29:50 -0800439 return StringValue(mount_point);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700440}
441
Doug Zongker9931f7f2009-06-10 14:11:53 -0700442// is_mounted(mount_point)
Tianjie Xuc4447322017-03-06 14:44:59 -0800443Value* IsMountedFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
444 if (argv.size() != 1) {
445 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800446 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700447
Tao Bao039f2da2016-11-22 16:29:50 -0800448 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800449 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800450 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
451 }
452 const std::string& mount_point = args[0];
453 if (mount_point.empty()) {
454 return ErrorAbort(state, kArgsParsingFailure,
455 "mount_point argument to unmount() can't be empty");
456 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700457
Tao Bao039f2da2016-11-22 16:29:50 -0800458 scan_mounted_volumes();
459 MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point.c_str());
460 if (vol == nullptr) {
461 return StringValue("");
462 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700463
Tao Bao039f2da2016-11-22 16:29:50 -0800464 return StringValue(mount_point);
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700465}
466
Tianjie Xuc4447322017-03-06 14:44:59 -0800467Value* UnmountFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
468 if (argv.size() != 1) {
469 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800470 }
471 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800472 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800473 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
474 }
475 const std::string& mount_point = args[0];
476 if (mount_point.empty()) {
477 return ErrorAbort(state, kArgsParsingFailure,
478 "mount_point argument to unmount() can't be empty");
479 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700480
Tao Bao039f2da2016-11-22 16:29:50 -0800481 scan_mounted_volumes();
482 MountedVolume* vol = find_mounted_volume_by_mount_point(mount_point.c_str());
483 if (vol == nullptr) {
Tao Bao0bbc7642017-03-29 23:57:47 -0700484 uiPrintf(state, "Failed to unmount %s: No such volume", mount_point.c_str());
Tao Bao039f2da2016-11-22 16:29:50 -0800485 return nullptr;
486 } else {
487 int ret = unmount_mounted_volume(vol);
488 if (ret != 0) {
Tao Bao0bbc7642017-03-29 23:57:47 -0700489 uiPrintf(state, "Failed to unmount %s: %s", mount_point.c_str(), strerror(errno));
Nick Kralevich6a821fe2014-10-23 20:36:42 -0700490 }
Tao Bao039f2da2016-11-22 16:29:50 -0800491 }
Nick Kralevich6a821fe2014-10-23 20:36:42 -0700492
Tao Bao039f2da2016-11-22 16:29:50 -0800493 return StringValue(mount_point);
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700494}
495
JP Abgrall37aedb32014-06-16 19:07:39 -0700496static int exec_cmd(const char* path, char* const argv[]) {
Tao Bao039f2da2016-11-22 16:29:50 -0800497 pid_t child;
498 if ((child = vfork()) == 0) {
499 execv(path, argv);
Tao Bao3da88012017-02-03 13:09:23 -0800500 _exit(EXIT_FAILURE);
Tao Bao039f2da2016-11-22 16:29:50 -0800501 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700502
Tao Bao039f2da2016-11-22 16:29:50 -0800503 int status;
504 waitpid(child, &status, 0);
505 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
506 LOG(ERROR) << path << " failed with status " << WEXITSTATUS(status);
507 }
508 return WEXITSTATUS(status);
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700509}
510
Doug Zongker9931f7f2009-06-10 14:11:53 -0700511// format(fs_type, partition_type, location, fs_size, mount_point)
512//
Tao Bao039f2da2016-11-22 16:29:50 -0800513// fs_type="ext4" partition_type="EMMC" location=device fs_size=<bytes> mount_point=<location>
514// fs_type="f2fs" partition_type="EMMC" location=device fs_size=<bytes> mount_point=<location>
JP Abgrall37aedb32014-06-16 19:07:39 -0700515// if fs_size == 0, then make fs uses the entire partition.
Doug Zongker9931f7f2009-06-10 14:11:53 -0700516// if fs_size > 0, that is the size to use
JP Abgrall37aedb32014-06-16 19:07:39 -0700517// if fs_size < 0, then reserve that many bytes at the end of the partition (not for "f2fs")
Tianjie Xuc4447322017-03-06 14:44:59 -0800518Value* FormatFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
519 if (argv.size() != 5) {
520 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 5 args, got %zu", name,
521 argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800522 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700523
Tao Bao039f2da2016-11-22 16:29:50 -0800524 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800525 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800526 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
527 }
528 const std::string& fs_type = args[0];
529 const std::string& partition_type = args[1];
530 const std::string& location = args[2];
531 const std::string& fs_size = args[3];
532 const std::string& mount_point = args[4];
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700533
Tao Bao039f2da2016-11-22 16:29:50 -0800534 if (fs_type.empty()) {
535 return ErrorAbort(state, kArgsParsingFailure, "fs_type argument to %s() can't be empty", name);
536 }
537 if (partition_type.empty()) {
538 return ErrorAbort(state, kArgsParsingFailure, "partition_type argument to %s() can't be empty",
539 name);
540 }
541 if (location.empty()) {
542 return ErrorAbort(state, kArgsParsingFailure, "location argument to %s() can't be empty", name);
543 }
544 if (mount_point.empty()) {
545 return ErrorAbort(state, kArgsParsingFailure, "mount_point argument to %s() can't be empty",
546 name);
547 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700548
Tao Bao039f2da2016-11-22 16:29:50 -0800549 int64_t size;
550 if (!android::base::ParseInt(fs_size, &size)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800551 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse int in %s", name,
Tao Bao039f2da2016-11-22 16:29:50 -0800552 fs_size.c_str());
553 }
554
555 if (fs_type == "ext4") {
Jin Qianac318082017-04-21 14:36:12 -0700556 const char* mke2fs_argv[] = { "/sbin/mke2fs_static", "-t", "ext4", "-b", "4096",
557 location.c_str(), nullptr, nullptr };
558 std::string size_str;
559 if (size != 0) {
560 size_str = std::to_string(size / 4096LL);
561 mke2fs_argv[6] = size_str.c_str();
562 }
563
564 int status = exec_cmd(mke2fs_argv[0], const_cast<char**>(mke2fs_argv));
Tao Bao039f2da2016-11-22 16:29:50 -0800565 if (status != 0) {
Jin Qian502fd1c2017-11-02 11:58:12 -0700566 LOG(ERROR) << name << ": mke2fs failed (" << status << ") on " << location;
567 return StringValue("");
Jin Qianac318082017-04-21 14:36:12 -0700568 }
569
Tao Bao7af933b2017-07-11 16:45:04 -0700570 const char* e2fsdroid_argv[] = { "/sbin/e2fsdroid_static", "-e", "-a", mount_point.c_str(),
Jin Qianac318082017-04-21 14:36:12 -0700571 location.c_str(), nullptr };
572 status = exec_cmd(e2fsdroid_argv[0], const_cast<char**>(e2fsdroid_argv));
573 if (status != 0) {
574 LOG(ERROR) << name << ": e2fsdroid failed (" << status << ") on " << location;
Tao Bao039f2da2016-11-22 16:29:50 -0800575 return StringValue("");
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700576 }
Tao Bao039f2da2016-11-22 16:29:50 -0800577 return StringValue(location);
578 } else if (fs_type == "f2fs") {
579 if (size < 0) {
580 LOG(ERROR) << name << ": fs_size can't be negative for f2fs: " << fs_size;
581 return StringValue("");
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700582 }
Tao Bao039f2da2016-11-22 16:29:50 -0800583 std::string num_sectors = std::to_string(size / 512);
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700584
Tao Bao039f2da2016-11-22 16:29:50 -0800585 const char* f2fs_path = "/sbin/mkfs.f2fs";
Jaegeuk Kim1a8bb0f2017-11-01 13:24:43 -0700586 const char* f2fs_argv[] = { "mkfs.f2fs",
587 "-d1",
588 "-f",
Jaegeuk Kim2e5dc842018-04-05 22:42:13 -0700589 "-O", "encrypt",
590 "-O", "quota",
591 "-O", "verity",
592 "-w", "512",
Jaegeuk Kim1a8bb0f2017-11-01 13:24:43 -0700593 location.c_str(),
594 (size < 512) ? nullptr : num_sectors.c_str(),
595 nullptr };
Tao Bao397a8132017-05-12 11:02:27 -0700596 int status = exec_cmd(f2fs_path, const_cast<char**>(f2fs_argv));
Tao Bao039f2da2016-11-22 16:29:50 -0800597 if (status != 0) {
598 LOG(ERROR) << name << ": mkfs.f2fs failed (" << status << ") on " << location;
599 return StringValue("");
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700600 }
Jaegeuk Kimc1c73112017-11-28 19:48:05 -0800601
602 const char* sload_argv[] = { "/sbin/sload.f2fs", "-t", mount_point.c_str(), location.c_str(),
603 nullptr };
604 status = exec_cmd(sload_argv[0], const_cast<char**>(sload_argv));
605 if (status != 0) {
606 LOG(ERROR) << name << ": sload.f2fs failed (" << status << ") on " << location;
607 return StringValue("");
608 }
609
Tao Bao039f2da2016-11-22 16:29:50 -0800610 return StringValue(location);
611 } else {
612 LOG(ERROR) << name << ": unsupported fs_type \"" << fs_type << "\" partition_type \""
613 << partition_type << "\"";
614 }
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700615
Tao Bao039f2da2016-11-22 16:29:50 -0800616 return nullptr;
Nick Kralevich5dbdef02013-09-07 14:41:06 -0700617}
Doug Zongker8edb00c2009-06-11 17:21:44 -0700618
Tom Marshallbf4f24f2017-08-23 18:14:00 +0000619// rename(src_name, dst_name)
620// Renames src_name to dst_name. It automatically creates the necessary directories for dst_name.
621// Example: rename("system/app/Hangouts/Hangouts.apk", "system/priv-app/Hangouts/Hangouts.apk")
622Value* RenameFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
623 if (argv.size() != 2) {
624 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
625 argv.size());
626 }
627
628 std::vector<std::string> args;
629 if (!ReadArgs(state, argv, &args)) {
630 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
631 }
632 const std::string& src_name = args[0];
633 const std::string& dst_name = args[1];
634
635 if (src_name.empty()) {
636 return ErrorAbort(state, kArgsParsingFailure, "src_name argument to %s() can't be empty", name);
637 }
638 if (dst_name.empty()) {
639 return ErrorAbort(state, kArgsParsingFailure, "dst_name argument to %s() can't be empty", name);
640 }
641 if (!make_parents(dst_name)) {
642 return ErrorAbort(state, kFileRenameFailure, "Creating parent of %s failed, error %s",
643 dst_name.c_str(), strerror(errno));
644 } else if (access(dst_name.c_str(), F_OK) == 0 && access(src_name.c_str(), F_OK) != 0) {
645 // File was already moved
646 return StringValue(dst_name);
647 } else if (rename(src_name.c_str(), dst_name.c_str()) != 0) {
648 return ErrorAbort(state, kFileRenameFailure, "Rename of %s to %s failed, error %s",
649 src_name.c_str(), dst_name.c_str(), strerror(errno));
650 }
651
652 return StringValue(dst_name);
653}
654
655// delete([filename, ...])
656// Deletes all the filenames listed. Returns the number of files successfully deleted.
657//
658// delete_recursive([dirname, ...])
659// Recursively deletes dirnames and all their contents. Returns the number of directories
660// successfully deleted.
661Value* DeleteFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
662 std::vector<std::string> paths;
663 if (!ReadArgs(state, argv, &paths)) {
664 return nullptr;
665 }
666
667 bool recursive = (strcmp(name, "delete_recursive") == 0);
668
669 int success = 0;
670 for (const auto& path : paths) {
671 if ((recursive ? dirUnlinkHierarchy(path.c_str()) : unlink(path.c_str())) == 0) {
672 ++success;
673 }
674 }
675
676 return StringValue(std::to_string(success));
677}
678
679
Tianjie Xuc4447322017-03-06 14:44:59 -0800680Value* ShowProgressFn(const char* name, State* state,
681 const std::vector<std::unique_ptr<Expr>>& argv) {
682 if (argv.size() != 2) {
683 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
684 argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800685 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700686
Tao Bao039f2da2016-11-22 16:29:50 -0800687 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800688 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800689 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
690 }
691 const std::string& frac_str = args[0];
692 const std::string& sec_str = args[1];
Tianjie Xu5fe280a2016-10-17 18:15:20 -0700693
Tao Bao039f2da2016-11-22 16:29:50 -0800694 double frac;
695 if (!android::base::ParseDouble(frac_str.c_str(), &frac)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800696 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse double in %s", name,
Tao Bao039f2da2016-11-22 16:29:50 -0800697 frac_str.c_str());
698 }
699 int sec;
700 if (!android::base::ParseInt(sec_str.c_str(), &sec)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800701 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse int in %s", name,
Tao Bao039f2da2016-11-22 16:29:50 -0800702 sec_str.c_str());
703 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700704
Tao Bao039f2da2016-11-22 16:29:50 -0800705 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
706 fprintf(ui->cmd_pipe, "progress %f %d\n", frac, sec);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700707
Tao Bao039f2da2016-11-22 16:29:50 -0800708 return StringValue(frac_str);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700709}
710
Tianjie Xu5419ad32018-02-02 16:49:15 -0800711Value* SetProgressFn(const char* name, State* state,
712 const std::vector<std::unique_ptr<Expr>>& argv) {
Tianjie Xuc4447322017-03-06 14:44:59 -0800713 if (argv.size() != 1) {
714 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -0800715 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700716
Tao Bao039f2da2016-11-22 16:29:50 -0800717 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800718 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800719 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
720 }
721 const std::string& frac_str = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -0700722
Tao Bao039f2da2016-11-22 16:29:50 -0800723 double frac;
724 if (!android::base::ParseDouble(frac_str.c_str(), &frac)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800725 return ErrorAbort(state, kArgsParsingFailure, "%s: failed to parse double in %s", name,
Tao Bao039f2da2016-11-22 16:29:50 -0800726 frac_str.c_str());
727 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700728
Tao Bao039f2da2016-11-22 16:29:50 -0800729 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
730 fprintf(ui->cmd_pipe, "set_progress %f\n", frac);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700731
Tao Bao039f2da2016-11-22 16:29:50 -0800732 return StringValue(frac_str);
Doug Zongker9931f7f2009-06-10 14:11:53 -0700733}
734
Tom Marshall981118e2017-10-25 20:27:08 +0200735// package_extract_dir(package_dir, dest_dir)
736// Extracts all files from the package underneath package_dir and writes them to the
737// corresponding tree beneath dest_dir. Any existing files are overwritten.
738// Example: package_extract_dir("system", "/system")
739//
740// Note: package_dir needs to be a relative path; dest_dir needs to be an absolute path.
741Value* PackageExtractDirFn(const char* name, State* state,
742 const std::vector<std::unique_ptr<Expr>>&argv) {
743 if (argv.size() != 2) {
744 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
745 argv.size());
746 }
747
748 std::vector<std::string> args;
749 if (!ReadArgs(state, argv, &args)) {
750 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
751 }
752 const std::string& zip_path = args[0];
753 const std::string& dest_path = args[1];
754
755 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip;
756
757 // To create a consistent system image, never use the clock for timestamps.
758 constexpr struct utimbuf timestamp = { 1217592000, 1217592000 }; // 8/1/2008 default
759
760 bool success = ExtractPackageRecursive(za, zip_path, dest_path, &timestamp, sehandle);
761
762 return StringValue(success ? "t" : "");
763}
764
Tao Baoef0eb3b2016-11-14 21:29:52 -0800765// package_extract_file(package_file[, dest_file])
766// Extracts a single package_file from the update package and writes it to dest_file,
767// overwriting existing files if necessary. Without the dest_file argument, returns the
768// contents of the package file as a binary blob.
Tianjie Xuc4447322017-03-06 14:44:59 -0800769Value* PackageExtractFileFn(const char* name, State* state,
770 const std::vector<std::unique_ptr<Expr>>& argv) {
771 if (argv.size() < 1 || argv.size() > 2) {
772 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 or 2 args, got %zu", name,
773 argv.size());
Tao Baoef0eb3b2016-11-14 21:29:52 -0800774 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700775
Tianjie Xuc4447322017-03-06 14:44:59 -0800776 if (argv.size() == 2) {
Tao Baoef0eb3b2016-11-14 21:29:52 -0800777 // The two-argument version extracts to a file.
778
779 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800780 if (!ReadArgs(state, argv, &args)) {
781 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse %zu args", name,
782 argv.size());
Doug Zongker8edb00c2009-06-11 17:21:44 -0700783 }
Tao Baoef0eb3b2016-11-14 21:29:52 -0800784 const std::string& zip_path = args[0];
785 const std::string& dest_path = args[1];
Doug Zongker8edb00c2009-06-11 17:21:44 -0700786
Tao Baoef0eb3b2016-11-14 21:29:52 -0800787 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip;
788 ZipString zip_string_path(zip_path.c_str());
789 ZipEntry entry;
790 if (FindEntry(za, zip_string_path, &entry) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800791 LOG(ERROR) << name << ": no " << zip_path << " in package";
Tao Baoef0eb3b2016-11-14 21:29:52 -0800792 return StringValue("");
Doug Zongker9931f7f2009-06-10 14:11:53 -0700793 }
Doug Zongker8edb00c2009-06-11 17:21:44 -0700794
Tao Bao358c2ec2016-11-28 11:48:43 -0800795 unique_fd fd(TEMP_FAILURE_RETRY(
796 ota_open(dest_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)));
Tao Baoef0eb3b2016-11-14 21:29:52 -0800797 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800798 PLOG(ERROR) << name << ": can't open " << dest_path << " for write";
Tao Baoef0eb3b2016-11-14 21:29:52 -0800799 return StringValue("");
800 }
801
802 bool success = true;
803 int32_t ret = ExtractEntryToFile(za, &entry, fd);
804 if (ret != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800805 LOG(ERROR) << name << ": Failed to extract entry \"" << zip_path << "\" ("
806 << entry.uncompressed_length << " bytes) to \"" << dest_path
807 << "\": " << ErrorCodeString(ret);
Tao Baoef0eb3b2016-11-14 21:29:52 -0800808 success = false;
809 }
810 if (ota_fsync(fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800811 PLOG(ERROR) << "fsync of \"" << dest_path << "\" failed";
Tao Baoef0eb3b2016-11-14 21:29:52 -0800812 success = false;
813 }
814 if (ota_close(fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800815 PLOG(ERROR) << "close of \"" << dest_path << "\" failed";
Tao Baoef0eb3b2016-11-14 21:29:52 -0800816 success = false;
817 }
818
819 return StringValue(success ? "t" : "");
820 } else {
821 // The one-argument version returns the contents of the file as the result.
822
823 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -0800824 if (!ReadArgs(state, argv, &args)) {
825 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse %zu args", name,
826 argv.size());
Tao Baoef0eb3b2016-11-14 21:29:52 -0800827 }
828 const std::string& zip_path = args[0];
829
830 ZipArchiveHandle za = static_cast<UpdaterInfo*>(state->cookie)->package_zip;
831 ZipString zip_string_path(zip_path.c_str());
832 ZipEntry entry;
833 if (FindEntry(za, zip_string_path, &entry) != 0) {
834 return ErrorAbort(state, kPackageExtractFileFailure, "%s(): no %s in package", name,
835 zip_path.c_str());
836 }
837
838 std::string buffer;
839 buffer.resize(entry.uncompressed_length);
840
841 int32_t ret = ExtractToMemory(za, &entry, reinterpret_cast<uint8_t*>(&buffer[0]), buffer.size());
842 if (ret != 0) {
843 return ErrorAbort(state, kPackageExtractFileFailure,
844 "%s: Failed to extract entry \"%s\" (%zu bytes) to memory: %s", name,
845 zip_path.c_str(), buffer.size(), ErrorCodeString(ret));
846 }
847
848 return new Value(VAL_BLOB, buffer);
849 }
Doug Zongker9931f7f2009-06-10 14:11:53 -0700850}
851
Tom Marshallbf4f24f2017-08-23 18:14:00 +0000852// symlink(target, [src1, src2, ...])
853// Creates all sources as symlinks to target. It unlinks any previously existing src1, src2, etc
854// before creating symlinks.
855Value* SymlinkFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
856 if (argv.size() == 0) {
857 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1+ args, got %zu", name, argv.size());
858 }
859 std::string target;
860 if (!Evaluate(state, argv[0], &target)) {
861 return nullptr;
862 }
863
864 std::vector<std::string> srcs;
865 if (!ReadArgs(state, argv, &srcs, 1, argv.size())) {
866 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name);
867 }
868
869 size_t bad = 0;
870 for (const auto& src : srcs) {
871 if (unlink(src.c_str()) == -1 && errno != ENOENT) {
872 PLOG(ERROR) << name << ": failed to remove " << src;
873 ++bad;
874 } else if (!make_parents(src)) {
875 LOG(ERROR) << name << ": failed to symlink " << src << " to " << target
876 << ": making parents failed";
877 ++bad;
878 } else if (symlink(target.c_str(), src.c_str()) == -1) {
879 PLOG(ERROR) << name << ": failed to symlink " << src << " to " << target;
880 ++bad;
881 }
882 }
883 if (bad != 0) {
884 return ErrorAbort(state, kSymlinkFailure, "%s: Failed to create %zu symlink(s)", name, bad);
885 }
886 return StringValue("t");
887}
888
889struct perm_parsed_args {
890 bool has_uid;
891 uid_t uid;
892 bool has_gid;
893 gid_t gid;
894 bool has_mode;
895 mode_t mode;
896 bool has_fmode;
897 mode_t fmode;
898 bool has_dmode;
899 mode_t dmode;
900 bool has_selabel;
901 const char* selabel;
902 bool has_capabilities;
903 uint64_t capabilities;
904};
905
906static struct perm_parsed_args ParsePermArgs(State * state,
907 const std::vector<std::string>& args) {
908 struct perm_parsed_args parsed;
909 int bad = 0;
910 static int max_warnings = 20;
911
912 memset(&parsed, 0, sizeof(parsed));
913
914 for (size_t i = 1; i < args.size(); i += 2) {
915 if (args[i] == "uid") {
916 int64_t uid;
917 if (sscanf(args[i + 1].c_str(), "%" SCNd64, &uid) == 1) {
918 parsed.uid = uid;
919 parsed.has_uid = true;
920 } else {
921 uiPrintf(state, "ParsePermArgs: invalid UID \"%s\"\n", args[i + 1].c_str());
922 bad++;
923 }
924 continue;
925 }
926 if (args[i] == "gid") {
927 int64_t gid;
928 if (sscanf(args[i + 1].c_str(), "%" SCNd64, &gid) == 1) {
929 parsed.gid = gid;
930 parsed.has_gid = true;
931 } else {
932 uiPrintf(state, "ParsePermArgs: invalid GID \"%s\"\n", args[i + 1].c_str());
933 bad++;
934 }
935 continue;
936 }
937 if (args[i] == "mode") {
938 int32_t mode;
939 if (sscanf(args[i + 1].c_str(), "%" SCNi32, &mode) == 1) {
940 parsed.mode = mode;
941 parsed.has_mode = true;
942 } else {
943 uiPrintf(state, "ParsePermArgs: invalid mode \"%s\"\n", args[i + 1].c_str());
944 bad++;
945 }
946 continue;
947 }
948 if (args[i] == "dmode") {
949 int32_t mode;
950 if (sscanf(args[i + 1].c_str(), "%" SCNi32, &mode) == 1) {
951 parsed.dmode = mode;
952 parsed.has_dmode = true;
953 } else {
954 uiPrintf(state, "ParsePermArgs: invalid dmode \"%s\"\n", args[i + 1].c_str());
955 bad++;
956 }
957 continue;
958 }
959 if (args[i] == "fmode") {
960 int32_t mode;
961 if (sscanf(args[i + 1].c_str(), "%" SCNi32, &mode) == 1) {
962 parsed.fmode = mode;
963 parsed.has_fmode = true;
964 } else {
965 uiPrintf(state, "ParsePermArgs: invalid fmode \"%s\"\n", args[i + 1].c_str());
966 bad++;
967 }
968 continue;
969 }
970 if (args[i] == "capabilities") {
971 int64_t capabilities;
972 if (sscanf(args[i + 1].c_str(), "%" SCNi64, &capabilities) == 1) {
973 parsed.capabilities = capabilities;
974 parsed.has_capabilities = true;
975 } else {
976 uiPrintf(state, "ParsePermArgs: invalid capabilities \"%s\"\n", args[i + 1].c_str());
977 bad++;
978 }
979 continue;
980 }
981 if (args[i] == "selabel") {
982 if (!args[i + 1].empty()) {
983 parsed.selabel = args[i + 1].c_str();
984 parsed.has_selabel = true;
985 } else {
986 uiPrintf(state, "ParsePermArgs: invalid selabel \"%s\"\n", args[i + 1].c_str());
987 bad++;
988 }
989 continue;
990 }
991 if (max_warnings != 0) {
992 printf("ParsedPermArgs: unknown key \"%s\", ignoring\n", args[i].c_str());
993 max_warnings--;
994 if (max_warnings == 0) {
995 LOG(INFO) << "ParsedPermArgs: suppressing further warnings";
996 }
997 }
998 }
999 return parsed;
1000}
1001
1002static int ApplyParsedPerms(State* state, const char* filename, const struct stat* statptr,
1003 struct perm_parsed_args parsed) {
1004 int bad = 0;
1005
1006 if (parsed.has_selabel) {
1007 if (lsetfilecon(filename, parsed.selabel) != 0) {
1008 uiPrintf(state, "ApplyParsedPerms: lsetfilecon of %s to %s failed: %s\n", filename,
1009 parsed.selabel, strerror(errno));
1010 bad++;
1011 }
1012 }
1013
1014 /* ignore symlinks */
1015 if (S_ISLNK(statptr->st_mode)) {
1016 return bad;
1017 }
1018
1019 if (parsed.has_uid) {
1020 if (chown(filename, parsed.uid, -1) < 0) {
1021 uiPrintf(state, "ApplyParsedPerms: chown of %s to %d failed: %s\n", filename, parsed.uid,
1022 strerror(errno));
1023 bad++;
1024 }
1025 }
1026
1027 if (parsed.has_gid) {
1028 if (chown(filename, -1, parsed.gid) < 0) {
1029 uiPrintf(state, "ApplyParsedPerms: chgrp of %s to %d failed: %s\n", filename, parsed.gid,
1030 strerror(errno));
1031 bad++;
1032 }
1033 }
1034
1035 if (parsed.has_mode) {
1036 if (chmod(filename, parsed.mode) < 0) {
1037 uiPrintf(state, "ApplyParsedPerms: chmod of %s to %d failed: %s\n", filename, parsed.mode,
1038 strerror(errno));
1039 bad++;
1040 }
1041 }
1042
1043 if (parsed.has_dmode && S_ISDIR(statptr->st_mode)) {
1044 if (chmod(filename, parsed.dmode) < 0) {
1045 uiPrintf(state, "ApplyParsedPerms: chmod of %s to %d failed: %s\n", filename, parsed.dmode,
1046 strerror(errno));
1047 bad++;
1048 }
1049 }
1050
1051 if (parsed.has_fmode && S_ISREG(statptr->st_mode)) {
1052 if (chmod(filename, parsed.fmode) < 0) {
1053 uiPrintf(state, "ApplyParsedPerms: chmod of %s to %d failed: %s\n", filename, parsed.fmode,
1054 strerror(errno));
1055 bad++;
1056 }
1057 }
1058
1059 if (parsed.has_capabilities && S_ISREG(statptr->st_mode)) {
1060 if (parsed.capabilities == 0) {
1061 if ((removexattr(filename, XATTR_NAME_CAPS) == -1) && (errno != ENODATA)) {
1062 // Report failure unless it's ENODATA (attribute not set)
1063 uiPrintf(state, "ApplyParsedPerms: removexattr of %s to %" PRIx64 " failed: %s\n", filename,
1064 parsed.capabilities, strerror(errno));
1065 bad++;
1066 }
1067 } else {
1068 struct vfs_cap_data cap_data;
1069 memset(&cap_data, 0, sizeof(cap_data));
1070 cap_data.magic_etc = VFS_CAP_REVISION | VFS_CAP_FLAGS_EFFECTIVE;
1071 cap_data.data[0].permitted = (uint32_t)(parsed.capabilities & 0xffffffff);
1072 cap_data.data[0].inheritable = 0;
1073 cap_data.data[1].permitted = (uint32_t)(parsed.capabilities >> 32);
1074 cap_data.data[1].inheritable = 0;
1075 if (setxattr(filename, XATTR_NAME_CAPS, &cap_data, sizeof(cap_data), 0) < 0) {
1076 uiPrintf(state, "ApplyParsedPerms: setcap of %s to %" PRIx64 " failed: %s\n", filename,
1077 parsed.capabilities, strerror(errno));
1078 bad++;
1079 }
1080 }
1081 }
1082
1083 return bad;
1084}
1085
1086// nftw doesn't allow us to pass along context, so we need to use
1087// global variables. *sigh*
1088static struct perm_parsed_args recursive_parsed_args;
1089static State* recursive_state;
1090
1091static int do_SetMetadataRecursive(const char* filename, const struct stat* statptr, int fileflags,
1092 struct FTW* pfwt) {
1093 return ApplyParsedPerms(recursive_state, filename, statptr, recursive_parsed_args);
1094}
1095
1096static Value* SetMetadataFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1097 if ((argv.size() % 2) != 1) {
1098 return ErrorAbort(state, kArgsParsingFailure, "%s() expects an odd number of arguments, got %zu",
1099 name, argv.size());
1100 }
1101
1102 std::vector<std::string> args;
1103 if (!ReadArgs(state, argv, &args)) {
1104 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1105 }
1106
1107 struct stat sb;
1108 if (lstat(args[0].c_str(), &sb) == -1) {
1109 return ErrorAbort(state, kSetMetadataFailure, "%s: Error on lstat of \"%s\": %s", name,
1110 args[0].c_str(), strerror(errno));
1111 }
1112
1113 struct perm_parsed_args parsed = ParsePermArgs(state, args);
1114 int bad = 0;
1115 bool recursive = (strcmp(name, "set_metadata_recursive") == 0);
1116
1117 if (recursive) {
1118 recursive_parsed_args = parsed;
1119 recursive_state = state;
1120 bad += nftw(args[0].c_str(), do_SetMetadataRecursive, 30, FTW_CHDIR | FTW_DEPTH | FTW_PHYS);
1121 memset(&recursive_parsed_args, 0, sizeof(recursive_parsed_args));
1122 recursive_state = NULL;
1123 } else {
1124 bad += ApplyParsedPerms(state, args[0].c_str(), &sb, parsed);
1125 }
1126
1127 if (bad > 0) {
1128 return ErrorAbort(state, kSetMetadataFailure, "%s: some changes failed", name);
1129 }
1130
1131 return StringValue("");
1132}
1133
Tianjie Xuc4447322017-03-06 14:44:59 -08001134Value* GetPropFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1135 if (argv.size() != 1) {
1136 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -08001137 }
1138 std::string key;
1139 if (!Evaluate(state, argv[0], &key)) {
1140 return nullptr;
1141 }
1142 std::string value = android::base::GetProperty(key, "");
Doug Zongker8edb00c2009-06-11 17:21:44 -07001143
Tao Bao039f2da2016-11-22 16:29:50 -08001144 return StringValue(value);
Doug Zongker8edb00c2009-06-11 17:21:44 -07001145}
1146
Doug Zongker47cace92009-06-18 10:11:50 -07001147// file_getprop(file, key)
1148//
1149// interprets 'file' as a getprop-style file (key=value pairs, one
Tao Bao51d516e2016-11-03 14:49:01 -07001150// per line. # comment lines, blank lines, lines without '=' ignored),
Michael Rungeaa1a31e2014-04-25 18:47:18 -07001151// and returns the value for 'key' (or "" if it isn't defined).
Tianjie Xu5419ad32018-02-02 16:49:15 -08001152Value* FileGetPropFn(const char* name, State* state,
1153 const std::vector<std::unique_ptr<Expr>>& argv) {
Tianjie Xuc4447322017-03-06 14:44:59 -08001154 if (argv.size() != 2) {
1155 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
1156 argv.size());
Tao Bao358c2ec2016-11-28 11:48:43 -08001157 }
1158
1159 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001160 if (!ReadArgs(state, argv, &args)) {
Tao Bao358c2ec2016-11-28 11:48:43 -08001161 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1162 }
1163 const std::string& filename = args[0];
1164 const std::string& key = args[1];
1165
1166 struct stat st;
1167 if (stat(filename.c_str(), &st) < 0) {
1168 return ErrorAbort(state, kFileGetPropFailure, "%s: failed to stat \"%s\": %s", name,
1169 filename.c_str(), strerror(errno));
1170 }
1171
1172 constexpr off_t MAX_FILE_GETPROP_SIZE = 65536;
1173 if (st.st_size > MAX_FILE_GETPROP_SIZE) {
1174 return ErrorAbort(state, kFileGetPropFailure, "%s too large for %s (max %lld)",
1175 filename.c_str(), name, static_cast<long long>(MAX_FILE_GETPROP_SIZE));
1176 }
1177
1178 std::string buffer(st.st_size, '\0');
1179 unique_file f(ota_fopen(filename.c_str(), "rb"));
1180 if (f == nullptr) {
1181 return ErrorAbort(state, kFileOpenFailure, "%s: failed to open %s: %s", name, filename.c_str(),
1182 strerror(errno));
1183 }
1184
1185 if (ota_fread(&buffer[0], 1, st.st_size, f.get()) != static_cast<size_t>(st.st_size)) {
1186 ErrorAbort(state, kFreadFailure, "%s: failed to read %zu bytes from %s", name,
1187 static_cast<size_t>(st.st_size), filename.c_str());
1188 return nullptr;
1189 }
1190
1191 ota_fclose(f);
1192
1193 std::vector<std::string> lines = android::base::Split(buffer, "\n");
1194 for (size_t i = 0; i < lines.size(); i++) {
1195 std::string line = android::base::Trim(lines[i]);
1196
1197 // comment or blank line: skip to next line
1198 if (line.empty() || line[0] == '#') {
1199 continue;
1200 }
1201 size_t equal_pos = line.find('=');
1202 if (equal_pos == std::string::npos) {
1203 continue;
Doug Zongker47cace92009-06-18 10:11:50 -07001204 }
1205
Tao Bao358c2ec2016-11-28 11:48:43 -08001206 // trim whitespace between key and '='
1207 std::string str = android::base::Trim(line.substr(0, equal_pos));
Doug Zongker47cace92009-06-18 10:11:50 -07001208
Tao Bao358c2ec2016-11-28 11:48:43 -08001209 // not the key we're looking for
1210 if (key != str) continue;
Doug Zongker47cace92009-06-18 10:11:50 -07001211
Tao Bao358c2ec2016-11-28 11:48:43 -08001212 return StringValue(android::base::Trim(line.substr(equal_pos + 1)));
1213 }
Doug Zongker47cace92009-06-18 10:11:50 -07001214
Tao Bao358c2ec2016-11-28 11:48:43 -08001215 return StringValue("");
Doug Zongker8edb00c2009-06-11 17:21:44 -07001216}
1217
Doug Zongker8edb00c2009-06-11 17:21:44 -07001218// apply_patch_space(bytes)
Tianjie Xu5419ad32018-02-02 16:49:15 -08001219Value* ApplyPatchSpaceFn(const char* name, State* state,
1220 const std::vector<std::unique_ptr<Expr>>& argv) {
Tianjie Xuc4447322017-03-06 14:44:59 -08001221 if (argv.size() != 1) {
1222 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 args, got %zu", name,
1223 argv.size());
1224 }
Tao Bao039f2da2016-11-22 16:29:50 -08001225 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001226 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001227 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1228 }
1229 const std::string& bytes_str = args[0];
Doug Zongkerc4351c72010-02-22 14:46:32 -08001230
Tao Bao039f2da2016-11-22 16:29:50 -08001231 size_t bytes;
1232 if (!android::base::ParseUint(bytes_str.c_str(), &bytes)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001233 return ErrorAbort(state, kArgsParsingFailure, "%s(): can't parse \"%s\" as byte count", name,
1234 bytes_str.c_str());
Tao Bao039f2da2016-11-22 16:29:50 -08001235 }
Doug Zongkerc4351c72010-02-22 14:46:32 -08001236
Tianjie Xu99b73be2017-11-28 17:23:06 -08001237 // Skip the cache size check if the update is a retry.
1238 if (state->is_retry || CacheSizeCheck(bytes) == 0) {
1239 return StringValue("t");
Tao Bao039f2da2016-11-22 16:29:50 -08001240 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001241 return StringValue("");
Doug Zongkerd9c9d102009-06-12 12:24:39 -07001242}
1243
Tianjie Xuc4447322017-03-06 14:44:59 -08001244Value* WipeCacheFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1245 if (!argv.empty()) {
1246 return ErrorAbort(state, kArgsParsingFailure, "%s() expects no args, got %zu", name,
1247 argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -08001248 }
1249 fprintf(static_cast<UpdaterInfo*>(state->cookie)->cmd_pipe, "wipe_cache\n");
1250 return StringValue("t");
Doug Zongkerd0181b82011-10-19 10:51:12 -07001251}
1252
Tianjie Xuc4447322017-03-06 14:44:59 -08001253Value* RunProgramFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1254 if (argv.size() < 1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001255 return ErrorAbort(state, kArgsParsingFailure, "%s() expects at least 1 arg", name);
1256 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001257
Tao Bao039f2da2016-11-22 16:29:50 -08001258 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001259 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001260 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1261 }
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001262
Tianjie Xuc4447322017-03-06 14:44:59 -08001263 char* args2[argv.size() + 1];
1264 for (size_t i = 0; i < argv.size(); i++) {
Tao Bao039f2da2016-11-22 16:29:50 -08001265 args2[i] = &args[i][0];
1266 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001267 args2[argv.size()] = nullptr;
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001268
Tianjie Xuc4447322017-03-06 14:44:59 -08001269 LOG(INFO) << "about to run program [" << args2[0] << "] with " << argv.size() << " args";
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001270
Tao Bao039f2da2016-11-22 16:29:50 -08001271 pid_t child = fork();
1272 if (child == 0) {
1273 execv(args2[0], args2);
1274 PLOG(ERROR) << "run_program: execv failed";
Tao Bao3da88012017-02-03 13:09:23 -08001275 _exit(EXIT_FAILURE);
Tao Bao039f2da2016-11-22 16:29:50 -08001276 }
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001277
Tao Bao039f2da2016-11-22 16:29:50 -08001278 int status;
1279 waitpid(child, &status, 0);
1280 if (WIFEXITED(status)) {
1281 if (WEXITSTATUS(status) != 0) {
1282 LOG(ERROR) << "run_program: child exited with status " << WEXITSTATUS(status);
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001283 }
Tao Bao039f2da2016-11-22 16:29:50 -08001284 } else if (WIFSIGNALED(status)) {
1285 LOG(ERROR) << "run_program: child terminated by signal " << WTERMSIG(status);
1286 }
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001287
Tao Bao039f2da2016-11-22 16:29:50 -08001288 return StringValue(std::to_string(status));
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001289}
1290
Hristo Bojinovdb314d62010-08-02 10:29:49 -07001291// Read a local file and return its contents (the Value* returned
Doug Zongker512536a2010-02-17 16:11:44 -08001292// is actually a FileContents*).
Tianjie Xuc4447322017-03-06 14:44:59 -08001293Value* ReadFileFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1294 if (argv.size() != 1) {
1295 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -08001296 }
Doug Zongker512536a2010-02-17 16:11:44 -08001297
Tao Bao039f2da2016-11-22 16:29:50 -08001298 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001299 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001300 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1301 }
1302 const std::string& filename = args[0];
Doug Zongker512536a2010-02-17 16:11:44 -08001303
Tao Bao039f2da2016-11-22 16:29:50 -08001304 Value* v = new Value(VAL_INVALID, "");
Doug Zongker512536a2010-02-17 16:11:44 -08001305
Tao Bao039f2da2016-11-22 16:29:50 -08001306 FileContents fc;
1307 if (LoadFileContents(filename.c_str(), &fc) == 0) {
Doug Zongker512536a2010-02-17 16:11:44 -08001308 v->type = VAL_BLOB;
Tao Bao039f2da2016-11-22 16:29:50 -08001309 v->data = std::string(fc.data.begin(), fc.data.end());
1310 }
1311 return v;
Doug Zongker512536a2010-02-17 16:11:44 -08001312}
Doug Zongker8edb00c2009-06-11 17:21:44 -07001313
Tao Bao1bf17722016-11-03 23:52:01 -07001314// write_value(value, filename)
1315// Writes 'value' to 'filename'.
1316// Example: write_value("960000", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")
Tianjie Xuc4447322017-03-06 14:44:59 -08001317Value* WriteValueFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1318 if (argv.size() != 2) {
1319 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
1320 argv.size());
Tao Baod0f30882016-11-03 23:52:01 -07001321 }
Tao Bao1bf17722016-11-03 23:52:01 -07001322
Tao Baod0f30882016-11-03 23:52:01 -07001323 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001324 if (!ReadArgs(state, argv, &args)) {
Tao Baod0f30882016-11-03 23:52:01 -07001325 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name);
1326 }
Tao Bao1bf17722016-11-03 23:52:01 -07001327
Tao Baod0f30882016-11-03 23:52:01 -07001328 const std::string& filename = args[1];
1329 if (filename.empty()) {
1330 return ErrorAbort(state, kArgsParsingFailure, "%s(): Filename cannot be empty", name);
1331 }
Tao Bao1bf17722016-11-03 23:52:01 -07001332
Tao Baod0f30882016-11-03 23:52:01 -07001333 const std::string& value = args[0];
1334 if (!android::base::WriteStringToFile(value, filename)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001335 PLOG(ERROR) << name << ": Failed to write to \"" << filename << "\"";
Tao Baod0f30882016-11-03 23:52:01 -07001336 return StringValue("");
1337 } else {
1338 return StringValue("t");
1339 }
Tao Bao1bf17722016-11-03 23:52:01 -07001340}
1341
Doug Zongkerc87bab12013-11-25 13:53:25 -08001342// Immediately reboot the device. Recovery is not finished normally,
1343// so if you reboot into recovery it will re-start applying the
1344// current package (because nothing has cleared the copy of the
1345// arguments stored in the BCB).
1346//
1347// The argument is the partition name passed to the android reboot
1348// property. It can be "recovery" to boot from the recovery
1349// partition, or "" (empty string) to boot from the regular boot
1350// partition.
Tianjie Xuc4447322017-03-06 14:44:59 -08001351Value* RebootNowFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1352 if (argv.size() != 2) {
1353 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
1354 argv.size());
Tao Baobedf5fc2016-11-18 12:01:26 -08001355 }
Doug Zongkerc87bab12013-11-25 13:53:25 -08001356
Tao Baobedf5fc2016-11-18 12:01:26 -08001357 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001358 if (!ReadArgs(state, argv, &args)) {
Tao Baobedf5fc2016-11-18 12:01:26 -08001359 return ErrorAbort(state, kArgsParsingFailure, "%s(): Failed to parse the argument(s)", name);
1360 }
1361 const std::string& filename = args[0];
1362 const std::string& property = args[1];
Doug Zongkerc87bab12013-11-25 13:53:25 -08001363
Tao Baobedf5fc2016-11-18 12:01:26 -08001364 // Zero out the 'command' field of the bootloader message. Leave the rest intact.
1365 bootloader_message boot;
1366 std::string err;
1367 if (!read_bootloader_message_from(&boot, filename, &err)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001368 LOG(ERROR) << name << "(): Failed to read from \"" << filename << "\": " << err;
Tao Baobedf5fc2016-11-18 12:01:26 -08001369 return StringValue("");
1370 }
1371 memset(boot.command, 0, sizeof(boot.command));
1372 if (!write_bootloader_message_to(boot, filename, &err)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001373 LOG(ERROR) << name << "(): Failed to write to \"" << filename << "\": " << err;
Tao Baobedf5fc2016-11-18 12:01:26 -08001374 return StringValue("");
1375 }
Doug Zongkerc87bab12013-11-25 13:53:25 -08001376
Dmitri Plotnikoved9db0f2017-04-18 08:28:26 -07001377 std::string reboot_cmd = "reboot," + property;
1378 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1379 reboot_cmd += ",quiescent";
1380 }
Tao Baobedf5fc2016-11-18 12:01:26 -08001381 android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_cmd);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001382
Tao Baobedf5fc2016-11-18 12:01:26 -08001383 sleep(5);
1384 return ErrorAbort(state, kRebootFailure, "%s() failed to reboot", name);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001385}
1386
1387// Store a string value somewhere that future invocations of recovery
1388// can access it. This value is called the "stage" and can be used to
1389// drive packages that need to do reboots in the middle of
1390// installation and keep track of where they are in the multi-stage
1391// install.
1392//
1393// The first argument is the block device for the misc partition
1394// ("/misc" in the fstab), which is where this value is stored. The
1395// second argument is the string to store; it should not exceed 31
1396// bytes.
Tianjie Xuc4447322017-03-06 14:44:59 -08001397Value* SetStageFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1398 if (argv.size() != 2) {
1399 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
1400 argv.size());
Tao Baobedf5fc2016-11-18 12:01:26 -08001401 }
Doug Zongkerc87bab12013-11-25 13:53:25 -08001402
Tao Baobedf5fc2016-11-18 12:01:26 -08001403 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001404 if (!ReadArgs(state, argv, &args)) {
Tao Baobedf5fc2016-11-18 12:01:26 -08001405 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1406 }
1407 const std::string& filename = args[0];
1408 const std::string& stagestr = args[1];
Doug Zongkerc87bab12013-11-25 13:53:25 -08001409
Tao Baobedf5fc2016-11-18 12:01:26 -08001410 // Store this value in the misc partition, immediately after the
1411 // bootloader message that the main recovery uses to save its
1412 // arguments in case of the device restarting midway through
1413 // package installation.
1414 bootloader_message boot;
1415 std::string err;
1416 if (!read_bootloader_message_from(&boot, filename, &err)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001417 LOG(ERROR) << name << "(): Failed to read from \"" << filename << "\": " << err;
Tao Baobedf5fc2016-11-18 12:01:26 -08001418 return StringValue("");
1419 }
1420 strlcpy(boot.stage, stagestr.c_str(), sizeof(boot.stage));
1421 if (!write_bootloader_message_to(boot, filename, &err)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001422 LOG(ERROR) << name << "(): Failed to write to \"" << filename << "\": " << err;
Tao Baobedf5fc2016-11-18 12:01:26 -08001423 return StringValue("");
1424 }
Doug Zongkerc87bab12013-11-25 13:53:25 -08001425
Tao Baobedf5fc2016-11-18 12:01:26 -08001426 return StringValue(filename);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001427}
1428
1429// Return the value most recently saved with SetStageFn. The argument
1430// is the block device for the misc partition.
Tianjie Xuc4447322017-03-06 14:44:59 -08001431Value* GetStageFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1432 if (argv.size() != 1) {
1433 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 1 arg, got %zu", name, argv.size());
Tao Baobedf5fc2016-11-18 12:01:26 -08001434 }
Doug Zongkerc87bab12013-11-25 13:53:25 -08001435
Tao Baobedf5fc2016-11-18 12:01:26 -08001436 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001437 if (!ReadArgs(state, argv, &args)) {
Tao Baobedf5fc2016-11-18 12:01:26 -08001438 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1439 }
1440 const std::string& filename = args[0];
Doug Zongkerc87bab12013-11-25 13:53:25 -08001441
Tao Baobedf5fc2016-11-18 12:01:26 -08001442 bootloader_message boot;
1443 std::string err;
1444 if (!read_bootloader_message_from(&boot, filename, &err)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001445 LOG(ERROR) << name << "(): Failed to read from \"" << filename << "\": " << err;
Tao Baobedf5fc2016-11-18 12:01:26 -08001446 return StringValue("");
1447 }
Doug Zongkerc87bab12013-11-25 13:53:25 -08001448
Tao Baobedf5fc2016-11-18 12:01:26 -08001449 return StringValue(boot.stage);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001450}
1451
Tianjie Xuc4447322017-03-06 14:44:59 -08001452Value* WipeBlockDeviceFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1453 if (argv.size() != 2) {
1454 return ErrorAbort(state, kArgsParsingFailure, "%s() expects 2 args, got %zu", name,
1455 argv.size());
Tao Bao358c2ec2016-11-28 11:48:43 -08001456 }
Doug Zongkerc9d6e4f2014-02-24 16:02:50 -08001457
Tao Bao358c2ec2016-11-28 11:48:43 -08001458 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001459 if (!ReadArgs(state, argv, &args)) {
Tao Bao358c2ec2016-11-28 11:48:43 -08001460 return ErrorAbort(state, kArgsParsingFailure, "%s() Failed to parse the argument(s)", name);
1461 }
1462 const std::string& filename = args[0];
1463 const std::string& len_str = args[1];
Doug Zongkerc9d6e4f2014-02-24 16:02:50 -08001464
Tao Bao358c2ec2016-11-28 11:48:43 -08001465 size_t len;
1466 if (!android::base::ParseUint(len_str.c_str(), &len)) {
1467 return nullptr;
1468 }
1469 unique_fd fd(ota_open(filename.c_str(), O_WRONLY, 0644));
1470 // The wipe_block_device function in ext4_utils returns 0 on success and 1
1471 // for failure.
1472 int status = wipe_block_device(fd, len);
1473 return StringValue((status == 0) ? "t" : "");
Doug Zongkerc9d6e4f2014-02-24 16:02:50 -08001474}
1475
Tianjie Xuc4447322017-03-06 14:44:59 -08001476Value* EnableRebootFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1477 if (!argv.empty()) {
1478 return ErrorAbort(state, kArgsParsingFailure, "%s() expects no args, got %zu", name,
1479 argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -08001480 }
1481 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1482 fprintf(ui->cmd_pipe, "enable_reboot\n");
1483 return StringValue("t");
Doug Zongkerc704e062014-05-23 08:40:35 -07001484}
1485
Tianjie Xuc4447322017-03-06 14:44:59 -08001486Value* Tune2FsFn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Ethan Yonker7e1b9862015-03-19 14:10:01 -05001487#ifdef HAVE_LIBTUNE2FS
Tianjie Xuc4447322017-03-06 14:44:59 -08001488 if (argv.empty()) {
1489 return ErrorAbort(state, kArgsParsingFailure, "%s() expects args, got %zu", name, argv.size());
Tao Bao039f2da2016-11-22 16:29:50 -08001490 }
Michael Rungeb278c252014-11-21 00:12:28 -08001491
Tao Bao039f2da2016-11-22 16:29:50 -08001492 std::vector<std::string> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001493 if (!ReadArgs(state, argv, &args)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001494 return ErrorAbort(state, kArgsParsingFailure, "%s() could not read args", name);
1495 }
Michael Rungeb278c252014-11-21 00:12:28 -08001496
Tianjie Xuc4447322017-03-06 14:44:59 -08001497 char* args2[argv.size() + 1];
Tao Bao039f2da2016-11-22 16:29:50 -08001498 // Tune2fs expects the program name as its args[0]
1499 args2[0] = const_cast<char*>(name);
1500 if (args2[0] == nullptr) {
1501 return nullptr;
1502 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001503 for (size_t i = 0; i < argv.size(); ++i) {
Tao Bao039f2da2016-11-22 16:29:50 -08001504 args2[i + 1] = &args[i][0];
1505 }
Michael Rungeb278c252014-11-21 00:12:28 -08001506
Tao Bao039f2da2016-11-22 16:29:50 -08001507 // tune2fs changes the file system parameters on an ext2 file system; it
1508 // returns 0 on success.
Tianjie Xuc4447322017-03-06 14:44:59 -08001509 int result = tune2fs_main(argv.size() + 1, args2);
Tao Bao039f2da2016-11-22 16:29:50 -08001510 if (result != 0) {
1511 return ErrorAbort(state, kTune2FsFailure, "%s() returned error code %d", name, result);
1512 }
1513 return StringValue("t");
Ethan Yonker7e1b9862015-03-19 14:10:01 -05001514#else
Ethan Yonker8373cfe2017-09-08 06:50:54 -05001515 return ErrorAbort(state, kTune2FsFailure, "%s() support not present, no libtune2fs", name);
Ethan Yonker7e1b9862015-03-19 14:10:01 -05001516#endif // HAVE_LIBTUNE2FS
Michael Rungeb278c252014-11-21 00:12:28 -08001517}
1518
Doug Zongker9931f7f2009-06-10 14:11:53 -07001519void RegisterInstallFunctions() {
Tao Bao039f2da2016-11-22 16:29:50 -08001520 RegisterFunction("mount", MountFn);
1521 RegisterFunction("is_mounted", IsMountedFn);
1522 RegisterFunction("unmount", UnmountFn);
1523 RegisterFunction("format", FormatFn);
1524 RegisterFunction("show_progress", ShowProgressFn);
1525 RegisterFunction("set_progress", SetProgressFn);
Tom Marshallbf4f24f2017-08-23 18:14:00 +00001526 RegisterFunction("delete", DeleteFn);
1527 RegisterFunction("delete_recursive", DeleteFn);
Tom Marshall981118e2017-10-25 20:27:08 +02001528 RegisterFunction("package_extract_dir", PackageExtractDirFn);
Tao Bao039f2da2016-11-22 16:29:50 -08001529 RegisterFunction("package_extract_file", PackageExtractFileFn);
Tom Marshallbf4f24f2017-08-23 18:14:00 +00001530 RegisterFunction("symlink", SymlinkFn);
1531
1532 // Usage:
1533 // set_metadata("filename", "key1", "value1", "key2", "value2", ...)
1534 // Example:
1535 // set_metadata("/system/bin/netcfg", "uid", 0, "gid", 3003, "mode", 02750, "selabel",
1536 // "u:object_r:system_file:s0", "capabilities", 0x0);
1537 RegisterFunction("set_metadata", SetMetadataFn);
1538
1539 // Usage:
1540 // set_metadata_recursive("dirname", "key1", "value1", "key2", "value2", ...)
1541 // Example:
1542 // set_metadata_recursive("/system", "uid", 0, "gid", 0, "fmode", 0644, "dmode", 0755,
1543 // "selabel", "u:object_r:system_file:s0", "capabilities", 0x0);
1544 RegisterFunction("set_metadata_recursive", SetMetadataFn);
Nick Kralevich5dbdef02013-09-07 14:41:06 -07001545
Tao Bao039f2da2016-11-22 16:29:50 -08001546 RegisterFunction("getprop", GetPropFn);
1547 RegisterFunction("file_getprop", FileGetPropFn);
Nick Kralevich5dbdef02013-09-07 14:41:06 -07001548
Tao Bao039f2da2016-11-22 16:29:50 -08001549 RegisterFunction("apply_patch", ApplyPatchFn);
1550 RegisterFunction("apply_patch_check", ApplyPatchCheckFn);
1551 RegisterFunction("apply_patch_space", ApplyPatchSpaceFn);
Nick Kralevich5dbdef02013-09-07 14:41:06 -07001552
Tao Bao039f2da2016-11-22 16:29:50 -08001553 RegisterFunction("wipe_block_device", WipeBlockDeviceFn);
Doug Zongker8edb00c2009-06-11 17:21:44 -07001554
Tao Bao039f2da2016-11-22 16:29:50 -08001555 RegisterFunction("read_file", ReadFileFn);
1556 RegisterFunction("sha1_check", Sha1CheckFn);
Tom Marshallbf4f24f2017-08-23 18:14:00 +00001557 RegisterFunction("rename", RenameFn);
Tao Bao039f2da2016-11-22 16:29:50 -08001558 RegisterFunction("write_value", WriteValueFn);
Doug Zongkerd9c9d102009-06-12 12:24:39 -07001559
Tao Bao039f2da2016-11-22 16:29:50 -08001560 RegisterFunction("wipe_cache", WipeCacheFn);
Doug Zongker52b40362014-02-10 15:30:30 -08001561
Tao Bao039f2da2016-11-22 16:29:50 -08001562 RegisterFunction("ui_print", UIPrintFn);
Doug Zongker512536a2010-02-17 16:11:44 -08001563
Tao Bao039f2da2016-11-22 16:29:50 -08001564 RegisterFunction("run_program", RunProgramFn);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001565
Tao Bao039f2da2016-11-22 16:29:50 -08001566 RegisterFunction("reboot_now", RebootNowFn);
1567 RegisterFunction("get_stage", GetStageFn);
1568 RegisterFunction("set_stage", SetStageFn);
Doug Zongkera3f89ea2009-09-10 14:10:48 -07001569
Tao Bao039f2da2016-11-22 16:29:50 -08001570 RegisterFunction("enable_reboot", EnableRebootFn);
1571 RegisterFunction("tune2fs", Tune2FsFn);
Doug Zongker9931f7f2009-06-10 14:11:53 -07001572}