TODO update
[re6stnet.git] / vifibnet.py
1 #!/usr/bin/env python
2 import argparse, errno, os, select, subprocess, time
3 from argparse import ArgumentParser
4 import db, plib, upnpigd, utils, tunnel
5
6
7 class ArgParser(ArgumentParser):
8
9 def convert_arg_line_to_args(self, arg_line):
10 arg_line = arg_line.split('#')[0].rstrip()
11 if arg_line:
12 for arg in ('--' + arg_line.lstrip('--')).split():
13 if arg.strip():
14 yield arg
15
16
17 def ovpnArgs(optional_args, ca_path, cert_path):
18 # Treat openvpn arguments
19 if optional_args[0] == "--":
20 del optional_args[0]
21 optional_args.append('--ca')
22 optional_args.append(ca_path)
23 optional_args.append('--cert')
24 optional_args.append(cert_path)
25 return optional_args
26
27
28 def getConfig():
29 parser = ArgParser(fromfile_prefix_chars='@',
30 description='Resilient virtual private network application')
31 _ = parser.add_argument
32
33 # General Configuration options
34 _('--ip', default=None, dest='address', action='append', nargs=3,
35 help='Ip address, port and protocol advertised to other vpn nodes')
36 _('--internal-port', default=1194,
37 help='Port on the machine to listen on for incomming connections')
38 _('--peers-db-refresh', default=3600, type=int,
39 help='the time (seconds) to wait before refreshing the peers db')
40 _('-l', '--log', default='/var/log',
41 help='Path to vifibnet logs directory')
42 _('-s', '--state', default='/var/lib/vifibnet',
43 help='Path to VPN state directory')
44 _('--verbose', '-v', default=0, type=int,
45 help='Defines the verbose level')
46 #_('--babel-state', default='/var/lib/vifibnet/babel_state',
47 # help='Path to babeld state-file')
48 #_('--db', default='/var/lib/vifibnet/peers.db',
49 # help='Path to peers database')
50 _('--server', required=True,
51 help="VPN address of the discovery peer server")
52 _('--server-port', required=True, type=int,
53 help="VPN port of the discovery peer server")
54
55 # Routing algorithm options
56 _('--hello', type=int, default=30,
57 help='Hello interval for babel, in seconds')
58 _('-w', '--wireless', action='store_true',
59 help='''Set all interfaces to be treated as wireless interfaces
60 for the routing protocol''')
61
62 # Tunnel options
63 _('--proto', choices=['udp', 'tcp-server'], nargs='+', default=['udp'],
64 help='Protocol(s) to be used by other peers to connect')
65 _('--tunnel-refresh', default=300, type=int,
66 help='the time (seconds) to wait before changing the connections')
67 _('--dh', required=True,
68 help='Path to dh file')
69 _('--ca', required=True,
70 help='Path to the certificate authority file')
71 _('--cert', required=True,
72 help='Path to the certificate file')
73 # args to be removed ?
74 _('--connection-count', default=20, type=int,
75 help='Number of tunnels')
76 _('--refresh-rate', default=0.05, type=float,
77 help='''The ratio of connections to drop when refreshing the
78 connections''')
79 # Openvpn options
80 _('openvpn_args', nargs=argparse.REMAINDER,
81 help="Common OpenVPN options (e.g. certificates)")
82 return parser.parse_args()
83
84
85 def main():
86 # Get arguments
87 config = getConfig()
88 manual = bool(config.address)
89 network = utils.networkFromCa(config.ca)
90 internal_ip, prefix = utils.ipFromCert(network, config.cert)
91 openvpn_args = ovpnArgs(config.openvpn_args, config.ca, config.cert)
92
93 # Set global variables
94 tunnel.log = config.log
95 utils.verbose = plib.verbose = config.verbose
96
97 # Create and open read_only pipe to get server events
98 utils.log('Creating pipe for server events', 3)
99 r_pipe, write_pipe = os.pipe()
100 read_pipe = os.fdopen(r_pipe)
101
102 # Init db and tunnels
103 if manual:
104 utils.log('Manual external configuration', 3)
105 else:
106 utils.log('Attempting automatic configuration via UPnP', 4)
107 try:
108 forward = upnpigd.UpnpForward(config.internal_port, config.proto)
109 config.address = list([forward.external_ip,
110 str(forward.external_port), proto] for proto in config.proto)
111 except Exception:
112 forward = None
113 utils.log('An atempt to forward a port via UPnP failed', 4)
114
115 peer_db = db.PeerManager(config.state, config.server, config.server_port,
116 config.peers_db_refresh, config.address, internal_ip, prefix,
117 manual, config.proto, 200)
118 tunnel_manager = tunnel.TunnelManager(write_pipe, peer_db, openvpn_args,
119 config.hello, config.tunnel_refresh, config.connection_count,
120 config.refresh_rate)
121
122 # Launch routing protocol. WARNING : you have to be root to start babeld
123 interface_list = ['vifibnet'] + list(tunnel_manager.free_interface_set)
124 router = plib.router(network, internal_ip, interface_list, config.wireless,
125 config.hello, os.path.join(config.state, 'vifibnet.babeld.state'),
126 stdout=os.open(os.path.join(config.log, 'vifibnet.babeld.log'),
127 os.O_WRONLY | os.O_CREAT | os.O_TRUNC), stderr=subprocess.STDOUT)
128
129 # Establish connections
130 server_process = list(plib.server(internal_ip, len(network) + len(prefix),
131 config.connection_count, config.dh, write_pipe, config.internal_port,
132 proto, config.hello, '--dev', 'vifibnet', *openvpn_args,
133 stdout=os.open(os.path.join(config.log,
134 'vifibnet.server.%s.log' % (proto,)),
135 os.O_WRONLY | os.O_CREAT | os.O_TRUNC)) for proto in config.proto)
136 tunnel_manager.refresh()
137
138 # main loop
139 try:
140 while True:
141 nextUpdate = min(tunnel_manager.next_refresh, peer_db.next_refresh)
142 if forward != None:
143 nextUpdate = min(nextUpdate, forward.next_refresh)
144 nextUpdate = max(0, nextUpdate - time.time())
145
146 ready, tmp1, tmp2 = select.select([read_pipe], [], [], nextUpdate)
147 if ready:
148 peer_db.handle_message(read_pipe.readline())
149 if time.time() >= peer_db.next_refresh:
150 peer_db.refresh()
151 if time.time() >= tunnel_manager.next_refresh:
152 tunnel_manager.refresh()
153 except KeyboardInterrupt:
154 return 0
155
156 if __name__ == "__main__":
157 main()