Exemplo n.º 1
0
def get_link(_, update):

    chat_id = update.message.chat.id

    salt = Config.instance().crypto_salt
    m = sha224(bytes(abs(chat_id)))
    m.update(salt.encode())

    postfix = m.hexdigest()

    conn = Config.instance().connection
    cur = conn.cursor()
    sql = """INSERT INTO links 
                    (hash, chat_id) 
              VALUES(%s, %s)"""
    try:
        cur.execute(sql, (postfix, abs(chat_id)))
        conn.commit()
    except psycopg2.IntegrityError:
        # Chat already exists but it's okay
        conn.rollback()

    update.message.reply_text('{}/statistic/{}'.format(
                                    Config.instance().server,
                                    postfix))
Exemplo n.º 2
0
    def require_args():

        cfg.add_argument('--net-heads', nargs='*', type=int, help='net heads')
        cfg.add_argument('--net-avgpool-size',
                         default=3,
                         type=int,
                         choices=[3, 5, 7],
                         help='Avgpool kernel size determined by inputs size')
Exemplo n.º 3
0
 def __init__(self):
     # open syslog and notice startup
     syslog.openlog('captiveportal', logoption=syslog.LOG_DAEMON, facility=syslog.LOG_LOCAL4)
     syslog.syslog(syslog.LOG_NOTICE, 'starting captiveportal background process')
     # handles to ipfw, arp the config and the internal administration
     self.ipfw = IPFW()
     self.arp = ARP()
     self.cnf = Config()
     self.db = DB()
     self._conf_zone_info = self.cnf.get_zones()
Exemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Used for REST API
        #wsgi = kwargs['wsgi']
        #wsgi.register(FlowModReceiver, self)

        self.logger = util.log.getLogger('ReferenceMonitor')
        self.logger.info('refmon: start')

        # retrieve command line arguments
        CONF = cfg.CONF

        log_file_path = CONF['refmon']['log']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.log = open(log_file, "w")
        else:
            self.log = None

        # configure flow mod logging
        log_file_path = CONF['refmon']['flowmodlog']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.flow_mod_log = open(log_file, "w")
        else:
            self.flow_mod_log = None

        # load config from file
        self.logger.info('refmon: load config')
        try:
            config_file_path = CONF['refmon']['config']
            config_file = os.path.abspath(config_file_path)
            self.config = Config(config_file)
        except InvalidConfigError as e:
            self.logger.info('refmon: invalid config ' + str(e))

        self.config.always_ready = CONF['refmon']['always_ready']

        # start controller
        if self.config.isMultiSwitchMode():
            self.controller = MultiSwitchController(self.config)
        elif self.config.isMultiTableMode():
            self.controller = MultiTableController(self.config)
        elif self.config.isOneSwitchMode():
            self.controller = OneSwitchController(self.config)

# this must be set before Server, which uses it.
        self.flow_mod_times = Queue()

        # start server receiving flowmod requests
        self.server = Server(self, self.config.server["IP"],
                             self.config.server["Port"],
                             self.config.server["key"])
        self.server.start()
Exemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('config', help='path of config file')
    args = parser.parse_args()

    # locate config file
    config_file = os.path.abspath(args.config)

    # start central sdx controller
    logger = util.log.getLogger('xctrl')
    logger.info('init')

    config = Config(config_file)

    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' + str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"], config.refmon["key"])

    if config.isMDSMode():
        if config.isMultiSwitchMode():
            controller = MDSmS(client, config)
            logger.info('mode MDSmS - OF v1.0')
        elif config.isMultiTableMode():
            controller = MDSmT(client, config)
            logger.info('mode MDSmT - OF v1.3')
    elif config.isSupersetsMode():
        if config.isMultiSwitchMode():
            controller = GSSmS(client, config)
            logger.info('mode GSSmS - OF v1.3')
        elif config.isMultiTableMode():
            controller = GSSmT(client, config)
            logger.info('mode GSSmT - OF v1.3')

    logger.info('start')
    controller.start()
Exemplo n.º 6
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     Conf.writeConfig(self.config.filename,
                      self.config)  # saves all data to save in config file
     for i in self.Process:
         i.runs = False  # gives all threads in process the stop signal
     self.sendToArduino(
         self.Arduino1,
         ["", "", "stop", ""])  # sends stop signal to arduinos
     self.sendToArduino(self.Arduino2, ["", "", "stop", ""])
     self.Arduino1.runs = False  # sends stop signal to arduino thread and waits for them to end
     self.Arduino1.join()
     self.Arduino2.runs = False
     self.Arduino2.join()
     print("Closed")
Exemplo n.º 7
0
def main():
	# Config class
	config = Config.Config('config/config.yaml')
	
	# Logger class
	logger = Logger.Logger(config.get('log'))
	# Start the logger
	logger.run()
	
	# Network class
	network = Network.Network({
		'ip_file': config.get('ip.file')
	}, logger)
	
	# GoDaddy class
	godaddy = GoDaddy.GoDaddy({
		'username': config.get('godaddy.username'),
		'password': config.get('godaddy.password'),
		'hostname': config.get('godaddy.hostname'),
		'type': config.get('godaddy.type'),
	}, logger, network)
	
	# Get the public IP
	ip = network.getPublicIP()
	
	if network.checkIpCache(ip) != 1:
		godaddy.updateDNS(ip)
	else:
		print("Everything is all good, mate")
Exemplo n.º 8
0
    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Used for REST API
        wsgi = kwargs['wsgi']
        wsgi.register(FlowModReceiver, self)

        self.logger = logging.getLogger('ReferenceMonitor')
        self.logger.info('refmon: start')

        # retrieve command line arguments
        CONF = cfg.CONF
        config_file_path = CONF['refmon']['config']
        instance = int(CONF['refmon']['instance'])

        config_file = os.path.abspath(config_file_path)

        # load config from file
        self.logger.info('refmon: load config')
        try:
            self.config = Config(config_file, instance)
        except InvalidConfigError as e:
            self.logger.info('refmon: invalid config ' + str(e))

        # start controller
        self.controller = MultiTableController(self.config)
Exemplo n.º 9
0
def main():
    # sleep(5) #added a sleep to avoid "Connection refused" or "404" errors
    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='the directory of the example')
    args = parser.parse_args()

    # locate config file
    base_path = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), "..",
                     "examples", args.dir, "config"))
    config_file = os.path.join(base_path, "sdx_global.cfg")
    # locate the monitor's flows configuration file
    access_control_flows_file = os.path.join(base_path,
                                             "access_control_flows.cfg")
    config = Config(config_file)

    if os.path.exists(access_control_flows_file):
        with file(access_control_flows_file) as f:
            flows = json.load(f)
    else:
        flows = {"access_control_flows": {}}

    # start umbrella fabric manager
    logger = util.log.getLogger('access-control')
    logger.info('init')

    # Keep it for now just in case we decide to send messages to Refmon
    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' +
                str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"],
                          config.refmon["key"])

    controller = AccessControl(config, flows, client, logger)
    logger.info('start')
    controller.start()
