Commit 164cbdd4 authored by Ulysse Beaugnon's avatar Ulysse Beaugnon

Changes in config : it is now fully included in utils

parent 84e01d2c
from utils import * import utils
import sqlite3 import sqlite3
import xmlrpclib import xmlrpclib
class PeersDB: class PeersDB:
def __init__(self, dbPath): def __init__(self, dbPath):
log('Connectiong to peers database', 4) utils.log('Connectiong to peers database', 4)
self.db = sqlite3.connect(dbPath, isolation_level=None) self.db = sqlite3.connect(dbPath, isolation_level=None)
log('Preparing peers database', 4) utils.log('Preparing peers database', 4)
try: try:
self.db.execute("UPDATE peers SET used = 0") self.db.execute("UPDATE peers SET used = 0")
except sqlite3.OperationalError, e: except sqlite3.OperationalError, e:
...@@ -16,24 +16,24 @@ class PeersDB: ...@@ -16,24 +16,24 @@ class PeersDB:
def populate(self, n): def populate(self, n):
# TODO: don't reconnect to server each time ? # TODO: don't reconnect to server each time ?
log('Connecting to remote server', 3) utils.log('Connecting to remote server', 3)
self.proxy = xmlrpclib.ServerProxy('http://%s:%u' % (config.server, config.server_port)) self.proxy = xmlrpclib.ServerProxy('http://%s:%u' % (utils.config.server, utils.config.server_port))
log('Updating peers database : populating', 2) utils.log('Updating peers database : populating', 2)
# TODO: determine port and proto # TODO: determine port and proto
port = 1194 port = 1194
proto = 'udp' proto = 'udp'
new_peer_list = self.proxy.getPeerList(n, (config.internal_ip, config.external_ip, port, proto)) new_peer_list = self.proxy.getPeerList(n, (utils.config.internal_ip, utils.config.external_ip, port, proto))
self.db.executemany("INSERT OR IGNORE INTO peers (ip, port, proto, used) VALUES (?,?,?,0)", new_peer_list) self.db.executemany("INSERT OR IGNORE INTO peers (ip, port, proto, used) VALUES (?,?,?,0)", new_peer_list)
self.db.execute("DELETE FROM peers WHERE ip = ?", (config.external_ip,)) self.db.execute("DELETE FROM peers WHERE ip = ?", (utils.config.external_ip,))
def getUnusedPeers(self, nPeers): def getUnusedPeers(self, nPeers):
return self.db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 " return self.db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 "
"ORDER BY RANDOM() LIMIT ?", (nPeers,)) "ORDER BY RANDOM() LIMIT ?", (nPeers,))
def usePeer(self, id): def usePeer(self, id):
log('Updating peers database : using peer ' + str(id), 5) utils.log('Updating peers database : using peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,)) self.db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,))
def unusePeer(self, id): def unusePeer(self, id):
log('Updating peers database : unusing peer ' + str(id), 5) utils.log('Updating peers database : unusing peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,)) self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
import subprocess import subprocess
import utils
import os import os
def openvpn(*args, **kw): def openvpn(*args, **kw):
...@@ -15,9 +16,9 @@ def openvpn(*args, **kw): ...@@ -15,9 +16,9 @@ def openvpn(*args, **kw):
# '--ping', '1', # '--ping', '1',
# '--ping-exit', '3', # '--ping-exit', '3',
'--group', 'nogroup', '--group', 'nogroup',
'--verb', str(config.verbose), '--verb', str(utils.config.verbose),
] + list(args) + config.openvpn_args ] + list(args) + utils.config.openvpn_args
if config.verbose >= 5: if utils.config.verbose >= 5:
print repr(args) print repr(args)
return subprocess.Popen(args, **kw) return subprocess.Popen(args, **kw)
...@@ -28,11 +29,11 @@ def server(ip, pipe_fd, *args, **kw): ...@@ -28,11 +29,11 @@ def server(ip, pipe_fd, *args, **kw):
return openvpn( return openvpn(
'--tls-server', '--tls-server',
'--mode', 'server', '--mode', 'server',
'--up', 'up-server %s/%u' % (ip, len(config.vifibnet)), '--up', 'up-server %s/%u' % (ip, len(utils.config.vifibnet)),
'--client-connect', 'client-connect ' + str(pipe_fd), '--client-connect', 'client-connect ' + str(pipe_fd),
'--client-disconnect', 'client-connect ' + str(pipe_fd), '--client-disconnect', 'client-connect ' + str(pipe_fd),
'--dh', config.dh, '--dh', utils.config.dh,
'--max-clients', str(config.max_clients), '--max-clients', str(utils.config.max_clients),
*args, **kw) *args, **kw)
def client(serverIp, pipe_fd, *args, **kw): def client(serverIp, pipe_fd, *args, **kw):
......
...@@ -2,7 +2,6 @@ import os, random ...@@ -2,7 +2,6 @@ import os, random
import openvpn import openvpn
import utils import utils
import db import db
from config import *
connection_dict = {} # to remember current connections we made 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',
...@@ -14,7 +13,7 @@ def startNewConnections(n, write_pipe): ...@@ -14,7 +13,7 @@ def startNewConnections(n, write_pipe):
utils.log('Establishing a connection with id %s (%s:%s)' % (peer_id, ip, port), 2) utils.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[peer_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' % (peer_id,)), stdout=os.open(os.path.join(utils.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(peer_id) peers_db.usePeer(peer_id)
...@@ -50,11 +49,11 @@ def refreshConnections(write_pipe): ...@@ -50,11 +49,11 @@ 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) - utils.config.client_count + utils.config.refresh_count)):
peer_id = random.choice(connection_dict.keys()) peer_id = random.choice(connection_dict.keys())
killConnection(peer_id) killConnection(peer_id)
except Exception: except Exception:
pass pass
# Establish new connections # Establish new connections
startNewConnections(config.client_count - len(connection_dict), write_pipe) startNewConnections(utils.config.client_count - len(connection_dict), write_pipe)
...@@ -2,6 +2,8 @@ import time ...@@ -2,6 +2,8 @@ import time
import argparse import argparse
from OpenSSL import crypto from OpenSSL import crypto
config = None
def log(message, verbose_level): def log(message, verbose_level):
if config.verbose >= verbose_level: if config.verbose >= verbose_level:
print time.strftime("%d-%m-%Y %H:%M:%S : " + message) print time.strftime("%d-%m-%Y %H:%M:%S : " + message)
......
...@@ -10,23 +10,23 @@ import tunnelmanager ...@@ -10,23 +10,23 @@ import tunnelmanager
def startBabel(**kw): def startBabel(**kw):
args = ['babeld', args = ['babeld',
'-C', 'redistribute local ip %s' % (config.internal_ip), '-C', 'redistribute local ip %s' % (utils.config.internal_ip),
'-C', 'redistribute local deny', '-C', 'redistribute local deny',
# Route VIFIB ip adresses # Route VIFIB ip adresses
'-C', 'in ip %s::/%u' % (utils.ipFromBin(config.vifibnet), len(config.vifibnet)), '-C', 'in ip %s::/%u' % (utils.ipFromBin(utils.config.vifibnet), len(utils.config.vifibnet)),
# Route only addresse in the 'local' network, # Route only addresse in the 'local' network,
# or other entire networks # or other entire networks
#'-C', 'in ip %s' % (config.internal_ip), #'-C', 'in ip %s' % (config.internal_ip),
#'-C', 'in ip ::/0 le %s' % network_mask, #'-C', 'in ip ::/0 le %s' % network_mask,
# Don't route other addresses # Don't route other addresses
'-C', 'in deny', '-C', 'in deny',
'-d', str(config.verbose), '-d', str(utils.config.verbose),
'-s', '-s',
] ]
if config.babel_state: if utils.config.babel_state:
args += '-S', config.babel_state args += '-S', utils.config.babel_state
args = args + ['vifibnet'] + list(tunnelmanager.free_interface_set) args = args + ['vifibnet'] + list(tunnelmanager.free_interface_set)
if config.verbose >= 5: if utils.config.verbose >= 5:
print args print args
return subprocess.Popen(args, **kw) return subprocess.Popen(args, **kw)
...@@ -46,17 +46,14 @@ def handle_message(msg): ...@@ -46,17 +46,14 @@ def handle_message(msg):
def main(): def main():
# Get arguments # Get arguments
utils.getConfig() utils.getConfig()
global config
from utils import config
openvpn.config = config
tunnelmanager.config = config
db.config = config
# Setup database # Setup database
tunnelmanager.peers_db = db.PeersDB(config.db) tunnelmanager.peers_db = db.PeersDB(utils.config.db)
# Launch babel on all interfaces. WARNING : you have to be root to start babeld # Launch babel on all interfaces. WARNING : you have to be root to start babeld
utils.log('Starting babel', 3) utils.log('Starting babel', 3)
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) babel = startBabel(stdout=os.open(os.path.join(utils.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 # Create and open read_only pipe to get connect/disconnect events from openvpn
utils.log('Creating pipe for openvpn events', 3) utils.log('Creating pipe for openvpn events', 3)
...@@ -65,14 +62,13 @@ def main(): ...@@ -65,14 +62,13 @@ def main():
# Establish connections # Establish connections
utils.log('Starting openvpn server', 3) utils.log('Starting openvpn server', 3)
serverProcess = openvpn.server(config.internal_ip, write_pipe, '--dev', 'vifibnet', serverProcess = openvpn.server(utils.config.internal_ip, write_pipe, '--dev', 'vifibnet',
stdout=os.open(os.path.join(config.log, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC)) stdout=os.open(os.path.join(utils.config.log, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
tunnelmanager.startNewConnections(config.client_count, write_pipe) tunnelmanager.startNewConnections(utils.config.client_count, write_pipe)
# Timed refresh initializing # Timed refresh initializing
next_refresh = time.time() + config.refresh_time next_refresh = time.time() + utils.config.refresh_time
# TODO: use peers_db.populate(100) every once in a while ?
# main loop # main loop
try: try:
while True: while True:
...@@ -83,7 +79,7 @@ def main(): ...@@ -83,7 +79,7 @@ def main():
if time.time() >= next_refresh: if time.time() >= next_refresh:
tunnelmanager.peers_db.populate(10) tunnelmanager.peers_db.populate(10)
tunnelmanager.refreshConnections(write_pipe) tunnelmanager.refreshConnections(write_pipe)
next_refresh = time.time() + config.refresh_time next_refresh = time.time() + utils.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