-
Notifications
You must be signed in to change notification settings - Fork 3
/
redirector
executable file
·74 lines (56 loc) · 2.26 KB
/
redirector
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
#!/usr/bin/python3
import argparse
import http.server
import socketserver
import sys
class RedirectHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
host = self.headers.get('Host')
if not host:
self.send_response_only(400)
else:
host = host.split(':', 1)[0]
scheme = self.server.redirect_target_scheme
port = self.server.redirect_target_port
self.send_response_only(301)
self.send_header('Location', "%s://%s%s" % (scheme, host, port))
self.send_header('Date', self.date_time_string())
self.end_headers()
def do_GET(self):
self.do_HEAD()
def log_message(self, format, *args):
return
class Server(socketserver.TCPServer):
allow_reuse_address = True
redirect_target_scheme = 'https'
redirect_target_port = ''
def setup(self, https=True, target=8443):
self.redirect_target_scheme = https and 'https' or 'http'
if (https and target != 443) or (not https and target != 80):
self.redirect_target_port = ":%s" % target
def main(port=8000, bind="", https=True, target=8443):
"""Main runner."""
server_address = (bind, port)
httpd = Server(server_address, RedirectHandler)
httpd.setup(https=https, target=target)
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--http', action='store_true',
help='Redirect to http [default: https]')
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--port', action='store',
default=8000, type=int,
help='Specify alternate bind port [default: 8000]')
parser.add_argument('target', action='store',
default=8443, type=int, metavar='TARGET_PORT',
help='Redirect target port [default: 8443]')
args = parser.parse_args()
main(port=args.port, bind=args.bind, https=not args.http,
target=args.target)