-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpfs.py
74 lines (68 loc) · 2.75 KB
/
httpfs.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
import socket
import threading
import argparse
import os
def httpfs(host, port, verbose, inline):
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
listener.bind((host, port))
listener.listen(5)
print('Server is listening at', port)
while True:
conn, addr = listener.accept()
threading.Thread(target=handle_client, args=(conn, addr, verbose, inline)).start()
finally:
listener.close()
def handle_client(conn, addr, verbose, inline):
if verbose:
print ('New client from', addr)
if not inline:
inline = '.'
try:
while True:
error = False
data = conn.recv(1024)
if not data:
break
for e in data.split("/"):
if e == '..':
error = True
if not error:
reply = ""
if data.split(" ")[0] == "GET" and data.split(" ")[1] == "/" or data.split(" ")[1] == "":
if verbose:
print("Returning the root directory files")
if inline:
os.chdir(inline)
reply = filter(os.path.isfile, os.listdir(os.curdir))
else:
reply = filter(os.path.isfile, os.listdir(os.curdir))
reply = ', '.join(reply)
if data.split(" ")[0] == "GET" and data.split(" ")[1] != "/" and data.split(" ")[1] != "":
if verbose:
print("Returning the specified file contents")
try:
with open(inline + data.split(" ")[1], "r") as f:
reply = f.read()
except IOError:
reply = "HTTP ERROR 404"
if data.split(" ")[0] == "POST":
if verbose:
print("Writing to " + data.split(" ")[1])
with open(inline + data.split(" ")[1], "w") as f:
f.write(data.split("\r\n\r\n")[1].decode("utf-8"))
reply = "Data successfully written to " + data.split(" ")[1]
reply = reply + '\n'
if verbose:
print(reply)
conn.sendall(reply)
else:
conn.sendall("Access Denied \n")
finally:
conn.close()
parser = argparse.ArgumentParser()
parser.add_argument("-p", dest="port", help="server port", type=int, default=8080)
parser.add_argument("-v", dest="verbose", action="store_true", help="verbose")
parser.add_argument("--d", nargs="?", dest="inline", help="inline-data")
args = parser.parse_args()
httpfs('', args.port, args.verbose, args.inline)