Repository navigation
Expand file tree
/
Copy pathproxy_server.py
More file actions
166 lines (145 loc) · 5.9 KB
/
Copy pathproxy_server.py
File metadata and controls
166 lines (145 loc) · 5.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import server
import socket
import os
import time
import string
from dataclasses import dataclass
from threading import *
from typing import Callable
@dataclass
class Cached_File:
content: str
last_modified: str
class Proxy_Server():
def __init__(self):
self.files = {}
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.origin_port = 8000
self.origin_host = socket.gethostname()
def read_request(self, connection):
# Request
print("READING REQUEST!!!!")
chunks = []
chunk = connection.recv(1024).decode()
chunks.append(chunk)
while "\r\n" not in chunk:
chunk = connection.recv(1024).decode()
chunks.append(chunk)
request = "".join(chunks)
print("Client send:\n%s" % request)
return request
# Params: request string
# Returns: request_headers list
# Splits headers based on \r\n
def parse_request(self, request):
request_headers = request.split("\r\n")
if len(request_headers) < 1:
return [], {}
return request_headers, self.parse_headers(request_headers)
# Params: headers list[string]
# Returns: parsed_headers dict
# Splits header lines
def parse_headers(self, headers):
parsed_headers = {}
for header in headers:
parsed_header = header.split(": ")
if len(parsed_header) == 2:
parsed_headers[parsed_header[0]] = parsed_header[1]
return parsed_headers
# Params: http_req string
# Returns: http_method string, endpoint string
# Parses request line to find method and endpoint
def parse_http_method(self, http_req):
if type(http_req) != str:
return "", ""
parsed_http_request = http_req.split(" ")
if len(parsed_http_request) < 2:
return "", ""
# Method
http_method, endpoint = parsed_http_request[0], parsed_http_request[1]
if endpoint == "/favicon.ico":
return "", ""
if endpoint[-1] == "/":
endpoint = endpoint[:-1]
return http_method, endpoint
def listen_proxy(self, host, port, num_connections):
self.socket.bind((host, port))
self.socket.listen(num_connections)
while True:
connection, addr = self.socket.accept()
print("REQUEST TO PROXY")
request = self.read_request(connection)
request_headers_list, request_headers_dict = self.parse_request(request)
http_method, endpoint = self.parse_http_method(request_headers_list[0])
print("Headers: \n%s\n" % request_headers_dict)
if not http_method and not endpoint:
connection.close()
continue
print("Method: %s\nEndpoint: %s\n" % (http_method, endpoint))
# Attach if-modified-since header
request = self.conditional_get(http_method, endpoint, request)
# Send req to origin
client_socket = socket.socket()
client_socket.connect((self.origin_host, self.origin_port))
client_socket.send(request.encode())
print("RECEIVING ORIGIN RESPONSE")
chunks = []
chunk = client_socket.recv(1024).decode()
chunks.append(chunk)
while "\r\n" not in chunk:
chunk = client_socket.recv(1024).decode()
chunks.append(chunk)
response = "".join(chunks)
# Cache the file from response
print("Origin server sent:\n%s" % response)
client_socket.close()
if self.has_not_modified_header(response) and (http_method, endpoint) in self.files:
response += self.files[(http_method, endpoint)].content
else:
self.cache_file(response, http_method, endpoint)
connection.sendall(response.encode())
def connect_origin(self, request):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((self.origin_host, self.origin_port))
client_socket.send(b"Hello, world")
print("SENDING HEADERS TO ORIGIN SERVER")
return client_socket
def receive_response(self, client_socket):
print("RECEIVING RESPONSE")
chunks = []
chunk = client_socket.recv(1024).decode()
chunks.append(chunk)
while "\r\n" not in chunk:
chunk = client_socket.recv(1024).decode()
chunks.append(chunk)
response = "".join(chunks)
print("Origin server sent:\n%s" % response.decode())
client_socket.close()
return response
def conditional_get(self, http_method, endpoint, request):
if (http_method, endpoint) not in self.files:
return request
else:
request+="\r\nIf-Modified-Since: %s" % self.files[(http_method, endpoint)].last_modified
return request
def has_not_modified_header(self, response):
response_body = response.split("\r\n\r\n")
return "304" in response_body[0]
def cache_file(self, response, http_method, endpoint):
response_body = response.split("\r\n\r\n")
_, response_headers_dict = self.parse_request(response_body[0])
if "Last-Modified" not in response_headers_dict:
return
# Only cache files that have the last-modified header
new_file = Cached_File
new_file.content = response_body[1]
new_file.last_modified = response_headers_dict["Last-Modified"]
self.files[(http_method, endpoint)] = new_file # idk if you can actually do this
def main():
PROXY_PORT = 3000
PROXY_HOST = "localhost"
proxy_server = Proxy_Server()
print("Initializing proxy with host %s and port %s \n" % (PROXY_HOST, PROXY_PORT))
proxy_server.listen_proxy(PROXY_HOST, PROXY_PORT, 5)
if __name__ == "__main__":
main()