/
server.py
executable file
·118 lines (91 loc) · 3.37 KB
/
server.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
#!/usr/bin/env python
# Import 'with' statement for Python 2.5 and earlier. 'with' and 'as' are
# keywords in Python 2.6.
from __future__ import with_statement
from contextlib import closing
import os
import sys
import SocketServer
import tarfile
import uuid
import time
import re
# Some globals:
tmpDir = '/opt/tmp/' # MUST END IN /
tmpFilePrefix = 'recvr-'
targetDir = '/opt/tiles/' # ALSO MUST END IN /
class TCPUploadReceive(SocketServer.StreamRequestHandler):
def handle(self):
tempFile = tmpDir + tmpFilePrefix + uuid.uuid4().hex
done = False
f = open(tempFile, 'w')
http = False
bufferSize = 4096
index = 0
log(tempFile + " opened for writing.")
# str.format was not included until Python 2.6. The % operator in
# earlier versions has a similar function to str.format.
if sys.version_info < (2, 6):
log('Receiving file from %s...' % (self.client_address[0]))
else:
log("Receiving file from {}...".format(self.client_address[0]))
def finishHttp(good):
if good:
self.wfile.write('HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
self.request.close()
else:
self.wfile.write('{ "success": false, "message": "Bad mime type." }')
f.close()
log("Bad mime type detected on HTTP POST. Killing transfer.")
while not done:
if index > 0 and http:
self.wfile.write('HTTP/1.1 100 Continue\r\n\r\n')
bufferData = self.request.recv(bufferSize).strip()
if index == 0 and checkHttp(bufferData):
http = True
index += 1
continue
if bufferData != "":
f.write(bufferData)
if http and len(bufferData) < bufferSize:
finishHttp(True)
break
else:
log('We have hit the done.')
done = True
index += 1
f.close()
unTarFile(tempFile, targetDir)
rmFile(tempFile)
self.wfile.write('{ "success": true }')
log("Finished!\n")
def unTarFile(tarPath, target):
log("Extracting...")
with closing(tarfile.open(tarPath, 'r|*')) as tarball:
tarball.extractall(target)
def rmFile(path):
log("Removing temp file...")
os.unlink(path)
def log(message):
logTime = '%H:%M:%S%%%y-%m-%d - '
sys.stdout.write(time.strftime(logTime))
sys.stdout.write(message)
sys.stdout.write('\n')
sys.stdout.flush()
def checkHttp(bufferData):
headMatch = '^POST.*HTTP.*'
contMatch = "Content-type: application\/(x-gzip|x-tar|x-bz2|x-bzip|x-bzip2)"
if re.search(headMatch, bufferData, re.I) and re.search(contMatch, bufferData, re.I | re.M):
return True
return False
if __name__ == "__main__":
# Some environment fixing, before we begin:
if not os.path.exists(tmpDir):
os.makedirs(tmpDir)
if not os.path.exists(targetDir):
os.makedirs(targetDir)
HOST, PORT = "0.0.0.0", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), TCPUploadReceive)
log("Receiver now listening on port " + str(PORT))
server.serve_forever()