-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabct-web
More file actions
executable file
·78 lines (70 loc) · 2.72 KB
/
abct-web
File metadata and controls
executable file
·78 lines (70 loc) · 2.72 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
#!/usr/bin/env python3
from abct.abct import pn, dn
from abct.output import bct, bin_to_bb2, abct_out, has_out
from http.server import SimpleHTTPRequestHandler
import json
import os
import re
import socketserver
import sys
PORT = int(os.environ.get('PORT') or sys.argv[1])
WELCOME = {'description': 'Welcome to Arithmetic Bitwise Cyclic Tag over HTTP webservice. Expect redirects. Inspect cookies.'}
class ABCTserver(SimpleHTTPRequestHandler):
def _set_headers(self):
self.send_header('Content-type', 'application/json;charset=utf-8')
self.end_headers()
def do_HEAD(self):
self.send_response(200)
self._set_headers()
def do_GET(self):
PATH_RE = re.compile(r'/(b/)?(\d+)/(b/)?(\d+)')
output = None
c = {}
if self.path.endswith('.ico'):
self.favicon()
try:
p_bin, p, d_bin, d = PATH_RE.match(self.path).groups()
if p_bin or d_bin:
r = 303
# path/data contains a BCT binary portion, convert and redirect
p = bin_to_bb2(p) if p_bin else p
d = bin_to_bb2(d) if d_bin else d
self.send_response(r)
self.send_header('Location', '/%s/%s/' % (p, d))
else:
p = int(p)
d = int(d)
c = {'program': bct(p), 'data': bct(d)}
output = abct_out(d) if has_out(p, d) else None
r = 200
if d > 0:
d = dn(p, d)
r = 303
self.send_response(r)
self.send_header('Location', '/%d/%d/' % (pn(p), d))
if output:
print('OUTPUT: %s' % output.decode())
c['output'] = output.decode('utf8')
self.send_header('Set-Cookie', 'output=%s' % output.decode('unicode-escape'))
except Exception as e:
if self.path == '/':
c = WELCOME
r = 200
else:
self.log_error('%s: %s', self.path, e)
r = 400
c = {'error': 'expecting URL path /<program (int)>/<data (int)>'}
if r != 303:
self.send_response(r)
self._set_headers()
self.wfile.write(json.dumps(c, ensure_ascii=False).encode('utf8'))
def favicon(self):
with open('public/favicon.png', 'rb') as f:
self.send_response(200)
self.send_header('Content-type', 'image/png')
self.end_headers()
self.wfile.write(f.read())
return
with socketserver.TCPServer(('', PORT), ABCTserver) as httpd:
print('Arithmetic Bitwise Cyclic Tag Server listening on port', PORT)
httpd.serve_forever()