Exemplo n.º 10
0
def main():
    # sleep(5) #added a sleep to avoid "Connection refused" or "404" errors
    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='the directory of the example')
    args = parser.parse_args()

    # locate config file
    base_path = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), "..",
                     "examples", args.dir, "config"))
    config_file = os.path.join(base_path, "sdx_global.cfg")
    # locate the monitor's flows configuration file
    monitor_flows_file = os.path.join(base_path, "monitor_flows.cfg")
    config = Config(config_file)

    # start umbrella fabric manager
    logger = util.log.getLogger('monitor')
    logger.info('init')

    try:
        with file(monitor_flows_file) as f:
            flows = json.load(f)
    except IOError:
        flows = None
        logger.info("No file specified for initial flows.")

    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' +
                str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"],
                          config.refmon["key"])

    controller = Monitor(config, flows, client, logger)
    logger.info('start')
    controller.start()
Exemplo n.º 11
0
 def __init__(self):
     # open syslog and notice startup
     syslog.openlog('captiveportal', logoption=syslog.LOG_DAEMON)
     syslog.syslog(syslog.LOG_NOTICE, 'starting captiveportal background process')
     # handles to ipfw, arp the config and the internal administration
     self.ipfw = IPFW()
     self.arp = ARP()
     self.cnf = Config()
     self.db = DB()
     self._conf_zone_info = self.cnf.get_zones()
Exemplo n.º 12
0
    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Use REST API for Anomaly Detection for now
        wsgi = kwargs['wsgi']
        wsgi.register(AnomalyDetectionReceiver, self)

        self.logger = util.log.getLogger('ReferenceMonitor')
        self.logger.info('refmon: start')

        # retrieve command line arguments
        CONF = cfg.CONF

        log_file_path = CONF['refmon']['log']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.log = open(log_file, "w")
        else:
            self.log = None

        # configure flow mod logging
        log_file_path = CONF['refmon']['flowmodlog']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.flow_mod_log = open(log_file, "w")
        else:
            self.flow_mod_log = None

        # load config from file
        self.logger.info('refmon: load config')
        try:
            config_file_path = CONF['refmon']['config']
            config_file = os.path.abspath(config_file_path)
            self.config = Config(config_file)
        except InvalidConfigError as e:
            self.logger.info('refmon: invalid config '+str(e))
            # No sense to continue the execution             
            sys.exit()            

        self.config.always_ready = CONF['refmon']['always_ready']

        # start controller
        if self.config.isMultiSwitchMode():
            self.controller = MultiSwitchController(self.config)
        elif self.config.isMultiTableMode():
            self.controller = MultiTableController(self.config)
        elif self.config.isMultiHopMode():
			self.controller = MultiHopController(self.config)

	# this must be set before Server, which uses it.
        self.flow_mod_times = Queue()

        # start server receiving flowmod requests
        self.server = Server(self, self.config.server["IP"], self.config.server["Port"], self.config.server["key"])
        self.server.start()
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--file', default='tardy.json')
    parser.add_argument('-d', '--dump', action='store_true')
    parser.add_argument('-a', '--action')
    parser.add_argument('-t', '--test', action='store_true')
    parser.add_argument('-g', '--git', action='store_true')
    parser.add_argument('-l', '--last', action='store_true')
    parser.add_argument('-n', '--nocolour', action='store_true')
    parser.add_argument('-q', '--quiet', action='store_true')
    result = parser.parse_args()

    if result.dump:
        storage = Storage()
        print 'Dumping:', storage.filename
        storage.load()
        pprint.pprint(storage.data)
        return

    if result.last:
        storage = Storage()
        storage.load()
        print storage.data[result.file]['apps'][-1]
        return

    choices = ['update', 'delete', 'create', 'restart']
    if result.action not in choices:
        raise ValueError('--action must be one of %s' % ','.join(choices))

    if not result.file:
        raise ValueError('--file must be specified')

    config = Config(filename=result.file, test=result.test,
                    colour=result.nocolour, quiet=result.quiet)
    if result.git:
        config.git.clone()
        config.stackato.cwd = config.git.repo

    try:
        getattr(config.stackato, result.action)()
    finally:
        config.save()
Exemplo n.º 14
0
def is_enable_deployment():
    try:
        deploy = Config.get('deploy', {})
        servers = deploy.get('servers', [])

        for server in servers:
            if server and server.get('enable', False):
                return True
        return False
    except Exception as e:
        print("utils#is_enable_deployment raise Exception: " + str(e))
        return False
Exemplo n.º 15
0
def get_quiz(level, stage):
    level_obj = None
    stage_obj = None
    try:
        level_obj = Level.from_key(level)
        stage_obj = Stage(stage)
    except ValueError:
        return "予期しないリクエストを受けました", 400

    return render_template('index.j2',
                           config=Config(level_obj, stage_obj),
                           quiz=Quiz(level_obj.max_no, 5))
Exemplo n.º 16
0
 def __init__(self):
     self.window = tk.Tk()  # initialises main window
     self.window.title("GUI")
     self.window.resizable(0, 0)
     self.window.columnconfigure(0, weight=1)
     self.FrameLeft = frameLeft(self)
     self.FrameRight = frameRight(self)
     self.FrameLeft.frame.grid(row=0, column=0,
                               sticky="nsw")  # initialises info frame
     self.FrameRight.frame.grid(row=0, column=1,
                                sticky="nsew")  # initialises control frame
     self.log = None
     self.Process = list()  # list for handling threads
     self.startProcessAir = list(
     )  # list for the pneumatic controlled threads
     if makeLogFile:
         self.log = Log.LogFile('Test')
     if platform.system(
     ) == "Windows":  # sets window to appropriate size for os and initialises Arduinos to their
         # compatible ports
         self.Arduino1 = Ard.Arduino(self, name="Arduino 1", port='COM7')
         self.Arduino2 = Ard.Arduino(self, name="Arduino 2", port='COM6')
         self.window.geometry("800x480")
     else:
         self.Arduino1 = Ard.Arduino(self,
                                     name="Arduino 1",
                                     port='/dev/ttyACM0')
         self.Arduino2 = Ard.Arduino(self,
                                     name="Arduino 2",
                                     port='/dev/ttyACM1')
         self.window.attributes('-fullscreen', True)
         self.window.geometry("800x480")
         self.FrameLeft.startAirControl()
     try:
         self.config = Conf.openConfig(
             'GUI.config')  # trys to load existing config, else makes new
     except:
         self.config = Conf.Config('GUI.config')
     self.window.bind("<ButtonRelease-1>", self.getNumber)
