def main(self): (self.options, args) = self.parser.parse_args() #print("===================================") #print(self.options, args) #self.usage() #print(self.config) #print("===================================") protocol = Protocol() if self.options.id2ip : print(protocol.id2ip(int(self.options.cai), int(self.options.id2ip))) elif self.options.ip2id : print(protocol.ip2id(str(self.options.ip2id))) elif self.options.tms : tms = TMS() tms.sendtoid(int(self.options.cai), int(self.options.tms), args[0]) elif self.options.route : print("Please add the following route:") print("route add %s.0.0.0 mask 255.0.0.0 192.168.11.1" % self.options.cai) elif self.options.ping : os.system("ping %s" % self.options.ping) elif self.options.online : os.system("ping %s" % protocol.id2ip(int(self.options.cai), int(self.options.online))) else: self.usage()
def btn_6_delete(self): data = [] id_line = {} row_count = self.tableWidget_6_delete.rowCount() for i in range(row_count): id = self.tableWidget_6_delete.item(i, 0).text() # 不需要发送其他信息,因为服务器只用id检索条目进行删除 if not id: id = "$" name = "$" sex = "$" age = "$" #name = self.tableWidget_6_delete.item(i, 1).text() #sex = self.tableWidget_6_delete.item(i, 2).text() #age = self.tableWidget_6_delete.item(i, 3).text() if not re.match(r"\b\d{6}\b", id): self.tableWidget_6_delete.setItem(i, 4, QtWidgets.QTableWidgetItem("Error")) continue item_str = Protocol.item_pack(id, name, sex, age) id_line[id] = i data.append(item_str) # 发送信息 header = Protocol.gen_default_header() smsg = Protocol.msg_pack("DELETE", header, data) sock.send(smsg.encode("unicode_escape")) # 接收服务器发回的信息 rmsg = sock.recv(1024).decode("unicode_escape") print(rmsg) rst = Protocol.msg_unpack(rmsg) rhear_line = rst[0] rheader = rst[1] rdata = rst[2] for id in id_line: self.tableWidget_6_delete.setItem(id_line[id], 4, QtWidgets.QTableWidgetItem(rheader[id]))
def setSpeed(self, pluginAction, dev): try: newValue = int(pluginAction.props.get(u"speed", 100)) except ValueError: # The int() cast above might fail if the user didn't enter a number: indigo.server.log(u"set speed to device \"%s\" -- invalid value" % (dev.name), isError=True) return m = Magiccolor() m.connect() p = Protocol() p.keyNum=p.MODE_SPEED p.keyValue=newValue m.sendMsg(p) sendSuccess = True # Set to False if it failed. if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s to %d" % (dev.name, "set speed", newValue)) # And then tell the Indigo Server to update the state: dev.updateStateOnServer("programNumber", newValue) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s to %d failed" % (dev.name, "set speed", newValue), isError=True)
def get_value_4(Window, entry1, entry2, entry3, entry4, protocole, ProtoWindow): """ This program gets 4 values from a label. Entry: Window(Frame): the protocol window entry1(Label variable): the first value to get entry2(Label variable): the second value to get entry3(Label variable): the third value to get entry4(Label variable): the fourth value to get protocole(list): the list of the protocole ProtoWindow(Frame): the protocol frame """ pos = protocole.index(['position']) protocole[pos - 1] = [ protocole[pos - 1][0], entry1.get(), entry2.get(), entry3.get(), entry4.get() ] Prot.EcrireProtocoleFichier(protocole, 'temp.txt') Prot.AfficherProtocol(ProtoWindow, protocole) Window.destroy()
def __handle_existing_connections(self): # IF no_errors then: # Gets the player's move (who's turn is up) num, msg = Protocol.recv_all(self.players_sockets[self.turn]) if num == Protocol.NetworkErrorCodes.DISCONNECTED: Protocol.send_all(self.players_sockets[1 - self.turn], 'EXIT') self.shut_down_server() # Sends the move to his opponent if num != Protocol.NetworkErrorCodes.FAILURE: eNum, eMsg = Protocol.send_all(self.players_sockets[1 - self.turn], msg) if eNum == Protocol.NetworkErrorCodes.FAILURE: Protocol.send_all(self.players_sockets[self.turn], 'EXIT') self.shut_down_server() # Receives the opponent's response num, msg = Protocol.recv_all(self.players_sockets[1- self.turn]) if num == Protocol.NetworkErrorCodes.FAILURE: print msg self.shut_down_server() if num == Protocol.NetworkErrorCodes.DISCONNECTED: Protocol.send_all(self.players_sockets[self.turn], 'EXIT') self.shut_down_server() # Sends the response back to the player who's turn is up eNum, eMsg = Protocol.send_all(self.players_sockets[self.turn], msg) if eNum: print eMsg self.close_client()
def setPause(self, pluginAction, dev): newValue = pluginAction.props.get(u"pauseRun", False) m = Magiccolor() m.connect() p = Protocol() p.keyNum=p.MODE_PAUSE indigo.server.log("%d" % newValue) if newValue: p.keyValue=1 else: p.keyValue=0 m.sendMsg(p) sendSuccess = True # Set to False if it failed. if sendSuccess: # If success then log that the command was successfully sent. indigo.server.log(u"sent \"%s\" %s to %d" % (dev.name, "pause", newValue)) # And then tell the Indigo Server to update the state: dev.updateStateOnServer("pauseRun", newValue) else: # Else log failure but do NOT update state on Indigo Server. indigo.server.log(u"send \"%s\" %s to %d failed" % (dev.name, "set pause", newValue), isError=True)
def btn_4_search(self): id = self.lineEdit_4_old_id.text() if not id: id = "$" name = "$" sex = "$" age = "$" data = [] item_str = Protocol.item_pack(id, name, sex, age) data.append(item_str) header = Protocol.gen_default_header() smsg = Protocol.msg_pack("SEARCH", header, data) #print(smsg, end="") sock.send(smsg.encode("unicode_escape")) rmsg = sock.recv(1024).decode("unicode_escape") print(rmsg) rst = Protocol.msg_unpack(rmsg) rhead_line = rst[0] rheader = rst[1] rdata = rst[2] #item_str = rdata[0] if len(rdata)>0: item_str = rdata[0] item = item_str.split() self.lineEdit_4_old_id.setText(item[0]) self.lineEdit_4_old_name.setText(item[1]) self.lineEdit_4_old_sex.setText(item[2]) self.lineEdit_4_old_age.setText(item[3]) self.lineEdit_4_new_id.setText(item[0]) self.lineEdit_4_new_name.setText(item[1]) self.lineEdit_4_new_sex.setText(item[2]) self.lineEdit_4_new_age.setText(item[3])
def __handle_new_connection(self): connection, client_address = self.l_socket.accept() # Request from new client to send his name eNum, eMsg = Protocol.send_all(connection, "ok_name") if eNum: sys.stderr.write(eMsg) self.shut_down_server() ################################################ # Receive new client's name num, msg = Protocol.recv_all(connection) if num == Protocol.NetworkErrorCodes.FAILURE: sys.stderr.write(msg) self.shut_down_server() if num == Protocol.NetworkErrorCodes.DISCONNECTED: sys.stderr.write(msg) self.shut_down_server() self.players_names.append(msg) self.players_sockets.append(connection) self.all_sockets.append(connection) print "New client named '%s' has connected at address %s." % (msg,client_address[0]) if len(self.players_sockets) == 2: # we can start the game self.__set_start_game(0) self.__set_start_game(1)
def multiblock_encryption(c, key_id, versus, data, block_size, working_key_mode, working_key = ''): """ TODO. """ start = False chaining_data = '' result = '' while data != '': if len(data) <= block_size and not start: buff = data data = '' flag = 0x03 start = True else: if len(data) > block_size: buff = data[:block_size] data = data[block_size:] flag = 0x00 # body else: buff = data data = '' flag = 0x02 # end if not start: flag = 0x01 # start start = True Protocol.send_multiblock_encryption(c, key_id, flag, versus, buff, chaining_data, working_key_mode, working_key) ack = Protocol.recv_multiblock_encryption(c, 4) if ack['ack_code'] == 0x00: chaining_data = ack['chaining_data'] result += ack['data'] else: break return ack['ack_code'], result
def btn_4_update(self): # 获取文本框内容 id = self.lineEdit_4_new_id.text() if not id: id = "$" name = self.lineEdit_4_new_name.text() if not name: name = "$" sex = self.lineEdit_4_new_sex.text() if not sex: sex = "$" age = self.lineEdit_4_new_age.text() if not age: age = "$" # 检查数据是否符合规范 if self.check_item([id, name, sex, age, ""]): # 发送更新的条目信息 data = [] item_str = Protocol.item_pack(id, name, sex, age) data.append(item_str) header = Protocol.gen_default_header() smsg = Protocol.msg_pack("UPDATE", header, data) #print(smsg, end="") sock.send(smsg.encode("unicode_escape")) # 接收服务器发回的信息 rmsg = sock.recv(1024).decode("unicode_escape") print(rmsg) rst = Protocol.msg_unpack(rmsg) rhead_line = rst[0] rheader = rst[1] rdata = rst[2] self.lineEdit_4_state.setText(rheader[id]) else: self.lineEdit_4_state.setText("Error")
def start(self, serverSocket, addr): print("Client connected: ", addr) try: while True: dataRec = serverSocket.recv(1024) header, msg = Protocol.decodeMessage(dataRec.decode()) print("Header: ", header) print("Message: ", msg) if (header == Protocol.HEAD_REQUEST): self.sendFileList(serverSocket) break elif (header == Protocol.HEAD_FILE): self.sendFile(serverSocket, self.conf.serverSharePath + "/" + msg) break elif (header == Protocol.HEAD_UPLOAD): self.receiveFile(serverSocket, self.conf.serverDownloadPath + "/" + msg) break else: serverSocket.send( Protocol.prepareMessage(Protocol.HEAD_ERROR, "")) break except Exception as e: print("Error: ", e) print("Client disconnected: ", addr) serverSocket.close()
def getStatus(self, strIDs, timeout): # convert str to list ids = strIDs.split() # peek jobs tmpWrapper = _TimedMethod(self.taskBuffer.peekJobs, timeout) tmpWrapper.run(ids, False, True, True, False) # make response if tmpWrapper.result == Protocol.TimeOutToken: # timeout response = Protocol.Response(Protocol.SC_TimeOut) else: if isinstance(tmpWrapper.result, types.ListType): # succeed response = Protocol.Response(Protocol.SC_Success) # make return retStr = '' attStr = '' for job in tmpWrapper.result: if job == None: retStr += '%s+' % 'notfound' attStr += '0+' else: retStr += '%s+' % job.jobStatus attStr += '%s+' % job.attemptNr response.appendNode('status', retStr[:-1]) response.appendNode('attemptNr', attStr[:-1]) else: # failed response = Protocol.Response(Protocol.SC_Failed) _logger.debug("getStatus : %s ret -> %s" % (strIDs, response.encode())) return response.encode()
def configureEEG(self): if not self.emulate_headset_data: self.serial_device = \ serial_interface.SerialDevice( \ self.log, \ device_address=self.device_address, \ DEBUG=self.DEBUG, \ parent=self) self.serial_device.start() else: self.serial_device = None self.protocol = \ serial_interface.ProtocolHandler( \ self.log, \ self.serial_device, \ device_id=self.device_id, \ device_model=self.device_model, \ DEBUG=self.DEBUG, \ parent=self) self.protocol.start()
def launch(name): # Game game = Game.Game() # Try to connect socket = Network.connect("192.168.0.3", 8080) Protocol.setName(socket, name) # Thread for inputs q = queue.Queue() t = None startThread(t, q) # Main event loop data = bytes() while True: # Send commands try: line = q.get_nowait() interpretCommand(line, socket) except queue.Empty: pass # Get order order = Network.getOrder(socket) try: if order is not None: Protocol.manageOrder(socket, order, game) except Protocol.ByeException: break socket.close()
def join( self, sock ): """Join a room using the given socket""" login = Protocol.getProtocol().getInitJoinPacket( self.nick ) login.send( sock ) time.sleep( 2 ) login = Protocol.getProtocol().getJoinPacket( self.nick, self.roomName ) login.send( sock )
def sketch_loop(): global sketchQueue global sketchRun global proxyCmdBuffer global proxyRxBuffer toSend = [] rxBytes = [] target = 1 temperature = 80 rssi = -60 timestamp = 0 WRITE = 2 SREG_TARGET = 7 SREG_PING = 11 PING = 1 while sketchRun: for target in range(2,6): # set target toSend = Protocol.form_packet(cmd=WRITE, addr=SREG_TARGET, data=target) for b in toSend: proxyCmdBuffer.write(b) #get response rxBytes = [] rxBytes.append(ord(proxyRxBuffer.read())) rxBytes.append(ord(proxyRxBuffer.read())) for i in range(rxBytes[-1]): rxBytes.append(ord(proxyRxBuffer.read())) rxBytes.append(ord(proxyRxBuffer.read())) ############## get data toSend = Protocol.form_packet(cmd=WRITE, addr=SREG_PING, data=PING) for b in toSend: proxyCmdBuffer.write(b) #get response rxBytes = [] rxBytes.append(ord(proxyRxBuffer.read())) rxBytes.append(ord(proxyRxBuffer.read())) for i in range(rxBytes[-1]): rxBytes.append(ord(proxyRxBuffer.read())) rxBytes.append(ord(proxyRxBuffer.read())) rssi = -((rxBytes[3]^0xff)+1) temperature = rxBytes[4] timestamp = time.time() sketchQueue.put({'timestamp':timestamp, 'id':target, 'network':'BP', 'data':{'temp':temperature, 'rssi':rssi} }) time.sleep(0.1)
def test_v1_functionality(self): vehicle_id = 1 lon = 16.1784483 lat = 51.1826638 action_id = 5 data = (vehicle_id, lat, lon, action_id) packet = Protocol.encode(data) assert data == Protocol.decode(packet)
def finish_request(self, request, client_address): data, _ = request ipacket = Protocol.Packet ( data ) if ipacket.opcode == Protocol.Packet.RRQ: if not self.handle_RRQ (ipacket, client_address): Protocol.Send_ERROR (client_address, 2) elif ipacket.opcode == Protocol.Packet.WRQ: self.handle_WRQ (ipacket, client_address) else: self.report_error ( "Message from %s, opcode %s, does not belong to a known session." % (client_address, ipacket.opcode) )
def getKeyPair(self, realDN, publicKeyName, privateKeyName): tmpMsg = "getKeyPair {0}/{1} : ".format(publicKeyName, privateKeyName) if realDN == None: # cannot extract DN tmpMsg += "failed since DN cannot be extracted" _logger.debug(tmpMsg) response = Protocol.Response( Protocol.SC_Perms, 'Cannot extract DN from proxy. not HTTPS?') else: # get compact DN compactDN = self.taskBuffer.cleanUserID(realDN) # check permission self.specialDispatchParams.update() if not 'allowKey' in self.specialDispatchParams: allowKey = [] else: allowKey = self.specialDispatchParams['allowKey'] if not compactDN in allowKey: # permission denied tmpMsg += "failed since '{0}' not in the authorized user list who have 'k' in {1}.USERS.GRIDPREF".format( compactDN, panda_config.schemaMETA) _logger.debug(tmpMsg) response = Protocol.Response(Protocol.SC_Perms, tmpMsg) else: # look for key pair if not 'keyPair' in self.specialDispatchParams: keyPair = {} else: keyPair = self.specialDispatchParams['keyPair'] notFound = False if not publicKeyName in keyPair: # public key is missing notFound = True tmpMsg += "failed for '{2}' since {0} is missing on {1}".format( publicKeyName, socket.getfqdn(), compactDN) elif not privateKeyName in keyPair: # private key is missing notFound = True tmpMsg += "failed for '{2}' since {0} is missing on {1}".format( privateKeyName, socket.getfqdn(), compactDN) if notFound: # private or public key is missing _logger.debug(tmpMsg) response = Protocol.Response(Protocol.SC_MissKey, tmpMsg) else: # key pair is available response = Protocol.Response(Protocol.SC_Success) response.appendNode('publicKey', keyPair[publicKeyName]) response.appendNode('privateKey', keyPair[privateKeyName]) tmpMsg += "sent key-pair to '{0}'".format(compactDN) _logger.debug(tmpMsg) # return return response.encode()
def _dispatch_packet(self, head=Protocol.NET_HEAD(), packet_data=""): header = packet_data url = Protocol.get_url(header) if not url: return params = Protocol.urlparams2dict(url) try: service = url[0:8] if service != "/chelun?": #logger.error("Recv|not chelun service:%s|header:%s",url,header) return query = params["query"] cityid = params["cityid"] if not query: logger.error("Recv|invalid query:%s", url) return citykey = DataSource.get_weather_citykey(cityid) if not citykey: logger.error("Recv|invalid cityid:%s", url) return #logger.debug("Recv|Url:%s",url) task = Protocol.REQUEST_PACKET() task.request_type = head.request_type task.request_key = citykey task.request_tick = Utils.gettickcount() if query in ["weather", "weather2"]: weather_data = KvCache.get_data_from_cache(k=citykey) if not weather_data: logger.debug( "Recv|get_data_from_cache failed;then ask worker;%s", url) MsgPipe.MsgPipe.push(fileno=self.client_socket.fileno(), sessionid=self.client_session_id, msgdata=task) return logger.debug("Recv|get_data_from_cache succ;%s", url) self.send_data_bychunked(weather_data) return elif query == "weather3": task.request_type = "TEST" logger.debug("Recv|Test;%s", url) MsgPipe.MsgPipe.push(fileno=self.client_socket.fileno(), sessionid=self.client_session_id, msgdata=task) return pass except: pass pass
def __init__(self, main_server_address=None, user_data=None): if (main_server_address): self.main_server_address = main_server_address else: self.main_server_address = ('localhost', 56789) self.dtp_server_address = None self.logger = Protocol.Logger() self.parser = Protocol.Parser(module=Protocol) self.user_data = None self.sock = None self.data_sock = None self.book_data = None
def preopt_image(myconnection, head_line, header, data): id = header["Image"] file_name = header["FileName"] file_size = header["FileSize"] path = os.getcwd() + "/" + id + "_" + file_name fp = open(path, "wb") fp.close() sheader = Protocol.gen_default_header() info = "Image_" + id sheader.update({info: "READY", "Path": path}) smsg = Protocol.msg_pack("300", sheader, []) myconnection.send(smsg.encode("unicode_escape")) return path
def basicUnitTest(): client = Protocol.ForgotPasswordClientProtocol() server = Protocol.ForgotPasswordServerProtocol() cTransport, sTransport = MockTransportToProtocol.CreateTransportPair( client, server) server.connection_made(sTransport) client.connection_made(cTransport) # client.send_initial_message() packet1 = Packets.RequestForgotPasswordPacket() packet1.userId = 'ehsia1' packet1Bytes = packet1.__serialize__() sResponse1 = server.data_received(packet1Bytes) assert isinstance(sResponse1, Packets.SecurityQuestionPacket) packet2 = Packets.SecurityQuestionPacket() packet2.securityQuestion = 'What was your hometown?' packet2Bytes = packet2.__serialize__() cResponse1 = client.data_received(packet2Bytes) cResponse1 = PacketType.Deserialize(cResponse1) assert isinstance(cResponse1, Packets.SecurityAnswerPacket) packet3 = Packets.SecurityAnswerPacket() packet3.securityAnswer = 'Windsor, CT' packet3Bytes = packet3.__serialize__() sResponse2 = server.data_received(packet3Bytes) assert isinstance(sResponse2, Packets.ForgotPasswordTokenPacket) packet3.securityAnswer = 'Windsor' packet3Bytes = packet3.__serialize__() sResponse2 = server.data_received(packet3Bytes) assert sResponse2 == "Invalid" packet4 = Packets.ForgotPasswordTokenPacket() packet4.token = 'asdf2313241SqwerXq' packet4Bytes = packet4.__serialize__() cResponse2 = client.data_received(packet4Bytes) cResponse2 = PacketType.Deserialize(cResponse2) assert isinstance(cResponse2, Packets.ResetPasswordInputPacket) packet5 = Packets.ResetPasswordInputPacket() packet5.newPassword = '******' packet5.passwordConfirmation = 'gronkgronkgronk' packet5Bytes = packet5.__serialize__() sResponse3 = server.data_received(packet5Bytes) assert isinstance(sResponse3, Packets.PasswordResetPacket) assert sResponse3.verification == True packet5.newPassword = '******' packet5.passwordConfirmation = 'gronkgronkgronk' packet5Bytes = packet5.__serialize__() sResponse3 = server.data_received(packet5Bytes) assert isinstance(sResponse3, Packets.PasswordResetPacket) assert sResponse3.verification == False print("Protocol completed! All tests passed!")
def ConnectedCallback(_socket): if _socket is not None: self._ConnectingConfirm(socket_id, _socket) confirm_message = Protocol.PackMapCtrlMsg('link_confirm', socket_id) self._SelfSendData(confirm_message) self._Log(logging.DEBUG, 'Sending confirm message to remote, ID: [%d]', socket_id) else: try: refuse_message = Protocol.PackMapCtrlMsg('link_refuse', socket_id) self._SelfSendData(refuse_message) self._DelConnectingInfo(socket_id) self._Log(logging.DEBUG, 'Sending refuse message to remote, ID: [%d]', socket_id) except socket.error: pass
def uploadFile(self, uploadFileName): mySocket = self.connect() request = Protocol.prepareMessage(Protocol.HEAD_UPLOAD, uploadFileName) mySocket.send(request) header, msg = Protocol.decodeMessage(mySocket.recv(1024).decode()) if (header == Protocol.HEAD_READY): f = open(self.conf.clientSharePath + "/" + uploadFileName, 'rb') l = f.read(1024) while (l): mySocket.send(l) l = f.read(1024) else: print("Upload Failed: \nHeader: ", header, " \nMessage: ", msg)
def getDownloadFileList(self): mySocket = self.connect() request = Protocol.prepareMessage(Protocol.HEAD_REQUEST, "") mySocket.send(request) header, msg = Protocol.decodeMessage(mySocket.recv(1024).decode()) mySocket.close() if (header == Protocol.HEAD_REQUEST): files = msg.split(",") self.downloadFileList = [] for f in files: self.downloadFileList.append(f)
def protocolController(): loop = asyncio.get_event_loop() loop.set_debug(enabled=True) client = Protocol.ForgotPasswordClientProtocol() server = Protocol.ForgotPasswordServerProtocol() serv = playground.getConnector().create_playground_server( lambda: server, 8080) s = loop.run_until_complete(serv) print("Echo server running at {}".format(s.sockets[0].gethostname())) cli = playground.getConnector().create_playground_connection( lambda: client, "20174.1.1.1", 8080) transport, protocol = loop.run_until_complete(cli) print("Echo client running with t:{}. p:{}".format(transport, protocol)) loop.run_forever() loop.close()
def returnBook(self): # return book to libaray server # send memo xml file to data server try: sock = socket.create_connection(self.server_address) content = '' logging.debug(self.book_title) with open(here("clientdata/" + self.book_title + ".xml"), "r") as xmlfd: for r in xmlfd: content += r f = sock.makefile("rwb", 0) data = Protocol.ReturnRequest(book_title=self.book_title, memo_content=content, user_id=self.user_data.userId) f.write(data.serialize()) rdata = sock.recv(1024) recv_data = Protocol.ReturnRequest.parse(rdata) logging.debug("return " + bytes.decode(recv_data.memo_content)) os.remove(here("clientdata/" + self.book_title + ".pdf")) self.setParent(None) except IOError as e: logging.debug(e) except Exception as e: logging.debug(e) else: f.close() sock.close() pass
def start(self): logging.info("Starting node {}".format(self.node_id)) child_read_fd, self.write_fd = os.pipe() self.read_fd, child_write_fd = os.pipe() self.pid = os.fork() sys.stderr.flush() sys.stdout.flush() if self.pid != 0: # In the parent process. os.close(child_read_fd) os.close(child_write_fd) self.proto = Protocol.Protocol(self) else: # In the child process. os.dup2(child_read_fd, 0) os.dup2(child_write_fd, 1) os.dup2(child_write_fd, 2) argv = self.node_type.args.split() argv.insert(0, self.node_type.path) env = os.environ env['PROCNET_URI'] = "tcp://localhost:14395" env['PROCNET_AUTH_TOKEN'] = self.token try: os.execvpe(self.node_type.path, argv, env) except FileNotFoundError: os._exit(1)
def send_defend(self, result): msg = 'client:defending:' + result eNum, eMsg = Protocol.send_all(self.socket_to_server, msg) if eNum: sys.stderr.write(eMsg) self.close_client(1)
def run(self): from app import APP APP.Functions.set_process_name ( "0@TFTPD_DATA" ) logger = APP.LoggingClient ( name = "TFTPD%05d" % self.pid ) queue_errors = 0 while 1: try: (client_address, initiating_packet, filename, filesize) = self.rfQueue.get() except: queue_errors += 1 if queue_errors > 2: logger ("Too many errors reading rfqueue") break time.sleep(queue_errors) queue_errors = 0 if client_address is None: break logger ("Sending %s to %s" % (filename, client_address)) try: with open(filename, 'r') as source: try: (bytes, dt, speed) = Protocol.Handle_RRQ (initiating_packet, client_address, source) logger ( "Sent %d bytes to %s at %.1f kB/s" % (bytes, client_address, speed/ 1024) ) except Protocol.TFTPProtocolError as e: logger ( "TFTP Protocol Error: %s" % e ) except: info = sys.exc_info()[:2] logger ( "TFTP error: %s, %s" % (info[0], info[1])) logger ( "EXIT" )
def launch_protocol(self): #self.thread_onoff = False print('nb proie = ', self.nb_prey.get(), 'nb chasseur = ', self.nb_hunter.get()) print('largeur = ', self.width_grid.get(), 'hauteur = ', self.height_grid.get()) print('ratio = ', self.ratio_grid.get()) self.protocols.append( Protocol(nb_hunter=self.nb_hunter.get(), nb_prey=self.nb_prey.get(), ratio=self.ratio_grid.get(), time_limit=self.time_limit.get(), width_grid=self.width_grid.get(), height_grid=self.height_grid.get(), wall=self.wall.get(), id_protocol=self.nb_protocol, experience=self, detection_range_prey=self.detection_range_prey.get(), detection_range_hunter=self.detection_range_hunter.get())) self.nb_protocol += 1 for p in self.protocols: print(p.grid.map) print(p.agents) print("Id ", p.id_protocol, " : ", p.run)
def findServos(self, comm): """Retrieves and processes the list of available (responsive) servos attached to the arm's Arduino controller. Returns a dictionary mapping from servo functions to Servo() objects, or None if no matching servo was found for a particular function""" servos = { 'swing': None, 'actuator': None, 'shoulder': None, 'wrist_x': None, 'wrist_y': None } # Mapping of IDs->functions v1_IDs = { 0 : 'swing', 1 : 'actuator', 2 : 'shoulder' } v2_IDs = { 1 : 'wrist_x', 0 : 'wrist_y' } # Servos retrieved from Arduino found = Protocol.findServos(comm) i = 0 for v1servo in found['v1']: servos[v1_IDs[i]] = v1servo i += 1 j = 0 for v2servo in found['v2']: servos[v2_IDs[j]] = v2servo j += 1 # Return our output servo dictionary return servos
def __init__(self): self.Protocol = Protocol.Protocol() self.FieldManager = FieldManager.FieldManager() self.ConstructManager = ConstructManager.ConstructManager() self.StartNode = StartNode.StartNode("Name", "Protocol Desciption", "Dependent Protocol Name", "Dependency Pattern") self.EndNode = EndNode.EndNode()
def updateEventRanges(self, eventRanges, timeout, acceptJson, version): # peek jobs tmpWrapper = _TimedMethod(self.taskBuffer.updateEventRanges, timeout) tmpWrapper.run(eventRanges, version) # make response if tmpWrapper.result == Protocol.TimeOutToken: # timeout response = Protocol.Response(Protocol.SC_TimeOut) else: # succeed response = Protocol.Response(Protocol.SC_Success) # make return response.appendNode('Returns', tmpWrapper.result[0]) response.appendNode('Command', tmpWrapper.result[1]) _logger.debug("updateEventRanges : ret -> %s" % (response.encode(acceptJson))) return response.encode(acceptJson)
def init_File_server(): host, port = Protocol.get_host(_config['nameserver']) with closing(HTTPConnection(host, port)) as conn: data = 'srv=%s&dirs=%s' % ( _config['srv'], '\n'.join(_config['directories']), ) conn.request('POST', '/', data)
def MAC_verification(connection, KeyId, Versus = None, Data = None, MACData = None): """ Keyboard and Security, MAC verification (0x40, 0x07). :Parameters: -*connection* (PupySPOT): Object managing spot connection. - *KeyId* (integer): Slot ID of Master Key. - *Versus* (Enums.Versus): Operation required. - *Data* (bytes array): Data block on which the operation is performed. - *MACData* (bytes array): MAC data buffer to verify. :Returns: Ack-Code indicating successful of the operation. """ Protocol.send_mac_verification(connection, key_id = KeyId, versus = Versus, data = Data, mac = MACData) ack = Protocol.recv_send_mac_verification(connection, timeout = 120) return ack['ack_code']
def __set_start_game(self, player_num): welcome_msg = "start|turn|" + self.players_names[1] if not player_num else "start|not_turn|" + self.players_names[0] eNum, eMsg = Protocol.send_all(self.players_sockets[player_num], welcome_msg) if eNum: sys.stderr.write(eMsg) self.shut_down_server()
def get_values_matrix(Window, x, y, temp_file, ProtoWindow): """ This program gets 2 positions from a matrix of labels (it is called 2 times each to add one position). Entry: Window(Frame): the protocol window x: the first value to get y(Label variable): the second value to get temp_file(string): the name of the file ProtoWindow(Frame): the protocol frame """ protocole = Prot.ReadProtocolFile(temp_file) pos = protocole.index(['position']) protocole[pos - 1] = protocole[pos - 1] + [x, y] Prot.EcrireProtocoleFichier(protocole, 'temp.txt') if len(protocole[pos - 1]) == 5: Prot.AfficherProtocol(ProtoWindow, protocole) Window.destroy()
def get_tests(config={}): tests = [] import Cipher; tests += Cipher.get_tests(config=config) import Hash; tests += Hash.get_tests(config=config) import Protocol; tests += Protocol.get_tests(config=config) import PublicKey; tests += PublicKey.get_tests(config=config) import Random; tests += Random.get_tests(config=config) import Util; tests += Util.get_tests(config=config) return tests
def data_encryption(connection, KeyId, Versus=None, Data=None, WorkingKey=''): """ Keyboard and Security, Data encryption (0x40, 0x03). :Parameters: -*connection* (PupySPOT): Object managing spot connection. - *KeyId* (integer): Slot ID of Master Key. - *Versus* (Enums.Versus): Operation required. - *Data* (bytes array): Data block on which the operation is performed. - *WorkingKey* (bytes array): Working Key value encrypted with Master Key. :Returns: Ack-Code indicating successful of the operation. """ Protocol.send_data_encryption(connection, keyid = KeyId, versus = Versus, data = Data, mode = 0x00 if WorkingKey == '' else 0x01, working_key = WorkingKey) ack = Protocol.recv_data_encryption(connection, timeout = 120) if ack['ack_code'] != 0x00: ack['Data'] = None return ack['ack_code'], ack['Data']
def doExecute( self, sock, words ): if self.room.getAcl().hasPermission( self.nick, Acl.SHUTDOWN ): number = random.randrange( 0, len(LAST_WORDS) ) self.sendMessage( sock, LAST_WORDS[ number ] ) time.sleep( 2 ) #send the leave message leavePacket = Protocol.getProtocol().getLeavePacket( self.room.getNick() ) leavePacket.send( sock ) self.room.shutdown()
def __handle_standard_input(self): msg = sys.stdin.readline().strip().upper() if msg == 'EXIT': # user wants to quit eNum, eMsg = Protocol.send_all(self.socket_to_server, "PLAYER_QUIT_EXIT") if eNum: print eMsg self.close_client() self.close_client() else: return msg
def send_attack(self, place): """ sends my attack to other (incommiiiiiing!) """ msg = 'client:attacking:' + place eNum, eMsg = Protocol.send_all(self.socket_to_server, msg) if eNum: sys.stderr.write(eMsg) self.close_client(1)
def multiblock_MAC_verification(connection, KeyId, WorkingKeyMode = None, WorkingKey = None, Versus = None, Data = None, IV = None, BlockSize = 16, MACData = None): """ MultiBlock Encryption, MAC verification: Keyboard and Security (0x40,0x16). :Parameters: -*connection* (PupySPOT): Object managing spot connection. - *KeyId* (integer): Slot ID of Master Key. - *WorkingKeyMode* (Enums.WKMode): Working Key format. - *WorkingKey* (bytes array): Working Key value encrypted with Master Key. - *Versus* (Enums.Versus): Operation required. - *Data* (bytes array): Data block on which the operation is performed. - *IV* (bytes array): Initial vector IV. - *BlockSize* (integer): Length of each block. - *MACData* (bytes array): MAC data buffer to verify. :Returns: Ack-Code indicating successful of the operation. """ blkcount = 0 data = Data cblock = IV macData = None # block split while True: block = data[:BlockSize] data = data[BlockSize:] #send if len(block) > 0 and len(data) > 0: flags = Enums.Flags.START_DATA_BLOCK if blkcount == 0 else Enums.Flags.INTERMEDIATE_DATA_BLOCK else: flags = Enums.Flags.FIRSTANDLAST_DATA_BLOCK if blkcount == 0 else Enums.Flags.END_DATA_BLOCK macData = MACData Protocol.send_multiblock_verification(connection, KeyId = KeyId, WorkingKeyMode = Enums.WKMode[WorkingKeyMode], WorkingKey = WorkingKey, Flags = flags, Versus = Enums.Versus[Versus], Data = block, ChainingData = cblock, MACData = macData) #receive ack = Protocol.recv_multiblock_verification(connection, 120) if ack['ACKcode'] == 0x00: cblock = ack['ChainingData'] if flags == Enums.Flags.FIRSTANDLAST_DATA_BLOCK or flags == Enums.Flags.END_DATA_BLOCK: break else: break blkcount += 1 return ack['ACKcode']
def connect_to_server(self): # Create a TCP/IP socket_to_server try: self.socket_to_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as msg: self.socket_to_server = None sys.stderr.write(repr(msg) + '\n') exit(EXIT_ERROR) server_address = (self.server_name, int(self.server_port)) try: self.socket_to_server.connect(server_address) self.all_sockets.append( self.socket_to_server) # this will allow us to use Select System-call except socket.error as msg: self.socket_to_server.close() self.socket_to_server = None sys.stderr.write(repr(msg) + '\n') exit(EXIT_ERROR) # we wait to get ok from server to know we can send our name num, msg = Protocol.recv_all(self.socket_to_server) if num == Protocol.NetworkErrorCodes.FAILURE: sys.stderr.write(msg) self.close_client(1) if num == Protocol.NetworkErrorCodes.DISCONNECTED: self.bye('disconnected') # send our name to server eNum, eMsg = Protocol.send_all(self.socket_to_server, sys.argv[3]) if eNum: sys.stderr.write(eMsg) self.close_client(1) print "*** Connected to server on %s ***" % server_address[0] print print "Waiting for an opponent..." print
def get_platform(connection): """ Gets the platform type. :Parameters: -*connection* (PupySPOT): Object managing spot connection. :Returns: A string containing the platform type. """ Protocol.send_hardware_configuration(connection, [0x01, 0x42]) hw_conf_ack = Protocol.recv_hardware_configuration(connection, 0) connection.platform = None if hw_conf_ack['Entry'][str(int(0x42))].startswith('MCF532x'): connection.platform = 'M3' elif hw_conf_ack['Entry'][str(int(0x42))].startswith('OMAP35xx'): connection.platform = 'NGP' elif hw_conf_ack['Entry'][str(int(0x42))].startswith('UPMxxxxx'): connection.platform = 'VGD' return connection.platform
def send_to_server(self, msg): err_num, err_msg = Protocol.send_all(self.socket_to_server, msg) if err_num == Protocol.NetworkErrorCodes.FAILURE: print err_msg self.close_client(EXIT_ERROR) if err_num == Protocol.NetworkErrorCodes.DISCONNECTED: print "Server has closed connection." self.close_client(EXIT_OK)
def callback(self,data): self.logger.info('recv from server : %s' % binascii.b2a_hex(data)) pro = Protocol.decode(data) if (pro.head != 0xEC or pro.tail != 0xEA): return # 服务器认证 if (pro.cmd == MASTER_AUTHOR): ip = "%d.%d.%d.%d" % (pro.state, pro.R, pro.G, pro.B) port = pro.deviceID self.client = RBClient(ip, port) protocol = Protocol(SUB_AUTHOR, pro.masterID) self.client.sendData(protocol.command()) self.client.recvData(self.callback) # 控制设备 if (pro.cmd == 0x03): light = C4Light() if pro.state: light.powerOn(pro.deviceID) else: light.powerOff(pro.deviceID)
def __handle_server_request(self): """ handles all massages got from server """ num, msg = Protocol.recv_all(self.socket_to_server) if num == Protocol.NetworkErrorCodes.FAILURE: sys.stderr.write(msg) self.close_client(1) # the connection disconnected if num == Protocol.NetworkErrorCodes.DISCONNECTED: self.bye('disconnected') if "start" in msg: self.__start_game(msg) elif msg: (who, what, data) = msg.split(':') # the othe side left if data == 'EXIT' : self.bye('other '+ data) # a respond to my former attack or attacking me. if who == 'client': result = {'attacking': self.defend, 'defending': self.update_result, }.get(what)(data.upper()) # result is the outcome from the other's attack. #(if he didnt attacked in this message will be none) if result: self.send_defend(result) self.my_turn = True print self.opponent_name + ' plays: ' + data self.print_board() # iv'e lost ): if result == 'LOST': self.bye(result) else: print "It's your turn..." else: self.print_board() # the other tells us he lost the game... I guess we won. if data == 'LOST': self.bye('other '+ data) self.print_board()
def get_bundle_version(connection, platform, login_answer): """ Gets the bundle version. :Parameters: -*connection* (PupySPOT): Object managing spot connection. -*platform* (string): Platform type. -*login_answer* (string): TODO. :Returns: A string containing the bundle version. """ version = None if platform == 'M3': Protocol.send_software_configuration(connection, []) ack = Protocol.recv_software_configuration(connection, 0) version = ack['Entry']['15'].split('\n')[0].split(' ')[1] elif platform == 'NGP': version = '|'.join([str(e['app_id']) + '=' + e['app_ascii'].strip('\x00') for e in login_answer['entries']]) elif platform == 'VGD': version = '|'.join([str(e['app_id']) + '=' + e['app_ascii'].strip('\x00') for e in login_answer['entries']]) return version
def __handle_server_request(self): num, msg = Protocol.recv_all(self.socket_to_server) if num == Protocol.NetworkErrorCodes.FAILURE: sys.stderr.write(msg) self.close_client() if num == Protocol.NetworkErrorCodes.DISCONNECTED: print "Server has closed connection." self.close_client() if "EXIT" in msg: print "Your opponent has disconnected. You win!" self.close_client() if "start" in msg: self.__start_game(msg) else: msg_type = Client.server_msg_type(msg) # Analyzing massage type #print "msg = " + msg # ----------blllaaaaaaaaaaaaaaaaaaaaaa - ERASE if msg_type == OPPONENT_ANSWER: win = self.player.update_opponent_board(msg, self.latest_move[0], self.latest_move[1]) self.print_board() if win: #game ended - send massage print "You won!" self.close_client() else: # A move was sent from the other client result = self.player.check_move(msg) Protocol.send_all(self.socket_to_server, result) # Sends the response to the server print self.opponent_name + " plays: " + msg self.print_board() if "ALL" in result: print "You lost :(" self.close_client() else: print "It's your turn..."
def sendMessage( self, sock, msg ): #break up msg in appropriate chunks idxStart = 0 idxEnd = MAX_PACKET_SIZE msgList = [] while idxEnd < len( msg ): #make sure we break on a space while not msg[ idxEnd - 1 ] == " " and idxEnd > ( idxStart + MAX_PACKET_SIZE - 40 ): idxEnd = idxEnd - 1 msgList.append( msg[ idxStart : idxEnd ] ) idxStart = idxEnd idxEnd = idxStart + MAX_PACKET_SIZE msgList.append( msg[ idxStart : idxEnd ] ) for message in msgList: if self.isPm: packet = Protocol.getProtocol().getPmPacket( self.room.getNick(), self.nick, message ) else: packet = Protocol.getProtocol().getSpeechPacket( self.room.getNick() \ ,self.room.getRoomName(), message ) packet.send( sock ) time.sleep( 3 )
def run_client(self): while True: r_sockets = select.select(self.all_sockets, [], [])[0] # We won't use writable and exceptional sockets if sys.stdin in r_sockets: move = self.__handle_standard_input() eNum, eMsg = Protocol.send_all(self.socket_to_server, move) if eNum: print eMsg self.close_client() self.latest_move = Client.parse_msg(move) elif self.socket_to_server in r_sockets: self.__handle_server_request()
def run( self ): sleepMax = Config.getConfig().getInt( "quotes", "sleep_max" ) sleepMin = Config.getConfig().getInt( "quotes", "sleep_min" ) quoteDb = Config.getConfig().getString( "quotes", "quotefile" ) store = SqliteQuoteStore.SqliteQuoteStore( quoteDb ) while not self.finished: interval = random.randrange( sleepMin, sleepMax ) time.sleep( interval * 60 ) msg = QuoteCommand.formatQuote( store.getRandomQuote() ) packet = Protocol.getProtocol().getSpeechPacket( self.room.getNick(), self.room.getRoomName(), msg.strip() ) packet.send( self.sock )
def get_card_reader_type(connection): """ Gets the card reader type. :Parameters: -*connection* (PupySPOT): Object managing spot connection. :Returns: A string containing the card reader type. """ Protocol.send_hardware_configuration(connection, [0x34]) hw_conf_ack = Protocol.recv_hardware_configuration(connection, 0) connection.cr_type = None if hw_conf_ack['Entry']['52'].startswith('ZU-'): connection.cr_type = 'PANASONIC' elif hw_conf_ack['Entry']['52'].startswith('MAGTEK-HCR'): connection.cr_type = 'HCR2' elif hw_conf_ack['Entry']['52'].startswith('Sankyo'): connection.cr_type = 'SANKYO' elif hw_conf_ack['Entry']['52'].startswith('SANKYO-HCR2'): connection.cr_type = 'SANKYO-HCR2' elif hw_conf_ack['Entry']['52'].startswith('Omron'): connection.cr_type = 'OMRON' return connection.cr_type
def rcv_from_server(self): err_num, msg = Protocol.recv_all(self.socket_to_server) if err_num == Protocol.NetworkErrorCodes.FAILURE: sys.stderr.write(msg) self.close_client(EXIT_ERROR) elif err_num == Protocol.NetworkErrorCodes.DISCONNECTED: print "Server has closed connection." self.close_client(EXIT_OK) else: return msg