mitmproxy/netlib/wsgi.py

160 lines
5.2 KiB
Python
Raw Normal View History

2014-08-16 13:53:07 +00:00
from __future__ import (absolute_import, print_function, division)
import cStringIO
import urllib
import time
import traceback
2014-08-16 13:53:07 +00:00
from . import odict, tcp
2012-06-18 22:42:25 +00:00
2015-04-09 00:09:33 +00:00
class ClientConn(object):
def __init__(self, address):
self.address = tcp.Address.wrap(address)
2015-04-09 00:09:33 +00:00
class Flow(object):
def __init__(self, address, request):
self.client_conn = ClientConn(address)
self.request = request
2015-04-09 00:09:33 +00:00
class Request(object):
def __init__(self, scheme, method, path, headers, content):
self.scheme, self.method, self.path = scheme, method, path
self.headers, self.content = headers, content
2012-06-18 22:42:25 +00:00
def date_time_string():
"""Return the current date and time formatted for a message header."""
WEEKS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
MONTHS = [
None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
2012-06-18 22:42:25 +00:00
now = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
WEEKS[wd],
day, MONTHS[month], year,
hh, mm, ss
)
2012-06-18 22:42:25 +00:00
return s
2015-04-09 00:09:33 +00:00
class WSGIAdaptor(object):
2012-06-18 22:42:25 +00:00
def __init__(self, app, domain, port, sversion):
self.app, self.domain, self.port, self.sversion = app, domain, port, sversion
def make_environ(self, flow, errsoc, **extra):
if '?' in flow.request.path:
path_info, query = flow.request.path.split('?', 1)
2012-06-18 22:42:25 +00:00
else:
path_info = flow.request.path
2012-06-18 22:42:25 +00:00
query = ''
environ = {
'wsgi.version': (1, 0),
'wsgi.url_scheme': flow.request.scheme,
'wsgi.input': cStringIO.StringIO(flow.request.content),
'wsgi.errors': errsoc,
'wsgi.multithread': True,
'wsgi.multiprocess': False,
'wsgi.run_once': False,
'SERVER_SOFTWARE': self.sversion,
'REQUEST_METHOD': flow.request.method,
'SCRIPT_NAME': '',
'PATH_INFO': urllib.unquote(path_info),
'QUERY_STRING': query,
'CONTENT_TYPE': flow.request.headers.get('Content-Type', [''])[0],
'CONTENT_LENGTH': flow.request.headers.get('Content-Length', [''])[0],
'SERVER_NAME': self.domain,
'SERVER_PORT': str(self.port),
2012-06-18 22:42:25 +00:00
# FIXME: We need to pick up the protocol read from the request.
'SERVER_PROTOCOL': "HTTP/1.1",
2012-06-18 22:42:25 +00:00
}
environ.update(extra)
if flow.client_conn.address:
2015-05-30 00:02:58 +00:00
environ["REMOTE_ADDR"], environ[
"REMOTE_PORT"] = flow.client_conn.address()
2012-06-18 22:42:25 +00:00
for key, value in flow.request.headers.items():
2012-06-18 22:42:25 +00:00
key = 'HTTP_' + key.upper().replace('-', '_')
if key not in ('HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH'):
environ[key] = value
return environ
def error_page(self, soc, headers_sent, s):
"""
Make a best-effort attempt to write an error page. If headers are
already sent, we just bung the error into the page.
"""
c = """
<html>
<h1>Internal Server Error</h1>
<pre>%s"</pre>
</html>
""" % s
2012-06-18 22:42:25 +00:00
if not headers_sent:
soc.write("HTTP/1.1 500 Internal Server Error\r\n")
soc.write("Content-Type: text/html\r\n")
soc.write("Content-Length: %s\r\n" % len(c))
2012-06-18 22:42:25 +00:00
soc.write("\r\n")
soc.write(c)
def serve(self, request, soc, **env):
2012-06-18 22:42:25 +00:00
state = dict(
response_started=False,
headers_sent=False,
status=None,
headers=None
2012-06-18 22:42:25 +00:00
)
2012-06-18 22:42:25 +00:00
def write(data):
if not state["headers_sent"]:
soc.write("HTTP/1.1 %s\r\n" % state["status"])
2012-06-18 22:42:25 +00:00
h = state["headers"]
if 'server' not in h:
h["Server"] = [self.sversion]
2012-06-18 22:42:25 +00:00
if 'date' not in h:
h["Date"] = [date_time_string()]
soc.write(h.format())
2012-06-18 22:42:25 +00:00
soc.write("\r\n")
state["headers_sent"] = True
2012-06-26 02:49:23 +00:00
if data:
soc.write(data)
2012-06-18 22:42:25 +00:00
soc.flush()
def start_response(status, headers, exc_info=None):
if exc_info:
try:
if state["headers_sent"]:
raise exc_info[0], exc_info[1], exc_info[2]
finally:
exc_info = None
elif state["status"]:
raise AssertionError('Response already started')
state["status"] = status
state["headers"] = odict.ODictCaseless(headers)
return write
errs = cStringIO.StringIO()
try:
dataiter = self.app(
self.make_environ(request, errs, **env), start_response
)
2012-06-18 22:42:25 +00:00
for i in dataiter:
write(i)
if not state["headers_sent"]:
write("")
except Exception:
2012-06-18 22:42:25 +00:00
try:
s = traceback.format_exc()
errs.write(s)
2012-06-18 22:42:25 +00:00
self.error_page(soc, state["headers_sent"], s)
except Exception: # pragma: no cover
pass
2012-06-18 22:42:25 +00:00
return errs.getvalue()