Beispiel #1
0
 def testTimetickCallback(self):
     self.logger.info("start testing...")
     self.logger.info("************************************************")
     self.logger.info("***           TimetickCallback:normal        ***")
     self.logger.info("************************************************")
     connection = L2tpv3Connection.L2tpConnection(
         1666, 1666,
         L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)
     # send a SCCRQ form remote
     msgAvp = ControlMessageAVP(ControlMessageAVP.SCCRQ)
     assignedAvp = AssignedControlConnectionID(connection.localConnID)
     sccrq = L2tpv3ControlPacket(1666, avps=(msgAvp, assignedAvp))
     connection.transport.SendPacket(
         sccrq, (connection.remoteAddr, connection.localConnID))
     # before timetick callback, the value nr/ns
     # lastNr = transport.ackNr
     lastNs = connection.transport.ns
     connection.transport.sendTimeout = 0
     connection.transport.resendTimes = 1
     connection.transport.TimetickCallback()
     # after timetick callback, need to send the stopccn, sothe ns +1
     self.assertEqual(lastNs, connection.transport.ns)
     connection.transport.sendTimeout = 0
     connection.transport.resendTimes = 0.5
     connection.transport.TimetickCallback()
     self.assertEqual(connection.connection_status,
                      L2tpv3Connection.L2tpConnection.CLOSED)
Beispiel #2
0
    def test_A2__handleConnectionQuery_connID_isin_connDB(self):
        """(remoteAddr, connID) is in connectionDb Create a connection.

        Result: success.

        """
        # Create a connection
        global_dispatcher = Dispatcher()
        L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress = '127.0.0.1'
        dispatcher = L2tpv3Dispatcher.L2tpv3Dispatcher(
            global_dispatcher,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress,
            create_global_listen=False)

        self.dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher
        self.connection = L2tpv3Connection.L2tpConnection(
            9527, 21203, "127.0.0.1")

        # Create a msg
        cmd = l2tpMsg.L2tpCommandReq()
        cmd.cmd = l2tpMsg.CONNECTION_INFO

        # connection is in local connection DB
        para = l2tpMsg.ConnectionPara()

        # Get addr and connID invoke connection
        para.remoteAddr = self.connection.remoteAddr
        para.connectionID = self.connection.localConnID
        para.localAddr = L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress

        cmd.conn.MergeFrom(para)
        msg = self.api._handleMsg(cmd)
        # SUCCESS = 1
        self.assertEqual(msg.rsp, 1)
Beispiel #3
0
    def CreateConnection(self, RemoteAddr):
        dispatcher = L2tpv3Dispatcher.L2tpv3Dispatcher(
            self.LocalAddr, createGlobalListen=False)
        dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher
        self.dispatcher = dispatcher

        # we need to create connection
        connection = L2tpv3Connection.L2tpConnection(0, 0, RemoteAddr)
        self.connection = connection

        # Initiate SCCRQ connection request message
        connection.localRequest(RemoteAddr)

        processStep(dispatcher)

        # Validate if FSM current state is established

        if L2tpFsm.L2tpv3ConnectionFsm.StateEstablished != connection.fsm.current:
            self.logger.info(
                "FSM current state is not established,current state is:%s" %
                (connection.fsm.current))
            # self.fail("Connection is not establshed!!!")

        else:
            self.logger.info("Connection is established successfully")
