def cycle_identity(): socket = make_socket("localhost", "9050") socket.write("AUTHENTICATE \"\"\n") while True: socket.write("signal NEWNYM\n\x00") print "[" + str(socket) + ": cycle_identity -> signal NEWNYM\n" time.sleep(300000/1000000.0)
def put_client_media_files(self, reupload_all=False): self.ui.status_bar_message("Sending media files to server...") # Size of tar archive. if reupload_all: filenames = self.database.all_media_filenames() else: filenames = self.database.media_filenames_to_sync_for(\ self.server_info["machine_id"]) size = tar_file_size(self.database.mediadir(), filenames) if size == 0: return self.con.putrequest("PUT", "/client_media_files?session_token=%s" \ % (self.server_info["session_token"], )) self.con.endheaders() socket = self.con.sock.makefile("wb", bufsize=BUFFER_SIZE) socket.write(str(size) + "\n") # Bundle the media files in a single tar stream, and send it over a # buffered socket in order to save memory. Note that this is a short # cut for efficiency reasons and bypasses the routines in Partner, and # in fact even httplib.HTTPConnection.send. saved_path = os.getcwdu() os.chdir(self.database.mediadir()) tar_pipe = tarfile.open(mode="w|", # Open in streaming mode. format=tarfile.PAX_FORMAT, fileobj=socket) for filename in filenames: tar_pipe.add(filename) tar_pipe.close() os.chdir(saved_path) if self.con.getresponse().read() != "OK": raise Exception("Error sending media files to server.")
def _apns_send( token, alert, badge=None, sound=None, category=None, content_available=False, action_loc_key=None, loc_key=None, loc_args=[], extra={}, identifier=0, expiration=None, priority=10, socket=None, certfile=None, mutable_content=False ): data = {} aps_data = {} if action_loc_key or loc_key or loc_args: alert = {"body": alert} if alert else {} if action_loc_key: alert["action-loc-key"] = action_loc_key if loc_key: alert["loc-key"] = loc_key if loc_args: alert["loc-args"] = loc_args if alert is not None: aps_data["alert"] = alert if badge is not None: if callable(badge): badge = badge(token) aps_data["badge"] = badge if sound is not None: aps_data["sound"] = sound if category is not None: aps_data["category"] = category if content_available: aps_data["content-available"] = 1 if mutable_content: aps_data["mutable-content"] = 1 data["aps"] = aps_data data.update(extra) # convert to json, avoiding unnecessary whitespace with separators (keys sorted for tests) json_data = json.dumps(data, separators=(",", ":"), sort_keys=True).encode("utf-8") max_size = SETTINGS["APNS_MAX_NOTIFICATION_SIZE"] if len(json_data) > max_size: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (max_size)) # if expiration isn't specified use 1 month from now expiration_time = expiration if expiration is not None else int(time.time()) + 2592000 frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority) if socket: socket.write(frame) else: with closing(_apns_create_socket_to_push(certfile)) as socket: socket.write(frame) _apns_check_errors(socket) return token
def broadcast_data (sock,message): for socket in conn_list: if socket != server_socket and socket != sock : try : socket.write(message) except : socket.close() conn_list.remove(socket)
def main(): socket = tcp_connect('testdrs.my-domain-registry.nl') socket.write("""<?xml version="1.0" encoding="UTF-8" standalone="no"?><epp xmlns="urn:ietf:params:xml:ns:epp-1.0"><hello/></epp>""") data = socket.read() print data data = socket.read() socket.close() print data
def _apns_send(token, alert, badge=None, sound="default", category=None, content_available=True, action_loc_key=None, loc_key=None, loc_args=[], extra={}, identifier=0, expiration=None, priority=10, socket=None, **kwargs): data = {} aps_data = {} custom_params = alert alert = custom_params.pop('message') if action_loc_key or loc_key or loc_args: alert = {"body": alert} if alert else {} if action_loc_key: alert["action-loc-key"] = action_loc_key if loc_key: alert["loc-key"] = loc_key if loc_args: alert["loc-args"] = loc_args if alert is not None: aps_data["alert"] = alert if badge is not None: aps_data["badge"] = badge if sound is not None: aps_data["sound"] = sound if category is not None: aps_data["category"] = category if content_available: aps_data["content-available"] = 1 if custom_params.keys(): aps_data['custom_params'] = {'data': custom_params} data["aps"] = aps_data data.update(extra) # convert to json, avoiding unnecessary whitespace with separators (keys sorted for tests) json_data = json.dumps(data, separators=(",", ":"), sort_keys=True).encode("utf-8") max_size = SETTINGS["MAX_SIZE"] if len(json_data) > max_size: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (max_size)) # if expiration isn't specified use 1 month from now expiration_time = expiration if expiration is not None else int(time.time()) + 2592000 frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority) if socket: socket.write(frame) else: with closing(_apns_create_socket_to_push(**kwargs)) as socket: socket.write(frame) _apns_check_errors(socket)
def send(self, id, str): socket = self.client_table[id] socket.write("start") totalsent = 0 while totalsent < str.__len__(): sent = socket.write(str[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent socket.write("end")
def testWriteTimeout(self): starttime = time.time() try: socket = TSocket.TSocket('localhost', self.port) socket.setTimeout(10) socket.open() lsock = self.listen_sock.accept() while True: socket.write("hi" * 100) except: assert time.time() - starttime < 5.0
def _apns_send(token, alert, badge=0, sound=None, content_available=False, action_loc_key=None, loc_key=None, loc_args=[], extra={}, identifier=0, expiration=None, priority=10, socket=None, logger=None): data = {} aps_data = {} if action_loc_key or loc_key or loc_args: alert = {"body": alert} if alert else {} if action_loc_key: alert["action-loc-key"] = action_loc_key if loc_key: alert["loc-key"] = loc_key if loc_args: alert["loc-args"] = loc_args if alert is not None: aps_data["alert"] = alert if badge: aps_data["badge"] = badge if sound is not None: aps_data["sound"] = sound if content_available: aps_data["content-available"] = 1 data["aps"] = aps_data data.update(extra) # convert to json, avoiding unnecessary whitespace with separators json_data = json.dumps(data, separators=(",", ":")) if(logger is not None): logger.debug(json_data) if len(json_data) > APNS_MAX_NOTIFICATION_SIZE: raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (APNS_MAX_NOTIFICATION_SIZE)) # if expiration isn't specified use 1 month from now expiration_time = expiration if expiration is not None else int(time.time()) + 2592000 frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority) if socket: socket.write(frame) else: with closing(_apns_create_socket()) as socket: socket.write(frame) _apns_check_errors(socket)
def create_room(self, socket, room): socket.write({ "action": "create_room", "user": self.username, "room": room })
None RETURNS: @message -- The message received from the currently connected socket. ''' # Read from the connected socket until the packet length is reached or # the maximum size is reached. When the entire message is recovered # string it together and return it. If at any point nothing is received # it is assumed that the connection was broken or the transmission # finished and what is in the buffer will be returned. chunks = [] total_recieved = 0 while total_recieved < 2048: chunk = self.sock.recv(min(2048 - total_recieved, 2048)) if chunk == '': break raise RuntimeError('Connection Broken') chunks.append(chunk) total_recieved = total_recieved + len(chunk) return ''.join(chunks) if __name__ == '__main__': socket = TCPSocket('hello') socket.connect('104.131.44.2', 3000) socket.write('GET / HTTP/1.1\rHost: www.batphone.co\r\n\r\n') sleep(2) response = socket.read() print response
def on_data(self, socket, data): pos = data.find('\n') if pos < 0: # need to wait for new line return 0 elif pos == 0: return 1 # just a keep-alive args = data[0:pos].split(' ') if self.DEBUG: print 'inT:', ' '.join(args) # client->server commands: # CGET hash -- get value with specified hash # CPUT data -- put data into hash table (base64-encoded) # CSHOW -- request a listing of all nodes # server->client commands: # CERROR msg -- there was some kind of error # CDATA data -- data that was stored (base64-encoded) # C*K hash -- insert succeeded # CPEER hash ip:port -- peer in system if args[0] == 'CGET': hash = args[1] t = Trans(Trans.GET, self, socket) t.add() self.find(hash, t.id) elif args[0] == 'CPUT': to_add = base64.b64decode(args[1]) hash = make_file_id(to_add) t = Trans(Trans.PUT, self, socket, to_add) t.add() self.find(hash, t.id) elif args[0] == 'CSHOW': t = Trans(Trans.SHOW, self, socket) t.add() if self.finger[0] != self.myname: # we can have trouble here if a node just joined and our successor # has not been updated to reflect that self.dgram_socket.send(self.finger[0], ['SHOW', self.myname, t.id]) socket.write(['CPEER', make_id(self.myname), self.myname]) # get/put operations done over TCP because data could be larger than 1 packet # GET hash transid -- request for data # DATA data transid -- hash and its data (sent in response to GET) # ERROR msg transid -- there was an error # PUT data transid -- data to insert (hash calculated at inserting node) # OK hash transid -- insert succeeded elif args[0] == 'GET': (hash, transid) = args[1:] if hash in self.items: socket.write(['DATA', base64.b64encode(self.items[hash]), transid]) else: socket.write(['ERROR', 'data.not.found', transid]) socket.close_when_done() elif args[0] == 'DATA': (data, transid) = args[1:] t = self.trans[transid] t.client.write(['CDATA', data]) t.client.close_when_done() t.remove() elif args[0] == 'ERROR': (msg, transid) = args[1:] t = self.trans[transid] t.client.write(['CERROR', msg]) t.client.close_when_done() t.remove() elif args[0] == 'PUT': (data, transid) = args[1:] data = base64.b64decode(data) hash = make_file_id(data) print 'adding %s' % hash self.items[hash] = data socket.write(['OK', hash, transid]) socket.close_when_done() elif args[0] == 'OK': (hash, transid) = args[1:] t = self.trans[transid] t.client.write(['C*K', hash]) t.client.close_when_done() t.remove() # value transfers are done over TCP as well # RETR low high -- ask for data in range (low, high] # XFER hash data -- response to RETR (transferring data to new node) elif args[0] == 'RETR': (low, high) = args[1:] for i in self.items.iterkeys(): if id_distance(low, i) < id_distance(low, high): print 'transferring %s to peer' % i socket.write(['XFER', i, base64.b64encode(self.items[i])]) socket.close_when_done() elif args[0] == 'XFER': (hash, data) = args[1:] # add to database self.items[hash] = base64.b64decode(data) else: print 'unknown message:', ' '.join(args) return pos + 1
def send_get(self, socket, data): socket.write("GET /%s HTTP/1.0" % (self.path) ) socket.write("\n\n")
def get_rooms(self, socket): socket.write({"action": "get_rooms", "user": self.username})
def test_preexisting_token(self): token = self.context.token opts = self.opts.kwargs.copy() opts["token"] = token opts["username"] = "******" opts["password"] = "******" newContext = binding.Context(**opts) response = newContext.get("/services") self.assertEqual(response.status, 200) socket = newContext.connect() socket.write("POST %s HTTP/1.1\r\n" % self.context._abspath("some/path/to/post/to")) socket.write("Host: %s:%s\r\n" % (self.context.host, self.context.port)) socket.write("Accept-Encoding: identity\r\n") socket.write("Authorization: %s\r\n" % self.context.token) socket.write("X-Splunk-Input-Mode: Streaming\r\n") socket.write("\r\n") socket.close()
def err(socket, code, message): socket.write("HTTP/1.1 " + code + " " + message + "\r\n\r\n") socket.write("<h1>" + message + "</h1>")
def ok(socket, code, msg): socket.write("HTTP/1.1 " + code + " OK\r\n\r\n") socket.write(msg)
def write_to_socket(socket, namespace, data): lnData = getLenOf(data) msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len("sender-0"),len("receiver-0"),len(namespace),len(lnData),len(data)),getType(1,TYPE_ENUM),0,getType(2,TYPE_STRING),len("sender-0"),"sender-0",getType(3,TYPE_STRING),len("receiver-0"),"receiver-0",getType(4,TYPE_STRING),len(namespace),namespace,getType(5,TYPE_ENUM),0,getType(6,TYPE_BYTES),lnData,data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) socket.write(msg)
def test_preexisting_token_sans_splunk(self): token = self.context.token if token.startswith('Splunk '): token = token.split(' ', 1)[1] self.assertFalse(token.startswith('Splunk ')) else: self.fail('Token did not start with "Splunk ".') opts = self.opts.kwargs.copy() opts["token"] = token opts["username"] = "******" opts["password"] = "******" newContext = binding.Context(**opts) response = newContext.get("/services") self.assertEqual(response.status, 200) socket = newContext.connect() socket.write("POST %s HTTP/1.1\r\n" %\ self.context._abspath("some/path/to/post/to")) socket.write("Host: %s:%s\r\n" %\ (self.context.host, self.context.port)) socket.write("Accept-Encoding: identity\r\n") socket.write("Authorization: %s\r\n" %\ self.context.token) socket.write("X-Splunk-Input-Mode: Streaming\r\n") socket.write("\r\n") socket.close()
def err(socket, code, msg): socket.write("HTTP/1.1 "+code+" "+msg+"\r\n\r\n") socket.write("<h1>"+msg+"</h1>")
# if expiration isn't specified use 1 month from now expiration_time = expiration if expiration is not None else int(time.time()) + 2592000 frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority) if socket: try: socket.write(frame) except Socket.error, e: if e[0] == errno.EPIPE: raise APNSServerError(20, identifier) raise APNSServerError(255, identifier) else: with closing(_apns_create_socket_to_push()) as socket: socket.write(frame) _apns_check_errors(socket) def _apns_read_and_unpack(socket, data_format): length = struct.calcsize(data_format) data = socket.recv(length) if data: return struct.unpack_from(data_format, data, 0) else: return None def _apns_receive_feedback(socket): expired_token_list = []
def test_preexisting_token_sans_splunk(self): token = self.context.token if token.startswith('Splunk '): token = token.split(' ', 1)[1] self.assertFalse(token.startswith('Splunk ')) else: self.fail('Token did not start with "Splunk ".') opts = self.opts.kwargs.copy() opts["token"] = token opts["username"] = "******" opts["password"] = "******" newContext = binding.Context(**opts) response = newContext.get("/services") self.assertEqual(response.status, 200) socket = newContext.connect() socket.write(("POST %s HTTP/1.1\r\n" %\ self.context._abspath("some/path/to/post/to")).encode('utf-8')) socket.write(("Host: %s:%s\r\n" %\ (self.context.host, self.context.port)).encode('utf-8')) socket.write("Accept-Encoding: identity\r\n".encode('utf-8')) socket.write(("Authorization: %s\r\n" %\ self.context.token).encode('utf-8')) socket.write(("X-Splunk-Input-Mode: Streaming\r\n").encode('utf-8')) socket.write(("\r\n").encode('utf-8')) socket.close()
def login(self, socket): socket.write({"action": "login", "user": self.username})
def test_preexisting_token(self): token = self.context.token opts = self.opts.kwargs.copy() opts["token"] = token opts["username"] = "******" opts["password"] = "******" newContext = binding.Context(**opts) response = newContext.get("/services") self.assertEqual(response.status, 200) socket = newContext.connect() socket.write("POST %s HTTP/1.1\r\n" % \ self.context._abspath("some/path/to/post/to")) socket.write("Host: %s:%s\r\n" % \ (self.context.host, self.context.port)) socket.write("Accept-Encoding: identity\r\n") socket.write("Authorization: %s\r\n" % \ self.context.token) socket.write("X-Splunk-Input-Mode: Streaming\r\n") socket.write("\r\n") socket.close()
def disconnect(self, socket): socket.write({"action": "disconnect", "user": self.username})
def join_room(self, socket, room): socket.write({ "action": "join_room", "user": self.username, "room": room })
def test_connect_with_preexisting_token_sans_user_and_pass(self): token = self.context.token opts = self.opts.kwargs.copy() del opts['username'] del opts['password'] opts["token"] = token newContext = binding.connect(**opts) response = newContext.get('/services') self.assertEqual(response.status, 200) socket = newContext.connect() socket.write("POST %s HTTP/1.1\r\n" % \ self.context._abspath("some/path/to/post/to")) socket.write("Host: %s:%s\r\n" % \ (self.context.host, self.context.port)) socket.write("Accept-Encoding: identity\r\n") socket.write("Authorization: %s\r\n" % \ self.context.token) socket.write("X-Splunk-Input-Mode: Streaming\r\n") socket.write("\r\n") socket.close()
def get_players(self, socket): socket.write({"action": "get_players", "user": self.username})
def test_unicode_socket(self): socket = self.context.connect() socket.write(u"POST %s HTTP/1.1\r\n" %\ self.context._abspath("some/path/to/post/to")) socket.write(u"Host: %s:%s\r\n" %\ (self.context.host, self.context.port)) socket.write(u"Accept-Encoding: identity\r\n") socket.write(u"Authorization: %s\r\n" %\ self.context.token) socket.write(u"X-Splunk-Input-Mode: Streaming\r\n") socket.write("\r\n") socket.close()
def evaluate_request(self, socket): request = socket.request print(socket.addr, request) close = False write = True action = request['action'] user = request['user'] if action == 'login': print("agregar usuario") player = Player(socket, user) if user not in self.players.keys(): self.players[user] = player print("usuario agregado") content = { "status": "login", "rooms": self.get_rooms(), "players": self.get_players() } else: print("usuario ya existe") content = { "status": "error", "message": f'User "{user}" exists' } close = True elif user in self.players.keys(): if action == 'get_rooms': print("mostrar rooms") content = {"status": "get_rooms", "rooms": self.get_rooms()} elif action == 'create_room': print("agregar room") room_name = request['room'] room = Room(room_name) if room_name not in self.rooms.keys(): self.rooms[room_name] = room print("room agregado") content = { "status": "room_created", "rooms": self.get_rooms() } else: print("room ya existe") content = { "status": "error", "message": f'Room "{room_name}" exists' } elif action == 'join_room': print("usuario unido a room") room_name = request['room'] if room_name in self.rooms.keys(): connected = self.rooms[room_name].connect_player( self.players[user]) if connected: self.players[user].change_state('inroom') content = { "status": "join_room", "room": room_name, "players_in_room": self.rooms[room_name].get_players_in_room() } socket.write(content) write = False self.rooms[room_name].try_start() else: content = { "status": "error", "message": f'Room "{room_name}"is full' } else: content = { "status": "error", "message": f'Room "{room_name}"doesnt exists' } elif action == 'get_players': print("mostrar jugadores") content = { "status": "get_players", "players": self.get_players() } elif action == 'message_to_room': print("enviar mensaje a room") room = request['room'] message = request['message'] content = { "status": "message_to_room", "from": user, "room": room, "message": message } if (self.message_to_room(content, room)): content = { "status": "message_to_room_sent", "from": user, "room": room, "message": message } else: content = { "status": "error", "message": 'couldnt send message to room' } elif action == 'message_to_player': print("enviar mensaje a jugador") to = request['to'] message = request['message'] content = { "status": "message_to_player", "from": user, "to": to, "message": message } if (self.message_to_player(content, to)): content = { "status": "message_to_player_sent", "from": user, "to": to, "message": message } else: content = { "status": "error", "message": 'couldnt send message to player' } elif action == 'card_pick': print('seleccion del jugador') room = request['room'] pick = request['card'] player_name = user if room in self.rooms.keys(): self.rooms[room].card_pick(pick, player_name) write = False else: content = { "status": "error", "message": 'room doesnt exists' } elif action == 'disconnect': print("bye player") self.players.pop(user) content = {"status": "disconnect"} close = True # TODO: enviar y recibir mensajes (chat) # TODO: logica del juego else: content = { "status": "error", "message": f'Command "{action}" doesnt exists' } else: content = {"status": "error", "message": 'login first'} if write: socket.write(content) if close: socket.close()