1 # Written by John Hoffman
2 # see LICENSE.txt for license information
5 from httplib import HTTPConnection, HTTPSConnection, HTTPException
6 from urlparse import urlparse
7 from bencode import bdecode
8 from gzip import GzipFile
9 from StringIO import StringIO
10 from __init__ import product_name, version_short
11 from traceback import print_exc,print_stack
13 from BaseLib.Core.Utilities.timeouturlopen import find_proxy
15 VERSION = product_name+'/'+version_short
19 class btHTTPcon(HTTPConnection): # attempt to add automatic connection timeout
21 HTTPConnection.connect(self)
23 self.sock.settimeout(30)
27 class btHTTPScon(HTTPSConnection): # attempt to add automatic connection timeout
29 HTTPSConnection.connect(self)
31 self.sock.settimeout(30)
36 def __init__(self, url):
38 self._open(url.strip())
39 self.error_return = None
44 if self.tries > MAX_REDIRECTS:
45 raise IOError, ('http error', 500,
46 "Internal Server Error: Redirect Recursion")
47 (scheme, netloc, path, pars, query, fragment) = urlparse(url)
48 if scheme != 'http' and scheme != 'https':
49 raise IOError, ('url error', 'unknown url type', scheme, url)
57 proxyhost = find_proxy(url)
63 desturl = scheme+'://'+netloc+wanturl
67 self.connection = btHTTPcon(desthost)
69 self.connection = btHTTPScon(desthost)
70 self.connection.request('GET', desturl, None,
71 { 'Host': netloc, 'User-Agent': VERSION,
72 'Accept-Encoding': 'gzip' } )
73 self.response = self.connection.getresponse()
74 except HTTPException, e:
76 raise IOError, ('http error', str(e))
77 status = self.response.status
78 if status in (301, 302):
80 self.connection.close()
83 self._open(self.response.getheader('Location'))
89 if d.has_key('failure reason'):
90 self.error_return = data
94 raise IOError, ('http error', status, self.response.reason)
100 if self.error_return:
101 return self.error_return
105 data = self.response.read()
106 if self.response.getheader('Content-Encoding', '').find('gzip') >= 0:
108 compressed = StringIO(data)
109 f = GzipFile(fileobj = compressed)
112 raise IOError, ('http error', 'got corrupt response')
116 self.connection.close()
122 def __init__(self,url):
124 print >>sys.stderr,"CURL",url
127 self.c = pycurl.Curl()
128 self.c.setopt(c.URL, url)
129 self.c.setopt(c.WRITEFUNCTION, t.body_callback)
133 def body_callback(self, buf):
134 self.contents = self.contents + buf