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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
| __version__ = '0.0.1'
import ctypes, sys, mimetypes, time, posixpath, urllib, os, shutil, cgi, platform
os_system = platform.system()
py_version = sys.version.split()[0][0]
if py_version == '2':
import urlparse
from urllib import unquote, quote
elif py_version == '3':
from urllib import parse as urlparse
from urllib.parse import unquote, quote
DEFAULT_ERROR_MESSAGE = '<head>\n<title>Error response</title>\n</head>\n<body>\n<h1>Error response</h1>\n<p>Error code %(code)d.\n<p>Message: %(message)s.\n<p>Error code explanation: %(code)s = %(explain)s.\n</body>\n'
DEFAULT_ERROR_CONTENT_TYPE = 'text/html'
def _quote_html(html):
return html.replace('&', '&').replace('<', '<').replace('>', '>')
class HeaderOption:
def __init__(self, fp, index):
self.fp = fp
self.headers = []
self.dict = {}
line = self.fp.readline(65537).strip()
while line:
self.headers.append(line + '\n')
head = line.split(':')
if len(head) == 2:
self.dict[head[0].lower()] = head[1].strip()
elif len(head) > 2:
self.dict[head[0].lower()] = ':'.join(head[1:])
line = self.fp.readline(65537).strip()
def get(self, head, default=None):
head = head.lower()
if head in self.dict:
return self.dict[head]
else:
return ''
def __str__(self):
return ''.join(self.headers)
class BaseHTTPRequestHandler:
sys_version = 'Python/' + sys.version.split()[0]
server_version = 'BaseHTTP/' + __version__
default_request_version = 'HTTP/0.9'
if os_system == 'Linux':
wfile = sys.stdout
rfile = sys.stdin
libc = ctypes.CDLL('libc.so.6')
else:
wfile = open('info', 'wb')
rfile = open('payload', 'rb')
def parse_request(self):
self.command = None
self.request_version = version = self.default_request_version
self.close_connection = 1
self.set_cookie = 0
self.cookie = None
requestline = self.raw_requestline
requestline = requestline.rstrip('\r\n')
self.requestline = requestline
words = requestline.split()
if len(words) == 3:
command, path, version = words
if version[:5] != 'HTTP/':
self.send_error(400, 'Bad request version (%r)' % version)
return False
try:
base_version_number = version.split('/', 1)[1]
version_number = base_version_number.split('.')
if len(version_number) != 2:
raise ValueError
version_number = (
int(version_number[0]), int(version_number[1]))
except (ValueError, IndexError):
self.send_error(400, 'Bad request version (%r)' % version)
return False
if version_number >= (1, 1) and self.protocol_version >= 'HTTP/1.1':
self.close_connection = 0
if version_number >= (2, 0):
self.send_error(505, 'Invalid HTTP Version (%s)' % base_version_number)
return False
else:
if len(words) == 2:
command, path = words
self.close_connection = 1
if command != 'GET':
self.send_error(400, 'Bad HTTP/0.9 request type (%r)' % command)
return False
else:
if not words:
return False
else:
self.send_error(400, 'Bad request syntax (%r)' % requestline)
return False
self.command, self.path, self.request_version = command, path, version
self.headers = self.MessageClass(self.rfile, 0)
conntype = self.headers.get('Connection', '')
if conntype.lower() == 'close':
self.close_connection = 1
else:
if conntype.lower() == 'keep-alive' and self.protocol_version >= 'HTTP/1.1':
self.close_connection = 0
else:
self.close_connection = 1
self.cookie = self.headers.get('Set-Cookie', '')
if self.cookie.lower() != '':
self.set_cookie = 1
return True
def handle_one_request(self):
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(414)
return
if not self.raw_requestline:
self.close_connection = 1
return
if not self.parse_request():
return
mname = 'do_' + self.command
if not hasattr(self, mname):
self.send_error(501, 'Unsupported method (%r)' % self.command)
return
method = getattr(self, mname)
method()
self.wfile.flush()
except Exception as e:
self.close_connection = 1
return
def handle(self):
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request()
def send_error(self, code, message=None):
try:
short, long = self.responses[code]
except KeyError:
short, long = ('???', '???')
if message is None:
message = short
explain = long
self.send_response(code, message)
self.send_header('Connection', 'close')
content = None
if code >= 200 and code not in (204, 205, 304):
content = self.error_message_format % {'code': code,
'message': _quote_html(message),
'explain': explain}
self.send_header('Content-Type', self.error_content_type)
self.end_headers()
if self.command != 'HEAD' and content:
self.wfile.write(content)
error_message_format = DEFAULT_ERROR_MESSAGE
error_content_type = DEFAULT_ERROR_CONTENT_TYPE
def send_response(self, code, message=None):
if message is None:
if code in self.responses:
message = self.responses[code][0]
else:
message = ''
if self.request_version != 'HTTP/0.9':
self.wfile.write('%s %d %s\r\n' % (
self.protocol_version, code, message))
else:
self.wfile.write('%s %d %s111\r\n' % (self.protocol_version, code, message))
self.send_header('Server', self.version_string())
self.send_header('Date', self.date_time_string())
if self.set_cookie:
self.send_header('Cookie', self.cookie)
def send_header(self, keyword, value):
if type(value) != bytes:
value = value.encode()
if self.request_version != 'HTTP/0.9':
if os_system == 'Linux':
string = ctypes.c_buffer(1024)
self.libc.sprintf(string, value)
self.wfile.write('%s: %s\r\n' % (keyword, string.value.decode()))
else:
self.wfile.write('%s: %s\r\n' % (keyword, value.decode()))
if keyword.lower() == 'connection':
if value.lower() == 'close':
self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close_connection = 0
def send_body(self, content):
if self.request_version != 'HTTP/0.9':
self.wfile.write('\r\n%s' % content)
def end_headers(self):
if self.request_version != 'HTTP/0.9':
self.wfile.write('\r\n')
def version_string(self):
return self.server_version + ' ' + self.sys_version
def date_time_string(self, timestamp=None):
if timestamp is None:
timestamp = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
s = '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s
def log_date_time_string(self):
now = time.time()
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
s = '%02d/%3s/%04d %02d:%02d:%02d' % (
day, self.monthname[month], year, hh, mm, ss)
return s
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def address_string(self):
host, port = self.client_address[:2]
return socket.getfqdn(host)
protocol_version = 'HTTP/1.1'
MessageClass = HeaderOption
responses = {100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted', 'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices', 'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified', 'Document has not changed since given time'),
305: ('Use Proxy', 'You must use proxy specified in Location to access this resource.'),
307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'),
400: ('Bad Request', 'Bad request syntax or unsupported method'),
401: ('Unauthorized', 'No permission -- see authorization schemes'),
402: ('Payment Required', 'No payment -- see charging schemes'),
403: ('Forbidden', 'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed', 'Specified method is invalid for this resource.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone', 'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'),
417: ('Expectation Failed', 'Expect condition could not be satisfied.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented', 'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable', 'The server cannot process the request due to a high load'),
504: ('Gateway Timeout', 'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.')}
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
server_version = 'BabyHTTP/' + __version__
def do_GET(self):
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
def do_HEAD(self):
f = self.send_head()
if f:
f.close()
def do_GAGA(self):
self.send_response(200)
self.send_header('Content-type', self.guess_type('/gaga'))
self.send_header('Content-Length', '10')
self.send_body('your look what?')
self.end_headers()
def send_head(self):
path = self.translate_path(self.path)
f = None
if 'flag' in self.path:
self.send_error(403, self.responses[403][0])
return
if os.path.isdir(path):
parts = urlparse.urlsplit(self.path)
if not parts.path.endswith('/'):
self.send_response(301)
new_parts = (parts[0], parts[1], parts[2] + '/',
parts[3], parts[4])
new_url = urlparse.urlunsplit(new_parts)
self.send_header('Location', new_url)
self.end_headers()
return
for index in ('index.html', 'index.htm'):
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
self.send_error(403, self.responses[403][0])
return
ctype = self.guess_type(path)
try:
f = open(path, 'r')
except IOError:
self.send_error(404, 'File not found')
return
try:
self.send_response(200)
self.send_header('Content-type', ctype)
fs = os.fstat(f.fileno())
self.send_header('Content-Length', str(fs[6]))
self.send_header('Last-Modified', self.date_time_string(fs.st_mtime))
self.end_headers()
return f
except:
f.close()
raise
def list_directory(self, path):
import tempfile
try:
list = os.listdir(path)
except os.error:
self.send_error(404, 'No permission to list directory')
return
list.sort(key=lambda a: a.lower())
f = tempfile.TemporaryFile(mode='w+t')
displaypath = cgi.escape(unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write('<html>\n<title>Directory listing for %s</title>\n' % displaypath)
f.write('<body>\n<h2>Directory listing for %s</h2>\n' % displaypath)
f.write('<hr>\n<ul>\n')
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
if os.path.isdir(fullname):
displayname = name + '/'
linkname = name + '/'
if os.path.islink(fullname):
displayname = name + '@'
f.write('<li><a href="%s">%s</a>\n' % (
quote(linkname), cgi.escape(displayname)))
f.write('</ul>\n<hr>\n</body>\n</html>\n')
length = f.tell()
f.seek(0)
self.send_response(200)
encoding = sys.getfilesystemencoding()
self.send_header('Content-type', 'text/html; charset=%s' % encoding)
self.send_header('Content-Length', str(length))
self.end_headers()
return f
def translate_path(self, path):
path = path.split('?', 1)[0]
path = path.split('#', 1)[0]
trailing_slash = path.rstrip().endswith('/')
path = posixpath.normpath(unquote(path))
words = path.split('/')
words = filter(None, words)
path = os.getcwd()
for word in words:
if not os.path.dirname(word):
if word in (os.curdir, os.pardir):
pass
else:
path = os.path.join(path, word)
if trailing_slash:
path += '/'
return path
def copyfile(self, source, outputfile):
shutil.copyfileobj(source, outputfile)
def guess_type(self, path):
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
return self.extensions_map['']
if not mimetypes.inited:
mimetypes.init()
extensions_map = mimetypes.types_map.copy()
extensions_map.update({'': 'application/octet-stream',
'.py': 'text/plain',
'.c': 'text/plain',
'.h': 'text/plain'})
def main():
a = SimpleHTTPRequestHandler()
a.handle()
if __name__ == '__main__':
main()
|