-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTPClient.py
300 lines (248 loc) · 11.2 KB
/
HTTPClient.py
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import socket
import sys
import os
import bs4 as bs
class HTTPClient:
def __init__(self, host, port):
self.host = host.lower() # The server's hostname.
self.port = int(port) # The port used to reach the host.
self.s = self.createSocket() # Instantiate the socket and connect with host/port.
"""
Creates an IPv4, TCP socket and connects to the host using the hostname and port number.
@return: returns the created socket.
"""
def createSocket(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create an IPv4, TCP socket.
print(f"[SOCKET CREATED]")
s.connect((socket.gethostbyname(self.host), self.port)) # Connect to the host using the host name and port number.
print(f"[SOCKET CONNECTED] {self.host} {self.port}")
return s
"""
Transforms an HTTP string request and transforms it to bytes, then sends it to the server.
@param request: The HTTP string request.
"""
def encodeAndSend(self, request):
bytes = request.encode('utf-8') # Encode string to bytes.
try:
self.s.send(bytes) # Send the request to the server.
except Exception as e:
print(f"Error sending: {e}")
"""
Sets the host and executes a certain HTTP command based on user input.
@param host: The host to send the request to.
@param requestType: String to determine the request type.
@param filename: When calling PUT/POST, the name fo the file to make changes to or create.
@param body: When calling PUT/POST, the content of the file.
"""
def executeRequest(self, host, requestType, filename="", body=""):
self.host = host.lower() # Set the host.
requestType = requestType.upper()
if requestType == 'GET':
self.get(filename)
elif requestType == 'POST':
self.post(filename, body)
elif requestType == 'PUT':
self.put(filename, body)
elif requestType == 'HEAD':
self.head()
else:
print('Unknown request type')
"""
Retrieves an HTML page from a certain webserver and stores the results locally.
@param filename: What specific filename to retrieve from the webserver, if nothing is provided, retrieves the root.
"""
def get(self, filename=""):
modifiedSince = input("If-Modified-Since: ")
if modifiedSince == "":
request = f'GET /{filename} HTTP/1.1\r\nHost: {self.host}\r\n\r\n'
elif modifiedSince != "":
request = f'GET /{filename} HTTP/1.1\r\nHost: {self.host}\r\nIf-Modified-Since: {modifiedSince}\r\n\r\n'
print(f"[RETRIEVING] GET /{filename} HTTP/1.1")
self.encodeAndSend(request) # Send request to server.
response = self.rvcChunks() # Read the server reply & store it in 'response'.
contentType = self.findContentType(response)
if contentType == b'text':
charset = self.findCharset(response)
self.removeHeadersAndWriteFile(response, filename) # Pass the byte response to removeHeadersAndWriteFile
images = self.scrapeImages(filename)
if images:
print(f"[IMAGES FOUND] {images [0:2]}...")
self.getImages(images)
self.alterImageSrc(filename, charset)
elif contentType == b'image':
self.writeImage(filename, response)
"""
Retrieves the HEAD response from a certain webserver and stores the results locally.
"""
def head(self):
modifiedSince = input("If-Modified-Since: ")
if modifiedSince == "":
request = f'HEAD / HTTP/1.1\r\nHost: {self.host}\r\nConnection: close\r\n\r\n'
elif modifiedSince != "":
request = f'HEAD / HTTP/1.1\r\nHost: {self.host}\r\nIf-Modified-Since: {modifiedSince}\r\nConnection: close\r\n\r\n'
print(f"[RETRIEVING] HEAD / HTTP/1.1")
self.encodeAndSend(request)
response = self.s.recv(2048)
start = response.find(b"HTTP/1.1") + 9
statusCode = response[start:start + 3].decode()
if statusCode == "200":
self.writeFile(response, "headers.html")
else:
self.removeHeadersAndWriteFile(response, "headers.html")
"""
Appends content to an existing file on the server.
@param filename: What specific filename to alter from the webserver.
@param body: The content to append to the file.
"""
def post(self, filename, body):
contenLength = len(body)
request = f'POST /{filename} HTTP/1.1\r\nHost: {self.host}\r\nContent-Length: {contenLength}\r\n\r\n{body}\r\n\r\n'
print(f"[SENDING] POST /{filename} HTTP/1.1")
self.encodeAndSend(request)
response = self.s.recv(2048)
print(f"[CREATED] {response.decode()}")
"""
Creates a new file on the server with the provided content..
@param filename: What specific filename to create on the webserver.
@param body: The content to write to the new file.
"""
def put(self, filename, body):
contenLength = len(body)
request = f'PUT /{filename} HTTP/1.1\r\nHost: {self.host}\r\nContent-Length: {contenLength}\r\n\r\n{body}\r\n\r\n'
print(f"[SENDING] PUT /{filename} HTTP/1.1")
self.encodeAndSend(request)
response = self.s.recv(1024)
print(f"[CREATED] {response.decode()}")
"""
Retrieves all the chunks from a certain webpage and stores them.
@return: The request response.
"""
def rvcChunks(self):
BUFFERSIZE = 4096
response = b''
totalLength = 0
contentLength = sys.maxsize
while True:
data = self.s.recv(BUFFERSIZE)
totalLength += len(data)
response += data
if b"Content-Length:" in data:
startPos = data.index(b"Content-Length:") # Start position in byte stream where "Content-Length" is found.
endPos = data[startPos:].index(b"\r\n") # Returns the data from the start position in byte stream, finds the first occurence of "\r\n" in the byte stream after content length and save its position.
contentLength = data[startPos + 16:startPos + endPos].decode() # Gets the content length bytes and decodes it to discover the total content contentLength of HTTP request.
if totalLength >= int(contentLength):
break
return response
"""
Looks for the charset in the response, more specifically in the HTTP header.
@param response: The encoded response from the server.
@return: The Content-Type charset to decode the response with.
"""
def findCharset(self, response):
charset = ""
if response.find(b"Content-Type:") != -1:
headerEnd = response.find(b"\r\n\r\n")
range = response[:headerEnd]
if range.find(b"charset=") != -1:
startPos = range.find(b"charset=")
findData = response[startPos:]
endPos = findData.find(b"\r\n")
charset = findData[8:endPos].decode()
else:
charset = 'utf-8'
return charset
"""
Looks for the content type in the response, more specifically in the Content-Type header.
@param response: The encoded response from the server.
@return: The Content-Type to classify the response.
"""
def findContentType(self, response):
type = ""
contentType = response.index(b"Content-Type:")
data = response[contentType:].split(b"\r\n")[0].split(b" ")[1]
if b"/" in data:
type = data.split(b"/")[0]
return type
"""
Creates the file that contains the requested content from a webpage.
@param content: The content that will be stored in the file.
@param filename: Name of the file where the requested content is located.
"""
def writeFile(self, content, filename):
if filename == "":
filename = "index.html"
myDir = os.getcwd() + "/" + self.host
if not os.path.exists(myDir):
os.mkdir(myDir) # Create host folder.
with open(myDir + "/" + filename, "wb") as f: # Write file.
f.write(content)
"""
Removes the HTTP headers from the response.
@param response: The byte response from the HTTP request.
@param filename: Determines the name of the file to write.
"""
def removeHeadersAndWriteFile(self, response, filename):
body = response.split(b'\r\n\r\n')[1]
self.writeFile(body, filename)
return
"""
Looks for all embedded images in the HTML body.
@param filename: Name of the resource.
@return: A dictionary containing the src of all the images.
"""
def scrapeImages(self, filename):
if filename == "":
filename = "index.html"
images = []
with open(self.host + "/" + filename, "rb") as text_file:
soup = bs.BeautifulSoup(text_file, 'lxml')
for image in soup.find_all('img'):
images.append(image.get('src'))
return images
"""
Retrieves each image individually from a webpage.
@param images: Dictionary of all the images names to be retrieved from the webpage.
"""
def getImages(self, images):
for image in images:
request = f'GET /{image} HTTP/1.1\r\nHost: {self.host}\r\n\r\n' # Construct request byte string.
print(f"[RETRIEVING] GET /{image} HTTP/1.1")
self.encodeAndSend(request)
response = self.rvcChunks()
self.writeImage(image, response)
"""
Writes images from the webpage and saves them locally.
The original folder structure from the webpage is preserved.
@param imageName: Name of an individual image.
@param response: The response that contains the image.
"""
def writeImage(self, imageName, response):
image = response.split(b'\r\n\r\n')[1] # Gets the image data and makes sure the header is excluded.
if imageName.startswith('/'):
imageName = imageName[1:]
if imageName.find('/'):
os.makedirs(os.getcwd() + "/" + self.host + "/" + os.path.dirname(imageName), exist_ok=True)
with open(os.getcwd() + "/" + self.host + "/" + imageName, "wb") as f:
f.write(image)
else:
with open(os.getcwd() + "/" + self.host + "/" + imageName, "wb") as f:
f.write(image)
"""
Alters the src path from the images in the body so the stored webpage loads the images correctly.
@param filename: The filename to search for images and alter their sources.
@param charset: The encoding for the content of the webpage.
"""
def alterImageSrc(self, filename, charset):
if filename == "":
filename = "index.html"
body = open(os.getcwd() + "/" + self.host + "/" + filename, "rb")
soup = bs.BeautifulSoup(body, 'lxml')
images = soup.find_all("img")
for image in images:
src = image.get('src')
if src[0] == '/':
image['src'] = src[1:]
soupStr = str(soup.prettify())
soupBytes = soupStr.encode(charset)
with open(os.getcwd() + "/" + self.host + "/" + filename, "wb") as f:
f.write(soupBytes)