Beispiel #4
0
    def testUnnormalTimetickCallback(self):
        self.logger.info("start testing...")
        self.logger.info("************************************************")
        self.logger.info("***          TimetickCallback:unnormal       ***")
        self.logger.info("************************************************")
        connection = L2tpv3Connection.L2tpConnection(
            1888, 1888,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)
        # send a zlb form remote
        msgAvp = ControlMessageAVP(ControlMessageAVP.ZLB)
        assignedAvp = AssignedControlConnectionID(connection.localConnID)
        zlb = L2tpv3ControlPacket(1888, avps=(msgAvp, assignedAvp))
        connection.transport.SendPacket(
            zlb, (connection.remoteAddr, connection.localConnID))

        # send a ZLB form remote, before timetick callback is True
        lastNeedSendZlb = connection.transport.needSendZlb = True

        connection.transport.sendZlbTimeout = 0
        connection.transport.TimetickCallback()
        # after send ZLB, the needSendZlb change to False
        self.assertNotEqual(connection.transport.needSendZlb, lastNeedSendZlb)
        connection.CloseConnection()

        connection = L2tpv3Connection.L2tpConnection(
            2000, 2000,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)
        # send a zlb form remote
        msgAvp = ControlMessageAVP(ControlMessageAVP.ZLB)
        assignedAvp = AssignedControlConnectionID(connection.localConnID)
        zlb = L2tpv3ControlPacket(2000, avps=(msgAvp, assignedAvp))
        connection.transport.SendPacket(
            zlb, (connection.remoteAddr, connection.localConnID))
        connection.transport.lastTimetick = time.time() - 60
        sendListTime = connection.transport.sendList[0]["time"]
        connection.transport.TimetickCallback()
        # after timetick callback, this time should be updated
        self.assertTrue(
            connection.transport.sendList[0]["time"] > sendListTime)
        """connection.transport.lastTimetick = time.time() + 60
        sendListTime = connection.transport.sendList[0]["time"]
        connection.transport.TimetickCallback()
        # after timetick callback, this time should be updated
        self.assertFalse(connection.transport.sendList[0]["time"] > sendListTime)"""
        connection.CloseConnection()
Beispiel #5
0
 def testSetDispatcher(self):
     self.logger.info("start testing...")
     self.logger.info("************************************************")
     self.logger.info("***            SetDispatcher:normal          ***")
     self.logger.info("************************************************")
     connection = L2tpv3Connection.L2tpConnection(
         888, 888, L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)
     connection.transport.SetDispatcher(self.dispatcher)
     self.assertEqual(self.dispatcher, connection.transport.dispatcher)
     connection.CloseConnection()
Beispiel #6
0
 def testSetUnmormalDispatcher(self):
     self.logger.info("start testing...")
     self.logger.info("************************************************")
     self.logger.info("***           SetDispatcher:unnormal         ***")
     self.logger.info("************************************************")
     connection = L2tpv3Connection.L2tpConnection(
         1222, 1222,
         L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)
     try:
         connection.transport.SetDispatcher("test")
     except Exception as e:
         self.assertRegexpMatches(str(e),
                                  L2tpv3TransportError.ParameterTypeError)
     connection.CloseConnection()
Beispiel #7
0
    def test_B3__handleSessionQuery_localsessionID_isin_AND_connID_isNotin_DB(
            self):
        """No connection and create session.

        Check: Cannot find the connection
        in local connection DB

        Result: Failure.

        """
        # Create a connection for connection ID
        global_dispatcher = Dispatcher()
        L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress = '127.0.0.1'
        dispatcher = L2tpv3Dispatcher.L2tpv3Dispatcher(
            global_dispatcher,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress,
            create_global_listen=False)

        self.dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher
        self.connection = L2tpv3Connection.L2tpConnection(
            10202, 1719, "127.0.0.1")

        # Create a session for sessionID
        session = L2tpv3Session.L2tpv3Session(randint(1, 0xFFFFFFFF), 0,
                                              "sender", self.connection)
        self.connection.addSession(session)
        session.LocalRequest()

        cmd = l2tpMsg.L2tpCommandReq()
        cmd.cmd = l2tpMsg.SESSION_INFO

        sess = cmd.sess
        conn = sess.conn

        # connectionID is not in local connection DB
        conn.remoteAddr = '127.0.0.1'
        # Connection is not in connection DB && return
        conn.connectionID = 1652974642

        # Local session is in connection session
        sess.localSessionID = session.localSessionId

        msg = self.api._handleMsg(cmd)

        # FAILIURE = 2
        self.assertEqual(msg.rsp, 2)
        self.assertEqual(msg.retMsg,
                         "Cannot find the connection in local connection DB")
