Always kill child processes gracefully
[re6stnet.git] / re6st / plib.py
1 import logging, errno, os
2 from . import utils
3
4 here = os.path.realpath(os.path.dirname(__file__))
5 ovpn_server = os.path.join(here, 'ovpn-server')
6 ovpn_client = os.path.join(here, 'ovpn-client')
7 ovpn_log = None
8
9 def openvpn(iface, encrypt, *args, **kw):
10 args = ['openvpn',
11 '--dev-type', 'tap',
12 '--dev', iface,
13 '--persist-tun',
14 '--persist-key',
15 '--script-security', '2',
16 '--up', ovpn_client,
17 #'--user', 'nobody', '--group', 'nogroup',
18 ] + list(args)
19 if ovpn_log:
20 args += '--log-append', os.path.join(ovpn_log, '%s.log' % iface),
21 if not encrypt:
22 args += '--cipher', 'none'
23 logging.debug('%r', args)
24 return utils.Popen(args, **kw)
25
26
27 def server(iface, max_clients, dh_path, pipe_fd, port, proto, encrypt, *args, **kw):
28 client_script = '%s %s' % (ovpn_server, pipe_fd)
29 if pipe_fd is not None:
30 args = ('--client-disconnect', client_script) + args
31 return openvpn(iface, encrypt,
32 '--tls-server',
33 '--mode', 'server',
34 '--client-connect', client_script,
35 '--dh', dh_path,
36 '--max-clients', str(max_clients),
37 '--port', str(port),
38 '--proto', 'tcp-server' if proto == 'tcp' else proto,
39 *args, **kw)
40
41
42 def client(iface, server_address, encrypt, *args, **kw):
43 remote = ['--nobind', '--client']
44 try:
45 for ip, port, proto in utils.address_list(server_address):
46 remote += '--remote', ip, port, \
47 'tcp-client' if proto == 'tcp' else proto
48 except ValueError, e:
49 logging.warning("Failed to parse node address %r (%s)",
50 server_address, e)
51 remote += args
52 return openvpn(iface, encrypt, *remote, **kw)
53
54
55 def router(subnet, hello_interval, table, log_path, state_path, pidfile,
56 tunnel_interfaces, *args, **kw):
57 s = utils.ipFromBin(subnet)
58 n = len(subnet)
59 cmd = ['babeld',
60 '-h', str(hello_interval),
61 '-H', str(hello_interval),
62 '-L', log_path,
63 '-S', state_path,
64 '-I', pidfile,
65 '-s',
66 '-C', 'redistribute local deny',
67 '-C', 'redistribute ip %s/%u eq %u' % (s, n, n),
68 '-C', 'redistribute deny']
69 if table:
70 cmd += '-t%u' % table, '-T%u' % table
71 else:
72 cmd[-2:-2] = '-C', 'redistribute ip ::/0 eq 0'
73 for iface in tunnel_interfaces:
74 cmd += '-C', 'interface %s rxcost 512' % iface
75 cmd += args
76 # WKRD: babeld fails to start if pidfile already exists
77 try:
78 os.remove(pidfile)
79 except OSError, e:
80 if e.errno != errno.ENOENT:
81 raise
82 logging.info('%r', cmd)
83 return utils.Popen(cmd, **kw)