-
Notifications
You must be signed in to change notification settings - Fork 118
/
modules.py
4954 lines (4543 loc) · 248 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
# 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 copy
import fnmatch
import math
import ntpath
import os
import shutil
import sqlite3 as sl
import sys
import tempfile
import time
import traceback
from datetime import datetime
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, update_phones
from runtime import *
console_widget = None
# ============================================================================
# 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):
try:
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)
else:
print("Android Platform Tools is not found.")
except Exception as e:
traceback.print_exc()
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while checking for platform tools.")
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, sortColumn=None, sorting_direction='ASC'):
try:
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,
PACKAGE.full_ota
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.show_custom_rom_options and 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])
# Clear the previous sort order arrows
for i in range(self.list.GetColumnCount()):
col = self.list.GetColumn(i)
col_text = col.Text.rstrip(" ▲▼")
col.SetImage(-1)
col.SetText(f"{col_text} ")
self.list.SetColumn(i, col)
# Order the query results based on the sortColumn and sorting_direction if provided
if sortColumn is not None:
# Set the sort order arrow for the current column
col = self.list.GetColumn(sortColumn - 1)
col_text = col.Text.strip()
if sorting_direction == 'ASC':
col.SetText(f"{col_text} ▲")
col.SetImage(-1)
elif sorting_direction == 'DESC':
col.SetText(f"{col_text} ▼")
col.SetImage(-1)
self.list.SetColumn(sortColumn - 1, col)
# Get the column name based on the sortColumn number
column_map = {
1: 'BOOT.boot_hash',
2: 'PACKAGE.boot_hash',
3: 'PACKAGE.package_sig',
4: 'BOOT.magisk_version',
5: 'BOOT.patch_method',
6: 'BOOT.hardware',
7: 'BOOT.epoch',
8: 'PACKAGE.file_path'
}
column_name = column_map.get(sortColumn, '')
if column_name:
sql += f" ORDER BY {column_name} {sorting_direction};"
else:
# Add default sorting
sql += " ORDER BY BOOT.is_patched ASC, BOOT.epoch ASC;"
with con:
data = con.execute(sql, parameters)
i = 0
full_ota = None
for row in data:
boot_hash = row[1][:8] or ''
package_boot_hash = row[9][:8] or ''
package_sig = row[11] or ''
patched_with_version = str(row[5]) or ''
patch_method = row[4] or ''
hardware = row[6] or ''
ts = datetime.fromtimestamp(row[7])
boot_date = ts.strftime('%Y-%m-%d %H:%M:%S')
package_path = row[12] or ''
if self.config.firmware_path == package_path:
full_ota = row[15]
index = self.list.InsertItem(i, boot_hash) # boot_hash (SHA1)
self.list.SetItem(index, 1, package_boot_hash) # package_boot_hash (Source SHA1)
self.list.SetItem(index, 2, package_sig) # package_sig (Package Fingerprint)
self.list.SetItem(index, 3, patched_with_version) # patched_with_version
self.list.SetItem(index, 4, patch_method) # patched_method
self.list.SetItem(index, 5, hardware) # hardware
self.list.SetItem(index, 6, boot_date) # boot_date
self.list.SetItem(index, 7, package_path) # package_path
if row[3]:
self.list.SetItemColumnImage(i, 0, 0)
else:
self.list.SetItemColumnImage(i, 0, -1)
i += 1
if i > 0 and full_ota is not None:
set_ota(self, bool(full_ota))
auto_resize_boot_list(self)
# 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.update_widget_states()
# we need to do this, otherwise the focus goes on the next control, which is a radio button, and undesired.
self.process_firmware.SetFocus()
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while populating boot list")
puml("#red:Encountered an error while populating boot list;\n")
traceback.print_exc()
# ============================================================================
# Function auto_resize_boot_list
# ============================================================================
def auto_resize_boot_list(self):
try:
# auto size columns to largest text, including the header (except the last column)
cw = 0
column_widths = copy.deepcopy(self.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 - 20
self.list.SetColumnWidth(self.list.ColumnCount - 1, available_width)
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while auto resizing boot list")
puml("#red:Encountered an error while auto resizing boot list;\n")
traceback.print_exc()
# ============================================================================
# Function identify_sdk_version
# ============================================================================
def identify_sdk_version(self):
try:
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"
res = run_shell(theCmd)
if res and isinstance(res, subprocess.CompletedProcess) and res.stdout:
# Split lines based on mixed EOL formats
lines = re.split(r'\r?\n', res.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', '34.0.4')):
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
message = (
f"You have an old or problematic Android platform Tools version {sdk_version}\n"
"You are strongly advised to update before continuing.\n"
"Are you sure you want to continue?"
)
dlg = wx.MessageDialog(
parent=None,
message=message,
caption='Bad Android Platform Tools',
style=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 res.stderr:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: {res.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
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while identifying sdk version")
puml("#red:Encountered an error while identifying sdk version;\n")
traceback.print_exc()
# ============================================================================
# Function get_flash_settings
# ============================================================================
def get_flash_settings(self):
try:
message = ''
isPatched = ''
p_custom_rom = self.config.show_custom_rom_options and 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 and p_custom_rom_path:
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 and boot.is_patched:
if boot.patch_method:
message += f" Patched with {boot.magisk_version} on {boot.hardware} method: {boot.patch_method}\n"
else:
message += f" Patched with {boot.magisk_version} on {boot.hardware}\n"
message += f"\nFlash Mode: {self.config.flash_mode}\n"
message += "\n"
return message
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while getting flash settings")
puml("#red:Encountered an error while while getting flash settings;\n")
traceback.print_exc()
# ============================================================================
# Function adb_kill_server
# ============================================================================
def adb_kill_server(self):
try:
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 and isinstance(res, subprocess.CompletedProcess) and 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"Return Code: {res.returncode}")
print(f"Stdout: {res.stdout}")
print(f"Stderr: {res.stderr}")
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
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while killing adb server.")
puml("#red:Encountered an error while killing adb server;\n")
traceback.print_exc()
# ============================================================================
# Function set_flash_button_state
# ============================================================================
def set_flash_button_state(self):
try:
boot = get_boot()
factory_images = os.path.join(get_config_path(), 'factory_images')
if boot and os.path.exists(boot.boot_path) and os.path.exists(os.path.join(factory_images, boot.package_sig)):
self.flash_button.Enable()
else:
self.flash_button.Disable()
except Exception:
traceback.print_exc()
self.flash_button.Disable()
# ============================================================================
# Function select_firmware
# ============================================================================
def select_firmware(self):
try:
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"The following firmware is selected:\n{firmware}")
if self.config.check_for_firmware_hash_validity:
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 and 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")
self.toast("Firmware SHA256 Match", f"SHA256 of {filename}{extension} matches the segment in the filename.")
set_firmware_hash_validity(True)
else:
print(f"WARNING: Expected to match {firmware_hash[:8]} in the {filename}{extension} but didn't, please double check to make sure the checksum is good.")
puml("#orange:Unable to match the checksum in the filename;\n")
self.toast("Firmware SHA256 Mismatch", f"WARNING! SHA256 of {filename}{extension} does not match segments in the filename.\nPlease double check to make sure the checksum is good.")
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' or firmware[0] == 'crDroidAndroid':
set_firmware_id(f"{firmware[0]}-{firmware[1]}-{firmware[2]}")
self.config.firmware_is_ota = True
else:
set_firmware_id(f"{firmware[0]}-{firmware[1]}")
self.config.firmware_is_ota = False
except Exception as e:
traceback.print_exc()
set_firmware_model(None)
set_firmware_id(filename)
set_ota(self, self.config.firmware_is_ota)
if get_firmware_id():
set_flash_button_state(self)
else:
self.flash_button.Disable()
populate_boot_list(self)
self.update_widget_states()
if self.config.check_for_firmware_hash_validity:
return firmware_hash
else:
return 'Checksum validity check is disabled!'
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'
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while selecting ota/firmware file:")
puml("#red:Encountered an error while selecting ota/firmware file;\n")
traceback.print_exc()
# ============================================================================
# Function process_file
# ============================================================================
def process_file(self, file_type):
try:
print("")
print("==============================================================================")
print(f" {datetime.now():%Y-%m-%d %H:%M:%S} PixelFlasher {VERSION} Processing {file_type} file ...")
print("==============================================================================")
print(f"Low memory option: {self.config.low_mem}")
print(get_printable_memory())
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_init_boot = False
is_stock_boot = False
is_payload_bin = False
factory_images = os.path.join(config_path, 'factory_images')
if file_type == 'firmware':
is_stock_boot = True
file_to_process = self.config.firmware_path
print(f"Factory File: {file_to_process}")
puml(f"note right:{file_to_process}\n")
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_vbmeta_img = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="vbmeta.img", nested=True)
found_boot_img_lz4 = ''
set_firmware_has_init_boot(False)
set_ota(self, False)
if found_init_boot_img:
set_firmware_has_init_boot(True)
is_init_boot = True
if found_flash_all_bat and found_flash_all_sh and (get_firmware_hash_validity() or not self.config.check_for_firmware_hash_validity):
# assume Pixel factory file
if self.config.check_for_firmware_hash_validity:
print("Detected Pixel firmware")
package_sig = found_flash_all_bat.split('/')[0]
package_dir_full = os.path.join(factory_images, package_sig)
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)
if res and isinstance(res, subprocess.CompletedProcess):
debug(f"Return Code: {res.returncode}")
debug(f"Stdout: {res.stdout}")
debug(f"Stderr: {res.stderr}")
if res.returncode != 0:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {file_to_process}")
puml("#red:ERROR: Could not extract image;\n")
print("Aborting ...\n")
self.toast(f"Process action", "Could not extract {file_to_process}")
return
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {file_to_process}")
puml("#red:ERROR: Could not extract image;\n")
print("Aborting ...\n")
self.toast(f"Process action", "Could not extract {file_to_process}")
return
elif found_boot_img or found_init_boot_img:
print(f"Detected Non Pixel firmware, with: {found_boot_img} {found_init_boot_img}")
# 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")
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", self.config.low_mem):
is_payload_bin = True
set_ota(self, True)
if get_ota() and (get_firmware_hash_validity() or not self.config.check_for_firmware_hash_validity):
print("Detected OTA 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:
boot_image_file = "boot.img.lz4"
else:
# if not look for boot.img (some Samsung devices don't have boot.img.lz4)
found_boot_img = check_archive_contains_file(archive_file_path=image_file_path, file_to_check="boot.img", nested=False)
if found_boot_img:
boot_image_file = "boot.img"
if boot_image_file:
print(f"Extracting {boot_image_file} from {found_ap} ...")
puml(f":Extract {boot_image_file};\n")
theCmd = f"\"{path_to_7z}\" x -bd -y -o\"{package_dir_full}\" \"{image_file_path}\" {boot_image_file}"
debug(f"{theCmd}")
res = run_shell(theCmd)
# expect ret 0
if res and isinstance(res, subprocess.CompletedProcess):
debug(f"Return Code: {res.returncode}")
debug(f"Stdout: {res.stdout}")
debug(f"Stderr: {res.stderr}")
if res.returncode != 0:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {boot_image_file}")
puml(f"#red:ERROR: Could not extract {boot_image_file};\n")
print("Aborting ...\n")
self.toast(f"Process action", "Could not extract {boot_image_file}.")
return
else:
if boot_image_file == "boot.img.lz4":
# unpack boot.img.lz4
print(f"Unpacking {boot_image_file} ...")
puml(f":Unpack {boot_image_file};\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_image_file}")
puml("#red:ERROR: Could not unpack {boot_image_file};\n")
print("Aborting ...\n")
self.toast("Process action", f"Could not unpack {boot_image_file}.")
return
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {boot_image_file}")
puml(f"#red:ERROR: Could not extract {boot_image_file};\n")
print("Aborting ...\n")
self.toast("Process action", f"Could not extract {boot_image_file}.")
return
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not find {boot_image_file}")
puml(f"#red:ERROR: Could not find {boot_image_file};\n")
print("Aborting ...\n")
self.toast("Process action", f"Could not find {boot_image_file}.")
return
else:
print("Detected Unsupported firmware file.")
print("Aborting ...")
self.toast("Process action", "Detected unsupported firmware.")
return
else:
file_to_process = self.config.custom_rom_path
print(f"ROM File: {file_to_process}")
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)
found_vbmeta_img = check_archive_contains_file(archive_file_path=file_to_process, file_to_check="vbmeta.img", nested=False)
set_rom_has_init_boot(False)
if found_init_boot_img:
set_rom_has_init_boot(True)
is_init_boot = True
elif check_zip_contains_file(file_to_process, "payload.bin", self.config.low_mem):
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")
# 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
is_stock_boot = True
temp_dir = tempfile.TemporaryDirectory()
temp_dir_path = temp_dir.name
try:
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 and isinstance(res, subprocess.CompletedProcess):
debug(f"Return Code: {res.returncode}")
debug(f"Stdout: {res.stdout}")
debug(f"Stderr: {res.stderr}")
if res.returncode != 0:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract payload.bin.")
puml("#red:ERROR: Could not extract payload.bin;\n")
print("Aborting ...\n")
self.toast("Process action", "Could not extract payload.bin.")
return
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract payload.bin.")
puml("#red:ERROR: Could not extract payload.bin;\n")
print("Aborting ...\n")
self.toast("Process action", "Could not extract payload.bin.")
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)
if self.config.extra_img_extracts:
print("Option to copy extra img files is enabled.")
extract_payload(payload_file_path, out=package_dir_full, diff=False, old='old', images='boot,vbmeta,init_boot,dtbo,super_empty,vendor_boot,vendor_kernel_boot')
if os.path.exists(os.path.join(package_dir_full, 'dtbo.img')):
dtbo_img_file = os.path.join(package_dir_full, 'dtbo.img')
debug(f"Copying {dtbo_img_file}")
shutil.copy(dtbo_img_file, os.path.join(tmp_dir_full, 'dtbo.img'), follow_symlinks=True)
if os.path.exists(os.path.join(package_dir_full, 'super_empty.img')):
super_empty_img_file = os.path.join(package_dir_full, 'super_empty.img')
debug(f"Copying {super_empty_img_file}")
shutil.copy(super_empty_img_file, os.path.join(tmp_dir_full, 'super_empty.img'), follow_symlinks=True)
if os.path.exists(os.path.join(package_dir_full, 'vendor_boot.img')):
vendor_boot_img_file = os.path.join(package_dir_full, 'vendor_boot.img')
debug(f"Copying {vendor_boot_img_file}")
shutil.copy(vendor_boot_img_file, os.path.join(tmp_dir_full, 'vendor_boot.img'), follow_symlinks=True)
if os.path.exists(os.path.join(package_dir_full, 'vendor_kernel_boot.img')):
vendor_kernel_boot_img_file = os.path.join(package_dir_full, 'vendor_kernel_boot.img')
debug(f"Copying {vendor_kernel_boot_img_file}")
shutil.copy(vendor_kernel_boot_img_file, os.path.join(tmp_dir_full, 'vendor_kernel_boot.img'), follow_symlinks=True)
else:
print("Extracting files from payload.bin ...")
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')
debug(f"Copying {boot_img_file}")
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')
debug(f"Copying {boot_img_file}")
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 evaluate to False
is_init_boot = True
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered while processing payload.bin")
traceback.print_exc()
finally:
temp_dir.cleanup()
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")
self.toast("Process action", "The selected firmware is not valid.")
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 '
is_init_boot = True
if found_vbmeta_img:
files_to_extract += 'vbmeta.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")
self.toast("Process action", f"Nothing to extract from {file_type}")
return
print(f"Extracting {files_to_extract} from {image_file_path} ...")
puml(f":Extract {files_to_extract};\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 and isinstance(res, subprocess.CompletedProcess):
debug(f"Return Code: {res.returncode}")
debug(f"Stdout: {res.stdout}")
debug(f"Stderr: {res.stderr}")
if res.returncode != 0:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {boot_file_name}.")
puml(f"#red:ERROR: Could not extract {boot_file_name};\n")
self.toast("Process action", f"Could not extract {boot_file_name}")
print("Aborting ...\n")
return
else:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Could not extract {boot_file_name}.")
puml(f"#red:ERROR: Could not extract {boot_file_name};\n")
self.toast("Process action", f"Could not extract {boot_file_name}")
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")
self.toast("Process action", f"Could not extract {boot_file_name}")
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)
else:
print(f"Found a cached copy of {file_type} {boot_file_name} sha1={checksum}")
# we need to copy boot.img for Pixel 7, 7P, 7a .. so that we can do live boot or KernelSu Patching.
if found_init_boot_img and os.path.exists(os.path.join(tmp_dir_full, 'boot.img')):
shutil.copy(os.path.join(tmp_dir_full, 'boot.img'), cached_boot_img_dir_full, follow_symlinks=True)
# we copy vbmeta.img so that we can do selective vbmeta verity / verification patching.
if found_vbmeta_img and os.path.exists(package_dir_full):
shutil.copy(os.path.join(tmp_dir_full, 'vbmeta.img'), package_dir_full, follow_symlinks=True)
# Let's see if we have a record for the firmware/rom being processed
print(f"Checking DB entry for PACKAGE: {file_to_process}")
package_id = 0
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:
package_id = data[0][0]
print(f"Found a previous {file_type} PACKAGE record id={package_id} for package_sig: {package_sig} Firmware: {file_to_process}")
print(f"Package ID: {package_id}")
else:
# create PACKAGE db record
print(f"Creating DB entry for PACKAGE: {file_to_process}")
sql = 'INSERT INTO PACKAGE (boot_hash, type, package_sig, file_path, epoch, full_ota ) values(?, ?, ?, ?, ?, ?) ON CONFLICT (file_path) DO NOTHING'
data = checksum, file_type, package_sig, file_to_process, time.time(), self.config.firmware_is_ota
try:
cursor.execute(sql, data)
con.commit()
package_id = cursor.lastrowid
print(f"Package ID: {package_id}")
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error.")
traceback.print_exc()
# Let's see if we already have an entry for the BOOT
print(f"Checking DB entry for BOOT: {checksum}")
boot_id = 0
cursor.execute(f"SELECT ID FROM BOOT WHERE 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: {checksum}")
print(f"Boot_ID: {boot_id}")
else:
# create BOOT db record
print(f"Creating DB entry for BOOT: {checksum}")
sql = 'INSERT INTO BOOT (boot_hash, file_path, is_patched, magisk_version, hardware, epoch, patch_method, is_odin, is_stock_boot, is_init_boot) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (boot_hash) DO NOTHING'
data = checksum, cached_boot_img_path, 0, '', '', time.time(), '', is_odin, is_stock_boot, is_init_boot