forked from badabing2005/PixelFlasher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
phone.py
4255 lines (3976 loc) · 212 KB
/
phone.py
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
#!/usr/bin/env python
# This file is part of PixelFlasher https://github.com/badabing2005/PixelFlasher
#
# Copyright (C) 2024 Badabing2005
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Affero General Public License
# for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Also add information on how to contact you by electronic and paper mail.
#
# If your software can interact with users remotely through a computer network,
# you should also make sure that it provides a way for users to get its source.
# For example, if your program is a web application, its interface could
# display a "Source" link that leads users to an archive of the code. There are
# many ways you could offer source, and different solutions will be better for
# different programs; see section 13 for the specific requirements.
#
# You should also get your employer (if you work as a programmer) or school, if
# any, to sign a "copyright disclaimer" for the program, if necessary. For more
# information on this, and how to apply and follow the GNU AGPL, see
# <https://www.gnu.org/licenses/>.
import contextlib
import re
import subprocess
import time
import traceback
from datetime import datetime
from urllib.parse import urlparse
from packaging.version import parse
from constants import *
from runtime import *
# ============================================================================
# Class Package
# ============================================================================
class Package():
def __init__(self, value):
self.value = value
self.type = ''
self.installed = False
self.enabled = False
self.user0 = False
self.magisk_denylist = False
self.details = ''
self.path = ''
self.path2 = ''
self.label = ''
self.icon = ''
self.uid = ''
# ============================================================================
# Class Backup
# ============================================================================
class Backup():
def __init__(self, value):
self.value = value # sha1
self.date = ''
self.firmware = ''
# ============================================================================
# Class Vbmeta
# ============================================================================
class Vbmeta():
def __init__(self):
self.clear()
def clear(self):
self.type = '' # one of ["a_only", "ab", "none"]
self.verity_a = None
self.verity_b = None
self.verification_a = None
self.verification_b = None
# ============================================================================
# Class Magisk
# ============================================================================
class Magisk():
def __init__(self, dirname):
self.dirname = dirname
# ============================================================================
# Class MagiskApk
# ============================================================================
class MagiskApk():
def __init__(self, type):
self.type = type
# ============================================================================
# Class DeviceProps
# ============================================================================
class DeviceProps:
def __init__(self):
self.property = {}
def get(self, key):
return self.property.get(key, "Property not found")
def upsert(self, key, value):
self.property[key] = value
# ============================================================================
# Class Device
# ============================================================================
class Device():
# Class variable
vendor = "google"
def __init__(self, id, mode, true_mode = None):
# Instance variables
self.id = id
self.mode = mode
if true_mode:
self.true_mode = true_mode
else:
self.true_mode = mode
# The below are for caching.
self._adb_device_info = None
self._fastboot_device_info = None
self._rooted = None
self._magisk_version = None
self._magisk_app_version = None
self._magisk_version_code = None
self._magisk_app_version_code = None
self._get_magisk_detailed_modules = None
self._magisk_modules_summary = None
self._magisk_apks = None
self._magisk_config_path = None
self._apatch_app_version = None
self._apatch_app_version_code = None
self._ksu_version = None
self._ksu_app_version = None
self._ksu_version_code = None
self._ksu_app_version_code = None
self._has_init_boot = None
self._kernel = None
self._magisk_denylist_enforced = None
self._magisk_zygisk_enabled = None
self.packages = {}
self.backups = {}
self.vbmeta = {}
self.props = {}
self._config_kallsyms = None
self._config_kallsyms_all = None
# Get vbmeta details
self.vbmeta = self.get_vbmeta_details()
# ----------------------------------------------------------------------------
# property adb_device_info
# ----------------------------------------------------------------------------
@property
def adb_device_info(self):
if self.mode == 'adb':
if self._adb_device_info is None:
self._adb_device_info = self.device_info
else:
self._adb_device_info = ''
return self._adb_device_info
# ----------------------------------------------------------------------------
# property unlock_ability
# ----------------------------------------------------------------------------
@property
def unlock_ability(self):
if self.mode == 'adb':
return
try:
theCmd = f"\"{get_fastboot()}\" -s {self.id} flashing get_unlock_ability"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode != 0:
return 'UNKNOWN'
lines = (f"{res.stderr}{res.stdout}").splitlines()
for line in lines:
if "get_unlock_ability:" in line:
value = line.split("get_unlock_ability:")[1].strip()
if value == '1':
return "Yes"
elif value == '0':
return "No"
else:
return "UNKNOWN"
return 'UNKNOWN' # Value not found
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get unlock ability.")
puml("#red:ERROR: Could not get unlock ability;\n", True)
return 'UNKNOWN'
# ----------------------------------------------------------------------------
# method get_package_details
# ----------------------------------------------------------------------------
def get_package_details(self, package):
if self.mode != 'adb':
return
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell dumpsys package {package}"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
path = self.get_path_from_details(res.stdout)
return res.stdout, path
else:
return '', ''
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get_package_details.")
puml("#red:ERROR: Could not get_package_details;\n", True)
return '', ''
# ----------------------------------------------------------------------------
# method get_battery_details
# ----------------------------------------------------------------------------
def get_battery_details(self):
if self.mode != 'adb':
return
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell dumpsys battery"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
return res.stdout
else:
return '', ''
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get battery details.")
puml("#red:ERROR: Could not get battery details;\n", True)
return '', ''
# ----------------------------------------------------------------------------
# method get_page_size
# ----------------------------------------------------------------------------
def get_page_size(self):
if self.mode != 'adb':
return
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell getconf PAGE_SIZE"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
return res.stdout.strip('\n')
else:
return ''
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get page size")
puml("#red:ERROR: Could not get page size;\n", True)
return ''
# -----------------------------------------------
# Function get_path_from_package_details
# -----------------------------------------------
def get_path_from_details(self, details):
try:
pattern = re.compile(r'(?s)Dexopt state:.*?path:(.*?)\n(?!.*path:)', re.DOTALL)
match = re.search(pattern, details)
if match:
return match[1].strip()
else:
return ''
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get_path_from_package_details.")
puml("#red:ERROR: Could not get_path_from_package_details;\n", True)
# ----------------------------------------------------------------------------
# property fastboot_device_info
# ----------------------------------------------------------------------------
@property
def fastboot_device_info(self):
if self.mode == 'f.b':
if self._fastboot_device_info is None:
self._fastboot_device_info = self.device_info
else:
self._fastboot_device_info = ''
return self._fastboot_device_info
# ----------------------------------------------------------------------------
# property device_info
# ----------------------------------------------------------------------------
@property
def device_info(self):
"""
Retrieves device information based on the mode of operation.
If the mode is 'adb', it uses the `getprop` command to fetch the device information using ADB.
If the mode is 'f.b', it uses the `getvar all` command to fetch the device information using Fastboot.
Returns:
str: The device information.
Raises:
RuntimeError: If the ADB or Fastboot command is not found.
Example:
```python
phone = Phone()
info = phone.device_info()
print(info)
```
"""
if self.mode == 'adb':
if get_adb():
if self.rooted:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'/bin/getprop\'\""
else:
theCmd = f"\"{get_adb()}\" -s {self.id} shell /bin/getprop"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 127 or "/system/bin/sh: /bin/getprop: not found" in res.stdout:
if self.rooted:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'getprop\'\""
else:
theCmd = f"\"{get_adb()}\" -s {self.id} shell getprop"
res = run_shell(theCmd)
return ''.join(res.stdout)
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: adb command is not found!")
puml("#red:ERROR: adb command is not found!;\n", True)
elif self.mode == 'f.b':
if get_fastboot():
theCmd = f"\"{get_fastboot()}\" -s {self.id} getvar all"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and (res.stdout == ''):
return ''.join(res.stderr)
else:
return ''.join(res.stdout)
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: fastboot command is not found!")
puml("#red:ERROR: fastboot command is not found!;\n", True)
# ----------------------------------------------------------------------------
# Method init
# ----------------------------------------------------------------------------
def init(self, mode):
try:
device_props = DeviceProps()
if mode == 'f.b':
device_info = self.fastboot_device_info
else:
device_info = self.adb_device_info
if device_info:
for line in device_info.split('\n'):
try:
if not line or ':' not in line:
continue
line = line.strip()
if mode == 'f.b':
key, value = line.rsplit(':', 1)
key = key.replace('(bootloader) ', 'bootloader_')
else:
key, value = line.rsplit(': ', 1)
key = key.strip('[]')
value = value.strip('[]')
except Exception as e:
continue
device_props.upsert(key, value)
self.props = device_props
# set has_init_boot
self._has_init_boot = False
if self.hardware in KNOWN_INIT_BOOT_DEVICES:
self._has_init_boot = True
partitions = self.get_partitions()
if partitions != -1 and ('init_boot' in partitions or 'init_boot_a' in partitions or 'init_boot_b' in partitions):
self._has_init_boot = True
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not init device class")
puml("#red:ERROR: Could not get_package_details;\n", True)
# ----------------------------------------------------------------------------
# method get_prop
# ----------------------------------------------------------------------------
def get_prop(self, prop, prop2=None):
if self.props is None:
return ''
if self.mode == "f.b":
res = self.props.get(f"bootloader_{prop}")
# debug(f"prop: {prop} value: [{res}]")
if res == 'Property not found' or res is None:
if not prop2:
# debug(f"Property {prop} not found.")
return ''
res = self.props.get(f"bootloader_{prop2}")
# debug(f"prop2: {prop2} value: [{res}]")
if res == 'Property not found' or res is None:
# debug(f"Bootloader property {prop} and {prop2} are not found.")
return ''
return res
else:
res = self.props.get(prop)
# debug(f"prop: {prop} value: [{res}]")
if res == 'Property not found' or res is None:
if prop2:
res = self.props.get(prop2)
# debug(f"prop2: {prop2} value: [{res}]")
if res == 'Property not found' or res is None:
# debug(f"Bootloader property {prop} and {prop2} are not found.")
return ''
return res
else:
# debug(f"Property {prop} not found.")
return ''
return res
# ----------------------------------------------------------------------------
# method dump_prop
# ----------------------------------------------------------------------------
def dump_props(self): # sourcery skip: use-join
print("\nDumping properties ...")
data = ''
for key, value in self.props.property.items():
data += f"[{key}]: [{value}]\n"
print(data)
# ----------------------------------------------------------------------------
# property has_init_boot
# ----------------------------------------------------------------------------
@property
def has_init_boot(self):
if self._has_init_boot is None:
return False
else:
return self._has_init_boot
# ----------------------------------------------------------------------------
# property active_slot
# ----------------------------------------------------------------------------
@property
def active_slot(self):
res = self.get_prop('current-slot', 'ro.boot.slot_suffix')
if not res:
return ''
if res != '':
res = res.replace("_", "")
return res
# ----------------------------------------------------------------------------
# property inactive_slot
# ----------------------------------------------------------------------------
@property
def inactive_slot(self):
if self.active_slot is None:
return ''
if self.active_slot == 'a':
return 'b'
else:
return 'a'
# ----------------------------------------------------------------------------
# property build
# ----------------------------------------------------------------------------
@property
def build(self):
try:
build = self.get_prop('ro.build.id')
if build is not None and build != '':
return build
build = self.ro_build_fingerprint
if self.ro_build_fingerprint != '':
return build.split('/')[3]
else:
return ''
except Exception:
return ''
# ----------------------------------------------------------------------------
# property api_level
# ----------------------------------------------------------------------------
@property
def firmware_date(self):
if self.build:
build_date_match = re.search(r'\b(\d{6})\b', self.build.lower())
if build_date_match:
build_date = build_date_match[1]
return int(build_date)
# ----------------------------------------------------------------------------
# property api_level
# ----------------------------------------------------------------------------
@property
def api_level(self):
return self.get_prop('ro.build.version.sdk')
# ----------------------------------------------------------------------------
# property hardware
# ----------------------------------------------------------------------------
@property
def hardware(self):
res = self.get_prop('product', 'ro.hardware')
if res:
return res
else:
return ''
# ----------------------------------------------------------------------------
# property architecture
# ----------------------------------------------------------------------------
@property
def architecture(self):
return self.get_prop('ro.product.cpu.abi')
# ----------------------------------------------------------------------------
# property ro_build_fingerprint
# ----------------------------------------------------------------------------
@property
def ro_build_fingerprint(self):
res = self.get_prop('ro.build.fingerprint')
if res == '':
return f"{self.get_prop('ro.product.brand')}/{self.get_prop('ro.product.name')}/{self.get_prop('ro.product.device')}:{self.get_prop('ro.build.version.release')}/{self.get_prop('ro.build.id')}/{self.get_prop('ro.build.version.incremental')}:{self.get_prop('ro.build.type')}/{self.get_prop('ro.build.tags')}"
# ----------------------------------------------------------------------------
# property ro_boot_flash_locked
# ----------------------------------------------------------------------------
@property
def ro_boot_flash_locked(self):
res = self.get_prop('ro.boot.flash.locked')
if res == '0':
add_unlocked_device(self.id)
return res
# ----------------------------------------------------------------------------
# property unlocked
# ----------------------------------------------------------------------------
@property
def unlocked(self):
res = self.get_prop('unlocked')
if res != 'yes':
return False
add_unlocked_device(self.id)
return True
# ----------------------------------------------------------------------------
# property root_symbol
# ----------------------------------------------------------------------------
@property
def root_symbol(self):
if self.mode == 'f.b':
return '?'
elif self.rooted:
return '✓'
else:
return '✗'
# ----------------------------------------------------------------------------
# property kernel
# ----------------------------------------------------------------------------
@property
def kernel(self):
if self._kernel is None and self.mode == 'adb':
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell uname -a"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
self._kernel = res.stdout.strip('\n')
match = re.search(r"\b(\d+\.\d+\.\d+-android\d+)\b", self._kernel)
if match:
self._kmi = match[1]
else:
self._kmi = None
except Exception:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get kernel information.")
traceback.print_exc()
self._rooted = None
self._magisk_denylist_enforced = None
self._magisk_zygisk_enabled = None
return self._kernel
# ----------------------------------------------------------------------------
# property kmi
# ----------------------------------------------------------------------------
@property
def kmi(self):
try:
match = re.search(r"\b(\d+\.\d+\.\d+-android\d+)\b", self.kernel)
if match:
return match[1]
else:
return ''
except Exception:
return ''
# ----------------------------------------------------------------------------
# property is_gki
# ----------------------------------------------------------------------------
@property
def is_gki(self):
try:
ro_kernel_version = self.get_prop('ro.kernel.version')
if parse(ro_kernel_version) >= parse('5.4'):
return True
else:
return False
except Exception:
return False
# ----------------------------------------------------------------------------
# property magisk_path
# ----------------------------------------------------------------------------
@property
def magisk_path(self):
try:
magisk_path = get_magisk_package()
if self.true_mode == 'adb' and magisk_path is not None and magisk_path != '':
res = self.get_package_path(magisk_path, True)
if res != -1:
return res
self._rooted = None
self._magisk_denylist_enforced = None
self._magisk_zygisk_enabled = None
return None
except Exception:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get magisk path")
traceback.print_exc()
return None
# ----------------------------------------------------------------------------
# property ksu_path
# ----------------------------------------------------------------------------
@property
def ksu_path(self):
try:
if self.true_mode == 'adb':
res = self.get_package_path(KERNEL_SU_PKG_NAME, True)
if res != -1:
return res
self._rooted = None
self._magisk_denylist_enforced = None
self._magisk_zygisk_enabled = None
return None
except Exception:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get KernelSU path")
traceback.print_exc()
return None
# ----------------------------------------------------------------------------
# property apatch_path
# ----------------------------------------------------------------------------
@property
def apatch_path(self):
try:
if self.true_mode == 'adb':
res = self.get_package_path(APATCH_PKG_NAME, True)
if res != -1:
return res
self._rooted = None
self._magisk_denylist_enforced = None
self._magisk_zygisk_enabled = None
return None
except Exception:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get APatch path")
traceback.print_exc()
return None
# ----------------------------------------------------------------------------
# property magisk_version
# ----------------------------------------------------------------------------
@property
def magisk_version(self):
if self._magisk_version is None and self.mode == 'adb' and self.rooted:
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'magisk -c\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
regex = re.compile("(.*?):.*\((.*?)\)")
m = re.findall(regex, res.stdout)
if m:
self._magisk_version = f"{m[0][0]}:{m[0][1]}"
self._magisk_version_code = f"{m[0][1]}"
else:
self._magisk_version = res.stdout
self._magisk_version_code = res.stdout
self._magisk_version_code = self._magisk_version.strip(':')
self._magisk_version = self._magisk_version.strip('\n')
except Exception:
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'/data/adb/magisk/magisk32 -c\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
self._magisk_version = res.stdout.strip('\n')
self._magisk_version_code = self._magisk_version.strip(':')
except Exception:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get magisk version, assuming that it is not rooted.")
traceback.print_exc()
self._rooted = None
self._magisk_denylist_enforced = None
self._magisk_zygisk_enabled = None
return self._magisk_version
# ----------------------------------------------------------------------------
# property magisk_version_code
# ----------------------------------------------------------------------------
@property
def magisk_version_code(self):
if self._magisk_version_code is None:
return ''
else:
return self._magisk_version_code
# ----------------------------------------------------------------------------
# property magisk_config_path
# ----------------------------------------------------------------------------
@property
def magisk_config_path(self):
if self._magisk_config_path is None and self.mode == 'adb' and self.rooted:
try:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'ls -1 $(magisk --path)/.magisk/config\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
self._magisk_config_path = res.stdout.strip('\n')
else:
self._magisk_config_path = None
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get magisk sha1.")
puml("#red:ERROR: Could not get magisk sha1;\n", True)
self._magisk_config_path = None
return self._magisk_config_path
# ----------------------------------------------------------------------------
# property current_device_print
# ----------------------------------------------------------------------------
@property
def current_device_print(self):
return process_dict(the_dict=self.props.property, add_missing_keys=True, pif_flavor='playintegrityfork_9999999')
# ----------------------------------------------------------------------------
# property current_device_props_in_json
# ----------------------------------------------------------------------------
@property
def current_device_props_as_json(self): # sourcery skip: use-join
return json.dumps(self.props.property, indent=4)
# ----------------------------------------------------------------------------
# method get_partitions
# ----------------------------------------------------------------------------
def get_partitions(self):
try:
if self.mode != 'adb':
return -1
if self.rooted:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'cd /dev/block/bootdevice/by-name/; ls -1 .\'\""
else:
theCmd = f"\"{get_adb()}\" -s {self.id} shell cd /dev/block/bootdevice/by-name/; ls -1 ."
try:
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
list = res.stdout.split('\n')
else:
return -1
if not list:
return -1
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get partitions list.")
puml("#red:ERROR: Could not get partitions list.;\n", True)
return -1
return list
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error in get_partitions.")
puml("#red:Encountered an error in get_partitions.;\n")
traceback.print_exc()
return -1
# ----------------------------------------------------------------------------
# method get_verity_verification
# ----------------------------------------------------------------------------
def get_verity_verification(self, item):
if self.mode != 'adb':
return -1
if not self.rooted:
return -1
try:
res = self.push_avbctl()
if res != 0:
return -1
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'/data/local/tmp/avbctl get-{item}\'\""
print(f"Checking {item} status: ...")
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
return res.stdout
print(f"Return Code: {res.returncode}.")
print(f"Stdout: {res.stdout}")
print(f"Stderr: {res.stderr}")
return -1
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get {item} status.")
puml(f"#red:ERROR: Could not get {item} status.;\n", True)
return -1
# ----------------------------------------------------------------------------
# method reset_ota_update
# ----------------------------------------------------------------------------
def reset_ota_update(self):
if self.mode != 'adb':
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: reset_ota_update function is only available in adb mode.\nAborting ...")
return -1
if not self.rooted:
return -1
try:
res = self.push_update_engine_client(local_filename="update_engine_client_r72")
if res != 0:
return -1
print("Cancelling ongoing OTA update (if one is in progress) ...")
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'/data/local/tmp/update_engine_client --cancel\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess):
debug(f"{res.stdout} {res.stderr}")
if (res.returncode == 1 or "CANNOT LINK EXECUTABLE" in res.stderr):
print("Trying again with an older binary to Cancel ongoing OTA update (if one is in progress) ...")
res = self.push_update_engine_client(local_filename="update_engine_client_r28")
if res != 0:
return -1
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'/data/local/tmp/update_engine_client --cancel\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess):
debug(f"{res.stdout} {res.stderr}")
if not (res.returncode == 0 or res.returncode == 248):
return -1
print("Resetting an already applied update (if one exists) ...")
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'/data/local/tmp/update_engine_client --reset_status\'\""
res = run_shell2(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
return res.stdout
print(f"Return Code: {res.returncode}.")
print(f"Stdout: {res.stdout}")
print(f"Stderr: {res.stderr}")
return -1
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an exception if reset_ota_update function.")
puml(f"#red:ERROR: Encountered an exception if reset_ota_update function.;\n", True)
return -1
# ----------------------------------------------------------------------------
# method get_vbmeta_details
# ----------------------------------------------------------------------------
def get_vbmeta_details(self):
if self.mode != 'adb' or not self.rooted:
return None
try:
self.vbmeta.clear()
vbmeta_a = ''
vbmeta_b = ''
vbmeta_a_only = ''
vbmeta = Vbmeta()
vbmeta.type = 'none'
partitions = self.get_partitions()
if "vbmeta_a" in partitions:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'dd if=/dev/block/bootdevice/by-name/vbmeta_a bs=1 skip=123 count=1 status=none | xxd -p\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
vbmeta.type = 'ab'
vbmeta_a = int(res.stdout.strip('\n'))
if "vbmeta_b" in partitions:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'dd if=/dev/block/bootdevice/by-name/vbmeta_b bs=1 skip=123 count=1 status=none | xxd -p\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
vbmeta.type = 'ab'
vbmeta_b = int(res.stdout.strip('\n'))
if "vbmeta_a" not in partitions and "vbmeta_b" not in partitions and "vbmeta" in partitions:
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'dd if=/dev/block/bootdevice/by-name/vbmeta bs=1 skip=123 count=1 status=none | xxd -p\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
vbmeta.type = 'a_only'
vbmeta_a_only = int(res.stdout.strip('\n'))
if vbmeta_a == 0:
vbmeta.verity_a = True
vbmeta.verification_a = True
elif vbmeta_a == 1:
vbmeta.verity_a = False
vbmeta.verification_a = True
elif vbmeta_a == 2:
vbmeta.verity_a = True
vbmeta.verification_a = False
elif vbmeta_a == 3:
vbmeta.verity_a = False
vbmeta.verification_a = False
if vbmeta_b == 0:
vbmeta.verity_b = True
vbmeta.verification_b = True
elif vbmeta_b == 1:
vbmeta.verity_b = False
vbmeta.verification_b = True
elif vbmeta_b == 2:
vbmeta.verity_b = True
vbmeta.verification_b = False
elif vbmeta_b == 3:
vbmeta.verity_b = False
vbmeta.verification_b = False
if vbmeta.type == "a_only":
if vbmeta_a_only == 0:
vbmeta.verity_a = True
vbmeta.verification_a = True
elif vbmeta_a_only == 1:
vbmeta.verity_a = False
vbmeta.verification_a = True
elif vbmeta_a_only == 2:
vbmeta.verity_a = True
vbmeta.verification_a = False
elif vbmeta_a_only == 3:
vbmeta.verity_a = False
vbmeta.verification_a = False
self.vbmeta = vbmeta
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get vbmeta details.")
puml("#red:ERROR: Could not get vbmeta details.;\n", True)
return vbmeta
return vbmeta
# ----------------------------------------------------------------------------
# method get_magisk_backups
# ----------------------------------------------------------------------------
def get_magisk_backups(self):
if self.mode != 'adb' or not self.rooted:
return -1
try:
self.backups.clear()
theCmd = f"\"{get_adb()}\" -s {self.id} shell \"su -c \'ls -l -d -1 /data/magisk_backup_*\'\""
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.returncode == 0:
list = res.stdout.split('\n')
else:
return -1
if not list:
return -1
for item in list:
if item:
regex = re.compile("d.+root\sroot\s\w+\s(.*)\s\/data\/magisk_backup_(.*)")
m = re.findall(regex, item)
if m:
backup_date = f"{m[0][0]}"
backup_sha1 = f"{m[0][1]}"
backup = Backup(backup_sha1)
backup.date = backup_date
with contextlib.suppress(Exception):
backup.firmware = self.get_firmware_from_boot(backup_sha1)
self.backups[backup_sha1] = backup
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not get backup list.")
puml("#red:ERROR: Could not get backup list.;\n", True)
return -1
return 0
# ----------------------------------------------------------------------------
# function get_firmware_from_boot
# ----------------------------------------------------------------------------
def get_firmware_from_boot(self, sha1):
try:
con = get_db()
con.execute("PRAGMA foreign_keys = ON")
con.commit()
cursor = con.cursor()
cursor.execute(f"SELECT package_sig FROM PACKAGE WHERE boot_hash = '{sha1}'")
data = cursor.fetchall()
if len(data) > 0:
return data[0][0]
else:
return ''
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while getting firmware from boot.")
puml("#red:Encountered an error while while getting firmware from boot.;\n")
traceback.print_exc()
# ----------------------------------------------------------------------------
# property magisk_backups
# ----------------------------------------------------------------------------
@property