##// END OF EJS Templates
Work around a urllib2 bug in Python < 2.4.2...
Alexis S. L. Carvalho -
r4226:fffacca4 default
parent child Browse files
Show More
@@ -1,394 +1,402
1 1 # httprepo.py - HTTP repository proxy classes for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 5 #
6 6 # This software may be used and distributed according to the terms
7 7 # of the GNU General Public License, incorporated herein by reference.
8 8
9 9 from node import *
10 10 from remoterepo import *
11 11 from i18n import gettext as _
12 12 from demandload import *
13 13 demandload(globals(), "hg os urllib urllib2 urlparse zlib util httplib")
14 14 demandload(globals(), "errno keepalive tempfile socket changegroup")
15 15
16 16 class passwordmgr(urllib2.HTTPPasswordMgrWithDefaultRealm):
17 17 def __init__(self, ui):
18 18 urllib2.HTTPPasswordMgrWithDefaultRealm.__init__(self)
19 19 self.ui = ui
20 20
21 21 def find_user_password(self, realm, authuri):
22 22 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(
23 23 self, realm, authuri)
24 24 user, passwd = authinfo
25 25 if user and passwd:
26 26 return (user, passwd)
27 27
28 28 if not self.ui.interactive:
29 29 raise util.Abort(_('http authorization required'))
30 30
31 31 self.ui.write(_("http authorization required\n"))
32 32 self.ui.status(_("realm: %s\n") % realm)
33 33 if user:
34 34 self.ui.status(_("user: %s\n") % user)
35 35 else:
36 36 user = self.ui.prompt(_("user:"), default=None)
37 37
38 38 if not passwd:
39 39 passwd = self.ui.getpass()
40 40
41 41 self.add_password(realm, authuri, user, passwd)
42 42 return (user, passwd)
43 43
44 44 def netlocsplit(netloc):
45 45 '''split [user[:passwd]@]host[:port] into 4-tuple.'''
46 46
47 47 a = netloc.find('@')
48 48 if a == -1:
49 49 user, passwd = None, None
50 50 else:
51 51 userpass, netloc = netloc[:a], netloc[a+1:]
52 52 c = userpass.find(':')
53 53 if c == -1:
54 54 user, passwd = urllib.unquote(userpass), None
55 55 else:
56 56 user = urllib.unquote(userpass[:c])
57 57 passwd = urllib.unquote(userpass[c+1:])
58 58 c = netloc.find(':')
59 59 if c == -1:
60 60 host, port = netloc, None
61 61 else:
62 62 host, port = netloc[:c], netloc[c+1:]
63 63 return host, port, user, passwd
64 64
65 65 def netlocunsplit(host, port, user=None, passwd=None):
66 66 '''turn host, port, user, passwd into [user[:passwd]@]host[:port].'''
67 67 if port:
68 68 hostport = host + ':' + port
69 69 else:
70 70 hostport = host
71 71 if user:
72 72 if passwd:
73 73 userpass = urllib.quote(user) + ':' + urllib.quote(passwd)
74 74 else:
75 75 userpass = urllib.quote(user)
76 76 return userpass + '@' + hostport
77 77 return hostport
78 78
79 # work around a bug in Python < 2.4.2
80 # (it leaves a "\n" at the end of Proxy-authorization headers)
81 class request(urllib2.Request):
82 def add_header(self, key, val):
83 if key.lower() == 'proxy-authorization':
84 val = val.strip()
85 return urllib2.Request.add_header(self, key, val)
86
79 87 class httpsendfile(file):
80 88 def __len__(self):
81 89 return os.fstat(self.fileno()).st_size
82 90
83 91 def _gen_sendfile(connection):
84 92 def _sendfile(self, data):
85 93 # send a file
86 94 if isinstance(data, httpsendfile):
87 95 # if auth required, some data sent twice, so rewind here
88 96 data.seek(0)
89 97 for chunk in util.filechunkiter(data):
90 98 connection.send(self, chunk)
91 99 else:
92 100 connection.send(self, data)
93 101 return _sendfile
94 102
95 103 class httpconnection(keepalive.HTTPConnection):
96 104 # must be able to send big bundle as stream.
97 105 send = _gen_sendfile(keepalive.HTTPConnection)
98 106
99 107 class basehttphandler(keepalive.HTTPHandler):
100 108 def http_open(self, req):
101 109 return self.do_open(httpconnection, req)
102 110
103 111 has_https = hasattr(urllib2, 'HTTPSHandler')
104 112 if has_https:
105 113 class httpsconnection(httplib.HTTPSConnection):
106 114 response_class = keepalive.HTTPResponse
107 115 # must be able to send big bundle as stream.
108 116 send = _gen_sendfile(httplib.HTTPSConnection)
109 117
110 118 class httphandler(basehttphandler, urllib2.HTTPSHandler):
111 119 def https_open(self, req):
112 120 return self.do_open(httpsconnection, req)
113 121 else:
114 122 class httphandler(basehttphandler):
115 123 pass
116 124
117 125 def zgenerator(f):
118 126 zd = zlib.decompressobj()
119 127 try:
120 128 for chunk in util.filechunkiter(f):
121 129 yield zd.decompress(chunk)
122 130 except httplib.HTTPException, inst:
123 131 raise IOError(None, _('connection ended unexpectedly'))
124 132 yield zd.flush()
125 133
126 134 class httprepository(remoterepository):
127 135 def __init__(self, ui, path):
128 136 self.path = path
129 137 self.caps = None
130 138 self.handler = None
131 139 scheme, netloc, urlpath, query, frag = urlparse.urlsplit(path)
132 140 if query or frag:
133 141 raise util.Abort(_('unsupported URL component: "%s"') %
134 142 (query or frag))
135 143 if not urlpath: urlpath = '/'
136 144 host, port, user, passwd = netlocsplit(netloc)
137 145
138 146 # urllib cannot handle URLs with embedded user or passwd
139 147 self._url = urlparse.urlunsplit((scheme, netlocunsplit(host, port),
140 148 urlpath, '', ''))
141 149 self.ui = ui
142 150
143 151 proxyurl = ui.config("http_proxy", "host") or os.getenv('http_proxy')
144 152 # XXX proxyauthinfo = None
145 153 self.handler = httphandler()
146 154 handlers = [self.handler]
147 155
148 156 if proxyurl:
149 157 # proxy can be proper url or host[:port]
150 158 if not (proxyurl.startswith('http:') or
151 159 proxyurl.startswith('https:')):
152 160 proxyurl = 'http://' + proxyurl + '/'
153 161 snpqf = urlparse.urlsplit(proxyurl)
154 162 proxyscheme, proxynetloc, proxypath, proxyquery, proxyfrag = snpqf
155 163 hpup = netlocsplit(proxynetloc)
156 164
157 165 proxyhost, proxyport, proxyuser, proxypasswd = hpup
158 166 if not proxyuser:
159 167 proxyuser = ui.config("http_proxy", "user")
160 168 proxypasswd = ui.config("http_proxy", "passwd")
161 169
162 170 # see if we should use a proxy for this url
163 171 no_list = [ "localhost", "127.0.0.1" ]
164 172 no_list.extend([p.lower() for
165 173 p in ui.configlist("http_proxy", "no")])
166 174 no_list.extend([p.strip().lower() for
167 175 p in os.getenv("no_proxy", '').split(',')
168 176 if p.strip()])
169 177 # "http_proxy.always" config is for running tests on localhost
170 178 if (not ui.configbool("http_proxy", "always") and
171 179 host.lower() in no_list):
172 180 ui.debug(_('disabling proxy for %s\n') % host)
173 181 else:
174 182 proxyurl = urlparse.urlunsplit((
175 183 proxyscheme, netlocunsplit(proxyhost, proxyport,
176 184 proxyuser, proxypasswd or ''),
177 185 proxypath, proxyquery, proxyfrag))
178 186 handlers.append(urllib2.ProxyHandler({scheme: proxyurl}))
179 187 ui.debug(_('proxying through http://%s:%s\n') %
180 188 (proxyhost, proxyport))
181 189
182 190 # urllib2 takes proxy values from the environment and those
183 191 # will take precedence if found, so drop them
184 192 for env in ["HTTP_PROXY", "http_proxy", "no_proxy"]:
185 193 try:
186 194 if os.environ.has_key(env):
187 195 del os.environ[env]
188 196 except OSError:
189 197 pass
190 198
191 199 passmgr = passwordmgr(ui)
192 200 if user:
193 201 ui.debug(_('http auth: user %s, password %s\n') %
194 202 (user, passwd and '*' * len(passwd) or 'not set'))
195 203 passmgr.add_password(None, host, user, passwd or '')
196 204
197 205 handlers.extend((urllib2.HTTPBasicAuthHandler(passmgr),
198 206 urllib2.HTTPDigestAuthHandler(passmgr)))
199 207 opener = urllib2.build_opener(*handlers)
200 208
201 209 # 1.0 here is the _protocol_ version
202 210 opener.addheaders = [('User-agent', 'mercurial/proto-1.0')]
203 211 urllib2.install_opener(opener)
204 212
205 213 def __del__(self):
206 214 if self.handler:
207 215 self.handler.close_all()
208 216 self.handler = None
209 217
210 218 def url(self):
211 219 return self.path
212 220
213 221 # look up capabilities only when needed
214 222
215 223 def get_caps(self):
216 224 if self.caps is None:
217 225 try:
218 226 self.caps = self.do_read('capabilities').split()
219 227 except hg.RepoError:
220 228 self.caps = ()
221 229 self.ui.debug(_('capabilities: %s\n') %
222 230 (' '.join(self.caps or ['none'])))
223 231 return self.caps
224 232
225 233 capabilities = property(get_caps)
226 234
227 235 def lock(self):
228 236 raise util.Abort(_('operation not supported over http'))
229 237
230 238 def do_cmd(self, cmd, **args):
231 239 data = args.pop('data', None)
232 240 headers = args.pop('headers', {})
233 241 self.ui.debug(_("sending %s command\n") % cmd)
234 242 q = {"cmd": cmd}
235 243 q.update(args)
236 244 qs = '?%s' % urllib.urlencode(q)
237 245 cu = "%s%s" % (self._url, qs)
238 246 try:
239 247 if data:
240 248 self.ui.debug(_("sending %s bytes\n") %
241 249 headers.get('content-length', 'X'))
242 resp = urllib2.urlopen(urllib2.Request(cu, data, headers))
250 resp = urllib2.urlopen(request(cu, data, headers))
243 251 except urllib2.HTTPError, inst:
244 252 if inst.code == 401:
245 253 raise util.Abort(_('authorization failed'))
246 254 raise
247 255 except httplib.HTTPException, inst:
248 256 self.ui.debug(_('http error while sending %s command\n') % cmd)
249 257 self.ui.print_exc()
250 258 raise IOError(None, inst)
251 259 except IndexError:
252 260 # this only happens with Python 2.3, later versions raise URLError
253 261 raise util.Abort(_('http error, possibly caused by proxy setting'))
254 262 # record the url we got redirected to
255 263 resp_url = resp.geturl()
256 264 if resp_url.endswith(qs):
257 265 resp_url = resp_url[:-len(qs)]
258 266 if self._url != resp_url:
259 267 self.ui.status(_('real URL is %s\n') % resp_url)
260 268 self._url = resp_url
261 269 try:
262 270 proto = resp.getheader('content-type')
263 271 except AttributeError:
264 272 proto = resp.headers['content-type']
265 273
266 274 # accept old "text/plain" and "application/hg-changegroup" for now
267 275 if not proto.startswith('application/mercurial-') and \
268 276 not proto.startswith('text/plain') and \
269 277 not proto.startswith('application/hg-changegroup'):
270 278 raise hg.RepoError(_("'%s' does not appear to be an hg repository") %
271 279 self._url)
272 280
273 281 if proto.startswith('application/mercurial-'):
274 282 try:
275 283 version = float(proto[22:])
276 284 except ValueError:
277 285 raise hg.RepoError(_("'%s' sent a broken Content-type "
278 286 "header (%s)") % (self._url, proto))
279 287 if version > 0.1:
280 288 raise hg.RepoError(_("'%s' uses newer protocol %s") %
281 289 (self._url, version))
282 290
283 291 return resp
284 292
285 293 def do_read(self, cmd, **args):
286 294 fp = self.do_cmd(cmd, **args)
287 295 try:
288 296 return fp.read()
289 297 finally:
290 298 # if using keepalive, allow connection to be reused
291 299 fp.close()
292 300
293 301 def lookup(self, key):
294 302 d = self.do_cmd("lookup", key = key).read()
295 303 success, data = d[:-1].split(' ', 1)
296 304 if int(success):
297 305 return bin(data)
298 306 raise hg.RepoError(data)
299 307
300 308 def heads(self):
301 309 d = self.do_read("heads")
302 310 try:
303 311 return map(bin, d[:-1].split(" "))
304 312 except:
305 313 raise util.UnexpectedOutput(_("unexpected response:"), d)
306 314
307 315 def branches(self, nodes):
308 316 n = " ".join(map(hex, nodes))
309 317 d = self.do_read("branches", nodes=n)
310 318 try:
311 319 br = [ tuple(map(bin, b.split(" "))) for b in d.splitlines() ]
312 320 return br
313 321 except:
314 322 raise util.UnexpectedOutput(_("unexpected response:"), d)
315 323
316 324 def between(self, pairs):
317 325 n = "\n".join(["-".join(map(hex, p)) for p in pairs])
318 326 d = self.do_read("between", pairs=n)
319 327 try:
320 328 p = [ l and map(bin, l.split(" ")) or [] for l in d.splitlines() ]
321 329 return p
322 330 except:
323 331 raise util.UnexpectedOutput(_("unexpected response:"), d)
324 332
325 333 def changegroup(self, nodes, kind):
326 334 n = " ".join(map(hex, nodes))
327 335 f = self.do_cmd("changegroup", roots=n)
328 336 return util.chunkbuffer(zgenerator(f))
329 337
330 338 def changegroupsubset(self, bases, heads, source):
331 339 baselst = " ".join([hex(n) for n in bases])
332 340 headlst = " ".join([hex(n) for n in heads])
333 341 f = self.do_cmd("changegroupsubset", bases=baselst, heads=headlst)
334 342 return util.chunkbuffer(zgenerator(f))
335 343
336 344 def unbundle(self, cg, heads, source):
337 345 # have to stream bundle to a temp file because we do not have
338 346 # http 1.1 chunked transfer.
339 347
340 348 type = ""
341 349 types = self.capable('unbundle')
342 350 # servers older than d1b16a746db6 will send 'unbundle' as a
343 351 # boolean capability
344 352 try:
345 353 types = types.split(',')
346 354 except AttributeError:
347 355 types = [""]
348 356 if types:
349 357 for x in types:
350 358 if x in changegroup.bundletypes:
351 359 type = x
352 360 break
353 361
354 362 tempname = changegroup.writebundle(cg, None, type)
355 363 fp = httpsendfile(tempname, "rb")
356 364 try:
357 365 try:
358 366 rfp = self.do_cmd(
359 367 'unbundle', data=fp,
360 368 headers={'content-type': 'application/octet-stream'},
361 369 heads=' '.join(map(hex, heads)))
362 370 try:
363 371 ret = int(rfp.readline())
364 372 self.ui.write(rfp.read())
365 373 return ret
366 374 finally:
367 375 rfp.close()
368 376 except socket.error, err:
369 377 if err[0] in (errno.ECONNRESET, errno.EPIPE):
370 378 raise util.Abort(_('push failed: %s') % err[1])
371 379 raise util.Abort(err[1])
372 380 finally:
373 381 fp.close()
374 382 os.unlink(tempname)
375 383
376 384 def stream_out(self):
377 385 return self.do_cmd('stream_out')
378 386
379 387 class httpsrepository(httprepository):
380 388 def __init__(self, ui, path):
381 389 if not has_https:
382 390 raise util.Abort(_('Python support for SSL and HTTPS '
383 391 'is not installed'))
384 392 httprepository.__init__(self, ui, path)
385 393
386 394 def instance(ui, path, create):
387 395 if create:
388 396 raise util.Abort(_('cannot create new http repository'))
389 397 if path.startswith('hg:'):
390 398 ui.warn(_("hg:// syntax is deprecated, please use http:// instead\n"))
391 399 path = 'http:' + path[3:]
392 400 if path.startswith('https:'):
393 401 return httpsrepository(ui, path)
394 402 return httprepository(ui, path)
General Comments 0
You need to be logged in to leave comments. Login now