Small fixes in tunnel and registry
[re6stnet.git] / tunnel.py
1 import os, random, traceback, time, struct, subprocess, operator, math
2 import plib, utils, db
3
4 log = None
5 smooth = 0.3 # this is used to smooth the traffic sampling. Lower value
6 # mean more smooth
7
8 # Be carfull the refresh interval should let the routes be established
9
10
11 class Connection:
12
13 def __init__(self, address, write_pipe, hello, iface, prefix,
14 ovpn_args):
15 self.process = plib.client(address, write_pipe, hello, '--dev', iface,
16 *ovpn_args, stdout=os.open(os.path.join(log,
17 'vifibnet.client.%s.log' % (prefix,)),
18 os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
19 stderr=subprocess.STDOUT)
20
21 self.iface = iface
22 self.routes = 0
23 self._prefix = prefix
24 self._bandwidth = None
25 self._last_trafic = None
26
27 # TODO : update the stats
28 def refresh(self):
29 # Check that the connection is alive
30 if self.process.poll() != None:
31 utils.log('Connection with %s has failed with return code %s'
32 % (self._prefix, self.process.returncode), 3)
33 return False
34
35 self._updateBandwidth()
36 return True
37
38 def _updateBandwidth(self):
39 try:
40 f_rx = open('/sys/class/net/%s/statistics/rx_bytes' %
41 self.iface, 'r')
42 f_tx = open('/sys/class/net/%s/statistics/tx_bytes' %
43 self.iface, 'r')
44
45 trafic = int(f_rx.read()) + int(f_tx.read())
46 t = time.time()
47
48 if bool(self._last_trafic):
49 bw = (trafic - self._last_trafic) / (t -
50 self._last_trafic_update)
51 if bool(self._bandwidth):
52 self._bandwidth = ((1 - smooth) * self._bandwidth
53 + smooth * bw)
54 else:
55 self._bandwidth = bw
56
57 utils.log('New bandwidth calculated on iface %s : %s' %
58 (self.iface, self._bandwidth), 4)
59
60 self._last_trafic_update = t
61 self._last_trafic = trafic
62 except IOError: # This just means that the interface is downs
63 utils.log('Unable to calculate bandwidth on iface %s' %
64 self.iface, 4)
65
66
67 class TunnelManager:
68
69 def __init__(self, write_pipe, peer_db, openvpn_args, hello_interval,
70 refresh, connection_count, refresh_rate, iface_list, network):
71 self._write_pipe = write_pipe
72 self._peer_db = peer_db
73 self._connection_dict = {}
74 self._iface_to_prefix = {}
75 self._ovpn_args = openvpn_args
76 self._hello = hello_interval
77 self._refresh_time = refresh
78 self._network = network
79 self._net_len = len(network)
80 self._iface_list = iface_list
81 self.__indirect_connect = []
82 self.free_interface_set = set(('client1', 'client2', 'client3',
83 'client4', 'client5', 'client6',
84 'client7', 'client8', 'client9',
85 'client10', 'client11', 'client12'))
86 self.next_refresh = time.time()
87
88 self._client_count = int(math.ceil(float(connection_count) / 2.0))
89 self._refresh_count = int(math.ceil(refresh_rate * self._client_count))
90
91 def refresh(self):
92 utils.log('Refreshing the tunnels...', 2)
93 self._cleanDeads()
94 self._countRoutes()
95 self._removeSomeTunnels()
96 self._makeNewTunnels()
97 utils.log('Tunnels refreshed', 2)
98 self.next_refresh = time.time() + self._refresh_time
99
100 def _cleanDeads(self):
101 for prefix in self._connection_dict.keys():
102 if not self._connection_dict[prefix].refresh():
103 self._kill(prefix)
104 self._peer_db.flagPeer(prefix)
105
106 def _removeSomeTunnels(self):
107 # Get the candidates to killing
108 candidates = sorted(self._connection_dict, key=lambda p:
109 self._connection_dict[p].routes)
110 print max(0, len(self._connection_dict) - self._client_count + self._refresh_count) # DEBUG
111 print self._client_count
112 for prefix in candidates[0: max(0, len(self._connection_dict) -
113 self._client_count + self._refresh_count)]:
114 self._kill(prefix)
115
116 def _kill(self, prefix):
117 utils.log('Killing the connection with %s...' % (prefix,), 2)
118 connection = self._connection_dict.pop(prefix)
119 try:
120 connection.process.kill()
121 except OSError:
122 # If the process is already exited
123 pass
124 self.free_interface_set.add(connection.iface)
125 self._peer_db.unusePeer(prefix)
126 del self._iface_to_prefix[connection.iface]
127 utils.log('Connection with %s killed' % (prefix,), 2)
128
129 def _makeNewTunnels(self):
130 i = 0
131 utils.log('Trying to make %i new tunnels...' %
132 (self._client_count - len(self._connection_dict)), 5)
133 try:
134 for prefix, address in self._peer_db.getUnusedPeers(
135 self._client_count - len(self._connection_dict)):
136 utils.log('Establishing a connection with %s' % prefix, 2)
137 iface = self.free_interface_set.pop()
138 self._connection_dict[prefix] = Connection(address,
139 self._write_pipe, self._hello, iface,
140 prefix, self._ovpn_args)
141 self._iface_to_prefix[iface] = prefix
142 self._peer_db.usePeer(prefix)
143 i += 1
144 utils.log('%u new tunnels established' % (i,), 3)
145 except KeyError:
146 utils.log("""Can't establish connection with %s
147 : no available interface""" % prefix, 2)
148 except Exception:
149 traceback.print_exc()
150
151 def _countRoutes(self):
152 utils.log('Starting to count the routes on each interface...', 3)
153 self._indirect_connect = []
154 for iface in self._iface_to_prefix.keys():
155 self._connection_dict[self._iface_to_prefix[iface]].routes = 0
156 f = open('/proc/net/ipv6_route', 'r')
157 for line in f:
158 ip, subnet_size, iface = struct.unpack('32s x 2s 106x %ss x'
159 % (len(line) - 142), line)
160 ip = bin(int(ip, 16))[2:].rjust(128, '0')
161
162 if ip.startswith(self._network):
163 iface = iface.strip()
164 subnet_size = int(subnet_size, 16)
165 utils.log('Route on iface %s detected to %s/%s'
166 % (iface, ip, subnet_size), 8)
167 if iface in self._iface_to_prefix.keys():
168 self._connection_dict[self._iface_to_prefix[iface]].routes += 1
169 if iface in self._iface_list and self._net_len < subnet_size < 128:
170 prefix = ip[self._net_len:subnet_size]
171 utils.log('A route to %s has been discovered on the LAN'
172 % (prefix,), 3)
173 self._peer_db.blacklist(prefix)
174
175 utils.log("Routes have been counted", 3)
176 for p in self._connection_dict.keys():
177 utils.log('Routes on iface %s : %s' % (
178 self._connection_dict[p].iface,
179 self._connection_dict[p].routes), 5)