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
#!/usr/bin/python3
import os
import html
from subprocess import * 
import urllib.parse
from pygments import highlight
from pygments.lexers import guess_lexer_for_filename, guess_lexer
from pygments.formatters import HtmlFormatter
from pygments.styles import get_style_by_name

path = urllib.parse.unquote(os.getenv("QUERY_STRING")).split()
if len(path) != 0:
    path = path[0]
else:
    print("HTTP/1.1 307 Temporary Redirect\r\nLocation: ?/pub/hammy/http\r\n")
    exit()

full_path = os.path.realpath(path)

if not full_path.startswith("/pub"):
    print("HTTP/1.1 307 Temporary Redirect\r\nLocation: ?/pub\r\n")
    exit()

if os.path.isfile(full_path):
    print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n")
    f = open(full_path, "r")
    contents = f.read()
    formatter = HtmlFormatter(style='lovelace',full=True, wrapcode=True,linenos="table")
    if full_path.find(".") > -1:
        print(highlight(contents, guess_lexer_for_filename(full_path, contents), formatter))
    else:
        print(highlight(contents, guess_lexer(contents), formatter))
    f.close()
elif os.path.isdir(full_path):
    print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n")
    print('''
        <style>

        body {
            font-family: monospace;
            max-width: 500px;
            margin: auto;
            margin-bottom: 40px;
            margin-top: 20px;
            padding-left: 10px;
            padding-right: 10px;
        }
        </style>
        <meta name="viewport" content="width=device-width, initial-scale=1">

    ''')
    files = sorted(os.listdir(full_path))
    print(f'<h1>showing folder {html.escape(path)}</h1>')
    if path != "/pub":
        backup = '/'.join(path.split('/')[:-1])
        print(f'<a href="?{html.escape(backup)}">..</a><br>')
    for file in files:
        if not file.startswith("."):
            print(f'<a href="?{html.escape(path)}/{html.escape(file)}">{html.escape(full_path+"/"+file)}</a><br>')
else:
    print("HTTP/1.1 404 BAD\r\nContent-Type: text/plain\r\n")
    print("404: File not found")