Test single-ip certs and simplify Babel rules
[re6stnet.git] / re6st / plib.py
1 import logging, errno, os, subprocess
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 #'--user', 'nobody', '--group', 'nogroup',
17 ] + list(args)
18 if ovpn_log:
19 args += '--log-append', os.path.join(ovpn_log, '%s.log' % iface),
20 if not encrypt:
21 args += '--cipher', 'none'
22 logging.debug('%r', args)
23 return subprocess.Popen(args, **kw)
24
25
26 def server(iface, my_ip, max_clients, dh_path, pipe_fd, port, proto, encrypt, *args, **kw):
27 client_script = '%s %s' % (ovpn_server, pipe_fd)
28 if pipe_fd is not None:
29 args = ('--client-disconnect', client_script) + args
30 return openvpn(iface, encrypt,
31 '--tls-server',
32 '--mode', 'server',
33 '--up', '%s %s' % (ovpn_server, my_ip),
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(network, subnet, hello_interval, log_path, state_path, pidfile,
56 tunnel_interfaces, *args, **kw):
57 s = utils.ipFromBin(subnet)
58 n = len(subnet)
59 cmd = ['babeld',
60 '-C', 'redistribute local deny',
61 '-C', 'redistribute ip %s/%u eq %u' % (s, n, n),
62 '-C', 'redistribute deny',
63 #'-C', 'in ip %s/%u' % (utils.ipFromBin(network), len(network)),
64 #'-C', 'in deny',
65 '-h', str(hello_interval),
66 '-H', str(hello_interval),
67 '-L', log_path,
68 '-S', state_path,
69 '-I', pidfile,
70 '-s']
71 for iface in tunnel_interfaces:
72 cmd += '-C', 'interface %s rxcost 512' % iface
73 cmd += args
74 # WKRD: babeld fails to start if pidfile already exists
75 try:
76 os.remove(pidfile)
77 except OSError, e:
78 if e.errno != errno.ENOENT:
79 raise
80 logging.info('%r', cmd)
81 return subprocess.Popen(cmd, **kw)