def _handle_request(self, connection_hash, tcp_pkt): if http.has_complete_headers(tcp_pkt.data): req = http.parse_request(tcp_pkt.data) logging.debug('Request URL: %s' % req['host'] + req['path']) logging.debug('Storing stream %s.' % connection_hash) self.packet_streams[connection_hash] = TcpStream(connection_hash)
def handle(self): while self.is_alive: try: data = self.conn.recv(1024) except ConnectionResetError: print(f"[-] {self.addr} disconnected: Connection losed.") self.__del__() else: if data: status = 200 try: request = http.parse_request(data) except http.MethodNotAllowed: status = 405 path = "error_sites/405.html" except Exception: status = 400 path = "error_sites/400.html" else: if request.uri == '/': request.uri = "/index.html" path = os.path.join("htdocs/", request.uri[1:]) try: f = open(path, "r") except FileNotFoundError: status = 404 path = "error_sites/404.html" f = open("error_sites/404.html", "r") _, ext = os.path.splitext(path) print(f"[i] {self.addr} requested {request.uri}") d = f.read() f.close() response = http.Response(d, content_type=http.mime_types[ext], status=status) try: self.conn.sendall(response.get_raw()) except OSError: self.__del__() print(f"[i] {self.addr} ended the connection.")
def test_request_round_trip(self): req0 = http.Request( method ='POST', path ='/api/data', header ={ 'Host': 'www.example.com', 'Referer': 'www.searchengine.com', 'User-Agent': 'CodeX Special Web Client', }, body ="{field: 'foo', value: 42}".encode("UTF-8")) # Round trip through our API. msg = http.format_request(req0) req1 = http.parse_request(msg) self.assertEqual(req1.method, 'POST') self.assertEqual(req1.path, '/api/data') self.assertEqual(len(req1.header), 3) self.assertTrue('Host' in req1.header) self.assertEqual(req1.header['Host'], 'www.example.com') self.assertTrue('Referer' in req1.header) self.assertEqual(req1.header['Referer'], 'www.searchengine.com') self.assertTrue('User-Agent' in req1.header) self.assertEqual(req1.header['User-Agent'], 'CodeX Special Web Client') self.assertEqual(req1.body, "{field: 'foo', value: 42}".encode("UTF-8"))