Commit 1d46fa73 authored by Guillaume Bury's avatar Guillaume Bury

Testing ipchange

parent 7a772d02
#!/usr/bin/python -S
import os, sys
os.write(int(sys.argv[1]), '%(script_type)s %(external_ip)s\n' % os.environ)
...@@ -48,9 +48,7 @@ class main(object): ...@@ -48,9 +48,7 @@ class main(object):
email text, email text,
cert text)""") cert text)""")
except sqlite3.OperationalError, e: except sqlite3.OperationalError, e:
if e.args[0] == 'table vifib already exists': if e.args[0] != 'table vifib already exists':
pass
else:
raise RuntimeError raise RuntimeError
else: else:
self.db.execute("INSERT INTO vifib VALUES ('',null,null)") self.db.execute("INSERT INTO vifib VALUES ('',null,null)")
...@@ -146,19 +144,26 @@ class main(object): ...@@ -146,19 +144,26 @@ class main(object):
client_address = "2001:db8:42::" client_address = "2001:db8:42::"
ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, client_address)) ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, client_address))
ip = bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0') ip = bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
assert(ip.startswith(self.network)) if ip.startswith(self.network):
prefix = ip[len(self.network):] prefix = ip[len(self.network):]
prefix, = self.db.execute("SELECT prefix FROM vifib WHERE prefix <= ? ORDER BY prefix DESC", (prefix,)).next() prefix, = self.db.execute("SELECT prefix FROM vifib WHERE prefix <= ? ORDER BY prefix DESC", (prefix,)).next()
ip, port, proto = address ip, port, proto = address
self.db.execute("INSERT OR REPLACE INTO peers VALUES (?,?,?,?)", (prefix, ip, port, proto)) self.db.execute("INSERT OR REPLACE INTO peers VALUES (?,?,?,?)", (prefix, ip, port, proto))
return True
else:
print "Unauthorized connection from %s which does not start with %s" % (ip, self.network)
return False
def getPeerList(self, handler, n, address): def getPeerList(self, handler, n, address):
assert 0 < n < 1000 assert 0 < n < 1000
print "declaring new node" print "declaring new node"
self.declare(handler, address) if not self.declare(handler, address):
# TODO: do something intelligent
raise RuntimeError
print "sending peers" print "sending peers"
return self.db.execute("SELECT ip, port, proto FROM peers ORDER BY random() LIMIT ?", (n,)).fetchall() return self.db.execute("SELECT ip, port, proto FROM peers ORDER BY random() LIMIT ?", (n,)).fetchall()
if __name__ == "__main__": if __name__ == "__main__":
main() main()
...@@ -18,7 +18,7 @@ def main(): ...@@ -18,7 +18,7 @@ def main():
config = parser.parse_args() config = parser.parse_args()
if config.req and len(config.req) % 2 == 1: if config.req and len(config.req) % 2 == 1:
print "Sorry, request argument was incorrect, there must be an even number of request arguments" print "Sorry, request argument was incorrect, there must be an even number of request arguments"
os.exit(1) exit(1)
# Get token # Get token
email = raw_input('Please enter your email address : ') email = raw_input('Please enter your email address : ')
...@@ -44,7 +44,7 @@ def main(): ...@@ -44,7 +44,7 @@ def main():
# Get certificates # Get certificates
ca = s.getCa() ca = s.getCa()
cert = s.requestCertificate(token,req) cert = s.requestCertificate(token, req)
# Generating dh file # Generating dh file
subprocess.call(['openssl', 'dhparam', '-out', os.path.join(config.dir, 'dh2048.pem'), '2048']) subprocess.call(['openssl', 'dhparam', '-out', os.path.join(config.dir, 'dh2048.pem'), '2048'])
......
...@@ -12,7 +12,7 @@ connection_dict = {} # to remember current connections we made ...@@ -12,7 +12,7 @@ connection_dict = {} # to remember current connections we made
free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5', free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
'client6', 'client7', 'client8', 'client9', 'client10')) 'client6', 'client7', 'client8', 'client9', 'client10'))
# TODO : flag in some way the peers that are connected to us so we don't connect to them # TODO: flag in some way the peers that are connected to us so we don't connect to them
# Or maybe we just don't care # Or maybe we just don't care
class PeersDB: class PeersDB:
...@@ -100,7 +100,7 @@ def getConfig(): ...@@ -100,7 +100,7 @@ def getConfig():
help='Path to vifibnet logs directory') help='Path to vifibnet logs directory')
_('--client-count', default=2, type=int, _('--client-count', default=2, type=int,
help='Number of client connections') help='Number of client connections')
# TODO : use maxpeer # TODO: use maxpeer
_('--max-clients', default=10, type=int, _('--max-clients', default=10, type=int,
help='the number of peers that can connect to the server') help='the number of peers that can connect to the server')
_('--refresh-time', default=60, type=int, _('--refresh-time', default=60, type=int,
...@@ -119,10 +119,6 @@ def getConfig(): ...@@ -119,10 +119,6 @@ def getConfig():
help='Path to the certificate authority file') help='Path to the certificate authority file')
_('--cert', required=True, _('--cert', required=True,
help='Path to the certificate file') help='Path to the certificate file')
# Temporary args - to be removed
# ~ Can be removed, should ip be a global variable ?
_('--ip', required=True,
help='IPv6 of the server')
# Openvpn options # Openvpn options
_('openvpn_args', nargs=argparse.REMAINDER, _('openvpn_args', nargs=argparse.REMAINDER,
help="Common OpenVPN options (e.g. certificates)") help="Common OpenVPN options (e.g. certificates)")
...@@ -151,32 +147,31 @@ def getConfig(): ...@@ -151,32 +147,31 @@ def getConfig():
def startNewConnection(n, write_pipe): def startNewConnection(n, write_pipe):
try: try:
for id, ip, port, proto in peers_db.getUnusedPeers(n): for peer_id, ip, port, proto in peers_db.getUnusedPeers(n):
log.log('Establishing a connection with id %s (%s:%s)' % (id,ip,port), 2) log.log('Establishing a connection with id %s (%s:%s)' % (peer_id, ip, port), 2)
iface = free_interface_set.pop() iface = free_interface_set.pop()
connection_dict[id] = ( openvpn.client( ip, write_pipe, '--dev', iface, '--proto', proto, '--rport', str(port), connection_dict[peer_id] = ( openvpn.client( ip, write_pipe, '--dev', iface, '--proto', proto, '--rport', str(port),
stdout=os.open(os.path.join(config.log, 'vifibnet.client.%s.log' % (id,)), stdout=os.open(os.path.join(config.log, 'vifibnet.client.%s.log' % (peer_id,)),
os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ), os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ),
iface) iface)
peers_db.usePeer(id) peers_db.usePeer(peer_id)
except KeyError: except KeyError:
log.log("Can't establish connection with %s : no available interface" % ip, 2) log.log("Can't establish connection with %s : no available interface" % ip, 2)
pass
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
def killConnection(id): def killConnection(peer_id):
try: try:
log.log('Killing the connection with id ' + str(id), 2) log.log('Killing the connection with id ' + str(peer_id), 2)
p, iface = connection_dict.pop(id) p, iface = connection_dict.pop(peer_id)
p.kill() p.kill()
free_interface_set.add(iface) free_interface_set.add(iface)
peers_db.unusePeer(id) peers_db.unusePeer(peer_id)
except KeyError: except KeyError:
log.log("Can't kill connection to " + peer + ": no existing connection", 1) log.log("Can't kill connection to " + peer_id + ": no existing connection", 1)
pass pass
except Exception: except Exception:
log.log("Can't kill connection to " + peer + ": uncaught error", 1) log.log("Can't kill connection to " + peer_id + ": uncaught error", 1)
pass pass
def checkConnections(): def checkConnections():
...@@ -188,23 +183,23 @@ def checkConnections(): ...@@ -188,23 +183,23 @@ def checkConnections():
peers_db.unusePeer(id) peers_db.unusePeer(id)
del connection_dict[id] del connection_dict[id]
def refreshConnections(): def refreshConnections(write_pipe):
checkConnections() checkConnections()
# Kill some random connections # Kill some random connections
try: try:
for i in range(0, max(0, len(connection_dict) - config.client_count + config.refresh_count)): for i in range(0, max(0, len(connection_dict) - config.client_count + config.refresh_count)):
id = random.choice(connection_dict.keys()) peer_id = random.choice(connection_dict.keys())
killConnection(id) killConnection(peer_id)
except Exception: except Exception:
pass pass
# Establish new connections # Establish new connections
startNewConnection(config.client_count - len(connection_dict)) startNewConnection(config.client_count - len(connection_dict), write_pipe)
def handle_message(msg): def handle_message(msg):
script_type, arg = msg.split() script_type, arg = msg.split()
if script_type == 'client-connect': if script_type == 'client-connect':
log.log('Incomming connection from %s' % (arg,), 3) log.log('Incomming connection from %s' % (arg,), 3)
# TODO : check if we are not already connected to it # TODO: check if we are not already connected to it
elif script_type == 'client-disconnect': elif script_type == 'client-disconnect':
log.log('%s has disconnected' % (arg,), 3) log.log('%s has disconnected' % (arg,), 3)
elif script_type == 'ipchange': elif script_type == 'ipchange':
...@@ -250,7 +245,7 @@ def main(): ...@@ -250,7 +245,7 @@ def main():
if ready: if ready:
handle_message(read_pipe.readline()) handle_message(read_pipe.readline())
if time.time() >= next_refresh: if time.time() >= next_refresh:
refreshConnections() refreshConnections(write_pipe)
next_refresh = time.time() + config.refresh_time next_refresh = time.time() + config.refresh_time
except KeyboardInterrupt: except KeyboardInterrupt:
return 0 return 0
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment