Пример #1
0
  def _flow_mod_add (self, flow_mod, connection, table):
    """
    Process an OFPFC_ADD flow mod sent to the switch.
    """
    match = flow_mod.match
    priority = flow_mod.priority

    if flow_mod.flags & OFPFF_EMERG:
      if flow_mod.idle_timeout != 0 or flow_mod.hard_timeout != 0:
        # Emergency flow mod has non-zero timeouts. Do not add.
        self.log.warn("Rejecting emergency flow with nonzero timeout")
        self.send_error(type=OFPET_FLOW_MOD_FAILED,
                        code=OFPFMFC_BAD_EMERG_TIMEOUT,
                        ofp=flow_mod, connection=connection)
        return
      if flow_mod.flags & OFPFF_SEND_FLOW_REM:
        # Emergency flows can't send removal messages, we we might want to
        # reject this early.  Sadly, there's no error code for this, so we just
        # abuse EPERM.  If we eventually support Nicira extended error codes,
        # we should use one here.
        self.log.warn("Rejecting emergency flow with flow removal flag")
        self.send_error(type=OFPET_FLOW_MOD_FAILED,
                        code=OFPFMFC_EPERM,
                        ofp=flow_mod, connection=connection)
        return
      #NOTE: An error is sent anyways because the current implementation does
      #      not support emergency entries.
      self.log.warn("Rejecting emergency flow (not supported)")
      self.send_error(type=OFPET_FLOW_MOD_FAILED,
                      code=OFPFMFC_ALL_TABLES_FULL,
                      ofp=flow_mod, connection=connection)
      return
    #FELIPE TOMM - TCC
    #AQUI CHAMA A FUNCAO QUE VERIFICA SE JA EXISTE UMA REGRA IGUAL
    new_entry = TableEntry.from_flow_mod(flow_mod)
    log = core.getLogger()
    log.debug("Entrou _FLOW_MOD_ADD")
    if flow_mod.flags & OFPFF_CHECK_OVERLAP:
      log.debug("Entrou _FLOW_MOD_ADD - 1 if")
      if table.check_for_overlapping_entry(new_entry):
        # Another entry overlaps. Do not add.
        log.debug("Entrou _FLOW_MOD_ADD - 1 if")
        self.send_error(type=OFPET_FLOW_MOD_FAILED, code=OFPFMFC_OVERLAP,
                        ofp=flow_mod, connection=connection)
        return

    if flow_mod.command == OFPFC_ADD:
      # Exactly matching entries have to be removed if OFPFC_ADD
      table.remove_matching_entries(match, priority=priority, strict=True)

    if len(table) >= self.max_entries:
      # Flow table is full. Respond with error message.
      self.send_error(type=OFPET_FLOW_MOD_FAILED,
                      code=OFPFMFC_ALL_TABLES_FULL,
                      ofp=flow_mod, connection=connection)
      return

    table.add_entry(new_entry)
Пример #2
0
def _do_launch(argv):
    component_order = []
    components = {}

    curargs = {}
    pox_options = curargs

    for arg in argv:
        if not arg.startswith("-"):
            if arg not in components:
                components[arg] = []
            curargs = {}
            components[arg].append(curargs)
            component_order.append(arg)
        else:
            arg = arg.lstrip("-").split("=", 1)
            arg[0] = arg[0].replace("-", "_")
            if len(arg) == 1: arg.append(True)
            curargs[arg[0]] = arg[1]

    _options.process_options(pox_options)
    global core
    if pox.core.core is not None:
        core = pox.core.core
        core.getLogger('boot').debug('Using existing POX core')
    else:
        core = pox.core.initialize(_options.threaded_selecthub,
                                   _options.epoll_selecthub,
                                   _options.handle_signals)

    _pre_startup()
    modules = _do_imports(n.split(':')[0] for n in component_order)
    if modules is False:
        return False

    inst = {}
    for name in component_order:
        cname = name
        inst[name] = inst.get(name, -1) + 1
        params = components[name][inst[name]]
        name = name.split(":", 1)
        launch = name[1] if len(name) == 2 else "launch"
        name = name[0]

        name, module, members = modules[name]

        if launch in members:
            f = members[launch]
            # We explicitly test for a function and not an arbitrary callable
            if type(f) is not types.FunctionType:
                print(launch, "in", name, "isn't a function!")
                return False

            if getattr(f, '_pox_eval_args', False):
                import ast
                for k, v in params.items():
                    if isinstance(v, str):
                        try:
                            params[k] = ast.literal_eval(v)
                        except:
                            # Leave it as a string
                            pass

            multi = False
            if f.__code__.co_argcount > 0:
                #FIXME: This code doesn't look quite right to me and may be broken
                #       in some cases.  We should refactor to use inspect anyway,
                #       which should hopefully just fix it.
                if (f.__code__.co_varnames[f.__code__.co_argcount -
                                           1] == '__INSTANCE__'):
                    # It's a multi-instance-aware component.

                    multi = True

                    # Special __INSTANCE__ paramter gets passed a tuple with:
                    # 1. The number of this instance (0...n-1)
                    # 2. The total number of instances for this module
                    # 3. True if this is the last instance, False otherwise
                    # The last is just a comparison between #1 and #2, but it's
                    # convenient.
                    params['__INSTANCE__'] = (inst[cname],
                                              len(components[cname]),
                                              inst[cname] + 1 == len(
                                                  components[cname]))

            if multi == False and len(components[cname]) != 1:
                print(name, "does not accept multiple instances")
                return False

            try:
                if f(**params) is False:
                    # Abort startup
                    return False
            except TypeError as exc:
                instText = ''
                if inst[cname] > 0:
                    instText = "instance {0} of ".format(inst[cname] + 1)
                print("Error executing {2}{0}.{1}:".format(
                    name, launch, instText))
                if inspect.currentframe() is sys.exc_info()[2].tb_frame:
                    # Error is with calling the function
                    # Try to give some useful feedback
                    if _options.verbose:
                        traceback.print_exc()
                    else:
                        exc = sys.exc_info()[0:2]
                        print(''.join(traceback.format_exception_only(*exc)),
                              end='')
                    print()
                    EMPTY = "<Unspecified>"
                    code = f.__code__
                    argcount = code.co_argcount
                    argnames = code.co_varnames[:argcount]
                    defaults = list((f.func_defaults) or [])
                    defaults = [EMPTY] * (argcount - len(defaults)) + defaults
                    args = {}
                    for n, a in enumerate(argnames):
                        args[a] = [EMPTY, EMPTY]
                        if n < len(defaults):
                            args[a][0] = defaults[n]
                        if a in params:
                            args[a][1] = params[a]
                            del params[a]
                    if '__INSTANCE__' in args:
                        del args['__INSTANCE__']

                    if f.__doc__ is not None:
                        print("Documentation for {0}:".format(name))
                        doc = f.__doc__.split("\n")
                        #TODO: only strip the same leading space as was on the first
                        #      line
                        doc = map(str.strip, doc)
                        print('', ("\n ".join(doc)).strip())

                    #print(params)
                    #print(args)

                    print("Parameters for {0}:".format(name))
                    if len(args) == 0:
                        print(" None.")
                    else:
                        print(" {0:25} {1:25} {2:25}".format(
                            "Name", "Default", "Active"))
                        print(" {0:25} {0:25} {0:25}".format("-" * 15))

                        for k, v in args.iteritems():
                            print(" {0:25} {1:25} {2:25}".format(
                                k, str(v[0]),
                                str(v[1] if v[1] is not EMPTY else v[0])))

                    if len(params):
                        print(
                            "This component does not have a parameter named " +
                            "'{0}'.".format(params.keys()[0]))
                        return False
                    missing = [
                        k for k, x in args.iteritems()
                        if x[1] is EMPTY and x[0] is EMPTY
                    ]
                    if len(missing):
                        print("You must specify a value for the '{0}' "
                              "parameter.".format(missing[0]))
                        return False

                    return False
                else:
                    # Error is inside the function
                    raise
        elif len(params) > 0 or launch is not "launch":
            print("Module %s has no %s(), but it was specified or passed " \
                  "arguments" % (name, launch))
            return False

    return True
from pox import core
from pox.lib.addresses import * 
from pox.lib.packet import *
from pox.lib.recoco.recoco import *
import re

# Get a logger
log = core.getLogger("fw")