Beispiel #8
0
    def test_B4__handleSessionQuery_localsessionID_AND_connID_isin_DB(self):
        """Create connection and session.

        Result: success.

        """
        # Create a connection for connectionID
        global_dispatcher = Dispatcher()
        L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress = '127.0.0.1'
        dispatcher = L2tpv3Dispatcher.L2tpv3Dispatcher(
            global_dispatcher,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress,
            create_global_listen=False)

        self.dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher
        self.connection = L2tpv3Connection.L2tpConnection(
            3110, 7222, "127.0.0.1")

        # Create a session for sessionID
        session = L2tpv3Session.L2tpv3Session(randint(1, 0xFFFFFFFF), 0,
                                              "sender", self.connection)
        self.connection.addSession(session)
        session.LocalRequest()

        cmd = l2tpMsg.L2tpCommandReq()
        cmd.cmd = l2tpMsg.SESSION_INFO

        sess = cmd.sess
        conn = sess.conn

        # connection is in local connection DB
        conn.remoteAddr = self.connection.remoteAddr
        conn.localAddr = L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress
        conn.connectionID = self.connection.localConnID

        # Local session is in connection session
        sess.localSessionID = session.localSessionId

        msg = self.api._handleMsg(cmd)
        print msg

        # Success = 1
        self.assertEqual(msg.rsp, 1)
Beispiel #9
0
    def test_B2__handleSessionQuery_sessID_isNotin_AND_connID_isin_DB(self):
        """Create connection and no session.

        Check: Cannot find the session in
        local connection DB

        Result: FAILURE.

        """
        # Create a connection for connection ID
        global_dispatcher = Dispatcher()
        L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress = '127.0.0.1'
        dispatcher = L2tpv3Dispatcher.L2tpv3Dispatcher(
            global_dispatcher,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress,
            create_global_listen=False)

        self.dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher
        self.connection = L2tpv3Connection.L2tpConnection(
            7097, 8208, "127.0.0.1")

        cmd = l2tpMsg.L2tpCommandReq()
        cmd.cmd = l2tpMsg.SESSION_INFO

        sess = cmd.sess
        conn = sess.conn

        # connection is in local connection DB
        conn.remoteAddr = self.connection.remoteAddr
        conn.localAddr = L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress
        conn.connectionID = self.connection.localConnID

        # Local session is not in connection session
        sess.localSessionID = 2406980214

        msg = self.api._handleMsg(cmd)

        # FAILIURE = 2
        self.assertEqual(msg.rsp, 2)
        self.assertEqual(msg.retMsg,
                         "Cannot find the session in local connection DB")
Beispiel #10
0
    def setUpClass(cls):
        cls.logger.info("start setup...")
        cls.logger.info("************************************************")
        cls.logger.info("***                setUpClass:               ***")
        cls.logger.info("************************************************")
        # open logger
        setup_logging("L2TP")
        # use the localhost as the default IP address
        global_dispatcher = Dispatcher()
        dispatcher = L2tpv3Dispatcher(
            global_dispatcher,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress,
            create_global_listen=False)
        cls.dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher

        # create the connection
        cls.connection = L2tpv3Connection.L2tpConnection(
            666, 666, L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)

        # instance the transport
        cls.transport = cls.connection.transport
