2016-12-23 19:20:07 +00:00
|
|
|
#!/usr/bin/env python
|
2017-01-20 12:44:21 +00:00
|
|
|
import os
|
2017-01-26 00:21:49 +00:00
|
|
|
import socket
|
2017-01-26 14:27:08 +00:00
|
|
|
import sys
|
2017-01-20 12:44:21 +00:00
|
|
|
import BaseHTTPServer
|
|
|
|
import SocketServer
|
2017-02-27 21:07:57 +00:00
|
|
|
import ssl
|
|
|
|
import argparse
|
2016-12-23 19:20:07 +00:00
|
|
|
|
2017-02-27 21:07:57 +00:00
|
|
|
parser = argparse.ArgumentParser(description = 'Simple http/https server')
|
|
|
|
parser.add_argument('--https', action='store_true', help = 'Use https')
|
|
|
|
parser.add_argument('--port', type = int, default = 80, help = 'server port')
|
|
|
|
parser.add_argument('--host', default = "localhost", help = 'server host')
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
if args.https and args.port == 80:
|
|
|
|
args.port = 443
|
2016-12-23 19:20:07 +00:00
|
|
|
|
2017-01-20 12:44:21 +00:00
|
|
|
class myHTTPServer(SocketServer.ForkingMixIn, BaseHTTPServer.HTTPServer):
|
2017-01-26 00:21:49 +00:00
|
|
|
address_family = socket.AF_INET6
|
2017-01-20 12:44:21 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
class myHandler(BaseHTTPServer.BaseHTTPRequestHandler):
|
2016-12-23 19:20:07 +00:00
|
|
|
def do_GET(self):
|
|
|
|
if self.path == "/":
|
|
|
|
self.path = "/http_server.py"
|
|
|
|
|
|
|
|
try:
|
2017-01-20 12:44:21 +00:00
|
|
|
f = open(os.curdir + os.sep + self.path)
|
2016-12-23 19:20:07 +00:00
|
|
|
self.send_response(200)
|
|
|
|
self.send_header('Content-type', 'text/plain')
|
|
|
|
self.end_headers()
|
|
|
|
self.wfile.write(f.read())
|
|
|
|
f.close()
|
|
|
|
return
|
|
|
|
|
|
|
|
except IOError:
|
|
|
|
self.send_error(404,'File Not Found: %s' % self.path)
|
|
|
|
|
|
|
|
def do_POST(self):
|
2018-09-14 19:48:51 +00:00
|
|
|
#if self.headers.getheader('Transfer-Encoding') == 'chunked':
|
|
|
|
# todo
|
|
|
|
#else:
|
|
|
|
content_len = int(self.headers.getheader('Content-Length', 0))
|
|
|
|
|
|
|
|
post_body = self.rfile.read(content_len)
|
|
|
|
#print('post:', content_len, post_body)
|
2016-12-23 19:20:07 +00:00
|
|
|
self.do_GET()
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
2017-02-27 21:07:57 +00:00
|
|
|
server = myHTTPServer(('', args.port), myHandler)
|
|
|
|
if args.https:
|
2017-03-07 19:01:37 +00:00
|
|
|
os.system('openssl req -subj "/CN={host}" -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout http_server.key -out http_server.crt'.format(host=args.host))
|
|
|
|
server.socket = ssl.wrap_socket(server.socket, keyfile="http_server.key", certfile='http_server.crt', server_side=True)
|
2017-02-27 21:07:57 +00:00
|
|
|
|
|
|
|
print 'Started http' + ( 's' if args.https else '' ) + ' server on port' , args.port
|
2016-12-23 19:20:07 +00:00
|
|
|
server.serve_forever()
|
|
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
print '^C received, shutting down the web server'
|
|
|
|
server.socket.close()
|