class Firewall (object):
  """
  Firewall class.
  Extend this to implement some firewall functionality.
  Don't change the name or anything -- the eecore component
  expects it to be firewall.Firewall.
  """
  PRINT_BUFFERS = False
  TIMEOUT = 10
  BASIC_PORTS = 1024
  FTP_PORTS = 65536
  
  def __init__(self):
    """
    Constructor.
    Put your initialization code here.
    """
    
    #dictionary to hold all the monitoring data for the connections
    #K: Port number
    #V: Timer
    self.timers = {}
def _do_launch (argv):
  component_order = []
  components = {}

  curargs = {}
  pox_options = curargs

  for arg in argv:
    if not arg.startswith("-"):
      if arg not in components:
        components[arg] = []
      curargs = {}
      components[arg].append(curargs)
      component_order.append(arg)
    else:
      arg = arg.lstrip("-").split("=", 1)
      arg[0] = arg[0].replace("-", "_")
      if len(arg) == 1: arg.append(True)
      curargs[arg[0]] = arg[1]

  _options.process_options(pox_options)
  global core
  if pox.core.core is not None:
    core = pox.core.core
    core.getLogger('boot').debug('Using existing POX core')
  else:
    core = pox.core.initialize(_options.threaded_selecthub)

  _pre_startup()
  modules = _do_imports(n.split(':')[0] for n in component_order)
  if modules is False:
    return False

  inst = {}
  for name in component_order:
    cname = name
    inst[name] = inst.get(name, -1) + 1
    params = components[name][inst[name]]
    name = name.split(":", 1)
    launch = name[1] if len(name) == 2 else "launch"
    name = name[0]

    name,module,members = modules[name]

    if launch in members:
      f = members[launch]
      # We explicitly test for a function and not an arbitrary callable
      if type(f) is not types.FunctionType:
        print(launch, "in", name, "isn't a function!")
        return False

      if getattr(f, '_pox_eval_args', False):
        import ast
        for k,v in params.items():
          if isinstance(v, str):
            try:
              params[k] = ast.literal_eval(v)
            except:
              # Leave it as a string
              pass

      multi = False
      if f.func_code.co_argcount > 0:
        #FIXME: This code doesn't look quite right to me and may be broken
        #       in some cases.  We should refactor to use inspect anyway,
        #       which should hopefully just fix it.
        if (f.func_code.co_varnames[f.func_code.co_argcount-1]
            == '__INSTANCE__'):
          # It's a multi-instance-aware component.

          multi = True

          # Special __INSTANCE__ paramter gets passed a tuple with:
          # 1. The number of this instance (0...n-1)
          # 2. The total number of instances for this module
          # 3. True if this is the last instance, False otherwise
          # The last is just a comparison between #1 and #2, but it's
          # convenient.
          params['__INSTANCE__'] = (inst[cname], len(components[cname]),
           inst[cname] + 1 == len(components[cname]))

      if multi == False and len(components[cname]) != 1:
        print(name, "does not accept multiple instances")
        return False

      try:
        if f(**params) is False:
          # Abort startup
          return False
      except TypeError as exc:
        instText = ''
        if inst[cname] > 0:
          instText = "instance {0} of ".format(inst[cname] + 1)
        print("Error executing {2}{0}.{1}:".format(name,launch,instText))
        if inspect.currentframe() is sys.exc_info()[2].tb_frame:
          # Error is with calling the function
          # Try to give some useful feedback
          if _options.verbose:
            traceback.print_exc()
          else:
            exc = sys.exc_info()[0:2]
            print(''.join(traceback.format_exception_only(*exc)), end='')
          print()
          EMPTY = "<Unspecified>"
          code = f.__code__
          argcount = code.co_argcount
          argnames = code.co_varnames[:argcount]
          defaults = list((f.func_defaults) or [])
          defaults = [EMPTY] * (argcount - len(defaults)) + defaults
          args = {}
          for n, a in enumerate(argnames):
            args[a] = [EMPTY,EMPTY]
            if n < len(defaults):
              args[a][0] = defaults[n]
            if a in params:
              args[a][1] = params[a]
              del params[a]
          if '__INSTANCE__' in args:
            del args['__INSTANCE__']

          if f.__doc__ is not None:
            print("Documentation for {0}:".format(name))
            doc = f.__doc__.split("\n")
            #TODO: only strip the same leading space as was on the first
            #      line
            doc = map(str.strip, doc)
            print('',("\n ".join(doc)).strip())

          #print(params)
          #print(args)

          print("Parameters for {0}:".format(name))
          if len(args) == 0:
            print(" None.")
          else:
            print(" {0:25} {1:25} {2:25}".format("Name", "Default",
                                                "Active"))
            print(" {0:25} {0:25} {0:25}".format("-" * 15))

            for k,v in args.iteritems():
              print(" {0:25} {1:25} {2:25}".format(k,str(v[0]),
                    str(v[1] if v[1] is not EMPTY else v[0])))

          if len(params):
            print("This component does not have a parameter named "
                  + "'{0}'.".format(params.keys()[0]))
            return False
          missing = [k for k,x in args.iteritems()
                     if x[1] is EMPTY and x[0] is EMPTY]
          if len(missing):
            print("You must specify a value for the '{0}' "
                  "parameter.".format(missing[0]))
            return False

          return False
        else:
          # Error is inside the function
          raise
    elif len(params) > 0 or launch is not "launch":
      print("Module %s has no %s(), but it was specified or passed " \
            "arguments" % (name, launch))
      return False

  return True
