Commit b1c728a1 by Guillaume Bury

Fixed prefix=0 bug

1 parent fae2739f
......@@ -154,6 +154,7 @@ OPTIONS : VIFIBNET.PY
Complete public ( reachable from the internet ) address of the machine
running a registry. Will be used to get the pirvate address of the
registry and/or bootstrap peers
Examples : http://ipv4:port, http://[ipv6]:port
--hello duration
Set hello interval, in seconds, for both wired and wireless
......
......@@ -4,7 +4,7 @@ import utils
class PeerManager:
# internal ip = temp arg/attribute
def __init__(self, db_dir_path, registry, key_path, refresh_time, address,
def __init__(self, db_path, registry, key_path, refresh_time, address,
internal_ip, prefix, manual, pp , db_size):
self._refresh_time = refresh_time
self._address = address
......@@ -17,8 +17,7 @@ class PeerManager:
self._manual = manual
logging.info('Connecting to peers database...')
self._db = sqlite3.connect(os.path.join(db_dir_path, 'peers.db'),
isolation_level=None)
self._db = sqlite3.connect(db_path, isolation_level=None)
logging.debug('Database opened')
logging.info('Preparing peers database...')
......
#!/usr/bin/env python
import argparse, math, random, select, smtplib, sqlite3, string, socket
import subprocess, time, threading, traceback, errno
import subprocess, time, threading, traceback, errno, logging
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
from email.mime.text import MIMEText
from OpenSSL import crypto
......@@ -41,6 +41,8 @@ class main(object):
self.refresh_interval = 600
self.last_refresh = time.time()
utils.setupLog(1)
# Command line parsing
parser = argparse.ArgumentParser(
description='Peer discovery http server for vifibnet')
......@@ -91,7 +93,7 @@ class main(object):
self.key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
# Get vpn network prefix
self.network = bin(self.ca.get_serial_number())[3:]
print "Network prefix : %s/%u" % (self.network, len(self.network))
logging.info("Network prefix : %s/%u" % (self.network, len(self.network)))
# Starting server
server4 = SimpleXMLRPCServer4(('0.0.0.0', self.config.port), requestHandler=RequestHandler, allow_none=True)
......@@ -132,16 +134,22 @@ class main(object):
s.quit()
def _getPrefix(self, prefix_len):
assert 0 < prefix_len <= 128 - len(self.network)
for prefix, in self.db.execute("""SELECT prefix FROM vpn WHERE length(prefix) <= ? AND cert is null
ORDER BY length(prefix) DESC""", (prefix_len,)):
while len(prefix) < prefix_len:
self.db.execute("UPDATE vpn SET prefix = ? WHERE prefix = ?", (prefix + '1', prefix))
prefix += '0'
self.db.execute("INSERT INTO vpn VALUES (?,null,null)", (prefix,))
max_len = 128 - len(self.network)
assert 0 < prefix_len <= max_len
try:
prefix, = self.db.execute("""SELECT prefix FROM vpn WHERE length(prefix) <= ? AND cert is null
ORDER BY length(prefix) DESC""", (prefix_len,)).next()
except StopIteration:
logging.error('There are no more free /%s prefix available' % (prefix_len,))
raise
while len(prefix) < prefix_len:
self.db.execute("UPDATE vpn SET prefix = ? WHERE prefix = ?", (prefix + '1', prefix))
prefix += '0'
self.db.execute("INSERT INTO vpn VALUES (?,null,null)", (prefix,))
if len(prefix) < max_len or '1' in prefix:
return prefix
logging.error('There are no more free /%s prefix available' % (prefix_len,))
raise RuntimeError
self.db.execute("UPDATE vpn SET cert = 'reserved' WHERE prefix = ?", (prefix,))
return self._getPrefix(prefix_len)
def requestCertificate(self, handler, token, cert_req):
try:
......
......@@ -20,6 +20,8 @@ def main():
help='Directory where the key and certificate will be stored')
_('-r', '--req', nargs=2, action='append',
help='Name and value of certificate request additional arguments')
_('--email', help='Your email address')
_('--token', help='The token you received')
config = parser.parse_args()
# Establish connection with server
......@@ -33,33 +35,12 @@ def main():
if config.ca_only:
sys.exit(0)
# Create and initialize peers DB
db = sqlite3.connect(os.path.join(config.dir, 'peers.db'), isolation_level=None)
try:
db.execute("""CREATE TABLE peers (
prefix TEXT PRIMARY KEY,
address TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
date INTEGER DEFAULT (strftime('%s', 'now')))""")
db.execute("CREATE INDEX _peers_used ON peers(used)")
except sqlite3.OperationalError, e:
if e.args[0] == 'table peers already exists':
print "Table peers already exists, leaving it as it is"
else:
print "sqlite3.OperationalError :" + e.args[0]
sys.exit(1)
if not config.no_boot:
prefix, address = s.getBootstrapPeer()
db.execute("INSERT INTO peers (prefix, address) VALUES (?,?)", (prefix, address))
if config.db_only:
sys.exit(0)
# Get token
email = raw_input('Please enter your email address : ')
_ = s.requestToken(email)
token = raw_input('Please enter your token : ')
if not config.token:
if not config.email:
config.email = raw_input('Please enter your email address : ')
_ = s.requestToken(config.email)
config.token = raw_input('Please enter your token : ')
# Generate key and cert request
pkey = crypto.PKey()
......@@ -76,7 +57,7 @@ def main():
req = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
# Get certificate
cert = s.requestCertificate(token, req)
cert = s.requestCertificate(config.token, req)
# Store cert and key
with open(os.path.join(config.dir, 'cert.key'), 'w') as f:
......
......@@ -25,7 +25,6 @@ class Connection:
self.bandwidth = None
self._last_trafic = None
# TODO : update the stats
def refresh(self):
# Check that the connection is alive
if self.process.poll() != None:
......@@ -83,10 +82,7 @@ class TunnelManager:
self._network = network
self._net_len = len(network)
self._iface_list = iface_list
self.free_interface_set = set(('client1', 'client2', 'client3',
'client4', 'client5', 'client6',
'client7', 'client8', 'client9',
'client10', 'client11', 'client12'))
self.free_interface_set = set('client' + str(i) for i in xrange(1,13))
self.next_refresh = time.time()
self._client_count = int(math.ceil(float(connection_count) / 2.0))
......
import argparse, time, struct, socket
import argparse, time, struct, socket, logging
from OpenSSL import crypto
verbose = 0
logging_levels = logging.WARNING, logging.INFO, logging.DEBUG, 5
def log(message, verbose_level):
if verbose >= verbose_level:
print time.strftime("%d-%m-%Y %H:%M:%S :"),
print message
def setupLog(log_level):
logging.basicConfig(level=logging_levels[log_level],
format='%(asctime)s : %(message)s',
datefmt='%d-%m-%Y %H:%M:%S')
logging.addLevelName(5, 'TRACE')
logging.trace = lambda *args, **kw: logging.log(5, *args, **kw)
def binFromIp(ip):
ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
......@@ -21,7 +23,7 @@ def ipFromBin(prefix):
def ipFromPrefix(vifibnet, prefix, prefix_len):
prefix = bin(int(prefix))[2:].rjust(prefix_len, '0')
ip_t = (vifibnet + prefix).ljust(128, '0')
ip_t = (vifibnet + prefix).ljust(127, '0').ljust(128, '1')
return ipFromBin(ip_t), prefix
def networkFromCa(ca_path):
......
......@@ -94,13 +94,11 @@ def main():
internal_ip, prefix = utils.ipFromCert(network, config.cert)
openvpn_args = ovpnArgs(config.openvpn_args, config.ca, config.cert,
config.key)
config.db_path = os.path.join(config.state, 'peers.db')
# Set logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s : %(message)s',
datefmt='%d-%m-%Y %H:%M:%S')
logging.addLevelName(5, 'TRACE')
logging.trace = lambda *args, **kw: logging.log(5, *args, **kw)
utils.setupLog(config.verbose)
logging.trace("Configuration :\n%s" % config)
# Set global variables
......@@ -133,7 +131,7 @@ def main():
except upnpigd.NoUPnPDevice:
logging.info('No upnp device found')
peer_db = db.PeerManager(config.state, config.registry, config.key,
peer_db = db.PeerManager(config.db_path, config.registry, config.key,
config.peers_db_refresh, config.address, internal_ip, prefix,
manual, config.pp, 200)
tunnel_manager = tunnel.TunnelManager(write_pipe, peer_db, openvpn_args,
......@@ -190,8 +188,7 @@ def main():
pass
except sqlite3.Error:
traceback.print_exc()
db_path = os.path.join(config.state, 'peers.db')
os.rename(db_path, db_path + '.bak')
os.rename(config.db_path, config.db_path + '.bak')
os.execvp(sys.executable, sys.argv)
except KeyboardInterrupt:
return 0
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!