]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/common_http.py
66a6291cb5497e3ec89a60a990a5d2917525d860
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / common_http.py
1
2 import os
3 from cStringIO import StringIO
4 import urlparse, httplib
5 import allmydata # for __full_version__
6
7 from allmydata.util.encodingutil import quote_output
8 from allmydata.scripts.common import TahoeError
9
10
11 # copied from twisted/web/client.py
12 def parse_url(url, defaultPort=None):
13     url = url.strip()
14     parsed = urlparse.urlparse(url)
15     scheme = parsed[0]
16     path = urlparse.urlunparse(('','')+parsed[2:])
17     if defaultPort is None:
18         if scheme == 'https':
19             defaultPort = 443
20         else:
21             defaultPort = 80
22     host, port = parsed[1], defaultPort
23     if ':' in host:
24         host, port = host.split(':')
25         port = int(port)
26     if path == "":
27         path = "/"
28     return scheme, host, port, path
29
30
31 def do_http(method, url, body=""):
32     if isinstance(body, str):
33         body = StringIO(body)
34     elif isinstance(body, unicode):
35         raise TypeError("do_http body must be a bytestring, not unicode")
36     else:
37         # We must give a Content-Length header to twisted.web, otherwise it
38         # seems to get a zero-length file. I suspect that "chunked-encoding"
39         # may fix this.
40         assert body.tell
41         assert body.seek
42         assert body.read
43     scheme, host, port, path = parse_url(url)
44     if scheme == "http":
45         c = httplib.HTTPConnection(host, port)
46     elif scheme == "https":
47         c = httplib.HTTPSConnection(host, port)
48     else:
49         raise ValueError("unknown scheme '%s', need http or https" % scheme)
50     c.putrequest(method, path)
51     c.putheader("Hostname", host)
52     c.putheader("User-Agent", allmydata.__full_version__ + " (tahoe-client)")
53     c.putheader("Accept", "text/plain, application/octet-stream")
54     c.putheader("Connection", "close")
55
56     old = body.tell()
57     body.seek(0, os.SEEK_END)
58     length = body.tell()
59     body.seek(old)
60     c.putheader("Content-Length", str(length))
61     c.endheaders()
62
63     while True:
64         data = body.read(8192)
65         if not data:
66             break
67         c.send(data)
68
69     return c.getresponse()
70
71
72 def format_http_success(resp):
73     return "%s %s" % (resp.status, quote_output(resp.reason, quotemarks=False))
74
75 def format_http_error(msg, resp):
76     return "%s: %s %s\n%s" % (msg, resp.status, quote_output(resp.reason, quotemarks=False),
77                               quote_output(resp.read(), quotemarks=False))
78
79 def check_http_error(resp, stderr):
80     if resp.status < 200 or resp.status >= 300:
81         print >>stderr, format_http_error("Error during HTTP request", resp)
82         return 1
83
84
85 class HTTPError(TahoeError):
86     def __init__(self, msg, resp):
87         TahoeError.__init__(self, format_http_error(msg, resp))