예제 #1
0
    def __receive_login(peer: Peer, command: bytes, message: bytes):
        if command == Protocol.Flags.LOGIN:
            username = message.split(bytes([Protocol.Flags.SEPARATOR
                                            ]))[0].decode()
            passwd = message.split(bytes([Protocol.Flags.SEPARATOR
                                          ]))[1].decode()
            hashed = str(
                hashpw(passwd.encode("utf-8"), b"$2a$12$" +
                       b"SZ4R4Z3G3SZ4DJ4LS0RT..")).split("..")[1][:-1]
            logging.info("LOGIN from \"" + username + "\"")

            peer_id = SQLModule.PeersSQLModule.get_id(username)
            if peer_id == -1 or hashed == SQLModule.PeersSQLModule.get_hashed_pwd(
                    username):
                if peer_id == -1:
                    SQLModule.PeersSQLModule.add_peer(username, hashed)
                    logging.info("Account created for \"" + username + "\"")
                    peer.send(
                        Protocol.server_message(
                            Protocol.ServerFlags.ACK,
                            "Account created for \"" + username + "\""))
                peer.name = username
                peer.logged_in = True
                logging.info("\"" + username + "\" has logged in succesfully")
                peer.send(
                    Protocol.server_message(Protocol.ServerFlags.ACK,
                                            "Successful login"))

            else:
                logging.warning("\"" + username + "\" failed to log in")
                peer.send(
                    Protocol.server_message(Protocol.ServerFlags.NAK,
                                            "Wrong password for this user"))
                peer.logged_in = False
예제 #2
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.address = ("192.168.1.107", 1237)
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sock.connect(self.address)
     self.thread_owner = ""
     self.protocol = Protocol(self)
예제 #3
0
 def onBtnProtocol(self):
     proto = Protocol(self.currentTest)
     proto.exec()
     if proto.ret:
         self.ticket.data = self.currentTest
         dispatcher.send(self.signals.WB_UPDATE_TEST, dispatcher.Anonymous,self.ticket)
         self.fillDialog()
예제 #4
0
 def decodeCommandData(self, msg):
     protocol = msg['protocol']
     model = msg['model']
     method = msg['method']
     methods = Protocol.methodsForProtocol(protocol, model)
     if not method & methods:
         return
     for device in self.devices:
         params = device.params()
         if params['protocol'] != protocol:
             continue
         if not method & device.methods():
             continue
         deviceParams = params['protocolParams']
         thisDevice = True
         for parameter in Protocol.parametersForProtocol(protocol, model):
             if parameter not in msg:
                 thisDevice = False
                 break
             if parameter not in deviceParams:
                 thisDevice = False
                 break
             if msg[parameter] != deviceParams[parameter]:
                 thisDevice = False
                 break
         if thisDevice:
             device.setState(method, None)
 def handle_req_file_request(self):
     file_name_str = self.get_sized_payload().decode("UTF-8")
     file_path = self.shared_dir_path.joinpath(file_name_str)
     if file_path.exists():
         self.client_connection.sendall(Protocol.ack_file_bytes(file_path))
     else:
         self.client_connection.sendall(
             Protocol.rej_file_bytes(file_path.name))
예제 #6
0
    def onBtnReport(self):
        proto = Protocol(self.currentTest,self.currentProject)
        proto.exec()
        if proto.ret:
            self.ticket.data = self.currentProject
            dispatcher.send(self.signals.WB_UPDATE_PROJECT, dispatcher.Anonymous,self.ticket)

            self.ticket.data = self.currentTest
            dispatcher.send(self.signals.WB_UPDATE_TEST, dispatcher.Anonymous,self.ticket)
예제 #7
0
    def run(self):
        self.protocol = Protocol(self)
        self.sendBySocket(
            self.protocol.sendLogin(self.id_center, self.password))

        while True:
            chunk = self.socket.recv(1024)
            fromClient = str(chunk)
            print("recibo -->", fromClient)
            self.proccessMsg(fromClient)
예제 #8
0
 def send(cls, data, ctype=2, img=False):
     """发送数据
     :param cls:
     :param data:  数据
     :param ctype: 类型
     :param img:   表示本次接收的数据是否为图片
     """
     assert cls._socket != None
     cls._socket.sendall(Protocol.pack(data, ctype))
     Protocol.increase()
     return cls.recv(img)
예제 #9
0
    def join_network(self, connection_addr):
        # """Protocol utlized for each peer to join a network given one or more nodes initialized in
        # P2P network."""
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect(connection_addr)

        self.audit.sending_data(Protocol.req_join_bytes())
        client_socket.sendall(Protocol.req_join_bytes(self.listening_addr))

        new_client_connection_thread = ClientConnectionThread(
            self, self.shared_dir_path, client_socket)
        new_client_connection_thread.start()

        self.connections.append(new_client_connection_thread)
예제 #10
0
class Network(asyncio.Protocol):

    def __init__(self, app, name):
        self.application = app
        self.botName = name
        self.players = self.application.GetPlayers()
        Debug("Network initialisation")

    
    def connection_made(self, transport):
        """ call when the connection with the server is done """
        self.transport = transport
    
        # Cnx ok, create the Protocol object
        Debug("Connexion ok")
        self.protocol = Protocol(self.application, transport)
        self.protocol.setStateLogin()
        
        # start the dialog
        self.protocol.Out('handshake', protocol_version=5, 
                          server_adress='localhost', server_port=25565, next_state=2)
        self.protocol.Out('login_start', name=self.botName)    

    
    def data_received(self, data):
        """ 
        incoming data are ready 
        """
        
        # compute all packets
        while (len(data) > 0):
            packet = Packet(data)
            size   = packet.getVarint()
            offset = packet.getVarintSize()
            packet = Packet(data[offset:offset+size])
            
            # compute the packet
            self.protocol.Receive(packet)
            
            # remove the packet
            data = data[offset+size:]
        
        
    def connection_lost(self, exc):
        """
        the connection is closed
        """
        Debug('Server closed the connection')
        # stop the infinite loop
        asyncio.get_event_loop().stop()
예제 #11
0
 def connect(cls, host, port, pwd):
     """连接服务器
     :param cls:
     :param host: 地址
     :param port: 端口
     :param pwd: 密码
     """
     Protocol.init(pwd)
     cls._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     cls._socket.settimeout(10)  # 10s 超时
     try:
         cls._socket.connect((host, port))
     except Exception as e:
         cls._socket = None
         raise e
예제 #12
0
 def __init__(self, dataObject):
     Protocol.__init__(self, dataObject)
     self.states = {
                    self.INVALID         : self.invalid,
                    self.STARTTOKEN      : self.starttoken, 
                    self.VALIDATIONTYPE  : self.validationtype,                      
                    self.PACKETNUMBER    : self.packetnumber,
                    self.PACKETID        : self.packetid, 
                    self.ADDRSPEC        : self.addrspec, 
                    self.ADDRFIELD       : self.addrfield, 
                    self.DATALEN         : self.datalen
                    self.DATAFIELD       : self.datafield
                    self.WAITCRC         : self.waitcrc
                    self.CRC             : self.crc
                   }
예제 #13
0
    def list_files(self):
        addrs_arr = Protocol.parse_config_file_to_arr(self.addr_config_path)
        for addr in addrs_arr:
            if not (addr == self.listening_addr):
                client_socket = socket.socket(socket.AF_INET,
                                              socket.SOCK_STREAM)
                client_socket.connect(addr)

                self.audit.sending_data(Protocol.req_list_bytes())
                client_socket.sendall(Protocol.req_list_bytes())

                new_client_connection_thread = ClientConnectionThread(
                    self, self.shared_dir_path, client_socket)
                new_client_connection_thread.start()

                self.connections.append(new_client_connection_thread)
예제 #14
0
 def logout(self) -> None:
     if self.__room_joined:
         self.leave_room()
     if self.__logged_in:
         self.__network_module.send(Protocol.logout_message())
         self.__logged_in = False
         self.__username = ''
예제 #15
0
    def connect_to_server(self, address: str, port: int) -> None:
        if self.__connected:
            self.disconnect()

        self.__network_module.connect_to_host(address, port)
        self.__network_module.send(Protocol.hello_message())  # first message
        self.__connected = True
예제 #16
0
    def leave_room(self) -> None:
        if self.__room_joined:
            self.__network_module.send(Protocol.leave_message())
            self.__room_joined = False
            self.__room_name = ''

        self.__window_module.display_special_message('You left the room!')
예제 #17
0
    def __init__(self, status_code, headers=None, payload=None):
        """
            Creates as new http response.

            :param status_code: Status code: 200, 404, 302, 400, ...
            :param headers: Headers of the response as a dictionary object
            :param payload: Payload as Protocol object
        """
        Protocol.__init__(self)
        self.status_code = int(status_code)
        if HttpStatusCodes.has_key(self.status_code):
            self.status_msg = HttpStatusCodes[self.status_code]
        else:
            raise ValueError("Status code " + str(self.status_code) + " is not recognised as a valid http status code")
        self.headers = headers
        self.payload = payload
	def decodeDataSelflearning(data):
		value = int(data['data'], 16)

		house = (value & 0xFFFFFFC0) >> 6
		group = (value & 0x20) >> 5
		methodCode = (value & 0x10) >> 4
		unit = (value & 0xF)
		unit = unit+1

		if house < 1 or house > 67108863 or unit < 1 or unit > 16:
			# not arctech selflearning
			return None

		method = 0
		if Protocol.checkBit(value, 4):
			method = Device.TURNON
		else:
			method = Device.TURNOFF

		retval = {}
		retval['class'] = 'command'
		retval['protocol'] = 'arctech'
		retval['model'] = 'selflearning'
		retval['house'] = str(house)
		retval['unit'] = str(unit)
		retval['group'] = group
		retval['method'] = method
		return retval
예제 #19
0
    def _command(self, action, value, success, failure, **kwargs):
        protocol = Protocol.protocolInstance(self._protocol)
        if not protocol:
            logging.warning("Unknown protocol %s", self._protocol)
            failure(0)
            return
        protocol.setModel(self._model)
        protocol.setParameters(self._protocolParams)
        msg = protocol.stringForMethod(action, value)
        if msg is None:
            failure(0)
            logging.error("Could not encode rf-data for %s:%s %s",
                          self._protocol, self._model, action)
            return

        def s(params):
            success()

        def f():
            failure(Device.FAILED_STATUS_NO_REPLY)

        prefixes = {}
        if 'P' in msg:
            prefixes['P'] = msg['P']
        if 'R' in msg:
            prefixes['R'] = msg['R']
        if 'S' in msg:
            self.controller.queue(
                RF433Msg('S', msg['S'], prefixes, success=s, failure=f))
