Commit c2f9c96c authored by Guillaume Bury's avatar Guillaume Bury

Fixed some syntax bugs

parent b1c728a1
......@@ -145,16 +145,18 @@ OPTIONS : VIFIBNET.PY
-v, --verbose level
Defines the verbose level, level should be an integer between 0
and 5 ( including ). There is no precise convention for verbode
and 3 ( including ). There is no precise convention for verbode
level for now, except an increased number means more log messages.
This parameter is also given to openvpn and babel for their log.
This parameter is also given to babel for its log.
To adjust verbose level for openvpn, add an openvpn optional
arguments at the end of the command line
Default : 0
--registry address
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
Examples : http://192.0.2.42:80, http://[2001:db8:42::1]:80
--hello duration
Set hello interval, in seconds, for both wired and wireless
......
......@@ -122,8 +122,8 @@ class PeerManager:
logging.debug('Boot peer received from server')
p = subprocess.Popen(('openssl', 'rsautl', '-decrypt', '-inkey', self._key_path),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
bootpeer = p.communicate(bootpeer).split()
self.db.execute("INSERT INTO peers (prefix, address) VALUES (?,?)", bootpeer)
bootpeer = p.communicate(bootpeer)[0].split()
self._db.execute("INSERT INTO peers (prefix, address) VALUES (?,?)", bootpeer)
logging.debug('Boot peer added')
return True
except socket.error:
......@@ -162,7 +162,7 @@ class PeerManager:
if not self._manual:
external_ip = arg
new_address = list([external_ip, port, proto]
for port, proto in self._pp)
for port, proto, _ in self._pp)
if self._address != new_address:
self._address = new_address
logging.info('Received new external ip : %s'
......
......@@ -12,7 +12,6 @@ def openvpn(hello_interval, *args, **kw):
'--user', 'nobody',
'--ping-exit', str(4 * hello_interval),
'--group', 'nogroup',
'--verb', str(verbose),
] + list(args)
logging.trace('%s' % (args,))
return subprocess.Popen(args, **kw)
......
#!/usr/bin/env python
import argparse, math, random, select, smtplib, sqlite3, string, socket
import subprocess, time, threading, traceback, errno, logging
import subprocess, time, threading, traceback, errno, logging, os, xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
from email.mime.text import MIMEText
from OpenSSL import crypto
......@@ -41,7 +41,7 @@ class main(object):
self.refresh_interval = 600
self.last_refresh = time.time()
utils.setupLog(1)
utils.setupLog(3)
# Command line parsing
parser = argparse.ArgumentParser(
......@@ -126,7 +126,7 @@ class main(object):
# Creating and sending email
s = smtplib.SMTP(self.config.mailhost)
me = 'postmaster@vifibnet.com'
msg = MIMEText('Hello world !\nYour token : %s' % (token,)) # XXX
msg = MIMEText('Hello world !\nYour token : %s' % (token,)) # XXX
msg['Subject'] = '[Vifibnet] Token Request'
msg['From'] = me
msg['To'] = email
......@@ -197,23 +197,28 @@ class main(object):
FROM peers ORDER BY random() LIMIT 1""").next()
def getBootstrapPeer(self, handler, client_prefix):
cert = self.db.execute("SELECT cert FROM vpn WHERE prefix = ?", (client_prefix,))
cert, = self.db.execute("SELECT cert FROM vpn WHERE prefix = ?",
(client_prefix,)).next()
logging.trace('Getting bootpeer info...')
if self.config.bootstrap:
bootpeer = random.choice(self.config.bootstrap)
try:
prefix, address = self.db.execute("""SELECT prefix, address
FROM peers WHERE prefix = ?""", (bootpeer,))
FROM peers WHERE prefix = ?""", (bootpeer,)).next()
except StopIteration:
logging.info('Bootstrap peer %s unknown, sending random peer'
% hex(int(bootpeer, 2))[2:])
prefix, address = self._randomPeer()
else:
prefix, address = self._randomPeer()
logging.trace('Gotten bootpeer info from db')
r, w = os.pipe()
try:
threading.Thread(target=os.write, args=(w, cert)).start()
p = subprocess.Popen(('openssl', 'rsautl', '-encrypt', '-certin', '-inkey', '/proc/self/fd/%u' % r),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print "Sending bootstrap peer (%s, %s)" % (prefix, address)
return xmlrpclib.Binary(p.communicate('%s %s' % (prefix, address)))
logging.info("Sending bootstrap peer (%s, %s)" % (prefix, address))
return xmlrpclib.Binary(p.communicate('%s %s' % (prefix, address))[0])
finally:
os.close(r)
os.close(w)
......
......@@ -8,10 +8,6 @@ def main():
_ = parser.add_argument
_('--ca-only', action='store_true',
help='To only get CA form server')
_('--db-only', action='store_true',
help='To only get CA and setup peer db with bootstrap peer')
_('--no-boot', action='store_true',
help='Enable to skip getting bootstrap peer')
_('--server', required=True,
help='Address of the server delivering certifiactes')
_('--port', required=True, type=int,
......
......@@ -71,7 +71,7 @@ class Connection:
class TunnelManager:
def __init__(self, write_pipe, peer_db, openvpn_args, hello_interval,
refresh, connection_count, refresh_rate, iface_list, network):
refresh, connection_count, refresh_ratio, iface_list, network):
self._write_pipe = write_pipe
self._peer_db = peer_db
self._connection_dict = {}
......@@ -82,11 +82,12 @@ class TunnelManager:
self._network = network
self._net_len = len(network)
self._iface_list = iface_list
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))
self._refresh_count = int(math.ceil(refresh_rate * self._client_count))
self._client_count = (connection_count + 1) // 2
self._refresh_count = int(math.ceil(refresh_ratio * self._client_count))
self.free_interface_set = set('client' + str(i)
for i in xrange(1, self._client_count + 1))
def refresh(self):
logging.info('Refreshing the tunnels...')
......
......@@ -89,12 +89,14 @@ def main():
config = getConfig()
if not config.pp:
config.pp = [['1194', 'udp'], ['1194', 'tcp-server']]
config.pp = list((port, proto, 'vifibnet-%s' % proto)
for port, proto in config.pp)
manual = bool(config.address)
network = utils.networkFromCa(config.ca)
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')
db_path = os.path.join(config.state, 'peers.db')
# Set logging
utils.setupLog(config.verbose)
......@@ -118,20 +120,23 @@ def main():
for c, s in ('udp', 'udp'), ('tcp-client', 'tcp-server'):
if len(list(x for x in config.address if x[2] == c)) \
< len(list(x for x in config.pp if x[1] == s)):
pass # XXX: warn user about probable misconfiguration
logging.warning("""Beware: in manual configuration, you
declared less external configurations regarding
protocol %s/%s than you gave internal server
configurations""" % (c, s))
else:
logging.info('Attempting automatic configuration via UPnP...')
try:
forwarder = upnpigd.Forwarder()
config.address = []
for port, proto in config.pp:
for port, proto, _ in config.pp:
ext = forwarder.AddRule(port, proto)
if ext:
config.address.append(ext)
except upnpigd.NoUPnPDevice:
logging.info('No upnp device found')
peer_db = db.PeerManager(config.db_path, config.registry, config.key,
peer_db = db.PeerManager(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,
......@@ -139,22 +144,23 @@ def main():
config.refresh_ratio, config.iface_list, network)
# Launch routing protocol. WARNING : you have to be root to start babeld
interface_list = ['vifibnet'] + list(tunnel_manager.free_interface_set) \
+ config.iface_list
interface_list = list(tunnel_manager.free_interface_set) \
+ config.iface_list + list(iface
for _, _, iface in config.pp)
router = plib.router(network, internal_ip, interface_list, config.wireless,
config.hello, os.path.join(config.state, 'vifibnet.babeld.state'),
stdout=os.open(os.path.join(config.log, 'vifibnet.babeld.log'),
config.hello, os.path.join(config.state, 'babeld.state'),
stdout=os.open(os.path.join(config.log, 'babeld.log'),
os.O_WRONLY | os.O_CREAT | os.O_TRUNC), stderr=subprocess.STDOUT)
# Establish connections
server_process = list(plib.server(internal_ip, len(network) + len(prefix),
config.connection_count, config.dh, write_pipe, port,
proto, config.hello, '--dev', 'vifibnet-%s' % proto, *openvpn_args,
proto, config.hello, '--dev', iface, *openvpn_args,
stdout=os.open(os.path.join(config.log,
'vifibnet.server.%s.log' % (proto,)),
os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
stderr=subprocess.STDOUT)
for port, proto in config.pp)
for port, proto, iface in config.pp)
tunnel_manager.refresh()
# main loop
......@@ -188,7 +194,7 @@ def main():
pass
except sqlite3.Error:
traceback.print_exc()
os.rename(config.db_path, config.db_path + '.bak')
os.rename(db_path, db_path + '.bak')
os.execvp(sys.executable, sys.argv)
except KeyboardInterrupt:
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