-
Notifications
You must be signed in to change notification settings - Fork 2
/
lpac-mbim
executable file
·167 lines (138 loc) · 5.35 KB
/
lpac-mbim
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
#!/usr/bin/python3
# SPDX-FileCopyrightText: 2024 Luca Weiss
# SPDX-License-Identifier: MIT
import os
import json
import subprocess
import sys
from pprint import pprint
from typing import Optional
DEBUG = False
# read the device path from the command line
if len(sys.argv)>1 and sys.argv[1].startswith('--device='):
DEV=sys.argv[1].split('--device=')[1]
sys.argv.pop(1)
else:
DEV = "/dev/wwan0mbim0"
if not(os.path.exists(DEV)):
print('device',DEV,'is not found, pass it in the first command line parameter like --device=/dev/wwan0mbim1 or --device=/dev/cdc-wdm1')
sys.exit()
# apdu request doesn't provide us the channel_id again, so we need to persist it
CHANNEL_ID: Optional[int] = None
def run_mbimcli(command: str) -> str:
try:
command = command.replace('"', '')
output_bytes = subprocess.check_output(["mbimcli", "-p", "-d", DEV] + command.split(),
stderr=subprocess.STDOUT,
timeout=10)
output_str = output_bytes.decode("utf-8")
return output_str.strip()
except subprocess.CalledProcessError as e:
print("Error executing command:", e.output.decode("utf-8"))
return None
def send_apdu(apdu: str) -> str:
output_cmd = run_mbimcli(f'--ms-set-uicc-apdu="channel={CHANNEL_ID},command={apdu}"').split('\n')
status = int(output_cmd[1].split(': ')[1])
status_hex = hex(status)[2:].zfill(4).upper()
status_hex = "".join([status_hex[i:i + 2] for i in range(0, len(status_hex), 2)][::-1])
response = output_cmd[2].split(': ')[1].replace(':', '')
if response.strip() != "(null)":
return f'{response}{status_hex}'
else:
return f'{status_hex}'
def open_channel(aid: str) -> str:
output_cmd = run_mbimcli(f'--ms-set-uicc-open-channel="application-id={aid}",channel-group=1').split('\n')
channel_line = next(line for line in output_cmd if line.startswith('\t channel:'))
channel_id_str = channel_line.split(': ')[1].strip()
channel_id = int(channel_id_str)
return channel_id
def close_channel(channel_id: int) -> None:
run_mbimcli(f'--ms-set-uicc-close-channel="channel={channel_id}"')
def handle_type_apdu(func: str, param: str):
if func == "connect":
# Nothing to do
print("INFO: Connect")
return {"ecode": 0}
if func == "disconnect":
# Nothing to do
print("INFO: Disconnect")
return {"ecode": 0}
if func == "logic_channel_open":
print(f"INFO: Open channel with AID {param}")
try:
channel_id = open_channel(param)
# We need to persist the channel ID for send_apdu
global CHANNEL_ID
CHANNEL_ID = channel_id
return {"ecode": 1}
except subprocess.CalledProcessError as e:
print(e)
return {"ecode": "-1"}
if func == "logic_channel_close":
try:
print(f"INFO: Close channel {CHANNEL_ID}")
close_channel(int(CHANNEL_ID))
return {"ecode": 0}
except subprocess.CalledProcessError as e:
print(e)
return {"ecode": "-1"}
if func == "transmit":
try:
if DEBUG:
print(f"Send APDU: {param}")
data = send_apdu(param)
if DEBUG:
print(f"Recv APDU: {data}")
return {"ecode": 0, "data": data}
except subprocess.CalledProcessError as e:
return {"ecode": "-1"}
raise RuntimeError(f"Unhandled func {func}")
def main():
if os.environ.get("DEBUG") == "1":
global DEBUG
DEBUG = 1
env = os.environ.copy()
env["APDU_INTERFACE"] = "libapduinterface_stdio.so"
env["LPAC_APDU"] = "stdio"
cmd = ['lpac'] + sys.argv[1:]
with subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env,
text=True) as proc:
while proc.poll() is None:
# Read a line from lpac
line = proc.stdout.readline().strip()
if DEBUG:
print(f"recv={line}")
if not line:
continue
try:
req = json.loads(line)
except json.decoder.JSONDecodeError:
print("Failed to decode JSON:")
print(line)
continue
req_type = req["type"]
if req_type == "lpa":
print("INFO: Received LPA data. Printing...")
pprint(req)
continue
if req_type == "progress":
print("INFO: Received progress. Printing...")
pprint(req)
continue
if req_type == "apdu":
payload = handle_type_apdu(req["payload"]["func"], req["payload"]["param"])
resp = {"type": "apdu", "payload": payload}
# Send a line to lpac
if DEBUG:
print(f"send={json.dumps(resp)}")
proc.stdin.write(json.dumps(resp) + "\n")
proc.stdin.flush()
continue
raise RuntimeError(f"Unknown request type {req_type}")
print(f"Exit code: {proc.returncode}")
if __name__ == '__main__':
main()