Exemplo n.º 17
0
def main():
    Config('config.json')
    Config.add_connection(conn)

    token = Config.instance().token
    webhook = Config.instance().is_webhook

    setup = setup_server if webhook else setup_updater
    dp = setup(token)
    Config.add_dispatcher(dp)

    app.run()
Exemplo n.º 18
0
    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Used for REST API
        # wsgi = kwargs['wsgi']
        # wsgi.register(FlowModReceiver, self)

        self.logger = util.log.getLogger("ReferenceMonitor")
        self.logger.info("refmon: start")

        # retrieve command line arguments
        CONF = cfg.CONF

        log_file_path = CONF["refmon"]["log"]
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.log = open(log_file, "w")
        else:
            self.log = None

        # configure flow mod logging
        log_file_path = CONF["refmon"]["flowmodlog"]
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.flow_mod_log = open(log_file, "w")
        else:
            self.flow_mod_log = None

        # load config from file
        self.logger.info("refmon: load config")
        try:
            config_file_path = CONF["refmon"]["config"]
            config_file = os.path.abspath(config_file_path)
            self.config = Config(config_file)
        except InvalidConfigError as e:
            self.logger.info("refmon: invalid config " + str(e))

        self.config.always_ready = CONF["refmon"]["always_ready"]

        # start controller
        if self.config.isMultiSwitchMode():
            self.controller = MultiSwitchController(self.config)
        elif self.config.isMultiTableMode():
            self.controller = MultiTableController(self.config)

        # start server receiving flowmod requests
        self.server = Server(self, self.config.server["IP"], self.config.server["Port"], self.config.server["key"])
        self.server.start()

        self.flow_mod_times = Queue()
Exemplo n.º 19
0
def get_message(_, update):
    chat_id = abs(update.message.chat.id)
    text = update.message.text

    if not text:
        return

    conn = Config.instance().connection
    cur = conn.cursor()
    sql = """CREATE TABLE IF NOT EXISTS public.chat%s (w TEXT);"""
    cur.execute(sql, (chat_id, ))

    sql = """
    INSERT INTO public.chat{} (w) 
    SELECT lexeme FROM unnest(to_tsvector('russian', %s));
    """.format(chat_id)
    cur.execute(sql, (text, ))
    conn.commit()
Exemplo n.º 20
0
class TestConfigurationReaders(unittest.TestCase):
    configuration = config.Configuration()

    def setUp(self):
        os.environ['SEARCHCVE_MONGODB'] = 'testdb'
        os.environ['SEARCHCVE_MONGOHOST'] = 'localhost'
        os.environ['SEARCHCVE_MONGOPORT'] = '27017'
        os.environ['SEARCHCVE_CVESTARTYEAR'] = '2022'

    def test_MongoDB(self):
        dbname = 'testdb'
        self.assertEqual(self.configuration.getMongoDB(), dbname)

    def test_MongoHost(self):
        self.assertEqual(self.configuration.getMongoHost(), 'localhost')

    def test_MongoPort(self):
        self.assertEqual(self.configuration.getMongoPort(), '27017')

    def test_CVEStartYear(self):
        startyear = '2002'
        self.assertEqual(str((self.configuration.getCVEStartYear())),
                         startyear)
Exemplo n.º 21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('config', help='path of config file')
    args = parser.parse_args()

    # locate config file
    config_file = os.path.abspath(args.config)

    config = Config(config_file)
    lbalancer = IP_LBalancer(config)

    # start umbrella fabric manager
    logger = util.log.getLogger('uctrl')
    logger.info('init')

    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' +
                str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"],
                          config.refmon["key"])

    controller = Umbrella(config, client, logger, lbalancer)
    logger.info('start')
    controller.start()
    def __init__(self):
        # Call superconstructor
        super(self.__class__, self).__init__()

        # Main application
        self.app = 0

        # Model viewer
        self.model_viewer = 0

        # Load configuration
        self.config = Config.getConfig()

        # Create application
        self.app = Main_Application()

        # Initialize GUI
        self.initUI()

        self._loadAllCities()

        # Show GUI
        self.show()
Exemplo n.º 23
0
def setup_server(token):

    app.add_url_rule(Config.instance().hook_key,
                     'hook',
                     methods=['GET', 'POST'],
                     view_func=webhook_listener)

    bot = Bot(token)
    Config.add_bot(bot)

    s = bot.setWebhook(Config.instance().hook_url + Config.instance().hook_key,
                       certificate=open(Config.instance().cert, 'rb'))

    print('webhook setup ' + 'ok' if s else 'failed')

    dispatcher = Dispatcher(bot, None, workers=0)
    register_handlers(dispatcher)

    return dispatcher
Exemplo n.º 24
0
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
    overlay user web template package on installed default template, default template should be installed
    in /var/captiveportal/zone<zoneid>/htdocs/ first.
"""
import os
import sys
import zipfile
import StringIO
from lib import Config

if len(sys.argv) > 1:
    cnf = Config()
    zoneid = sys.argv[1]
    target_directory = '/var/captiveportal/zone%s/htdocs/' % zoneid
    template_data = cnf.fetch_template_data(sys.argv[1])
    if template_data is not None and len(template_data) > 20:
        print('overlay user template package for zone %s' % zoneid)
        zip_content = template_data.decode('base64')
        input_data = StringIO.StringIO(zip_content)
        with zipfile.ZipFile(input_data,
                             mode='r',
                             compression=zipfile.ZIP_DEFLATED) as zf_in:
            for zf_info in zf_in.infolist():
                if zf_info.filename[-1] != '/':
                    target_filename = '%s%s' % (target_directory,
                                                zf_info.filename)
                    file_target_directory = '/'.join(
Exemplo n.º 25
0
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
    overlay user web template package on installed default template, default template should be installed
    in /var/captiveportal/zone<zoneid>/htdocs/ first.
"""
import os
import sys
import zipfile
import StringIO
from lib import Config

if len(sys.argv) > 1:
    cnf = Config()
    zoneid = sys.argv[1]
    target_directory = '/var/captiveportal/zone%s/htdocs/' % zoneid
    template_data = cnf.fetch_template_data(sys.argv[1])
    if template_data is not None and len(template_data) > 20:
        print ('overlay user template package for zone %s' % zoneid)
        zip_content = template_data.decode('base64')
        input_data = StringIO.StringIO(zip_content)
        with zipfile.ZipFile(input_data, mode='r', compression=zipfile.ZIP_DEFLATED) as zf_in:
            for zf_info in zf_in.infolist():
                if zf_info.filename[-1] != '/':
                    target_filename = '%s%s' % (target_directory, zf_info.filename)
                    file_target_directory = '/'.join(target_filename.split('/')[:-1])
                    if not os.path.isdir(file_target_directory):
                        os.makedirs(file_target_directory)
                    with open(target_filename, 'wb') as f_out:
