| 43 | |
| 44 | class ReqHandler(_BaseHTTPServer.BaseHTTPRequestHandler): |
| 45 | def do_GET(self): |
| 46 | path, query = self.path.split('?', 1) if '?' in self.path else (self.path, "") |
| 47 | params = {} |
| 48 | content = None |
| 49 | |
| 50 | if query: |
| 51 | params.update(_urllib.parse.parse_qs(query)) |
| 52 | |
| 53 | for key in params: |
| 54 | if params[key]: |
| 55 | params[key] = params[key][-1] |
| 56 | |
| 57 | self.url, self.params = path, params |
| 58 | |
| 59 | if path == '/': |
| 60 | path = "index.html" |
| 61 | |
| 62 | path = path.strip('/') |
| 63 | |
| 64 | path = path.replace('/', os.path.sep) |
| 65 | path = os.path.abspath(os.path.join(HTML_DIR, path)).strip() |
| 66 | |
| 67 | if not os.path.isfile(path) and os.path.isfile("%s.html" % path): |
| 68 | path = "%s.html" % path |
| 69 | |
| 70 | if ".." not in os.path.relpath(path, HTML_DIR) and os.path.isfile(path) and not path.endswith(DISABLED_CONTENT_EXTENSIONS): |
| 71 | content = open(path, "rb").read() |
| 72 | self.send_response(_http_client.OK) |
| 73 | self.send_header(HTTP_HEADER.CONNECTION, "close") |
| 74 | self.send_header(HTTP_HEADER.CONTENT_TYPE, mimetypes.guess_type(path)[0] or "application/octet-stream") |
| 75 | else: |
| 76 | content = ("<!DOCTYPE html><html lang=\"en\"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL %s was not found on this server.</p></body></html>" % self.path.split('?')[0]).encode(UNICODE_ENCODING) |
| 77 | self.send_response(_http_client.NOT_FOUND) |
| 78 | self.send_header(HTTP_HEADER.CONNECTION, "close") |
| 79 | |
| 80 | if content is not None: |
| 81 | for match in re.finditer(b"<!(\\w+)!>", content): |
| 82 | name = match.group(1) |
| 83 | _ = getattr(self, "_%s" % name.lower(), None) |
| 84 | if _: |
| 85 | content = self._format(content, **{name: _()}) |
| 86 | |
| 87 | if "gzip" in self.headers.get(HTTP_HEADER.ACCEPT_ENCODING): |
| 88 | self.send_header(HTTP_HEADER.CONTENT_ENCODING, "gzip") |
| 89 | _ = six.BytesIO() |
| 90 | compress = gzip.GzipFile("", "w+b", 9, _) |
| 91 | compress._stream = _ |
| 92 | compress.write(content) |
| 93 | compress.flush() |
| 94 | compress.close() |
| 95 | content = compress._stream.getvalue() |
| 96 | |
| 97 | self.send_header(HTTP_HEADER.CONTENT_LENGTH, str(len(content))) |
| 98 | |
| 99 | self.end_headers() |
| 100 | |
| 101 | if content: |
| 102 | self.wfile.write(content) |