forked from badabing2005/PixelFlasher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules.py
3013 lines (2758 loc) · 144 KB
/
modules.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
import contextlib
import math
import ntpath
import os
import shutil
import sqlite3 as sl
import sys
import tempfile
import time
import fnmatch
from datetime import datetime
from urllib.parse import urlparse
import wx
from packaging.version import parse
from platformdirs import *
from constants import *
from file_editor import FileEditor
from magisk_downloads import MagiskDownloads
from message_box_ex import MessageBoxEx
from payload_dumper import extract_payload
from phone import get_connected_devices
from runtime import *
# ============================================================================
# Class FlashFile
# ============================================================================
class FlashFile():
def __init__(self, linenum = '', platform = '', type = '', command = '', action = '', arg1 = '', arg2 = ''):
# Instance variables
self.linenum = linenum
self.platform = platform
self.type = type
self.command = command
self.action = action
self.arg1 = arg1
self.arg2 = arg2
@property
def full_line(self):
response = f"{self.command} {self.action} {self.arg1} {self.arg2}"
return response.strip()
@property
def sync_line(self):
if self.type in ['init', 'sleep']:
response = self.type
elif self.type in ['path', 'if_block']:
# don't include
response = ''
else:
response = f"{self.command} {self.action} {self.arg1} {self.arg2}"
return response.strip()
# ============================================================================
# Function check_platform_tools
# ============================================================================
def check_platform_tools(self):
if sys.platform == "win32":
adb_binary = 'adb.exe'
fastboot_binary = 'fastboot.exe'
else:
adb_binary = 'adb'
fastboot_binary = 'fastboot'
if self.config.platform_tools_path:
adb = os.path.join(self.config.platform_tools_path, adb_binary)
fastboot = os.path.join(self.config.platform_tools_path, fastboot_binary)
if os.path.exists(fastboot) and os.path.exists(adb):
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} Selected Platform Tools Path:\n{self.config.platform_tools_path}.")
adb = os.path.join(self.config.platform_tools_path, adb_binary)
fastboot = os.path.join(self.config.platform_tools_path, fastboot_binary)
set_adb(adb)
set_fastboot(fastboot)
set_adb_sha256(sha256(adb))
set_fastboot_sha256(sha256(fastboot))
res = identify_sdk_version(self)
print(f"SDK Version: {get_sdk_version()}")
print(f"Adb SHA256: {get_adb_sha256()}")
print(f"Fastboot SHA256: {get_fastboot_sha256()}")
puml(f":Selected Platform Tools;\nnote left: {self.config.platform_tools_path}\nnote right:{get_sdk_version()}\n")
if res == -1:
return -1
set_android_product_out(self.config.platform_tools_path)
return
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: The selected path {self.config.platform_tools_path} does not have adb and or fastboot")
puml(f"#red:Selected Platform Tools;\nnote left: {self.config.platform_tools_path}\nnote right:The selected path does not have adb and or fastboot\n")
self.config.platform_tools_path = None
set_adb(None)
set_fastboot(None)
if not self.config.platform_tools_path:
print("Looking for Android Platform Tools in system PATH environment ...")
adb = which(adb_binary)
if adb:
folder_path = os.path.dirname(adb)
print(f"Found Android Platform Tools in {folder_path}")
adb = os.path.join(folder_path, adb_binary)
fastboot = os.path.join(folder_path, fastboot_binary)
set_adb(adb)
set_fastboot(fastboot)
set_adb_sha256(sha256(adb))
if os.path.exists(get_fastboot()):
self.config.platform_tools_path = folder_path
res = identify_sdk_version(self)
set_fastboot_sha256(sha256(fastboot))
print(f"SDK Version: {get_sdk_version()}")
print(f"Adb SHA256: {get_adb_sha256()}")
print(f"Fastboot SHA256: {get_fastboot_sha256()}")
if res == -1:
return -1
set_android_product_out(self.config.platform_tools_path)
return
else:
print(f"fastboot is not found in: {self.config.platform_tools_path}")
self.config.platform_tools_path = None
set_adb(None)
set_fastboot(None)
else:
print("Android Platform Tools is not found.")
with contextlib.suppress(Exception):
if self.config.platform_tools_path:
self.platform_tools_picker.SetPath(self.config.platform_tools_path)
set_android_product_out(self.config.platform_tools_path)
else:
self.platform_tools_picker.SetPath('')
return -1
# ============================================================================
# Function set_android_product_out
# ============================================================================
def set_android_product_out(sdk_path):
# add the SDK path to to ANDROID_PRODUCT_OUT env
env_vars = get_env_variables()
env_vars["ANDROID_PRODUCT_OUT"] = f"{sdk_path}"
set_env_variables(env_vars)
# ============================================================================
# Function populate_boot_list
# ============================================================================
def populate_boot_list(self):
self.list.DeleteAllItems()
con = get_db()
con.execute("PRAGMA foreign_keys = ON")
con.commit()
sql = """
SELECT
BOOT.id as boot_id,
BOOT.boot_hash,
BOOT.file_path as boot_path,
BOOT.is_patched,
BOOT.patch_method,
BOOT.magisk_version,
BOOT.hardware,
BOOT.epoch as boot_date,
PACKAGE.id as package_id,
PACKAGE.boot_hash as package_boot_hash,
PACKAGE.type as package_type,
PACKAGE.package_sig,
PACKAGE.file_path as package_path,
PACKAGE.epoch as package_date,
BOOT.is_odin
FROM BOOT
JOIN PACKAGE_BOOT
ON BOOT.id = PACKAGE_BOOT.boot_id
JOIN PACKAGE
ON PACKAGE.id = PACKAGE_BOOT.package_id
"""
# Apply filter if show all is not selected
parameters = []
if not self.config.show_all_boot:
rom_path = ''
firmware_path = ''
if self.config.custom_rom and self.config.advanced_options:
rom_path = self.config.custom_rom_path
if self.config.firmware_path:
firmware_path = self.config.firmware_path
sql += """
WHERE
(BOOT.is_patched = 0 AND PACKAGE.file_path IN (?, ?))
OR
(BOOT.is_patched = 1 AND PACKAGE.boot_hash IN (
SELECT PACKAGE.boot_hash
FROM BOOT
JOIN PACKAGE_BOOT
ON BOOT.id = PACKAGE_BOOT.boot_id
JOIN PACKAGE
ON PACKAGE.id = PACKAGE_BOOT.package_id
WHERE
(BOOT.is_patched = 0 AND PACKAGE.file_path IN (?, ?))
))
"""
parameters.extend([firmware_path, rom_path, firmware_path, rom_path])
# Order by is_patched in ascending order, then epoch in ascending order
sql += "ORDER BY BOOT.is_patched ASC, BOOT.epoch ASC;"
with con:
data = con.execute(sql, parameters)
i = 0
for row in data:
index = self.list.InsertItem(i, row[1][:8]) # boot_hash (SHA1)
self.list.SetItem(index, 1, row[9][:8]) # package_boot_hash (Source SHA1)
self.list.SetItem(index, 2, row[11]) # package_sig (Package Fingerprint)
patch_method = row[4] or ''
self.list.SetItem(index, 3, str(row[5])) # pacthed with magisk_version
self.list.SetItem(index, 4, patch_method) # patched_method
self.list.SetItem(index, 5, row[6]) # hardware
ts = datetime.fromtimestamp(row[7])
self.list.SetItem(index, 6, ts.strftime('%Y-%m-%d %H:%M:%S')) # boot_date
self.list.SetItem(index, 7, row[12]) # package_path
if row[3]:
self.list.SetItemColumnImage(i, 0, 0)
else:
self.list.SetItemColumnImage(i, 0, -1)
i += 1
# auto size columns to largest text, including the header (except the last column)
cw = 0
column_widths = get_boot_column_widths()
for i in range(self.list.ColumnCount - 1):
self.list.SetColumnWidth(i, -1) # Set initial width to -1 (default)
width = self.list.GetColumnWidth(i)
self.list.SetColumnWidth(i, -2) # Auto-size column width to largest text
width = max(width, self.list.GetColumnWidth(i), column_widths[i]) # Get the maximum width
if width > column_widths[i]:
column_widths[i] = width # Store / update the width in the array
self.list.SetColumnWidth(i, width) # Set the column width
cw += width
# Set the last column width to the available room
available_width = self.list.BestVirtualSize.Width - cw - 10
self.list.SetColumnWidth(self.list.ColumnCount - 1, available_width)
set_boot_column_widths(column_widths)
# disable buttons
self.config.boot_id = None
self.config.selected_boot_md5 = None
if self.list.ItemCount == 0 :
if self.config.firmware_path:
print("\nPlease Process the firmware!")
else:
print("\nPlease select a boot image!")
self.process_firmware.SetFocus()
# we need to do this, otherwise the focus goes on the next control, which is a radio button, and undesired.
# ============================================================================
# Function identify_sdk_version
# ============================================================================
def identify_sdk_version(self):
sdk_version = None
set_sdk_state(False)
# Let's grab the adb version
with contextlib.suppress(Exception):
if get_adb():
theCmd = f"\"{get_adb()}\" --version"
response = run_shell(theCmd)
if response.stdout:
# Split lines based on mixed EOL formats
lines = re.split(r'\r?\n', response.stdout)
for line in lines:
if 'Version' in line:
sdk_version = line.split()[1]
set_sdk_version(sdk_version)
# If version is old treat it as bad SDK
sdkver = sdk_version.split("-")[0]
if parse(sdkver) < parse(SDKVERSION) or (sdkver in ('34.0.0', '34.0.1', '34.0.2', '34.0.3')):
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Detected old or problematic Android Platform Tools version {sdk_version}")
# confirm if you want to use older version
dlg = wx.MessageDialog(None, f"You have an old or problematic Android platform Tools version {sdk_version}\nYou are strongly advised to update to the latest known good version to avoid any issues.\n(Android Platform-Tools version 33.0.3 is known to be good).\n\nAre you sure want to continue?",'Bad Android Platform Tools',wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION)
result = dlg.ShowModal()
puml(f"#red:Selected Platform Tools;\nnote left: {self.config.platform_tools_path}\nnote right:ERROR: Detected old or problematic Android Platform Tools version {sdk_version}\n")
if result == wx.ID_YES:
print(f"{datetime.now():%Y-%m-%d %H:%M:%S} User accepted the bad version {sdk_version} of Android platform tools.")
set_sdk_state(True)
puml("#red:User wanted to proceed regardless;\n")
else:
print("Bad Android platform tools is not accepted. For your protection, disabling device selection.")
print("Please update Android SDK.\n")
break
# 34.01 is still broken, skip the whitelisted binaries
# elif sdkver == '34.0.1' and (
# get_adb_sha256() not in (
# '30c68c1c1a9814a724f47ca544f273b8097263677383046ddb7a0e8c26f7dc60',
# 'bfd5ea39c672b8f0f51796d6fe5439f152e86eafbba9f402d3abda802050e956',
# '9d8e3e278b4415416b5da6f94f752e808f8a71fa8397bb6a765c1b44bb807bb2')
# or get_fastboot_sha256() not in (
# 'd765b626aa5b54d9d226eb1a915657c6197379835bde67742f9a2832c8c5c2a9',
# 'e8e6b8f4e8d69401967d16531308b48f144202e459662eae656a0c6e68c2741f',
# '29c66b605521dea3c3e32f3b1fd7c30a1637ec3eb729820a48bd6827e4659a20')):
# print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: The selected Android Platform Tools version {sdkver} has known issues, please select another version.")
# puml(f"#red:Android Platform Tools version {sdkver} has known issues;\n")
# dlg = wx.MessageDialog(None, f"Android Platform Tools version {sdkver} has known issues, please select another version.",f"Android Platform Tools {sdkver}",wx.OK | wx.ICON_EXCLAMATION)
# result = dlg.ShowModal()
# break
else:
set_sdk_state(True)
elif response.stderr:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: {response.stderr}")
self.update_widget_states()
if get_sdk_state():
return
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Android Platform Tools version is not available or is too old.")
print(" For your protection, disabling device selection.")
print(" Please select valid Android SDK.\n")
puml("#pink:For your protection, disabled device selection;\n")
self.config.device = None
self.device_choice.SetItems([''])
self.device_choice.Select(-1)
return -1
# ============================================================================
# Function get_flash_settings
# ============================================================================
def get_flash_settings(self):
message = ''
isPatched = ''
p_custom_rom = self.config.custom_rom and self.config.advanced_options
p_custom_rom_path = self.config.custom_rom_path
boot = get_boot()
device = get_phone()
if not device:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: You must first select a valid device.")
return
message += f"Android SDK Version: {get_sdk_version()}\n"
message += f"Device: {self.config.device} {device.hardware} {device.build}\n"
message += f"Factory Image: {self.config.firmware_path}\n"
if p_custom_rom :
message += f"Custom Rom: {str(p_custom_rom)}\n"
message += f"Custom Rom File: {p_custom_rom_path}\n"
rom_file = ntpath.basename(p_custom_rom_path)
set_custom_rom_file(rom_file)
message += f"\nBoot image: {boot.boot_hash[:8]} / {boot.package_boot_hash[:8]} \n"
message += f" From: {boot.package_path}\n"
if boot.is_patched:
if boot.patch_method:
message += f" Patched with Magisk {boot.magisk_version} on {boot.hardware} method: {boot.patch_method}\n"
else:
message += f" Patched with Magisk {boot.magisk_version} on {boot.hardware}\n"
message += f"\nFlash Mode: {self.config.flash_mode}\n"
message += "\n"
return message
# ============================================================================
# Function wifi_adb_connect
# ============================================================================
def wifi_adb_connect(self, value, disconnect = False):
if disconnect:
command = 'disconnect'
else:
command = 'connect'
print(f"Remote ADB {command}ing: {value}")
if get_adb():
puml(":Wifi ADB;\n", True)
if ':' in value:
ip,port = value.split(':')
else:
ip = value.strip()
port = '5555'
theCmd = f"\"{get_adb()}\" {command} {ip}:{port}"
res = run_shell(theCmd)
puml(f"note right\n=== {command} to: {ip}:{port}\nend note\n")
if res.returncode == 0 and 'cannot' not in res.stdout and 'failed' not in res.stdout:
print(f"ADB {command}ed: {ip}:{port}")
puml(f"#palegreen:Succeeded;\n")
self.device_choice.SetItems(get_connected_devices())
self._select_configured_device()
if not disconnect:
print(f"Please select the device: {ip}:{port}")
return 0
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not {command} {ip}:{port}\n")
print(f"{res.stderr}")
print(f"{res.stdout}")
puml(f"#red:**Failed**\n{res.stderr}\n{res.stdout};\n")
return -1
# ============================================================================
# Function adb_kill_server
# ============================================================================
def adb_kill_server(self):
if get_adb():
print("Invoking adb kill-server ...")
puml(":adb kill-server;\n", True)
theCmd = f"\"{get_adb()}\" kill-server"
res = run_shell(theCmd)
if res.returncode == 0:
print("returncode: 0")
puml(f"#palegreen:Succeeded;\n")
self.device_choice.SetItems(get_connected_devices())
self._select_configured_device()
return 0
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not kill adb server.\n")
print(f"{res.stderr}")
print(f"{res.stdout}")
puml(f"#red:**Failed**\n{res.stderr}\n{res.stdout};\n")
return -1
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Missing Android platform tools.\n")
puml(f"#red:Missing Android platform tools;\n")
return -1
# ============================================================================
# Function set_flash_button_state
# ============================================================================
def set_flash_button_state(self):
try:
boot = get_boot()
if self.config.firmware_path and os.path.exists(boot.package_path):
self.flash_button.Enable()
else:
self.flash_button.Disable()
except Exception:
self.flash_button.Disable()
# ============================================================================
# Function select_firmware
# ============================================================================
def select_firmware(self):
puml(":Selecting Firmware;\n", True)
firmware = ntpath.basename(self.config.firmware_path)
filename, extension = os.path.splitext(firmware)
extension = extension.lower()
if extension in ['.zip', '.tgz', '.tar']:
print(f"{datetime.now():%Y-%m-%d %H:%M:%S} The following firmware is selected:\n{firmware}")
firmware_hash = sha256(self.config.firmware_path)
print(f"Selected Firmware {firmware} SHA-256: {firmware_hash}")
puml(f"note right\n{firmware}\nSHA-256: {firmware_hash}\nend note\n")
# Check to see if the first 8 characters of the checksum is in the filename, Google published firmwares do have this.
if firmware_hash[:8] in firmware:
print(f"Expected to match {firmware_hash[:8]} in the filename and did. This is good!")
puml(f"#CDFFC8:Checksum matches portion of the filename {firmware};\n")
set_firmware_hash_validity(True)
else:
print(f"WARNING: Expected to match {firmware_hash[:8]} in the filename but didn't, please double check to make sure the checksum is good.")
puml("#orange:Unable to match the checksum in the filename;\n")
set_firmware_hash_validity(False)
firmware = filename.split("-")
if len(firmware) == 1:
set_firmware_model(None)
set_firmware_id(filename)
else:
try:
set_firmware_model(firmware[0])
if firmware[1] == 'ota':
set_firmware_id(f"{firmware[0]}-{firmware[1]}-{firmware[2]}")
set_ota(True)
self.enable_disable_radio_button('OTA', True, selected=True, just_select=True)
self.config.flash_mode = 'OTA'
else:
set_firmware_id(f"{firmware[0]}-{firmware[1]}")
if self.config.flash_mode == 'OTA':
self.config.flash_mode = 'dryRun'
self.enable_disable_radio_button('dryRun', True, selected=True, just_select=True)
set_ota(False)
except Exception as e:
set_firmware_model(None)
set_firmware_id(filename)
if get_firmware_id():
set_flash_button_state(self)
else:
self.flash_button.Disable()
populate_boot_list(self)
self.update_widget_states()
return firmware_hash
else:
print(f"{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: The selected file {firmware} is not a valid archive file.")
puml("#red:The selected firmware is not valid;\n")
self.config.firmware_path = None
self.firmware_picker.SetPath('')
return 'Select Pixel Firmware'
# ============================================================================
# Function process_file
# ============================================================================
def process_file(self, file_type):
print("")
print("==============================================================================")
print(f" {datetime.now():%Y-%m-%d %H:%M:%S} PixelFlasher {VERSION} Processing {file_type} file ...")
print("==============================================================================")
puml(f"#cyan:Process {file_type};\n", True)
config_path = get_config_path()
path_to_7z = get_path_to_7z()
boot_images = os.path.join(config_path, get_boot_images_dir())
tmp_dir_full = os.path.join(config_path, 'tmp')
con = get_db()
con.execute("PRAGMA foreign_keys = ON")
con.commit()
cursor = con.cursor()
start_1 = time.time()
checksum = ''
is_odin = False
is_payload_bin = False
factory_images = os.path.join(config_path, 'factory_images')
if file_type == 'firmware':
file_to_process = self.config.firmware_path
package_sig = get_firmware_id()
package_dir_full = os.path.join(factory_images, package_sig)
found_flash_all_bat = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="flash-all.bat", nested=False)
found_flash_all_sh = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="flash-all.sh", nested=False)
found_boot_img = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="boot.img", nested=True)
found_init_boot_img = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="init_boot.img", nested=True)
found_boot_img_lz4 = ''
set_firmware_has_init_boot(False)
if found_init_boot_img:
set_firmware_has_init_boot(True)
if found_flash_all_bat and found_flash_all_sh and get_firmware_hash_validity():
# assume Pixel factory file
print("Detected Pixel firmware")
image_file_path = os.path.join(package_dir_full, f"image-{package_sig}.zip")
# Unzip the factory image
debug(f"Unzipping Image: {file_to_process} into {package_dir_full} ...")
theCmd = f"\"{path_to_7z}\" x -bd -y -o\"{factory_images}\" \"{file_to_process}\""
debug(theCmd)
res = run_shell2(theCmd)
elif found_boot_img or found_init_boot_img:
print(f"Detected Non Pixel firmware, with: {found_boot_img} {found_init_boot_img}")
# TODO
# Check if the firmware file starts with image-* and warn the user or abort
firmware_file_name = os.path.basename(file_to_process)
if firmware_file_name.startswith('image-'):
title = "Possibly extracted firmware."
message = f"WARNING: It looks like you have extracted the firmware file.\nand selected the image zip from it.\n\n"
message += f"You should not extract the file, please select the downloaded firmware file instead\n\n"
message += f"If this is not the case, and you want to continue with this selection\n"
message += "Click OK to accept and continue.\n"
message += "or Hit CANCEL to abort."
print(f"\n*** Dialog ***\n{message}\n______________\n")
puml("#orange:WARNING;\n", True)
puml(f"note right\n{message}\nend note\n")
dlg = wx.MessageDialog(None, message, title, wx.CANCEL | wx.OK | wx.ICON_EXCLAMATION)
result = dlg.ShowModal()
if result != wx.ID_OK:
print("User pressed cancel.")
puml("#pink:User Pressed Cancel to abort;\n}\n")
print("Aborting ...\n")
return
print("User pressed ok.")
puml(":User Pressed OK to continue;\n")
image_file_path = file_to_process
elif check_zip_contains_file(file_to_process, "payload.bin"):
is_payload_bin = True
if get_firmware_hash_validity() and get_ota():
print("Detected OTA file, please select a firmware file")
else:
print("Detected a firmware, with payload.bin")
else:
# -------------------------
# Samsung firmware handling
# -------------------------
# Get file list from zip
file_list = get_zip_file_list(file_to_process)
patterns = {
'AP': 'AP_*.tar.md5',
'BL': 'BL_*.tar.md5',
'HOME_CSC': 'HOME_CSC_*.tar.md5',
'CSC': 'CSC_*.tar.md5',
}
found_ap = ''
found_bl = ''
found_csc = ''
found_home_csc = ''
# see if we find AP_*.tar.md5, if yes set is_samsung flag
for file in file_list:
if not found_ap and fnmatch.fnmatch(file, patterns['AP']):
# is_odin = 1
is_odin = True
print(f"Found {file} file.")
found_ap = file
if not found_bl and fnmatch.fnmatch(file, patterns['BL']):
print(f"Found {file} file.")
found_bl = file
if not found_home_csc and fnmatch.fnmatch(file, patterns['HOME_CSC']):
print(f"Found {file} file.")
found_home_csc = file
if not found_csc and fnmatch.fnmatch(file, patterns['CSC']):
print(f"Found {file} file.")
found_csc = file
# TODO check settings, see if offer samsung extraction options is enabled
# if yes, offer list of found files to extract
if found_ap:
# assume Samsung firmware
print("Detected Samsung firmware")
image_file_path = os.path.join(package_dir_full, found_ap)
# Unzip the factory image
debug(f"Unzipping Image: {file_to_process} into {package_dir_full} ...")
theCmd = f"\"{path_to_7z}\" x -bd -y -o\"{package_dir_full}\" \"{file_to_process}\""
debug(theCmd)
res = run_shell2(theCmd)
# see if there is boot.img.lz4 in AP file
found_boot_img_lz4 = check_archive_contains_file(archive_file_path=image_file_path, file_to_check="boot.img.lz4", nested=False)
if found_boot_img_lz4:
print(f"Extracting boot.img.lz4 from {found_ap} ...")
puml(f":Extract boot.img.lz4;\n")
theCmd = f"\"{path_to_7z}\" x -bd -y -o\"{package_dir_full}\" \"{image_file_path}\" boot.img.lz4"
debug(f"{theCmd}")
res = run_shell(theCmd)
# expect ret 0
if res.returncode != 0:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract boot.img.lz4")
print(res.stderr)
puml("#red:ERROR: Could not extract boot.img.lz4;\n")
print("Aborting ...\n")
return
else:
# unpack boot.img.lz4
print("Unpacking boot.img.lz4 ...")
puml(f":Unpack boot.img.lz4;\n")
unpack_lz4(os.path.join(package_dir_full, 'boot.img.lz4'), os.path.join(package_dir_full, 'boot.img'))
# Check if it exists
if os.path.exists(os.path.join(package_dir_full, 'boot.img')):
found_boot_img = 'boot.img'
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not unpack boot.img.lz4")
puml("#red:ERROR: Could not unpack boot.img.lz4;\n")
print("Aborting ...\n")
return
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not find boot.img.lz4")
puml("#red:ERROR: Could not find boot.img.lz4;\n")
print("Aborting ...\n")
return
else:
print("Detected Unsupported firmware file.")
print("Aborting ...")
return
else:
file_to_process = self.config.custom_rom_path
found_boot_img = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="boot.img", nested=False)
found_init_boot_img = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="init_boot.img", nested=False)
set_rom_has_init_boot(False)
if found_init_boot_img:
set_rom_has_init_boot(True)
elif check_zip_contains_file(file_to_process, "payload.bin"):
print("Detected a ROM, with payload.bin")
is_payload_bin = True
package_sig = get_custom_rom_id()
package_dir_full = os.path.join(factory_images, package_sig)
image_file_path = file_to_process
puml(f"note right:{image_file_path}\n")
# see if we have a record for the firmware/rom being processed
cursor.execute(f"SELECT ID, boot_hash FROM PACKAGE WHERE package_sig = '{package_sig}' AND file_path = '{file_to_process}'")
data = cursor.fetchall()
if len(data) > 0:
pre_package_id = data[0][0]
pre_checksum = data[0][1]
debug(f"Found a previous {file_type} PACKAGE record id={pre_package_id} for package_sig: {package_sig} Firmware: {file_to_process}")
else:
pre_package_id = 0
pre_checksum = 'x'
# delete all files in tmp folder to make sure we're dealing with new files only.
delete_all(tmp_dir_full)
if is_payload_bin:
# extract the payload.bin into a temporary directory
temp_dir = tempfile.TemporaryDirectory()
temp_dir_path = temp_dir.name
print(f"Extracting payload.bin from {file_to_process} ...")
puml(":Extract payload.bin;\n")
theCmd = f"\"{path_to_7z}\" x -bd -y -o\"{temp_dir_path}\" \"{file_to_process}\" payload.bin"
debug(f"{theCmd}")
res = run_shell(theCmd)
# expect ret 0
if res.returncode != 0:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract payload.bin.")
print(res.stderr)
puml("#red:ERROR: Could not extract payload.bin;\n")
print("Aborting ...\n")
return
# extract boot.img, init_boot.img, vbmeta.img from payload.bin
payload_file_path = os.path.join(temp_dir_path, "payload.bin")
if not os.path.exists(package_dir_full):
os.makedirs(package_dir_full, exist_ok=True)
extract_payload(payload_file_path, out=package_dir_full, diff=False, old='old', images='boot,vbmeta,init_boot')
if os.path.exists(os.path.join(package_dir_full, 'boot.img')):
boot_img_file = os.path.join(package_dir_full, 'boot.img')
shutil.copy(boot_img_file, os.path.join(tmp_dir_full, 'boot.img'), follow_symlinks=True)
boot_file_name = 'boot.img'
if os.path.exists(os.path.join(package_dir_full, 'init_boot.img')):
boot_img_file = os.path.join(package_dir_full, 'init_boot.img')
shutil.copy(boot_img_file, os.path.join(tmp_dir_full, 'init_boot.img'), follow_symlinks=True)
boot_file_name = 'init_boot.img'
found_init_boot_img = 'True' # This is intentionally a string, all we care is for it to not evalute to False
else:
if is_odin:
shutil.copy(os.path.join(package_dir_full, 'boot.img'), os.path.join(tmp_dir_full, 'boot.img'), follow_symlinks=True)
if not os.path.exists(image_file_path):
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: The firmware file did not have the expected structure / contents.")
if file_type == 'firmware':
print(f"Please check {self.config.firmware_path} to make sure it is a valid factory image file.")
puml("#red:The selected firmware is not valid;\n")
print("Aborting ...\n")
return
files_to_extract = ''
if found_boot_img:
boot_file_name = 'boot.img'
files_to_extract += 'boot.img '
if found_init_boot_img:
boot_file_name = 'init_boot.img'
files_to_extract += 'init_boot.img '
files_to_extract = files_to_extract.strip()
if not is_odin:
if not files_to_extract:
print(f"Nothing to extract from {file_type}")
print("Aborting ...")
puml("#red:Nothing to extract from {file_type};\n")
return
print(f"Extracting {boot_file_name} from {image_file_path} ...")
puml(f":Extract {boot_file_name};\n")
theCmd = f"\"{path_to_7z}\" x -bd -y -o\"{tmp_dir_full}\" \"{image_file_path}\" {files_to_extract}"
debug(f"{theCmd}")
res = run_shell(theCmd)
# expect ret 0
if res.returncode != 0:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {boot_file_name}.")
print(res.stderr)
puml(f"#red:ERROR: Could not extract {boot_file_name};\n")
print("Aborting ...\n")
return
# sometimes the return code is 0 but no file to extract, handle that case.
# also handle the case of extraction from payload.bin
boot_img_file = os.path.join(tmp_dir_full, boot_file_name)
if not os.path.exists(boot_img_file):
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {boot_file_name}, ")
print(f"Please make sure the file: {image_file_path} has {boot_file_name} in it.")
puml(f"#red:ERROR: Could not extract {boot_file_name};\n")
print("Aborting ...\n")
return
# get the checksum of the boot_file_name
checksum = sha1(os.path.join(boot_img_file))
print(f"sha1 of {boot_file_name}: {checksum}")
puml(f"note right:sha1 of {boot_file_name}: {checksum}\n")
# if a matching boot_file_name is not found, store it.
cached_boot_img_dir_full = os.path.join(boot_images, checksum)
cached_boot_img_path = os.path.join(cached_boot_img_dir_full, boot_file_name)
print(f"Checking for cached copy of {boot_file_name}")
if not os.path.exists(cached_boot_img_dir_full):
os.makedirs(cached_boot_img_dir_full, exist_ok=True)
if not os.path.exists(cached_boot_img_path):
print(f"Cached copy of {boot_file_name} with sha1: {checksum} is not found.")
print(f"Copying {boot_img_file} to {cached_boot_img_dir_full}")
shutil.copy(boot_img_file, cached_boot_img_dir_full, follow_symlinks=True)
if found_init_boot_img:
# we need to copy boot.img for Pixel 7, 7P, 7a so that we can do live boot.
shutil.copy(os.path.join(tmp_dir_full, 'boot.img'), cached_boot_img_dir_full, follow_symlinks=True)
else:
print(f"Found a cached copy of {file_type} {boot_file_name} sha1={checksum}")
# create PACKAGE db record
sql = 'INSERT INTO PACKAGE (boot_hash, type, package_sig, file_path, epoch ) values(?, ?, ?, ?, ?) ON CONFLICT (file_path) DO NOTHING'
data = checksum, file_type, package_sig, file_to_process, time.time()
try:
cursor.execute(sql, data)
con.commit()
except Exception as e:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error.")
print(e)
package_id = cursor.lastrowid
print(f"Package ID: {package_id}")
# if we didn't insert a new record, let's use the pre_package_id in case we need to insert a record into PACKAGE_BOOT
if package_id == 0:
package_id = pre_package_id
# create BOOT db record
sql = 'INSERT INTO BOOT (boot_hash, file_path, is_patched, magisk_version, hardware, epoch, patch_method, is_odin) values(?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (boot_hash) DO NOTHING'
data = checksum, cached_boot_img_path, 0, '', '', time.time(), '', is_odin
try:
cursor.execute(sql, data)
con.commit()
except Exception as e:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error.")
print(e)
boot_id = cursor.lastrowid
print(f"Boot ID: {boot_id}")
# if boot_id record does not exist, set it to 0
cursor.execute(f"SELECT ID FROM BOOT WHERE id = '{boot_id}'")
data = cursor.fetchall()
if len(data) == 0:
boot_id = 0
# if we didn't insert in BOOT or id does not exist, see if we have a record for the boot being processed in case we need to insert a record into PACKAGE_BOOT
if boot_id == 0:
cursor.execute(f"SELECT ID FROM BOOT WHERE boot_hash = '{pre_checksum}' OR boot_hash = '{checksum}'")
data = cursor.fetchall()
if len(data) > 0:
boot_id = data[0][0]
print(f"Found a previous BOOT record id={boot_id} for boot_hash: {pre_checksum} or {checksum}")
else:
boot_id = 0
# create PACKAGE_BOOT db record
if package_id > 0 and boot_id > 0:
debug(f"Creating PACKAGE_BOOT record, package_id: {package_id} boot_id: {boot_id}")
sql = 'INSERT INTO PACKAGE_BOOT (package_id, boot_id, epoch) values(?, ?, ?) ON CONFLICT (package_id, boot_id) DO NOTHING'
data = package_id, boot_id, time.time()
try:
cursor.execute(sql, data)
con.commit()
package_boot_id = cursor.lastrowid
if package_boot_id == 0:
print(f"Record PACKAGE_BOOT record, package_id: {package_id} boot_id: {boot_id} already exists")
else:
print(f"Package_Boot ID: {package_boot_id}")
except Exception as e:
print(f"Record PACKAGE_BOOT record, package_id: {package_id} boot_id: {boot_id} already exists")
set_db(con)
populate_boot_list(self)
end_1 = time.time()
print(f"Process {file_type} time: {math.ceil(end_1 - start_1)} seconds")
print("------------------------------------------------------------------------------\n")
# ============================================================================
# Function process_flash_all_file
# ============================================================================
def process_flash_all_file(filepath):
cwd = os.getcwd()
flash_file_lines = []
with open(filepath) as fp:
#1st line, platform
line = fp.readline()
if line[:9] == "@ECHO OFF":
filetype = 'bat'
elif line[:9] == "#!/bin/sh":
filetype = 'sh'
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Unexpected first line: {line} in file: {filepath}")
flash = FlashFile(1, platform = filetype, type = "init", command = line.strip())
flash_file_lines.append(flash)
cnt = 1
in_if_block = False
if_block_data = ''
while line:
line = fp.readline()
#---------------------------------
# Line that should not be captured
if line.strip() == '':
# blank line, ignore it
continue
elif line[:2] == "::":
# comment line windows, ignore it
continue
elif line[:1] == "#":
# comment line Linux, ignore it
continue
elif line[:10] == "pause >nul":
# pause line, ignore it
continue
elif line[:4] == "exit":
# exit line, ignore it
continue
elif line[:26] == "echo Press any key to exit":
# exit line, ignore it
continue
#-----------------------
# line that are relevant
elif line[:4] == "if !":
# if line to check fastboot version, grab it differently (all as one block)
in_if_block = True
if_block_data += line
continue
elif line[:7] == " echo ":
# part of the previous if, grab it differently (all as one block)
if in_if_block:
if_block_data += line
continue
elif line[:6] == " exit":
# part of the previous if, grab it differently (all as one block)
if in_if_block:
if_block_data += line
continue
elif line[:2] == "fi":
# part of the previous if, grab it differently (all as one block)
if in_if_block:
if_block_data += line
in_if_block = False
flash = FlashFile(cnt, platform = filetype, type = "if_block", command = if_block_data.strip())
flash_file_lines.append(flash)
continue
elif line[:5] == "PATH=":
flash = FlashFile(cnt, platform = filetype, type = "path", command = line.strip())
flash_file_lines.append(flash)
continue
elif line[:5] == "ping " or line[:6] == "sleep ":
flash = FlashFile(cnt, platform = filetype, type = "sleep", command = line.strip())
flash_file_lines.append(flash)
continue
elif line[:8] == "fastboot":
parts = line.split()
if parts[1] == 'flash':
flash = FlashFile(cnt, platform = filetype, type = "fastboot", command = "fastboot", action = "flash", arg1 = parts[2], arg2 = parts[3])
flash_file_lines.append(flash)
continue
elif parts[1] == 'reboot-bootloader':
flash = FlashFile(cnt, platform = filetype, type = "fastboot", command = "fastboot", action = "reboot-bootloader")
flash_file_lines.append(flash)
continue
elif parts[1] == '-w' and parts[2] == 'update':
flash = FlashFile(cnt, platform = filetype, type = "fastboot", command = "fastboot", action = "-w update", arg1 = parts[3])
flash_file_lines.append(flash)
continue
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR! Encountered an unexpected fastboot line while parsing {filepath}")
print(line)
return "ERROR"
#-----------------
# Unexpected lines
else:
print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S} ERROR! Encountered an unexpected line while parsing {filepath}")
print(line)
return "ERROR"
cnt += 1
return flash_file_lines
# ============================================================================
# Function ui_action
# ============================================================================
def ui_action(device, dump_file, local_file, look_for):
# Get uiautomator dump of view1
# the_view = "view1.xml"
res = device.uiautomator_dump(dump_file)
if res == -1:
puml("#red:Failed to uiautomator dump;\n}\n")
return -1
# Pull dump_file
print(f"Pulling {dump_file} from the phone to: {local_file} ...")
res = device.pull_file(dump_file, local_file)
if res != 0:
puml("#red:Failed to pull uiautomator dump from the phone;\n}\n")
return -1
# get bounds
coords = get_ui_cooridnates(local_file, look_for)
# Check for Display being locked again
if not device.is_display_unlocked():
print("ERROR: The device display is Locked!\n")
return -1
# Click on coordinates
res = device.click(coords)
if res == -1:
puml("#red:Failed to click;\n}\n")
return -1
# Sleep 2 seconds
print("Sleeping 2 seconds to make sure the view is loaded ...")
time.sleep(2)
# Check for Display being locked again
if not device.is_display_unlocked():
print("ERROR: The device display is Locked!\n")
return -1
# ============================================================================
# Function drive_magisk (TODO)
# ============================================================================
def drive_magisk(self, boot_file_name):
print("UI Automator is broken, until Google fixes it, this feature is disabled.")
return -1