Exemplo n.º 26
0
class RefMon(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_3.OFP_VERSION]
    _CONTEXTS = { 'wsgi': WSGIApplication }

    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Use REST API for Anomaly Detection for now
        wsgi = kwargs['wsgi']
        wsgi.register(AnomalyDetectionReceiver, self)

        self.logger = util.log.getLogger('ReferenceMonitor')
        self.logger.info('refmon: start')

        # retrieve command line arguments
        CONF = cfg.CONF

        log_file_path = CONF['refmon']['log']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.log = open(log_file, "w")
        else:
            self.log = None

        # configure flow mod logging
        log_file_path = CONF['refmon']['flowmodlog']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.flow_mod_log = open(log_file, "w")
        else:
            self.flow_mod_log = None

        # load config from file
        self.logger.info('refmon: load config')
        try:
            config_file_path = CONF['refmon']['config']
            config_file = os.path.abspath(config_file_path)
            self.config = Config(config_file)
        except InvalidConfigError as e:
            self.logger.info('refmon: invalid config '+str(e))
            # No sense to continue the execution             
            sys.exit()            

        self.config.always_ready = CONF['refmon']['always_ready']

        # start controller
        if self.config.isMultiSwitchMode():
            self.controller = MultiSwitchController(self.config)
        elif self.config.isMultiTableMode():
            self.controller = MultiTableController(self.config)
        elif self.config.isMultiHopMode():
			self.controller = MultiHopController(self.config)

	# this must be set before Server, which uses it.
        self.flow_mod_times = Queue()

        # start server receiving flowmod requests
        self.server = Server(self, self.config.server["IP"], self.config.server["Port"], self.config.server["key"])
        self.server.start()

    def close(self):
        self.logger.info('refmon: stop')

        if self.log:
            self.log.close()
        if self.flow_mod_log:
            self.flow_mod_log.close()

        self.server.stop()

    @set_ev_cls(ofp_event.EventOFPStateChange, [MAIN_DISPATCHER, DEAD_DISPATCHER])
    def dp_state_change_handler(self, ev):
        datapath = ev.datapath

        if ev.state == MAIN_DISPATCHER:
            self.controller.switch_connect(datapath)
        elif ev.state == DEAD_DISPATCHER:
            self.controller.switch_disconnect(datapath)
        
    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        self.controller.packet_in(ev)

    @set_ev_cls(ofp_event.EventOFPBarrierReply, MAIN_DISPATCHER)
    def barrier_reply_handler(self, ev):
        datapath = ev.msg.datapath
        if self.controller.handle_barrier_reply(datapath):
            end_time = time()

            try:
                start_time = self.flow_mod_times.get_nowait()
            except Empty:
                pass

            if self.log:
                self.log.write(str(start_time) + " " + str(end_time) + " " + str(end_time - start_time) + "\n")

    def process_flow_mods(self, msg):
        self.flow_mod_times.put(time())

        self.logger.info('refmon: received flowmod request')

        # authorization
        if "auth_info" in msg:
            auth_info = msg["auth_info"]

            # TODO: FLANC authorization here
           
            origin = auth_info["participant"]

            if "flow_mods" in msg:

                flow_mods = msg["flow_mods"]
                # Flows from the participant come without the switch
                # The fabric controllers picks the switches where
                # they shall be installed
               
                participant = str(msg['auth_info']['participant']) 
                if participant in self.config.participants:                    
                    flow_mods = self.controller.distribute_participant_flows(flow_mods, self.config.participants[participant])

                 # flow mod logging
                if self.flow_mod_log:
                    self.flow_mod_log.write('BURST: ' + str(time()) + '\n')
                    self.flow_mod_log.write('PARTICIPANT: ' + str(msg['auth_info']['participant']) + '\n')
                    for flow_mod in flow_mods:
                        self.flow_mod_log.write(json.dumps(flow_mod) + '\n')
                    self.flow_mod_log.write('\n')

                self.logger.debug('BURST: ' + str(time()))
                self.logger.debug('PARTICIPANT: ' + str(msg['auth_info']['participant']))
                for flow_mod in flow_mods:
                    self.logger.debug('FLOWMOD from ' + str(origin) + ': ' + json.dumps(flow_mod))
                # push flow mods to the data plane
                for flow_mod in flow_mods:
                    if self.config.ofv == "1.0":
                        fm = OFP10FlowMod(self.config, origin, flow_mod)
                    elif self.config.ofv == "1.3":
                        fm = OFP13FlowMod(self.config, origin, flow_mod)
                    self.logger.debug("rule validated. match: " + str(fm.matches) + " table:" + str(fm.table) + " cookie:" + str(fm.cookie))
                    self.controller.process_flow_mod(fm)

    @set_ev_cls(ofp_event.EventOFPErrorMsg, MAIN_DISPATCHER)
    def error_msg_handler(self, ev):
        msg = ev.msg

        print 'error msg type 0x%x code 0x%x' % (msg.type, msg.code)
