Commit bf262697 authored by Guillaume Bury's avatar Guillaume Bury

Tested peer discovery through server

parent 2776b12a
#!/usr/bin/env python
import argparse, math, random, smtplib, sqlite3, string, time
import argparse, math, random, smtplib, sqlite3, string, struct, socket, time
from email.mime.text import MIMEText
from functools import wraps
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
......@@ -20,6 +20,10 @@ class main(object):
parser = argparse.ArgumentParser(
description='Peer discovery http server for vifibnet')
_ = parser.add_argument
_('--prefix', required=True,
help='Prefix of the network deployed ( example : 2001:db8:42')
_('--prefix-len', required=True, type=int,
help='Prefix length')
_('--db', required=True,
help='Path to database file')
_('--ca', required=True,
......@@ -140,15 +144,23 @@ class main(object):
return crypto.dump_certificate(crypto.FILETYPE_PEM, self.ca)
def declare(self, handler, address):
# guess prefix from handler.client_address
ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, handler.client_address)))
prefix = bin(ip1)[2:] + bin(ip2)]2:]
client_address, _ = handler.client_address
# For Testing purposes only
client_address = "2001:db8:42::"
assert(client_address.startswith(self.config.prefix))
ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, client_address))
ip1 = bin(ip1)[2:].rjust(64, '0')
ip2 = bin(ip2)[2:].rjust(64, '0')
prefix = (ip1 + ip2)[self.config.prefix_len:]
prefix, = self.db.execute("SELECT prefix FROM vifib WHERE prefix <= ? ORDER BY prefix DESC", (prefix,)).next()
ip, port, proto = address
self.db.execute("INSERT INTO peers VALUES (?,?,?,?)", (prefix, ip, port, proto))
self.db.execute("INSERT OR REPLACE INTO peers VALUES (?,?,?,?)", (prefix, ip, port, proto))
def getPeerList(self, handler, n, address):
assert 0 < n < 1000
print "declaring new node"
self.declare(handler, address)
print "sending peers"
return self.db.execute("SELECT ip, port, proto FROM peers ORDER BY random() LIMIT ?", (n,)).fetchall()
......
#!/usr/bin/env python
import argparse, errno, os, select, sqlite3, subprocess, sys, time, xmlrpclib
from OpenSSL import crypto
import traceback
import upnpigd
import openvpn
import random
import log
VIFIB_NET = "2001:db8:42::/48"
VIFIB_NET = "2001:db8:42:"
VIFIB_LEN = 48
connection_dict = {} # to remember current connections we made
free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
'client6', 'client7', 'client8', 'client9', 'client10'))
......@@ -36,9 +38,11 @@ class PeersDB:
self.populateDB(100)
def populateDB(self, n):
log.log('Populating Peers DB', 2)
(ip, port) = upnpigd.GetExternalInfo(1194)
proto = 'udp'
self.db.executemany("INSERT INTO peers (ip, port, proto) VALUES ?", self.proxy.getPeerList(n, port, proto))
new_peer_list = self.proxy.getPeerList(n, (ip, port, proto))
self.db.executemany("INSERT INTO peers (ip, port, proto) VALUES (?,?,?)", new_peer_list)
def getUnusedPeers(self, nPeers):
return self.db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 "
......@@ -52,19 +56,19 @@ class PeersDB:
log.log('Updating peers database : unusing peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
def ipFromPrefix(prefix, prefix_len):
tmp = hew(int(prefix, 2))[2::]
def ipFromPrefix(prefix):
tmp = hex(int(prefix, 2))[2:]
ip = VIFIB_NET
for i in xrange(0, len(ip), 4):
for i in xrange(0, len(tmp), 4):
ip += tmp[i:i+4] + ':'
ip += ':'
return ip + ':'
def startBabel(**kw):
args = ['babeld',
'-C', 'redistribute local ip %s' % (config.ip),
'-C', 'redistribute local deny',
# Route VIFIB ip adresses
'-C', 'in ip %s' % VIFIB_NET,
'-C', 'in ip %s:/%u' % (VIFIB_NET, VIFIB_LEN),
# Route only addresse in the 'local' network,
# or other entire networks
#'-C', 'in ip %s' % (config.ip),
......@@ -85,9 +89,9 @@ def getConfig():
_ = parser.add_argument
_('--server', required=True,
help='Address for peer discovery server')
_('--server-port', required=True,
_('--server-port', required=True, type=int,
help='Peer discovery server port')
_('--log-directory', default='/var/log',
_('-l', '--log', default='/var/log',
help='Path to vifibnet logs directory')
_('--client-count', default=2, type=int,
help='Number of client connections')
......@@ -115,18 +119,19 @@ def getConfig():
_('openvpn_args', nargs=argparse.REMAINDER,
help="Common OpenVPN options (e.g. certificates)")
openvpn.config = config = parser.parse_args()
log.verbose = config.verbose
with open(config.cert, 'r') as f:
cert = crypto.load_certificate(crypto.FILETYPE_PEM, f)
cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
subject = cert.get_subject()
prefix_txt, prefix_len_txt = subject.serialNumber.split('/')
prefix = int(prefix_txt)
prefix_len = int(prefix_len_txt)
prefix, _ = subject.serialNumber.split('/')
ip = ipFromPrefix(prefix)
print ip
log.log('Intranet ip : %s' % (ip,), 4)
if config.openvpn_args[0] == "--":
del config.openvpn_args[0]
config.openvpn_args.append('--cert')
config.openvpn_args.append(config.cert)
log.log("Configuration completed", 1)
def startNewConnection(n):
try:
......@@ -134,7 +139,7 @@ def startNewConnection(n):
log.log('Establishing a connection with id %s (%s:%s)' % (id,ip,port), 2)
iface = free_interface_set.pop()
connection_dict[id] = ( openvpn.client( ip, '--dev', iface, '--proto', proto, '--rport', str(port),
stdout=os.open(os.path.join(config.log_directory, 'vifibnet.client.%s.log' % (id,)),
stdout=os.open(os.path.join(config.log, 'vifibnet.client.%s.log' % (id,)),
os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ),
iface)
peers_db.usePeer(id)
......@@ -202,8 +207,7 @@ def main():
# Launch babel on all interfaces
log.log('Starting babel', 3)
babel = startBabel(stdout=os.open('%s/babeld.log' % (config.log_directory,), os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
stderr=subprocess.STDOUT)
babel = startBabel(stdout=os.open(os.path.join(config.log, 'vifibnet.babeld.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC), stderr=subprocess.STDOUT)
# Create and open read_only pipe to get connect/disconnect events from openvpn
log.log('Creating pipe for openvpn events', 3)
......@@ -213,7 +217,7 @@ def main():
# Establish connections
log.log('Starting openvpn server', 3)
serverProcess = openvpn.server(config.ip, write_pipe, '--dev', 'vifibnet',
stdout=os.open(os.path.join(config.log_directory, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
stdout=os.open(os.path.join(config.log, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
startNewConnection(config.client_count)
# Timed refresh initializing
......
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