예제 #20
0
 def recv(cls, img=False):
     """接收数据
     :param img:   表示本次接收的数据是否为图片
     """
     assert cls._socket != None
     try:
         # 数据长度
         header = cls._socket.recv(4)
         totalSize, = struct.unpack('>i', header)
         recvSize = 0
         totalData = header
         while recvSize < totalSize:
             recvData = cls._socket.recv(1024)
             recvSize += len(recvData)
             totalData += recvData
         if img:
             # 获取图片的代码后面会有其它字符串(其实是两个包)
             try:  # 如果是超时则不管它
                 totalData += cls._socket.recv(1024)
             except:
                 pass
     except:
         totalData = None
     message = Protocol.unpack(totalData)
     return message
예제 #21
0
    def __init__(self, method="GET", url="/", headers=ExampleHttpHeaders["default"], payload=None):
        """
            Initiates a new http request object.

            :param method: HTTP method: GET, POST, PUT, ...
            :param url: The request url
            :param headers: a dictionary with header values. See the SampleHttpHeaders variable for an example
            :param payload: The http payload as a Protocol object
        """
        Protocol.__init__(self)
        if method not in HttpRequestMethods:
            raise ValueError("The method " + method + " is not recognised as a valid http method")
        self.method = method
        self.url = url
        self.headers = headers
        self.payload = payload
예제 #22
0
def makePackets(fileName): #Creates a Packet Dictionary object, where the keys are Packet objects and the values are Protocol objects. Furthermore, the Protocol Dictionary that is also returned contains the protocols as keys and a list of fields as a value.
    myFile = open(fileName, 'r')
    PacketNumber = {}
    i = 0
    # create element tree object
    tree = ET.parse(myFile)

    # get root element
    root = tree.getroot()

    # create empty list for objects
    Packets = {}
    ProtocolsList = {}
    for item in root.findall('packet'):
        TemporaryPacket = Packet(item.attrib)
        Packets[TemporaryPacket] = None
        PacketNumber[i]= TemporaryPacket
        Protocols = {}
        for child in item:
            # Packets[item] = child
            TemporaryProtocol = Protocol(child.attrib)
            FieldValues = []
            for fields in child.findall('field'):
                FieldValues.append(Field(fields.attrib))
            Protocols[TemporaryProtocol] = FieldValues
            ProtocolsList[TemporaryProtocol] = FieldValues
        Packets[TemporaryPacket] = Protocols
        i +=1

    ListMe = [PacketNumber,Packets,ProtocolsList]
    return ListMe
예제 #23
0
 def decodeSensor(self, msg):
     protocol = Protocol.protocolInstance(msg['protocol'])
     if not protocol:
         logging.error("No known protocol for %s", msg['protocol'])
         return
     data = protocol.decodeData(msg)
     if not data:
         return
     p = data['protocol']
     m = data['model']
     sensorId = data['id']
     sensorData = data['values']
     sensor = None
     for s in self.sensors:
         if s.compare(p, m, sensorId):
             sensor = s
             break
     if sensor is None:
         sensor = SensorNode()
         sensor.setParams({'protocol': p, 'model': m, 'sensorId': sensorId})
         sensor.setManager(self.deviceManager)
         self.sensors.append(sensor)
     if 'battery' in data:
         sensor.batteryLevel = data['battery']
     sensor.updateValues(sensorData)
예제 #24
0
	def decodeDataSelflearning(data):
		value = int(data['data'], 16)

		house = (value & 0xFFFFFFC0) >> 6
		group = (value & 0x20) >> 5
		methodCode = (value & 0x10) >> 4
		unit = (value & 0xF)
		unit = unit+1

		if house < 1 or house > 67108863 or unit < 1 or unit > 16:
			# not arctech selflearning
			return None

		method = 0
		if Protocol.checkBit(value, 4):
			method = Device.TURNON
		else:
			method = Device.TURNOFF

		retval = {}
		retval['class'] = 'command'
		retval['protocol'] = 'arctech'
		retval['model'] = 'selflearning'
		retval['house'] = str(house)
		retval['unit'] = str(unit)
		retval['group'] = group
		retval['method'] = method
		return retval
    def handle_join_network_request(self):
        addr_str = self.get_sized_payload().decode("utf-8")
        new_ip, new_port = self.find_ip_and_port_addr(addr_str)

        ack_join_bytes = Protocol.ack_join_bytes(self.address_file)
        self.client_connection.sendall(ack_join_bytes)

        self.add_to_addresses_file((new_ip, new_port))
    def handle_ack_join_network_request(self):
        # The loop needs to call join network for each of the other ones.
        new_addr_file_bytes = self.get_sized_payload()

        tmp_file_path = self.shared_dir_path.joinpath(".tmp")
        open(tmp_file_path, 'wb').write(new_addr_file_bytes)

        new_addr_array = Protocol.parse_config_file_to_arr(tmp_file_path)
        my_addr_array = Protocol.parse_config_file_to_arr(self.address_file)

        for addr in new_addr_array:
            if not addr in my_addr_array:
                self.add_to_addresses_file(addr)
                # TODO: add code here that will make new connections with these folk

        if self.shared_dir_path.joinpath(".tmp").is_file():
            self.shared_dir_path.joinpath(".tmp").unlink()
예제 #27
0
    def __init__(self, status_code, headers=None, payload=None):
        """
            Creates as new http response.

            :param status_code: Status code: 200, 404, 302, 400, ...
            :param headers: Headers of the response as a dictionary object
            :param payload: Payload as Protocol object
        """
        Protocol.__init__(self)
        self.status_code = int(status_code)
        if HttpStatusCodes.has_key(self.status_code):
            self.status_msg = HttpStatusCodes[self.status_code]
        else:
            raise ValueError('Status code ' + str(self.status_code) +
                             ' is not recognised as a valid http status code')
        self.headers = headers
        self.payload = payload
예제 #28
0
def main():
    try:
        board = Board(7, 7)
        mySide = Side.SOUTH
        n = 1
        while (True):
            recvmsg = recvMsg()
            try:
                protocol = Protocol()
                messType = protocol.getMessageType(recvmsg)
                if messType == MsgType.START:
                    interpretStartMsg = protocol.interpretStartMsg(recvmsg)
                    mySide = Side.SOUTH if interpretStartMsg else Side.NORTH
                    if interpretStartMsg:
                        n = 0
                        move = calculateNextBestMove(board, mySide)
                        sendMsg(protocol.createMoveMsg(move))
                        continue
                    continue
                elif messType == MsgType.STATE:
                    interpretStateMsg = protocol.interpretStateMsg(
                        recvmsg, board)
                    if interpretStateMsg.again and interpretStateMsg.move == -1:  # if opponent does swap
                        mySide = Side.opposite(mySide)
                        move = calculateNextBestMove(board, mySide)
                        sendMsg(protocol.createMoveMsg(move))
                    elif interpretStateMsg.again and n != 0:  # if we swap
                        if interpretStateMsg.move <= 2:
                            mySide = Side.opposite(mySide)
                            sendMsg(protocol.createSwapMsg())  # Stab
                        else:
                            move = calculateNextBestMove(board, mySide)
                            sendMsg(protocol.createMoveMsg(move))
                    elif interpretStateMsg.again:
                        move = calculateNextBestMove(board, mySide)
                        sendMsg(protocol.createMoveMsg(move))
                    n = 0
                    continue
                else:
                    break
            except InvalidMessageException:
                invalidMessage = InvalidMessageException("Invalid move")
                print(invalidMessage.getMessage())
    except IOException:
        ioExceptionMessage = IOException("IOException")
        print(ioExceptionMessage.getMessage())
    def run(self):
        while (1):
            data = self.client_connection.recv(8)

            if not data:
                self.audit.connection_closed(
                    self.client_connection.getsockname(),
                    self.client_connection.getpeername())
                break

            data_str = data.decode("UTF-8")

            self.audit.data_recieved(data_str)

            if data_str == Protocol.req_join_string():
                self.handle_join_network_request()

            elif data_str == Protocol.ack_join_string():
                self.handle_ack_join_network_request()

            elif data_str == Protocol.req_list_string():
                self.handle_list_request()

            elif data_str == Protocol.ack_list_string():
                self.handle_ack_list_request()

            elif data_str == Protocol.req_file_string():
                self.handle_req_file_request()

            elif data_str == Protocol.ack_file_string():
                self.handle_ack_file_request()

            elif data_str == Protocol.rej_file_string():
                pass
예제 #30
0
    def login(self, username: str, password: str) -> None:
        if self.__logged_in:
            self.logout()

        self.__network_module.send(Protocol.login_message(username, password))
        self.__logged_in = True
        self.__username = username

        self.__window_module.add_title_text(self.__username)
예제 #31
0
 def receive_message(self, data: bytes) -> None:
     messages: List[bytes] = data.split(bytes([Protocol.Flags.TERMINATOR]))
     if len(messages) > 0:
         for i in range(0, len(messages) - 1):
             flag: Protocol.Flags = messages[i][0]
             body: str = ''
             if len(messages[i]) > 1:
                 body = messages[i][1:]
             self.__process_message(Protocol.Message(flag, body))
예제 #32
0
def main():
    # Define IP header (Task 3.)
    ip = IP(src=src_ip, dst=dst_ip)

    # Define customized header (Task 3.)

    my_id = '0616225'
    my_dept = 'cs'
    my_gender = '2'
    student = Protocol(id=my_id, dept=my_dept, gender=my_gender)

    # Read file and store into list
    count = 0
    secret = []
    tmp = ''.join(reversed(my_id))
    with open('./data/secret.txt', 'r') as file:
        for line in file:
            line = tmp[count % 7] + line
            secret.append(line)
            count += 1

    # Send packets
    for i in range(0, len(secret)):
        # TCP connection - SYN / SYN-ACK
        tcp_syn = TCP(sport=src_port, dport=dst_port, flags='S', seq=0)
        packet = ip / tcp_syn
        tcp_syn_ack = sr1(packet)
        print '[INFO] Send SYN and receive SYN-ACK'
        tcp_syn_ack.show()

        # TCP connection - ACK (Task 3.)
        ack = tcp_syn_ack.seq + 1
        tcp_ack = TCP(sport=src_port,
                      dport=dst_port,
                      flags='A',
                      seq=1,
                      ack=ack)
        packet = ip / tcp_ack
        send(packet)

        print '[INFO] Send ACK'

        # Send packet with customized header (Task 3.)

        ack = tcp_ack.seq + 1
        tcp = TCP(sport=src_port, dport=dst_port, flags='', seq=2, ack=ack)
        packet = ip / tcp / student
        send(packet)
        print '[INFO] Send packet with customized header'
        # Send packet with secret payload (Task 3.)
        ack = tcp.seq + 1
        tcp = TCP(sport=src_port, dport=dst_port, flags='', seq=3, ack=ack)
        payload = Raw(secret[i])
        packet = ip / tcp / payload
        send(packet)
        print '[INFO] Send packet with secret payload'