Exemplo n.º 27
0
class RefMon(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_3.OFP_VERSION]
    # REST API _CONTEXTS = { 'wsgi': WSGIApplication }

    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Used for REST API
        # wsgi = kwargs['wsgi']
        # wsgi.register(FlowModReceiver, self)

        self.logger = util.log.getLogger("ReferenceMonitor")
        self.logger.info("refmon: start")

        # retrieve command line arguments
        CONF = cfg.CONF

        log_file_path = CONF["refmon"]["log"]
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.log = open(log_file, "w")
        else:
            self.log = None

        # configure flow mod logging
        log_file_path = CONF["refmon"]["flowmodlog"]
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.flow_mod_log = open(log_file, "w")
        else:
            self.flow_mod_log = None

        # load config from file
        self.logger.info("refmon: load config")
        try:
            config_file_path = CONF["refmon"]["config"]
            config_file = os.path.abspath(config_file_path)
            self.config = Config(config_file)
        except InvalidConfigError as e:
            self.logger.info("refmon: invalid config " + str(e))

        self.config.always_ready = CONF["refmon"]["always_ready"]

        # start controller
        if self.config.isMultiSwitchMode():
            self.controller = MultiSwitchController(self.config)
        elif self.config.isMultiTableMode():
            self.controller = MultiTableController(self.config)

        # start server receiving flowmod requests
        self.server = Server(self, self.config.server["IP"], self.config.server["Port"], self.config.server["key"])
        self.server.start()

        self.flow_mod_times = Queue()

    def close(self):
        self.logger.info("refmon: stop")

        if self.log:
            self.log.close()
        if self.flow_mod_log:
            self.flow_mod_log.close()

        self.server.stop()

    @set_ev_cls(ofp_event.EventOFPStateChange, [MAIN_DISPATCHER, DEAD_DISPATCHER])
    def dp_state_change_handler(self, ev):
        datapath = ev.datapath

        if ev.state == MAIN_DISPATCHER:
            self.controller.switch_connect(datapath)
        elif ev.state == DEAD_DISPATCHER:
            self.controller.switch_disconnect(datapath)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        self.controller.packet_in(ev)

    @set_ev_cls(ofp_event.EventOFPBarrierReply, MAIN_DISPATCHER)
    def barrier_reply_handler(self, ev):
        datapath = ev.msg.datapath
        if self.controller.handle_barrier_reply(datapath):
            end_time = time()

            try:
                start_time = self.flow_mod_times.get_nowait()
            except Empty:
                pass

            if self.log:
                self.log.write(str(start_time) + " " + str(end_time) + " " + str(end_time - start_time) + "\n")

    def process_flow_mods(self, msg):
        self.flow_mod_times.put(time())

        self.logger.info("refmon: received flowmod request")

        # authorization
        if "auth_info" in msg:
            auth_info = msg["auth_info"]

            # TODO: FLANC authorization here

            origin = auth_info["participant"]

            if "flow_mods" in msg:

                # flow mod logging
                if self.flow_mod_log:
                    self.flow_mod_log.write("BURST: " + str(time()) + "\n")
                    self.flow_mod_log.write("PARTICIPANT: " + str(msg["auth_info"]["participant"]) + "\n")
                    for flow_mod in msg["flow_mods"]:
                        self.flow_mod_log.write(json.dumps(flow_mod) + "\n")
                    self.flow_mod_log.write("\n")

                # push flow mods to the data plane
                self.logger.info("refmon: process " + str(len(msg["flow_mods"])) + " flowmods from " + str(origin))
                for flow_mod in msg["flow_mods"]:
                    if self.config.ofv == "1.0":
                        fm = OFP10FlowMod(self.config, origin, flow_mod)
                    elif self.config.ofv == "1.3":
                        fm = OFP13FlowMod(self.config, origin, flow_mod)

                    self.controller.process_flow_mod(fm)
Exemplo n.º 28
0
class RefMon(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_3.OFP_VERSION]

    # REST API _CONTEXTS = { 'wsgi': WSGIApplication }

    def __init__(self, *args, **kwargs):
        super(RefMon, self).__init__(*args, **kwargs)

        # Used for REST API
        #wsgi = kwargs['wsgi']
        #wsgi.register(FlowModReceiver, self)

        self.logger = util.log.getLogger('ReferenceMonitor')
        self.logger.info('refmon: start')

        # retrieve command line arguments
        CONF = cfg.CONF

        log_file_path = CONF['refmon']['log']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.log = open(log_file, "w")
        else:
            self.log = None

        # configure flow mod logging
        log_file_path = CONF['refmon']['flowmodlog']
        if log_file_path is not None:
            log_file = os.path.abspath(log_file_path)
            self.flow_mod_log = open(log_file, "w")
        else:
            self.flow_mod_log = None

        # load config from file
        self.logger.info('refmon: load config')
        try:
            config_file_path = CONF['refmon']['config']
            config_file = os.path.abspath(config_file_path)
            self.config = Config(config_file)
        except InvalidConfigError as e:
            self.logger.info('refmon: invalid config ' + str(e))

        self.config.always_ready = CONF['refmon']['always_ready']

        # start controller
        if self.config.isMultiSwitchMode():
            self.controller = MultiSwitchController(self.config)
        elif self.config.isMultiTableMode():
            self.controller = MultiTableController(self.config)

# this must be set before Server, which uses it.
        self.flow_mod_times = Queue()

        # start server receiving flowmod requests
        self.server = Server(self, self.config.server["IP"],
                             self.config.server["Port"],
                             self.config.server["key"])
        self.server.start()

    def close(self):
        self.logger.info('refmon: stop')

        if self.log:
            self.log.close()
        if self.flow_mod_log:
            self.flow_mod_log.close()

        self.server.stop()

    @set_ev_cls(ofp_event.EventOFPStateChange,
                [MAIN_DISPATCHER, DEAD_DISPATCHER])
    def dp_state_change_handler(self, ev):
        datapath = ev.datapath

        if ev.state == MAIN_DISPATCHER:
            self.controller.switch_connect(datapath)
        elif ev.state == DEAD_DISPATCHER:
            self.controller.switch_disconnect(datapath)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        self.controller.packet_in(ev)

    @set_ev_cls(ofp_event.EventOFPBarrierReply, MAIN_DISPATCHER)
    def barrier_reply_handler(self, ev):
        datapath = ev.msg.datapath
        if self.controller.handle_barrier_reply(datapath):
            end_time = time()

            try:
                start_time = self.flow_mod_times.get_nowait()
            except Empty:
                pass

            if self.log:
                self.log.write(
                    str(start_time) + " " + str(end_time) + " " +
                    str(end_time - start_time) + "\n")

    def process_flow_mods(self, msg):
        self.flow_mod_times.put(time())

        self.logger.info('refmon: received flowmod request')

        # authorization
        if "auth_info" in msg:
            auth_info = msg["auth_info"]

            # TODO: FLANC authorization here

            origin = auth_info["participant"]

            if "flow_mods" in msg:

                # flow mod logging
                if self.flow_mod_log:
                    self.flow_mod_log.write('BURST: ' + str(time()) + '\n')
                    self.flow_mod_log.write(
                        'PARTICIPANT: ' +
                        str(msg['auth_info']['participant']) + '\n')
                    for flow_mod in msg["flow_mods"]:
                        self.flow_mod_log.write(json.dumps(flow_mod) + '\n')
                    self.flow_mod_log.write('\n')

                self.logger.debug('BURST: ' + str(time()))
                self.logger.debug('PARTICIPANT: ' +
                                  str(msg['auth_info']['participant']))
                for flow_mod in msg["flow_mods"]:
                    self.logger.debug('FLOWMOD from ' + str(origin) + ': ' +
                                      json.dumps(flow_mod))

                # push flow mods to the data plane
                for flow_mod in msg["flow_mods"]:
                    if self.config.ofv == "1.0":
                        fm = OFP10FlowMod(self.config, origin, flow_mod)
                    elif self.config.ofv == "1.3":
                        fm = OFP13FlowMod(self.config, origin, flow_mod)
                    self.controller.process_flow_mod(fm)
