flashstream-host-volumes-server 0.1.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.
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: flashstream-host-volumes-server
3
+ Version: 0.1.0
4
+ Summary: Cross-platform host service for Flashstream removable drive management
5
+ Requires-Python: >=3.11
@@ -0,0 +1,214 @@
1
+
2
+ # Flashstream Host
3
+
4
+ Cross-platform host service for Flashstream.
5
+
6
+ Manages removable storage devices through a TCP interface.
7
+
8
+ ## Features
9
+
10
+ - Linux and macOS support
11
+ - Native system service integration
12
+ - TCP server
13
+ - Removable volume management
14
+ - Optional token authentication
15
+ - Bounded concurrent connections
16
+ - Structured logging
17
+ - Graceful shutdown
18
+ - No third-party runtime dependencies
19
+
20
+ ## Requirements
21
+
22
+ ### Linux
23
+
24
+ - Python 3.11+
25
+ - systemd
26
+ - util-linux (findmnt, lsblk)
27
+ - udisks2 (udisksctl)
28
+
29
+ ### macOS
30
+
31
+ - Python 3.11+
32
+ - diskutil
33
+ - launchd
34
+
35
+ ## Installation
36
+
37
+ ### Linux
38
+
39
+ ```bash
40
+ chmod +x scripts/install-linux.sh
41
+ sudo ./scripts/install-linux.sh
42
+ ```
43
+
44
+ ### macOS
45
+
46
+ ```bash
47
+ chmod +x scripts/install-macos.sh
48
+ sudo ./scripts/install-macos.sh
49
+ ```
50
+
51
+ ## Configuration
52
+
53
+ Linux:
54
+
55
+ `/etc/flashstream-host/flashstream-host.env`
56
+
57
+ macOS:
58
+
59
+ `/Library/LaunchDaemons/com.flashstream.host.plist`
60
+
61
+ Available variables:
62
+
63
+ | Variable | Default |
64
+ |---|---|
65
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_HOST | 127.0.0.1 |
66
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_PORT | 8765 |
67
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_CONNECTION_TIMEOUT | 10 |
68
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_MAX_CONNECTIONS | 16 |
69
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_MAX_REQUEST_SIZE | 4096 |
70
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_LOG_LEVEL | INFO |
71
+ | FLASHSTREAM_HOST_VOLUMES_SERVER_TOKEN | Empty |
72
+
73
+ ## Protocol
74
+
75
+ ### Ping
76
+
77
+ Request:
78
+
79
+ ```text
80
+ PING
81
+ ```
82
+
83
+ Response:
84
+
85
+ ```text
86
+ PONG
87
+ ```
88
+
89
+ ### Status
90
+
91
+ Request:
92
+
93
+ ```text
94
+ STATUS
95
+ ```
96
+
97
+ Response:
98
+
99
+ ```text
100
+ OK: READY Linux
101
+ ```
102
+
103
+ ### Eject
104
+
105
+ Request:
106
+
107
+ ```text
108
+ EJECT /media/usb
109
+ ```
110
+
111
+ Response:
112
+
113
+ ```text
114
+ OK: EJECTED /media/usb
115
+ ```
116
+
117
+ ### Authentication
118
+
119
+ When FLASHSTREAM_HOST_VOLUMES_SERVER_TOKEN is configured, send:
120
+
121
+ ```text
122
+ AUTH your-secret-token
123
+ ```
124
+
125
+ The server responds:
126
+
127
+ ```text
128
+ OK: AUTHENTICATED
129
+ ```
130
+
131
+ Then send the command.
132
+
133
+ Each connection handles one command and is closed afterwards.
134
+
135
+ ## Linux management
136
+
137
+ ```bash
138
+ sudo systemctl start flashstream-host
139
+ sudo systemctl stop flashstream-host
140
+ sudo systemctl restart flashstream-host
141
+ sudo systemctl status flashstream-host
142
+ ```
143
+
144
+ Logs:
145
+
146
+ ```bash
147
+ journalctl -u flashstream-host -f
148
+ ```
149
+
150
+ ## macOS management
151
+
152
+ ```bash
153
+ sudo launchctl print system/com.flashstream.host
154
+ sudo launchctl kickstart -k system/com.flashstream.host
155
+ ```
156
+
157
+ ## Security
158
+
159
+ The server binds to localhost by default.
160
+
161
+ If using 0.0.0.0:
162
+
163
+ - Restrict access using a firewall.
164
+ - Configure FLASHSTREAM_HOST_VOLUMES_SERVER_TOKEN.
165
+ - Do not expose the service directly to the public internet.
166
+
167
+ The token is transmitted over plaintext TCP.
168
+ Use only trusted networks or a protected transport.
169
+
170
+ ## Uninstallation
171
+
172
+ Linux:
173
+
174
+ ```bash
175
+ sudo ./scripts/uninstall-linux.sh
176
+ ```
177
+
178
+ macOS:
179
+
180
+ ```bash
181
+ sudo ./scripts/uninstall-macos.sh
182
+ ```
183
+
184
+
185
+ ### Protocol
186
+
187
+
188
+ ```bash
189
+
190
+ flashstream-host-volumes-server
191
+
192
+ ```
193
+
194
+
195
+ ```bash
196
+ PING token=8362546384
197
+
198
+ STATUS token=8362546384
199
+
200
+ VOLUMES token=8362546384
201
+
202
+ EJECT token=8362546384 path="/Volumes/My USB Drive"
203
+
204
+
205
+ PING token=01234
206
+ STATUS token=01234
207
+ VOLUMES token=01234
208
+ EJECT token=01234 path=/Volumes/TRANS2GB
209
+
210
+ ```
211
+
212
+
213
+
214
+
@@ -0,0 +1,24 @@
1
+
2
+ [build-system]
3
+ requires = ["setuptools>=75"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ name = "flashstream-host-volumes-server"
8
+ version = "0.1.0"
9
+ description = "Cross-platform host service for Flashstream removable drive management"
10
+ requires-python = ">=3.11"
11
+ dependencies = []
12
+
13
+ [project.scripts]
14
+ flashstream-host-volumes-server = "flashstream_host_volumes_server.__main__:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ where = ["src"]
18
+
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "build>=1.2",
23
+ "twine>=6.0",
24
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,96 @@
1
+ import logging
2
+ import signal
3
+ import sys
4
+ import threading
5
+
6
+ from flashstream_host_volumes_server.config import validate_config, Config
7
+ from flashstream_host_volumes_server.server import EjectTCPServer
8
+
9
+
10
+ logger = logging.getLogger('flashstream_host_volumes_server')
11
+
12
+
13
+ def configure_logging(level: str) -> None:
14
+ logging.basicConfig(
15
+ level=getattr(logging, level),
16
+ format='%(asctime)s %(levelname)s %(name)s: %(message)s',
17
+ datefmt='%b %d %H:%M:%S',
18
+ stream=sys.stdout,
19
+ force=True,
20
+ )
21
+
22
+
23
+ def main() -> None:
24
+ try:
25
+ config = Config.from_env()
26
+ validate_config(config)
27
+
28
+ except (ValueError, OSError) as exc:
29
+ print(f'Configuration error: {exc}', file=sys.stderr)
30
+ raise SystemExit(1)
31
+
32
+ configure_logging(config.log_level)
33
+
34
+ stop_event = threading.Event()
35
+ server = None
36
+ server_thread = None
37
+
38
+ def handle_signal(signum, frame):
39
+ logger.info(
40
+ '🛑 Received signal: %s',
41
+ signal.Signals(signum).name,
42
+ )
43
+ stop_event.set()
44
+
45
+ signal.signal(signal.SIGTERM, handle_signal)
46
+ signal.signal(signal.SIGINT, handle_signal)
47
+ signal.signal(signal.SIGTSTP, handle_signal)
48
+
49
+ try:
50
+ server = EjectTCPServer(
51
+ (config.host, config.port),
52
+ config,
53
+ )
54
+
55
+ logger.info('🚀 Flashstream Host started')
56
+ logger.info('🖥️ Platform: %s', server.platform)
57
+ logger.info('🌐 Listening on %s:%s', config.host, config.port)
58
+ logger.info('⏱️ Connection timeout: %ss', config.connection_timeout)
59
+ logger.info('🔌 Maximum connections: %s', config.max_connections)
60
+ logger.info(
61
+ '🔐 Authentication: %s',
62
+ 'enabled' if config.token else 'disabled',
63
+ )
64
+
65
+ server_thread = threading.Thread(
66
+ target=server.serve_forever,
67
+ kwargs={'poll_interval': 0.5},
68
+ name='flashstream-host-volumes-server',
69
+ daemon=False,
70
+ )
71
+
72
+ server_thread.start()
73
+
74
+ logger.info('✅ Server is ready')
75
+
76
+ stop_event.wait()
77
+
78
+ except OSError:
79
+ logger.exception('❌ Cannot start Flashstream Host')
80
+ raise SystemExit(1)
81
+
82
+ finally:
83
+ if server is not None:
84
+ logger.info('🛑 Shutting down server')
85
+
86
+ server.shutdown()
87
+ server.server_close()
88
+
89
+ if server_thread is not None:
90
+ server_thread.join()
91
+
92
+ logger.info('👋 Flashstream Host stopped')
93
+
94
+
95
+ if __name__ == '__main__':
96
+ main()
@@ -0,0 +1,68 @@
1
+
2
+ import os
3
+
4
+ from dataclasses import dataclass
5
+
6
+ PROJECT_ENVS_NAME = 'FLASHSTREAM_HOST_VOLUMES_SERVER'
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class Config:
10
+ host: str = '127.0.0.1'
11
+ port: int = 8765
12
+ connection_timeout: float = 10.0
13
+ command_timeout: float = 30.0
14
+ max_connections: int = 16
15
+ max_request_size: int = 4096
16
+ log_level: str = 'INFO'
17
+ token: str = ''
18
+
19
+ @classmethod
20
+ def from_env(cls) -> 'Config':
21
+ """Load configuration from environment variables."""
22
+
23
+ return cls(
24
+ host=os.getenv(f'{PROJECT_ENVS_NAME}_HOST', '127.0.0.1'),
25
+ port=int(os.getenv(f'{PROJECT_ENVS_NAME}_PORT', '8765')),
26
+ connection_timeout=float(
27
+ os.getenv(f'{PROJECT_ENVS_NAME}_CONNECTION_TIMEOUT', '10')
28
+ ),
29
+ command_timeout=float(
30
+ os.getenv(f'{PROJECT_ENVS_NAME}_COMMAND_TIMEOUT', '30')
31
+ ),
32
+ max_connections=int(
33
+ os.getenv(f'{PROJECT_ENVS_NAME}_MAX_CONNECTIONS', '16')
34
+ ),
35
+ max_request_size=int(
36
+ os.getenv(f'{PROJECT_ENVS_NAME}_MAX_REQUEST_SIZE', '4096')
37
+ ),
38
+ log_level=os.getenv(f'{PROJECT_ENVS_NAME}_LOG_LEVEL', 'INFO').upper(),
39
+ token=os.getenv(f'{PROJECT_ENVS_NAME}_TOKEN', ''),
40
+ )
41
+
42
+
43
+ def validate_config(config: Config) -> None:
44
+ """Validate application configuration."""
45
+
46
+ if not config.host:
47
+ raise ValueError(f'{PROJECT_ENVS_NAME}_HOST cannot be empty')
48
+
49
+ if not 1 <= config.port <= 65535:
50
+ raise ValueError(f'{PROJECT_ENVS_NAME}_PORT must be between 1 and 65535')
51
+
52
+ if config.connection_timeout <= 0:
53
+ raise ValueError(f'{PROJECT_ENVS_NAME}_CONNECTION_TIMEOUT must be positive')
54
+
55
+ if config.command_timeout <= 0:
56
+ raise ValueError(f'{PROJECT_ENVS_NAME}_COMMAND_TIMEOUT must be positive')
57
+
58
+ if config.max_connections < 1:
59
+ raise ValueError(f'{PROJECT_ENVS_NAME}_MAX_CONNECTIONS must be positive')
60
+
61
+ if not 64 <= config.max_request_size <= 65536:
62
+ raise ValueError(f'{PROJECT_ENVS_NAME}_MAX_REQUEST_SIZE must be between 64 and 65536')
63
+
64
+ if config.log_level not in {'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'}:
65
+ raise ValueError(f'Invalid {PROJECT_ENVS_NAME}_LOG_LEVEL')
66
+
67
+ if '\n' in config.token or '\r' in config.token:
68
+ raise ValueError(f'{PROJECT_ENVS_NAME}_TOKEN cannot contain newline characters')
@@ -0,0 +1,429 @@
1
+
2
+ import json
3
+ import logging
4
+ import platform
5
+ import plistlib
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+
10
+ from pathlib import Path
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class EjectError(Exception):
17
+ """Raised when a volume cannot be ejected."""
18
+
19
+
20
+ def run_command(
21
+ *args: str,
22
+ timeout: float = 30.0,
23
+ ) -> subprocess.CompletedProcess[str]:
24
+ """Execute a system command without invoking a shell."""
25
+ try:
26
+ return subprocess.run(
27
+ args,
28
+ capture_output=True,
29
+ text=True,
30
+ timeout=timeout,
31
+ check=False,
32
+ )
33
+
34
+ except subprocess.TimeoutExpired as exc:
35
+ raise EjectError(
36
+ f'Command timed out: {args[0]}'
37
+ ) from exc
38
+
39
+ except OSError as exc:
40
+ raise EjectError(
41
+ f'Cannot execute {args[0]}: {exc}'
42
+ ) from exc
43
+
44
+
45
+ def _check_result(
46
+ result: subprocess.CompletedProcess[str],
47
+ error: str,
48
+ ) -> None:
49
+ """Raise an error when a command fails."""
50
+ if result.returncode != 0:
51
+ raise EjectError(
52
+ result.stderr.strip() or error
53
+ )
54
+
55
+
56
+ def _mac_disk_info(
57
+ path: Path,
58
+ timeout: float,
59
+ ) -> dict:
60
+ """Get macOS disk information."""
61
+ result = run_command(
62
+ 'diskutil',
63
+ 'info',
64
+ '-plist',
65
+ str(path),
66
+ timeout=timeout,
67
+ )
68
+
69
+ _check_result(result, 'Cannot inspect volume')
70
+
71
+ try:
72
+ return plistlib.loads(result.stdout.encode())
73
+
74
+ except (ValueError, plistlib.InvalidFileException) as exc:
75
+ raise EjectError(
76
+ 'Invalid diskutil response'
77
+ ) from exc
78
+
79
+
80
+ def is_mountpoint(
81
+ path: Path,
82
+ timeout: float = 30.0,
83
+ ) -> bool:
84
+ """Check whether path is an actual mountpoint."""
85
+ system = platform.system()
86
+
87
+ if system == 'Darwin':
88
+ info = _mac_disk_info(path, timeout)
89
+ mountpoint = info.get('MountPoint')
90
+
91
+ return bool(mountpoint) and Path(mountpoint) == path
92
+
93
+ if system == 'Linux':
94
+ result = run_command(
95
+ 'findmnt',
96
+ '--json',
97
+ '--mountpoint',
98
+ str(path),
99
+ '--output',
100
+ 'TARGET',
101
+ timeout=timeout,
102
+ )
103
+
104
+ if result.returncode == 1:
105
+ return False
106
+
107
+ _check_result(result, 'Cannot inspect mountpoint')
108
+
109
+ try:
110
+ filesystems = json.loads(result.stdout).get(
111
+ 'filesystems',
112
+ [],
113
+ )
114
+
115
+ return any(
116
+ item.get('target') == str(path)
117
+ for item in filesystems
118
+ )
119
+
120
+ except (json.JSONDecodeError, TypeError, AttributeError) as exc:
121
+ raise EjectError(
122
+ 'Invalid findmnt response'
123
+ ) from exc
124
+
125
+ raise EjectError(f'Unsupported platform: {system}')
126
+
127
+
128
+ def get_linux_device(
129
+ path: Path,
130
+ timeout: float = 30.0,
131
+ ) -> str:
132
+ """Resolve a mountpoint to its block device."""
133
+ result = run_command(
134
+ 'findmnt',
135
+ '--json',
136
+ '--mountpoint',
137
+ str(path),
138
+ '--output',
139
+ 'TARGET,SOURCE',
140
+ timeout=timeout,
141
+ )
142
+
143
+ _check_result(result, 'Cannot determine mounted device')
144
+
145
+ try:
146
+ filesystems = json.loads(result.stdout)['filesystems']
147
+ filesystem = filesystems[0]
148
+
149
+ if filesystem['target'] != str(path):
150
+ raise EjectError('Mountpoint mismatch')
151
+
152
+ device = filesystem['source']
153
+
154
+ except (json.JSONDecodeError, KeyError, IndexError, TypeError) as exc:
155
+ raise EjectError(
156
+ 'Invalid findmnt response'
157
+ ) from exc
158
+
159
+ if not isinstance(device, str) or not device.startswith('/dev/'):
160
+ raise EjectError(
161
+ f'Unsupported block device source: {device}'
162
+ )
163
+
164
+ return device
165
+
166
+
167
+ def get_linux_whole_device(
168
+ device: str,
169
+ timeout: float = 30.0,
170
+ ) -> str:
171
+ """Resolve a partition to its parent physical device."""
172
+ if not shutil.which('lsblk'):
173
+ logger.warning('lsblk is unavailable; using partition device')
174
+ return device
175
+
176
+ result = run_command(
177
+ 'lsblk',
178
+ '-ndo',
179
+ 'PKNAME',
180
+ device,
181
+ timeout=timeout,
182
+ )
183
+
184
+ if result.returncode != 0:
185
+ logger.warning(
186
+ 'Cannot determine parent device: %s',
187
+ result.stderr.strip(),
188
+ )
189
+ return device
190
+
191
+ parent = result.stdout.strip()
192
+
193
+ return f'/dev/{parent}' if parent else device
194
+
195
+
196
+ def eject_linux(
197
+ path: Path,
198
+ timeout: float = 30.0,
199
+ ) -> str:
200
+ """Unmount and power off a Linux block device."""
201
+ device = get_linux_device(path, timeout)
202
+ whole_device = get_linux_whole_device(device, timeout)
203
+
204
+ logger.info('Linux device: %s', device)
205
+ logger.info('Physical device: %s', whole_device)
206
+
207
+ result = run_command(
208
+ 'udisksctl',
209
+ 'unmount',
210
+ '--block-device',
211
+ device,
212
+ timeout=timeout,
213
+ )
214
+
215
+ _check_result(result, 'Unmount failed')
216
+
217
+ logger.info('Volume unmounted: %s', path)
218
+
219
+ result = run_command(
220
+ 'udisksctl',
221
+ 'power-off',
222
+ '--block-device',
223
+ whole_device,
224
+ timeout=timeout,
225
+ )
226
+
227
+ if result.returncode == 0:
228
+ logger.info('Physical device powered off: %s', whole_device)
229
+ return f'UNMOUNTED'
230
+
231
+ logger.warning(
232
+ 'Unmounted, but power-off failed: %s',
233
+ result.stderr.strip(),
234
+ )
235
+
236
+ return f'FORCE UNMOUNTED'
237
+
238
+
239
+ def eject_macos(
240
+ path: Path,
241
+ timeout: float = 30.0,
242
+ ) -> str:
243
+ """Eject a macOS removable disk."""
244
+ info = _mac_disk_info(path, timeout)
245
+
246
+ mountpoint = info.get('MountPoint')
247
+
248
+ if not mountpoint or Path(mountpoint) != path:
249
+ raise EjectError('Mountpoint mismatch')
250
+
251
+ device_id = (
252
+ info.get('ParentWholeDisk')
253
+ or info.get('DeviceIdentifier')
254
+ )
255
+
256
+ if not isinstance(device_id, str) or not re.fullmatch(
257
+ r'disk\d+(?:s\d+)?',
258
+ device_id,
259
+ ):
260
+ raise EjectError('Invalid disk identifier')
261
+
262
+ device = f'/dev/{device_id}'
263
+
264
+ result = run_command(
265
+ 'diskutil',
266
+ 'eject',
267
+ device,
268
+ timeout=timeout,
269
+ )
270
+
271
+ if result.returncode == 0:
272
+ return f'UNMOUNTED'
273
+
274
+ logger.warning(
275
+ 'Eject failed, trying forced unmount: %s',
276
+ result.stderr.strip(),
277
+ )
278
+
279
+ result = run_command(
280
+ 'diskutil',
281
+ 'unmount',
282
+ 'force',
283
+ str(path),
284
+ timeout=timeout,
285
+ )
286
+
287
+ if result.returncode == 0:
288
+ logger.warning('Volume force-unmounted: %s', path)
289
+ return f'FORCE UNMOUNTED'
290
+
291
+ raise EjectError(
292
+ result.stderr.strip() or 'Disk eject failed'
293
+ )
294
+
295
+
296
+ def eject_volume(
297
+ path: str,
298
+ timeout: float = 30.0,
299
+ ) -> str:
300
+ """Validate and eject a mounted volume."""
301
+ try:
302
+ mountpoint = Path(path)
303
+
304
+ if not mountpoint.is_absolute():
305
+ raise EjectError(
306
+ 'Mountpoint must be an absolute path'
307
+ )
308
+
309
+ if not mountpoint.exists() or not mountpoint.is_dir():
310
+ raise EjectError('Mountpoint not found')
311
+
312
+ mountpoint = mountpoint.resolve(strict=True)
313
+
314
+ if mountpoint == Path('/'):
315
+ raise EjectError(
316
+ 'Root filesystem cannot be ejected'
317
+ )
318
+
319
+ if not is_mountpoint(mountpoint, timeout):
320
+ raise EjectError('Path is not a mountpoint')
321
+
322
+ logger.info('Ejecting: %s', mountpoint)
323
+
324
+ system = platform.system()
325
+
326
+ if system == 'Darwin':
327
+ return eject_macos(mountpoint, timeout)
328
+
329
+ if system == 'Linux':
330
+ return eject_linux(mountpoint, timeout)
331
+
332
+ raise EjectError(
333
+ f'Unsupported platform: {system}'
334
+ )
335
+
336
+ except EjectError:
337
+ raise
338
+
339
+ except (OSError, ValueError) as exc:
340
+ raise EjectError(str(exc)) from exc
341
+
342
+
343
+ def list_volumes(
344
+ timeout: float = 10.0,
345
+ ) -> list[dict[str, str]]:
346
+ """Return mounted volumes on macOS or Linux."""
347
+ system = platform.system()
348
+
349
+ if system == 'Darwin':
350
+ return _list_macos_volumes(timeout)
351
+
352
+ if system == 'Linux':
353
+ return _list_linux_volumes(timeout)
354
+
355
+ raise EjectError(f'Unsupported platform: {system}')
356
+
357
+
358
+ def _list_macos_volumes(
359
+ timeout: float,
360
+ ) -> list[dict[str, str]]:
361
+ """List mounted macOS volumes."""
362
+ result = run_command(
363
+ 'mount',
364
+ timeout=timeout,
365
+ )
366
+
367
+ _check_result(result, 'Cannot list mounted volumes')
368
+
369
+ volumes = []
370
+
371
+ for line in result.stdout.splitlines():
372
+ device, separator, mount_info = line.partition(' on ')
373
+
374
+ if not separator or not device.startswith('/dev/'):
375
+ continue
376
+
377
+ mount_point, separator, filesystem_info = mount_info.rpartition(' (')
378
+
379
+ if not separator:
380
+ continue
381
+
382
+ filesystem = filesystem_info.split(',', 1)[0].rstrip(')')
383
+
384
+ volumes.append({
385
+ 'path': mount_point,
386
+ 'device': device,
387
+ 'filesystem': filesystem,
388
+ })
389
+
390
+ return volumes
391
+
392
+
393
+ def _list_linux_volumes(
394
+ timeout: float,
395
+ ) -> list[dict[str, str]]:
396
+ """List mounted block-device volumes using findmnt."""
397
+ result = run_command(
398
+ 'findmnt',
399
+ '--json',
400
+ '--list',
401
+ '--types',
402
+ 'ext2,ext3,ext4,xfs,btrfs,vfat,exfat,ntfs,ntfs3,fuseblk',
403
+ '--output',
404
+ 'TARGET,SOURCE,FSTYPE',
405
+ timeout=timeout,
406
+ )
407
+
408
+ _check_result(result, 'Cannot list mounted volumes')
409
+
410
+ try:
411
+ filesystems = json.loads(result.stdout).get(
412
+ 'filesystems',
413
+ [],
414
+ )
415
+
416
+ except (json.JSONDecodeError, TypeError, AttributeError) as exc:
417
+ raise EjectError(
418
+ 'Invalid findmnt response'
419
+ ) from exc
420
+
421
+ return [
422
+ {
423
+ 'path': item.get('target', ''),
424
+ 'device': item.get('source', ''),
425
+ 'filesystem': item.get('fstype', ''),
426
+ }
427
+ for item in filesystems
428
+ if item.get('target') and item.get('source')
429
+ ]
@@ -0,0 +1,82 @@
1
+
2
+ import re
3
+ import shlex
4
+
5
+
6
+ _KEY_RE = re.compile(r"^[a-z][a-z0-9_]*$")
7
+ _COMMAND_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")
8
+
9
+
10
+ class ProtocolError(ValueError):
11
+ """Invalid wire-protocol request."""
12
+
13
+
14
+ def parse_request(line: str) -> tuple[str, dict[str, str]]:
15
+ """Parse COMMAND key=value [key=value ...]. Values may be quoted."""
16
+ if not line or any(ord(char) < 32 and char != "\t" for char in line):
17
+ raise ProtocolError("invalid_request")
18
+
19
+ try:
20
+ parts = shlex.split(line, posix=True)
21
+ except ValueError as exc:
22
+ raise ProtocolError("invalid_quoting") from exc
23
+
24
+ if not parts or not _COMMAND_RE.fullmatch(parts[0]):
25
+ raise ProtocolError("invalid_command")
26
+
27
+ command = parts[0]
28
+ params: dict[str, str] = {}
29
+
30
+ for item in parts[1:]:
31
+ key, separator, value = item.partition("=")
32
+
33
+ if not separator or not _KEY_RE.fullmatch(key):
34
+ raise ProtocolError("invalid_parameter")
35
+
36
+ if key in params:
37
+ raise ProtocolError("duplicate_parameter")
38
+
39
+ if any(ord(char) < 32 for char in value):
40
+ raise ProtocolError("invalid_parameter")
41
+
42
+ params[key] = value
43
+
44
+ if "token" not in params:
45
+ raise ProtocolError("missing_token")
46
+
47
+ return command, params
48
+
49
+
50
+ def _format_fields(parts: list[str], fields: dict[str, object]) -> str:
51
+ """Append validated key-value fields to a protocol message."""
52
+
53
+ for key, value in fields.items():
54
+ if not _KEY_RE.fullmatch(key):
55
+ raise ValueError(f'Invalid field name: {key}')
56
+
57
+ value = str(value)
58
+
59
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
60
+ raise ValueError(f'Control character in field: {key}')
61
+
62
+ parts.append(f'{key}={shlex.quote(value)}')
63
+
64
+ return ' '.join(parts)
65
+
66
+
67
+ def format_message(prefix: str, **fields: object) -> str:
68
+ """Format a protocol command or message."""
69
+
70
+ if not _COMMAND_RE.fullmatch(prefix):
71
+ raise ValueError('Invalid message prefix')
72
+
73
+ return _format_fields([prefix], fields)
74
+
75
+
76
+ def format_response(status: str, **params: object) -> str:
77
+ """Format a response using status as the first field."""
78
+
79
+ if status not in {'ok', 'error', 'volume', 'end'}:
80
+ raise ValueError('Invalid response status')
81
+
82
+ return _format_fields([f'status={status}'], params)
@@ -0,0 +1,262 @@
1
+
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import hmac
6
+ import json
7
+ import logging
8
+ import platform
9
+ import socket
10
+ import socketserver
11
+ import threading
12
+
13
+ from flashstream_host_volumes_server.config import Config
14
+ from flashstream_host_volumes_server.eject import EjectError, eject_volume, list_volumes
15
+ from flashstream_host_volumes_server.protocol import ProtocolError, parse_request, format_response
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class EjectRequestHandler(socketserver.StreamRequestHandler):
21
+ server: EjectTCPServer
22
+
23
+ def setup(self) -> None:
24
+ super().setup()
25
+ self.connection.settimeout(
26
+ self.server.config.connection_timeout
27
+ )
28
+
29
+ def reply(self, message: str) -> None:
30
+ self.wfile.write(f'{message}\n'.encode('utf-8'))
31
+ self.wfile.flush()
32
+
33
+ def try_reply(self, message: str) -> None:
34
+ try:
35
+ self.reply(message)
36
+ except OSError:
37
+ logger.debug('Client disconnected: %s', self.client_address[0])
38
+
39
+ def read_line(self) -> str | None:
40
+ max_size = self.server.config.max_request_size
41
+ raw = self.rfile.readline(max_size + 1)
42
+
43
+ if not raw:
44
+ return None
45
+
46
+ if len(raw) > max_size:
47
+ self.reply(format_response('error', message='request_too_large'))
48
+ return None
49
+
50
+ if not raw.endswith(b'\n'):
51
+ self.reply(format_response('error', message='incomplete_request'))
52
+ return None
53
+
54
+ try:
55
+ line = raw.decode('utf-8').rstrip('\r\n')
56
+ except UnicodeDecodeError:
57
+ self.reply(format_response('error', message='invalid_encoding'))
58
+ return None
59
+
60
+ if not line:
61
+ self.reply(format_response('error', message='invalid_request'))
62
+ return None
63
+
64
+ return line
65
+
66
+ def handle(self) -> None:
67
+ peer = self.client_address[0]
68
+ logger.info('Connection from %s', peer)
69
+
70
+ try:
71
+ line = self.read_line()
72
+
73
+ if line is None:
74
+ return
75
+
76
+ command, params = parse_request(line)
77
+
78
+ supplied_token_hashed = params.pop('token', None)
79
+ expected_token_hashed = hashlib.sha256(self.server.config.token.encode('utf-8')).hexdigest()
80
+
81
+ if (
82
+ supplied_token_hashed is None
83
+ or not hmac.compare_digest(
84
+ supplied_token_hashed.encode('utf-8'),
85
+ expected_token_hashed.encode('utf-8'),
86
+ )
87
+ ):
88
+ self.reply(format_response('error', action=command, message='unauthorized'))
89
+ return
90
+
91
+ handlers = {
92
+ 'PING': self._handle_ping,
93
+ 'STATUS': self._handle_status,
94
+ 'VOLUMES': self._handle_volumes,
95
+ 'EJECT': self._handle_eject,
96
+ }
97
+
98
+ handler = handlers.get(command)
99
+
100
+ if handler is None:
101
+ self.reply(format_response('error', action=command, message='unknown_command'))
102
+ return
103
+
104
+ logger.info('Request from %s: %s', peer, command)
105
+ handler(params)
106
+
107
+ except ProtocolError as exc:
108
+ self.try_reply(format_response('error', action=command, message=str(exc)))
109
+
110
+ except EjectError as exc:
111
+ logger.warning(
112
+ 'Storage operation failed from %s: %s',
113
+ peer,
114
+ exc,
115
+ )
116
+ self.try_reply(format_response('error', action=command, message=str(exc)))
117
+
118
+ except TimeoutError:
119
+ logger.warning('Connection timed out: %s', peer)
120
+
121
+ except OSError:
122
+ logger.debug(
123
+ 'Connection error: %s',
124
+ peer,
125
+ exc_info=True,
126
+ )
127
+
128
+ except Exception:
129
+ logger.exception('Unexpected handler error from %s', peer)
130
+ self.try_reply(format_response('error', action=command, message='internal_error'))
131
+
132
+ @staticmethod
133
+ def require_params(
134
+ params: dict[str, str],
135
+ allowed: set[str],
136
+ required: set[str] | None = None,
137
+ ) -> None:
138
+ if params.keys() - allowed:
139
+ raise ProtocolError('unknown_parameter')
140
+
141
+ if required and required - params.keys():
142
+ raise ProtocolError('missing_parameter')
143
+
144
+ def _handle_ping(self, params: dict[str, str]) -> None:
145
+ self.require_params(params, set())
146
+ self.reply(
147
+ format_response(
148
+ 'ok',
149
+ action='PING',
150
+ message='PONG'
151
+ ))
152
+
153
+ def _handle_status(self, params: dict[str, str]) -> None:
154
+ self.require_params(params, set())
155
+
156
+ self.reply(
157
+ format_response(
158
+ 'ok',
159
+ action='STATUS',
160
+ platform=self.server.platform,
161
+ )
162
+ )
163
+
164
+ def _handle_volumes(self, params: dict[str, str]) -> None:
165
+ self.require_params(params, set())
166
+
167
+ volumes = list_volumes(
168
+ self.server.config.command_timeout
169
+ )
170
+
171
+ self.reply(
172
+ format_response(
173
+ 'ok',
174
+ action='VOLUMES',
175
+ volumes=json.dumps(
176
+ volumes,
177
+ ensure_ascii=False,
178
+ separators=(',', ':'),
179
+ ),
180
+ )
181
+ )
182
+
183
+ def _handle_eject(self, params: dict[str, str]) -> None:
184
+ self.require_params(params, {'path'})
185
+
186
+ path = params['path']
187
+
188
+ message = eject_volume(
189
+ path,
190
+ self.server.config.command_timeout,
191
+ )
192
+
193
+ self.reply(
194
+ format_response(
195
+ 'ok',
196
+ action='EJECT',
197
+ path=path,
198
+ message=message
199
+ )
200
+ )
201
+
202
+ class EjectTCPServer(socketserver.ThreadingTCPServer):
203
+ allow_reuse_address = True
204
+ daemon_threads = False
205
+ block_on_close = True
206
+
207
+ def __init__(
208
+ self,
209
+ address: tuple[str, int],
210
+ config: Config,
211
+ ) -> None:
212
+ self.config = config
213
+ self.platform = platform.system()
214
+
215
+ if self.platform not in {'Darwin', 'Linux'}:
216
+ raise RuntimeError(
217
+ f'Unsupported platform: {self.platform}'
218
+ )
219
+
220
+ self._slots = threading.BoundedSemaphore(
221
+ config.max_connections
222
+ )
223
+
224
+ super().__init__(address, EjectRequestHandler)
225
+
226
+ def process_request(
227
+ self,
228
+ request: socket.socket,
229
+ client_address: tuple[str, int],
230
+ ) -> None:
231
+ if not self._slots.acquire(blocking=False):
232
+ logger.warning(
233
+ 'Connection limit reached: %s',
234
+ client_address[0],
235
+ )
236
+
237
+ try:
238
+ request.sendall(b'ERROR message=server_busy\n')
239
+ except OSError:
240
+ pass
241
+
242
+ self.shutdown_request(request)
243
+ return
244
+
245
+ try:
246
+ super().process_request(request, client_address)
247
+ except Exception:
248
+ self._slots.release()
249
+ raise
250
+
251
+ def process_request_thread(
252
+ self,
253
+ request: socket.socket,
254
+ client_address: tuple[str, int],
255
+ ) -> None:
256
+ try:
257
+ super().process_request_thread(
258
+ request,
259
+ client_address,
260
+ )
261
+ finally:
262
+ self._slots.release()
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: flashstream-host-volumes-server
3
+ Version: 0.1.0
4
+ Summary: Cross-platform host service for Flashstream removable drive management
5
+ Requires-Python: >=3.11
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/flashstream_host_volumes_server/__init__.py
4
+ src/flashstream_host_volumes_server/__main__.py
5
+ src/flashstream_host_volumes_server/config.py
6
+ src/flashstream_host_volumes_server/eject.py
7
+ src/flashstream_host_volumes_server/protocol.py
8
+ src/flashstream_host_volumes_server/server.py
9
+ src/flashstream_host_volumes_server.egg-info/PKG-INFO
10
+ src/flashstream_host_volumes_server.egg-info/SOURCES.txt
11
+ src/flashstream_host_volumes_server.egg-info/dependency_links.txt
12
+ src/flashstream_host_volumes_server.egg-info/entry_points.txt
13
+ src/flashstream_host_volumes_server.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ flashstream-host-volumes-server = flashstream_host_volumes_server.__main__:main