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