Repository navigation
Expand file tree
/
Copy pathchasha.py
More file actions
554 lines (456 loc) · 18.4 KB
/
Copy pathchasha.py
File metadata and controls
554 lines (456 loc) · 18.4 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import socket
import re
import os
import traceback
text_types = [".txt", ".ps", ".text", ".lst", ".dat",
".py", ".c", ".c++", ".cpp", ".md", ".rst",
".css", ".js", ".java", ".scm", ".ss", ".cfm"]
def cget(obj, idx, default=None):
try:
return obj[idx]
except IndexError:
return default
class GopherError(Exception):
pass
class Information(object):
def __init__(self, body):
self.body = body
def __str__(self):
return self.body
def __bytes__(self):
return bytes(self.body, encoding="utf8")
def to_gemini(self):
# NOTE we actually probably want to apply some sort
# of grouping algorithm to remove newlines or the like
# from `self#body`, but for now just return the same
return self.body
class Search(object):
# XXX I suspect what we actually want is to make
# a decorator that can mark something as a search,
# and then use that to instantiate a Search object.
# this can then return the wrapped call? I may need
# to think about this more
#
# actually, thinking about it more, since we will
# still need to mount a route, we may not care about
# having this as a wrapper, but rather just to help
# the Directory system; it *may not* be needed much
# herein
def __init__(self, prompt):
self.prompt = prompt
class Directory(object):
def __init__(self, descriptor, name=None, children=None, port=7070,
host='127.0.0.1'):
self.descriptor = descriptor
self.port = port
self.host = host
if children is not None:
self.children = children
else:
self.children = []
self.name = name
def add_child(self, child):
self.children.append(child)
#### start refactorable zone
# really, the although the below is at least _somewhat_ clean
# I suspect it could be made cleaner still.
def add_common(self, dtype, description, descriptor, host=None, port=None):
if host is None:
host = self.host
if port is None:
port = self.port
self.add_child([dtype, description, descriptor, host, port])
def add_link(self, description, descriptor, host=None, port=None):
self.add_common('h',
description,
"URL:{0}".format(descriptor),
host,
port)
def add_image(self, description, descriptor, host=None, port=None):
self.add_common('I',
description,
descriptor,
host,
port)
def add_binary(self, description, descriptor, host=None, port=None):
self.add_common('9',
description,
descriptor,
host,
port)
def add_telnet(self, description, descriptor, host=None, port=None):
self.add_common('8',
description,
descriptor,
host,
port)
def add_search(self, description, descriptor, host=None, port=None):
self.add_common('7',
description,
descriptor,
host,
port)
def add_uue(self, description, descriptor, host=None, port=None):
self.add_common('6',
description,
descriptor,
host,
port)
def add_binarchive(self, description, descriptor, host=None, port=None):
self.add_common('5',
description,
descriptor,
host,
port)
def add_binhex(self, description, descriptor, host=None, port=None):
self.add_common('4',
description,
descriptor,
host,
port)
def add_error(self, description, descriptor, host=None, port=None):
self.add_common('3',
description,
descriptor,
host="error.nohost",
port="0")
def add_ccso(self, description, descriptor, host=None, port=None):
self.add_common('2',
description,
descriptor,
host,
port)
def add_directory(self, description, descriptor, host=None, port=None):
self.add_common('1',
description,
descriptor,
host,
port)
def add_text(self, description, descriptor, host=None, port=None):
self.add_common('0',
description,
descriptor,
host,
port)
def add_audio(self, description, descriptor, host=None, port=None):
self.add_common('s',
description,
descriptor,
host,
port)
def add_html(self, description, descriptor, host=None, port=None):
self.add_common('h',
description,
descriptor,
host,
port)
#### end refactorable zone
def listing(self):
tmpl = "1{0}\t{1}\t{2}\t{3}\t+"
return tmpl.format(self.name,
self.descriptor,
self.host,
self.port)
def __str__(self):
res = []
for child in self.children:
if isinstance(child, (list, tuple)):
tmpl = "{0}{1}\t{2}\t{3}\t{4}\t{5}"
if isinstance(child, tuple):
child = list(child)
res.append(tmpl.format(child[0],
child[1],
cget(child, 2, "FAKE"),
cget(child, 3, "NULL"),
cget(child, 4, "0"),
cget(child, 5, "+")))
elif isinstance(child, Directory):
res.append(child.listing())
elif isinstance(child, Information):
res.append(str(child))
elif isinstance(child, Search):
res.append(child.listing())
elif isinstance(child, str):
# should probably handle multiline strings here...
res.append("i{0}\tFAKE\tNULL\t0\t+".format(child))
res.append(".\r\n")
return '\r\n'.join(res)
def __bytes__(self):
res = []
for child in self.children:
if isinstance(child, (list, tuple)):
tmpl = "{0}{1}\t{2}\t{3}\t{4}\t{5}"
if isinstance(child, tuple):
child = list(child)
res.append(tmpl.format(cget(child, 0),
cget(child, 1),
cget(child, 2, "FAKE"),
cget(child, 3, "NULL"),
cget(child, 4, "0"),
cget(child, 5, "+")))
elif isinstance(child, Directory):
res.append(child.listing())
elif isinstance(child, Information):
res.append(str(child))
elif isinstance(child, Search):
res.append(child.listing())
elif isinstance(child, str):
# should probably handle multiline strings here...
res.append("i{0}\tFAKE\tNULL\t0\t+".format(child))
res.append(".\r\n")
return bytes('\r\n'.join(res), "utf-8")
def to_gemini(self):
res = []
for child in self.children:
if isinstance(child, (list, tuple)):
dtype = child[0]
match dtype
case 'i':
res.append(child[1])
case '2':
res.append(f"=> ccso://{child[2]} {child[1]}")
case ['8', 'T']:
res.append(f"=> telnet://{child[2]} {child[1]}")
case 'h':
next_url = child[2].replace("URL:", "")
res.append(f"=> {next_url} {child[1]}")
case _:
# FIXME we can actually do a bit better here by detecting if the
# host for the next URL is actually the same as this server...
next_url = None
if child[4] != 1965:
next_url = f"gemini://{child[3]}:{child[4]}/{child[2]}"
else:
next_url = f"gemini://{child[3]}/{child[2]}"
res.append(f"=> {next_url} {child[1]}")
elif isinstance(child, Directory):
tmpl = f"=> {child.descriptor} {child.name}"
res.append(tmpl)
elif isinstance(child, Information):
res.append(child.to_gemini())
elif isinstance(child, Search):
res.append(child.to_gemini())
elif isinstance(child, str):
res.append(child)
return bytes('\r\n'.join(res), "utf-8")
class Request(object):
def __init__(self, descriptor=None, search=None, body=None, rtype=None):
self.descriptor = descriptor
self.search = search
self.body = body
self.rtype = rtype
class Chasha(object):
def __init__(self):
self.routes = {}
self.dyn_routes = {}
self.dyn_search = {}
self.search_routes = {}
self.typepats = {'int': '[0-9]+',
'float': '[0-9]+\.[0-9]+',
'path': '[A-Za-z0-9/\.\-\s]+',
'alnum': '[A-Za-z0-9]',
'alpha': '[A-Za-z]+'}
# really more for inspection than anything
# else. Probalby *could* use these as the
# defaults down below...
self.debug = False
self.port = 7070
self.host = '0.0.0.0'
self.request = None
def add_route(self, descriptor, callback, cfg):
# XXX I suspect we can clean this up more
# with the Information & Search classes from
# above: we can just have one _route_ table
# and then wrap the callback in whatever
# class from above, and allow the class to
# handle actually calling the callback
#
# this would in someways make the Search handling
# easier
if ':' in descriptor:
desc = self.compile_route(descriptor)
if "search" in cfg:
self.dyn_search[re.compile(desc)] = callback
else:
self.dyn_routes[re.compile(desc)] = callback
elif "search" in cfg:
self.search_routes[descriptor] = callback
else:
self.routes[descriptor] = callback
def route(self, descriptor, **kwargs):
def wrapper(handler):
self.add_route(descriptor, handler, kwargs)
return handler
return wrapper
def default(self):
return self.route("/")
def compile_route(self, descriptor):
parts = descriptor.split('/')
res = []
# could probably do this in a few replace calls,
# but being explicit & breaking things apart seems nicer to me
for part in parts:
if ':' in part:
chasti = part[1:-1].split(':')
if chasti[1] not in self.typepats:
pat = ".*"
else:
pat = self.typepats[chasti[1]]
res.append("(?P<{0}>{1})".format(chasti[0], pat))
else:
res.append(part)
return '/'.join(res)
def router(self, descriptor):
idx = 0
if self.debug:
print("[!] In router;descriptor: {0}".format(descriptor))
if descriptor == "":
return self.routes.get("/")
# NOTE: just for intial testing
# actual processing has to go on here in the real deal...
# TODO: look at processing the routes with subs & regex...
# e.g. foo/bar<blah:int> could become foo/bar<blah:[0-9]+
if descriptor in self.routes:
# do we have a static descriptor that matches?
# if yes, just return it
if self.debug:
print("[!] in self.routes?")
return self.routes[descriptor]
elif descriptor in self.search_routes:
return self.search_routes[descriptor]
else:
if self.debug:
print("[!] in self.dyn_routes?")
descriptors = list(self.dyn_routes.keys())
for desc in descriptors:
mat = desc.match(descriptor)
if mat:
if self.debug:
print("[!] in dyn return?")
return (mat, self.dyn_routes[desc])
if self.debug:
print("[!] in None return")
return None
def run(self, **kwargs):
self.port = kwargs.get('port', 7070)
self.host = kwargs.get('host', '0.0.0.0')
self.server_type = kwargs.get("server_type", "gopher")
if self.server_type not in ["gopher", "gemini", "spartan"]:
self.server_type = "gopher"
self.loop_flag = True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((self.host, self.port))
sock.listen(1)
while self.loop_flag:
try:
if self.debug:
print("[!] waiting for accept...")
conn, addr = sock.accept()
print("[+] client connected from {0}".format(addr), end=' ')
# FIXME we need to actually read more here...
desc = conn.recv(2048)
desc = desc.strip()
# XXX this is also likely needing a review:
desc = desc.decode("utf-8")
print(" and requested: ", desc)
if self.debug:
print("[!] client sent data...")
try:
descparts = desc.split('\t')
self.request = Request(cget(descparts, 0),
cget(descparts, 1))
handler = self.router(descparts[0])
if self.debug:
print("[!] router matched said data...")
print("[!] type of handler: ", type(handler))
if isinstance(handler, tuple):
mat = handler[0]
if self.debug:
print("[!] mat.groupdict:", mat.groupdict())
print("[!] handler: ", handler[1])
handler = handler[1]
data = handler(**mat.groupdict())
else:
data = handler()
if self.debug:
print("[!] handler returned data...")
except GopherError as ge:
data = "3gophererror\t{0}\terror.host\t1\r\n".format(ge.message)
except Exception as e:
print("[!] exception: ", e)
traceback.print_exception(e)
data = "3nosuchdroute\tdoes not exist\terror.host\t1\r\n"
# NOTE: should process return type here...
print("[!] here on 344, data is:", type(data), data)
if type(data) is str:
conn.send(bytes(data, "utf-8"))
else:
conn.send(bytes(data))
conn.close()
except KeyboardInterrupt:
self.loop_flag = False
except Exception as e:
print(e)
traceback.print_exception(e)
# NOTE: Should check if socket accidentally closed here
# and, if so, reopen
pass
sock.close()
def static_dispatch(portion, descriptor, root="."):
"""Handle static requests from a descriptor
in a safe fashion (removing '..', canonicalizing,
&c. Dispatches file reads or directory creation
based on the type of object pointed to. Use
`static_file` if you only want serve files.
"""
portion = portion.replace("../", "")
tpath = os.path.join(root, portion)
if os.path.isfile(tpath):
fh = file(tpath)
data = fh.read()
fh.close()
return data
return static_directory(portion, os.path.join(descriptor, portion), root)
def static_file(portion, descriptor, root="."):
"""Handle static file request from a descriptor
in a safe fashion (removing '..', canonicalizing,
&c. Analogous to Bottle's `static_file`
"""
portion = portion.replace("../", "")
tpath = os.path.join(root, portion)
if os.path.isfile(tpath):
fh = file(tpath)
data = fh.read()
fh.close()
return data
raise GopherError("Descriptor is not a file")
def static_directory(directory, descriptor, root='.', unknowns_as='5'):
"""Create a `Directory` object from a file system
directory; Meant to simplify the process of having
standard directories to load data from, &c.
"""
retd = Directory(directory)
if directory[0] == "/":
directory = directory[1:]
directory = directory.replace("../", "")
rpath = os.path.join(os.path.abspath(root), directory)
items = os.listdir(os.path.join(os.path.abspath(root), directory))
for item in items:
tdesc = os.path.join(descriptor, item)
tpath = os.path.join(rpath, item)
if os.path.isfile(tpath):
tmp = os.path.splitext(item)
if len(tmp) == 0:
retd.add_child([unknowns_as,
tdesc,
item])
elif tmp[1] in text_types:
retd.add_text(item, tdesc)
elif tmp[1] == ".html":
retd.add_html(item, tdesc)
else:
retd.add_binary(item, tdesc)
else:
retd.add_directory(item, tdesc)
return retd
#class ChashaAsync(Chasha, asyncore.dispatcher)