def proc_http_connection(self, sock): sck_id = str(sock) data = common.recv(sock, common.BUFFER_SIZE) if len(data): self.data_of_new_socks[ sck_id] = self.data_of_new_socks[sck_id] + data if self.data_of_new_socks[sck_id].find("\r\n\r\n") > 0: self.logger.info( "received http header\n" + self.data_of_new_socks[sck_id].split("\r\n\r\n")[0]) host = re.findall(self.re_host_patten, self.data_of_new_socks[sck_id]) if len(host): domain = host[0] if self.domain_to_host.has_key(domain): host_name, port = self.domain_to_host[domain] if self.hosts.has_key(host_name): self.hosts[host_name].add_http_tunnel_req( sock, self.data_of_new_socks[sck_id], port) self.__remove_new_sock(sock) else: self.__remove_new_sock(sock) common.safe_close_socket(sock) else: self.__remove_new_sock(sock) common.safe_close_socket(sock)
def main(self): actions = { 'pong': self.on_pong, "setup": self.on_setup, "registered": self.on_registered } while True: sock = common.connect_to(self.proxy_addr, self.proxy_port) if sock is None: time.sleep(10) continue self.logger.info("connected to %s:%d" % (self.proxy_addr, self.proxy_port)) try: common.set_sock_buff_size(sock) #sock.setblocking(1) sock.settimeout(5) self.registered = False text = '' socks_to_read = [sock] send_ping = True while True: if self.registered: if send_ping: sock.sendall("ping;") send_ping = False else: send_ping = True else: sock.send("register %s;" % self.my_name) readable, writable, exceptional = select.select( socks_to_read, [], [], 10) if len(readable): try: data = common.recv(sock, common.BUFFER_SIZE) except socket.error: self.logger.error(traceback.format_exc()) break if len(data) == 0: self.logger.warn( 'read exception, disconnected by remote') break else: text += data while True: action, params, text = common.get_action(text) if action is None: break if actions.has_key(action): actions[action](sock, params) except: self.logger.error(traceback.format_exc()) common.safe_close_socket(sock)
def proc_cmd_connection(self, sck): sck_id = str(sck) data = common.recv(sck, common.BUFFER_SIZE) if len(data): text = self.data_of_new_socks[sck_id] + data while True: action, params, text = common.get_action(text, "\r\n") self.data_of_new_socks[sck_id] = text if action is None: break if self.actions.has_key(action): self.actions[action](sck, params, text) else: self.__remove_new_sock(sck) common.safe_close_socket(sck)
def __proc_host_actions(self, actions): try: data = common.recv(self.base_sck, common.BUFFER_SIZE) if len(data): text = self.data_from_host + data while True: action, params, text = common.get_action(text) if action is None: break if actions.has_key(action): actions[action](params) self.data_from_host = text else: # 与host的连接断开 self.logger.info(u'与host的连接断开') self.running.clear() except socket.error, e: self.running.clear() self.logger.error(traceback.format_exc())
def req_session(self): '''Reqiest a new session from the server :return: list of string, The list of files the server has stored for the user ''' if self.id is None: logging.error( "Yo, what's up! You have no ID and should request one " "from the server before initiating the session (use: req_id())" ) return None try: logging.debug('Requesting a new session from the server') p_new_sess = common.ctrl_struct.pack(*(common.CTRL_REQ_INIT_SESS, self.id)) self.sock.sendall(p_new_sess) p_new_sess_resp = common.recv(self.sock) if p_new_sess_resp is None: logging.error('Got an empty message?') return None new_sess_code, new_sess_files = p_new_sess_resp.split( common.DELIM_LONG) if int(new_sess_code) != common.CTRL_OK: logging.error('Server was not happy') return None self.files = new_sess_files.split(common.DELIM) except socket.timeout as err: logging.debug('Socket timeout error: %s' % err) return None except socket.error as err: logging.debug('Socket error: %s' % err) return None except struct.error as err: logging.debug('Struct un/packing error: %s' % err) return None except KeyboardInterrupt: logging.debug('Caught SIGINT') return None except BaseException as err: logging.debug('Unknown error: %s' % err) return None return self.files
def recv_changes(self): '''Receive messages from the server and put them into a queue :return: None (only if there was an interrupt or the variable `self.is_running' is set to False; otherwise the receiving loop is always running regardless of caught exceptions) ''' logging.debug('Starting to receive messages from the server') while self.is_running: try: msg = common.recv(self.sock) if msg is not None: unmarshalled_msg = common.unmarshall(msg) client.queue_incoming.put(unmarshalled_msg) logging.debug( 'Received a message from the server; pushed it into a queue' ) else: logging.debug("Server dropped?") break except socket.timeout as err: logging.debug('Socket timeout error: %s' % err) break except socket.error as err: logging.debug('Socket error: %s' % err) break except ValueError as err: logging.debug('Unmarshalling (?) error: %s' % err) break except RuntimeError as err: logging.debug('Runtime error: %s' % err) break except KeyboardInterrupt: logging.debug('Caught SIGINT') break except BaseException as err: logging.debug('Unknown error: %s' % err) break self.is_running = False
import socket from common import send, recv def connect_to_server(ip, port): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((ip, port)) return server server = connect_to_server("3.1.5.104", 4000) print(recv(server, 10))
import socket from common import send, recv import time def create_socket(ip, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((ip, port)) sock.listen(5) # become a server socket, maximum 5 connections return sock def accept_client(sock): client, address = sock.accept() return client, address sock = create_socket("0.0.0.0", 4000) client, address = accept_client(sock) print(recv(client,2).decode("utf-8"))
def run(self): '''Sender/receiver part in the server, one per file :return: None ''' while len(self.parent_manager.clients) > 0: sockets = self.parent_manager.clients.keys() outputs = self.parent_manager.outputs.keys() readable, writable, exceptional = select.select( sockets, outputs, sockets, 0.5) for r in readable: msg = common.recv(r) if msg and msg != common.DELIM: logging.debug("Received message from client #ID = '%d'" % self.parent_manager.clients[r][ client_manager.KEY_USERID]) # let's parse the sent message and apply it on our file try: ret_edit = self.parent_manager.file_manager.edit( *common.unmarshall(msg)) if not ret_edit: logging.debug( "Encountered an error while editing the file") continue except ValueError as err: logging.debug( "Encountered some kind of error in unmarshalling: %s" % err) if r not in exceptional: exceptional.append(r) continue # put into a queue for s in sockets: if s is not r: if s not in self.parent_manager.outputs: self.parent_manager.outputs[s] = [] self.parent_manager.outputs[s].append(msg) else: logging.debug( "Connection dropped with client #ID = '%d'?" % self.parent_manager.clients[r][ client_manager.KEY_USERID]) if r in self.parent_manager.outputs: del self.parent_manager.outputs[r] del self.parent_manager.clients[r] r.close() for w in writable: if w in self.parent_manager.outputs: while len(self.parent_manager.outputs[w]) > 0: logging.debug( "Sending the changes to client #ID = '%d'" % self.parent_manager.clients[w][ client_manager.KEY_USERID]) common.send(w, self.parent_manager.outputs[w].pop(0)) del self.parent_manager.outputs[w] for e in exceptional: logging.debug( "Client #ID = '%d' dropped connection" % self.parent_manager.clients[e][client_manager.KEY_USERID]) if e in self.parent_manager.outputs: del self.parent_manager.outputs[e] if e in self.parent_manager.clients: del self.parent_manager.clients[e] logging.debug("No clients left, cleaning up") self.parent_manager.file_manager.close() del server_backend.server.managers[self.parent_manager.fn]
def req_file(self, fn, visibility=common.FILEMODE_PUBLIC): '''Returns file contents :param fn: string, file name (id:file basename) to be opened :param visibility, int, sets the ownership if a) the file is about to be created; and if b) the value of `make_public' is set to either common.FILEMODE_PUBLIC or common.FILEMODE_PRIVATE otherwise the visibility defaults to common.FILEMODE_DEFAULT on the server side :return: string, the contents of the file if everything succeeded None, if there was an error ''' if self.id is None: logging.error( "Yo, what's up! You have no ID and should request one " "from the server before initiating the session (use: req_id())" ) return False self.fn = fn file_contents = '' try: logging.debug( "Requesting to open file '%s' by server w/ opening mode '%d'" % (self.fn, visibility)) req = common.DELIM.join([self.fn, str(visibility)]) self.sock.sendall(req) p_new_file_resp = self.sock.recv(common.ctrl_struct.size) if not p_new_file_resp: logging.debug("Server was not happy") raise RuntimeError( "Server was not happy b/c it didn't send us anything") new_file_code, _ = common.ctrl_struct.unpack(p_new_file_resp) if new_file_code == common.CTRL_OK_CREATE_FILE: logging.debug( 'Server had to create a new file, which is empty anyways') elif new_file_code == common.CTRL_OK_READ_FILE: logging.debug( "Server has to serve the file for us; let's read it") # read from socket resp = common.recv(self.sock) if resp is None: logging.error("Server was not happy") raise RuntimeError( "Server was not happy b/c it didn't send us anything") resp_code, file_contents = resp.split(common.DELIM) print("File contents: " + str(file_contents)) if int(resp_code) == common.CTRL_OK: logging.debug('Received %d bytes of the file' % len(file_contents)) else: logging.error('Server was not happy') raise RuntimeError( 'Server was not happy b/c it sent us a wrong control code' ) else: logging.error('Server was not happy') raise RuntimeError( 'Server was not happy b/c it sent us a wrong control code') # now boot up a new thread which listens to incoming edit control messages sent by the server # this thread should die only if # a) self.is_running is set to False; or if # b) the main thread exits (we daemonize the thread) receiving_thread = threading.Thread(target=self.recv_changes, name='ReceiveFromServerThread') receiving_thread.setDaemon(True) receiving_thread.start() except socket.timeout as err: logging.debug('Socket timeout error: %s' % err) return None except socket.error as err: logging.debug('Socket error: %s' % err) return None except struct.error as err: logging.debug('Struct un/packing error: %s' % err) return None except RuntimeError as err: logging.debug('Runtime error: %s' % err) return None except KeyboardInterrupt: logging.debug('Caught SIGINT') return None except BaseException as err: logging.debug('Unknown error: %s' % err) return None return file_contents