예제 #33
0
 def __init__(self,
              player_1,
              player_2,
              _log_board_state=False,
              create_protocol=True):
     global log_board_state
     log_board_state = _log_board_state
     # board_logger.debug("#" * 200)
     self.player_1: Player = player_1
     self.player_2: Player = player_2
     self.players: [Player] = [player_1, player_2]
     random.shuffle(self.players)
     self.players = cycle(self.players)
     self.current_player: Player = next(self.players)
     self.board: Board = Board(player_1, player_2)
     if create_protocol:
         self.protocol = Protocol()
     else:
         self.protocol = None
예제 #34
0
    def set_game_in_server(self):

        self.send_data(Protocol.new_game(self.username, self.game_type))

        _expected_answer = self.receive_data()

        if _expected_answer == "GAME_SET":
            pass
        else:
            ClientUI.print_detail("Huge error. Server sent back >>> " + _expected_answer)
예제 #35
0
파일: GUI.py 프로젝트: Rinwhisper/BS
 def flushCurrentQRCode(self):
     new = Protocol.produce(self.current_raw_image_obj["flag"],
                            self.current_raw_image_obj["id"],
                            self.current_raw_image_obj["data"])
     self.image = ImageTk.PhotoImage(
         image=self.resize(new, (self.canvas_size, self.canvas_size)))
     self.canvas.create_image(self.canvas_size / 2,
                              self.canvas_size / 2,
                              image=self.image,
                              anchor="center")
예제 #36
0
 def __receive_hello(peer: Peer, command: bytes):
     """
     
     Tries to receives HELLO, if the message is not HELLO, terminates the peer
     
     :param peer:
     :param command:
     :return:
     """
     if command == Protocol.Flags.HELLO:
         logging.info("HELLO message received")
         peer.send(Protocol.hello_message())
         peer.send(
             Protocol.server_message(Protocol.ServerFlags.ACK,
                                     "Welcome to the server"))
         peer.hello_done = True
     else:
         logging.warning("No HELLO received, closing connection")
         peer.terminate()
         peer.hello_done = False
예제 #37
0
파일: sender.py 프로젝트: Shih-Sian/Lab0
def main():
    # Define IP header
    ip = IP(src=src_ip, dst=dst_ip)

    # Define customized header
    # [TODO] Add 'id' field in customized header here (Task 2.)
    #        And fill in your department
    student = Protocol(dept='cs', id='0716030')
    msg = [
        'This lab is a little hard.', 'I am just kidding.',
        'It is so damn difficult.'
    ]

    # [TODO] Fill in the message payload (Task 2.)
    msg = [
        "Anything you want to say (less than 60 charaters)",
        "Computer Networks is interesting.", "I agree XD"
    ]

    # Send packets
    for i in range(0, len(msg)):
        # TCP connection - SYN / SYN-ACK
        tcp_syn = TCP(sport=src_port, dport=dst_port, flags='S', seq=0)
        packet = ip / tcp_syn
        tcp_syn_ack = sr1(packet)
        print '[INFO] Send SYN and receive SYN-ACK'
        #tcp_syn_ack.show()

        # TCP connection - ACK
        ack = tcp_syn_ack.seq + 1
        tcp_ack = TCP(sport=src_port,
                      dport=dst_port,
                      flags='A',
                      seq=1,
                      ack=ack)
        packet = ip / tcp_ack
        send(packet)
        print '[INFO] Send ACK'

        # Send packet with customized header
        ack = tcp_ack.seq + 1
        tcp = TCP(sport=src_port, dport=dst_port, flags='', seq=2, ack=ack)
        packet = ip / tcp / student
        send(packet)
        print '[INFO] Send packet with customized header'

        # Send packet with payload
        ack = tcp.seq + 1
        tcp = TCP(sport=src_port, dport=dst_port, flags='', seq=3, ack=ack)
        payload = Raw(msg[i])
        packet = ip / tcp / payload
        send(packet)
        print '[INFO] Send packet with payload'
예제 #38
0
 def connection_made(self, transport):
     """ call when the connection with the server is done """
     self.transport = transport
 
     # Cnx ok, create the Protocol object
     Debug("Connexion ok")
     self.protocol = Protocol(self.application, transport)
     self.protocol.setStateLogin()
     
     # start the dialog
     self.protocol.Out('handshake', protocol_version=5, 
                       server_adress='localhost', server_port=25565, next_state=2)
     self.protocol.Out('login_start', name=self.botName)    
예제 #39
0
    def select_player(self):

        user_input = ClientUI.select_player()

        if user_input.upper() == "A":
            self.set_game_in_server()
            self.send_data(Protocol.auto_player(self.username))

        else:
            # self.set_game_in_server()

            while True:

                self.send_data(Protocol.send_list(self.username, self.game_type))

                data = self.receive_data().strip()

                while "MATCH_LIST" not in data:
                    data = self.receive_data().strip()

                player_list = data.split('@')

                del player_list[0]
                if len(player_list) != 0:
                    print("\nPlease insert the username that you would like to play with:")
                    print("------------------------------------------------------------")
                    for index in range(len(player_list)):
                        ClientUI.print_detail(str(index + 1) + " -> " + player_list[index])

                    print("----------------------------------------------------------")
                    player_name = ClientUI.get_user_input("\nEnter the username: "******"\nThere is no player. Please try it again!!!\n")
                    self.select_player()
                    break
예제 #40
0
파일: Model.py 프로젝트: DanFaudemer/TFC
 def __init__(self, **kwargs):
     Thread.__init__(self)
     # Serial thread
     self.serialthread = SerialPort()
     # Controller Read/Write variables over serial
     self.controller = DistantIO()
     # Serial protocol
     self.protocol = Protocol()
     # Variable manager
     self.variable_manager = VariableManager(self)
     self.variable_manager.start()
     self.running = True;
     # Data logger
     self.logger = DataLogger()
