2 from cStringIO import StringIO
3 import urlparse, httplib
4 import allmydata # for __full_version__
6 from allmydata.util.stringutils import quote_output
7 from allmydata.scripts.common import TahoeError
10 # copied from twisted/web/client.py
11 def parse_url(url, defaultPort=None):
13 parsed = urlparse.urlparse(url)
15 path = urlparse.urlunparse(('','')+parsed[2:])
16 if defaultPort is None:
21 host, port = parsed[1], defaultPort
23 host, port = host.split(':')
27 return scheme, host, port, path
30 def do_http(method, url, body=""):
31 if isinstance(body, str):
33 elif isinstance(body, unicode):
34 raise TypeError("do_http body must be a bytestring, not unicode")
36 # We must give a Content-Length header to twisted.web, otherwise it
37 # seems to get a zero-length file. I suspect that "chunked-encoding"
42 scheme, host, port, path = parse_url(url)
44 c = httplib.HTTPConnection(host, port)
45 elif scheme == "https":
46 c = httplib.HTTPSConnection(host, port)
48 raise ValueError("unknown scheme '%s', need http or https" % scheme)
49 c.putrequest(method, path)
50 c.putheader("Hostname", host)
51 c.putheader("User-Agent", allmydata.__full_version__ + " (tahoe-client)")
52 c.putheader("Accept", "text/plain, application/octet-stream")
53 c.putheader("Connection", "close")
59 c.putheader("Content-Length", str(length))
63 data = body.read(8192)
68 return c.getresponse()
71 def format_http_success(resp):
72 return "%s %s" % (resp.status, quote_output(resp.reason, quotemarks=False))
74 def format_http_error(msg, resp):
75 return "%s: %s %s\n%s" % (msg, resp.status, quote_output(resp.reason, quotemarks=False),
76 quote_output(resp.read(), quotemarks=False))
78 def check_http_error(resp, stderr):
79 if resp.status < 200 or resp.status >= 300:
80 print >>stderr, format_http_error("Error during HTTP request", resp)
84 class HTTPError(TahoeError):
85 def __init__(self, msg, resp):
86 TahoeError.__init__(format_http_error(msg, resp))