Exemplo n.º 29
0
def main():
    syslog.syslog(syslog.LOG_ERR, 'starting captiveportal background process')
    # handle to ipfw, arp and the config
    ipfw = IPFW()
    arp = ARP()
    cnf = Config()
    while True:
        try:
            # construct objects
            db = DB()

            # update accounting info
            db.update_accounting_info(ipfw.list_accounting_info())

            # process sessions per zone
            arp.reload()
            cpzones = cnf.get_zones()
            for zoneid in cpzones:
                registered_addresses = ipfw.list_table(zoneid)
                registered_add_accounting = ipfw.list_accounting_info()
                expected_clients = db.list_clients(zoneid)
                # handle connected clients, timeouts, address changes, etc.
                for db_client in expected_clients:
                    # fetch ip address (or network) from database
                    cpnet = db_client['ipAddress'].strip()

                    # there are different reasons why a session should be removed, check for all reasons and
                    # use the same method for the actual removal
                    drop_session = False

                    # todo, static ip and addresses shouldn't be affected by the timeout rules below.
                    # check if hardtimeout is set and overrun for this session
                    if 'hardtimeout' in cpzones[zoneid] and str(cpzones[zoneid]['hardtimeout']).isdigit():
                        # hardtimeout should be set and we should have collected some session data from the client
                        if int(cpzones[zoneid]['hardtimeout']) > 0  and float(db_client['startTime']) > 0:
                            if (time.time() - float(db_client['startTime'])) / 60 > int(cpzones[zoneid]['hardtimeout']):
                                drop_session = True

                    # check if idletimeout is set and overrun for this session
                    if 'idletimeout' in cpzones[zoneid] and str(cpzones[zoneid]['idletimeout']).isdigit():
                        # idletimeout should be set and we should have collected some session data from the client
                        if int(cpzones[zoneid]['idletimeout']) > 0 and float(db_client['last_accessed']) > 0:
                            if (time.time() - float(db_client['last_accessed'])) / 60 > int(cpzones[zoneid]['idletimeout']):
                                drop_session = True

                    # check session, if it should be active, validate its properties
                    if not drop_session:
                        # registered client, but not active according to ipfw (after reboot)
                        if cpnet not in registered_addresses:
                            ipfw.add_to_table(zoneid, cpnet)

                        # is accounting rule still available? need to reapply after reload / reboot
                        if cpnet not in registered_add_accounting and db_client['ipAddress'] not in registered_add_accounting:
                            ipfw.add_accounting(cpnet)
                    else:
                        # remove session
                        db.del_client(zoneid, db_client['sessionId'])
                        ipfw.delete_from_table(zoneid, cpnet)
                        ipfw.del_accounting(cpnet)

            # cleanup, destruct
            del db

            # sleep
            time.sleep(5)
        except KeyboardInterrupt:
            break
        except SystemExit:
            break
        except:
            syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
Exemplo n.º 30
0
def replace_ip(network, ip):
    net, subnet = network.split('/')
    gw = net.split('.')
    gw[3] = ip
    gw = '.'.join(gw)
    gw = '/'.join([gw, subnet])
    return gw

if __name__ == "__main__":
    setLogLevel('info')

    parser = argparse.ArgumentParser()
    parser.add_argument('config', help='path of config file', nargs='?', default= default_isdx_config)
    args = parser.parse_args()

    # locate config file
    config_file = os.path.abspath(args.config)

    config = Config(config_file)

    net = Mininet(switch=OVSSwitch)
    net.addController( 'c0', controller=RemoteController, ip='127.0.0.1', port= 6633)
    create_topo(net, config)
    net.start()

    CLI(net)

    net.stop()

    info("done\n")
Exemplo n.º 31
0
                loader=FileSystemLoader(template_directory),
                autoescape=select_autoescape(['html', 'xml']))
            self.template = template_environment.get_template(template_file)

    def render_template(self, *args, **kwargs):
        """
            Render the loaded template and write it to <output_file>.
        """
        data_dict = kwargs.get('data_dict', {})

        rendered_template = self.template.render(**kwargs)

        return rendered_template


confs = conf.Configuration()
sender = confs.getMailSender()
host = confs.getMailHost()
port = confs.getMailPort()
username = confs.getMailUsername()
password = confs.getMailPassword()
tls = confs.getMailTls()

mailer = Mailer(
    dict(transport=dict(use='smtp',
                        host=host,
                        port=port,
                        tls=tls,
                        username=username,
                        password=password)))
Exemplo n.º 32
0
    def require_args():

        cfg.add_argument('--net-heads', nargs='*', type=int, help='net heads')
Exemplo n.º 33
0
 def __init__(self):
     self.script_path = os.path.dirname(os.path.realpath(__file__))
     self.arguments = Config(self.script_path)
     self.controller = Controller(self.script_path, self.arguments)
