datap 0.1.0__tar.gz → 0.1.2__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.
- {datap-0.1.0/src/datap.egg-info → datap-0.1.2}/PKG-INFO +42 -22
- datap-0.1.0/PKG-INFO → datap-0.1.2/README.md +34 -31
- {datap-0.1.0 → datap-0.1.2}/pyproject.toml +8 -3
- {datap-0.1.0 → datap-0.1.2}/src/btsh/__init__.py +7 -1
- {datap-0.1.0 → datap-0.1.2}/src/btsh/channel.py +4 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/cli.py +95 -4
- {datap-0.1.0 → datap-0.1.2}/src/btsh/client.py +9 -2
- {datap-0.1.0 → datap-0.1.2}/src/btsh/crypto.py +34 -8
- {datap-0.1.0 → datap-0.1.2}/src/btsh/modem.py +12 -9
- {datap-0.1.0 → datap-0.1.2}/src/btsh/session.py +40 -3
- datap-0.1.2/src/btsh/tcp.py +75 -0
- datap-0.1.0/README.md → datap-0.1.2/src/datap.egg-info/PKG-INFO +50 -20
- {datap-0.1.0 → datap-0.1.2}/src/datap.egg-info/SOURCES.txt +2 -0
- datap-0.1.2/src/datap.egg-info/requires.txt +10 -0
- {datap-0.1.0 → datap-0.1.2}/tests/test_channels.py +43 -0
- {datap-0.1.0 → datap-0.1.2}/tests/test_modem.py +5 -3
- {datap-0.1.0 → datap-0.1.2}/setup.cfg +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/__main__.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/audio.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/ble.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/bt.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/channels.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/codec.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/framing.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/hub.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/mcp.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/node.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/py.typed +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/server.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/btsh/transport.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/datap.egg-info/dependency_links.txt +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/datap.egg-info/entry_points.txt +0 -0
- {datap-0.1.0 → datap-0.1.2}/src/datap.egg-info/top_level.txt +0 -0
- {datap-0.1.0 → datap-0.1.2}/tests/test_crypto.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/tests/test_e2e.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/tests/test_framing.py +0 -0
- {datap-0.1.0 → datap-0.1.2}/tests/test_mesh.py +0 -0
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datap
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Shell over a Bluetooth speaker's audio codec: run commands without an SSH server
|
|
5
5
|
Author: Marc Partensky
|
|
6
|
-
License: MIT
|
|
6
|
+
License-Expression: MIT
|
|
7
7
|
Keywords: bluetooth,a2dp,sbc,modem,shell,ssh
|
|
8
8
|
Requires-Python: >=3.10
|
|
9
9
|
Description-Content-Type: text/markdown
|
|
10
|
+
Provides-Extra: portaudio
|
|
11
|
+
Requires-Dist: sounddevice>=0.4; extra == "portaudio"
|
|
12
|
+
Provides-Extra: ble
|
|
13
|
+
Requires-Dist: bleak>=0.21; extra == "ble"
|
|
14
|
+
Provides-Extra: all
|
|
15
|
+
Requires-Dist: sounddevice>=0.4; extra == "all"
|
|
16
|
+
Requires-Dist: bleak>=0.21; extra == "all"
|
|
10
17
|
|
|
11
18
|
# btsh
|
|
12
19
|
|
|
@@ -25,8 +32,8 @@ whatever Bluetooth channel you can actually use, and turns it into `exec` and
|
|
|
25
32
|
|
|
26
33
|
## The honest part about Android
|
|
27
34
|
|
|
28
|
-
The intended topology ("an Android app that
|
|
29
|
-
and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
35
|
+
The intended topology ("an Android app that shows up as a Bluetooth device,
|
|
36
|
+
plays music and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
30
37
|
|
|
31
38
|
* `A2dpSinkService` is a system service and every entry point enforces
|
|
32
39
|
`BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
|
|
@@ -37,9 +44,10 @@ and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
|
37
44
|
`AudioRecord`/`AudioTrack` path for it.
|
|
38
45
|
* HFP is the same story: SCO audio belongs to the telephony stack.
|
|
39
46
|
|
|
40
|
-
So the Android app in `android/` is a **BLE GATT peripheral** that advertises
|
|
41
|
-
|
|
42
|
-
|
|
47
|
+
So the Android app in `android/` is a **BLE GATT peripheral** that advertises
|
|
48
|
+
under a name you pick from a list of 20 real earbud names in the app
|
|
49
|
+
("Redmi Buds 6 Pro" by default) with the 128-bit
|
|
50
|
+
service UUID in the scan response, and serves the exact same frames. That is the only radio channel an app may serve
|
|
43
51
|
on Android, and `bleak` drives it from all three desktop OSes. The acoustic
|
|
44
52
|
modem stays available where the OS does expose the stream (desktops), and it is
|
|
45
53
|
what makes "the speaker's codec carries your shell" literal.
|
|
@@ -47,8 +55,8 @@ what makes "the speaker's codec carries your shell" literal.
|
|
|
47
55
|
## Install
|
|
48
56
|
|
|
49
57
|
```bash
|
|
50
|
-
pip install
|
|
51
|
-
pip install
|
|
58
|
+
pip install datap # core, stdlib only
|
|
59
|
+
pip install "datap[all]" # + sounddevice (PortAudio) and bleak (BLE)
|
|
52
60
|
```
|
|
53
61
|
|
|
54
62
|
`ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
|
|
@@ -65,10 +73,17 @@ btsh demo
|
|
|
65
73
|
Two processes on one host, no socket and no SSH, still through SBC:
|
|
66
74
|
|
|
67
75
|
```bash
|
|
68
|
-
btsh serve --transport fifo --codec sbc
|
|
69
|
-
btsh exec --transport fifo --codec sbc --
|
|
76
|
+
btsh serve --transport fifo --codec sbc &
|
|
77
|
+
btsh exec --transport fifo --codec sbc -- "uname -a | head -1"
|
|
70
78
|
```
|
|
71
79
|
|
|
80
|
+
There is no key to hand over before the first run: the default link mode is
|
|
81
|
+
`--crypto sealed`, and each side generates an X25519 identity in
|
|
82
|
+
`~/.btsh/identity` on first use. `exec`/`shell` print the peer fingerprint they
|
|
83
|
+
sealed to, so two machines can be compared once and remembered by eye. A
|
|
84
|
+
pre-shared key (`--key FILE` with `--crypto psk`) is only for peers that cannot
|
|
85
|
+
do asymmetric crypto, such as the Android app today.
|
|
86
|
+
|
|
72
87
|
Real speaker, PipeWire (Linux):
|
|
73
88
|
|
|
74
89
|
```bash
|
|
@@ -90,9 +105,9 @@ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -s
|
|
|
90
105
|
Android server over BLE:
|
|
91
106
|
|
|
92
107
|
```bash
|
|
93
|
-
btsh scan --timeout 10 # the app advertises as "
|
|
94
|
-
btsh exec --transport ble --ble-name "
|
|
95
|
-
btsh shell --transport ble --ble-name "
|
|
108
|
+
btsh scan --timeout 10 # the app advertises as "Redmi Buds 6 Pro"
|
|
109
|
+
btsh exec --transport ble --ble-name "Redmi" -- "id"
|
|
110
|
+
btsh shell --transport ble --ble-name "Redmi"
|
|
96
111
|
```
|
|
97
112
|
|
|
98
113
|
## CLI
|
|
@@ -129,10 +144,14 @@ One frame, 12 bytes of overhead:
|
|
|
129
144
|
.. crc32 over version..payload
|
|
130
145
|
```
|
|
131
146
|
|
|
132
|
-
* Acoustic link: each frame is modulated as 4-FSK (
|
|
133
|
-
|
|
134
|
-
32 bit sync word. Measured:
|
|
135
|
-
200 and 328 kbit/s
|
|
147
|
+
* Acoustic link: each frame is modulated as 4-FSK (32 sample symbols,
|
|
148
|
+
1000/2500/4000/5500 Hz, 2 bits per symbol, 3000 bit/s raw), 24 ms of lead
|
|
149
|
+
silence, 12 symbol preamble, 32 bit sync word. Measured: 20/20 frames
|
|
150
|
+
recovered through ffmpeg SBC at 128, 200 and 328 kbit/s (0/20 at 64 kbit/s,
|
|
151
|
+
where the codec cuts the band), ~330 B/s of payload.
|
|
152
|
+
* Compression: any JSON body over 96 bytes is deflated when that wins by 10 %,
|
|
153
|
+
before sealing, so shell output travels 2 to 3.5 times shorter. Measurement
|
|
154
|
+
does not change the format: the receiver inflates after unsealing.
|
|
136
155
|
* Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
|
|
137
156
|
* Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
|
|
138
157
|
* Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
|
|
@@ -142,8 +161,9 @@ One frame, 12 bytes of overhead:
|
|
|
142
161
|
|
|
143
162
|
## Limits, stated plainly
|
|
144
163
|
|
|
145
|
-
* Payload throughput is ~
|
|
146
|
-
commands, not for `tar | gzip`
|
|
164
|
+
* Payload throughput is ~330 B/s on the acoustic link, ~0.6 s for a command
|
|
165
|
+
and its short output. It is a shell for small commands, not for `tar | gzip`
|
|
166
|
+
over the air, and SBC below 128 kbit/s cannot carry the modem at all.
|
|
147
167
|
* A2DP is one way: a full session needs HFP (the speaker's microphone) or two
|
|
148
168
|
paired devices. `pw` and `portaudio` record from the same node/device they
|
|
149
169
|
play into, so duplex means a headset, not a plain speaker.
|
|
@@ -168,7 +188,7 @@ btsh selftest --frames 12
|
|
|
168
188
|
android/app/src/main/java/com/marcpartensky/btsh/
|
|
169
189
|
├── Protocol.kt frame pack/unpack, same bytes as Python
|
|
170
190
|
├── ShellRunner.kt /system/bin/sh or su -c, output capped
|
|
171
|
-
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC,
|
|
191
|
+
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, BLE advertising
|
|
172
192
|
├── BtshService.kt foreground service, keeps advertising alive
|
|
173
193
|
└── MainActivity.kt key field, start/stop, log
|
|
174
194
|
```
|
|
@@ -184,7 +204,7 @@ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.
|
|
|
184
204
|
then start it, set the same key as the client, and connect from the desktop:
|
|
185
205
|
|
|
186
206
|
```bash
|
|
187
|
-
btsh exec --transport ble --ble-name "
|
|
207
|
+
btsh exec --transport ble --ble-name "Redmi" --key ~/.btsh.key -- "getprop ro.product.model"
|
|
188
208
|
```
|
|
189
209
|
|
|
190
210
|
## Nix
|
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: datap
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: Shell over a Bluetooth speaker's audio codec: run commands without an SSH server
|
|
5
|
-
Author: Marc Partensky
|
|
6
|
-
License: MIT
|
|
7
|
-
Keywords: bluetooth,a2dp,sbc,modem,shell,ssh
|
|
8
|
-
Requires-Python: >=3.10
|
|
9
|
-
Description-Content-Type: text/markdown
|
|
10
|
-
|
|
11
1
|
# btsh
|
|
12
2
|
|
|
13
3
|
A shell that rides on a Bluetooth link, no SSH server anywhere.
|
|
@@ -25,8 +15,8 @@ whatever Bluetooth channel you can actually use, and turns it into `exec` and
|
|
|
25
15
|
|
|
26
16
|
## The honest part about Android
|
|
27
17
|
|
|
28
|
-
The intended topology ("an Android app that
|
|
29
|
-
and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
18
|
+
The intended topology ("an Android app that shows up as a Bluetooth device,
|
|
19
|
+
plays music and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
30
20
|
|
|
31
21
|
* `A2dpSinkService` is a system service and every entry point enforces
|
|
32
22
|
`BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
|
|
@@ -37,9 +27,10 @@ and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
|
37
27
|
`AudioRecord`/`AudioTrack` path for it.
|
|
38
28
|
* HFP is the same story: SCO audio belongs to the telephony stack.
|
|
39
29
|
|
|
40
|
-
So the Android app in `android/` is a **BLE GATT peripheral** that advertises
|
|
41
|
-
|
|
42
|
-
|
|
30
|
+
So the Android app in `android/` is a **BLE GATT peripheral** that advertises
|
|
31
|
+
under a name you pick from a list of 20 real earbud names in the app
|
|
32
|
+
("Redmi Buds 6 Pro" by default) with the 128-bit
|
|
33
|
+
service UUID in the scan response, and serves the exact same frames. That is the only radio channel an app may serve
|
|
43
34
|
on Android, and `bleak` drives it from all three desktop OSes. The acoustic
|
|
44
35
|
modem stays available where the OS does expose the stream (desktops), and it is
|
|
45
36
|
what makes "the speaker's codec carries your shell" literal.
|
|
@@ -47,8 +38,8 @@ what makes "the speaker's codec carries your shell" literal.
|
|
|
47
38
|
## Install
|
|
48
39
|
|
|
49
40
|
```bash
|
|
50
|
-
pip install
|
|
51
|
-
pip install
|
|
41
|
+
pip install datap # core, stdlib only
|
|
42
|
+
pip install "datap[all]" # + sounddevice (PortAudio) and bleak (BLE)
|
|
52
43
|
```
|
|
53
44
|
|
|
54
45
|
`ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
|
|
@@ -65,10 +56,17 @@ btsh demo
|
|
|
65
56
|
Two processes on one host, no socket and no SSH, still through SBC:
|
|
66
57
|
|
|
67
58
|
```bash
|
|
68
|
-
btsh serve --transport fifo --codec sbc
|
|
69
|
-
btsh exec --transport fifo --codec sbc --
|
|
59
|
+
btsh serve --transport fifo --codec sbc &
|
|
60
|
+
btsh exec --transport fifo --codec sbc -- "uname -a | head -1"
|
|
70
61
|
```
|
|
71
62
|
|
|
63
|
+
There is no key to hand over before the first run: the default link mode is
|
|
64
|
+
`--crypto sealed`, and each side generates an X25519 identity in
|
|
65
|
+
`~/.btsh/identity` on first use. `exec`/`shell` print the peer fingerprint they
|
|
66
|
+
sealed to, so two machines can be compared once and remembered by eye. A
|
|
67
|
+
pre-shared key (`--key FILE` with `--crypto psk`) is only for peers that cannot
|
|
68
|
+
do asymmetric crypto, such as the Android app today.
|
|
69
|
+
|
|
72
70
|
Real speaker, PipeWire (Linux):
|
|
73
71
|
|
|
74
72
|
```bash
|
|
@@ -90,9 +88,9 @@ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -s
|
|
|
90
88
|
Android server over BLE:
|
|
91
89
|
|
|
92
90
|
```bash
|
|
93
|
-
btsh scan --timeout 10 # the app advertises as "
|
|
94
|
-
btsh exec --transport ble --ble-name "
|
|
95
|
-
btsh shell --transport ble --ble-name "
|
|
91
|
+
btsh scan --timeout 10 # the app advertises as "Redmi Buds 6 Pro"
|
|
92
|
+
btsh exec --transport ble --ble-name "Redmi" -- "id"
|
|
93
|
+
btsh shell --transport ble --ble-name "Redmi"
|
|
96
94
|
```
|
|
97
95
|
|
|
98
96
|
## CLI
|
|
@@ -129,10 +127,14 @@ One frame, 12 bytes of overhead:
|
|
|
129
127
|
.. crc32 over version..payload
|
|
130
128
|
```
|
|
131
129
|
|
|
132
|
-
* Acoustic link: each frame is modulated as 4-FSK (
|
|
133
|
-
|
|
134
|
-
32 bit sync word. Measured:
|
|
135
|
-
200 and 328 kbit/s
|
|
130
|
+
* Acoustic link: each frame is modulated as 4-FSK (32 sample symbols,
|
|
131
|
+
1000/2500/4000/5500 Hz, 2 bits per symbol, 3000 bit/s raw), 24 ms of lead
|
|
132
|
+
silence, 12 symbol preamble, 32 bit sync word. Measured: 20/20 frames
|
|
133
|
+
recovered through ffmpeg SBC at 128, 200 and 328 kbit/s (0/20 at 64 kbit/s,
|
|
134
|
+
where the codec cuts the band), ~330 B/s of payload.
|
|
135
|
+
* Compression: any JSON body over 96 bytes is deflated when that wins by 10 %,
|
|
136
|
+
before sealing, so shell output travels 2 to 3.5 times shorter. Measurement
|
|
137
|
+
does not change the format: the receiver inflates after unsealing.
|
|
136
138
|
* Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
|
|
137
139
|
* Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
|
|
138
140
|
* Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
|
|
@@ -142,8 +144,9 @@ One frame, 12 bytes of overhead:
|
|
|
142
144
|
|
|
143
145
|
## Limits, stated plainly
|
|
144
146
|
|
|
145
|
-
* Payload throughput is ~
|
|
146
|
-
commands, not for `tar | gzip`
|
|
147
|
+
* Payload throughput is ~330 B/s on the acoustic link, ~0.6 s for a command
|
|
148
|
+
and its short output. It is a shell for small commands, not for `tar | gzip`
|
|
149
|
+
over the air, and SBC below 128 kbit/s cannot carry the modem at all.
|
|
147
150
|
* A2DP is one way: a full session needs HFP (the speaker's microphone) or two
|
|
148
151
|
paired devices. `pw` and `portaudio` record from the same node/device they
|
|
149
152
|
play into, so duplex means a headset, not a plain speaker.
|
|
@@ -168,7 +171,7 @@ btsh selftest --frames 12
|
|
|
168
171
|
android/app/src/main/java/com/marcpartensky/btsh/
|
|
169
172
|
├── Protocol.kt frame pack/unpack, same bytes as Python
|
|
170
173
|
├── ShellRunner.kt /system/bin/sh or su -c, output capped
|
|
171
|
-
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC,
|
|
174
|
+
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, BLE advertising
|
|
172
175
|
├── BtshService.kt foreground service, keeps advertising alive
|
|
173
176
|
└── MainActivity.kt key field, start/stop, log
|
|
174
177
|
```
|
|
@@ -184,7 +187,7 @@ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.
|
|
|
184
187
|
then start it, set the same key as the client, and connect from the desktop:
|
|
185
188
|
|
|
186
189
|
```bash
|
|
187
|
-
btsh exec --transport ble --ble-name "
|
|
190
|
+
btsh exec --transport ble --ble-name "Redmi" --key ~/.btsh.key -- "getprop ro.product.model"
|
|
188
191
|
```
|
|
189
192
|
|
|
190
193
|
## Nix
|
|
@@ -204,4 +207,4 @@ services.btsh = {
|
|
|
204
207
|
cwd = "/home/marc";
|
|
205
208
|
allow = [ "^ls" "^cat" "^uname" ];
|
|
206
209
|
};
|
|
207
|
-
```
|
|
210
|
+
```
|
|
@@ -1,18 +1,23 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["setuptools>=
|
|
2
|
+
requires = ["setuptools>=77.0.0"]
|
|
3
3
|
build-backend = "setuptools.build_meta"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "datap"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.2"
|
|
8
8
|
description = "Shell over a Bluetooth speaker's audio codec: run commands without an SSH server"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
11
|
-
license =
|
|
11
|
+
license = "MIT"
|
|
12
12
|
authors = [{ name = "Marc Partensky" }]
|
|
13
13
|
keywords = ["bluetooth", "a2dp", "sbc", "modem", "shell", "ssh"]
|
|
14
14
|
dependencies = []
|
|
15
15
|
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
portaudio = ["sounddevice>=0.4"]
|
|
18
|
+
ble = ["bleak>=0.21"]
|
|
19
|
+
all = ["sounddevice>=0.4", "bleak>=0.21"]
|
|
20
|
+
|
|
16
21
|
[project.scripts]
|
|
17
22
|
btsh = "btsh.cli:main"
|
|
18
23
|
|
|
@@ -2,7 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
from importlib.metadata import PackageNotFoundError
|
|
6
|
+
from importlib.metadata import version as _distribution_version
|
|
7
|
+
|
|
8
|
+
try: # installed from PyPI or a wheel
|
|
9
|
+
__version__ = _distribution_version("datap")
|
|
10
|
+
except PackageNotFoundError: # running from a source tree, keep in sync with pyproject.toml
|
|
11
|
+
__version__ = "0.1.2"
|
|
6
12
|
|
|
7
13
|
from .channel import Channel, ChannelError # noqa: E402
|
|
8
14
|
from .client import Client # noqa: E402
|
|
@@ -46,6 +46,10 @@ class Channel:
|
|
|
46
46
|
self.seq = (self.seq + 1) & 0xFF
|
|
47
47
|
return self.seq
|
|
48
48
|
|
|
49
|
+
def next_seq(self) -> int:
|
|
50
|
+
"""Public form of the counter, for callers that must tag before sending."""
|
|
51
|
+
return self._next_seq()
|
|
52
|
+
|
|
49
53
|
def _transmit(self, frame: Frame) -> None:
|
|
50
54
|
wire = framing.pack(frame)
|
|
51
55
|
payload = wire if self.mode == "raw" else modem.modulate(wire)
|
|
@@ -9,8 +9,9 @@ import shutil
|
|
|
9
9
|
import socket
|
|
10
10
|
import sys
|
|
11
11
|
import threading
|
|
12
|
+
import time
|
|
12
13
|
|
|
13
|
-
from . import __version__, audio, ble, bt, codec
|
|
14
|
+
from . import __version__, audio, ble, bt, codec, tcp
|
|
14
15
|
from .channel import Channel, ChannelError
|
|
15
16
|
from .client import Client
|
|
16
17
|
from .server import ShellConfig, ShellServer
|
|
@@ -40,7 +41,7 @@ def _add_link_args(parser: argparse.ArgumentParser) -> None:
|
|
|
40
41
|
group = parser.add_argument_group("link")
|
|
41
42
|
group.add_argument(
|
|
42
43
|
"--transport",
|
|
43
|
-
choices=("fifo", "pw", "portaudio", "ble", "loopback"),
|
|
44
|
+
choices=("fifo", "pw", "portaudio", "ble", "tcp", "loopback"),
|
|
44
45
|
default="fifo",
|
|
45
46
|
help="fifo: two pipes on one host; pw: PipeWire; portaudio: Linux/macOS/Windows; ble: GATT",
|
|
46
47
|
)
|
|
@@ -51,6 +52,8 @@ def _add_link_args(parser: argparse.ArgumentParser) -> None:
|
|
|
51
52
|
group.add_argument("--input-device", help="PortAudio input device (index or name)")
|
|
52
53
|
group.add_argument("--ble-address", help="BLE peripheral MAC / UUID")
|
|
53
54
|
group.add_argument("--ble-name", help="BLE peripheral name to scan for")
|
|
55
|
+
group.add_argument("--host", help="tcp transport: hub host (or BTSH_HOST)")
|
|
56
|
+
group.add_argument("--port", type=int, help="tcp transport: hub port (default 7878)")
|
|
54
57
|
group.add_argument("--codec", choices=("none", "sbc"), default="sbc", help="codec the acoustic link must survive")
|
|
55
58
|
group.add_argument("--key", help="file holding the pre-shared key (HMAC-SHA256 handshake)")
|
|
56
59
|
group.add_argument(
|
|
@@ -95,6 +98,11 @@ def _build_transport(args, role: str):
|
|
|
95
98
|
audio.PortAudioTransport(output_device=args.output_device, input_device=args.input_device),
|
|
96
99
|
"acoustic",
|
|
97
100
|
)
|
|
101
|
+
if args.transport == "tcp":
|
|
102
|
+
host = args.host or os.environ.get("BTSH_HOST")
|
|
103
|
+
if not host:
|
|
104
|
+
raise SystemExit("btsh: pass --host (or BTSH_HOST) for the tcp transport")
|
|
105
|
+
return tcp.TcpTransport(host, args.port or tcp.DEFAULT_PORT), "raw"
|
|
98
106
|
if args.transport == "ble":
|
|
99
107
|
if role == "server":
|
|
100
108
|
raise SystemExit(
|
|
@@ -246,6 +254,18 @@ def cmd_serve(args) -> int:
|
|
|
246
254
|
return 0
|
|
247
255
|
|
|
248
256
|
|
|
257
|
+
def _announce_link(session) -> None:
|
|
258
|
+
"""Trust on first use: say who we are sealed to, or warn about a clear link."""
|
|
259
|
+
if session.sealed:
|
|
260
|
+
print(f"btsh: sealed to peer {session.peer_fingerprint}", file=sys.stderr)
|
|
261
|
+
return
|
|
262
|
+
print(
|
|
263
|
+
"btsh: WARNING link is not sealed, traffic is in the clear "
|
|
264
|
+
"(peer sent no identity; run both sides with --crypto sealed)",
|
|
265
|
+
file=sys.stderr,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
249
269
|
def cmd_exec(args) -> int:
|
|
250
270
|
key = _read_key(args.key)
|
|
251
271
|
parts = list(args.command)
|
|
@@ -258,7 +278,8 @@ def cmd_exec(args) -> int:
|
|
|
258
278
|
try:
|
|
259
279
|
transport, mode = _build_transport(args, "client")
|
|
260
280
|
channel = _channel(args, transport, mode)
|
|
261
|
-
client = Client.connect(channel, key=key, verbose=args.verbose)
|
|
281
|
+
client = Client.connect(channel, key=key, identity=_identity(args), verbose=args.verbose)
|
|
282
|
+
_announce_link(client.session)
|
|
262
283
|
result = client.exec(command, timeout=args.command_timeout)
|
|
263
284
|
transport.close()
|
|
264
285
|
except (TransportError, ChannelError, AuthError, codec.CodecError) as exc:
|
|
@@ -277,7 +298,8 @@ def cmd_shell(args) -> int:
|
|
|
277
298
|
key = _read_key(args.key)
|
|
278
299
|
transport, mode = _build_transport(args, "client")
|
|
279
300
|
channel = _channel(args, transport, mode)
|
|
280
|
-
client = Client.connect(channel, key=key, verbose=args.verbose)
|
|
301
|
+
client = Client.connect(channel, key=key, identity=_identity(args), verbose=args.verbose)
|
|
302
|
+
_announce_link(client.session)
|
|
281
303
|
try:
|
|
282
304
|
return client.shell()
|
|
283
305
|
finally:
|
|
@@ -434,6 +456,61 @@ def cmd_mcp(args) -> int:
|
|
|
434
456
|
transport.close()
|
|
435
457
|
|
|
436
458
|
|
|
459
|
+
def cmd_node(args) -> int:
|
|
460
|
+
"""Register as a named peer that answers exec requests, like a mesh node."""
|
|
461
|
+
from .node import Node
|
|
462
|
+
|
|
463
|
+
transport, mode = _build_transport(args, "client")
|
|
464
|
+
channel = _channel(args, transport, mode)
|
|
465
|
+
config = ShellConfig(
|
|
466
|
+
cwd=os.path.abspath(os.path.expanduser(args.cwd)),
|
|
467
|
+
timeout=args.timeout,
|
|
468
|
+
max_output=args.max_output,
|
|
469
|
+
allow=args.allow,
|
|
470
|
+
deny=args.deny,
|
|
471
|
+
)
|
|
472
|
+
node = Node(
|
|
473
|
+
channel,
|
|
474
|
+
args.name,
|
|
475
|
+
config=config,
|
|
476
|
+
key=_read_key(args.key),
|
|
477
|
+
identity=_identity(args),
|
|
478
|
+
verbose=args.verbose,
|
|
479
|
+
)
|
|
480
|
+
words = list(args.command or [])
|
|
481
|
+
# argparse keeps the "--" separator in a REMAINDER positional.
|
|
482
|
+
while words and words[0] == "--":
|
|
483
|
+
words.pop(0)
|
|
484
|
+
command = " ".join(words).strip()
|
|
485
|
+
try:
|
|
486
|
+
node.start()
|
|
487
|
+
print(f"btsh node: registered as {args.name} on {transport.describe()}", file=sys.stderr, flush=True)
|
|
488
|
+
if command:
|
|
489
|
+
target = args.to or "server"
|
|
490
|
+
print(f"btsh node: exec on {target}: {command}", file=sys.stderr, flush=True)
|
|
491
|
+
if target in ("server", "local"):
|
|
492
|
+
answer = node.call({"op": "exec", "cmd": command}, timeout=args.exec_timeout)
|
|
493
|
+
else:
|
|
494
|
+
answer = node.exec_on(target, command, timeout=args.exec_timeout)
|
|
495
|
+
sys.stdout.write(answer.get("stdout") or "")
|
|
496
|
+
sys.stdout.flush()
|
|
497
|
+
if answer.get("stderr"):
|
|
498
|
+
sys.stderr.write(answer["stderr"])
|
|
499
|
+
sys.stderr.flush()
|
|
500
|
+
if answer.get("op") == "error":
|
|
501
|
+
print(f"btsh node: {answer}", file=sys.stderr)
|
|
502
|
+
return 1
|
|
503
|
+
return int(answer.get("rc") or 0)
|
|
504
|
+
print("btsh node: answering exec requests, ctrl-c to stop", file=sys.stderr, flush=True)
|
|
505
|
+
while True:
|
|
506
|
+
time.sleep(1.0)
|
|
507
|
+
except KeyboardInterrupt:
|
|
508
|
+
return 0
|
|
509
|
+
finally:
|
|
510
|
+
node.stop()
|
|
511
|
+
transport.close()
|
|
512
|
+
|
|
513
|
+
|
|
437
514
|
def build_parser() -> argparse.ArgumentParser:
|
|
438
515
|
parser = argparse.ArgumentParser(prog="btsh", description="Shell over a Bluetooth speaker's audio codec.")
|
|
439
516
|
parser.add_argument("--version", action="version", version=f"btsh {__version__}")
|
|
@@ -496,6 +573,20 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
496
573
|
mesh.add_argument("--verbose", action="store_true")
|
|
497
574
|
mesh.set_defaults(func=cmd_mesh)
|
|
498
575
|
|
|
576
|
+
node = sub.add_parser("node", help="register as a named peer that answers exec requests")
|
|
577
|
+
_add_link_args(node)
|
|
578
|
+
node.add_argument("--name", default=socket.gethostname())
|
|
579
|
+
node.add_argument("--to", default="", help="send the command to this peer instead of the hub")
|
|
580
|
+
node.add_argument("--cwd", default=".")
|
|
581
|
+
node.add_argument("--timeout", type=float, default=120.0, help="per command timeout on this host")
|
|
582
|
+
node.add_argument("--exec-timeout", type=float, default=180.0,
|
|
583
|
+
help="how long to wait for the remote command")
|
|
584
|
+
node.add_argument("--max-output", type=int, default=65536)
|
|
585
|
+
node.add_argument("--allow", action="append", default=[], help="regex a local command must match")
|
|
586
|
+
node.add_argument("--deny", action="append", default=[], help="regex a local command must not match")
|
|
587
|
+
node.add_argument("command", nargs=argparse.REMAINDER)
|
|
588
|
+
node.set_defaults(func=cmd_node)
|
|
589
|
+
|
|
499
590
|
mcp = sub.add_parser("mcp", help="serve MCP over stdio as a node of the mesh")
|
|
500
591
|
_add_link_args(mcp)
|
|
501
592
|
mcp.add_argument("--name", default=socket.gethostname())
|
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import sys
|
|
6
6
|
import time
|
|
7
7
|
|
|
8
|
+
from . import crypto
|
|
8
9
|
from .channel import Channel
|
|
9
10
|
from .session import Session
|
|
10
11
|
|
|
@@ -16,8 +17,14 @@ class Client:
|
|
|
16
17
|
self.handshaked = False
|
|
17
18
|
|
|
18
19
|
@classmethod
|
|
19
|
-
def connect(
|
|
20
|
-
|
|
20
|
+
def connect(
|
|
21
|
+
cls,
|
|
22
|
+
channel: Channel,
|
|
23
|
+
key: bytes | None = None,
|
|
24
|
+
identity: "crypto.Identity | None" = None,
|
|
25
|
+
verbose: bool = False,
|
|
26
|
+
) -> "Client":
|
|
27
|
+
client = cls(Session(channel, key=key, identity=identity, verbose=verbose))
|
|
21
28
|
client.session.hello()
|
|
22
29
|
client.handshaked = True
|
|
23
30
|
return client
|
|
@@ -172,6 +172,13 @@ def aead_open(key: bytes, nonce: bytes, sealed: bytes, aad: bytes = b"") -> byte
|
|
|
172
172
|
|
|
173
173
|
|
|
174
174
|
# -- identities ---------------------------------------------------------
|
|
175
|
+
def fingerprint(public: bytes) -> str:
|
|
176
|
+
"""Short, human-comparable digest of a 32 byte public key."""
|
|
177
|
+
if len(public) != 32:
|
|
178
|
+
return ""
|
|
179
|
+
return hashlib.sha256(public).hexdigest()[:16]
|
|
180
|
+
|
|
181
|
+
|
|
175
182
|
class Identity:
|
|
176
183
|
"""A long-lived X25519 keypair; the fingerprint is what humans compare."""
|
|
177
184
|
|
|
@@ -183,18 +190,37 @@ class Identity:
|
|
|
183
190
|
|
|
184
191
|
@classmethod
|
|
185
192
|
def from_file(cls, path: str) -> "Identity":
|
|
186
|
-
|
|
187
|
-
|
|
193
|
+
resolved = os.path.expanduser(path)
|
|
194
|
+
with open(resolved, "rb") as handle:
|
|
195
|
+
secret = handle.read().strip()
|
|
196
|
+
if len(secret) != 32:
|
|
197
|
+
raise ValueError(f"{resolved} does not hold a 32 byte secret ({len(secret)} bytes)")
|
|
198
|
+
return cls(secret)
|
|
188
199
|
|
|
189
200
|
def save(self, path: str) -> None:
|
|
201
|
+
"""Write the secret atomically, with a per-process temporary name.
|
|
202
|
+
|
|
203
|
+
A fixed ``.tmp`` suffix loses the race when two nodes start at once on
|
|
204
|
+
the same machine: one truncates the file the other is reading, and the
|
|
205
|
+
identity comes back shorter than 32 bytes.
|
|
206
|
+
"""
|
|
190
207
|
path = os.path.expanduser(path)
|
|
191
208
|
directory = os.path.dirname(path) or "."
|
|
192
|
-
os.makedirs(directory, exist_ok=True)
|
|
193
|
-
temporary = f"{path}.tmp"
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
209
|
+
os.makedirs(directory, mode=0o700, exist_ok=True)
|
|
210
|
+
temporary = f"{path}.{os.getpid()}.{os.urandom(4).hex()}.tmp"
|
|
211
|
+
try:
|
|
212
|
+
with open(temporary, "wb") as handle:
|
|
213
|
+
handle.write(self.secret)
|
|
214
|
+
handle.flush()
|
|
215
|
+
os.fsync(handle.fileno())
|
|
216
|
+
os.chmod(temporary, 0o600)
|
|
217
|
+
os.replace(temporary, path)
|
|
218
|
+
finally:
|
|
219
|
+
if os.path.exists(temporary):
|
|
220
|
+
try:
|
|
221
|
+
os.unlink(temporary)
|
|
222
|
+
except OSError:
|
|
223
|
+
pass
|
|
198
224
|
|
|
199
225
|
@property
|
|
200
226
|
def fingerprint(self) -> str:
|
|
@@ -4,13 +4,16 @@ The waveform is a 4-FSK modulation chosen to survive lossy Bluetooth codecs
|
|
|
4
4
|
(SBC/AAC/aptX) that resample and requantise the signal:
|
|
5
5
|
|
|
6
6
|
sample rate 48 kHz
|
|
7
|
-
symbol
|
|
8
|
-
tones 1000 /
|
|
9
|
-
bits per symbol 2 (
|
|
7
|
+
symbol 32 samples (0.67 ms), 1500 symbols/s
|
|
8
|
+
tones 1000 / 2500 / 4000 / 5500 Hz, 1500 Hz apart
|
|
9
|
+
bits per symbol 2 (1500 * 2 = 3000 bit/s, ~330 bytes/s of payload)
|
|
10
10
|
|
|
11
|
-
Measured with ffmpeg SBC
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
Measured with ffmpeg SBC, 20 frames per point: 40 B and 224 B payloads recover
|
|
12
|
+
20/20 at 128, 200 and 328 kbit/s, and 0/20 at 64 kbit/s, where the codec cuts
|
|
13
|
+
the band above ~5 kHz. The first design ran at 2 ms per symbol (1000 bit/s);
|
|
14
|
+
shortening the symbol to 32 samples and spacing the tones 1500 Hz apart triples
|
|
15
|
+
the rate, and that spacing is not optional: 1000 Hz apart at 32 samples fails
|
|
16
|
+
8/8, because the tones no longer fit in separate decoder bins.
|
|
14
17
|
|
|
15
18
|
Every burst starts with 24 ms of silence, a 12 symbol preamble and the 32 bit
|
|
16
19
|
sync word, so the receiver can find the burst and align its symbol clock
|
|
@@ -23,13 +26,13 @@ import array
|
|
|
23
26
|
import math
|
|
24
27
|
|
|
25
28
|
SAMPLE_RATE = 48000
|
|
26
|
-
SYMBOL_SAMPLES =
|
|
27
|
-
TONES = (1000.0,
|
|
29
|
+
SYMBOL_SAMPLES = 32
|
|
30
|
+
TONES = (1000.0, 2500.0, 4000.0, 5500.0)
|
|
28
31
|
SYNC_WORD = 0x1ACFFC1D
|
|
29
32
|
PREAMBLE = (3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0)
|
|
30
33
|
LEAD_SILENCE = 1152 # 24 ms, lets the receiver see a clean onset
|
|
31
34
|
TAIL_SILENCE = 2304 # 48 ms, drains the codec and the speaker
|
|
32
|
-
RAMP =
|
|
35
|
+
RAMP = 6 # raised-cosine ramp at each symbol edge, limits spectral splatter
|
|
33
36
|
|
|
34
37
|
|
|
35
38
|
class ModemError(Exception):
|
|
@@ -7,6 +7,7 @@ import hmac
|
|
|
7
7
|
import json
|
|
8
8
|
import os
|
|
9
9
|
import time
|
|
10
|
+
import zlib
|
|
10
11
|
|
|
11
12
|
from . import crypto, framing
|
|
12
13
|
from .channel import Channel
|
|
@@ -16,6 +17,8 @@ MAX_BODY = framing.MAX_PAYLOAD - TAG_LEN
|
|
|
16
17
|
HELLO_CONTEXT = b"btsh-v1"
|
|
17
18
|
HELLO_MARK = b"B2"
|
|
18
19
|
SEAL_AAD = b"btsh-msg-v2"
|
|
20
|
+
COMPRESS_MIN = 96 # below this the wrapper costs more than it saves
|
|
21
|
+
COMPRESS_RATIO = 0.9 # only keep deflate when it wins by at least 10 %
|
|
19
22
|
|
|
20
23
|
|
|
21
24
|
class AuthError(Exception):
|
|
@@ -71,6 +74,11 @@ class Session:
|
|
|
71
74
|
"""True when messages to this peer are encrypted end to end per hop."""
|
|
72
75
|
return bool(self.identity is not None and len(self.peer_public) == 32)
|
|
73
76
|
|
|
77
|
+
@property
|
|
78
|
+
def peer_fingerprint(self) -> str:
|
|
79
|
+
"""Fingerprint of the peer public key, empty when the peer sent none."""
|
|
80
|
+
return crypto.fingerprint(self.peer_public)
|
|
81
|
+
|
|
74
82
|
def hello(self, name: str | None = None) -> None:
|
|
75
83
|
"""Client side handshake: nonce, optional public key, optional name."""
|
|
76
84
|
nonce = os.urandom(16)
|
|
@@ -88,6 +96,11 @@ class Session:
|
|
|
88
96
|
self.peer_public = payload[32:64]
|
|
89
97
|
if len(payload) < 32:
|
|
90
98
|
raise AuthError("malformed HELLO_ACK")
|
|
99
|
+
if self.identity is not None and len(self.peer_public) != 32:
|
|
100
|
+
raise AuthError(
|
|
101
|
+
"peer offered no public key: refusing to exchange plaintext "
|
|
102
|
+
"(use --crypto psk on both sides to accept a signed-only link)"
|
|
103
|
+
)
|
|
91
104
|
server_nonce, tag = payload[:16], payload[16:32]
|
|
92
105
|
expected = _digest(self.key, HELLO_CONTEXT + nonce + server_nonce) if self.key else b"\x00" * TAG_LEN
|
|
93
106
|
if not hmac.compare_digest(tag, expected):
|
|
@@ -109,6 +122,11 @@ class Session:
|
|
|
109
122
|
client_nonce = payload[:16]
|
|
110
123
|
client_public = b""
|
|
111
124
|
self.peer_name = payload[16:].decode("utf-8", "replace").strip()
|
|
125
|
+
if self.identity is not None and len(client_public) != 32:
|
|
126
|
+
raise AuthError(
|
|
127
|
+
"peer offered no public key: refusing to exchange plaintext "
|
|
128
|
+
"(use --crypto psk on both sides to accept a signed-only link)"
|
|
129
|
+
)
|
|
112
130
|
self.peer_public = client_public if len(client_public) == 32 else b""
|
|
113
131
|
nonce = os.urandom(16)
|
|
114
132
|
tag = _digest(self.key, HELLO_CONTEXT + client_nonce + nonce) if self.key else b"\x00" * TAG_LEN
|
|
@@ -119,6 +137,10 @@ class Session:
|
|
|
119
137
|
# -- messages --------------------------------------------------------
|
|
120
138
|
def _encode(self, obj: dict) -> bytes:
|
|
121
139
|
body = json.dumps(obj, separators=(",", ":")).encode()
|
|
140
|
+
if len(body) >= COMPRESS_MIN:
|
|
141
|
+
packed = zlib.compress(body, 9)
|
|
142
|
+
if len(packed) < len(body) * COMPRESS_RATIO:
|
|
143
|
+
body = json.dumps({"z": crypto.b64encode(packed)}, separators=(",", ":")).encode()
|
|
122
144
|
if self.sealed:
|
|
123
145
|
box = crypto.seal(self.peer_public, body, SEAL_AAD)
|
|
124
146
|
body = json.dumps({"s": crypto.b64encode(box)}, separators=(",", ":")).encode()
|
|
@@ -128,7 +150,9 @@ class Session:
|
|
|
128
150
|
body = self._encode(obj)
|
|
129
151
|
chunks = [body[i : i + MAX_BODY] for i in range(0, len(body), MAX_BODY)] or [b""]
|
|
130
152
|
for index, chunk in enumerate(chunks):
|
|
131
|
-
|
|
153
|
+
# Advance the shared counter: reusing one seq for every chunk of a message
|
|
154
|
+
# made the peer see duplicated frames and ACK the same number twice.
|
|
155
|
+
seq = self.channel.next_seq()
|
|
132
156
|
flags = 0
|
|
133
157
|
if index == 0:
|
|
134
158
|
flags |= framing.FLAG_START
|
|
@@ -168,8 +192,11 @@ class Session:
|
|
|
168
192
|
if not self._verify(frame.seq, chunk, frame.payload[:TAG_LEN]):
|
|
169
193
|
raise AuthError(f"bad frame tag (seq {frame.seq})")
|
|
170
194
|
buffer.extend(chunk)
|
|
195
|
+
return self._decode_body(bytes(buffer))
|
|
196
|
+
|
|
197
|
+
def _decode_body(self, raw: bytes) -> dict:
|
|
171
198
|
try:
|
|
172
|
-
message = json.loads(
|
|
199
|
+
message = json.loads(raw)
|
|
173
200
|
except json.JSONDecodeError as exc:
|
|
174
201
|
raise ValueError(f"peer sent invalid json: {exc}") from exc
|
|
175
202
|
if not isinstance(message, dict):
|
|
@@ -181,7 +208,17 @@ class Session:
|
|
|
181
208
|
inner = crypto.open_sealed(self.identity, crypto.b64decode(message["s"]), SEAL_AAD)
|
|
182
209
|
except crypto.CryptoError as exc:
|
|
183
210
|
raise AuthError(f"cannot open sealed message: {exc}") from exc
|
|
184
|
-
|
|
211
|
+
try:
|
|
212
|
+
message = json.loads(inner)
|
|
213
|
+
except json.JSONDecodeError as exc:
|
|
214
|
+
raise ValueError(f"sealed payload is not json: {exc}") from exc
|
|
185
215
|
if not isinstance(message, dict):
|
|
186
216
|
raise ValueError("sealed payload is not an object")
|
|
217
|
+
if "z" in message:
|
|
218
|
+
try:
|
|
219
|
+
message = json.loads(zlib.decompress(crypto.b64decode(message["z"])))
|
|
220
|
+
except (zlib.error, ValueError) as exc:
|
|
221
|
+
raise ValueError(f"cannot inflate compressed message: {exc}") from exc
|
|
222
|
+
if not isinstance(message, dict):
|
|
223
|
+
raise ValueError("compressed payload is not an object")
|
|
187
224
|
return message
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""TCP transport: the same frames over a socket instead of a radio.
|
|
2
|
+
|
|
3
|
+
The Android app can serve the hub over IP (it listens on the port below), which
|
|
4
|
+
lets a client reach it through the tailnet with no Bluetooth adapter at all.
|
|
5
|
+
Wire format is identical to the BLE link: every burst is a 4 byte big endian
|
|
6
|
+
length followed by one wire frame.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import socket
|
|
12
|
+
import struct
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from .transport import Transport, TransportError
|
|
16
|
+
|
|
17
|
+
DEFAULT_PORT = 7878
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TcpTransport(Transport):
|
|
21
|
+
"""Client side of the hub's TCP listener."""
|
|
22
|
+
|
|
23
|
+
name = "tcp"
|
|
24
|
+
|
|
25
|
+
def __init__(self, host: str, port: int = DEFAULT_PORT, connect_timeout: float = 10.0) -> None:
|
|
26
|
+
self.host = host
|
|
27
|
+
self.port = port
|
|
28
|
+
self._buffer = bytearray()
|
|
29
|
+
try:
|
|
30
|
+
self._sock = socket.create_connection((host, port), timeout=connect_timeout)
|
|
31
|
+
except OSError as exc:
|
|
32
|
+
raise TransportError(f"TCP connect to {host}:{port} failed: {exc}") from exc
|
|
33
|
+
self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
34
|
+
|
|
35
|
+
def send_burst(self, pcm: bytes) -> None:
|
|
36
|
+
try:
|
|
37
|
+
self._sock.sendall(struct.pack(">I", len(pcm)) + pcm)
|
|
38
|
+
except OSError as exc:
|
|
39
|
+
raise TransportError(f"TCP write failed: {exc}") from exc
|
|
40
|
+
|
|
41
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
42
|
+
deadline = time.monotonic() + timeout
|
|
43
|
+
while time.monotonic() < deadline:
|
|
44
|
+
if len(self._buffer) >= 4:
|
|
45
|
+
(length,) = struct.unpack(">I", bytes(self._buffer[:4]))
|
|
46
|
+
if 0 < length <= 65535 and len(self._buffer) >= 4 + length:
|
|
47
|
+
frame = bytes(self._buffer[4 : 4 + length])
|
|
48
|
+
del self._buffer[: 4 + length]
|
|
49
|
+
return frame
|
|
50
|
+
if length > 65535:
|
|
51
|
+
self._buffer.clear()
|
|
52
|
+
raise TransportError("TCP peer sent a bogus frame length")
|
|
53
|
+
remaining = max(0.01, deadline - time.monotonic())
|
|
54
|
+
try:
|
|
55
|
+
self._sock.settimeout(remaining)
|
|
56
|
+
chunk = self._sock.recv(4096)
|
|
57
|
+
except socket.timeout:
|
|
58
|
+
return None
|
|
59
|
+
except OSError as exc:
|
|
60
|
+
raise TransportError(f"TCP read failed: {exc}") from exc
|
|
61
|
+
if not chunk:
|
|
62
|
+
raise TransportError("TCP peer closed the connection")
|
|
63
|
+
self._buffer.extend(chunk)
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
def describe(self) -> dict:
|
|
67
|
+
out = super().describe()
|
|
68
|
+
out.update({"host": self.host, "port": self.port})
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
def close(self) -> None:
|
|
72
|
+
try:
|
|
73
|
+
self._sock.close()
|
|
74
|
+
except OSError: # pragma: no cover - trivial
|
|
75
|
+
pass
|
|
@@ -1,3 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datap
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Shell over a Bluetooth speaker's audio codec: run commands without an SSH server
|
|
5
|
+
Author: Marc Partensky
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: bluetooth,a2dp,sbc,modem,shell,ssh
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Provides-Extra: portaudio
|
|
11
|
+
Requires-Dist: sounddevice>=0.4; extra == "portaudio"
|
|
12
|
+
Provides-Extra: ble
|
|
13
|
+
Requires-Dist: bleak>=0.21; extra == "ble"
|
|
14
|
+
Provides-Extra: all
|
|
15
|
+
Requires-Dist: sounddevice>=0.4; extra == "all"
|
|
16
|
+
Requires-Dist: bleak>=0.21; extra == "all"
|
|
17
|
+
|
|
1
18
|
# btsh
|
|
2
19
|
|
|
3
20
|
A shell that rides on a Bluetooth link, no SSH server anywhere.
|
|
@@ -15,8 +32,8 @@ whatever Bluetooth channel you can actually use, and turns it into `exec` and
|
|
|
15
32
|
|
|
16
33
|
## The honest part about Android
|
|
17
34
|
|
|
18
|
-
The intended topology ("an Android app that
|
|
19
|
-
and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
35
|
+
The intended topology ("an Android app that shows up as a Bluetooth device,
|
|
36
|
+
plays music and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
20
37
|
|
|
21
38
|
* `A2dpSinkService` is a system service and every entry point enforces
|
|
22
39
|
`BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
|
|
@@ -27,9 +44,10 @@ and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
|
27
44
|
`AudioRecord`/`AudioTrack` path for it.
|
|
28
45
|
* HFP is the same story: SCO audio belongs to the telephony stack.
|
|
29
46
|
|
|
30
|
-
So the Android app in `android/` is a **BLE GATT peripheral** that advertises
|
|
31
|
-
|
|
32
|
-
|
|
47
|
+
So the Android app in `android/` is a **BLE GATT peripheral** that advertises
|
|
48
|
+
under a name you pick from a list of 20 real earbud names in the app
|
|
49
|
+
("Redmi Buds 6 Pro" by default) with the 128-bit
|
|
50
|
+
service UUID in the scan response, and serves the exact same frames. That is the only radio channel an app may serve
|
|
33
51
|
on Android, and `bleak` drives it from all three desktop OSes. The acoustic
|
|
34
52
|
modem stays available where the OS does expose the stream (desktops), and it is
|
|
35
53
|
what makes "the speaker's codec carries your shell" literal.
|
|
@@ -37,8 +55,8 @@ what makes "the speaker's codec carries your shell" literal.
|
|
|
37
55
|
## Install
|
|
38
56
|
|
|
39
57
|
```bash
|
|
40
|
-
pip install
|
|
41
|
-
pip install
|
|
58
|
+
pip install datap # core, stdlib only
|
|
59
|
+
pip install "datap[all]" # + sounddevice (PortAudio) and bleak (BLE)
|
|
42
60
|
```
|
|
43
61
|
|
|
44
62
|
`ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
|
|
@@ -55,10 +73,17 @@ btsh demo
|
|
|
55
73
|
Two processes on one host, no socket and no SSH, still through SBC:
|
|
56
74
|
|
|
57
75
|
```bash
|
|
58
|
-
btsh serve --transport fifo --codec sbc
|
|
59
|
-
btsh exec --transport fifo --codec sbc --
|
|
76
|
+
btsh serve --transport fifo --codec sbc &
|
|
77
|
+
btsh exec --transport fifo --codec sbc -- "uname -a | head -1"
|
|
60
78
|
```
|
|
61
79
|
|
|
80
|
+
There is no key to hand over before the first run: the default link mode is
|
|
81
|
+
`--crypto sealed`, and each side generates an X25519 identity in
|
|
82
|
+
`~/.btsh/identity` on first use. `exec`/`shell` print the peer fingerprint they
|
|
83
|
+
sealed to, so two machines can be compared once and remembered by eye. A
|
|
84
|
+
pre-shared key (`--key FILE` with `--crypto psk`) is only for peers that cannot
|
|
85
|
+
do asymmetric crypto, such as the Android app today.
|
|
86
|
+
|
|
62
87
|
Real speaker, PipeWire (Linux):
|
|
63
88
|
|
|
64
89
|
```bash
|
|
@@ -80,9 +105,9 @@ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -s
|
|
|
80
105
|
Android server over BLE:
|
|
81
106
|
|
|
82
107
|
```bash
|
|
83
|
-
btsh scan --timeout 10 # the app advertises as "
|
|
84
|
-
btsh exec --transport ble --ble-name "
|
|
85
|
-
btsh shell --transport ble --ble-name "
|
|
108
|
+
btsh scan --timeout 10 # the app advertises as "Redmi Buds 6 Pro"
|
|
109
|
+
btsh exec --transport ble --ble-name "Redmi" -- "id"
|
|
110
|
+
btsh shell --transport ble --ble-name "Redmi"
|
|
86
111
|
```
|
|
87
112
|
|
|
88
113
|
## CLI
|
|
@@ -119,10 +144,14 @@ One frame, 12 bytes of overhead:
|
|
|
119
144
|
.. crc32 over version..payload
|
|
120
145
|
```
|
|
121
146
|
|
|
122
|
-
* Acoustic link: each frame is modulated as 4-FSK (
|
|
123
|
-
|
|
124
|
-
32 bit sync word. Measured:
|
|
125
|
-
200 and 328 kbit/s
|
|
147
|
+
* Acoustic link: each frame is modulated as 4-FSK (32 sample symbols,
|
|
148
|
+
1000/2500/4000/5500 Hz, 2 bits per symbol, 3000 bit/s raw), 24 ms of lead
|
|
149
|
+
silence, 12 symbol preamble, 32 bit sync word. Measured: 20/20 frames
|
|
150
|
+
recovered through ffmpeg SBC at 128, 200 and 328 kbit/s (0/20 at 64 kbit/s,
|
|
151
|
+
where the codec cuts the band), ~330 B/s of payload.
|
|
152
|
+
* Compression: any JSON body over 96 bytes is deflated when that wins by 10 %,
|
|
153
|
+
before sealing, so shell output travels 2 to 3.5 times shorter. Measurement
|
|
154
|
+
does not change the format: the receiver inflates after unsealing.
|
|
126
155
|
* Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
|
|
127
156
|
* Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
|
|
128
157
|
* Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
|
|
@@ -132,8 +161,9 @@ One frame, 12 bytes of overhead:
|
|
|
132
161
|
|
|
133
162
|
## Limits, stated plainly
|
|
134
163
|
|
|
135
|
-
* Payload throughput is ~
|
|
136
|
-
commands, not for `tar | gzip`
|
|
164
|
+
* Payload throughput is ~330 B/s on the acoustic link, ~0.6 s for a command
|
|
165
|
+
and its short output. It is a shell for small commands, not for `tar | gzip`
|
|
166
|
+
over the air, and SBC below 128 kbit/s cannot carry the modem at all.
|
|
137
167
|
* A2DP is one way: a full session needs HFP (the speaker's microphone) or two
|
|
138
168
|
paired devices. `pw` and `portaudio` record from the same node/device they
|
|
139
169
|
play into, so duplex means a headset, not a plain speaker.
|
|
@@ -158,7 +188,7 @@ btsh selftest --frames 12
|
|
|
158
188
|
android/app/src/main/java/com/marcpartensky/btsh/
|
|
159
189
|
├── Protocol.kt frame pack/unpack, same bytes as Python
|
|
160
190
|
├── ShellRunner.kt /system/bin/sh or su -c, output capped
|
|
161
|
-
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC,
|
|
191
|
+
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, BLE advertising
|
|
162
192
|
├── BtshService.kt foreground service, keeps advertising alive
|
|
163
193
|
└── MainActivity.kt key field, start/stop, log
|
|
164
194
|
```
|
|
@@ -174,7 +204,7 @@ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.
|
|
|
174
204
|
then start it, set the same key as the client, and connect from the desktop:
|
|
175
205
|
|
|
176
206
|
```bash
|
|
177
|
-
btsh exec --transport ble --ble-name "
|
|
207
|
+
btsh exec --transport ble --ble-name "Redmi" --key ~/.btsh.key -- "getprop ro.product.model"
|
|
178
208
|
```
|
|
179
209
|
|
|
180
210
|
## Nix
|
|
@@ -19,11 +19,13 @@ src/btsh/node.py
|
|
|
19
19
|
src/btsh/py.typed
|
|
20
20
|
src/btsh/server.py
|
|
21
21
|
src/btsh/session.py
|
|
22
|
+
src/btsh/tcp.py
|
|
22
23
|
src/btsh/transport.py
|
|
23
24
|
src/datap.egg-info/PKG-INFO
|
|
24
25
|
src/datap.egg-info/SOURCES.txt
|
|
25
26
|
src/datap.egg-info/dependency_links.txt
|
|
26
27
|
src/datap.egg-info/entry_points.txt
|
|
28
|
+
src/datap.egg-info/requires.txt
|
|
27
29
|
src/datap.egg-info/top_level.txt
|
|
28
30
|
tests/test_channels.py
|
|
29
31
|
tests/test_crypto.py
|
|
@@ -81,6 +81,49 @@ class SealedWireTest(unittest.TestCase):
|
|
|
81
81
|
crypto.open_sealed(eve, crypto.b64decode(body["s"]), b"btsh-msg-v2")
|
|
82
82
|
|
|
83
83
|
|
|
84
|
+
class DowngradeTest(unittest.TestCase):
|
|
85
|
+
def test_sealed_peer_refuses_a_plaintext_peer(self):
|
|
86
|
+
from btsh import framing
|
|
87
|
+
from btsh.session import AuthError
|
|
88
|
+
|
|
89
|
+
server = Session(Channel(LoopbackTransport.pair()[1]), identity=crypto.Identity())
|
|
90
|
+
hello = framing.Frame(ftype=framing.FT_HELLO, seq=0, payload=b"B2" + b"\x11" * 16)
|
|
91
|
+
with self.assertRaises(AuthError) as caught:
|
|
92
|
+
server.answer_hello(hello)
|
|
93
|
+
self.assertIn("no public key", str(caught.exception))
|
|
94
|
+
|
|
95
|
+
def test_a_peer_without_identity_still_works(self):
|
|
96
|
+
from btsh import framing
|
|
97
|
+
|
|
98
|
+
server = Session(Channel(LoopbackTransport.pair()[1]))
|
|
99
|
+
# legacy hello: nonce + name, no public key at all
|
|
100
|
+
hello = framing.Frame(ftype=framing.FT_HELLO, seq=0, payload=b"\x11" * 16 + b"A")
|
|
101
|
+
server.answer_hello(hello)
|
|
102
|
+
self.assertEqual(server.peer_name, "A")
|
|
103
|
+
self.assertFalse(server.sealed)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class CompressionTest(unittest.TestCase):
|
|
107
|
+
def setUp(self):
|
|
108
|
+
sender, self.recipient_identity = crypto.Identity(), crypto.Identity()
|
|
109
|
+
self.session = Session(Channel(LoopbackTransport.pair()[0]), identity=sender)
|
|
110
|
+
self.session.peer_public = self.recipient_identity.public
|
|
111
|
+
self.recipient = Session(Channel(LoopbackTransport.pair()[0]), identity=self.recipient_identity)
|
|
112
|
+
|
|
113
|
+
def test_repetitive_output_shrinks_and_round_trips(self):
|
|
114
|
+
payload = {"op": "result", "stdout": "drwxr-xr-x 2 root root 4096 etc\n" * 40}
|
|
115
|
+
raw = self.session._encode(payload)
|
|
116
|
+
plain = len(json.dumps(payload, separators=(",", ":")).encode())
|
|
117
|
+
self.assertLess(len(raw), plain * 0.75)
|
|
118
|
+
self.assertEqual(self.recipient._decode_body(raw), payload)
|
|
119
|
+
|
|
120
|
+
def test_short_messages_stay_uncompressed(self):
|
|
121
|
+
payload = {"op": "exec", "cmd": "ls"}
|
|
122
|
+
raw = self.session._encode(payload)
|
|
123
|
+
inner = crypto.b64decode(json.loads(raw)["s"])
|
|
124
|
+
self.assertNotIn(b'"z"', crypto.open_sealed(self.recipient_identity, inner, b"btsh-msg-v2"))
|
|
125
|
+
|
|
126
|
+
|
|
84
127
|
class ChannelMeshTest(unittest.TestCase):
|
|
85
128
|
def setUp(self):
|
|
86
129
|
self.stop = False
|
|
@@ -40,11 +40,13 @@ class ModemTest(unittest.TestCase):
|
|
|
40
40
|
self.assertEqual(modem.demodulate(codec.apply_codec(pcm, "sbc", bitrate)), wire)
|
|
41
41
|
|
|
42
42
|
def test_throughput_is_documented(self):
|
|
43
|
-
# 6 header + payload + 4 crc bytes, 4 symbols per byte at
|
|
43
|
+
# 6 header + payload + 4 crc bytes, 4 symbols per byte at 32 samples each
|
|
44
44
|
wire = wire_for(100)
|
|
45
45
|
samples = len(modem.modulate(wire)) // 2
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
seconds = samples / modem.SAMPLE_RATE
|
|
47
|
+
payload_rate = 100 / seconds
|
|
48
|
+
self.assertGreater(payload_rate, 150) # well above the original 108 B/s
|
|
49
|
+
self.assertLess(seconds, 1.5) # a full frame now fits in about 0.8 s
|
|
48
50
|
|
|
49
51
|
|
|
50
52
|
if __name__ == "__main__":
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|