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