Exemplo n.º 34
0
class CPBackgroundProcess(object):
    """ background process helper class
    """
    def __init__(self):
        # open syslog and notice startup
        syslog.openlog('captiveportal', logoption=syslog.LOG_DAEMON)
        syslog.syslog(syslog.LOG_NOTICE, 'starting captiveportal background process')
        # handles to ipfw, arp the config and the internal administration
        self.ipfw = IPFW()
        self.arp = ARP()
        self.cnf = Config()
        self.db = DB()
        self._conf_zone_info = self.cnf.get_zones()

    def list_zone_ids(self):
        """ return zone numbers
        """
        return self._conf_zone_info.keys()

    def initialize_fixed(self):
        """ initialize fixed ip / hosts per zone
        """
        cpzones = self._conf_zone_info
        for zoneid in cpzones:
            for conf_section in ['allowedaddresses', 'allowedmacaddresses']:
                for address in cpzones[zoneid][conf_section]:
                    if conf_section.find('mac') == -1:
                        sessions = self.db.sessions_per_address(zoneid, ip_address=address)
                        ip_address = address
                        mac_address = None
                    else:
                        sessions = self.db.sessions_per_address(zoneid, mac_address=address)
                        ip_address = None
                        mac_address = address
                    sessions_deleted = 0
                    for session in sessions:
                        if session['authenticated_via'] not in ('---ip---', '---mac---'):
                            sessions_deleted += 1
                            self.db.del_client(zoneid, session['sessionId'])
                    if sessions_deleted == len(sessions) or len(sessions) == 0:
                        # when there's no session active, add a new one
                        # (only administrative, the sync process will add it if neccesary)
                        if ip_address is not None:
                            self.db.add_client(zoneid, "---ip---", "", ip_address, "")
                        else:
                            self.db.add_client(zoneid, "---mac---", "", "", mac_address)

            # cleanup removed static sessions
            for dbclient in self.db.list_clients(zoneid):
                if dbclient['authenticated_via'] == '---ip---' \
                    and dbclient['ipAddress'] not in cpzones[zoneid]['allowedaddresses']:
                        self.ipfw.delete(zoneid, dbclient['ipAddress'])
                        self.db.del_client(zoneid, dbclient['sessionId'])
                elif dbclient['authenticated_via'] == '---mac---' \
                    and dbclient['macAddress'] not in cpzones[zoneid]['allowedmacaddresses']:
                        if dbclient['ipAddress']  != '':
                            self.ipfw.delete(zoneid, dbclient['ipAddress'])
                        self.db.del_client(zoneid, dbclient['sessionId'])

    def sync_zone(self, zoneid):
        """ Synchronize captiveportal zone.
            Handles timeouts and administrative changes to this zones sessions
        """
        if zoneid in self._conf_zone_info:
            # fetch data for this zone
            cpzone_info = self._conf_zone_info[zoneid]
            registered_addresses = self.ipfw.list_table(zoneid)
            registered_addr_accounting = self.ipfw.list_accounting_info()
            expected_clients = self.db.list_clients(zoneid)
            concurrent_users = self.db.find_concurrent_user_sessions(zoneid)

            # handle connected clients, timeouts, address changes, etc.
            for db_client in expected_clients:
                # fetch ip address (or network) from database
                cpnet = db_client['ipAddress'].strip()

                # there are different reasons why a session should be removed, check for all reasons and
                # use the same method for the actual removal
                drop_session_reason = None

                # session cleanups, only for users not for static hosts/ranges.
                if db_client['authenticated_via'] not in ('---ip---', '---mac---'):
                    # check if hardtimeout is set and overrun for this session
                    if 'hardtimeout' in cpzone_info and str(cpzone_info['hardtimeout']).isdigit():
                        # hardtimeout should be set and we should have collected some session data from the client
                        if int(cpzone_info['hardtimeout']) > 0  and float(db_client['startTime']) > 0:
                            if (time.time() - float(db_client['startTime'])) / 60 > int(cpzone_info['hardtimeout']):
                                drop_session_reason = "session %s hit hardtimeout" % db_client['sessionId']

                    # check if idletimeout is set and overrun for this session
                    if 'idletimeout' in cpzone_info and str(cpzone_info['idletimeout']).isdigit():
                        # idletimeout should be set and we should have collected some session data from the client
                        if int(cpzone_info['idletimeout']) > 0 and float(db_client['last_accessed']) > 0:
                            if (time.time() - float(db_client['last_accessed'])) / 60 > int(cpzone_info['idletimeout']):
                                drop_session_reason = "session %s hit idletimeout" % db_client['sessionId']

                    # cleanup concurrent users
                    if 'concurrentlogins' in cpzone_info and int(cpzone_info['concurrentlogins']) == 0:
                        if db_client['sessionId'] in concurrent_users:
                            drop_session_reason = "remove concurrent session %s" % db_client['sessionId']

                    # if mac address changes, drop session. it's not the same client
                    current_arp = self.arp.get_by_ipaddress(cpnet)
                    if current_arp is not None and current_arp['mac'] != db_client['macAddress']:
                        drop_session_reason = "mac address changed for session %s" % db_client['sessionId']
                elif db_client['authenticated_via'] == '---mac---':
                    # detect mac changes
                    current_ip = self.arp.get_address_by_mac(db_client['macAddress'])
                    if current_ip != None:
                        if db_client['ipAddress'] != '':
                            # remove old ip
                            self.ipfw.delete(zoneid, db_client['ipAddress'])
                        self.db.update_client_ip(zoneid, db_client['sessionId'], current_ip)
                        self.ipfw.add_to_table(zoneid, current_ip)
                        self.ipfw.add_accounting(current_ip)

                # check session, if it should be active, validate its properties
                if drop_session_reason is None:
                    # registered client, but not active according to ipfw (after reboot)
                    if cpnet not in registered_addresses:
                        self.ipfw.add_to_table(zoneid, cpnet)

                    # is accounting rule still available? need to reapply after reload / reboot
                    if cpnet not in registered_addr_accounting:
                        self.ipfw.add_accounting(cpnet)
                else:
                    # remove session
                    syslog.syslog(syslog.LOG_NOTICE, drop_session_reason)
                    self.ipfw.delete(zoneid, cpnet)
                    self.db.del_client(zoneid, db_client['sessionId'])

            # if there are addresses/networks in the underlying ipfw table which are not in our administration,
            # remove them from ipfw.
            for registered_address in registered_addresses:
                address_active = False
                for db_client in expected_clients:
                    if registered_address == db_client['ipAddress']:
                        address_active = True
                        break
                if not address_active:
                    self.ipfw.delete(zoneid, registered_address)
Exemplo n.º 35
0
def require_args():

    # args for training
    cfg.add_argument('--max-epochs',
                     default=200,
                     type=int,
                     help='maximal training epoch')
    cfg.add_argument('--display-freq',
                     default=80,
                     type=int,
                     help='log display frequency')
    cfg.add_argument('--batch-size',
                     default=256,
                     type=int,
                     help='size of mini-batch')
    cfg.add_argument('--num-workers',
                     default=4,
                     type=int,
                     help='number of workers used for loading data')
    cfg.add_argument('--data-nrepeat',
                     default=1,
                     type=int,
                     help='how many times each image in a ' +
                     'mini-batch should be repeated')
    cfg.add_argument('--pica-lamda',
                     default=2.0,
                     type=float,
                     help='weight of negative entropy regularisation')
Exemplo n.º 36
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import os
import sys
import hashlib

root_path = os.path.sep.join([os.path.split(os.path.realpath(__file__))[0], '..'])

sys.path.append(root_path)
from lib import Config

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='example: python %s -p password' % os.path.basename(__file__))
    parser.add_argument('-p', '--password', help='password', required=True)
    args = parser.parse_args()

    password_slat = Config.get('salt', '') + args.password

    print(hashlib.md5(password_slat.encode()).hexdigest())