Пример #5
0
from pox.lib.packet.ipv4 import ipv4
from pox.lib.packet.arp import arp
from pox.lib.addresses import IPAddr, EthAddr
from pox.lib.util import str_to_bool, dpid_to_str
from pox.lib.recoco import Timer
from pox.lib.revent import *

import pox.openflow.libopenflow_01 as of
import time
import numpy as np
import pickle

from tensorflow.keras.models import load_model


log = getLogger()

packets_arr = []

# Timeout for flows
FLOW_IDLE_TIMEOUT = 10

# Timeout for ARP entries
ARP_TIMEOUT = 60 * 2

# Maximum number of packet to buffer on a switch for an unknown IP
MAX_BUFFERED_PER_IP = 5

# Maximum time to hang on to a buffer for an unknown IP in seconds
MAX_BUFFER_TIME = 5
Пример #6
0
import subprocess
import re
import multiprocessing
import multiprocessing.dummy
import xmlrpclib
import json
import inspect
import socket
from ssl import SSLError

import pox.core
from pox.core import core
from pox.lib.addresses import *
from pox.lib.revent import *

log = core.getLogger()
config = {}
lock = multiprocessing.Lock()
rpc_lock = multiprocessing.Lock()

#############################################################################
# from: http://stackoverflow.com/questions/372365/set-timeout-for-xmlrpclib-serverproxy
import httplib

class TimeoutHTTPSConnection (httplib.HTTPSConnection):
  def connect (self):
    httplib.HTTPSConnection.connect(self)
    self.sock.settimeout(self.timeout)
  def set_timeout (self, timeout):
    self.timeout = timeout
Пример #7
0
import subprocess
import re
import multiprocessing
import multiprocessing.dummy
import xmlrpclib
import json
import inspect
import socket
from ssl import SSLError

import pox.core
from pox.core import core
from pox.lib.addresses import *
from pox.lib.revent import *

log = core.getLogger()
config = {}
lock = multiprocessing.Lock()
rpc_lock = multiprocessing.Lock()

#############################################################################
# from: http://stackoverflow.com/questions/372365/set-timeout-for-xmlrpclib-serverproxy
import httplib

class TimeoutHTTPSConnection (httplib.HTTPSConnection):
  def connect (self):
    httplib.HTTPSConnection.connect(self)
    self.sock.settimeout(self.timeout)
  def set_timeout (self, timeout):
    self.timeout = timeout
