mitmproxy/libpathod/pathoc.py

95 lines
3.3 KiB
Python
Raw Normal View History

import sys, os
from netlib import tcp, http
import netlib.utils
2012-10-04 21:30:32 +00:00
import language, utils
class PathocError(Exception): pass
class Pathoc(tcp.TCPClient):
def __init__(self, host, port):
tcp.TCPClient.__init__(self, host, port)
self.settings = dict(
staticdir = os.getcwd(),
unconstrained_file_access = True,
)
def request(self, spec):
"""
Return an (httpversion, code, msg, headers, content) tuple.
2012-10-04 21:30:32 +00:00
May raise language.ParseException, netlib.http.HttpError or
language.FileAccessDenied.
"""
2012-10-04 21:30:32 +00:00
r = language.parse_request(self.settings, spec)
ret = r.serve(self.settings, self.wfile, None, self.host)
self.wfile.flush()
return http.read_response(self.rfile, r.method, None)
def _show_summary(self, fp, httpversion, code, msg, headers, content):
print >> fp, "<< %s %s: %s bytes"%(code, utils.xrepr(msg), len(content))
def _show(self, fp, header, data, hexdump):
if hexdump:
print >> fp, "%s (hex dump):"%header
for line in netlib.utils.hexdump(data):
print >> fp, "\t%s %s %s"%line
else:
print >> fp, "%s (unprintables escaped):"%header
print >> fp, netlib.utils.cleanBin(data)
def print_request(self, spec, showreq, showresp, explain, hexdump, ignorecodes, ignoretimeout, fp=sys.stdout):
"""
Performs a series of requests, and prints results to the specified
file descriptor.
spec: A request specification
showreq: Print requests
showresp: Print responses
explain: Print request explanation
hexdump: When printing requests or responses, use hex dump output
ignorecodes: Sequence of return codes to ignore
Returns True if we have a non-ignored response.
"""
try:
2012-10-04 21:30:32 +00:00
r = language.parse_request(self.settings, spec)
except language.ParseException, v:
print >> fp, "Error parsing request spec: %s"%v.msg
print >> fp, v.marked()
return
2012-10-04 21:30:32 +00:00
except language.FileAccessDenied, v:
print >> fp, "File access error: %s"%v
return
resp, req = None, None
if showreq:
self.wfile.start_log()
2012-10-04 21:30:32 +00:00
if showresp:
self.rfile.start_log()
try:
req = r.serve(self.settings, self.wfile, None, self.host)
self.wfile.flush()
resp = http.read_response(self.rfile, r.method, None)
except http.HttpError, v:
print >> fp, "<< HTTP Error:", v.msg
except tcp.NetLibTimeout:
if ignoretimeout:
return
print >> fp, "<<", "Timeout"
except tcp.NetLibDisconnect: # pragma: nocover
print >> fp, "<<", "Disconnect"
if req:
if ignorecodes and resp and resp[1] in ignorecodes:
return
if showreq:
self._show(fp, ">> Request", self.wfile.get_log(), hexdump)
if showresp:
self._show(fp, "<< Response", self.rfile.get_log(), hexdump)
else:
if resp:
self._show_summary(fp, *resp)
return True