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)
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
def server(address): proto = Protocol() sock = proto.create_socket() sock.bind(address) file_requested, add = proto.listen(sock) # info = "Enjoyed minutes related as at on on. Is fanny dried as often me. Goodness as reserved raptures to mistaken steepest oh screened he. Gravity he mr sixteen esteems. Mile home its new way with high told said." proto.sendFile(sock, add, file_requested) return
def client(address): proto = Protocol() sock = proto.create_socket() sock.bind(('localhost', 5000)) recv = False while not recv: proto.connect(sock, address, 5, "trial2.txt") recv = proto.recvDataPackets(address, sock) return
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'
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)
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'
def client_send(client): protocol = Protocol() # TODO: Setters protocol.set_ip("") protocol.set_color("") protocol.set_state("") protocol.set_message("") protocol.set_pos_x(float()) protocol.set_pos_y(float()) # Send protocol to robot (host, port) client.send(protocol.build_data())
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 __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
def create_trainings_data(): count = 0 player1 = 0 player2 = 0 directory = "../protocol/gamefiles/splitted/" for filename in tqdm(os.listdir(directory)): if filename.endswith(".mat") or filename.endswith(".txt"): # print(os.path.join(directory, filename)) path = os.path.join("gamefiles/splitted/", filename) # prot = Protocol(HumanPlayer(Checker.WHITE), HumanPlayer(Checker.BLACK), path, 'r') prot = Protocol(path, 'r') # print(filename + " -> " + prot.whowon()) sim = Simulation() mapper = NNMapper() status = [] try: status = sim.runSimulation(prot, False) trainingsdata = [] for (t_board, t_next_play, t_winner) in status: trainingsdata.append( mapper.to_trainings_data(t_board, t_next_play, t_winner)) dump_trainingsdata(trainingsdata, count) count += 1 except: os.rename(os.path.join(directory, filename), os.path.join(directory + "broken/", filename)) if prot.whowonNumber() == 1: player1 += 1 else: player2 += 1 prot = None else: continue print("Player1: " + str(player1) + "Player2: " + str(player2)) print("Player1 won " + str((player1 / (player1 + player2)) * 100) + "%!")
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.')
from Protocol import Protocol import random from threading import Thread from time import sleep protocol = Protocol(4) def create_cmd(cmd): protocol.add_command([cmd]) def run(): protocol.run() run_thread = Thread(target=run, args=()) run_thread.start() for i in range(0, 400): cmd_thread = Thread(target=create_cmd, args=(random.randint(0, 1), )) cmd_thread.start() sleep(random.random())
bench(proxy.get_server_version) bench(proxy.status_server) bench(proxy.status_downloads) #bench(proxy.get_queue) #bench(proxy.get_collector) print try: # Make socket transport = Socket('localhost', 7228, False) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = Protocol(transport) # Create a client to use the protocol encoder client = Pyload.Client(protocol) # Connect! transport.open() print "Login", client.login(user, passwd) bench(client.getServerVersion) bench(client.statusServer) bench(client.statusDownloads) #bench(client.getQueue) #bench(client.getCollector)
from socket import * import socket import threading import logging import time import sys from Protocol import Protocol pm = Protocol() class ProcessTheClient(threading.Thread): def __init__(self, connection, address): self.connection = connection self.address = address threading.Thread.__init__(self) def run(self): buffer_arr = [] while True: data = self.connection.recv(1024) content = data.decode() buffer_arr.append(content) if len(content) < 1024: break hasil = pm.proses(buffer_arr) print(hasil) self.connection.sendall(hasil.encode()) self.connection.close()
from Protocol import Protocol from Message import CreateMsgType _idcount = 0 def GenID(): global _idcount rval = _idcount _idcount += 1 return rval GameProtocol = Protocol( ('Version', GenID(), ('version', 'B')), ('AcceptConnect', GenID()), ('ConnectionDeclined', GenID(), ('reason', '255s')), ('ChatMessage', GenID(), ('message', '255s')), ('SpawnEnt', GenID(), ('typename', '32s'), ('x', 'f'), ('y', 'f'), ('z', 'f')), ('SetName', GenID(), ('username', '32s'))) def test(): bytestr = GameProtocol.ChatMessage("hay guys") print "Chat Message:" print GameProtocol.ChatMessage.unpack(bytestr) bytestr = GameProtocol.SpawnEnt("RobotJesus", 10, -15, 20) print "Spawn Message" print GameProtocol.read(bytestr) if __name__ == '__main__': test()
def sendData(coflow_data, sleep_time, packets_size_list): print "coflow ", coflow_data["Coflow ID"], " start" this_thread = threading.currentThread() now_packet_count = [0] * len( coflow_data["Mapper ID"] ) # record the number of packet which sended by this mapper min_packet_num = [min(coflow_data["Dst data"])] * len( coflow_data["Mapper ID"] ) # record the min number of packet in this mapper send list all_flow_time = [] # record flow start and end time time_count_ = 0 # time count for waking up flow flow_index = 0 # index of flow which added into start_mapper list start_mapper = [] timeout = True start_time = time.time() while getattr(this_thread, "do_run", True): while flow_index < len(coflow_data["Mapper ID"]): if time_count_ >= sleep_time[flow_index]: # this flow starts this_mapper = {} this_mapper["Mapper ID"] = coflow_data["Mapper ID"][flow_index] this_mapper["Dst data"] = list(coflow_data["Dst data"]) this_mapper["Reducer ID"] = list(coflow_data["Reducer ID"]) this_mapper["Dst list"] = list(coflow_data["Dst list"]) start_mapper.append(this_mapper) all_flow_time.append(time.time()) flow_index += 1 else: break all_skip = True # check if all flow skip, time count+1 for i in range(len(start_mapper)): # send a packet to all reducer if len(start_mapper[i] ["Dst list"]) == 0: # skip if this flow completed continue else: all_skip = False for j in range(len(start_mapper[i]["Dst list"])): # send packet ip = IP(src=host_ip, dst=start_mapper[i]["Dst list"][j]) this_packet_size = int( random.choice(packets_size_list)) + 28 # + header coflow = Protocol( CoflowId=coflow_data["Coflow ID"], ArrivalTime=coflow_data["Arrival time"], FlowNum=coflow_data["Flow Number"], MapperId=start_mapper[i]["Mapper ID"], ReducerId=start_mapper[i]["Reducer ID"][j], PacketArrival=int(time.time()), PacketSize=this_packet_size) tcp = TCP() packet = ip / tcp / coflow / Raw( RandString(size=this_packet_size)) send(packet) time_count_ += 1 now_packet_count[i] += 1 # delete the complete flow dst while now_packet_count[i] >= min_packet_num[ i] and min_packet_num[i] != -1: tmp_index = start_mapper[i]["Dst data"].index( min_packet_num[i]) now_time = time.time() # record = "COFLOWID" + str(coflow_data["Coflow ID"]) + "\t" + str(start_mapper[i]["Mapper ID"]) + "\t" + str(start_mapper[i]["Reducer ID"][tmp_index]) + "\t" + str(start_mapper[i]["Dst data"][tmp_index]*1024/1024) + "\t" + str(all_flow_time[i]) + "\t" + str(now_time) + "\t" + str(now_time-all_flow_time[i]) + "\n" # ff.write(record) del start_mapper[i]["Dst data"][tmp_index] del start_mapper[i]["Dst list"][tmp_index] del start_mapper[i]["Reducer ID"][tmp_index] if start_mapper[i]["Dst data"] != []: min_packet_num[i] = min(start_mapper[i]["Dst data"]) else: min_packet_num[i] = -1 # complete break if all_skip: time_count_ += 1 # terminate while loop complete = True for m in min_packet_num: if m != -1: complete = False break if complete: timeout = False print str(coflow_data["Coflow ID"]), " complete!" end_time = time.time() record = "COFLOWID" + str(coflow_data["Coflow ID"]) + "\t" + str( coflow_data["Flow Number"]) + "\t" + str( start_time) + "\t" + str(end_time) + "\t" + str( end_time - start_time) + "\n" fw.write(record) break if timeout: # end by main process print str(coflow_data["Coflow ID"]), " complete! (timeout)" end_time = time.time() record = "COFLOWID" + str(coflow_data["Coflow ID"]) + "\t" + str( coflow_data["Flow Number"]) + "\t" + str(start_time) + "\t" + str( end_time) + "\t" + str(end_time - start_time) + "\n" fw.write(record)
def client_recieve(client): protocol = Protocol() protocol.save_data(client.receive()) print(protocol)
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_size=self.max_threads * 2, 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()) }) 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)