httprepo.py
238 lines
| 8.5 KiB
| text/x-python
|
PythonLexer
/ mercurial / httprepo.py
mpm@selenic.com
|
r1089 | # httprepo.py - HTTP repository proxy classes for mercurial | ||
# | ||||
Vadim Gelfer
|
r2859 | # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com> | ||
# Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com> | ||||
mpm@selenic.com
|
r1089 | # | ||
# This software may be used and distributed according to the terms | ||||
# of the GNU General Public License, incorporated herein by reference. | ||||
Matt Mackall
|
r7211 | from node import bin, hex, nullid | ||
Matt Mackall
|
r3891 | from i18n import _ | ||
Matt Mackall
|
r5176 | import repo, os, urllib, urllib2, urlparse, zlib, util, httplib | ||
Benoit Boissinot
|
r7280 | import errno, socket, changegroup, statichttprepo | ||
Benoit Boissinot
|
r7270 | import url | ||
Alexis S. L. Carvalho
|
r4678 | |||
Matt Mackall
|
r3661 | def zgenerator(f): | ||
zd = zlib.decompressobj() | ||||
try: | ||||
for chunk in util.filechunkiter(f): | ||||
yield zd.decompress(chunk) | ||||
Benoit Boissinot
|
r7280 | except httplib.HTTPException: | ||
Matt Mackall
|
r3661 | raise IOError(None, _('connection ended unexpectedly')) | ||
yield zd.flush() | ||||
Matt Mackall
|
r6313 | class httprepository(repo.repository): | ||
mpm@selenic.com
|
r1089 | def __init__(self, ui, path): | ||
Vadim Gelfer
|
r2673 | self.path = path | ||
Vadim Gelfer
|
r2442 | self.caps = None | ||
Andrei Vermel
|
r4132 | self.handler = None | ||
Vadim Gelfer
|
r2337 | scheme, netloc, urlpath, query, frag = urlparse.urlsplit(path) | ||
if query or frag: | ||||
raise util.Abort(_('unsupported URL component: "%s"') % | ||||
(query or frag)) | ||||
# urllib cannot handle URLs with embedded user or passwd | ||||
Benoit Boissinot
|
r7270 | self._url, authinfo = url.getauthinfo(path) | ||
mpm@selenic.com
|
r1089 | self.ui = ui | ||
Alexis S. L. Carvalho
|
r5066 | self.ui.debug(_('using %s\n') % self._url) | ||
Vadim Gelfer
|
r2337 | |||
Benoit Boissinot
|
r7270 | self.urlopener = url.opener(ui, authinfo) | ||
Thomas Arendsen Hein
|
r4516 | |||
Vadim Gelfer
|
r2673 | def url(self): | ||
return self.path | ||||
Vadim Gelfer
|
r2442 | # look up capabilities only when needed | ||
def get_caps(self): | ||||
if self.caps is None: | ||||
try: | ||||
Bryan O'Sullivan
|
r5258 | self.caps = util.set(self.do_read('capabilities').split()) | ||
Matt Mackall
|
r5176 | except repo.RepoError: | ||
Bryan O'Sullivan
|
r5258 | self.caps = util.set() | ||
Vadim Gelfer
|
r2465 | self.ui.debug(_('capabilities: %s\n') % | ||
(' '.join(self.caps or ['none']))) | ||||
Vadim Gelfer
|
r2442 | return self.caps | ||
capabilities = property(get_caps) | ||||
Vadim Gelfer
|
r1870 | def lock(self): | ||
raise util.Abort(_('operation not supported over http')) | ||||
mpm@selenic.com
|
r1089 | def do_cmd(self, cmd, **args): | ||
Vadim Gelfer
|
r2465 | data = args.pop('data', None) | ||
headers = args.pop('headers', {}) | ||||
Benoit Boissinot
|
r1402 | self.ui.debug(_("sending %s command\n") % cmd) | ||
mpm@selenic.com
|
r1089 | q = {"cmd": cmd} | ||
q.update(args) | ||||
Benoit Boissinot
|
r3562 | qs = '?%s' % urllib.urlencode(q) | ||
cu = "%s%s" % (self._url, qs) | ||||
Thomas Arendsen Hein
|
r2294 | try: | ||
Thomas Arendsen Hein
|
r3567 | if data: | ||
Alexis S. L. Carvalho
|
r5333 | self.ui.debug(_("sending %s bytes\n") % len(data)) | ||
Benoit Boissinot
|
r7270 | resp = self.urlopener.open(urllib2.Request(cu, data, headers)) | ||
Vadim Gelfer
|
r2467 | except urllib2.HTTPError, inst: | ||
if inst.code == 401: | ||||
raise util.Abort(_('authorization failed')) | ||||
raise | ||||
Thomas Arendsen Hein
|
r2294 | except httplib.HTTPException, inst: | ||
Vadim Gelfer
|
r2336 | self.ui.debug(_('http error while sending %s command\n') % cmd) | ||
self.ui.print_exc() | ||||
raise IOError(None, inst) | ||||
Thomas Arendsen Hein
|
r3399 | except IndexError: | ||
# this only happens with Python 2.3, later versions raise URLError | ||||
raise util.Abort(_('http error, possibly caused by proxy setting')) | ||||
Benoit Boissinot
|
r3562 | # record the url we got redirected to | ||
Thomas Arendsen Hein
|
r3570 | resp_url = resp.geturl() | ||
if resp_url.endswith(qs): | ||||
resp_url = resp_url[:-len(qs)] | ||||
if self._url != resp_url: | ||||
self.ui.status(_('real URL is %s\n') % resp_url) | ||||
self._url = resp_url | ||||
Vadim Gelfer
|
r2435 | try: | ||
proto = resp.getheader('content-type') | ||||
except AttributeError: | ||||
proto = resp.headers['content-type'] | ||||
mpm@selenic.com
|
r1089 | |||
# accept old "text/plain" and "application/hg-changegroup" for now | ||||
Thomas Arendsen Hein
|
r4633 | if not (proto.startswith('application/mercurial-') or | ||
proto.startswith('text/plain') or | ||||
proto.startswith('application/hg-changegroup')): | ||||
Thomas Arendsen Hein
|
r4739 | self.ui.debug(_("Requested URL: '%s'\n") % cu) | ||
Matt Mackall
|
r5176 | raise repo.RepoError(_("'%s' does not appear to be an hg repository") | ||
Thomas Arendsen Hein
|
r4633 | % self._url) | ||
mpm@selenic.com
|
r1089 | |||
Benoit Boissinot
|
r4012 | if proto.startswith('application/mercurial-'): | ||
try: | ||||
Thomas Arendsen Hein
|
r4356 | version = proto.split('-', 1)[1] | ||
version_info = tuple([int(n) for n in version.split('.')]) | ||||
Benoit Boissinot
|
r4012 | except ValueError: | ||
Dirkjan Ochtman
|
r5930 | raise repo.RepoError(_("'%s' sent a broken Content-Type " | ||
Benoit Boissinot
|
r4012 | "header (%s)") % (self._url, proto)) | ||
Thomas Arendsen Hein
|
r4356 | if version_info > (0, 1): | ||
Matt Mackall
|
r5176 | raise repo.RepoError(_("'%s' uses newer protocol %s") % | ||
Vadim Gelfer
|
r2673 | (self._url, version)) | ||
mpm@selenic.com
|
r1089 | |||
return resp | ||||
Vadim Gelfer
|
r2435 | def do_read(self, cmd, **args): | ||
fp = self.do_cmd(cmd, **args) | ||||
try: | ||||
return fp.read() | ||||
finally: | ||||
# if using keepalive, allow connection to be reused | ||||
fp.close() | ||||
Eric Hopper
|
r3444 | def lookup(self, key): | ||
Bryan O'Sullivan
|
r5259 | self.requirecap('lookup', _('look up remote revision')) | ||
Matt Mackall
|
r3445 | d = self.do_cmd("lookup", key = key).read() | ||
success, data = d[:-1].split(' ', 1) | ||||
if int(success): | ||||
return bin(data) | ||||
Matt Mackall
|
r5176 | raise repo.RepoError(data) | ||
Eric Hopper
|
r3444 | |||
mpm@selenic.com
|
r1089 | def heads(self): | ||
Vadim Gelfer
|
r2435 | d = self.do_read("heads") | ||
mpm@selenic.com
|
r1089 | try: | ||
return map(bin, d[:-1].split(" ")) | ||||
except: | ||||
Thomas Arendsen Hein
|
r3565 | raise util.UnexpectedOutput(_("unexpected response:"), d) | ||
mpm@selenic.com
|
r1089 | |||
def branches(self, nodes): | ||||
n = " ".join(map(hex, nodes)) | ||||
Vadim Gelfer
|
r2435 | d = self.do_read("branches", nodes=n) | ||
mpm@selenic.com
|
r1089 | try: | ||
br = [ tuple(map(bin, b.split(" "))) for b in d.splitlines() ] | ||||
return br | ||||
except: | ||||
Thomas Arendsen Hein
|
r3565 | raise util.UnexpectedOutput(_("unexpected response:"), d) | ||
mpm@selenic.com
|
r1089 | |||
def between(self, pairs): | ||||
Matt Mackall
|
r7342 | batch = 8 # avoid giant requests | ||
r = [] | ||||
for i in xrange(0, len(pairs), batch): | ||||
n = " ".join(["-".join(map(hex, p)) for p in pairs[i:i + batch]]) | ||||
d = self.do_read("between", pairs=n) | ||||
try: | ||||
r += [ l and map(bin, l.split(" ")) or [] for l in d.splitlines() ] | ||||
except: | ||||
raise util.UnexpectedOutput(_("unexpected response:"), d) | ||||
return r | ||||
mpm@selenic.com
|
r1089 | |||
Vadim Gelfer
|
r1736 | def changegroup(self, nodes, kind): | ||
mpm@selenic.com
|
r1089 | n = " ".join(map(hex, nodes)) | ||
f = self.do_cmd("changegroup", roots=n) | ||||
Matt Mackall
|
r3661 | return util.chunkbuffer(zgenerator(f)) | ||
Eric Hopper
|
r3444 | |||
def changegroupsubset(self, bases, heads, source): | ||||
Bryan O'Sullivan
|
r5259 | self.requirecap('changegroupsubset', _('look up remote changes')) | ||
Eric Hopper
|
r3444 | baselst = " ".join([hex(n) for n in bases]) | ||
headlst = " ".join([hex(n) for n in heads]) | ||||
f = self.do_cmd("changegroupsubset", bases=baselst, heads=headlst) | ||||
Matt Mackall
|
r3661 | return util.chunkbuffer(zgenerator(f)) | ||
mpm@selenic.com
|
r1089 | |||
Vadim Gelfer
|
r2439 | def unbundle(self, cg, heads, source): | ||
Vadim Gelfer
|
r2465 | # have to stream bundle to a temp file because we do not have | ||
# http 1.1 chunked transfer. | ||||
Matt Mackall
|
r3662 | type = "" | ||
types = self.capable('unbundle') | ||||
Alexis S. L. Carvalho
|
r3703 | # servers older than d1b16a746db6 will send 'unbundle' as a | ||
# boolean capability | ||||
try: | ||||
types = types.split(',') | ||||
except AttributeError: | ||||
types = [""] | ||||
Matt Mackall
|
r3662 | if types: | ||
Alexis S. L. Carvalho
|
r3703 | for x in types: | ||
Matt Mackall
|
r3662 | if x in changegroup.bundletypes: | ||
type = x | ||||
break | ||||
Thomas Arendsen Hein
|
r3613 | |||
Matt Mackall
|
r3662 | tempname = changegroup.writebundle(cg, None, type) | ||
Benoit Boissinot
|
r7270 | fp = url.httpsendfile(tempname, "rb") | ||
Vadim Gelfer
|
r2465 | try: | ||
try: | ||||
Benoit Boissinot
|
r7010 | resp = self.do_read( | ||
'unbundle', data=fp, | ||||
headers={'Content-Type': 'application/octet-stream'}, | ||||
heads=' '.join(map(hex, heads))) | ||||
resp_code, output = resp.split('\n', 1) | ||||
Vadim Gelfer
|
r2467 | try: | ||
Benoit Boissinot
|
r7010 | ret = int(resp_code) | ||
except ValueError, err: | ||||
raise util.UnexpectedOutput( | ||||
_('push failed (unexpected response):'), resp) | ||||
self.ui.write(output) | ||||
return ret | ||||
Vadim Gelfer
|
r2467 | except socket.error, err: | ||
if err[0] in (errno.ECONNRESET, errno.EPIPE): | ||||
Thomas Arendsen Hein
|
r3072 | raise util.Abort(_('push failed: %s') % err[1]) | ||
Vadim Gelfer
|
r2467 | raise util.Abort(err[1]) | ||
Vadim Gelfer
|
r2465 | finally: | ||
fp.close() | ||||
os.unlink(tempname) | ||||
Vadim Gelfer
|
r2439 | |||
Vadim Gelfer
|
r2612 | def stream_out(self): | ||
return self.do_cmd('stream_out') | ||||
mpm@selenic.com
|
r1089 | class httpsrepository(httprepository): | ||
Alexis S. L. Carvalho
|
r2569 | def __init__(self, ui, path): | ||
Benoit Boissinot
|
r7279 | if not url.has_https: | ||
Alexis S. L. Carvalho
|
r2569 | raise util.Abort(_('Python support for SSL and HTTPS ' | ||
'is not installed')) | ||||
httprepository.__init__(self, ui, path) | ||||
Vadim Gelfer
|
r2740 | |||
def instance(ui, path, create): | ||||
if create: | ||||
raise util.Abort(_('cannot create new http repository')) | ||||
Matt Mackall
|
r7211 | try: | ||
if path.startswith('https:'): | ||||
inst = httpsrepository(ui, path) | ||||
else: | ||||
inst = httprepository(ui, path) | ||||
inst.between([(nullid, nullid)]) | ||||
return inst | ||||
except repo.RepoError: | ||||
ui.note('(falling back to static-http)\n') | ||||
return statichttprepo.instance(ui, "static-" + path, create) | ||||