Beispiel #11
0
def processStep(dispatcher):
    dispatcher._processUnregisterRequest()
    socks = dict(dispatcher.poller.poll(1000 * dispatcher.timetick))
    try:
        for sock in socks:
            # For the transport sockets
            print "zmq.POLLIN is:", zmq.POLLIN
            if isinstance(sock, int) and socks[sock] == zmq.POLLIN:
                socketRecv = dispatcher.socketMapping[sock]
                print "socketRecv is:", socketRecv
                buf, addr = socketRecv.socket.recvfrom(2048)
                print "buf is:", buf
                print "addr is:", addr
                pkt = L2tpv3ControlPacket.L2tpv3ControlPacket.decode(buf)
                print "after decode,pkt is:", pkt
                connId = pkt.GetLocalConnectionID()
                dispatcher.logger.debug(
                    "Got a l2tp control packet with addr=%s, localConnectionID = %d"
                    % (addr[0], connId))
                dispatcher.logger.debug(pkt)
                addr = (addr[0], connId)
                # We should check local Cache if we have this connection in cache, if yes, we should throw this
                # packet to it's transport, it not, throw it into the global
                # transport
                if addr in dispatcher.transportMapping:
                    transport = dispatcher.transportMapping[addr]
                    transport.ReceivePacket(pkt, addr)
                elif connId != 0:
                    dispatcher.logger.warn(
                        "Cannot found the connection for packet, connectionId= %d"
                        % connId)
                    return
                else:
                    remoteId, ok = pkt.GetRemoteConnectionID()
                    if not ok:
                        dispatcher.logger.warn(
                            "Cannot find the remote connection ID, skip this packet"
                        )
                        return

                    if pkt.ns != 0:
                        dispatcher.logger.warn(
                            "Got a control packet with wrong NS, will not create connection for it"
                        )
                        return
                    conn = L2tpv3Connection.L2tpConnection(
                        connId, remoteId, addr[0])
                    conn.ReceiveControlPackets(pkt, addr)
            # For the API instance ZMQ socket
            elif isinstance(
                    sock,
                    zmq.sugar.socket.Socket) and socks[sock] == zmq.POLLIN:
                apiInstance = dispatcher.zmqMapping[sock]
                apiInstance.recvAndProcess()
            else:
                dispatcher.logger.error(
                    "Unexpected socket event happens, ignore it.")

        # Proccess the timeout event
        t = time.time()
        if t - dispatcher.lastTimetick < 0:
            dispatcher.logger.error(
                "The system time is changed, lower than previous, add some adjustment to it."
            )
            dispatcher.lastTimetick = t
            return

        if t - dispatcher.lastTimetick >= dispatcher.timetick:
            if t - dispatcher.lastTimetick > 60:
                # if the the time escaped larger than 1 min, we assume that
                # some one change the system time
                dispatcher.logger.error(
                    "The system time is changed, ahead too much, no need to change. "
                )

            dispatcher.lastTimetick = t
            for k in dispatcher.transportMapping:
                transport = dispatcher.transportMapping[k]
                transport.TimetickCallback()

            # execute testPlan
            if dispatcher.testPlan:
                timeElapse = time.time() - dispatcher.dispatcherStartTime
                popupList = list()
                for t in dispatcher.testPlan:
                    # the format is {time: {handler: xxx, name:xxx, arg:xxx}}
                    if t < timeElapse:
                        plan = dispatcher.testPlan[t]
                        dispatcher.logger.debug("Start to execute test plan:" +
                                                plan["name"])
                        handler = plan['handler']
                        arg = plan['arg']
                        handler(arg)
                        popupList.append(t)
                for t in popupList:
                    dispatcher.testPlan.pop(t)

    except Exception as e:
        dispatcher.logger.error(traceback.format_exc())
Beispiel #12
0
        else:
            LocalIPAddress = "::1"

    print "RemoteIPAddress ", RemoteIPAddress
    print "LocalIPAddress ", LocalIPAddress

    global_dispatcher = Dispatcher()
    l2tp_dispatcher = L2tpv3Dispatcher.L2tpv3Dispatcher(global_dispatcher,
                                                        LocalIPAddress,
                                                        create_global_listen=False)
    L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = l2tp_dispatcher

    l2tp_dispatcher.register_remote_address(RemoteIPAddress)

    # we need to create connection
    connection = L2tpv3Connection.L2tpConnection(
        0, 0, RemoteIPAddress, LocalIPAddress)

    def create_session_and_fire(connection):

        fsm = connection.fsm

        if fsm.fsm.current != 'established':
            return

        session = L2tpv3Session.L2tpv3Session(
            randint(1, 0xFFFFFFFF), 0, "sender", connection)
        connection.addSession(session)
        session.LocalRequest()

    l2tp_dispatcher.testPlan = dict()
    l2tp_dispatcher.testPlan[15] = {  # will execute it after 15 s