Exemplo n.º 37
0
class CPBackgroundProcess(object):
    """ background process helper class
    """
    def __init__(self):
        # open syslog and notice startup
        syslog.openlog('captiveportal', logoption=syslog.LOG_DAEMON, facility=syslog.LOG_LOCAL4)
        syslog.syslog(syslog.LOG_NOTICE, 'starting captiveportal background process')
        # handles to ipfw, arp the config and the internal administration
        self.ipfw = IPFW()
        self.arp = ARP()
        self.cnf = Config()
        self.db = DB()
        self._conf_zone_info = self.cnf.get_zones()

    def list_zone_ids(self):
        """ return zone numbers
        """
        return self._conf_zone_info.keys()

    def initialize_fixed(self):
        """ initialize fixed ip / hosts per zone
        """
        cpzones = self._conf_zone_info
        for zoneid in cpzones:
            for conf_section in ['allowedaddresses', 'allowedmacaddresses']:
                for address in cpzones[zoneid][conf_section]:
                    if conf_section.find('mac') == -1:
                        sessions = self.db.sessions_per_address(zoneid, ip_address=address)
                        ip_address = address
                        mac_address = None
                    else:
                        sessions = self.db.sessions_per_address(zoneid, mac_address=address)
                        ip_address = None
                        mac_address = address
                    sessions_deleted = 0
                    for session in sessions:
                        if session['authenticated_via'] not in ('---ip---', '---mac---'):
                            sessions_deleted += 1
                            self.db.del_client(zoneid, session['sessionId'])
                    if sessions_deleted == len(sessions) or len(sessions) == 0:
                        # when there's no session active, add a new one
                        # (only administrative, the sync process will add it if neccesary)
                        if ip_address is not None:
                            self.db.add_client(zoneid, "---ip---", "", ip_address, "")
                        else:
                            self.db.add_client(zoneid, "---mac---", "", "", mac_address)

            # cleanup removed static sessions
            for dbclient in self.db.list_clients(zoneid):
                if dbclient['authenticated_via'] == '---ip---' \
                        and dbclient['ipAddress'] not in cpzones[zoneid]['allowedaddresses']:
                        self.ipfw.delete(zoneid, dbclient['ipAddress'])
                        self.db.del_client(zoneid, dbclient['sessionId'])
                elif dbclient['authenticated_via'] == '---mac---' \
                        and dbclient['macAddress'] not in cpzones[zoneid]['allowedmacaddresses']:
                        if dbclient['ipAddress'] != '':
                            self.ipfw.delete(zoneid, dbclient['ipAddress'])
                        self.db.del_client(zoneid, dbclient['sessionId'])

    def sync_zone(self, zoneid):
        """ Synchronize captiveportal zone.
            Handles timeouts and administrative changes to this zones sessions
        """
        if zoneid in self._conf_zone_info:
            # fetch data for this zone
            cpzone_info = self._conf_zone_info[zoneid]
            registered_addresses = self.ipfw.list_table(zoneid)
            registered_addr_accounting = self.ipfw.list_accounting_info()
            expected_clients = self.db.list_clients(zoneid)
            concurrent_users = self.db.find_concurrent_user_sessions(zoneid)

            # handle connected clients, timeouts, address changes, etc.
            for db_client in expected_clients:
                # fetch ip address (or network) from database
                cpnet = db_client['ipAddress'].strip()

                # there are different reasons why a session should be removed, check for all reasons and
                # use the same method for the actual removal
                drop_session_reason = None

                # session cleanups, only for users not for static hosts/ranges.
                if db_client['authenticated_via'] not in ('---ip---', '---mac---'):
                    # check if hardtimeout is set and overrun for this session
                    if 'hardtimeout' in cpzone_info and str(cpzone_info['hardtimeout']).isdigit():
                        # hardtimeout should be set and we should have collected some session data from the client
                        if int(cpzone_info['hardtimeout']) > 0 and float(db_client['startTime']) > 0:
                            if (time.time() - float(db_client['startTime'])) / 60 > int(cpzone_info['hardtimeout']):
                                drop_session_reason = "session %s hit hardtimeout" % db_client['sessionId']

                    # check if idletimeout is set and overrun for this session
                    if 'idletimeout' in cpzone_info and str(cpzone_info['idletimeout']).isdigit():
                        # idletimeout should be set and we should have collected some session data from the client
                        if int(cpzone_info['idletimeout']) > 0 and float(db_client['last_accessed']) > 0:
                            if (time.time() - float(db_client['last_accessed'])) / 60 > int(cpzone_info['idletimeout']):
                                drop_session_reason = "session %s hit idletimeout" % db_client['sessionId']

                    # cleanup concurrent users
                    if 'concurrentlogins' in cpzone_info and int(cpzone_info['concurrentlogins']) == 0:
                        if db_client['sessionId'] in concurrent_users:
                            drop_session_reason = "remove concurrent session %s" % db_client['sessionId']

                    # if mac address changes, drop session. it's not the same client
                    current_arp = self.arp.get_by_ipaddress(cpnet)
                    if current_arp is not None and current_arp['mac'] != db_client['macAddress']:
                        drop_session_reason = "mac address changed for session %s" % db_client['sessionId']

                    # session accounting
                    if db_client['acc_session_timeout'] is not None \
                            and time.time() - float(db_client['startTime']) > db_client['acc_session_timeout']:
                            drop_session_reason = "accounting limit reached for session %s" % db_client['sessionId']
                elif db_client['authenticated_via'] == '---mac---':
                    # detect mac changes
                    current_ip = self.arp.get_address_by_mac(db_client['macAddress'])
                    if current_ip is not None:
                        if db_client['ipAddress'] != '':
                            # remove old ip
                            self.ipfw.delete(zoneid, db_client['ipAddress'])
                        self.db.update_client_ip(zoneid, db_client['sessionId'], current_ip)
                        self.ipfw.add_to_table(zoneid, current_ip)
                        self.ipfw.add_accounting(current_ip)

                # check session, if it should be active, validate its properties
                if drop_session_reason is None:
                    # registered client, but not active according to ipfw (after reboot)
                    if cpnet not in registered_addresses:
                        self.ipfw.add_to_table(zoneid, cpnet)

                    # is accounting rule still available? need to reapply after reload / reboot
                    if cpnet not in registered_addr_accounting:
                        self.ipfw.add_accounting(cpnet)
                else:
                    # remove session
                    syslog.syslog(syslog.LOG_NOTICE, drop_session_reason)
                    self.ipfw.delete(zoneid, cpnet)
                    self.db.del_client(zoneid, db_client['sessionId'])

            # if there are addresses/networks in the underlying ipfw table which are not in our administration,
            # remove them from ipfw.
            for registered_address in registered_addresses:
                address_active = False
                for db_client in expected_clients:
                    if registered_address == db_client['ipAddress']:
                        address_active = True
                        break
                if not address_active:
                    self.ipfw.delete(zoneid, registered_address)
Exemplo n.º 38
0
        self.curr_piece().about_piece()
        
    #Display a textual version of the game board
    def display_board(self, hide_column_count = 0, coordinates_only = False):
        print("Lines: {0:>3} Score: {1:>6}".format(self.line_count, self.score))
        for y in range(self.num_columns-1-hide_column_count, 0, -1):
            line = ""
            for x in range(self.num_rows): 
                if coordinates_only: line += "({},{})".format(x, y)
                elif self.not_empty((x,y)): line += "X"
                else: line += "_"
            print(line)

if __name__ == "__main__":
    #Perform tests and learn the syntax
    config = Config("CLASSIC_TETRIS")
    
    num_rows = config.num_rows 
    num_cols = config.num_columns
    display_cols = config.hide_column_count
    test_game_board = GameBoard(num_rows, num_cols)
    
    
    """
    #Place part of a line at 4, 2
    test_coordinates = (4, 2)
    test_game_board.set(test_coordinates, "LINE")
    """
    """
    #Place multiple pieces without colision
    #test_game_board.place_block("Z-PIECE", (7,0))