Debian Codegraph @

helpers/labgrid-bound-connect

raw symbols SCIP
1 #!/usr/bin/python3
2
3 # This is intended to be used via sudo. For example, add via visudo:
4 # %developers ALL = NOPASSWD: /usr/local/sbin/labgrid-bound-connect
5
6 import argparse
7 import os
8 import sys
9 import ipaddress
10 import subprocess
11
12
13 def main(ifname, address, port):
14 if not ifname:
15 raise ValueError("Empty interface name.")
16 if any((c == "/" or c.isspace()) for c in ifname):
17 raise ValueError(f"Interface name '{ifname}' contains invalid characters.")
18 if len(ifname) > 15:
19 raise ValueError(f"Interface name '{ifname}' is too long.")
20
21 address = ipaddress.ip_address(address)
22
23 if not 0 < port < 0xFFFF:
24 raise ValueError(f"Invalid port '{port}'.")
25
26 args = [
27 "socat",
28 "STDIO",
29 ]
30
31 if address.version == 4:
32 prefix = f"TCP4:{address}:{port}"
33 elif address.version == 6:
34 prefix = f"TCP6:[{address}]:{port}"
35 else:
36 raise RuntimeError(f"Invalid IP version '{address.version}'")
37
38 # Delete the IP lookup cache for the address in case it is stale
39 subprocess.run(["ip", "neigh", "del", str(address), "dev", ifname],
40 stdout=subprocess.DEVNULL,
41 stderr=subprocess.DEVNULL
42 )
43
44 args.append(','.join([
45 prefix,
46 f'so-bindtodevice={ifname}',
47 'connect-timeout=15',
48 'keepalive',
49 'keepcnt=3',
50 'keepidle=15',
51 'keepintvl=15',
52 'nodelay',
53 ]))
54
55 try:
56 os.execvp(args[0], args)
57 except FileNotFoundError as e:
58 raise RuntimeError("Missing socat binary") from e
59
60
61 if __name__ == "__main__":
62 parser = argparse.ArgumentParser()
63 parser.add_argument(
64 '-d',
65 '--debug',
66 action='store_true',
67 default=False,
68 help="enable debug mode"
69 )
70 parser.add_argument('interface', type=str, help='interface name')
71 parser.add_argument('address', type=str, help='destination IP address')
72 parser.add_argument('port', type=int, help='destination TCP port')
73 args = parser.parse_args()
74 try:
75 main(args.interface, args.address, args.port)
76 except Exception as e: # pylint: disable=broad-except
77 if args.debug:
78 import traceback
79 traceback.print_exc()
80 print(f"ERROR: {e}", file=sys.stderr)