]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/common_http.py
7b965525deced23e202d361180943818e6ea78a6
[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 from socket import error as socket_error
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 class BadResponse(object):
31     def __init__(self, url, err):
32         self.status = -1
33         self.reason = "Error trying to connect to %s: %s" % (url, err)
34     def read(self):
35         return ""
36
37
38 def do_http(method, url, body=""):
39     if isinstance(body, str):
40         body = StringIO(body)
41     elif isinstance(body, unicode):
42         raise TypeError("do_http body must be a bytestring, not unicode")
43     else:
44         # We must give a Content-Length header to twisted.web, otherwise it
45         # seems to get a zero-length file. I suspect that "chunked-encoding"
46         # may fix this.
47         assert body.tell
48         assert body.seek
49         assert body.read
50     scheme, host, port, path = parse_url(url)
51     if scheme == "http":
52         c = httplib.HTTPConnection(host, port)
53     elif scheme == "https":
54         c = httplib.HTTPSConnection(host, port)
55     else:
56         raise ValueError("unknown scheme '%s', need http or https" % scheme)
57     c.putrequest(method, path)
58     c.putheader("Hostname", host)
59     c.putheader("User-Agent", allmydata.__full_version__ + " (tahoe-client)")
60     c.putheader("Accept", "text/plain, application/octet-stream")
61     c.putheader("Connection", "close")
62
63     old = body.tell()
64     body.seek(0, os.SEEK_END)
65     length = body.tell()
66     body.seek(old)
67     c.putheader("Content-Length", str(length))
68
69     try:
70         c.endheaders()
71     except socket_error, err:
72         return BadResponse(url, err)
73
74     while True:
75         data = body.read(8192)
76         if not data:
77             break
78         c.send(data)
79
80     return c.getresponse()
81
82
83 def format_http_success(resp):
84     return "%s %s" % (resp.status, quote_output(resp.reason, quotemarks=False))
85
86 def format_http_error(msg, resp):
87     return "%s: %s %s\n%s" % (msg, resp.status, quote_output(resp.reason, quotemarks=False),
88                               quote_output(resp.read(), quotemarks=False))
89
90 def check_http_error(resp, stderr):
91     if resp.status < 200 or resp.status >= 300:
92         print >>stderr, format_http_error("Error during HTTP request", resp)
93         return 1
94
95
96 class HTTPError(TahoeError):
97     def __init__(self, msg, resp):
98         TahoeError.__init__(self, format_http_error(msg, resp))