blob: ccdbba576c8796e68171513b43b1fdf6c8f65400 [file] [log] [blame]
Dees_Troy51a0e822012-09-05 15:24:24 -04001/*
2 * Copyright (C) 2011 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 <assert.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <paths.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/stat.h>
26#include <sys/types.h>
27#include <sys/wait.h>
28#include <unistd.h>
29
30#include <ctype.h>
31#include "cutils/misc.h"
32#include "cutils/properties.h"
33#include <dirent.h>
34#include <getopt.h>
35#include <linux/input.h>
36#include <signal.h>
37#include <sys/limits.h>
38#include <termios.h>
39#include <time.h>
40#include <sys/vfs.h>
41
42#include "tw_reboot.h"
43#include "bootloader.h"
44#include "common.h"
45#include "extra-functions.h"
46#include "cutils/properties.h"
47#include "install.h"
48#include "minuitwrp/minui.h"
49#include "minzip/DirUtil.h"
50#include "minzip/Zip.h"
51#include "recovery_ui.h"
52#include "roots.h"
53#include "data.h"
54#include "variables.h"
Dees_Troy7d15c252012-09-05 20:47:21 -040055#include "install.h"
Dees_Troy51a0e822012-09-05 15:24:24 -040056
57//kang system() from bionic/libc/unistd and rename it __system() so we can be even more hackish :)
58#undef _PATH_BSHELL
59#define _PATH_BSHELL "/sbin/sh"
60
61static const char *SIDELOAD_TEMP_DIR = "/tmp/sideload";
62extern char **environ;
63
64int __system(const char *command) {
65 pid_t pid;
66 sig_t intsave, quitsave;
67 sigset_t mask, omask;
68 int pstat;
69 char *argp[] = {"sh", "-c", NULL, NULL};
70
71 if (!command) /* just checking... */
72 return(1);
73
74 argp[2] = (char *)command;
75
76 sigemptyset(&mask);
77 sigaddset(&mask, SIGCHLD);
78 sigprocmask(SIG_BLOCK, &mask, &omask);
79 switch (pid = vfork()) {
80 case -1: /* error */
81 sigprocmask(SIG_SETMASK, &omask, NULL);
82 return(-1);
83 case 0: /* child */
84 sigprocmask(SIG_SETMASK, &omask, NULL);
85 execve(_PATH_BSHELL, argp, environ);
86 _exit(127);
87 }
88
89 intsave = (sig_t) bsd_signal(SIGINT, SIG_IGN);
90 quitsave = (sig_t) bsd_signal(SIGQUIT, SIG_IGN);
91 pid = waitpid(pid, (int *)&pstat, 0);
92 sigprocmask(SIG_SETMASK, &omask, NULL);
93 (void)bsd_signal(SIGINT, intsave);
94 (void)bsd_signal(SIGQUIT, quitsave);
95 return (pid == -1 ? -1 : pstat);
96}
97
98static struct pid {
99 struct pid *next;
100 FILE *fp;
101 pid_t pid;
102} *pidlist;
103
104FILE *__popen(const char *program, const char *type) {
105 struct pid * volatile cur;
106 FILE *iop;
107 int pdes[2];
108 pid_t pid;
109
110 if ((*type != 'r' && *type != 'w') || type[1] != '\0') {
111 errno = EINVAL;
112 return (NULL);
113 }
114
115 if ((cur = malloc(sizeof(struct pid))) == NULL)
116 return (NULL);
117
118 if (pipe(pdes) < 0) {
119 free(cur);
120 return (NULL);
121 }
122
123 switch (pid = vfork()) {
124 case -1: /* Error. */
125 (void)close(pdes[0]);
126 (void)close(pdes[1]);
127 free(cur);
128 return (NULL);
129 /* NOTREACHED */
130 case 0: /* Child. */
131 {
132 struct pid *pcur;
133 /*
134 * because vfork() instead of fork(), must leak FILE *,
135 * but luckily we are terminally headed for an execl()
136 */
137 for (pcur = pidlist; pcur; pcur = pcur->next)
138 close(fileno(pcur->fp));
139
140 if (*type == 'r') {
141 int tpdes1 = pdes[1];
142
143 (void) close(pdes[0]);
144 /*
145 * We must NOT modify pdes, due to the
146 * semantics of vfork.
147 */
148 if (tpdes1 != STDOUT_FILENO) {
149 (void)dup2(tpdes1, STDOUT_FILENO);
150 (void)close(tpdes1);
151 tpdes1 = STDOUT_FILENO;
152 }
153 } else {
154 (void)close(pdes[1]);
155 if (pdes[0] != STDIN_FILENO) {
156 (void)dup2(pdes[0], STDIN_FILENO);
157 (void)close(pdes[0]);
158 }
159 }
160 execl(_PATH_BSHELL, "sh", "-c", program, (char *)NULL);
161 _exit(127);
162 /* NOTREACHED */
163 }
164 }
165
166 /* Parent; assume fdopen can't fail. */
167 if (*type == 'r') {
168 iop = fdopen(pdes[0], type);
169 (void)close(pdes[1]);
170 } else {
171 iop = fdopen(pdes[1], type);
172 (void)close(pdes[0]);
173 }
174
175 /* Link into list of file descriptors. */
176 cur->fp = iop;
177 cur->pid = pid;
178 cur->next = pidlist;
179 pidlist = cur;
180
181 return (iop);
182}
183
184/*
185 * pclose --
186 * Pclose returns -1 if stream is not associated with a `popened' command,
187 * if already `pclosed', or waitpid returns an error.
188 */
189int __pclose(FILE *iop) {
190 struct pid *cur, *last;
191 int pstat;
192 pid_t pid;
193
194 /* Find the appropriate file pointer. */
195 for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
196 if (cur->fp == iop)
197 break;
198
199 if (cur == NULL)
200 return (-1);
201
202 (void)fclose(iop);
203
204 do {
205 pid = waitpid(cur->pid, &pstat, 0);
206 } while (pid == -1 && errno == EINTR);
207
208 /* Remove the entry from the linked list. */
209 if (last == NULL)
210 pidlist = cur->next;
211 else
212 last->next = cur->next;
213 free(cur);
214
215 return (pid == -1 ? -1 : pstat);
216}
217
218char* sanitize_device_id(char* id) {
219 const char* whitelist ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._";
220 char* c = id;
221 char* str = (int*) calloc(50, sizeof *id);
222 while (*c)
223 {
224 if (strchr(whitelist, *c))
225 {
226 strncat(str, c, 1);
227 }
228 c++;
229 }
230 return str;
231}
232
233#define CMDLINE_SERIALNO "androidboot.serialno="
234#define CMDLINE_SERIALNO_LEN (strlen(CMDLINE_SERIALNO))
235#define CPUINFO_SERIALNO "Serial"
236#define CPUINFO_SERIALNO_LEN (strlen(CPUINFO_SERIALNO))
237#define CPUINFO_HARDWARE "Hardware"
238#define CPUINFO_HARDWARE_LEN (strlen(CPUINFO_HARDWARE))
239
240void get_device_id() {
241 FILE *fp;
242 char line[2048];
243 char hardware_id[32];
244 char* token;
245 char* new_device_id;
246
247 // Assign a blank device_id to start with
248 device_id[0] = 0;
249
250 // First, try the cmdline to see if the serial number was supplied
251 fp = fopen("/proc/cmdline", "rt");
252 if (fp != NULL)
253 {
254 // First step, read the line. For cmdline, it's one long line
255 fgets(line, sizeof(line), fp);
256 fclose(fp);
257
258 // Now, let's tokenize the string
259 token = strtok(line, " ");
260
261 // Let's walk through the line, looking for the CMDLINE_SERIALNO token
262 while (token)
263 {
264 // We don't need to verify the length of token, because if it's too short, it will mismatch CMDLINE_SERIALNO at the NULL
265 if (memcmp(token, CMDLINE_SERIALNO, CMDLINE_SERIALNO_LEN) == 0)
266 {
267 // We found the serial number!
268 strcpy(device_id, token + CMDLINE_SERIALNO_LEN);
269 new_device_id = sanitize_device_id(device_id);
270 strcpy(device_id, new_device_id);
271 free(new_device_id);
272 return;
273 }
274 token = strtok(NULL, " ");
275 }
276 }
277
278 // Now we'll try cpuinfo for a serial number
279 fp = fopen("/proc/cpuinfo", "rt");
280 if (fp != NULL)
281 {
282 while (fgets(line, sizeof(line), fp) != NULL) { // First step, read the line.
283 if (memcmp(line, CPUINFO_SERIALNO, CPUINFO_SERIALNO_LEN) == 0) // check the beginning of the line for "Serial"
284 {
285 // We found the serial number!
286 token = line + CPUINFO_SERIALNO_LEN; // skip past "Serial"
287 while ((*token > 0 && *token <= 32 ) || *token == ':') token++; // skip over all spaces and the colon
288 if (*token != 0) {
289 token[30] = 0;
290 if (token[strlen(token)-1] == 10) { // checking for endline chars and dropping them from the end of the string if needed
291 memset(device_id, 0, sizeof(device_id));
292 strncpy(device_id, token, strlen(token) - 1);
293 } else {
294 strcpy(device_id, token);
295 }
296 LOGI("=> serial from cpuinfo: '%s'\n", device_id);
297 fclose(fp);
298 new_device_id = sanitize_device_id(device_id);
299 strcpy(device_id, new_device_id);
300 free(new_device_id);
301 return;
302 }
303 } else if (memcmp(line, CPUINFO_HARDWARE, CPUINFO_HARDWARE_LEN) == 0) {// We're also going to look for the hardware line in cpuinfo and save it for later in case we don't find the device ID
304 // We found the hardware ID
305 token = line + CPUINFO_HARDWARE_LEN; // skip past "Hardware"
306 while ((*token > 0 && *token <= 32 ) || *token == ':') token++; // skip over all spaces and the colon
307 if (*token != 0) {
308 token[30] = 0;
309 if (token[strlen(token)-1] == 10) { // checking for endline chars and dropping them from the end of the string if needed
310 memset(hardware_id, 0, sizeof(hardware_id));
311 strncpy(hardware_id, token, strlen(token) - 1);
312 } else {
313 strcpy(hardware_id, token);
314 }
315 LOGI("=> hardware id from cpuinfo: '%s'\n", hardware_id);
316 }
317 }
318 }
319 fclose(fp);
320 }
321
322 if (hardware_id[0] != 0) {
323 LOGW("\nusing hardware id for device id: '%s'\n", hardware_id);
324 strcpy(device_id, hardware_id);
325 new_device_id = sanitize_device_id(device_id);
326 strcpy(device_id, new_device_id);
327 free(new_device_id);
328 return;
329 }
330
331 strcpy(device_id, "serialno");
332 LOGE("=> device id not found, using '%s'.", device_id);
333 return;
334}
335
336char* get_path (char* path) {
337 char *s;
338
339 /* Go to the end of the string. */
340 s = path + strlen(path) - 1;
341
342 /* Strip off trailing /s (unless it is also the leading /). */
343 while (path < s && s[0] == '/')
344 s--;
345
346 /* Strip the last component. */
347 while (path <= s && s[0] != '/')
348 s--;
349
350 while (path < s && s[0] == '/')
351 s--;
352
353 if (s < path)
354 return ".";
355
356 s[1] = '\0';
357 return path;
358}
359
360char* basename(char* name) {
361 const char* base;
362 for (base = name; *name; name++)
363 {
364 if(*name == '/')
365 {
366 base = name + 1;
367 }
368 }
369 return (char *) base;
370}
371
372/*
373 Checks md5 for a path
374 Return values:
375 -1 : MD5 does not exist
376 0 : Failed
377 1 : Success
378*/
379int check_md5(char* path) {
380 int o;
381 char cmd[PATH_MAX + 30];
382 char md5file[PATH_MAX + 40];
383 strcpy(md5file, path);
384 strcat(md5file, ".md5");
385 char dirpath[PATH_MAX];
386 char* file;
387 if (access(md5file, F_OK ) != -1) {
388 strcpy(dirpath, md5file);
389 get_path(dirpath);
390 chdir(dirpath);
391 file = basename(md5file);
392 sprintf(cmd, "/sbin/busybox md5sum -c '%s'", file);
393 FILE * cs = __popen(cmd, "r");
394 char cs_s[PATH_MAX + 50];
395 fgets(cs_s, PATH_MAX + 50, cs);
396 char* OK = strstr(cs_s, "OK");
397 if (OK != NULL) {
398 printf("MD5 is good. returning 1\n");
399 o = 1;
400 }
401 else {
402 printf("MD5 is bad. return -2\n");
403 o = -2;
404 }
405
406 __pclose(cs);
407 }
408 else {
409 //No md5 file
410 printf("setting o to -1\n");
411 o = -1;
412 }
413
414 return o;
415}
416
Dees_Troy7d15c252012-09-05 20:47:21 -0400417static int really_install_package(const char *path, int* wipe_cache)
418{
419 //ui->SetBackground(RecoveryUI::INSTALLING);
420 LOGI("Finding update package...\n");
421 //ui->SetProgressType(RecoveryUI::INDETERMINATE);
422 LOGI("Update location: %s\n", path);
423
424 if (ensure_path_mounted(path) != 0) {
425 LOGE("Can't mount %s\n", path);
426 return INSTALL_CORRUPT;
427 }
428
429 LOGI("Opening update package...\n");
430
431 int numKeys;
432 /*RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
433 if (loadedKeys == NULL) {
434 LOGE("Failed to load keys\n");
435 return INSTALL_CORRUPT;
436 }
437 LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);*/
438
439 // Give verification half the progress bar...
440 LOGI("Verifying update package...\n");
441 //ui->SetProgressType(RecoveryUI::DETERMINATE);
442 //ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
443
444 int err;
445 /*err = verify_file(path, loadedKeys, numKeys);
446 free(loadedKeys);
447 LOGI("verify_file returned %d\n", err);
448 if (err != VERIFY_SUCCESS) {
449 LOGE("signature verification failed\n");
450 return INSTALL_CORRUPT;
451 }*/
452
453 /* Try to open the package.
454 */
455 ZipArchive zip;
456 err = mzOpenZipArchive(path, &zip);
457 if (err != 0) {
458 LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
459 return INSTALL_CORRUPT;
460 }
461
462 /* Verify and install the contents of the package.
463 */
464 LOGI("Installing update...\n");
465 return try_update_binary(path, &zip, wipe_cache);
466}
467
Dees_Troy51a0e822012-09-05 15:24:24 -0400468static void set_sdcard_update_bootloader_message() {
469 struct bootloader_message boot;
470 memset(&boot, 0, sizeof(boot));
471 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
472 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
473 set_bootloader_message(&boot);
474}
475
476static char* copy_sideloaded_package(const char* original_path) {
477 if (ensure_path_mounted(original_path) != 0) {
478 LOGE("Can't mount %s\n", original_path);
479 return NULL;
480 }
481
482 if (ensure_path_mounted(SIDELOAD_TEMP_DIR) != 0) {
483 LOGE("Can't mount %s\n", SIDELOAD_TEMP_DIR);
484 return NULL;
485 }
486
487 if (mkdir(SIDELOAD_TEMP_DIR, 0700) != 0) {
488 if (errno != EEXIST) {
489 LOGE("Can't mkdir %s (%s)\n", SIDELOAD_TEMP_DIR, strerror(errno));
490 return NULL;
491 }
492 }
493
494 // verify that SIDELOAD_TEMP_DIR is exactly what we expect: a
495 // directory, owned by root, readable and writable only by root.
496 struct stat st;
497 if (stat(SIDELOAD_TEMP_DIR, &st) != 0) {
498 LOGE("failed to stat %s (%s)\n", SIDELOAD_TEMP_DIR, strerror(errno));
499 return NULL;
500 }
501 if (!S_ISDIR(st.st_mode)) {
502 LOGE("%s isn't a directory\n", SIDELOAD_TEMP_DIR);
503 return NULL;
504 }
505 if ((st.st_mode & 0777) != 0700) {
506 LOGE("%s has perms %o\n", SIDELOAD_TEMP_DIR, st.st_mode);
507 return NULL;
508 }
509 if (st.st_uid != 0) {
510 LOGE("%s owned by %lu; not root\n", SIDELOAD_TEMP_DIR, st.st_uid);
511 return NULL;
512 }
513
514 char copy_path[PATH_MAX];
515 strcpy(copy_path, SIDELOAD_TEMP_DIR);
516 strcat(copy_path, "/package.zip");
517
518 char* buffer = malloc(BUFSIZ);
519 if (buffer == NULL) {
520 LOGE("Failed to allocate buffer\n");
521 return NULL;
522 }
523
524 size_t read;
525 FILE* fin = fopen(original_path, "rb");
526 if (fin == NULL) {
527 LOGE("Failed to open %s (%s)\n", original_path, strerror(errno));
528 return NULL;
529 }
530 FILE* fout = fopen(copy_path, "wb");
531 if (fout == NULL) {
532 LOGE("Failed to open %s (%s)\n", copy_path, strerror(errno));
533 return NULL;
534 }
535
536 while ((read = fread(buffer, 1, BUFSIZ, fin)) > 0) {
537 if (fwrite(buffer, 1, read, fout) != read) {
538 LOGE("Short write of %s (%s)\n", copy_path, strerror(errno));
539 return NULL;
540 }
541 }
542
543 free(buffer);
544
545 if (fclose(fout) != 0) {
546 LOGE("Failed to close %s (%s)\n", copy_path, strerror(errno));
547 return NULL;
548 }
549
550 if (fclose(fin) != 0) {
551 LOGE("Failed to close %s (%s)\n", original_path, strerror(errno));
552 return NULL;
553 }
554
555 // "adb push" is happy to overwrite read-only files when it's
556 // running as root, but we'll try anyway.
557 if (chmod(copy_path, 0400) != 0) {
558 LOGE("Failed to chmod %s (%s)\n", copy_path, strerror(errno));
559 return NULL;
560 }
561
562 return strdup(copy_path);
563}
564
565int install_zip_package(const char* zip_path_filename) {
566 int result = 0;
567
568 //mount_current_storage();
569 int md5_req = DataManager_GetIntValue(TW_FORCE_MD5_CHECK_VAR);
570 if (md5_req == 1) {
571 ui_print("\n-- Verify md5 for %s", zip_path_filename);
572 int md5chk = check_md5((char*) zip_path_filename);
573 if (md5chk == 1) {
574 ui_print("\n-- Md5 verified, continue");
575 result = 0;
576 }
577 else if (md5chk == -1) {
578 if (md5_req == 1) {
579 ui_print("\n-- No md5 file found!");
580 ui_print("\n-- Aborting install");
581 result = INSTALL_ERROR;
582 }
583 else {
584 ui_print("\n-- No md5 file found, ignoring");
585 }
586 }
587 else if (md5chk == -2) {
588 ui_print("\n-- md5 file doesn't match!");
589 ui_print("\n-- Aborting install");
590 result = INSTALL_ERROR;
591 }
592 printf("%d\n", result);
593 }
594 if (result != INSTALL_ERROR) {
595 ui_print("\n-- Install %s ...\n", zip_path_filename);
596 set_sdcard_update_bootloader_message();
597 char* copy;
598 if (DataManager_GetIntValue(TW_FLASH_ZIP_IN_PLACE) == 1 && strlen(zip_path_filename) > 6 && strncmp(zip_path_filename, "/cache", 6) != 0) {
599 copy = strdup(zip_path_filename);
600 } else {
601 copy = copy_sideloaded_package(zip_path_filename);
602 //unmount_current_storage();
603 }
604 if (copy) {
605 result = really_install_package(copy, 0);
606 free(copy);
607 //update_system_details();
608 } else {
609 result = INSTALL_ERROR;
610 }
611 }
612 //mount_current_storage();
613 //finish_recovery(NULL);
614 return result;
615}
616
617//partial kangbang from system/vold
618#ifndef CUSTOM_LUN_FILE
619#define CUSTOM_LUN_FILE "/sys/devices/platform/usb_mass_storage/lun%d/file"
620#endif
621
622int usb_storage_enable(void)
623{
624 int fd;
625 char lun_file[255];
626
627 if (DataManager_GetIntValue(TW_HAS_DUAL_STORAGE) == 1 && DataManager_GetIntValue(TW_HAS_DATA_MEDIA) == 0) {
628 Volume *vol = volume_for_path(DataManager_GetSettingsStoragePath());
629 if (!vol)
630 {
631 LOGE("Unable to locate volume information.");
632 return -1;
633 }
634
635 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
636
637 if ((fd = open(lun_file, O_WRONLY)) < 0)
638 {
639 LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
640 return -1;
641 }
642
643 if ((write(fd, vol->device, strlen(vol->device)) < 0) &&
644 (!vol->device2 || (write(fd, vol->device, strlen(vol->device2)) < 0))) {
645 LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
646 close(fd);
647 return -1;
648 }
649 close(fd);
650
651 Volume *vol2 = volume_for_path(DataManager_GetStrValue(TW_EXTERNAL_PATH));
652 if (!vol)
653 {
654 LOGE("Unable to locate volume information.\n");
655 return -1;
656 }
657
658 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
659
660 if ((fd = open(lun_file, O_WRONLY)) < 0)
661 {
662 LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
663 return -1;
664 }
665
666 if ((write(fd, vol2->device, strlen(vol2->device)) < 0) &&
667 (!vol2->device2 || (write(fd, vol2->device, strlen(vol2->device2)) < 0))) {
668 LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
669 close(fd);
670 return -1;
671 }
672 close(fd);
673 } else {
674 if (DataManager_GetIntValue(TW_HAS_DATA_MEDIA) == 0)
675 strcpy(lun_file, DataManager_GetCurrentStoragePath());
676 else
677 strcpy(lun_file, DataManager_GetStrValue(TW_EXTERNAL_PATH));
678
679 Volume *vol = volume_for_path(lun_file);
680 if (!vol)
681 {
682 LOGE("Unable to locate volume information.\n");
683 return -1;
684 }
685
686 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
687
688 if ((fd = open(lun_file, O_WRONLY)) < 0)
689 {
690 LOGE("Unable to open ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
691 return -1;
692 }
693
694 if ((write(fd, vol->device, strlen(vol->device)) < 0) &&
695 (!vol->device2 || (write(fd, vol->device, strlen(vol->device2)) < 0))) {
696 LOGE("Unable to write to ums lunfile '%s': (%s)\n", lun_file, strerror(errno));
697 close(fd);
698 return -1;
699 }
700 close(fd);
701 }
702 return 0;
703}
704
705int usb_storage_disable(void)
706{
707 int fd, index;
708 char lun_file[255];
709
710 for (index=0; index<2; index++) {
711 sprintf(lun_file, CUSTOM_LUN_FILE, index);
712
713 if ((fd = open(lun_file, O_WRONLY)) < 0)
714 {
715 if (index == 0)
716 LOGE("Unable to open ums lunfile '%s': (%s)", lun_file, strerror(errno));
717 return -1;
718 }
719
720 char ch = 0;
721 if (write(fd, &ch, 1) < 0)
722 {
723 if (index == 0)
724 LOGE("Unable to write to ums lunfile '%s': (%s)", lun_file, strerror(errno));
725 close(fd);
726 return -1;
727 }
728
729 close(fd);
730 }
731 return 0;
732}
733
734void wipe_dalvik_cache()
735{
736 //ui_set_background(BACKGROUND_ICON_WIPE);
737 ensure_path_mounted("/data");
738 ensure_path_mounted("/cache");
739 ui_print("\n-- Wiping Dalvik Cache Directories...\n");
740 __system("rm -rf /data/dalvik-cache");
741 ui_print("Cleaned: /data/dalvik-cache...\n");
742 __system("rm -rf /cache/dalvik-cache");
743 ui_print("Cleaned: /cache/dalvik-cache...\n");
744 __system("rm -rf /cache/dc");
745 ui_print("Cleaned: /cache/dc\n");
746
747 struct stat st;
748 LOGE("TODO: Re-implement wipe dalvik into Partition Manager!\n");
749 if (1) //if (0 != stat(sde.blk, &st))
750 {
751 ui_print("/sd-ext not present, skipping\n");
752 } else {
753 __system("mount /sd-ext");
754 LOGI("Mounting /sd-ext\n");
755 if (stat("/sd-ext/dalvik-cache",&st) == 0)
756 {
757 __system("rm -rf /sd-ext/dalvik-cache");
758 ui_print("Cleaned: /sd-ext/dalvik-cache...\n");
759 }
760 }
761 ensure_path_unmounted("/data");
762 ui_print("-- Dalvik Cache Directories Wipe Complete!\n\n");
763 //ui_set_background(BACKGROUND_ICON_MAIN);
764 //if (!ui_text_visible()) return;
765}
766
767// BATTERY STATS
768void wipe_battery_stats()
769{
770 ensure_path_mounted("/data");
771 struct stat st;
772 if (0 != stat("/data/system/batterystats.bin", &st))
773 {
774 ui_print("No Battery Stats Found. No Need To Wipe.\n");
775 } else {
776 //ui_set_background(BACKGROUND_ICON_WIPE);
777 remove("/data/system/batterystats.bin");
778 ui_print("Cleared: Battery Stats...\n");
779 ensure_path_unmounted("/data");
780 }
781}
782
783// ROTATION SETTINGS
784void wipe_rotate_data()
785{
786 //ui_set_background(BACKGROUND_ICON_WIPE);
787 ensure_path_mounted("/data");
788 __system("rm -r /data/misc/akmd*");
789 __system("rm -r /data/misc/rild*");
790 ui_print("Cleared: Rotatation Data...\n");
791 ensure_path_unmounted("/data");
792}
793
794void fix_perms()
795{
796 ensure_path_mounted("/data");
797 ensure_path_mounted("/system");
798 //ui_show_progress(1,30);
799 ui_print("\n-- Fixing Permissions\n");
800 ui_print("This may take a few minutes.\n");
801 __system("./sbin/fix_permissions.sh");
802 ui_print("-- Done.\n\n");
803 //ui_reset_progress();
804}
805
806int get_battery_level(void)
807{
808 static int lastVal = -1;
809 static time_t nextSecCheck = 0;
810
811 struct timeval curTime;
812 gettimeofday(&curTime, NULL);
813 if (curTime.tv_sec > nextSecCheck)
814 {
815 char cap_s[4];
816 FILE * cap = fopen("/sys/class/power_supply/battery/capacity","rt");
817 if (cap)
818 {
819 fgets(cap_s, 4, cap);
820 fclose(cap);
821 lastVal = atoi(cap_s);
822 if (lastVal > 100) lastVal = 101;
823 if (lastVal < 0) lastVal = 0;
824 }
825 nextSecCheck = curTime.tv_sec + 60;
826 }
827 return lastVal;
828}
829
830char*
831print_batt_cap() {
832 char* full_cap_s = (char*)malloc(30);
833 char full_cap_a[30];
834
835 int cap_i = get_battery_level();
836
837 //int len = strlen(cap_s);
838 //if (cap_s[len-1] == '\n') {
839 // cap_s[len-1] = 0;
840 //}
841
842 // Get a usable time
843 struct tm *current;
844 time_t now;
845 now = time(0);
846 current = localtime(&now);
847
848 sprintf(full_cap_a, "Battery Level: %i%% @ %02D:%02D", cap_i, current->tm_hour, current->tm_min);
849 strcpy(full_cap_s, full_cap_a);
850
851 return full_cap_s;
852}
853
854void update_tz_environment_variables() {
855 setenv("TZ", DataManager_GetStrValue(TW_TIME_ZONE_VAR), 1);
856 tzset();
857}
858
859void run_script(const char *str1, const char *str2, const char *str3, const char *str4, const char *str5, const char *str6, const char *str7, int request_confirm)
860{
861 ui_print("%s", str1);
862 //ui_clear_key_queue();
863 ui_print("\nPress Power to confirm,");
864 ui_print("\nany other key to abort.\n");
865 int confirm;
866 /*if (request_confirm) // this option is used to skip the confirmation when the gui is in use
867 confirm = ui_wait_key();
868 else*/
869 confirm = KEY_POWER;
870
871 if (confirm == BTN_MOUSE || confirm == KEY_POWER || confirm == SELECT_ITEM) {
872 ui_print("%s", str2);
873 pid_t pid = fork();
874 if (pid == 0) {
875 char *args[] = { "/sbin/sh", "-c", (char*)str3, "1>&2", NULL };
876 execv("/sbin/sh", args);
877 fprintf(stderr, str4, strerror(errno));
878 _exit(-1);
879 }
880 int status;
881 while (waitpid(pid, &status, WNOHANG) == 0) {
882 ui_print(".");
883 sleep(1);
884 }
885 ui_print("\n");
886 if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
887 ui_print("%s", str5);
888 } else {
889 ui_print("%s", str6);
890 }
891 } else {
892 ui_print("%s", str7);
893 }
894 //if (!ui_text_visible()) return;
895}
896
897void install_htc_dumlock(void)
898{
899 struct statfs fs1, fs2;
900 int need_libs = 0;
901
902 ui_print("Installing HTC Dumlock to system...\n");
903 ensure_path_mounted("/system");
904 __system("cp /res/htcd/htcdumlocksys /system/bin/htcdumlock && chmod 755 /system/bin/htcdumlock");
905 if (statfs("/system/bin/flash_image", &fs1) != 0) {
906 ui_print("Installing flash_image...\n");
907 __system("cp /res/htcd/flash_imagesys /system/bin/flash_image && chmod 755 /system/bin/flash_image");
908 need_libs = 1;
909 } else
910 ui_print("flash_image is already installed, skipping...\n");
911 if (statfs("/system/bin/dump_image", &fs2) != 0) {
912 ui_print("Installing dump_image...\n");
913 __system("cp /res/htcd/dump_imagesys /system/bin/dump_image && chmod 755 /system/bin/dump_image");
914 need_libs = 1;
915 } else
916 ui_print("dump_image is already installed, skipping...\n");
917 if (need_libs) {
918 ui_print("Installing libs needed for flash_image and dump_image...\n");
919 __system("cp /res/htcd/libbmlutils.so /system/lib && chmod 755 /system/lib/libbmlutils.so");
920 __system("cp /res/htcd/libflashutils.so /system/lib && chmod 755 /system/lib/libflashutils.so");
921 __system("cp /res/htcd/libmmcutils.so /system/lib && chmod 755 /system/lib/libmmcutils.so");
922 __system("cp /res/htcd/libmtdutils.so /system/lib && chmod 755 /system/lib/libmtdutils.so");
923 }
924 ui_print("Installing HTC Dumlock app...\n");
925 ensure_path_mounted("/data");
926 mkdir("/data/app", 0777);
927 __system("rm /data/app/com.teamwin.htcdumlock*");
928 __system("cp /res/htcd/HTCDumlock.apk /data/app/com.teamwin.htcdumlock.apk");
929 sync();
930 ui_print("HTC Dumlock is installed.\n");
931}
932
933void htc_dumlock_restore_original_boot(void)
934{
935 ui_print("Restoring original boot...\n");
936 __system("htcdumlock restore");
937 ui_print("Original boot restored.\n");
938}
939
940void htc_dumlock_reflash_recovery_to_boot(void)
941{
942 ui_print("Reflashing recovery to boot...\n");
943 __system("htcdumlock recovery noreboot");
944 ui_print("Recovery is flashed to boot.\n");
945}
946
947void check_and_run_script(const char* script_file, const char* display_name)
948{
949 // Check for and run startup script if script exists
950 struct statfs st;
951 if (statfs(script_file, &st) == 0) {
952 ui_print("Running %s script...\n", display_name);
953 char command[255];
954 strcpy(command, "chmod 755 ");
955 strcat(command, script_file);
956 __system(command);
957 __system(script_file);
958 ui_print("\nFinished running %s script.\n", display_name);
959 }
960}
961
962int check_backup_name(int show_error) {
963 // Check the backup name to ensure that it is the correct size and contains only valid characters
964 // and that a backup with that name doesn't already exist
965 char backup_name[MAX_BACKUP_NAME_LEN];
966 char backup_loc[255], tw_image_dir[255];
967 int copy_size = strlen(DataManager_GetStrValue(TW_BACKUP_NAME));
968 int index, cur_char;
969 struct statfs st;
970
971 // Check size
972 if (copy_size > MAX_BACKUP_NAME_LEN) {
973 if (show_error)
974 LOGE("Backup name is too long.\n");
975 return -2;
976 }
977
978 // Check characters
979 strncpy(backup_name, DataManager_GetStrValue(TW_BACKUP_NAME), copy_size);
980 if (strcmp(backup_name, "0") == 0)
981 return 0; // A "0" (zero) means to use the current timestamp for the backup name
982 for (index=0; index<copy_size; index++) {
983 cur_char = (int)backup_name[index];
984 if ((cur_char >= 48 && cur_char <= 57) || (cur_char >= 65 && cur_char <= 91) || cur_char == 93 || cur_char == 95 || (cur_char >= 97 && cur_char <= 123) || cur_char == 125 || cur_char == 45 || cur_char == 46) {
985 // These are valid characters
986 // Numbers
987 // Upper case letters
988 // Lower case letters
989 // and -_.{}[]
990 } else {
991 if (show_error)
992 LOGE("Backup name '%s' contains invalid character: '%c'\n", backup_name, (char)cur_char);
993 return -3;
994 }
995 }
996
997 // Check to make sure that a backup with this name doesn't already exist
998 strcpy(backup_loc, DataManager_GetStrValue(TW_BACKUPS_FOLDER_VAR));
999 sprintf(tw_image_dir,"%s/%s/.", backup_loc, backup_name);
1000 if (statfs(tw_image_dir, &st) == 0) {
1001 if (show_error)
1002 LOGE("A backup with this name already exists.\n");
1003 return -4;
1004 }
1005
1006 // No problems found, return 0
1007 return 0;
1008}
Dees_Troy7d15c252012-09-05 20:47:21 -04001009
1010static const char *COMMAND_FILE = "/cache/recovery/command";
1011static const char *INTENT_FILE = "/cache/recovery/intent";
1012static const char *LOG_FILE = "/cache/recovery/log";
1013static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
1014static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
1015static const char *CACHE_ROOT = "/cache";
1016static const char *SDCARD_ROOT = "/sdcard";
1017static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
1018static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
1019
1020// close a file, log an error if the error indicator is set
1021static void check_and_fclose(FILE *fp, const char *name) {
1022 fflush(fp);
1023 if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
1024 fclose(fp);
1025}
1026
1027static void copy_log_file(const char* source, const char* destination, int append) {
1028 FILE *log = fopen_path(destination, append ? "a" : "w");
1029 if (log == NULL) {
1030 LOGE("Can't open %s\n", destination);
1031 } else {
1032 FILE *tmplog = fopen(source, "r");
1033 if (tmplog != NULL) {
1034 if (append) {
1035 fseek(tmplog, tmplog_offset, SEEK_SET); // Since last write
1036 }
1037 char buf[4096];
1038 while (fgets(buf, sizeof(buf), tmplog)) fputs(buf, log);
1039 if (append) {
1040 tmplog_offset = ftell(tmplog);
1041 }
1042 check_and_fclose(tmplog, source);
1043 }
1044 check_and_fclose(log, destination);
1045 }
1046}
1047
1048// clear the recovery command and prepare to boot a (hopefully working) system,
1049// copy our log file to cache as well (for the system to read), and
1050// record any intent we were asked to communicate back to the system.
1051// this function is idempotent: call it as many times as you like.
1052void twfinish_recovery(const char *send_intent) {
1053 // By this point, we're ready to return to the main system...
1054 if (send_intent != NULL) {
1055 FILE *fp = fopen_path(INTENT_FILE, "w");
1056 if (fp == NULL) {
1057 LOGE("Can't open %s\n", INTENT_FILE);
1058 } else {
1059 fputs(send_intent, fp);
1060 check_and_fclose(fp, INTENT_FILE);
1061 }
1062 }
1063
1064 // Copy logs to cache so the system can find out what happened.
1065 copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
1066 copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
1067 copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
1068 chmod(LOG_FILE, 0600);
1069 chown(LOG_FILE, 1000, 1000); // system user
1070 chmod(LAST_LOG_FILE, 0640);
1071 chmod(LAST_INSTALL_FILE, 0644);
1072
1073 // Reset to normal system boot so recovery won't cycle indefinitely.
1074 struct bootloader_message boot;
1075 memset(&boot, 0, sizeof(boot));
1076 set_bootloader_message(&boot);
1077
1078 // Remove the command file, so recovery won't repeat indefinitely.
1079 if (ensure_path_mounted(COMMAND_FILE) != 0 ||
1080 (unlink(COMMAND_FILE) && errno != ENOENT)) {
1081 LOGW("Can't unlink %s\n", COMMAND_FILE);
1082 }
1083
1084 ensure_path_unmounted(CACHE_ROOT);
1085 sync(); // For good measure.
1086}
1087