-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCmdHttpServer.py
More file actions
executable file
·440 lines (318 loc) · 8.68 KB
/
Copy pathCmdHttpServer.py
File metadata and controls
executable file
·440 lines (318 loc) · 8.68 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
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/usr/bin/env python
import os
import json
import mimetypes
import traceback
import urllib
import StringIO
import gzip
import socket
from threading import Thread
from urlparse import urlparse, parse_qs
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
#-------------------------------------------------------------------
# CmdHttpServerReq
class CmdHttpServerReq(BaseHTTPRequestHandler):
# Request handlers
handlers = {}
# Log file handle
logFile = 0
# Size of last response
sizeResponse = 0
# Number of requests handled
requests = 0
# Context
ctx = {}
# Set to non-zero to enable debug mode
DEBUG = 1
# Stack trace in response
STACK = 0
# Process multiple commands in order, must be numbered from 0, 1, 2, ...
ORDERED = 1
# Non-zero to enable compression
COMPRESS = 0
# Log requests
def log_message(self, format, *args):
if self.logFile:
self.logFile.write( "%s - - [%s] \"%s\" %s %i\n" %
(self.client_address[0],
self.log_date_time_string(),
args[0],
args[1],
self.sizeResponse))
# gzip encode string
def gzip_encode(self, content):
out = StringIO.StringIO()
f = gzip.GzipFile(fileobj=out, mode='w', compresslevel=5)
f.write(content)
f.close()
return out.getvalue()
# Send error to client
def _send_error(self, code, error, ext={}):
self._send_response(code, "html", "<html><body><h1>%i - %s</h1></body></html>" % (code, error), ext)
# Send response to client
def _send_response(self, code, type, data, ext={}):
# Send headers
self._set_headers(code, type, len(data), ext, data)
# Set headers
def _set_headers(self, code, type, sz, ext={}, data=0):
self.sizeResponse = sz
# Set response code
self.send_response(code)
# Set content type if user didn't specify
if 'Content-Type' not in ext and type:
# Get mime type
mime = {
'json': 'application/json'
}.get(type, mimetypes.MimeTypes().guess_type(type)[0])
# Default mime type
if not mime:
mime = 'application/octet'
# Set content type
self.send_header('Content-Type', mime + ';charset=UTF-8')
# Set extra headers
if len(ext):
for k,v in ext.iteritems():
self.send_header(k, v)
#self.send_header('Location', loc)
#self.send_header('Content-Location', loc)
# Are we compressing the data?
if self.COMPRESS and data:
if 'gzip' in self.headers['accept-encoding']:
self.send_header('Content-Encoding', 'gzip')
data = self.gzip_encode(data)
sz = len(data)
# Set content length
self.send_header('Content-Length', sz)
# Send the headers
self.end_headers()
# Do we have data to write?
if data and len(data):
self.wfile.write(data)
# Send json data to client
def sendJSON(self, code, j, ext={}):
try:
self._send_response(code, "json", json.dumps(j), ext)
except:
ts = ''
if self.STACK:
ts = "\r\n\r\n" + traceback.format_exc()
self._send_error(500, "Response encoding error" + ts)
if self.DEBUG:
raise
return
# Process commands
def processCmd(self, ch, path, qp, pd, ext={}):
# Is there post data?
if pd:
pl = int(self.headers['Content-Length'])
pd = self.rfile.read(pl)
#-----------------------------------------------------------
# Single command?
if 1 < len(path):
if path[1] not in ch:
return self.sendJSON(200, {"error": "Unsupported"}, ext)
try:
ret = ch[path[1]](self, path, qp, pd)
except:
ts = ''
if self.STACK:
ts = traceback.format_exc()
self.sendJSON(500, {"error": "Server error handling response", "tb": ts}, ext)
if self.DEBUG:
raise
return
self.sendJSON(200, ret, ext)
return
#-----------------------------------------------------------
# Multiple commands
if 'cmds' not in qp or not isinstance(qp['cmds'], dict):
return self.sendJSON(200, {"error": "Bad command format, 'cmds' field is missing"}, ext)
# Process each command
rep = {}
if self.ORDERED:
i = 0
while str(i) in qp['cmds']:
k = str(i)
v = qp['cmds'][k]
i += 1
if 'c' not in v:
rep[k] = {"error": "Ordered command missing"}
elif v['c'] not in ch:
rep[k] = {"error": "Unsupported"}
else:
# Parameters
p = v
if '_' in v:
p = v['_']
# Call the handler
try:
rep[k] = ch[v['c']](self, path, p, pd)
except:
ts = ''
if self.STACK:
ts = traceback.format_exc()
rep[k] = {"error": "Server error handling response", "tb": ts}
if self.DEBUG:
raise
else:
for k,v in qp['cmds'].iteritems():
if 'c' not in v:
rep[k] = {"error": "Unordered command missing"}
elif v['c'] not in ch:
rep[k] = {"error": "Unsupported"}
else:
# Parameters
p = v
if '_' in v:
p = v['_']
# Call the handler
try:
rep[k] = ch[v['c']](self, path, p, pd)
except:
ts = ''
if self.STACK:
ts = traceback.format_exc()
rep[k] = {"error": "Server error handling response", "tb": ts}
if self.DEBUG:
raise
# Send combined responses
self.sendJSON(200, rep, ext)
def sendFile(self, h, path, qp, ext={}):
if 'path' not in h:
# Redirect?
if 'default' in h:
ext['Location'] = h['default']
return self._set_headers(301, 0, 0, ext)
return self._send_error(404, "File not found", ext)
# Verify root path exists
root = h['path']
if not os.path.exists(root):
return self._send_error(404, "File not found", ext)
# Build the name to the file
fname = os.sep.join(path[1:])
floc = ''
# Default redirect?
if not len(fname):
# Was a default name specified?
if 'default' not in h:
return self._send_error(404, "File not found", ext)
# We will attempt a redirect
fname = h['default']
floc = "/".join([path[0], fname])
# Don't allow user to move up
if 0 <= fname.find('..'):
return self._send_error(404, "File not found", ext)
# Full path to the file
fpath = os.path.join(root, fname)
# Attempt to open file
try:
fh = open(fpath, "rb")
except:
fh = 0
# Punt if we didn't get a file
if not fh:
return self._send_error(404, "File not found", ext)
# File length
flen = os.path.getsize(fpath)
# Redirect to default?
if len(floc):
ext['Location'] = floc
return self._set_headers(301, fpath, flen, ext)
# Download only
if 'download' in h and h['download']:
ext['Content-Disposition'] = "attachment; filename=%s" % fname
# Send headers
self._set_headers(200, fpath, flen, ext)
# Send file data
while True:
part = fh.read(64 * 1024)
if not part:
break
self.wfile.write(part)
fh.close()
def runHandler(self, h, path, qp, pd):
ext = {}
# Extra headers?
if 'h' in h and len(h['h']):
ext = h['h']
# Command handler?
if 'c' in h:
self.processCmd(h['c'], path, qp, pd, ext)
return
# File path?
if 'f' in h:
self.sendFile(h['f'], path, qp, ext)
return
return self.sendJSON(400, {"error": "Invalid handler"}, ext)
def processRequest(self, pd):
# Count a request
self.requests += 1
# Parse get variables
url = urlparse(self.path)
query = url.query
qp = parse_qs(query)
# De-array list,
for k,v in qp.iteritems():
if isinstance(v, list) and 1 == len(v):
qp[k] = v[0]
# Decode json
for k,v in qp.iteritems():
if isinstance(v, str):
try:
j = json.loads(v)
qp[k] = j
except:
pass
# Split path
path = url.path.split('/')
# Skip if nothing in the first position and second yields a handler
if not path[0] and 1 < len(path) and path[1] in self.handlers:
path = path[1:]
# Is there a handler?
if path[0] not in self.handlers:
return self._send_error(400, "Bad Request")
# Get handler
h = self.handlers[path[0]]
# Run the handler
return self.runHandler(h, path, qp, pd)
def do_GET(self):
self.processRequest(0)
def do_HEAD(self):
self._set_headers(200, "html", 0)
def do_POST(self):
self.processRequest(1)
#-------------------------------------------------------------------
# CmdHttpServer
class CmdHttpServer():
# Save params
port = 7788
# Request handler
req = CmdHttpServerReq
# HTTP Server
httpServer = 0
# HTTP Server thread
httpThread = 0
# Constructor
def __init__(self, port, ctx={}):
self.port = port
if (len(ctx)):
self.req.ctx = ctx
# Server main thread function
def serverThread(self):
self.httpServer = HTTPServer(('', self.port), self.req)
try:
self.httpServer.serve_forever()
except socket.error:
pass
# Start server thread
def start(self):
self.httpThread = Thread(target=self.serverThread)
self.httpThread.start()
# Stop server thread
def stop(self):
if self.httpServer:
self.httpServer.socket.close()
if self.httpThread:
self.httpThread.join()