This repository has been archived by the owner on Sep 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 470
/
installer.cpp
2108 lines (1756 loc) · 66.9 KB
/
installer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014-2016 Andrew Gunnerson <andrewgunnerson@gmail.com>
*
* This file is part of MultiBootPatcher
*
* MultiBootPatcher is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MultiBootPatcher is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MultiBootPatcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include "installer.h"
// C++
#include <algorithm>
// C
#include <cstring>
// Linux/posix
#include <fcntl.h>
#include <mntent.h>
#include <signal.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
// Linux
#include <linux/loop.h>
// Legacy properties
#include "external/legacy_property_service.h"
// libmbcommon
#include "mbcommon/version.h"
// libmblog
#include "mblog/logging.h"
// libmbdevice
#include "mbdevice/json.h"
#include "mbdevice/validate.h"
// libmbp
#include "mbp/bootimage.h"
#include "mbp/cpiofile.h"
#include "mbp/patcherconfig.h"
// libmbutil
#include "mbutil/autoclose/dir.h"
#include "mbutil/autoclose/file.h"
#include "mbutil/archive.h"
#include "mbutil/chmod.h"
#include "mbutil/chown.h"
#include "mbutil/command.h"
#include "mbutil/copy.h"
#include "mbutil/delete.h"
#include "mbutil/directory.h"
#include "mbutil/file.h"
#include "mbutil/finally.h"
#include "mbutil/fstab.h"
#include "mbutil/loopdev.h"
#include "mbutil/mount.h"
#include "mbutil/path.h"
#include "mbutil/properties.h"
#include "mbutil/string.h"
#include "mbutil/time.h"
// Local
#include "image.h"
#include "multiboot.h"
#include "signature.h"
#include "switcher.h"
#include "wipe.h"
// Set to 1 to spawn a shell after installation
// NOTE: This should ONLY be used through adb. For example:
//
// $ adb push mbtool_recovery /tmp/updater
// $ adb shell /tmp/updater 3 1 /path/to/file_patched.zip
#define DEBUG_PRE_SHELL 0
#define DEBUG_POST_SHELL 0
// Use an update-binary file not from the zip file
#define DEBUG_USE_ALTERNATE_UPDATER 0
#define DEBUG_ALTERNATE_UPDATER_PATH "/tmp/updater.orig"
// Use a wrapper around the updater
#define DEBUG_USE_UPDATER_WRAPPER 0
#define DEBUG_UPDATER_WRAPPER_PATH "/tmp/strace_static"
//#define DEBUG_UPDATER_WRAPPER_ARGS "-f" // Comma-separated strings
#define HELPER_TOOL "/update-binary-tool"
#define UPDATE_BINARY "META-INF/com/google/android/update-binary"
#define UPDATE_BINARY_ORIG UPDATE_BINARY ".orig"
#define MULTIBOOT_BBWRAPPER "multiboot/bb-wrapper.sh"
#define MULTIBOOT_DEVICE_JSON "multiboot/device.json"
#define MULTIBOOT_INFO_PROP "multiboot/info.prop"
namespace mb {
const std::string Installer::CANCELLED = "cancelled";
Installer::Installer(std::string zip_file, std::string chroot_dir,
std::string temp_dir, int interface, int output_fd) :
_zip_file(std::move(zip_file)),
_chroot(std::move(chroot_dir)),
_temp(std::move(temp_dir)),
_interface(interface),
_output_fd(output_fd),
_ran(false)
{
_passthrough = _output_fd >= 0;
LOGD("Initialized installer for zip file: %s", _zip_file.c_str());
}
Installer::~Installer()
{
mb_device_free(_device);
}
/*
* Wrappers around functions that log failures
*/
static int log_mkdir(const char *pathname, mode_t mode)
{
int ret = mkdir(pathname, mode);
if (ret < 0) {
LOGE("Failed to create %s: %s", pathname, strerror(errno));
}
return ret;
}
static int log_mount(const char *source, const char *target, const char *fstype,
long unsigned int mountflags, const void *data)
{
int ret = mount(source, target, fstype, mountflags, data);
if (ret < 0) {
LOGE("Failed to mount %s (%s) at %s: %s",
source, fstype, target, strerror(errno));
}
return ret;
}
static int log_umount(const char *target)
{
int ret = umount(target);
if (ret < 0) {
LOGE("Failed to unmount %s: %s", target, strerror(errno));
}
return ret;
}
static int log_mknod(const char *pathname, mode_t mode, dev_t dev)
{
int ret = mknod(pathname, mode, dev);
if (ret < 0) {
LOGE("Failed to create special file %s: %s", pathname, strerror(errno));
}
return ret;
}
static bool log_is_mounted(const std::string &mountpoint)
{
bool ret = util::is_mounted(mountpoint);
if (!ret) {
LOGE("%s is not mounted", mountpoint.c_str());
}
return ret;
}
static bool log_unmount_all(const std::string &dir)
{
bool ret = util::unmount_all(dir);
if (!ret) {
LOGE("Failed to unmount all mountpoints within %s", dir.c_str());
}
return ret;
}
static bool log_delete_recursive(const std::string &path)
{
bool ret = util::delete_recursive(path);
if (!ret) {
LOGE("Failed to recursively remove %s", path.c_str());
}
return ret;
}
static bool log_copy_dir(const std::string &source,
const std::string &target, int flags)
{
bool ret = util::copy_dir(source, target, flags);
if (!ret) {
LOGE("Failed to copy contents of %s/ to %s/",
source.c_str(), target.c_str());
}
return ret;
}
/*
* Helper functions
*/
void Installer::output_cb(const char *line, bool error, void *userdata)
{
(void) error;
Installer *installer = static_cast<Installer *>(userdata);
installer->command_output(line);
}
int Installer::run_command(const char * const *argv)
{
return util::run_command(
argv[0],
argv,
nullptr,
nullptr,
_passthrough ? nullptr : &output_cb,
this
);
}
int Installer::run_command_chroot(const char *dir,
const char * const *argv)
{
return util::run_command(
argv[0],
argv,
nullptr,
dir,
_passthrough ? nullptr : &output_cb,
this
);
}
std::string Installer::in_chroot(const std::string &path) const
{
if (!path.empty() && path[0] == '/') {
return std::string(_chroot).append(path);
} else {
return std::string(_chroot).append("/").append(path);
}
}
bool Installer::create_chroot()
{
// We'll just call the recovery's mount tools directly to avoid having to
// parse TWRP and CWM's different fstab formats
const char *argv_mount_system[] = { "mount", "/system", nullptr };
const char *argv_mount_cache[] = { "mount", "/cache", nullptr };
const char *argv_mount_data[] = { "mount", "/data", nullptr };
const char *argv_mount_efs[] = { "mount", "-o", "ro", "/efs", nullptr };
run_command(argv_mount_system);
run_command(argv_mount_cache);
run_command(argv_mount_data);
run_command(argv_mount_efs);
// Remount as writable (needed for in-app flashing)
log_mount("", Roms::get_system_partition().c_str(), "", MS_REMOUNT, "");
log_mount("", Roms::get_cache_partition().c_str(), "", MS_REMOUNT, "");
log_mount("", Roms::get_data_partition().c_str(), "", MS_REMOUNT, "");
// Make sure everything really is mounted
if (!log_is_mounted("/system")
|| !log_is_mounted("/cache")
|| !log_is_mounted("/data")) {
return false;
}
// Unmount everything previously mounted in the chroot
if (!log_unmount_all(_chroot)) {
return false;
}
// Remove the chroot if it exists
if (!log_delete_recursive(_chroot)) {
return false;
}
// Create chroot and mount tmpfs there
if (log_mkdir(_chroot.c_str(), 0700) < 0
|| log_mount("tmpfs", _chroot.c_str(), "tmpfs", 0, "") < 0) {
return false;
}
// Create remaining directories
if (log_mkdir(in_chroot("/mb").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/dev").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/etc").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/proc").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/sbin").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/sys").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/tmp").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/data").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/cache").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/system").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/firmware").c_str(), 0755) < 0
|| log_mkdir(in_chroot("/efs").c_str(), 0755) < 0) {
return false;
}
// Other mounts
if (log_mount("none", in_chroot("/dev").c_str(), "tmpfs", 0, "") < 0
|| log_mkdir(in_chroot("/dev/pts").c_str(), 0755) < 0
|| log_mount("none", in_chroot("/dev/pts").c_str(), "devpts", 0, "") < 0
|| log_mount("none", in_chroot("/proc").c_str(), "proc", 0, "") < 0
|| log_mount("none", in_chroot("/sbin").c_str(), "tmpfs", 0, "") < 0
|| log_mount("none", in_chroot("/sys").c_str(), "sysfs", 0, "") < 0
|| log_mount("none", in_chroot("/tmp").c_str(), "tmpfs", 0, "") < 0) {
return false;
}
// Some recoveries don't have SELinux enabled
if (log_mount("none", in_chroot("/sys/fs/selinux").c_str(), "selinuxfs", 0, "") < 0
&& errno != ENOENT) {
LOGV("Ignoring /sys/fs/selinux mount");
LOGE("Failed to mount %s (%s) at %s: %s",
"none", "selinuxfs", in_chroot("/sys/fs/selinux").c_str(),
strerror(errno));
return false;
}
// Copy the contents of sbin since we need to mess with some of the binaries
// there. Also, for whatever reason, bind mounting /sbin results in EINVAL
// no matter if it's done from here or from busybox.
if (!log_copy_dir("/sbin", in_chroot("/sbin"),
util::COPY_ATTRIBUTES
| util::COPY_XATTRS
| util::COPY_EXCLUDE_TOP_LEVEL)) {
return false;
}
// Remove reboot binary
remove(in_chroot("/sbin/reboot").c_str());
// Don't create unnecessary special files in /dev to avoid install scripts
// from overwriting partitions
if (log_mknod(in_chroot("/dev/console").c_str(), S_IFCHR | 0644, makedev(5, 1)) < 0
|| log_mknod(in_chroot("/dev/null").c_str(), S_IFCHR | 0644, makedev(1, 3)) < 0
|| log_mknod(in_chroot("/dev/ptmx").c_str(), S_IFCHR | 0644, makedev(5, 2)) < 0
|| log_mknod(in_chroot("/dev/random").c_str(), S_IFCHR | 0644, makedev(1, 8)) < 0
|| log_mknod(in_chroot("/dev/tty").c_str(), S_IFCHR | 0644, makedev(5, 0)) < 0
|| log_mknod(in_chroot("/dev/urandom").c_str(), S_IFCHR | 0644, makedev(1, 9)) < 0
|| log_mknod(in_chroot("/dev/zero").c_str(), S_IFCHR | 0644, makedev(1, 5)) < 0
|| log_mknod(in_chroot("/dev/loop-control").c_str(), S_IFCHR | 0644, makedev(10, 237)) < 0
|| log_mknod(in_chroot("/dev/fuse").c_str(), S_IFCHR | 0644, makedev(10, 229))) {
return false;
}
// Create a few loopback devices since some installers expect them to exist,
// but don't create them. They are not necessary for mbtool to work.
if (log_mkdir(in_chroot("/dev/block").c_str(), 0755) < 0
|| log_mknod(in_chroot("/dev/block/loop0").c_str(), S_IFBLK | 0644, makedev(7, 0)) < 0
|| log_mknod(in_chroot("/dev/block/loop1").c_str(), S_IFBLK | 0644, makedev(7, 1)) < 0
|| log_mknod(in_chroot("/dev/block/loop2").c_str(), S_IFBLK | 0644, makedev(7, 2)) < 0
|| log_mknod(in_chroot("/dev/block/loop3").c_str(), S_IFBLK | 0644, makedev(7, 3)) < 0
|| log_mknod(in_chroot("/dev/block/loop4").c_str(), S_IFBLK | 0644, makedev(7, 4)) < 0
|| log_mknod(in_chroot("/dev/block/loop5").c_str(), S_IFBLK | 0644, makedev(7, 5)) < 0
|| log_mknod(in_chroot("/dev/block/loop6").c_str(), S_IFBLK | 0644, makedev(7, 6)) < 0
|| log_mknod(in_chroot("/dev/block/loop7").c_str(), S_IFBLK | 0644, makedev(7, 7)) < 0) {
return false;
}
// We need /dev/input/* and /dev/graphics/* for AROMA
if (!log_copy_dir("/dev/input", in_chroot("/dev/input"),
util::COPY_ATTRIBUTES
| util::COPY_XATTRS
| util::COPY_EXCLUDE_TOP_LEVEL)) {
return false;
}
if (!log_copy_dir("/dev/graphics", in_chroot("/dev/graphics"),
util::COPY_ATTRIBUTES
| util::COPY_XATTRS
| util::COPY_EXCLUDE_TOP_LEVEL)) {
return false;
}
// Mount EFS partition so patched Odin images can properly set up multi-CSC
if (!mount_efs()) {
return false;
}
util::create_empty_file(in_chroot("/.chroot"));
return true;
}
bool Installer::destroy_chroot() const
{
// Disassociate loop devices that the ROM installer may have assigned
// (grr, SuperSU...)
std::string dev_block_path(in_chroot("/dev/block"));
autoclose::dir dp = autoclose::opendir(dev_block_path.c_str());
if (dp) {
std::string path;
struct dirent *ent;
while ((ent = readdir(dp.get()))) {
path = dev_block_path;
path += '/';
path += ent->d_name;
util::loopdev_remove_device(path.c_str());
}
dp.reset();
}
log_umount(in_chroot("/system").c_str());
log_umount(in_chroot("/cache").c_str());
log_umount(in_chroot("/data").c_str());
log_umount(in_chroot("/efs").c_str());
log_umount(in_chroot("/dev/pts").c_str());
log_umount(in_chroot("/dev").c_str());
log_umount(in_chroot("/proc").c_str());
log_umount(in_chroot("/sys/fs/selinux").c_str());
log_umount(in_chroot("/sys").c_str());
log_umount(in_chroot("/tmp").c_str());
log_umount(in_chroot("/sbin").c_str());
log_umount(_chroot.c_str());
// Unmount everything previously mounted in the chroot
if (!util::unmount_all(_chroot)) {
LOGE("Failed to unmount previous mount points in %s", _chroot.c_str());
return false;
}
util::delete_recursive(_chroot);
if (log_is_mounted("/efs")) {
log_umount("/efs");
}
return true;
}
bool Installer::mount_efs() const
{
char manufacturer[PROP_VALUE_MAX];
char brand[PROP_VALUE_MAX];
util::property_get("ro.product.manufacturer", manufacturer, "");
util::property_get("ro.product.brand", brand, "");
if (strcasecmp(manufacturer, "samsung") != 0
&& strcasecmp(brand, "samsung") != 0) {
LOGD("Not mounting EFS partition because this is not a Samsung device");
return true;
}
LOGD("This is a Samsung device; mounting EFS partition in chroot");
struct stat sb;
// Mount /efs as read-only if it exists
if (log_is_mounted("/efs")) {
if (log_mount("/efs", in_chroot("/efs").c_str(), "",
MS_BIND | MS_RDONLY, "") < 0) {
return false;
}
LOGD("Bind mounted /efs to chroot as read-only");
} else if (stat("/etc/recovery.fstab", &sb) == 0) {
LOGD("Found /etc/recovery.fstab");
std::string efs_dev;
if (stat("/twres", &sb) == 0 && S_ISDIR(sb.st_mode)) {
LOGD("Looking for /efs entry in TWRP-format fstab");
std::vector<util::twrp_fstab_rec> recs =
util::read_twrp_fstab("/etc/recovery.fstab");
for (const util::twrp_fstab_rec &rec : recs) {
if (util::path_compare(rec.mount_point, "/efs") == 0
|| util::path_compare(rec.mount_point, "/efs1") == 0) {
LOGD("Found /efs fstab entry");
for (const std::string &dev : rec.blk_devices) {
if (stat(dev.c_str(), &sb) == 0) {
efs_dev = dev.c_str();
break;
}
}
break;
}
}
} else {
LOGE("Looking for /efs entry in non-TWRP-format fstab");
std::vector<util::fstab_rec> recs =
util::read_fstab("/etc/recovery.fstab");
for (const util::fstab_rec &rec : recs) {
if (util::path_compare(rec.mount_point, "/efs") == 0) {
LOGD("Found /efs fstab entry");
efs_dev = rec.blk_device;
break;
}
}
}
// FIXME: Temporary hack until the EFS partition path is specified in
// the device definition
std::vector<std::string> efs_devs{
efs_dev,
"/dev/block/bootdevice/by-name/efs",
"/dev/block/bootdevice/by-name/EFS",
};
for (auto const &dev : efs_devs) {
if (!dev.empty() && stat(dev.c_str(), &sb) == 0
&& log_mount(dev.c_str(), in_chroot("/efs").c_str(),
"ext4", MS_RDONLY, "") == 0) {
return true;
}
}
return false;
}
return true;
}
/*!
* \brief Extract needed multiboot files from the patched zip file
*/
bool Installer::extract_multiboot_files()
{
std::vector<util::extract_info> files{
{ UPDATE_BINARY_ORIG, _temp + "/updater" },
{ UPDATE_BINARY, _temp + "/mbtool" },
{ UPDATE_BINARY ".sig", _temp + "/mbtool.sig" },
{ MULTIBOOT_BBWRAPPER, _temp + "/bb-wrapper.sh" },
{ MULTIBOOT_BBWRAPPER ".sig", _temp + "/bb-wrapper.sh.sig" },
{ MULTIBOOT_DEVICE_JSON, _temp + "/device.json" },
{ MULTIBOOT_INFO_PROP, _temp + "/info.prop" },
};
if (!util::extract_files2(_zip_file, files)) {
LOGE("Failed to extract all multiboot files");
return false;
}
SigVerifyResult result;
result = verify_signature((_temp + "/mbtool").c_str(),
(_temp + "/mbtool.sig").c_str());
if (result != SigVerifyResult::VALID) {
LOGE("Invalid mbtool signature");
return false;
}
result = verify_signature((_temp + "/bb-wrapper.sh").c_str(),
(_temp + "/bb-wrapper.sh.sig").c_str());
if (result != SigVerifyResult::VALID) {
LOGE("Invalid busybox wrapper signature");
return false;
}
return true;
}
/*!
* \brief Replace busybox in the chroot with a wrapper that disables certain
* functions
*/
bool Installer::set_up_busybox_wrapper()
{
std::string temp_busybox = _temp + "/bb-wrapper.sh";
std::string sbin_busybox = in_chroot("/sbin/busybox");
rename(sbin_busybox.c_str(), in_chroot("/sbin/busybox_orig").c_str());
if (!util::copy_file(temp_busybox, sbin_busybox,
util::COPY_ATTRIBUTES | util::COPY_XATTRS)) {
LOGE("Failed to copy %s to %s: %s",
temp_busybox.c_str(), sbin_busybox.c_str(), strerror(errno));
return false;
}
if (chmod(sbin_busybox.c_str(), 0555) < 0) {
LOGE("Failed to chmod %s: %s", sbin_busybox.c_str(), strerror(errno));
return false;
}
return true;
}
/*!
* \brief Create 4G temporary ext4 image
*
* \param path Image file path
*/
bool Installer::create_image(const std::string &path, uint64_t size)
{
if (!util::mkdir_parent(path, S_IRWXU)) {
LOGE("%s: Failed to create parent directory: %s",
path.c_str(), strerror(errno));
return false;
}
auto result = create_ext4_image(path, size);
if (result == CreateImageResult::NOT_ENOUGH_SPACE) {
uint64_t avail = util::mount_get_avail_size(util::dir_name(path).c_str());
display_msg(std::string());
display_msg("There is not enough space to create %s", path.c_str());
display_msg("- Needed: %" PRIu64 " bytes", size);
display_msg("- Available: %" PRIu64 " bytes", avail);
}
return result == CreateImageResult::SUCCEEDED;
}
/*!
* \brief Copy a /system directory to an image file
*
* \param source Source directory
* \param image Target image file
* \param reverse If non-zero, then the image file is the source and the
* directory is the target
*/
bool Installer::system_image_copy(const std::string &source,
const std::string &image, bool reverse)
{
std::string temp_mnt(_temp);
temp_mnt += "/.system.tmp";
struct stat sb;
auto done = util::finally([&] {
util::umount(temp_mnt.c_str());
});
if (stat(source.c_str(), &sb) < 0
&& !util::mkdir_recursive(source, 0755)) {
LOGE("Failed to create %s: %s", source.c_str(), strerror(errno));
return false;
}
if (stat(temp_mnt.c_str(), &sb) < 0
&& mkdir(temp_mnt.c_str(), 0755) < 0) {
LOGE("Failed to create %s: %s", temp_mnt.c_str(), strerror(errno));
return false;
}
if (!util::mount(image.c_str(), temp_mnt.c_str(), "auto", 0, "")) {
LOGE("Failed to mount %s: %s", source.c_str(), strerror(errno));
return false;
}
if (reverse) {
if (!copy_system(temp_mnt, source)) {
LOGE("Failed to copy system files from %s to %s",
temp_mnt.c_str(), source.c_str());
return false;
}
} else {
if (!copy_system(source, temp_mnt)) {
LOGE("Failed to copy system files from %s to %s",
source.c_str(), temp_mnt.c_str());
return false;
}
}
if (!util::umount(temp_mnt.c_str())) {
LOGE("Failed to unmount %s: %s", temp_mnt.c_str(), strerror(errno));
return false;
}
return true;
}
/*!
* \brief Bind mount directory or create and mount image
*
* \param source Source path (directory or image file)
* \param bind_target Mount point for bind mount (if \a is_image is false)
* \param loop_target Path to create loop device (if \a is_image is true)
* \param is_image Whether \a source is an image file
* \param image_size Desired image size (only used if \a is_image is true and
* \a source doesn't exist)
*/
bool Installer::mount_dir_or_image(const std::string &source,
const std::string &bind_target,
const std::string &loop_target,
bool is_image,
uint64_t image_size)
{
if (is_image) {
struct stat sb;
if (stat(source.c_str(), &sb) < 0) {
double mib = (double) image_size / 1024 / 1024;
display_msg("Creating image (%.1f MiB) at %s",
mib, source.c_str());
display_msg("This may take a while");
if (!create_image(source, image_size)) {
display_msg("Failed to create image at %s", source.c_str());
return false;
}
}
std::string loopdev = util::loopdev_find_unused();
if (loopdev.empty()) {
LOGE("Failed to find unused loop device: %s", strerror(errno));
return false;
}
if (!util::loopdev_set_up_device(loopdev, source, 0, false)) {
LOGE("Failed to attach %s to %s: %s",
loopdev.c_str(), source.c_str(), strerror(errno));
return false;
}
if (!util::copy_file(loopdev, loop_target, 0)) {
LOGE("Failed to copy %s to %s: %s",
loopdev.c_str(), loop_target.c_str(), strerror(errno));
return false;
}
_associated_loop_devs.push_back(loopdev);
} else {
if (!util::bind_mount(source, 0771, bind_target, 0771)) {
display_msg("Failed to bind mount %s to %s",
source.c_str(), bind_target.c_str());
return false;
}
}
return true;
}
bool Installer::change_root(const std::string &path)
{
if (unshare(CLONE_NEWNS) < 0) {
LOGE("Failed to unshare mount namespace: %s", strerror(errno));
return false;
}
if (log_mount("", "/", "", MS_PRIVATE | MS_REC, "") < 0) {
return false;
}
// Unmount everything besides our chroot dir
{
std::vector<std::string> to_unmount;
struct mntent ent;
char buf[1024];
autoclose::file fp(setmntent("/proc/mounts", "r"), endmntent);
if (!fp) {
LOGE("%s: Failed to read file: %s",
"/proc/mounts", strerror(errno));
return false;
}
while (getmntent_r(fp.get(), &ent, buf, sizeof(buf))) {
if (strcmp(ent.mnt_dir, "/") != 0
&& !util::starts_with(ent.mnt_dir, path.c_str())) {
to_unmount.push_back(ent.mnt_dir);
}
}
// Close procfs fd
fp.reset();
// Unmount in reverse order
for (auto it = to_unmount.rbegin(); it != to_unmount.rend(); ++it) {
log_umount(it->c_str());
}
}
if (chdir(path.c_str()) < 0) {
LOGE("%s: Failed to chdir: %s", path.c_str(), strerror(errno));
return false;
}
if (chroot(path.c_str()) < 0) {
LOGE("%s: Failed to chroot: %s", path.c_str(), strerror(errno));
return false;
}
return true;
}
bool Installer::set_up_legacy_properties()
{
// We don't need to worry about /dev/__properties__ since that's not present
// in the chroot. Bionic will automatically fall back to getting the fd from
// the ANDROID_PROPERTY_WORKSPACE environment variable.
char tmp[32];
int propfd, propsz;
legacy_properties_init();
for (auto const &pair : _chroot_prop) {
LOGD("Setting legacy property: '%s' = '%s'",
pair.first.c_str(), pair.second.c_str());
legacy_property_set(pair.first.c_str(), pair.second.c_str());
}
legacy_get_property_workspace(&propfd, &propsz);
snprintf(tmp, sizeof(tmp), "%d,%d", dup(propfd), propsz);
char *orig_prop_env = getenv("ANDROID_PROPERTY_WORKSPACE");
LOGD("Original properties environment: %s",
orig_prop_env ? orig_prop_env : "null");
setenv("ANDROID_PROPERTY_WORKSPACE", tmp, 1);
LOGD("Switched to legacy properties environment: %s", tmp);
return true;
}
bool Installer::updater_fd_reader(int stdio_fd, int command_fd)
{
int status;
pid_t pid = fork();
if (pid < 0) {
LOGE("Failed to fork updater fd reader process");
} else if (pid == 0) {
// Don't need command_fd in the child process
close(command_fd);
// Read program output in child process (stdout, stderr)
char buf[1024];
autoclose::file fp(fdopen(stdio_fd, "rb"), fclose);
while (fgets(buf, sizeof(buf), fp.get())) {
command_output(buf);
}
_exit(EXIT_SUCCESS);
} else {
// Read special command fd in parent process
char buf[1024];
char *save_ptr;
// Similar parsing to AOSP recovery
autoclose::file fp(fdopen(command_fd, "rb"), fclose);
while (fgets(buf, sizeof(buf), fp.get())) {
char *cmd = strtok_r(buf, " \n", &save_ptr);
if (!cmd) {
continue;
} else if (strcmp(cmd, "progress") == 0
|| strcmp(cmd, "set_progress") == 0
|| strcmp(cmd, "wipe_cache") == 0
|| strcmp(cmd, "clear_display") == 0
|| strcmp(cmd, "enable_reboot") == 0) {
// Ignore
} else if (strcmp(cmd, "ui_print") == 0) {
char *str = strtok_r(nullptr, "\n", &save_ptr);
if (str) {
updater_print(str);
} else {
updater_print("\n");
}
} else {
LOGE("Unknown updater command: %s", cmd);
}
}
do {
if (waitpid(pid, &status, 0) < 0) {
LOGE("Failed to waitpid(): %s", strerror(errno));
return false;
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
return true;
}
return false;
}
/*!
* \brief Run real update-binary in the chroot
*/
bool Installer::run_real_updater()
{
#if DEBUG_USE_ALTERNATE_UPDATER
std::string updater(DEBUG_ALTERNATE_UPDATER_PATH);
#else
std::string updater(_temp);
updater += "/updater";
#endif
std::string chroot_updater = in_chroot("/mb/updater");
if (!util::copy_file(updater, chroot_updater,
util::COPY_ATTRIBUTES | util::COPY_XATTRS)) {
LOGE("Failed to copy %s to %s: %s",
updater.c_str(), chroot_updater.c_str(), strerror(errno));
return false;
}
#if DEBUG_USE_UPDATER_WRAPPER
if (!util::copy_file(DEBUG_UPDATER_WRAPPER_PATH, in_chroot("/mb/wrapper"),
util::COPY_ATTRIBUTES | util::COPY_XATTRS)) {
LOGE("Failed to copy %s to %s: %s",
DEBUG_UPDATER_WRAPPER_PATH, in_chroot("/mb/wrapper").c_str(),
strerror(errno));
return false;
}
#endif
if (chmod(chroot_updater.c_str(), 0555) < 0) {
LOGE("%s: Failed to chmod: %s",
chroot_updater.c_str(), strerror(errno));
return false;
}
pid_t parent = getppid();
bool aroma = is_aroma(chroot_updater);
LOGD("update-binary is AROMA: %d", aroma);
if (aroma) {
kill(parent, SIGSTOP);
}
auto resume_aroma = util::finally([&]{
if (aroma) {
kill(parent, SIGCONT);
}
});
int status;
pid_t pid;
int pipe_fds[2];
int stdio_fds[2];
if (!_passthrough) {
if (pipe(pipe_fds) < 0) {
return false;
}
if (pipe(stdio_fds) < 0) {
close(pipe_fds[0]);
close(pipe_fds[1]);
return false;
}
}
// Run updater in the chroot
std::vector<std::string> argv{
#if DEBUG_USE_UPDATER_WRAPPER
"/mb/wrapper",
#ifdef DEBUG_UPDATER_WRAPPER_ARGS
DEBUG_UPDATER_WRAPPER_ARGS,
#endif
#endif
"/mb/updater",
util::format("%d", _interface),
util::format("%d", _passthrough ? _output_fd : pipe_fds[1]),
"/mb/install.zip"
};
std::vector<const char *> argv_c;
for (const std::string &arg : argv) {
argv_c.push_back(arg.c_str());
}
argv_c.push_back(nullptr);
bool updater_ret = true;
if ((pid = fork()) >= 0) {
if (pid == 0) {
if (!_passthrough) {
// Close read ends of the pipes
close(pipe_fds[0]);
close(stdio_fds[0]);
}
if (!change_root(_chroot)) {
_exit(EXIT_FAILURE);
}
if (!_passthrough) {
if (dup2(stdio_fds[1], STDOUT_FILENO) < 0
|| dup2(stdio_fds[1], STDERR_FILENO) < 0) {
_exit(EXIT_FAILURE);
}
close(stdio_fds[1]);
}
if (!set_up_legacy_properties()) {
_exit(EXIT_FAILURE);
}