miasst 1.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- miasst-1.4.0/LICENSE +201 -0
- miasst-1.4.0/PKG-INFO +67 -0
- miasst-1.4.0/README.md +53 -0
- miasst-1.4.0/miassistant/__init__.py +0 -0
- miasst-1.4.0/miassistant/cli.py +61 -0
- miasst-1.4.0/miassistant/core.py +605 -0
- miasst-1.4.0/miasst.egg-info/PKG-INFO +67 -0
- miasst-1.4.0/miasst.egg-info/SOURCES.txt +12 -0
- miasst-1.4.0/miasst.egg-info/dependency_links.txt +1 -0
- miasst-1.4.0/miasst.egg-info/entry_points.txt +2 -0
- miasst-1.4.0/miasst.egg-info/requires.txt +4 -0
- miasst-1.4.0/miasst.egg-info/top_level.txt +1 -0
- miasst-1.4.0/pyproject.toml +25 -0
- miasst-1.4.0/setup.cfg +4 -0
miasst-1.4.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 offici5l
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
miasst-1.4.0/PKG-INFO
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: miasst
|
|
3
|
+
Version: 1.4.0
|
|
4
|
+
Summary: Cross-platform CLI for Xiaomi Mi Assistant mode: flash, wipe, reboot
|
|
5
|
+
Project-URL: Repository, https://github.com/MiForge/MiAssistantTool
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: pyusb
|
|
10
|
+
Requires-Dist: requests
|
|
11
|
+
Requires-Dist: pyaes
|
|
12
|
+
Requires-Dist: rsa
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
<div align="center">
|
|
16
|
+
|
|
17
|
+
<a href="https://github.com/MiForge/MiAssistantTool"><img src="https://img.shields.io/badge/MiAssistantTool-%230070FF?style=flat&logo=xiaomi&logoColor=%23FF6900" alt="MiAssistantTool" style="width: 200px; vertical-align: middle;" /></a><br>
|
|
18
|
+
|
|
19
|
+
Windows, macOS, Linux, and Termux.
|
|
20
|
+
|
|
21
|
+
[](https://pypi.org/project/miasst/)
|
|
22
|
+
[](CHANGELOG.md)
|
|
23
|
+
[](./LICENSE)
|
|
24
|
+
___
|
|
25
|
+
|
|
26
|
+
</div>
|
|
27
|
+
|
|
28
|
+
In Mi Assistant mode, without unlocking the bootloader:
|
|
29
|
+
|
|
30
|
+
- Read Info
|
|
31
|
+
- Flash Official Recovery ROM
|
|
32
|
+
- ROMs that can be flashed
|
|
33
|
+
- Format Data / Cache / Storage / Data + Storage / FRP
|
|
34
|
+
- Wipe Data Storage / EFS
|
|
35
|
+
- Reboot / Reboot to recovery / fastboot / bootloader
|
|
36
|
+
- Shutdown
|
|
37
|
+
|
|
38
|
+
___
|
|
39
|
+
|
|
40
|
+
### Dependencies
|
|
41
|
+
|
|
42
|
+
* Linux: `sudo apt install libusb-1.0-0`
|
|
43
|
+
* macOS: `brew install libusb`
|
|
44
|
+
* Termux: `pkg install libusb`
|
|
45
|
+
* Windows: No extra steps required (uses standard USB drivers).
|
|
46
|
+
|
|
47
|
+
### Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install miasst
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Usage
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
miasst
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Notes
|
|
60
|
+
|
|
61
|
+
On Termux (without root) you'll need the [Termux:API](https://github.com/termux/termux-api/releases/latest) app, and `pkg install termux-api`.
|
|
62
|
+
|
|
63
|
+
### Quick Installation (for Termux):
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
curl -sS https://raw.githubusercontent.com/MiForge/MiAssistantTool/main/install.sh | bash
|
|
67
|
+
```
|
miasst-1.4.0/README.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
<a href="https://github.com/MiForge/MiAssistantTool"><img src="https://img.shields.io/badge/MiAssistantTool-%230070FF?style=flat&logo=xiaomi&logoColor=%23FF6900" alt="MiAssistantTool" style="width: 200px; vertical-align: middle;" /></a><br>
|
|
4
|
+
|
|
5
|
+
Windows, macOS, Linux, and Termux.
|
|
6
|
+
|
|
7
|
+
[](https://pypi.org/project/miasst/)
|
|
8
|
+
[](CHANGELOG.md)
|
|
9
|
+
[](./LICENSE)
|
|
10
|
+
___
|
|
11
|
+
|
|
12
|
+
</div>
|
|
13
|
+
|
|
14
|
+
In Mi Assistant mode, without unlocking the bootloader:
|
|
15
|
+
|
|
16
|
+
- Read Info
|
|
17
|
+
- Flash Official Recovery ROM
|
|
18
|
+
- ROMs that can be flashed
|
|
19
|
+
- Format Data / Cache / Storage / Data + Storage / FRP
|
|
20
|
+
- Wipe Data Storage / EFS
|
|
21
|
+
- Reboot / Reboot to recovery / fastboot / bootloader
|
|
22
|
+
- Shutdown
|
|
23
|
+
|
|
24
|
+
___
|
|
25
|
+
|
|
26
|
+
### Dependencies
|
|
27
|
+
|
|
28
|
+
* Linux: `sudo apt install libusb-1.0-0`
|
|
29
|
+
* macOS: `brew install libusb`
|
|
30
|
+
* Termux: `pkg install libusb`
|
|
31
|
+
* Windows: No extra steps required (uses standard USB drivers).
|
|
32
|
+
|
|
33
|
+
### Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install miasst
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Usage
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
miasst
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Notes
|
|
46
|
+
|
|
47
|
+
On Termux (without root) you'll need the [Termux:API](https://github.com/termux/termux-api/releases/latest) app, and `pkg install termux-api`.
|
|
48
|
+
|
|
49
|
+
### Quick Installation (for Termux):
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
curl -sS https://raw.githubusercontent.com/MiForge/MiAssistantTool/main/install.sh | bash
|
|
53
|
+
```
|
|
File without changes
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from miassistant import core
|
|
8
|
+
|
|
9
|
+
def prompt_choice():
|
|
10
|
+
for n, (label, _) in core.ACTION_HANDLERS.items():
|
|
11
|
+
print(f" {n} > {label}")
|
|
12
|
+
print()
|
|
13
|
+
|
|
14
|
+
while True:
|
|
15
|
+
raw = input("Choice: ").strip()
|
|
16
|
+
if not raw.isdigit() or int(raw) not in core.ACTION_HANDLERS:
|
|
17
|
+
print("Invalid choice, try again.")
|
|
18
|
+
continue
|
|
19
|
+
return int(raw)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _relaunch_via_termux_usb(choice):
|
|
23
|
+
subprocess.run(["pkill", "-9", "-f", "tcp"])
|
|
24
|
+
|
|
25
|
+
while True:
|
|
26
|
+
result = subprocess.run(["termux-usb", "-l"], capture_output=True, text=True)
|
|
27
|
+
try:
|
|
28
|
+
devices = json.loads(result.stdout)
|
|
29
|
+
except json.JSONDecodeError:
|
|
30
|
+
devices = []
|
|
31
|
+
if devices:
|
|
32
|
+
device = devices[0]
|
|
33
|
+
result = subprocess.run(["termux-usb", "-r", device], capture_output=True, text=True)
|
|
34
|
+
if "granted" in result.stdout.lower():
|
|
35
|
+
break
|
|
36
|
+
print("\nUSB permission not granted. Please allow access when prompted.")
|
|
37
|
+
else:
|
|
38
|
+
for i in range(4):
|
|
39
|
+
print(f"\rNo USB devices connected {'.' * (i % 4)}", end="")
|
|
40
|
+
time.sleep(0.5)
|
|
41
|
+
|
|
42
|
+
env = os.environ.copy()
|
|
43
|
+
env["MIASSISTANT_CHOICE"] = str(choice)
|
|
44
|
+
subprocess.run(["termux-usb", "-E", "-e", "miasst", device], env=env)
|
|
45
|
+
sys.exit()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def main():
|
|
49
|
+
preset_choice = os.environ.get("MIASSISTANT_CHOICE")
|
|
50
|
+
choice = int(preset_choice) if preset_choice else prompt_choice()
|
|
51
|
+
|
|
52
|
+
if core.is_nonroot_termux() and "TERMUX_USB_FD" not in os.environ:
|
|
53
|
+
_relaunch_via_termux_usb(choice)
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
_, handler = core.ACTION_HANDLERS[choice]
|
|
57
|
+
handler()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
main()
|
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import json
|
|
3
|
+
import base64
|
|
4
|
+
import re
|
|
5
|
+
import urllib.parse
|
|
6
|
+
import requests
|
|
7
|
+
import usb.core
|
|
8
|
+
import usb.util
|
|
9
|
+
import usb.backend.libusb1
|
|
10
|
+
import struct
|
|
11
|
+
import os
|
|
12
|
+
import hashlib
|
|
13
|
+
import pyaes
|
|
14
|
+
from rsa import PublicKey
|
|
15
|
+
|
|
16
|
+
B_INTERFACE_CLASS = 0xFF
|
|
17
|
+
B_INTERFACE_SUBCLASS = 0x42
|
|
18
|
+
B_INTERFACE_PROTOCOL = 0x1
|
|
19
|
+
|
|
20
|
+
ADB_CNXN = int.from_bytes(b"CNXN", "little")
|
|
21
|
+
ADB_OPEN = int.from_bytes(b"OPEN", "little")
|
|
22
|
+
ADB_OKAY = int.from_bytes(b"OKAY", "little")
|
|
23
|
+
ADB_WRTE = int.from_bytes(b"WRTE", "little")
|
|
24
|
+
ADB_VERSION = 0x01000001
|
|
25
|
+
ADB_MAX_DATA = 1024 * 1024
|
|
26
|
+
ADB_SIDELOAD_CHUNK_SIZE = 1024 * 64
|
|
27
|
+
LIBUSB_OPTION_NO_DEVICE_DISCOVERY = 2
|
|
28
|
+
USB_TIMEOUT_MS = 3000
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class EPDesc(ctypes.Structure):
|
|
32
|
+
_fields_ = [
|
|
33
|
+
("bLength", ctypes.c_uint8), ("bDescriptorType", ctypes.c_uint8),
|
|
34
|
+
("bEndpointAddress", ctypes.c_uint8), ("bmAttributes", ctypes.c_uint8),
|
|
35
|
+
("wMaxPacketSize", ctypes.c_uint16), ("bInterval", ctypes.c_uint8),
|
|
36
|
+
("bRefresh", ctypes.c_uint8), ("bSynchAddress", ctypes.c_uint8),
|
|
37
|
+
("extra", ctypes.c_void_p), ("extra_length", ctypes.c_int),
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class IntfDesc(ctypes.Structure):
|
|
42
|
+
_fields_ = [
|
|
43
|
+
("bLength", ctypes.c_uint8), ("bDescriptorType", ctypes.c_uint8),
|
|
44
|
+
("bInterfaceNumber", ctypes.c_uint8), ("bAlternateSetting", ctypes.c_uint8),
|
|
45
|
+
("bNumEndpoints", ctypes.c_uint8), ("bInterfaceClass", ctypes.c_uint8),
|
|
46
|
+
("bInterfaceSubClass", ctypes.c_uint8), ("bInterfaceProtocol", ctypes.c_uint8),
|
|
47
|
+
("iInterface", ctypes.c_uint8), ("endpoint", ctypes.POINTER(EPDesc)),
|
|
48
|
+
("extra", ctypes.c_void_p), ("extra_length", ctypes.c_int),
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Intf(ctypes.Structure):
|
|
53
|
+
_fields_ = [("altsetting", ctypes.POINTER(IntfDesc)), ("num_altsetting", ctypes.c_int)]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ConfigDesc(ctypes.Structure):
|
|
57
|
+
_fields_ = [
|
|
58
|
+
("bLength", ctypes.c_uint8), ("bDescriptorType", ctypes.c_uint8),
|
|
59
|
+
("wTotalLength", ctypes.c_uint16), ("bNumInterfaces", ctypes.c_uint8),
|
|
60
|
+
("bConfigurationValue", ctypes.c_uint8), ("iConfiguration", ctypes.c_uint8),
|
|
61
|
+
("bmAttributes", ctypes.c_uint8), ("MaxPower", ctypes.c_uint8),
|
|
62
|
+
("interface", ctypes.POINTER(Intf)),
|
|
63
|
+
("extra", ctypes.c_void_p), ("extra_length", ctypes.c_int),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_nonroot_termux():
|
|
68
|
+
return (
|
|
69
|
+
bool(os.environ.get("PREFIX"))
|
|
70
|
+
and os.path.exists("/data/data/com.termux")
|
|
71
|
+
and hasattr(os, "geteuid")
|
|
72
|
+
and os.geteuid() != 0
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_adb_endpoints_raw(lib, dev):
|
|
77
|
+
lib.libusb_get_active_config_descriptor.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ConfigDesc))]
|
|
78
|
+
lib.libusb_get_active_config_descriptor.restype = ctypes.c_int
|
|
79
|
+
cfg = ctypes.POINTER(ConfigDesc)()
|
|
80
|
+
if lib.libusb_get_active_config_descriptor(dev, ctypes.byref(cfg)) != 0:
|
|
81
|
+
return None, None
|
|
82
|
+
for i in range(cfg.contents.bNumInterfaces):
|
|
83
|
+
intf = cfg.contents.interface[i]
|
|
84
|
+
if intf.num_altsetting == 0:
|
|
85
|
+
continue
|
|
86
|
+
alt = intf.altsetting[0]
|
|
87
|
+
if (alt.bInterfaceClass, alt.bInterfaceSubClass, alt.bInterfaceProtocol) != (
|
|
88
|
+
B_INTERFACE_CLASS, B_INTERFACE_SUBCLASS, B_INTERFACE_PROTOCOL
|
|
89
|
+
):
|
|
90
|
+
continue
|
|
91
|
+
ep_out = ep_in = None
|
|
92
|
+
for e in range(alt.bNumEndpoints):
|
|
93
|
+
ep = alt.endpoint[e]
|
|
94
|
+
if ep.bmAttributes & 0x03 != 0x02:
|
|
95
|
+
continue
|
|
96
|
+
if ep.bEndpointAddress & 0x80:
|
|
97
|
+
ep_in = ep.bEndpointAddress
|
|
98
|
+
else:
|
|
99
|
+
ep_out = ep.bEndpointAddress
|
|
100
|
+
if ep_out is not None and ep_in is not None:
|
|
101
|
+
return ep_out, ep_in
|
|
102
|
+
return None, None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def connect_termux_nonroot():
|
|
106
|
+
fd = os.environ.get("TERMUX_USB_FD")
|
|
107
|
+
if fd is None:
|
|
108
|
+
exit("\n\nWithout root (termux-usb must be used)\n\n")
|
|
109
|
+
fd = int(fd)
|
|
110
|
+
|
|
111
|
+
m = usb.backend.libusb1
|
|
112
|
+
lib_path = f"{os.environ.get('PREFIX', '')}/lib/libusb-1.0.so"
|
|
113
|
+
lib = m._load_library(find_library=lambda _: lib_path)
|
|
114
|
+
m._setup_prototypes(lib)
|
|
115
|
+
|
|
116
|
+
lib.libusb_set_option.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
117
|
+
lib.libusb_set_option.restype = ctypes.c_int
|
|
118
|
+
lib.libusb_set_option(None, LIBUSB_OPTION_NO_DEVICE_DISCOVERY)
|
|
119
|
+
|
|
120
|
+
backend = m._LibUSB(lib)
|
|
121
|
+
ctx = backend.ctx
|
|
122
|
+
|
|
123
|
+
lib.libusb_wrap_sys_device.argtypes = [ctypes.c_void_p, ctypes.c_longlong, ctypes.POINTER(ctypes.c_void_p)]
|
|
124
|
+
lib.libusb_wrap_sys_device.restype = ctypes.c_int
|
|
125
|
+
handle = ctypes.c_void_p()
|
|
126
|
+
if lib.libusb_wrap_sys_device(ctx, fd, ctypes.byref(handle)) != 0 or not handle.value:
|
|
127
|
+
exit("\n\ndevice is not connected, or not in mi assistant mode\n\n")
|
|
128
|
+
|
|
129
|
+
lib.libusb_get_device.argtypes = [ctypes.c_void_p]
|
|
130
|
+
lib.libusb_get_device.restype = ctypes.c_void_p
|
|
131
|
+
dev = lib.libusb_get_device(handle)
|
|
132
|
+
|
|
133
|
+
ep_out, ep_in = find_adb_endpoints_raw(lib, dev)
|
|
134
|
+
if ep_out is None:
|
|
135
|
+
exit("\n\ndevice is not connected, or not in mi assistant mode\n\n")
|
|
136
|
+
|
|
137
|
+
lib.libusb_claim_interface.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
138
|
+
lib.libusb_claim_interface.restype = ctypes.c_int
|
|
139
|
+
lib.libusb_claim_interface(handle, 0)
|
|
140
|
+
|
|
141
|
+
lib.libusb_bulk_transfer.argtypes = [
|
|
142
|
+
ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_char_p,
|
|
143
|
+
ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.c_uint,
|
|
144
|
+
]
|
|
145
|
+
lib.libusb_bulk_transfer.restype = ctypes.c_int
|
|
146
|
+
|
|
147
|
+
return {"kind": "raw", "lib": lib, "handle": handle, "ep_out": ep_out, "ep_in": ep_in, "backend": backend}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def connect_normal():
|
|
151
|
+
try:
|
|
152
|
+
dev_list = list(usb.core.find(find_all=True))
|
|
153
|
+
except usb.core.USBError:
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
for dev in dev_list:
|
|
157
|
+
for cfg in dev:
|
|
158
|
+
for intf in cfg:
|
|
159
|
+
if (intf.bInterfaceClass, intf.bInterfaceSubClass, intf.bInterfaceProtocol) != (
|
|
160
|
+
B_INTERFACE_CLASS, B_INTERFACE_SUBCLASS, B_INTERFACE_PROTOCOL
|
|
161
|
+
):
|
|
162
|
+
continue
|
|
163
|
+
out_ep = usb.util.find_descriptor(
|
|
164
|
+
intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT
|
|
165
|
+
)
|
|
166
|
+
in_ep = usb.util.find_descriptor(
|
|
167
|
+
intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN
|
|
168
|
+
)
|
|
169
|
+
if not out_ep or not in_ep:
|
|
170
|
+
continue
|
|
171
|
+
try:
|
|
172
|
+
if dev.is_kernel_driver_active(intf.bInterfaceNumber):
|
|
173
|
+
dev.detach_kernel_driver(intf.bInterfaceNumber)
|
|
174
|
+
except (NotImplementedError, usb.core.USBError):
|
|
175
|
+
pass
|
|
176
|
+
dev.set_configuration(cfg.bConfigurationValue)
|
|
177
|
+
usb.util.claim_interface(dev, intf.bInterfaceNumber)
|
|
178
|
+
return {"kind": "pyusb", "out_ep": out_ep, "in_ep": in_ep}
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def connect():
|
|
183
|
+
transport = connect_termux_nonroot() if is_nonroot_termux() else connect_normal()
|
|
184
|
+
if not transport:
|
|
185
|
+
exit("\n\ndevice is not connected, or not in mi assistant mode\n\n")
|
|
186
|
+
return transport
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class DeviceWriteError(Exception):
|
|
190
|
+
pass
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def usb_write(transport, data):
|
|
194
|
+
if transport["kind"] == "pyusb":
|
|
195
|
+
try:
|
|
196
|
+
transport["out_ep"].write(data, timeout=USB_TIMEOUT_MS)
|
|
197
|
+
except usb.core.USBError as e:
|
|
198
|
+
raise DeviceWriteError(str(e))
|
|
199
|
+
else:
|
|
200
|
+
buf = ctypes.create_string_buffer(data, len(data))
|
|
201
|
+
n = ctypes.c_int(0)
|
|
202
|
+
r = transport["lib"].libusb_bulk_transfer(
|
|
203
|
+
transport["handle"], transport["ep_out"], buf, len(data), ctypes.byref(n), USB_TIMEOUT_MS
|
|
204
|
+
)
|
|
205
|
+
if r != 0:
|
|
206
|
+
raise DeviceWriteError(f"libusb_bulk_transfer write failed (code {r})")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def usb_read(transport, size):
|
|
210
|
+
if transport["kind"] == "pyusb":
|
|
211
|
+
try:
|
|
212
|
+
return bytes(transport["in_ep"].read(size, timeout=USB_TIMEOUT_MS))
|
|
213
|
+
except usb.core.USBError:
|
|
214
|
+
return b""
|
|
215
|
+
buf = ctypes.create_string_buffer(size)
|
|
216
|
+
n = ctypes.c_int(0)
|
|
217
|
+
r = transport["lib"].libusb_bulk_transfer(
|
|
218
|
+
transport["handle"], transport["ep_in"], buf, size, ctypes.byref(n), USB_TIMEOUT_MS
|
|
219
|
+
)
|
|
220
|
+
return buf.raw[: n.value] if r == 0 else b""
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def send_packet(transport, cmd, arg0, arg1, data=b""):
|
|
224
|
+
header = struct.pack("<6I", cmd, arg0, arg1, len(data), 0, cmd ^ 0xFFFFFFFF)
|
|
225
|
+
usb_write(transport, header)
|
|
226
|
+
if data:
|
|
227
|
+
usb_write(transport, data)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class DeviceTimeout(Exception):
|
|
231
|
+
pass
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def read_packet(transport):
|
|
235
|
+
header = usb_read(transport, 24)
|
|
236
|
+
if len(header) < 24:
|
|
237
|
+
raise DeviceTimeout()
|
|
238
|
+
cmd, arg0, arg1, length, checksum, magic = struct.unpack("<6I", header)
|
|
239
|
+
data = usb_read(transport, length) if length else b""
|
|
240
|
+
return cmd, arg0, arg1, data
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def adb_connect(transport):
|
|
244
|
+
send_packet(transport, ADB_CNXN, ADB_VERSION, ADB_MAX_DATA, b"host::\x00")
|
|
245
|
+
_, _, _, data = read_packet(transport)
|
|
246
|
+
if not data.startswith(b"sideload::"):
|
|
247
|
+
exit("device not connected, or not in Mi Assistant mode")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def adb_cmd(transport, command):
|
|
251
|
+
send_packet(transport, ADB_OPEN, 1, 0, command.encode())
|
|
252
|
+
read_packet(transport)
|
|
253
|
+
_, _, _, resp = read_packet(transport)
|
|
254
|
+
read_packet(transport)
|
|
255
|
+
text = resp.decode(errors="ignore")
|
|
256
|
+
return text[:-1] if text.endswith("\n") else text
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def start_sideload(transport, file_path, validate):
|
|
260
|
+
file_size = os.path.getsize(file_path)
|
|
261
|
+
send_packet(transport, ADB_OPEN, 1, 0, f"sideload-host:{file_size}:{ADB_SIDELOAD_CHUNK_SIZE}:{validate}:0".encode())
|
|
262
|
+
|
|
263
|
+
total_sent = 0
|
|
264
|
+
final_message = ""
|
|
265
|
+
|
|
266
|
+
with open(file_path, "rb") as f:
|
|
267
|
+
while True:
|
|
268
|
+
try:
|
|
269
|
+
cmd, arg0, arg1, data = read_packet(transport)
|
|
270
|
+
except (DeviceTimeout, DeviceWriteError):
|
|
271
|
+
continue
|
|
272
|
+
|
|
273
|
+
if len(data) > 8:
|
|
274
|
+
final_message = data.decode(errors="ignore")
|
|
275
|
+
break
|
|
276
|
+
|
|
277
|
+
if cmd == ADB_OKAY:
|
|
278
|
+
send_packet(transport, ADB_OKAY, arg1, arg0)
|
|
279
|
+
|
|
280
|
+
if cmd != ADB_WRTE:
|
|
281
|
+
continue
|
|
282
|
+
|
|
283
|
+
m = re.match(r"\d+", data.decode(errors="ignore"))
|
|
284
|
+
block = int(m.group()) if m else 0
|
|
285
|
+
offset = block * ADB_SIDELOAD_CHUNK_SIZE
|
|
286
|
+
if offset > file_size:
|
|
287
|
+
break
|
|
288
|
+
to_write = min(ADB_SIDELOAD_CHUNK_SIZE, file_size - offset)
|
|
289
|
+
f.seek(offset)
|
|
290
|
+
chunk = f.read(to_write)
|
|
291
|
+
|
|
292
|
+
try:
|
|
293
|
+
send_packet(transport, ADB_WRTE, arg1, arg0, chunk)
|
|
294
|
+
send_packet(transport, ADB_OKAY, arg1, arg0)
|
|
295
|
+
except DeviceWriteError:
|
|
296
|
+
continue
|
|
297
|
+
total_sent += to_write
|
|
298
|
+
|
|
299
|
+
pct = min(100, int(total_sent * 100 / file_size))
|
|
300
|
+
print(f"\rFlashing in progress ... {pct}/100%", end="", flush=True)
|
|
301
|
+
|
|
302
|
+
print(f"\n\n{final_message}\n")
|
|
303
|
+
return final_message
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
_transport = None
|
|
307
|
+
_connected = False
|
|
308
|
+
_info = None
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def get_transport():
|
|
312
|
+
global _transport, _connected
|
|
313
|
+
if _transport is None:
|
|
314
|
+
_transport = connect()
|
|
315
|
+
if not _connected:
|
|
316
|
+
try:
|
|
317
|
+
adb_connect(_transport)
|
|
318
|
+
except DeviceTimeout:
|
|
319
|
+
exit("\n\nError: device did not respond in time. Make sure the screen is on and it is in Mi Assistant mode.\n\n")
|
|
320
|
+
_connected = True
|
|
321
|
+
return _transport
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def get_info():
|
|
325
|
+
global _info
|
|
326
|
+
if _info is None:
|
|
327
|
+
transport = get_transport()
|
|
328
|
+
try:
|
|
329
|
+
_info = {
|
|
330
|
+
"sn": adb_cmd(transport, "getsn:"),
|
|
331
|
+
"region": adb_cmd(transport, "getregion:"),
|
|
332
|
+
"device": adb_cmd(transport, "getdevice:"),
|
|
333
|
+
"branch": adb_cmd(transport, "getbranch:"),
|
|
334
|
+
"version": adb_cmd(transport, "getversion:"),
|
|
335
|
+
"romzone": adb_cmd(transport, "getromzone:"),
|
|
336
|
+
"language": adb_cmd(transport, "getlanguage:"),
|
|
337
|
+
"codebase": adb_cmd(transport, "getcodebase:"),
|
|
338
|
+
"carrier": adb_cmd(transport, "getcarrier:"),
|
|
339
|
+
"mitoken": adb_cmd(transport, "getmitoken:"),
|
|
340
|
+
"recoveryversion": adb_cmd(transport, "getrecoveryversion:"),
|
|
341
|
+
}
|
|
342
|
+
except DeviceTimeout:
|
|
343
|
+
exit("\n\nError: device did not respond in time. Make sure the screen is on and it is in Mi Assistant mode.\n\n")
|
|
344
|
+
return _info
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def read_info():
|
|
349
|
+
info = get_info()
|
|
350
|
+
print(f"\nDevice: {info['device']}")
|
|
351
|
+
print(f"Version: {info['version']}")
|
|
352
|
+
print(f"Serial Number: {info['sn']}")
|
|
353
|
+
print(f"Codebase: {info['codebase']}")
|
|
354
|
+
print(f"Branch: {info['branch']}")
|
|
355
|
+
print(f"Language: {info['language']}")
|
|
356
|
+
print(f"Region: {info['region']}")
|
|
357
|
+
print(f"ROM Zone: {info['romzone']}\n")
|
|
358
|
+
print(f"Mi Token: {info['mitoken']}")
|
|
359
|
+
print(f"Carrier: {info['carrier']}")
|
|
360
|
+
print(f"Recovery Version: {info['recoveryversion']}")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
BLOCK_SIZE = 16
|
|
364
|
+
|
|
365
|
+
def _pkcs7_pad(data):
|
|
366
|
+
p = BLOCK_SIZE - len(data) % BLOCK_SIZE
|
|
367
|
+
return data + bytes([p]) * p
|
|
368
|
+
|
|
369
|
+
def _pkcs7_unpad(data):
|
|
370
|
+
return data[:-data[-1]]
|
|
371
|
+
|
|
372
|
+
def _aes_cbc_encrypt(key, iv, data):
|
|
373
|
+
mode = pyaes.AESModeOfOperationCBC(key, iv=iv)
|
|
374
|
+
return b''.join(mode.encrypt(data[i:i+BLOCK_SIZE]) for i in range(0, len(data), BLOCK_SIZE))
|
|
375
|
+
|
|
376
|
+
def _aes_cbc_decrypt(key, iv, data):
|
|
377
|
+
mode = pyaes.AESModeOfOperationCBC(key, iv=iv)
|
|
378
|
+
return b''.join(mode.decrypt(data[i:i+BLOCK_SIZE]) for i in range(0, len(data), BLOCK_SIZE))
|
|
379
|
+
|
|
380
|
+
def _validate_request(info, md5):
|
|
381
|
+
key = b"miuiotavalided11"
|
|
382
|
+
iv = b"0102030405060708"
|
|
383
|
+
|
|
384
|
+
payload = {
|
|
385
|
+
"d": info["device"], "v": info["version"], "c": info["codebase"], "b": info["branch"],
|
|
386
|
+
"sn": info["sn"], "l": "en-US", "f": "1",
|
|
387
|
+
"options": {"zone": int(info["romzone"])},
|
|
388
|
+
"pkg": md5,
|
|
389
|
+
}
|
|
390
|
+
body = _pkcs7_pad(json.dumps(payload).encode())
|
|
391
|
+
enc = _aes_cbc_encrypt(key, iv, body)
|
|
392
|
+
q = urllib.parse.quote(base64.b64encode(enc).decode())
|
|
393
|
+
|
|
394
|
+
resp = requests.post(
|
|
395
|
+
"http://update.miui.com/updates/miotaV3.php",
|
|
396
|
+
data=f"q={q}&t=&s=1",
|
|
397
|
+
headers={"User-Agent": "MiTunes_UserAgent_v3.0", "Content-Type": "application/x-www-form-urlencoded"},
|
|
398
|
+
)
|
|
399
|
+
dec = _aes_cbc_decrypt(key, iv, base64.b64decode(resp.text.strip()))
|
|
400
|
+
result = json.loads(_pkcs7_unpad(dec).decode("utf-8", errors="ignore"))
|
|
401
|
+
return result
|
|
402
|
+
|
|
403
|
+
def validate_decrypt(validate):
|
|
404
|
+
PUBLIC_KEY_PEM = b"""-----BEGIN PUBLIC KEY-----
|
|
405
|
+
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs3X/eMU56OEc5buvfnXe
|
|
406
|
+
D+9X4xKsImY7Q3Y+FY/xcdRIIvypKPjqxgqV548+Vf/H2VHeUXsMgiaeAqbmNAwP
|
|
407
|
+
BU0He0p0YlUEOZ9Bkn6dKniuEe9G7PeL3tx6qjnf+Y5actf7IwJBTGJefa7wt+OZ
|
|
408
|
+
4pNCBfgPHkTW+3VGlioP8rHbnLyZ98BdNxrvcLqJHCTblwomhVR64syqP1/eVOqE
|
|
409
|
+
BKeHT+IkTXFZAzEVGha0FyKgBwcET/851zW93FiiC1HYpubLSiK1crbtDVK2ho4z
|
|
410
|
+
NWzHCPfAfKQQn1VqXthiwxTZ25i4FYbuySwZ7xfXhqJwcLKuxN9uRCHBG8KV9V5T
|
|
411
|
+
7wIDAQAB
|
|
412
|
+
-----END PUBLIC KEY-----"""
|
|
413
|
+
|
|
414
|
+
key = PublicKey.load_pkcs1_openssl_pem(PUBLIC_KEY_PEM)
|
|
415
|
+
encrypted_bytes = base64.b64decode(validate)
|
|
416
|
+
c = int.from_bytes(encrypted_bytes, 'big')
|
|
417
|
+
m = pow(c, key.e, key.n)
|
|
418
|
+
key_size_bytes = (key.n.bit_length() + 7) // 8
|
|
419
|
+
decrypted_padded_bytes = m.to_bytes(key_size_bytes, 'big')
|
|
420
|
+
if decrypted_padded_bytes[0:2] != b'\x00\x01':
|
|
421
|
+
raise ValueError("Error: Invalid padding (not PKCS#1 Type 1).")
|
|
422
|
+
separator_index = decrypted_padded_bytes.find(b'\x00', 2)
|
|
423
|
+
if separator_index == -1:
|
|
424
|
+
raise ValueError("Error: Padding separator (0x00) not found.")
|
|
425
|
+
payload_bytes = decrypted_padded_bytes[separator_index + 1:]
|
|
426
|
+
result = json.loads(payload_bytes.decode('utf-8').replace('}{', ','))
|
|
427
|
+
return result
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def file_info():
|
|
431
|
+
|
|
432
|
+
while True:
|
|
433
|
+
file_path = input("Enter .zip file path: ")
|
|
434
|
+
if os.path.isfile(file_path) and file_path.lower().endswith(".zip"):
|
|
435
|
+
break
|
|
436
|
+
print("Invalid path or file is not a .zip. Try again.")
|
|
437
|
+
|
|
438
|
+
md5_hash = hashlib.md5()
|
|
439
|
+
sha1_hash = hashlib.sha1()
|
|
440
|
+
with open(file_path, "rb") as f:
|
|
441
|
+
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
|
442
|
+
md5_hash.update(chunk)
|
|
443
|
+
sha1_hash.update(chunk)
|
|
444
|
+
md5_hex = md5_hash.hexdigest()
|
|
445
|
+
sha1_hex = sha1_hash.hexdigest()
|
|
446
|
+
|
|
447
|
+
return file_path, md5_hex, sha1_hex
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def extract_validate(data):
|
|
451
|
+
result = {}
|
|
452
|
+
seen = set()
|
|
453
|
+
def walk(obj, parent=None):
|
|
454
|
+
if isinstance(obj, dict):
|
|
455
|
+
if 'Validate' in obj and parent:
|
|
456
|
+
md5 = obj.get('md5')
|
|
457
|
+
if md5 not in seen:
|
|
458
|
+
seen.add(md5)
|
|
459
|
+
result[parent] = {'md5': obj.get('md5'), 'Validate': obj['Validate']}
|
|
460
|
+
for k, v in obj.items():
|
|
461
|
+
walk(v, k)
|
|
462
|
+
elif isinstance(obj, list):
|
|
463
|
+
for item in obj:
|
|
464
|
+
walk(item, parent)
|
|
465
|
+
walk(data)
|
|
466
|
+
return result
|
|
467
|
+
|
|
468
|
+
def flash_rom():
|
|
469
|
+
path, md5, sha1 = file_info()
|
|
470
|
+
|
|
471
|
+
info = get_info()
|
|
472
|
+
transport = get_transport()
|
|
473
|
+
r = _validate_request(info, md5)
|
|
474
|
+
|
|
475
|
+
if "PkgRom" in r and "Validate" in r["PkgRom"]:
|
|
476
|
+
validate = r["PkgRom"]["Validate"]
|
|
477
|
+
decrypted = validate_decrypt(validate)
|
|
478
|
+
if decrypted.get("SHA1") != sha1:
|
|
479
|
+
print("SHA1 mismatch between local file and server response.")
|
|
480
|
+
return
|
|
481
|
+
if r["PkgRom"]["Erase"] == 1:
|
|
482
|
+
input("NOTICE: Data will be erased during flashing.\nPress Enter to continue...")
|
|
483
|
+
start_sideload(transport, path, validate)
|
|
484
|
+
else:
|
|
485
|
+
r2 = _validate_request(info, "")
|
|
486
|
+
checkv = extract_validate(r2)
|
|
487
|
+
for key, v in checkv.items():
|
|
488
|
+
decrypted = validate_decrypt(v['Validate'])
|
|
489
|
+
if decrypted.get("SHA1") == sha1:
|
|
490
|
+
if v['md5'] != md5:
|
|
491
|
+
r3 = _validate_request(info, v['md5'])
|
|
492
|
+
if "PkgRom" in r3 and "Validate" in r3["PkgRom"]:
|
|
493
|
+
print("MD5 mismatch between local file and server response.")
|
|
494
|
+
validate3 = r3["PkgRom"]["Validate"]
|
|
495
|
+
start_sideload(transport, path, validate3)
|
|
496
|
+
break
|
|
497
|
+
else:
|
|
498
|
+
valid = []
|
|
499
|
+
for key, v in checkv.items():
|
|
500
|
+
r4 = _validate_request(info, v['md5'])
|
|
501
|
+
if "PkgRom" in r4 and "Validate" in r4["PkgRom"]:
|
|
502
|
+
pkg = r4["PkgRom"]
|
|
503
|
+
link = f"https://bigota.d.miui.com/{pkg['version']}/{pkg['filename']}"
|
|
504
|
+
valid.append((pkg['md5'], link))
|
|
505
|
+
if valid:
|
|
506
|
+
print("\nROMs that can be flashed on this device:")
|
|
507
|
+
for md5v, link in valid:
|
|
508
|
+
print(f"\nmd5: {md5v}\ndownload_url: {link}\n")
|
|
509
|
+
else:
|
|
510
|
+
print("\nNo ROM can be installed on this device !.")
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def check_rom():
|
|
514
|
+
info = get_info()
|
|
515
|
+
r2 = _validate_request(info, "")
|
|
516
|
+
checkv = extract_validate(r2)
|
|
517
|
+
valid = []
|
|
518
|
+
for key, v in checkv.items():
|
|
519
|
+
r4 = _validate_request(info, v['md5'])
|
|
520
|
+
if "PkgRom" in r4 and "Validate" in r4["PkgRom"]:
|
|
521
|
+
pkg = r4["PkgRom"]
|
|
522
|
+
link = f"https://bigota.d.miui.com/{pkg['version']}/{pkg['filename']}"
|
|
523
|
+
valid.append((pkg['md5'], link))
|
|
524
|
+
if valid:
|
|
525
|
+
print("\nROMs that can be flashed on this device:")
|
|
526
|
+
for md5v, link in valid:
|
|
527
|
+
print(f"\nmd5: {md5v}\ndownload_url: {link}\n")
|
|
528
|
+
else:
|
|
529
|
+
print("\nNo ROM can be installed on this device !.")
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def send_simple(command):
|
|
533
|
+
transport = get_transport()
|
|
534
|
+
print(adb_cmd(transport, command))
|
|
535
|
+
|
|
536
|
+
def format_data():
|
|
537
|
+
send_simple("format-data:")
|
|
538
|
+
|
|
539
|
+
def format_cache():
|
|
540
|
+
send_simple("format-cache:")
|
|
541
|
+
|
|
542
|
+
def format_storage():
|
|
543
|
+
send_simple("format-storage:")
|
|
544
|
+
|
|
545
|
+
def format_data_storage():
|
|
546
|
+
send_simple("format-data-storage:")
|
|
547
|
+
|
|
548
|
+
def format_frp():
|
|
549
|
+
send_simple("format-frp:")
|
|
550
|
+
|
|
551
|
+
def wipe_data_storage():
|
|
552
|
+
send_simple("wipe-data-storage:")
|
|
553
|
+
|
|
554
|
+
def wipe_efs():
|
|
555
|
+
print("\n⚠️ [WARNING]: If you are a normal user and don't know what this means, DO NOT use this command!")
|
|
556
|
+
print("Wiping EFS will permanently break your phone's network and delete your IMEI.")
|
|
557
|
+
confirm = input("Type 'YES' only if you are an expert and know exactly what you are doing: ")
|
|
558
|
+
if confirm == "YES":
|
|
559
|
+
print("Wiping EFS partition...")
|
|
560
|
+
send_simple("wipe-efs:")
|
|
561
|
+
else:
|
|
562
|
+
print("Operation cancelled.")
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def send_disconnecting(command, verb):
|
|
566
|
+
transport = get_transport()
|
|
567
|
+
try:
|
|
568
|
+
print(adb_cmd(transport, command))
|
|
569
|
+
except DeviceTimeout:
|
|
570
|
+
print(f"Device is {verb} (connection closed as expected).")
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def reboot():
|
|
574
|
+
send_disconnecting("reboot:", "rebooting")
|
|
575
|
+
|
|
576
|
+
def reboot_recovery():
|
|
577
|
+
send_disconnecting("recovery:", "rebooting to recovery")
|
|
578
|
+
|
|
579
|
+
def reboot_fastboot():
|
|
580
|
+
send_disconnecting("fastboot:", "rebooting to fastboot")
|
|
581
|
+
|
|
582
|
+
def reboot_bootloader():
|
|
583
|
+
send_disconnecting("bootloader:", "rebooting to bootloader")
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def shutdown():
|
|
587
|
+
send_disconnecting("shutdown:", "shutting down")
|
|
588
|
+
|
|
589
|
+
ACTION_HANDLERS = {
|
|
590
|
+
1: ("Read Info", read_info),
|
|
591
|
+
2: ("Flash Official Recovery ROM", flash_rom),
|
|
592
|
+
3: ("ROMs That Can Be Flashed", check_rom),
|
|
593
|
+
4: ("Format Data", format_data),
|
|
594
|
+
5: ("Format Cache", format_cache),
|
|
595
|
+
6: ("Format Storage", format_storage),
|
|
596
|
+
7: ("Format Data + Storage", format_data_storage),
|
|
597
|
+
8: ("Format FRP", format_frp),
|
|
598
|
+
9: ("Wipe Data Storage", wipe_data_storage),
|
|
599
|
+
10: ("Wipe EFS", wipe_efs),
|
|
600
|
+
11: ("Reboot", reboot),
|
|
601
|
+
12: ("Reboot to recovery", reboot_recovery),
|
|
602
|
+
13: ("Reboot to fastboot", reboot_fastboot),
|
|
603
|
+
14: ("Reboot to bootloader", reboot_bootloader),
|
|
604
|
+
15: ("Shutdown", shutdown),
|
|
605
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: miasst
|
|
3
|
+
Version: 1.4.0
|
|
4
|
+
Summary: Cross-platform CLI for Xiaomi Mi Assistant mode: flash, wipe, reboot
|
|
5
|
+
Project-URL: Repository, https://github.com/MiForge/MiAssistantTool
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: pyusb
|
|
10
|
+
Requires-Dist: requests
|
|
11
|
+
Requires-Dist: pyaes
|
|
12
|
+
Requires-Dist: rsa
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
<div align="center">
|
|
16
|
+
|
|
17
|
+
<a href="https://github.com/MiForge/MiAssistantTool"><img src="https://img.shields.io/badge/MiAssistantTool-%230070FF?style=flat&logo=xiaomi&logoColor=%23FF6900" alt="MiAssistantTool" style="width: 200px; vertical-align: middle;" /></a><br>
|
|
18
|
+
|
|
19
|
+
Windows, macOS, Linux, and Termux.
|
|
20
|
+
|
|
21
|
+
[](https://pypi.org/project/miasst/)
|
|
22
|
+
[](CHANGELOG.md)
|
|
23
|
+
[](./LICENSE)
|
|
24
|
+
___
|
|
25
|
+
|
|
26
|
+
</div>
|
|
27
|
+
|
|
28
|
+
In Mi Assistant mode, without unlocking the bootloader:
|
|
29
|
+
|
|
30
|
+
- Read Info
|
|
31
|
+
- Flash Official Recovery ROM
|
|
32
|
+
- ROMs that can be flashed
|
|
33
|
+
- Format Data / Cache / Storage / Data + Storage / FRP
|
|
34
|
+
- Wipe Data Storage / EFS
|
|
35
|
+
- Reboot / Reboot to recovery / fastboot / bootloader
|
|
36
|
+
- Shutdown
|
|
37
|
+
|
|
38
|
+
___
|
|
39
|
+
|
|
40
|
+
### Dependencies
|
|
41
|
+
|
|
42
|
+
* Linux: `sudo apt install libusb-1.0-0`
|
|
43
|
+
* macOS: `brew install libusb`
|
|
44
|
+
* Termux: `pkg install libusb`
|
|
45
|
+
* Windows: No extra steps required (uses standard USB drivers).
|
|
46
|
+
|
|
47
|
+
### Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install miasst
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Usage
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
miasst
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Notes
|
|
60
|
+
|
|
61
|
+
On Termux (without root) you'll need the [Termux:API](https://github.com/termux/termux-api/releases/latest) app, and `pkg install termux-api`.
|
|
62
|
+
|
|
63
|
+
### Quick Installation (for Termux):
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
curl -sS https://raw.githubusercontent.com/MiForge/MiAssistantTool/main/install.sh | bash
|
|
67
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
miassistant/__init__.py
|
|
5
|
+
miassistant/cli.py
|
|
6
|
+
miassistant/core.py
|
|
7
|
+
miasst.egg-info/PKG-INFO
|
|
8
|
+
miasst.egg-info/SOURCES.txt
|
|
9
|
+
miasst.egg-info/dependency_links.txt
|
|
10
|
+
miasst.egg-info/entry_points.txt
|
|
11
|
+
miasst.egg-info/requires.txt
|
|
12
|
+
miasst.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
miassistant
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "miasst"
|
|
7
|
+
version = "1.4.0"
|
|
8
|
+
description = "Cross-platform CLI for Xiaomi Mi Assistant mode: flash, wipe, reboot"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"pyusb",
|
|
13
|
+
"requests",
|
|
14
|
+
"pyaes",
|
|
15
|
+
"rsa",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Repository = "https://github.com/MiForge/MiAssistantTool"
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
miasst = "miassistant.cli:main"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
include = ["miassistant*"]
|
miasst-1.4.0/setup.cfg
ADDED