예제 #41
0
    def new_account(self):

        while True:
            self.username = input("Enter your Username: "******"VALID_USERNAME":
                break
            elif _expected_answer == "":
                print("Huge error. Server sent back >>> ", _expected_answer)
            else:
                print("Someone already has that username. Try another? [CANNOT CONTAIN '@' OR '_']")
예제 #42
0
    def login(self):

        self.username = ClientUI.get_user_input("Enter your Username: "******"VALID_USERNAME":
            pass
        elif _expected_answer == "":
            ClientUI.print_detail("Huge error. Server sent back >>> " + _expected_answer)
        else:
            ClientUI.print_detail("\nInvalid username. Please try it again.\n")
            self.welcome()
예제 #43
0
 def _rebind_slow(self):
     try:
         self.parseFiles()
     except:
         self.error(traceback.format_exc())
     
     try:
         self.dispatcher.rebind()
             
         for channel in dict(self.channels): # hack, but I guess reloading is all a hack :P
             chan = self.channels[channel].copy()
             del chan['chan'] # 'cause we're passing it ourselves
             self.channels[channel] = sys.modules['Protocol'].Channel(self, channel, **chan)
         
         self.protocol = Protocol(self, None)
     except:
         self.error(traceback.format_exc())
         
     self.admin_broadcast('Done reloading.')
     self.console_write('Done reloading.')
예제 #44
0
class DataHandler:
    def __init__(self):
        self.local_ip = None
        self.online_ip = None
        self.session_id = 0
        self.dispatcher = None
        self.console_buffer = []
        self.port = 8200
        self.natport = self.port+1
        self.dbtype = 'lan'
        self.lanadmin = {'username':'', 'password':''}
        self.latestspringversion = '*'
        self.log = False
        self.server = 'TASServer'
        self.server_version = 0.35
        self.sighup = False
        
        self.chanserv = None
        self.userdb = None
        self.engine = None
        self.tsbanurl = None
        self.channelfile = None
        self.protocol = None
        self.updatefile = None
        self.trusted_proxyfile = None
        
        self.max_threads = 25
        self.sqlurl = 'sqlite:///sqlite.txt'
        self.randomflags = False
        self.nextbattle = 0
        self.SayHooks = __import__('SayHooks')
        self.censor = True
        self.motd = None
        self.updates = {}
        self.running = True
        self.output = None
        
        self.trusted_proxies = []
        
        self.start_time = time.time()
        self.channels = {}
        self.chan_alias = {}
        self.usernames = {}
        self.clients = {}
        self.db_ids = {}
        self.battles = {}
        thread.start_new_thread(self.event_loop, ())
    
    def parseArgv(self, argv):
        'parses command-line options'
        args = {'ignoreme':[]}
        mainarg = 'ignoreme'

        tempargv = list(argv)
        while tempargv:
            arg = tempargv.pop(0)
            if arg.startswith('-'):
                mainarg = arg.lstrip('-').lower()

                if mainarg in ['g', 'loadargs']:
                    try:
                        name = tempargv[0]
                        if name.startswith('-'): raise Exception
                        f = file(name, 'r')
                        lines = f.read().split('\n')
                        f.close()

                        tempargv += ' '.join(lines).split(' ')
                    except:
                        pass

                args[mainarg] = []
            else:
                args[mainarg].append(arg)
        del args['ignoreme']

        for arg in args:
            argp = args[arg]
            if arg in ['h', 'help']:
                print 'Usage: server.py [OPTIONS]...'
                print 'Starts uberserver.'
                print
                print 'Options:'
                print '  -h, --help'
                print '      { Displays this screen then exits }'
                print '  -p, --port number'
                print '      { Server will host on this port (default is 8200) }'
                print '  -n, --natport number'
                print '      { Server will use this port for NAT transversal (default is 8201) }'
                print '  -l, --lan'
                print '      { Users do not need to be registered to login - breaks rudimentary features like channel ops/founders, channel/battle bans, etc. }'
                print '  -a, --lanadmin username password [hash] }'
                print '      { Hardcoded admin account for LAN. If third arg reads "hash" it will apply the standard hash algorithm to the supplied password }'
                print '  -g, --loadargs filename'
                print '      { Reads additional command-line arguments from file }'
                print '  -r  --randomflags'
                print '      { Randomizes country codes (flags) }'
                print '  -o, --output /path/to/file.log'
                print '      { Writes console output to file (for logging) }'
                print '  -u, --sighup'
                print '      { Reload the server on SIGHUP (if SIGHUP is supported by OS) }'
                print '  -v, --latestspringversion version'
                print '      { Sets latest Spring version to this string. Defaults to "*" }'
                print '  -m, --maxthreads number'
                print '      { Uses the specified number of threads for handling clients }'
                print '  -s, --sqlurl SQLURL'
                print '      { Uses SQL database at the specified sqlurl for user, channel, and ban storage. }'
                print '  -c, --no-censor'
                print '      { Disables censoring of #main, #newbies, and usernames (default is to censor) }'
                print '  --accounts /path/to/accounts.txt'
                print '      { Path to accounts.txt. For using the legacy TASServer account database. }'
                print '  --tsbans SQLURL'
                print '      { Uses SQL database at the specified sqlurl as a legacy TASServer ban database. } '
                print '  --channels /path/to/settings.xml'
                print '      { Path to ChanServ settings.xml, for using the legacy ChanServ channel database. }'
                print '  --updates /path/to/updates.txt'
                print '     { Path to updates.txt, for using Spring update system. }'
                print '  --proxies /path/to/proxies.txt'
                print '     { Path to proxies.txt, for trusting proxies to pass real IP through local IP }'
                print 'SQLURL Examples:'
                #print '  "sqlite:///:memory:" or "sqlite:///"'
                #print '     { both make a temporary database in memory }'
                print '  "sqlite:////absolute/path/to/database.txt"'
                print '     { uses a database in the file specified }'
                print '  "sqlite:///relative/path/to/database.txt"'
                print '     { note sqlite is slower than a real SQL server }'
                print '  "mysql://*****:*****@server:port/database"'
                print '     { requires the MySQLdb module }'
                print '  "oracle://*****:*****@server:port/database"'
                print '     { requires the cx_Oracle module }'
                print '  "postgres://*****:*****@server:port/database"'
                print '     { requires the psycopg2 module }'
                print '  "mssql://*****:*****@server:port/database"'
                print '     { requires pyodbc (recommended) or adodbapi or pymssql }'
                print '  "firebird://*****:*****@server:port/database"'
                print '     { requires the kinterbasdb module }'
                print
                print 'Usage example (this is what the test server uses at the moment):'
                print ' server.py -p 8300 -n 8301'
                print
                exit()
            if arg in ['p', 'port']:
                try: self.port = int(argp[0])
                except: print 'Invalid port specification'
            elif arg in ['n', 'natport']:
                try: self.natport = int(argp[0])
                except: print 'Invalid NAT port specification'
            elif arg in ['l', 'lan']:
                self.dbtype = 'lan'
            elif arg in ['a', 'lanadmin']:
                try:
                    if len(argp) > 2:
                        if argp[2] == 'hash':
                            m = md5(argp[1])
                            argp[1] = base64.b64encode(m.digest())
                    self.lanadmin = {'username':argp[0], 'password':argp[1]}
                except: print 'Invalid LAN admin specified'
            elif arg in ['r', 'randomcc']:
                try: self.randomflags = True
                except: print 'Error enabling random flags. (weird)'
            elif arg in ['o', 'output']:
                try:
                    self.output = file(argp[0], 'w')
                    print 'Logging enabled at: %s' % argp[0]
                    self.log = True
                except: print 'Error specifying log location'
            elif arg in ['u', 'sighup']:
                self.sighup = True
            elif arg in ['v', 'latestspringversion']:
                try: self.latestspringversion = argp[0] # ' '.join(argp) # shouldn't have spaces
                except: print 'Error specifying latest spring version'
            elif arg in ['m', 'maxthreads']:
                try: self.max_threads = int(argp[0])
                except: print 'Error specifing max threads'
            elif arg in ['s', 'sqlurl']:
                try:
                    self.sqlurl = argp[0]
                    self.dbtype = 'sql'
                except:
                    print 'Error specifying SQL URL'
            elif arg in ['c', 'no-censor']:
                self.censor = False
            elif arg == 'accounts':
                try:
                    self.engine = argp[0]
                    open(self.engine, 'r').close()
                    self.dbtype = 'legacy'
                except:
                    print 'Error opening legacy accounts.txt database.'
            elif arg == 'tsbans':
                self.tsbanurl = argp[0]
            elif arg == 'channels':
                try:
                    self.channelfile = argp[0]
                    open(self.channelfile, 'r').close()
                except:
                    print 'Error opening ChanServ settings.xml.'
                    self.channelfile = None
            elif arg == 'updates':
                try:
                    self.updatefile = argp[0]
                    open(self.updatefile, 'r').close()
                except:
                    print 'Error opening updates.txt.'
                    self.updatefile = None
            elif arg == 'proxies':
                try:
                    self.trusted_proxyfile = argp[0]
                    open(self.trusted_proxyfile, 'r').close()
                except:
                    print 'Error opening trusted proxy file.'
                    self.trusted_proxyfile = None
                    
        if self.dbtype == 'sql':
            if self.sqlurl == 'sqlite:///:memory:' or self.sqlurl == 'sqlite:///':
                print 'In-memory sqlite databases are not supported.'
                print 'Falling back to LAN mode.'
                print
                self.dbtype = 'lan'
            else:
                try:
                    sqlalchemy = __import__('sqlalchemy')
                    self.engine = sqlalchemy.create_engine(self.sqlurl, pool_recycle=300) # hopefully no thread will open more than two sql connections :/
                    if self.sqlurl.startswith('sqlite'):
                        print 'Multiple threads are not supported with sqlite, forcing a single thread'
                        print 'Please note the server performance will not be optimal'
                        print 'You might want to install a real database server or use LAN mode'
                        print
                        self.max_threads = 1
                except ImportError:
                    print 'sqlalchemy not found or invalid SQL URL, falling back to LAN mode.'
                    self.dbtype = 'lan'
        
        if self.dbtype == 'legacy':
            try:
                self.userdb = LegacyUsers.UsersHandler(self, self.engine)
                self.userdb.readAccounts()
            except:
                print traceback.format_exc()
                print 'Error loading accounts.txt database, falling back to LAN mode.'
                self.dbtype = 'lan'
        elif self.dbtype == 'sql':
            try:
                self.userdb = __import__('SQLUsers').UsersHandler
                self.userdb(self, self.engine)
            except:
                self.dbtype = 'lan'
                print traceback.format_exc()
                print 'Error importing SQL - falling back to LAN mode.'
        
        if self.dbtype == 'lan':
            self.userdb = __import__('LANUsers').UsersHandler(self)
            print 'Warning: LAN mode enabled - many user-specific features will be broken.'
        
        if self.channelfile:
            parser = LegacyChannels.Parser()
            channels = parser.parse(self.channelfile)
            
            userdb = self.getUserDB()
            for name in channels:
                channel = channels[name]
                
                owner = None
                admins = []
                
                client = userdb.clientFromUsername(channel['owner'])
                if client and client.id: owner = client.id
                
                for user in channel['admins']:
                    client = userdb.clientFromUsername(user)
                    if client and client.id:
                        admins.append(client.id)
                
                self.channels[name] = Channel(self, name, chanserv=bool(owner), owner=owner, admins=admins, key=channel['key'], antispam=channel['antispam'], topic={'user':'******', 'text':channel['topic'], 'time':int(time.time()*1000)})
            
            if self.chanserv:
                for name in channels:
                    self.chanserv.client._protocol._handle(self.chanserv.client, 'JOIN %s' % name)
        
        if not self.log:
            try:
                self.output = open('server.log', 'w')
                self.log = True
            except: pass
        
        self.parseFiles()
        
        self.protocol = Protocol(self, None)
    
    def parseFiles(self):
        if os.path.isfile('motd.txt'):
            motd = []
            f = open('motd.txt', 'r')
            data = f.read()
            f.close()
            if data:
                for line in data.split('\n'):
                    motd.append(line.strip())
            self.motd = motd
        
        if self.updatefile:
            self.updates = {}
            f = open(self.updatefile, 'r')
            data = f.read()
            f.close()
            if data:
                for line in data.split('\n'):
                    if not ':' in line: continue
                    left, right = line.split(':', 1)
                    
                    left = left.lower()
                    if ' ' in left:
                        name, version = left.rsplit(' ',1)
                    else:
                        name, version = left, 'default'
                    
                    if not name in self.updates:
                        self.updates[name] = {}
                    
                    if not version in self.updates[name]:
                        self.updates[name][version] = {}
                        
                    self.updates[name][version] = right
        
        if self.trusted_proxyfile:
            self.trusted_proxies = set([])
            f = open(self.trusted_proxyfile, 'r')
            data = f.read()
            f.close()
            if data:
                for line in data.split('\n'):
                    proxy = line.strip()
                    if not proxy.replace('.', '', 3).isdigit():
                        proxy = socket.gethostbyname(proxy)
                    
                    if proxy:
                        self.trusted_proxies.add(proxy)
    
    def getUserDB(self):
        if self.dbtype in ('legacy', 'lan'):
            return self.userdb
        elif self.dbtype == 'sql':
            return self.userdb(self, self.engine)
    
    def clientFromID(self, db_id):
        if db_id in self.db_ids: return self.db_ids[db_id]
    
    def clientFromUsername(self, username):
        if username in self.usernames: return self.usernames[username]

    def event_loop(self):
        start = time.time()
        lastsave = lastmute = lastidle = start
        while self.running:
            now = time.time()
            try:
                if now - lastsave >= 1800: # save every 30 minutes
                    lastsave = now
                    if self.dbtype == 'legacy' and self.userdb:
                        print 'Writing account database to file.',
                        start = time.time()
                        self.userdb.writeAccounts()
                        if self.channelfile:
                            writer = LegacyChannels.Writer()
                            writer.dump(self.channels, self.getUserDB().clientFromID)
                        print '..took %0.2f seconds.' % (time.time() - start)
                    
                if now - lastmute >= 1:
                    lastmute = now
                    self.mute_timeout_step()

                if now - lastidle >= 90:
                    lastidle = now
                    self.idle_timeout_step()
                
                self.console_print_step()
            except:
                self.error(traceback.format_exc())  
                
            time.sleep(max(0.1, 1 - (time.time() - start)))

    def mute_timeout_step(self):
        try:
            now = time.time()
            channels = dict(self.channels)
            for chan in channels:
                channel = channels[chan]
                mutelist = dict(channel.mutelist)
                for db_id in mutelist:
                    expiretime = mutelist[db_id]['expires']
                    if 0 < expiretime and expiretime < now:
                        del channel.mutelist[db_id]
                        channel.channelMessage('<%s> has been unmuted (mute expired).' % self.protocol.clientFromID(db_id).username)
        except:
            self.error(traceback.format_exc())

    def idle_timeout_step(self):
        now = time.time()
        for client in self.clients.values():
            if not client.logged_in and client.last_login < now - 90:
                client.Remove()

    def console_print_step(self):
        try:
            while self.console_buffer:
                line = self.console_buffer.pop(0)
                print line
                if self.log:
                    self.output.write(line+'\n')
            
            if self.output:
                self.output.flush()
        except:
            print separator
            print traceback.format_exc()
            print separator

    def error(self, error):
        error = '%s\n%s\n%s'%(separator,error,separator)
        self.console_write(error)
        for user in dict(self.usernames):
            try:
                if self.usernames[user].debug:
                    for line in error.split('\n'):
                        if line:
                            self.usernames[user].Send('SERVERMSG %s'%line)
            except KeyError: pass # the user was removed

    def console_write(self, lines=''):
        if type(lines) in(str, unicode):
            lines = lines.split('\n')
        elif not type(lines) in (list, tuple, set):
            try: lines = [lines.__repr__()]
            except: lines = ['Failed to print lines of type %s'%type(lines)]
        self.console_buffer += lines
    
    def multicast(self, clients, msg, ignore=()):
        if type(ignore) in (str, unicode): ignore = [ignore]
        static = []
        for client in clients:
            if client and not client.username in ignore:
                if client.static: static.append(client)
                else: client.Send(msg)
        
        # this is so static clients don't respond before other people even receive the message
        for client in static:
            client.Send(msg)
    
    def broadcast(self, msg, chan=None, ignore=()):
        if type(ignore) in (str, unicode): ignore = [ignore]
        try:
            if chan in self.channels:
                channel = self.channels[chan]
                if len(channel.users) > 0:
                    clients = [self.clientFromUsername(user) for user in list(channel.users)]
                    self.multicast(clients, msg, ignore)
            else:
                clients = [self.clientFromUsername(user) for user in list(self.usernames)]
                self.multicast(clients, msg, ignore)
        except: self.error(traceback.format_exc())

    def broadcast_battle(self, msg, battle_id, ignore=[]):
        if type(ignore) in (str, unicode): ignore = [ignore]
        if battle_id in self.battles:
            battle = self.battles[battle_id]
            clients = [self.clientFromUsername(user) for user in list(battle.users)]
            self.multicast(clients, msg, ignore)

    def admin_broadcast(self, msg):
        for user in dict(self.usernames):
            client = self.usernames[user]
            if 'admin' in client.accesslevels:
                client.Send('SERVERMSG Admin broadcast: %s'%msg)

    def _rebind_slow(self):
        try:
            self.parseFiles()
        except:
            self.error(traceback.format_exc())
        
        try:
            self.dispatcher.rebind()
                
            for channel in dict(self.channels): # hack, but I guess reloading is all a hack :P
                chan = self.channels[channel].copy()
                del chan['chan'] # 'cause we're passing it ourselves
                self.channels[channel] = sys.modules['Protocol'].Channel(self, channel, **chan)
            
            self.protocol = Protocol(self, None)
        except:
            self.error(traceback.format_exc())
            
        self.admin_broadcast('Done reloading.')
        self.console_write('Done reloading.')

    def reload(self):
        self.admin_broadcast('Reloading...')
        self.console_write('Reloading...')
        reload(sys.modules['SayHooks'])
        reload(sys.modules['Protocol'])
        reload(sys.modules['ChanServ'])
        reload(sys.modules['Client'])
        if 'SQLUsers' in sys.modules: reload(sys.modules['SQLUsers'])
        elif 'LANUsers' in sys.modules: reload(sys.modules['LANUsers'])
        elif 'tasserver.LegacyUsers' in sys.modules: reload(sys.modules['tasserver.LegacyUsers'])
        self.SayHooks = __import__('SayHooks')
        thread.start_new_thread(self._rebind_slow, ()) # why should reloading block the thread? :)
예제 #45
0
    def play_game(self):
        if self.game_type == "Battleship":
            if self.battleship_setup:
                self.game_ui.setUp(self.game_board)
                states = ""
                for row in range(self.game_board.get_num_rows()):
                    for col in range(self.game_board.get_num_columns()):
                        states += "@" + self.game_board.get_game_state()[row][col]
                states += "@"

                self.send_data(Protocol.set_ship(self.game_id, str(states)))

                self.battleship_setup = False

        if self.player_key == self.game_board.get_player_turn():
            if self.game_type == "Battleship":
                print("\nIt's your turn. Please make your move!!!\n")
            else:
                print("\nIt's your turn. Please make your move!!!\nYour game annotation is: ", self.player_key, "\n")
            
            move = self.game_ui.make_move(self.game_board)

            self.send_data(Protocol.play_game(self.game_id, str(move[0]) + "@" + str(move[1])))
        else:
            print("\nIt is not your turn. Please wait for the next player to make his/her move.")

        _expected_answer = self.receive_data()
        while _expected_answer == "":
            _expected_answer = self.receive_data()

        while _expected_answer != "GAME_OVER":

            if "BS_PRIMARY" in _expected_answer: # for Battleship Primary Grid
                count = 0
                temp = _expected_answer.split('@')
                del temp[0]
                for row in range(self.game_board.get_num_rows()):
                    for col in range(self.game_board.get_num_columns()):
                        self.game_board.primaryGrid1[row][col] = temp[count]
                        count += 1

            if "BS_TRACKING" in _expected_answer: # for Battleship Tracking Grid
                count = 0
                temp = _expected_answer.split('@')
                del temp[0]
                for row in range(self.game_board.get_num_rows()):
                    for col in range(self.game_board.get_num_columns()):
                        self.game_board.trackingGrid1[col][row] = temp[count]
                        count += 1

            if "UPDATE" in _expected_answer:
                count = 0
                temp = _expected_answer.split('@')
                del temp[0]
                for row in range(self.game_board.get_num_rows()):
                    for col in range(self.game_board.get_num_columns()):
                        self.game_board.get_game_state()[row][col] = temp[count]
                        count += 1

            elif "READY" in _expected_answer:
                self.game_ui.print_scores(self.game_board)
                self.game_ui.print_board(self.game_board)
                print("\nIt's your turn. Please make your move!!!\nYour game annotation is: ", self.player_key)
                move = self.game_ui.make_move(self.game_board)
                self.send_data(Protocol.play_game(self.game_id, str(move[0]) + "@" + str(move[1])))

            elif _expected_answer == "SWITCH_PLAYER":
                self.game_board.switch_Turn()

            elif "WAIT" in _expected_answer:
                print("WAIT from client")
                self.game_ui.print_scores(self.game_board)
                self.game_ui.print_board(self.game_board)
                print("\nIt is not your turn. Please wait for the next player to make his/her move.")

            elif "NO_MOVE_FOR_YOU" in _expected_answer:
                print("\nThere is no move for you. Changing the turn.")

            elif _expected_answer == "INVALID_MOVE":
                print("\nInvalid move. Please try it again !!!")
                move = self.game_ui.make_move(self.game_board)
                self.send_data(Protocol.play_game(self.game_id, str(move[0]) + "@" + str(move[1])))
            else:
                pass

            _expected_answer = self.receive_data()

        self.game_ui.print_scores(self.game_board)
        self.game_ui.print_board(self.game_board)
        print(self.game_board.winning_player())
예제 #46
0
 def __init__(self, my_bytes):
     Protocol.__init__(self)
     self._bytes = my_bytes
예제 #47
0
class ProtocolTest (unittest.TestCase):
    def setUp(self):
        self.protocol = Protocol(True)

    def tearDown(self):
        os.remove("test.u1db")
        os.remove("test1.u1db")

    """
   method: protocol
   when: called
   with: typeInsertAndList
   should: insertCorrect
   """
    def test_protocol_called_typeInsertAndList_insertCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"insert","lista":[{"cloud":"Stacksync", "user_eyeos":"eyeID_EyeosUser_2","status": "NEW", "is_root": false, "version": 1, "filename": "clients", "parent_id": "null", "server_modified": "2013-03-08 10:36:41.997", "path": "/documents/clients", "client_modified": "2013-03-08 10:36:41.997", "id": 9873615, "user": "******","is_folder":true}]}'
        else:
            params = '{"type":"insert","lista":[{"user_eyeos":"eyeID_EyeosUser_2","status": "NEW", "is_root": false, "version": 1, "filename": "clients", "parent_id": "null", "server_modified": "2013-03-08 10:36:41.997", "path": "/documents/clients", "client_modified": "2013-03-08 10:36:41.997", "id": 9873615, "user": "******","is_folder":true}]}'
        aux = json.loads(params)
        self.protocol.insert = Mock()
        self.protocol.insert.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.insert.assert_called_once_with(aux['lista'])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeSelectAndList
    should: returnArray
    """
    def test_protocol_called_typeSelectAndList_returnArray(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"select","lista":[{"id":"124568", "user_eyeos":"eyeID_EyeosUser_2", "cloud":"Stacksync", "path":"/documents/clients"}]}'
        else:
            params = '{"type":"select","lista":[{"id":"124568", "user_eyeos":"eyeID_EyeosUser_2", "path":"/documents/clients"}]}'
        aux = json.loads(params)
        self.protocol.select = Mock()
        self.protocol.select.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.select.assert_called_once_with(aux['lista'][0])
        self.assertEquals('[]',result)

    """
    method: protocol
    when: called
    with: typeUpdateAndList
    should: updateCorrect
    """
    def test_protocol_called_typeUpdateAndList_updateCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"update","lista":[{"parent_old":"null"},{"cloud": "Stacksync", "user_eyeos": "eyeID_EyeosUser_2", "status": "NEW", "is_root": false, "version": 1, "filename": "clients", "parent_id": "null", "server_modified": "2013-03-08 10:36:41.997", "path": "/documents/clients", "client_modified": "2013-03-08 10:36:41.997", "id": "9873615", "user": "******","is_folder":true}]}'
        else:
            params = '{"type":"update","lista":[{"parent_old":"null"},{"user_eyeos":"eyeID_EyeosUser_2","status": "NEW", "is_root": false, "version": 1, "filename": "clients", "parent_id": "null", "server_modified": "2013-03-08 10:36:41.997", "path": "/documents/clients", "client_modified": "2013-03-08 10:36:41.997", "id": "9873615", "user": "******","is_folder":true}]}'
        aux = json.loads(params)
        self.protocol.update = Mock()
        self.protocol.update.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.update.assert_called_once_with(aux['lista'])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeDeleteAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteAndList_deleteCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"delete","lista":[{"id":1234, "user_eyeos":"eyeID_EyeosUser_2", "cloud": "Stacksync", "parent_id":"3456"},{"id":"8907", "user_eyeos":"eyeID_EyeosUser_2", "cloud": "Stacksync", "parent_id":"3456"}]}'
        else:
            params = '{"type":"delete","lista":[{"id":1234,"user_eyeos":"eyeID_EyeosUser_2","parent_id":"3456"},{"id":"8907","user_eyeos":"eyeID_EyeosUser_2","parent_id":"3456"}]}'
        aux = json.loads(params)
        self.protocol.delete = Mock()
        self.protocol.delete.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.delete.assert_called_once_with(aux['lista'])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeGetParentAndPath
    should: returnArray
    """
    def test_protocol_called_typeGetParentAndList_returnArray(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"parent", "lista":[{"cloud": "Stacksync", "path":"/Documents/", "filename":"prueba", "user_eyeos":"eyeID_EyeosUser_2"}]}'
        else:
            params = '{"type":"parent", "lista":[{"path":"/Documents/", "filename":"prueba", "user_eyeos":"eyeID_EyeosUser_2"}]}'
        aux = json.loads(params)
        self.protocol.getParent = Mock()
        self.protocol.getParent.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.getParent.assert_called_once_with(aux[ 'lista' ][0])
        self.assertEquals('[]',result)

    """
    method: protocol
    when: called
    with: typeDeleteFolderAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteFolderAndList_deleteCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"deleteFolder","lista":[{"id":"1234","user_eyeos":"eyeID_EyeosUser_2", "cloud":"Stacksync", "path":"/documents/clients"}]}'
        else:
            params = '{"type":"deleteFolder","lista":[{"id":"1234","user_eyeos":"eyeID_EyeosUser_2","path":"/documents/clients"}]}'
        aux = json.loads(params)
        self.protocol.deleteFolder = Mock()
        self.protocol.deleteFolder.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteFolder.assert_called_once_with(aux[ 'lista' ][0])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeDeleteMetadataUserAndListUser
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteMetadataUserAndListUser_deleteCorrect(self):
        params = '{"type":"deleteMetadataUser","lista":[{"user_eyeos":"eyeID_EyeosUser_2"}]}'
        self.protocol.deleteMetadataUser = Mock()
        self.protocol.deleteMetadataUser.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteMetadataUser.assert_called_once_with(json.loads(params)['lista'])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeDeleteMetadataUserAndListUserAndCloud
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteMetadataUserAndListUserAndCloud_deleteCorrect(self):
        params = '{"type":"deleteMetadataUser","lista":[{"user_eyeos":"eyeID_EyeosUser_2", "cloud":"Stacksync"}]}'
        self.protocol.deleteMetadataUser = Mock()
        self.protocol.deleteMetadataUser.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteMetadataUser.assert_called_once_with(json.loads(params)['lista'])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeSelectMetatadataUserAndList
    should: returnArray
    """
    def test_protocol_called_typeSelectMetadataUserAndList_returnArray(self):
        params = '{"type":"selectMetadataUser","lista":[{"user_eyeos":"eyeID_EyeosUser_2"}]}'
        self.protocol.selectMetadataUser = Mock()
        self.protocol.selectMetadataUser.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.selectMetadataUser.assert_called_once_with("eyeID_EyeosUser_2")
        self.assertEquals('[]',result)

    """
    method: protocol
    when: called
    with: typeRenameMetadataAndUserAndList
    """
    def test_protocol_called_typeRenameMetadataAndUserAndList_renameCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type": "rename", "lista": [{"user_eyeos": "eyeID_EyeosUser_2", "cloud": "Stacksync", "status": "NEW", "version": 1, "filename": "prueba.txt", "parent_id": "null", "server_modified": "2013-03-08 10:36:41.997", "path": "/", "client_modified": "2013-03-08 10:36:41.997", "id": "9873615", "user": "******","is_folder":false}]}'
        else:
            params = '{"type": "rename", "lista": [{"user_eyeos": "eyeID_EyeosUser_2", "status": "NEW", "version": 1, "filename": "prueba.txt", "parent_id": "null", "server_modified": "2013-03-08 10:36:41.997", "path": "/", "client_modified": "2013-03-08 10:36:41.997", "id": "9873615", "user": "******","is_folder":false}]}'
        aux = json.loads(params)
        self.protocol.renameMetadata = Mock()
        self.protocol.renameMetadata.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.renameMetadata.assert_called_once_with(aux[ 'lista' ][0])
        self.assertEquals('true',result)


    """
  ##################################################################################################################################################
                                                                  TEST DOWNLOAD FILES
  ##################################################################################################################################################
  """

    """
    method: protocol
    when: called
    with: typeInsertDownloadVersionAndList
    should: insertCorrect
    """
    def test_protocol_called_typeInsertDownloadVersionAndList_insertCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type": "insertDownloadVersion", "lista": [{"id": "9873615", "cloud": "Stacksync", "user_eyeos": "eyeID_EyeosUser_2", "version": "2", "recover": false}]}'
        else:
            params = '{"type": "insertDownloadVersion", "lista": [{"id": "9873615", "user_eyeos": "eyeID_EyeosUser_2", "version": "2", "recover": false}]}'
        aux = json.loads(params)
        self.protocol.insertDownloadVersion = Mock()
        self.protocol.insertDownloadVersion.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.insertDownloadVersion.assert_called_once_with(aux[ 'lista' ][0])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeUpdateDownloadVersionAndList
    should: updateCorrect
    """
    def test_protocol_called_typeUpdateDownloadVersionAndList_updateCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type": "updateDownloadVersion", "lista": [{"id": "9873615", "cloud": "Stacksync", "user_eyeos": "eyeID_EyeosUser_2", "version": "3", "recover": false}]}'
        else:
            params = '{"type": "updateDownloadVersion", "lista": [{"id": "9873615", "user_eyeos": "eyeID_EyeosUser_2", "version": "3", "recover": false}]}'
        aux = json.loads(params)
        self.protocol.updateDownloadVersion = Mock()
        self.protocol.updateDownloadVersion.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.updateDownloadVersion.assert_called_once_with(aux[ 'lista' ][0])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeDeleteDownloadVersionAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteDownloadVersionAndList_deleteCorrect(self):
        params = '{"type":"deleteDownloadVersion","lista":[{"id":"9873615","user_eyeos":"eyeID_EyeosUser_2"}]}'
        self.protocol.deleteDownloadVersion = Mock()
        self.protocol.deleteDownloadVersion.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteDownloadVersion.assert_called_once_with("9873615","eyeID_EyeosUser_2")
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeGetDownloadVersionAndList
    should: returnMetadata
    """
    def test_protocol_called_typeGetDownloadVersionAndList_returnMetadata(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"getDownloadVersion","lista":[{"id": "9873615", "user_eyeos": "eyeID_EyeosUser_2", "cloud": "Stacksync"}]}'
            expected = {"id": "9873615", "cloud": "Stacksync", "user_eyeos": "eyeID_EyeosUser_2", "version": "3", "recover": False}
        else:
            params = '{"type":"getDownloadVersion","lista":[{"id": "9873615", "user_eyeos": "eyeID_EyeosUser_2"}]}'
            expected = {"id": "9873615", "user_eyeos": "eyeID_EyeosUser_2", "version": "3", "recover": False}
        aux = json.loads(params)
        self.protocol.getDownloadVersion = Mock()
        self.protocol.getDownloadVersion.return_value = expected
        result = self.protocol.protocol(params)
        self.protocol.getDownloadVersion.assert_called_once_with(aux[ 'lista' ][0])
        self.assertEquals(json.dumps(expected), result)

    """
    method: protocol
    when: called
    with: typeRecursiveDeleteVersionAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeRecursiveDeleteVersionAndList_deleteCorrect(self):
        if settings[ 'NEW_CODE' ] == "true":
            params = '{"type":"recursiveDeleteVersion","lista":[{"cloud":"Stacksync","id":"9873615","user_eyeos":"eyeID_EyeosUser_2"}]}'
        else:
            params = '{"type":"recursiveDeleteVersion","lista":[{"id":"9873615","user_eyeos":"eyeID_EyeosUser_2"}]}'

        aux = json.loads(params)
        self.protocol.recursiveDeleteVersion = Mock()
        self.protocol.recursiveDeleteVersion.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.recursiveDeleteVersion.assert_called_once_with(aux['lista'][0])
        self.assertEquals('true',result)

    """
   ##################################################################################################################################################
                                                                   TEST CALENDAR
   ##################################################################################################################################################
   """

    """
    method: protocol
    when: called
    with: typeDeleteEventAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteEventAndList_deleteCorrect(self):
        params = '{"type":"deleteEvent" , "lista":[{"type":"event","user_eyeos": "eyeos","calendar": "personal", "status":"DELETED" ,"isallday":"0", "timestart": "201419160000", "timeend":"201419170000", "repetition": "None", "finaltype": "1", "finalvalue": "0", "subject": "Visita Médico", "location": "Barcelona", "description": "Llevar justificante"},{"type":"event","user_eyeos": "eyeos","calendarid": "eyeID_Calendar_2b", "isallday": "1", "timestart": "201420160000", "timeend":"201420170000", "repetition": "None", "finaltype": "1", "finalvalue": "0", "subject": "Excursión", "location": "Girona", "description": "Mochila"}]}'
        aux = json.loads(params)
        self.protocol.deleteEvent = Mock()
        self.protocol.deleteEvent.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteEvent.assert_called_once_with(aux['lista'])
        self.assertEquals("true",result)

    """
    method: protocol
    when: called
    with: typeUpdateEventAndList
    should: updateCorrect
    """
    def test_protocol_called_typeUpdateEventAndList_updateCorrect(self):
        params = '{"type":"updateEvent" , "lista":[{"type":"event","user_eyeos": "eyeos","calendar": "personal", "status":"CHANGED", "isallday":"0", "timestart": "201419160000", "timeend":"201419170000", "repetition": "None", "finaltype": "1", "finalvalue": "0", "subject": "Visita Médico", "location": "Barcelona", "description": "Llevar justificante"},{"type":"event","user_eyeos": "eyeos","calendarid": "eyeID_Calendar_2b", "isallday": "1", "timestart": "201420160000", "timeend":"201420170000", "repetition": "None", "finaltype": "1", "finalvalue": "0", "subject": "Excursión", "location": "Girona", "description": "Mochila"}]}'
        aux = json.loads(params)
        self.protocol.updateEvent = Mock()
        self.protocol.updateEvent.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.updateEvent.assert_called_once_with(aux['lista'])
        self.assertEquals("true",result)

    """
    method: protocol
    when: called
    with: typeSelectEventAndList
    should: return Array
    """
    def test_protocol_called_typeSelectEventAndList_returnArray(self):
        params = '{"type":"selectEvent","lista":[{"type":"event","user_eyeos":"eyeos","calendar":"personal"}]}'
        aux = json.loads(params)
        self.protocol.selectEvent = Mock()
        self.protocol.selectEvent.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.selectEvent.assert_called_once_with("event","eyeos","personal")
        self.assertEquals("[]",result)

    """
    method: protocol
    when: called
    with: typeInsertEventAndList
    should: insertCorrect
    """
    def test_protocol_called_typeInsertEventAndList_insertCorrect(self):
        params = '{"type":"insertEvent" , "lista":[{"type":"event","user_eyeos": "eyeos","calendar": "personal", "status":"NEW", "isallday":"0", "timestart": "201419160000", "timeend":"201419170000", "repetition": "None", "finaltype": "1", "finalvalue": "0", "subject": "Visita Médico", "location": "Barcelona", "description": "Llevar justificante"},{"type":"event","user_eyeos": "eyeos","calendarid": "eyeID_Calendar_2b", "isallday": "1", "timestart": "201420160000", "timeend":"201420170000", "repetition": "None", "finaltype": "1", "finalvalue": "0", "subject": "Excursión", "location": "Girona", "description": "Mochila"}]}'
        aux = json.loads(params)
        self.protocol.insertEvent = Mock()
        self.protocol.insertEvent.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.insertEvent.assert_called_once_with(aux['lista'])
        self.assertEquals("true",result)


    """
   method: protocol
   when: called
   with: typeInsertCalendarAndList
   should: insertCorrect
   """
    def test_protocol_called_typeInsertCalendarAndList_insertCorrect(self):
        params = '{"type":"insertCalendar" , "lista":[{"type":"calendar","user_eyeos": "eyeos","name": "personal", "status":"NEW","description":"personal calendar","timezone":0}]}'
        aux = json.loads(params)
        self.protocol.insertCalendar = Mock()
        self.protocol.insertCalendar.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.insertCalendar.assert_called_once_with(aux['lista'])
        self.assertEquals("true",result)

    """
    method: protocol
    when: called
    with: typeDeleteCalendarAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteCalendarAndList_deleteCorrect(self):
        params = '{"type":"deleteCalendar" , "lista":[{"type":"calendar","user_eyeos": "eyeos","name": "personal"}]}'
        aux = json.loads(params)
        self.protocol.deleteCalendar = Mock()
        self.protocol.deleteCalendar.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteCalendar.assert_called_once_with(aux['lista'])
        self.assertEquals("true",result)


    """
    method: protocol
    when: called
    with: typeSelectCalendarAndList
    should: returnArray
    """
    def test_protocol_called_typeSelectCalendarAndList_returnArray(self):
        params = '{"type":"selectCalendar" , "lista":[{"type":"calendar","user_eyeos": "eyeos"}]}'
        aux = json.loads(params)
        self.protocol.selectCalendar = Mock()
        self.protocol.selectCalendar.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.selectCalendar.assert_called_once_with(aux['lista'][0])
        self.assertEquals("[]",result)

    """
   method: protocol
   when: called
   with: typeUpdateCalendarAndList
   should: updateCorrect
   """
    def test_protocol_called_typeUpdateCalendarAndList_updateCorrect(self):
        params = '{"type":"updateCalendar" , "lista":[{"type":"calendar","user_eyeos": "eyeos","name":"personal","description":"personal calendar","timezone":0,"status":"CHANGED"}]}'
        aux = json.loads(params)
        self.protocol.updateCalendar = Mock()
        self.protocol.updateCalendar.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.updateCalendar.assert_called_once_with(aux['lista'])
        self.assertEquals("true",result)

    """
    method: protocol
    when: called
    with: typeDeleteCalendarUserAndList
    should: deleteCorrect
    """
    def test_protocol_called_typeDeleteCalendarUserAndList_deleteCorrect(self):
        params = '{"type":"deleteCalendarUser","lista":[{"user_eyeos":"eyeos"}]}'
        self.protocol.deleteCalendarUser = Mock()
        self.protocol.deleteCalendarUser.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.deleteCalendarUser.assert_called_once_with("eyeos")
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: selectCalendarsAndEventsAndList
    should: returnArray
    """
    def test_protocol_called_selectCalendarsAndEventsAndList_returnArray(self):
        params = '{"type":"selectCalendarsAndEvents","lista":[{"user_eyeos":"eyeos"}]}'
        self.protocol.selectCalendarsAndEvents = Mock()
        self.protocol.selectCalendarsAndEvents.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.selectCalendarsAndEvents.assert_called_once_with("eyeos")
        self.assertEquals('[]',result)

    """
    ##################################################################################################################################################
                                                               TEST LOCK FILE
    ##################################################################################################################################################
    """



    """
    method: protocol
    when: called
    with: typeGetMetadataFileAndList
    should: returnArray
    """
    def test_protocol_called_typeGetMetadataFileAndList_returnArray(self):
        params = '{"type":"getMetadataFile","lista":[{"id":"124568","cloud":"Stacksync"}]}'
        self.protocol.getMetadataFile = Mock()
        self.protocol.getMetadataFile.return_value = []
        result = self.protocol.protocol(params)
        self.protocol.getMetadataFile.assert_called_once_with("124568","Stacksync")
        self.assertEquals('[]',result)


    """
    method: protocol
    when: called
    with: typeLockFileAndList
    should: correctBlock
    """

    def test_protocol_called_typeLockFileAndList_returnCorrectBlock(self):
        params = '{"type":"lockFile","lista":[{"id":"124568","cloud":"Stacksync","username":"******","IpServer":"192.168.56.101","datetime":"2015-05-12 10:50:00","status":"open","timeLimit":10}]}'
        aux = json.loads(params)
        self.protocol.lockFile = Mock()
        self.protocol.lockFile.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.lockFile.assert_called_once_with(aux['lista'][0])
        self.assertEquals('true',result)


    """
    method: protocol
    when: called
    with: typeUpdateDateTimeAndList
    should: updateCorrect
    """
    def test_protocol_called_typeUpdateDateTimeAndList_returnCorrectBlock(self):
        params = '{"type":"updateDateTime","lista":[{"id":"124568","cloud":"Stacksync","username":"******","IpServer":"192.168.56.101","datetime":"2015-05-12 10:50:00","status":"open"}]}'
        aux = json.loads(params)
        self.protocol.updateDateTime = Mock()
        self.protocol.updateDateTime.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.updateDateTime.assert_called_once_with(aux['lista'][0])
        self.assertEquals('true',result)

    """
    method: protocol
    when: called
    with: typeUnLockFileAndList
    should: returnCorrectUnBlock
    """
    def test_protocol_called_typeUnLockFileAndList_returnCorrectUnBlock(self):
        params = '{"type":"unLockFile","lista":[{"id":"124568","cloud":"Stacksync","username":"******","IpServer":"192.168.56.101","datetime":"2015-05-12 10:50:00","status":"close"}]}'
        aux = json.loads(params)
        self.protocol.unLockFile = Mock()
        self.protocol.unLockFile.return_value = True
        result = self.protocol.protocol(params)
        self.protocol.unLockFile.assert_called_once_with(aux['lista'][0])
        self.assertEquals('true',result)
예제 #48
0
 def setUp(self):
     self.protocol = Protocol(True)
예제 #49
0
파일: Model.py 프로젝트: DanFaudemer/TFC
class Model(Thread):
    def __init__(self, **kwargs):
        Thread.__init__(self)
        # Serial thread
        self.serialthread = SerialPort()
        # Controller Read/Write variables over serial
        self.controller = DistantIO()
        # Serial protocol
        self.protocol = Protocol()
        # Variable manager
        self.variable_manager = VariableManager(self)
        self.variable_manager.start()
        self.running = True;
        # Data logger
        self.logger = DataLogger()
        
    def get_ports(self):
        return self.serialthread.get_ports()
        
    def connect_com(self,COM_port):
        # Start serial thread (can run without COM port connected)
        if not self.serialthread.isAlive():
            self.serialthread.start()
            
        self.serialthread.connect(COM_port,115200)

    #Model update running in a thread
    def run(self):
        while self.running:
            if self.serialthread.char_available():
                c = self.serialthread.get_char()
                if not c is None:
                    self.protocol.process_rx(c)

            if self.protocol.available():
                p =  self.protocol.get()
                # Dump payload if controller is in heavy load ?
                pub.sendMessage('new_rx_payload',rxpayload=p)#USED ?
                if not p is None:
                    self.controller.decode(p)

    def disconnect_com(self):
        self.serialthread.disconnect()
         
    def stop(self):
        self.running = False
        self.serialthread.stop()
        self.variable_manager.stop()

        if self.serialthread.isAlive():
            self.serialthread.join(0.1)
            
        if self.serialthread.isAlive():
            self.serialthread.join(1)

        if self.serialthread.isAlive():
            print("--- Serial thread not properly joined.")

        if self.variable_manager.isAlive():
            self.variable_manager.join(0.1)
            
        if self.variable_manager.isAlive():
            self.variable_manager.join(1)
            
        self.stop_controller()
        
    def start_controller(self):
        #Get command for querying variable table MCU side
        cmd = self.controller.encode(cmd='table')
        #Feed command to serial protocol payload processor
        frame = self.protocol.process_tx(cmd)        
        #Send command
        self.serialthread.write(frame)      
        
    def stop_controller(self):
        #TODO : Tell MCU to stop sending all data
        pass

    def start_log(self):
        self.logger.start()
        
    def stop_log(self):
        self.logger.record_all()

    def read_var(self, varid):        
        # Get command
        cmd = self.controller.encode(cmd='read',var_id=varid)
        # Feed command to serial protocol payload processor
        frame = self.protocol.process_tx(cmd)
        # Send command
        self.serialthread.write(frame)

    def write_var(self,varid,value):
        # Get command
        cmd = self.controller.encode(cmd='write',var_id=varid,value=value)
        if cmd == None:
            return
        # Feed command to serial protocol payload processor
        frame = self.protocol.process_tx(cmd)
        # Send command
        self.serialthread.write(frame)
        
    def stop_read_var(self,varid):
        # Get command
        cmd = self.controller.encode(cmd='stop',var_id=varid)
        if cmd == None:
            return
        # Feed command to serial protocol payload processor
        frame = self.protocol.process_tx(cmd)
        # Send command
        self.serialthread.write(frame)
        
    def stop_read_all_vars():
        # Get command
        cmd = self.controller.encode(cmd='stopall')
        if cmd == None:
            return
        # Feed command to serial protocol payload processor
        frame = self.protocol.process_tx(cmd)
        # Send command
        self.serialthread.write(frame)
        
    def get_var_info(self,varid):
        return self.controller.get_var_info(varid)
예제 #50
0
    def parseArgv(self, argv):
        'parses command-line options'
        args = {'ignoreme':[]}
        mainarg = 'ignoreme'

        tempargv = list(argv)
        while tempargv:
            arg = tempargv.pop(0)
            if arg.startswith('-'):
                mainarg = arg.lstrip('-').lower()

                if mainarg in ['g', 'loadargs']:
                    try:
                        name = tempargv[0]
                        if name.startswith('-'): raise Exception
                        f = file(name, 'r')
                        lines = f.read().split('\n')
                        f.close()

                        tempargv += ' '.join(lines).split(' ')
                    except:
                        pass

                args[mainarg] = []
            else:
                args[mainarg].append(arg)
        del args['ignoreme']

        for arg in args:
            argp = args[arg]
            if arg in ['h', 'help']:
                print 'Usage: server.py [OPTIONS]...'
                print 'Starts uberserver.'
                print
                print 'Options:'
                print '  -h, --help'
                print '      { Displays this screen then exits }'
                print '  -p, --port number'
                print '      { Server will host on this port (default is 8200) }'
                print '  -n, --natport number'
                print '      { Server will use this port for NAT transversal (default is 8201) }'
                print '  -l, --lan'
                print '      { Users do not need to be registered to login - breaks rudimentary features like channel ops/founders, channel/battle bans, etc. }'
                print '  -a, --lanadmin username password [hash] }'
                print '      { Hardcoded admin account for LAN. If third arg reads "hash" it will apply the standard hash algorithm to the supplied password }'
                print '  -g, --loadargs filename'
                print '      { Reads additional command-line arguments from file }'
                print '  -r  --randomflags'
                print '      { Randomizes country codes (flags) }'
                print '  -o, --output /path/to/file.log'
                print '      { Writes console output to file (for logging) }'
                print '  -u, --sighup'
                print '      { Reload the server on SIGHUP (if SIGHUP is supported by OS) }'
                print '  -v, --latestspringversion version'
                print '      { Sets latest Spring version to this string. Defaults to "*" }'
                print '  -m, --maxthreads number'
                print '      { Uses the specified number of threads for handling clients }'
                print '  -s, --sqlurl SQLURL'
                print '      { Uses SQL database at the specified sqlurl for user, channel, and ban storage. }'
                print '  -c, --no-censor'
                print '      { Disables censoring of #main, #newbies, and usernames (default is to censor) }'
                print '  --accounts /path/to/accounts.txt'
                print '      { Path to accounts.txt. For using the legacy TASServer account database. }'
                print '  --tsbans SQLURL'
                print '      { Uses SQL database at the specified sqlurl as a legacy TASServer ban database. } '
                print '  --channels /path/to/settings.xml'
                print '      { Path to ChanServ settings.xml, for using the legacy ChanServ channel database. }'
                print '  --updates /path/to/updates.txt'
                print '     { Path to updates.txt, for using Spring update system. }'
                print '  --proxies /path/to/proxies.txt'
                print '     { Path to proxies.txt, for trusting proxies to pass real IP through local IP }'
                print 'SQLURL Examples:'
                #print '  "sqlite:///:memory:" or "sqlite:///"'
                #print '     { both make a temporary database in memory }'
                print '  "sqlite:////absolute/path/to/database.txt"'
                print '     { uses a database in the file specified }'
                print '  "sqlite:///relative/path/to/database.txt"'
                print '     { note sqlite is slower than a real SQL server }'
                print '  "mysql://*****:*****@server:port/database"'
                print '     { requires the MySQLdb module }'
                print '  "oracle://*****:*****@server:port/database"'
                print '     { requires the cx_Oracle module }'
                print '  "postgres://*****:*****@server:port/database"'
                print '     { requires the psycopg2 module }'
                print '  "mssql://*****:*****@server:port/database"'
                print '     { requires pyodbc (recommended) or adodbapi or pymssql }'
                print '  "firebird://*****:*****@server:port/database"'
                print '     { requires the kinterbasdb module }'
                print
                print 'Usage example (this is what the test server uses at the moment):'
                print ' server.py -p 8300 -n 8301'
                print
                exit()
            if arg in ['p', 'port']:
                try: self.port = int(argp[0])
                except: print 'Invalid port specification'
            elif arg in ['n', 'natport']:
                try: self.natport = int(argp[0])
                except: print 'Invalid NAT port specification'
            elif arg in ['l', 'lan']:
                self.dbtype = 'lan'
            elif arg in ['a', 'lanadmin']:
                try:
                    if len(argp) > 2:
                        if argp[2] == 'hash':
                            m = md5(argp[1])
                            argp[1] = base64.b64encode(m.digest())
                    self.lanadmin = {'username':argp[0], 'password':argp[1]}
                except: print 'Invalid LAN admin specified'
            elif arg in ['r', 'randomcc']:
                try: self.randomflags = True
                except: print 'Error enabling random flags. (weird)'
            elif arg in ['o', 'output']:
                try:
                    self.output = file(argp[0], 'w')
                    print 'Logging enabled at: %s' % argp[0]
                    self.log = True
                except: print 'Error specifying log location'
            elif arg in ['u', 'sighup']:
                self.sighup = True
            elif arg in ['v', 'latestspringversion']:
                try: self.latestspringversion = argp[0] # ' '.join(argp) # shouldn't have spaces
                except: print 'Error specifying latest spring version'
            elif arg in ['m', 'maxthreads']:
                try: self.max_threads = int(argp[0])
                except: print 'Error specifing max threads'
            elif arg in ['s', 'sqlurl']:
                try:
                    self.sqlurl = argp[0]
                    self.dbtype = 'sql'
                except:
                    print 'Error specifying SQL URL'
            elif arg in ['c', 'no-censor']:
                self.censor = False
            elif arg == 'accounts':
                try:
                    self.engine = argp[0]
                    open(self.engine, 'r').close()
                    self.dbtype = 'legacy'
                except:
                    print 'Error opening legacy accounts.txt database.'
            elif arg == 'tsbans':
                self.tsbanurl = argp[0]
            elif arg == 'channels':
                try:
                    self.channelfile = argp[0]
                    open(self.channelfile, 'r').close()
                except:
                    print 'Error opening ChanServ settings.xml.'
                    self.channelfile = None
            elif arg == 'updates':
                try:
                    self.updatefile = argp[0]
                    open(self.updatefile, 'r').close()
                except:
                    print 'Error opening updates.txt.'
                    self.updatefile = None
            elif arg == 'proxies':
                try:
                    self.trusted_proxyfile = argp[0]
                    open(self.trusted_proxyfile, 'r').close()
                except:
                    print 'Error opening trusted proxy file.'
                    self.trusted_proxyfile = None
                    
        if self.dbtype == 'sql':
            if self.sqlurl == 'sqlite:///:memory:' or self.sqlurl == 'sqlite:///':
                print 'In-memory sqlite databases are not supported.'
                print 'Falling back to LAN mode.'
                print
                self.dbtype = 'lan'
            else:
                try:
                    sqlalchemy = __import__('sqlalchemy')
                    self.engine = sqlalchemy.create_engine(self.sqlurl, pool_recycle=300) # hopefully no thread will open more than two sql connections :/
                    if self.sqlurl.startswith('sqlite'):
                        print 'Multiple threads are not supported with sqlite, forcing a single thread'
                        print 'Please note the server performance will not be optimal'
                        print 'You might want to install a real database server or use LAN mode'
                        print
                        self.max_threads = 1
                except ImportError:
                    print 'sqlalchemy not found or invalid SQL URL, falling back to LAN mode.'
                    self.dbtype = 'lan'
        
        if self.dbtype == 'legacy':
            try:
                self.userdb = LegacyUsers.UsersHandler(self, self.engine)
                self.userdb.readAccounts()
            except:
                print traceback.format_exc()
                print 'Error loading accounts.txt database, falling back to LAN mode.'
                self.dbtype = 'lan'
        elif self.dbtype == 'sql':
            try:
                self.userdb = __import__('SQLUsers').UsersHandler
                self.userdb(self, self.engine)
            except:
                self.dbtype = 'lan'
                print traceback.format_exc()
                print 'Error importing SQL - falling back to LAN mode.'
        
        if self.dbtype == 'lan':
            self.userdb = __import__('LANUsers').UsersHandler(self)
            print 'Warning: LAN mode enabled - many user-specific features will be broken.'
        
        if self.channelfile:
            parser = LegacyChannels.Parser()
            channels = parser.parse(self.channelfile)
            
            userdb = self.getUserDB()
            for name in channels:
                channel = channels[name]
                
                owner = None
                admins = []
                
                client = userdb.clientFromUsername(channel['owner'])
                if client and client.id: owner = client.id
                
                for user in channel['admins']:
                    client = userdb.clientFromUsername(user)
                    if client and client.id:
                        admins.append(client.id)
                
                self.channels[name] = Channel(self, name, chanserv=bool(owner), owner=owner, admins=admins, key=channel['key'], antispam=channel['antispam'], topic={'user':'******', 'text':channel['topic'], 'time':int(time.time()*1000)})
            
            if self.chanserv:
                for name in channels:
                    self.chanserv.client._protocol._handle(self.chanserv.client, 'JOIN %s' % name)
        
        if not self.log:
            try:
                self.output = open('server.log', 'w')
                self.log = True
            except: pass
        
        self.parseFiles()
        
        self.protocol = Protocol(self, None)