def response(self, sock: socket.socket) -> DataTuple: """ It listens the raw response from the server at sock and convert them to user friendly messages. :param sock: current working socket :return: a DataTuple that contains the info from the server response JSON """ if type(sock) is not socket.socket: raise DMProtocolError('sock is not of type socket') recv = sock.makefile('r') resp = recv.readline() resp = self.extract_json(resp) # DataTuple conversion if resp.type == 'ok': # when sending DirectMessage if type(resp.message) is str: if 'Direct message sent' in resp.message: print("Direct message successfully sent.") print('Server says: {}\n'.format(resp.message)) # when retrieving DirectMessage elif type(resp.message) is list: print('Messages successfully retrieved!') elif resp.type == 'error': print("An error occurs.") print('Error message: {}\n'.format(resp.message)) return resp
def parse_request(self, conn: socket) -> Request: # Все чтение сокета делал через файлы, так удобнее читать построчно file = conn.makefile('rb') data = file.readline(1024*64) # Нагуглил, что хедеры обязаны быть в этой кодировке line = data.decode('iso-8859-1') line = line.strip().split() if len(line) != 3: # Ожидаем метод, цель и протокол raise e.BadRequest('Request first line have to be 3 parts') method, target, proto = line # Перенаправляем / на /index.html if target == '/': target = '/index.html' # Других скорее всего и не будет, но на всякий if proto != 'HTTP/1.1': raise e.UnexpectedProto('Unexpected HTTP version') headers = self.parse_headers(file) host = headers.get('Host') if not host or host.strip() not in [self.__host, f'{self.__host}:{self.__port}']: raise e.BadRequest('Not found') return Request(method, target, proto, headers, file)
def reader(client: socket, output: Channel, cancel: Channel): '''This greenlet is spawned to monitor the client for incoming requests''' with client.makefile('rb') as client_input: while 1: metadata_bytes = client_input.read(METADATA_UNPACKER.size) if (len(metadata_bytes) < METADATA_UNPACKER.size): # Probably received EOF, so shut everything down try_write_channel(cancel, True, timeout=-1) return message_size, = METADATA_UNPACKER.unpack(metadata_bytes) message_bytes = client_input.read(message_size) if (len(message_bytes) < message_size): # Probably received EOF, so shut everything down try_write_channel(cancel, True, timeout=-1) return message = RequestMessage() message.ParseFromString(message_bytes) message_type = message.WhichOneof('type') message_handler = handlers.HANDLERS[message_type] message_handler(message, output, cancel)
def __init__(self, irc_url: str, conn: socket.socket, addr: Tuple[str, int]) -> None: self.irc_url = irc_url self.rfile = conn.makefile("rb") self.wfile = conn.makefile("wb") self.client_address = addr self.handle()
def handle(self, conn: socket.socket): try: in_ = conn.makefile('r') out = conn.makefile('w') # we must read in the full header even if we dont # intend to use it... header = [] line = " " while line not in ['\n', '\r\n', '']: line = in_.readline() header.append(line) print( f"""HTTP/1.1 201 Content-Type: text/plain; charset=UTF-8 Server-name: CPO debugger CPO State {datetime.datetime.now()} """, file=out) self.show_cso_state(file=out) out.flush() out.close() conn.shutdown(0) conn.close() finally: if conn is not None: conn.close()
def __init__(self, socket: Socket, session: Optional[Session] = None, number: int = 0) -> None: self.socket = socket self.file = socket.makefile('rwb', buffering=0) self.session = session self.number = number & ~1
def read_code(sock: socket) -> str: f = sock.makefile(mode='rwb', buffering=0) code = '' while True: line = f.readline().decode('utf-8') if line in ['END CODE\n']: break if line in ['', 'END CODE\n']: break code += line return code
def parse_request(self, connect: socket.socket) -> Request: rfile = connect.makefile(mode='rb') method, target, version = self.parse_request_line(rfile) headers = self.parse_headers(rfile) host = headers.get('Host') if not host: raise HTTPError(400, 'Bad request') if host not in (self._server_name, f'{self._server_name}:{self._port}'): raise HTTPError(404, 'Not found') return Request(method=method, target=target, version=version, headers=headers, rfile=rfile)
def handle(client: socket.socket): f = client.makefile('r') dbConn = sqlite3.connect('bees.db') cursor = dbConn.cursor() for line in f: print(line.strip()) size, speed = [float(x) for x in line.split(',')] sql = 'INSERT INTO bees(size, speed) VALUES (?, ?);' cursor.execute(sql, (size, speed)) dbConn.commit() cursor.close() dbConn.close()
def sender(self, sock: socket.socket, msg: str) -> None: """ A wrapper method to simplify the sending process. :param sock: currently working socket :param msg: the message needs to be sent :return: None """ if type(sock) is not socket.socket: raise DMProtocolError('sock is not of type socket') send = sock.makefile('w') send.write(msg + '\r\n') send.flush()
def __init__( self, irc_url: str, conn: socket.socket, addr: Tuple[str, int], password: Optional[str] = None, ) -> None: self.irc_url = irc_url self.password = password self.rfile = conn.makefile("rb") self.wfile = conn.makefile("wb") self.client_address = addr self.handle()
def _handle_request(self, connection: socket.socket) -> None: request = connection.makefile().readline().strip() if not request: return if request == SHUTDOWN_REQUEST: self._should_shut_down = True return if request == UPTIME_REQUEST: connection.sendall( str(int(time() - self._start_timestamp)).encode('utf')) else: connection.sendall( self._request_handler.process_request(request).encode('utf'))
def writer(client: socket, output: Channel, cancel: Channel): '''This greenlet is spawned to send output back to the client''' with client.makefile('wb') as client_output: cancelled = False while not cancelled: has_data, data = try_read_channel(output, timeout=1) if (has_data): metadata = METADATA_UNPACKER.pack(len(data)) client_output.write(metadata) client_output.write(data) client_output.flush() cancelled, _ = try_read_channel(cancel, timeout=0)
def send_response(self, *, connect: socket.socket, response: Response) -> None: wfile = connect.makefile('wb') status_line = f'HTTP/1.1 {response.status} {response.reason}\r\n' wfile.write(status_line.encode('iso-8859-1')) if response.headers: for (key, value) in response.headers: header_line = f'{key}: {value}\r\n' wfile.write(header_line.encode('iso-8859-1')) wfile.write(b'\r\n') if response.body: wfile.write(response.body) wfile.flush() wfile.close()
def send_response(self, conn: socket, resp): # Опять же пишем в файл file = conn.makefile('wb') # Записываем первую строку file.write(f'HTTP/1.1 {resp.status} {resp.reason}\r\n'.encode('iso-8859-1')) # Все хедеры if resp.headers: for k, v in resp.headers.items(): file.write(f'{k}: {v}\r\n'.encode('iso-8859-1')) # и разделитель file.write(b'\r\n') if resp.body: file.write(resp.body) file.flush() file.close()
def parse_request(req: socket.socket): reqData = '' rfile = req.makefile() first_line = rfile.readline(_MAXLINE+1) reqData += first_line first_line = first_line.rstrip('\r\n') words = first_line.split() if len(words) == 3: method, path, version = words elif len(words) == 2: method, path = words header_lines = [] while True: line = rfile.readline(_MAXLINE + 1) reqData += line header_lines.append(line) if line in ('\r\n', '\n', ''): break hstring = ''.join(header_lines) headers = email.parser.Parser().parsestr(hstring) length = headers.get("Content-Length") try: n_bytes = int(length) except (TypeError, ValueError): n_bytes = 0 if n_bytes > 0: reqData += rfile.read(n_bytes) #get host from header host = headers.get("Host") if host: return (reqData, host) #get host host from url scheme_position = path.find("://") if scheme_position == -1: path = path else: path = path[scheme_position+3:] host = path.split('/')[0] return (reqData, host)
def _create_io(client: socket.socket) -> Client: ''' Creates a namedtuple object for easy access to socket and i/o ''' return Client(client, client.makefile('r'), client.makefile('w'))
def __init__(self, sock: socket.socket): self._sock = sock sock_file = sock.makefile('rw') Cmdr.__init__(self, stdin=sock_file, stdout=sock_file) sys.stdout = sock_file Thread.__init__(self, name='HabPrompt', daemon=True)
def __init__(self, client_socket: socket.socket): self.headers_buffer = [] self.sock = client_socket self.rfile = client_socket.makefile('rb') self.wfile = client_socket.makefile('wb') self.process_request()
def __init__(self, sock: socket.socket): super().__init__(sock.makefile('rb'), sock.makefile('wb')) self.socket = sock
def begin_request(self, env, client: socket.socket): input = client.makefile('r') if 'CONTENT_LENGTH' in env: input = RestrictedInput(input, int(env["CONTENT_LENGTH"])) elif 'HTTP_TRANSFER_ENCODING' not in env: # Set it to eof automatically. input = RestrictedInput(input, 0) env['wsgi.input'] = input is_head = env['REQUEST_METHOD'] == 'HEAD' response = None response_sent = False def write(data: bytes): nonlocal response_sent, response if not response_sent: response_sent = True if response is None: response = ["200 Ok", []] client.sendall( b'HTTP/1.1 %s\r\nStatus: %s\r\nConnection: close\r\n' % (response[0].encode("ascii"), response[0].encode("ascii"))) for header in response[1]: client.sendall(b'%s: %s\r\n' % (header[0].encode("latin-1"), header[1].encode("latin-1"))) client.sendall(b'\r\n') self.logger.debug("Response sent") if not is_head: client.sendall(data) def start_response(status, headers): nonlocal response self.logger.debug(f"Receiving response: {status}") response = [status, headers] return write result = None try: self.logger.debug(repr(env)) self.logger.debug(self._app) result = self._app(env, start_response) for msg in result: write(msg) if not response_sent: write(b"") except Exception as e: print("Got error in WSGI Callback.") for line in '\n'.join( traceback.format_exception(type(e), e, e.__traceback__)).split("\n"): print(line, sep="", end="\n") finally: if hasattr(result, 'close'): result.close() client.shutdown(socket.SHUT_WR) client.close()
def _create_io(client: socket.socket)->Client: return Client(client,client.makefile('r'),client.makefile('w'))