Пример #8
0
def _do_launch(argv):
    component_order = []
    # Ordem dos componentes
    # Lista vazia

    components = {}
    # Componentes
    # Dicionario vazio

    curargs = {}
    # Argumentos atuais
    # Dicionario vazio

    pox_options = curargs
    # Opções do POX
    # Copia a referência do objeto curargs para pox_options

    for arg in argv:
        # arg(argumento)
        if not arg.startswith("-"):  # Se arg não inicia com "-"
            if arg not in components:  # Se arg não estiver em componentes
                components[arg] = [
                ]  # Adiciona uma lista vazia para a chave arg
            curargs = {}  # Reatribui um dicionario vazio a curargs
            components[arg].append(
                curargs
            )  # Adiciona curargs a lista de componentes na posicao arg
            component_order.append(
                arg)  # Adiciona arg a lista de ordem dos componentes
    else:  # Se arg inicia com "-"
        arg = arg.lstrip("-").split("=", 1)
        # Retira "-" arg e atribui uma lista de string com uma ou duas substrings
        # da arg, separadas por "=".
        arg[0] = arg[0].replace(
            "-", "_")  # Substitui todos os "-" por "_" de agr[0]
        if len(arg) == 1:  # Se arg[0] for uma lista de uma só posicao
            arg.append(True)  # Adiciona True no final
        curargs[arg[0]] = arg[1]
        # atribui o valor de arg[1] em curargs na posicao corespondente à string arg[0]

    _options.process_options(pox_options)
    # Se a opção for desconhecida encerra o processo.

    global core
    # Chama o objeto core como global
    if pox.core.core is not None:  # Verififar arquivo core
        core = pox.core.core
        core.getLogger('boot').debug('Using existing POX core')
    else:
        core = pox.core.initialize(_options.threaded_selecthub,
                                   _options.epoll_selecthub,
                                   _options.handle_signals)
    # Só quando olhar a core.py
    _pre_startup()
    # Todas as opções do POX foram lidas.
    modules = _do_imports(n.split(':')[0] for n in component_order)
    # Modulos recebe uma lista com:
    #     -> Dicionario, contendo informações sobre os modulos importados.
    #     -> False, se não for possível importar o módulo
    if modules is False:
        return False

    inst = {}
    # Dicionário vazio

    for name in component_order:
        # Passapor todos os componentes da lista component_order
        # atribui esse valos a name.
        cname = name
        # pra que serve "cname"?

        inst[name] = inst.get(name, -1) + 1
        # Atribui ao dicionario na chave "name", oq ele contiver com essa chave + 1
        # ou -1 + 1 se ele não tiver uma chave "name".
        params = components[name][inst[name]]
        # params recebe o valor dos componentes na chave name na posição
        # correspondente ao valor de inst[name].
        name = name.split(":", 1)
        # Atribui a name uma lista de strings com a string name quebrada
        # em no máximo duas posições, quebra essa feita no primeiro
        # caracter ":" que aparecer.

        launch = name[1] if len(name) == 2 else "launch"
        # launch recebe a segunda posicao da linta name, se ela contiver
        # duas posicoes, se não, ele recebe a string "launch".

        name = name[0]
        # name recebe a string da primeira posicao da lista name.

        name, module, members = modules[name]
        # Pega os elementos de modules na chave name e atribui às variáveis
        # simultaneamente. (Atribuição multipla)

        if launch in members:  # Se launch estiver em members
            f = members[launch]
            # atribui o mendo com a chave saunch à f

            # We explicitly test for a function and not an arbitrary callable.
            # Testamos explicitamente para uma função e não um arbitrário callable.
            if type(f) is not types.FunctionType:  # Se f não for uma função
                print(launch, "in", name,
                      "isn't a function!")  # Diz não é uma função
                return False  # Retorna falso

            if getattr(f, '_pox_eval_args', False):
                # Verifica se o metodo '_pox_eval_args' existe em f.
                import ast
                '''
        O módulo ast ajuda aplicações Python para processar árvores do Python
        sintaxe abstrata gramática. A própria sintaxe abstrata pode mudar com
        cada versão Python; Este módulo ajuda a descobrir programaticamente
        o que a gramática atual se parece.
        '''

                for k, v in params.items():  # Declarado na linha 267
                    #  Copia a chave -> k e o valor -> v das posições do dicionario params.
                    if isinstance(v, str):
                        # Se o objeto v é da classe string.
                        try:
                            params[k] = ast.literal_eval(v)
                            # Verifica se o valor de v é código python
                        except:
                            # Leave it as a string
                            pass

            multi = False
            if f.__code__.co_argcount > 0:  # Se a função f receber algum argumento.
                # FIXME: This code doesn't look quite right to me and may be broken
                #       in some cases.  We should refactor to use inspect anyway,
                #       which should hopefully just fix it.
                '''
        FIXME: Esse código não parece muito bem para mim e pode ser quebrado em alguns
        casos. Nós devemos refatorar para uso de qualquer forma, inspecionar
        que esperemos que deve apenas corrigi-lo.
        '''
                if (f.__code__.co_varnames[f.__code__.co_argcount -
                                           1] == '__INSTANCE__'):
                    # It's a multi-instance-aware component.
                    # É um componente de reconhecimento de instância de multipla.

                    multi = True

                    # Special __INSTANCE__ paramter gets passed a tuple with:
                    # 1. The number of this instance (0...n-1)
                    # 2. The total number of instances for this module
                    # 3. True if this is the last instance, False otherwise
                    # The last is just a comparison between #1 and #2, but it's
                    # convenient.

                    # Parâmetro especial __INSTANCE__ é passado uma tupla com:
                    # 1. O numero da instancia(0...n-1)
                    # O total de instancias deste módulo.
                    # 3. True se esta for a ultima instancia, False so não.
                    # O último é apenas uma comparação entre o #1 e #2, mas é conveniente.

                    params['__INSTANCE__'] = (inst[cname],
                                              len(components[cname]),
                                              inst[cname] + 1 == len(
                                                  components[cname]))

            if multi == False and len(components[cname]) != 1:
                # Verifica se existe mais de um objeto de multi.
                print(name, "does not accept multiple instances")
                return False
                # Cansei... Vou pular isso... Fllw
            try:
                if f(**params) is False:
                    # Abort startup
                    return False
            except TypeError as exc:
                instText = ''
                if inst[cname] > 0:
                    instText = "instance {0} of ".format(inst[cname] + 1)
                print("Error executing {2}{0}.{1}:".format(
                    name, launch, instText))
                if inspect.currentframe() is sys.exc_info()[2].tb_frame:
                    # Error is with calling the function
                    # Try to give some useful feedback
                    if _options.verbose:
                        traceback.print_exc()
                    else:
                        exc = sys.exc_info()[0:2]
                        print(''.join(traceback.format_exception_only(*exc)),
                              end='')
                    print()
                    EMPTY = "<Unspecified>"
                    code = f.__code__
                    argcount = code.co_argcount
                    argnames = code.co_varnames[:argcount]
                    defaults = list((f.func_defaults) or [])
                    defaults = [EMPTY] * (argcount - len(defaults)) + defaults
                    args = {}
                    for n, a in enumerate(argnames):
                        args[a] = [EMPTY, EMPTY]
                        if n < len(defaults):
                            args[a][0] = defaults[n]
                        if a in params:
                            args[a][1] = params[a]
                            del params[a]
                    if '__INSTANCE__' in args:
                        del args['__INSTANCE__']

                    if f.__doc__ is not None:
                        print("Documentation for {0}:".format(name))
                        doc = f.__doc__.split("\n")
                        # TODO: only strip the same leading space as was on the first
                        #      line
                        doc = map(str.strip, doc)
                        print('', ("\n ".join(doc)).strip())

                    # print(params)
                    # print(args)

                    print("Parameters for {0}:".format(name))
                    if len(args) == 0:
                        print(" None.")
                    else:
                        print(" {0:25} {1:25} {2:25}".format(
                            "Name", "Default", "Active"))
                        print(" {0:25} {0:25} {0:25}".format("-" * 15))

                        for k, v in args.iteritems():
                            print(" {0:25} {1:25} {2:25}".format(
                                k, str(v[0]),
                                str(v[1] if v[1] is not EMPTY else v[0])))

                    if len(params):
                        print(
                            "This component does not have a parameter named " +
                            "'{0}'.".format(params.keys()[0]))
                        return False
                    missing = [
                        k for k, x in args.iteritems()
                        if x[1] is EMPTY and x[0] is EMPTY
                    ]
                    if len(missing):
                        print("You must specify a value for the '{0}' "
                              "parameter.".format(missing[0]))
                        return False

                    return False
                else:
                    # Error is inside the function
                    raise
        elif len(params) > 0 or launch is not "launch":
            print("Module %s has no %s(), but it was specified or passed " \
                  "arguments" % (name, launch))
            return False

    return True