##// END OF EJS Templates
httppeer: handle error response from client reactor...
Gregory Szorc -
r37672:8cea0d57 default
parent child Browse files
Show More
@@ -1,1001 +1,1009 b''
1 # httppeer.py - HTTP repository proxy classes for mercurial
1 # httppeer.py - HTTP repository proxy classes for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import errno
11 import errno
12 import io
12 import io
13 import os
13 import os
14 import socket
14 import socket
15 import struct
15 import struct
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18 import weakref
18 import weakref
19
19
20 from .i18n import _
20 from .i18n import _
21 from .thirdparty import (
21 from .thirdparty import (
22 cbor,
22 cbor,
23 )
23 )
24 from .thirdparty.zope import (
24 from .thirdparty.zope import (
25 interface as zi,
25 interface as zi,
26 )
26 )
27 from . import (
27 from . import (
28 bundle2,
28 bundle2,
29 error,
29 error,
30 httpconnection,
30 httpconnection,
31 pycompat,
31 pycompat,
32 repository,
32 repository,
33 statichttprepo,
33 statichttprepo,
34 url as urlmod,
34 url as urlmod,
35 util,
35 util,
36 wireprotoframing,
36 wireprotoframing,
37 wireprototypes,
37 wireprototypes,
38 wireprotov1peer,
38 wireprotov1peer,
39 wireprotov2server,
39 wireprotov2server,
40 )
40 )
41
41
42 httplib = util.httplib
42 httplib = util.httplib
43 urlerr = util.urlerr
43 urlerr = util.urlerr
44 urlreq = util.urlreq
44 urlreq = util.urlreq
45
45
46 def encodevalueinheaders(value, header, limit):
46 def encodevalueinheaders(value, header, limit):
47 """Encode a string value into multiple HTTP headers.
47 """Encode a string value into multiple HTTP headers.
48
48
49 ``value`` will be encoded into 1 or more HTTP headers with the names
49 ``value`` will be encoded into 1 or more HTTP headers with the names
50 ``header-<N>`` where ``<N>`` is an integer starting at 1. Each header
50 ``header-<N>`` where ``<N>`` is an integer starting at 1. Each header
51 name + value will be at most ``limit`` bytes long.
51 name + value will be at most ``limit`` bytes long.
52
52
53 Returns an iterable of 2-tuples consisting of header names and
53 Returns an iterable of 2-tuples consisting of header names and
54 values as native strings.
54 values as native strings.
55 """
55 """
56 # HTTP Headers are ASCII. Python 3 requires them to be unicodes,
56 # HTTP Headers are ASCII. Python 3 requires them to be unicodes,
57 # not bytes. This function always takes bytes in as arguments.
57 # not bytes. This function always takes bytes in as arguments.
58 fmt = pycompat.strurl(header) + r'-%s'
58 fmt = pycompat.strurl(header) + r'-%s'
59 # Note: it is *NOT* a bug that the last bit here is a bytestring
59 # Note: it is *NOT* a bug that the last bit here is a bytestring
60 # and not a unicode: we're just getting the encoded length anyway,
60 # and not a unicode: we're just getting the encoded length anyway,
61 # and using an r-string to make it portable between Python 2 and 3
61 # and using an r-string to make it portable between Python 2 and 3
62 # doesn't work because then the \r is a literal backslash-r
62 # doesn't work because then the \r is a literal backslash-r
63 # instead of a carriage return.
63 # instead of a carriage return.
64 valuelen = limit - len(fmt % r'000') - len(': \r\n')
64 valuelen = limit - len(fmt % r'000') - len(': \r\n')
65 result = []
65 result = []
66
66
67 n = 0
67 n = 0
68 for i in xrange(0, len(value), valuelen):
68 for i in xrange(0, len(value), valuelen):
69 n += 1
69 n += 1
70 result.append((fmt % str(n), pycompat.strurl(value[i:i + valuelen])))
70 result.append((fmt % str(n), pycompat.strurl(value[i:i + valuelen])))
71
71
72 return result
72 return result
73
73
74 def _wraphttpresponse(resp):
74 def _wraphttpresponse(resp):
75 """Wrap an HTTPResponse with common error handlers.
75 """Wrap an HTTPResponse with common error handlers.
76
76
77 This ensures that any I/O from any consumer raises the appropriate
77 This ensures that any I/O from any consumer raises the appropriate
78 error and messaging.
78 error and messaging.
79 """
79 """
80 origread = resp.read
80 origread = resp.read
81
81
82 class readerproxy(resp.__class__):
82 class readerproxy(resp.__class__):
83 def read(self, size=None):
83 def read(self, size=None):
84 try:
84 try:
85 return origread(size)
85 return origread(size)
86 except httplib.IncompleteRead as e:
86 except httplib.IncompleteRead as e:
87 # e.expected is an integer if length known or None otherwise.
87 # e.expected is an integer if length known or None otherwise.
88 if e.expected:
88 if e.expected:
89 msg = _('HTTP request error (incomplete response; '
89 msg = _('HTTP request error (incomplete response; '
90 'expected %d bytes got %d)') % (e.expected,
90 'expected %d bytes got %d)') % (e.expected,
91 len(e.partial))
91 len(e.partial))
92 else:
92 else:
93 msg = _('HTTP request error (incomplete response)')
93 msg = _('HTTP request error (incomplete response)')
94
94
95 raise error.PeerTransportError(
95 raise error.PeerTransportError(
96 msg,
96 msg,
97 hint=_('this may be an intermittent network failure; '
97 hint=_('this may be an intermittent network failure; '
98 'if the error persists, consider contacting the '
98 'if the error persists, consider contacting the '
99 'network or server operator'))
99 'network or server operator'))
100 except httplib.HTTPException as e:
100 except httplib.HTTPException as e:
101 raise error.PeerTransportError(
101 raise error.PeerTransportError(
102 _('HTTP request error (%s)') % e,
102 _('HTTP request error (%s)') % e,
103 hint=_('this may be an intermittent network failure; '
103 hint=_('this may be an intermittent network failure; '
104 'if the error persists, consider contacting the '
104 'if the error persists, consider contacting the '
105 'network or server operator'))
105 'network or server operator'))
106
106
107 resp.__class__ = readerproxy
107 resp.__class__ = readerproxy
108
108
109 class _multifile(object):
109 class _multifile(object):
110 def __init__(self, *fileobjs):
110 def __init__(self, *fileobjs):
111 for f in fileobjs:
111 for f in fileobjs:
112 if not util.safehasattr(f, 'length'):
112 if not util.safehasattr(f, 'length'):
113 raise ValueError(
113 raise ValueError(
114 '_multifile only supports file objects that '
114 '_multifile only supports file objects that '
115 'have a length but this one does not:', type(f), f)
115 'have a length but this one does not:', type(f), f)
116 self._fileobjs = fileobjs
116 self._fileobjs = fileobjs
117 self._index = 0
117 self._index = 0
118
118
119 @property
119 @property
120 def length(self):
120 def length(self):
121 return sum(f.length for f in self._fileobjs)
121 return sum(f.length for f in self._fileobjs)
122
122
123 def read(self, amt=None):
123 def read(self, amt=None):
124 if amt <= 0:
124 if amt <= 0:
125 return ''.join(f.read() for f in self._fileobjs)
125 return ''.join(f.read() for f in self._fileobjs)
126 parts = []
126 parts = []
127 while amt and self._index < len(self._fileobjs):
127 while amt and self._index < len(self._fileobjs):
128 parts.append(self._fileobjs[self._index].read(amt))
128 parts.append(self._fileobjs[self._index].read(amt))
129 got = len(parts[-1])
129 got = len(parts[-1])
130 if got < amt:
130 if got < amt:
131 self._index += 1
131 self._index += 1
132 amt -= got
132 amt -= got
133 return ''.join(parts)
133 return ''.join(parts)
134
134
135 def seek(self, offset, whence=os.SEEK_SET):
135 def seek(self, offset, whence=os.SEEK_SET):
136 if whence != os.SEEK_SET:
136 if whence != os.SEEK_SET:
137 raise NotImplementedError(
137 raise NotImplementedError(
138 '_multifile does not support anything other'
138 '_multifile does not support anything other'
139 ' than os.SEEK_SET for whence on seek()')
139 ' than os.SEEK_SET for whence on seek()')
140 if offset != 0:
140 if offset != 0:
141 raise NotImplementedError(
141 raise NotImplementedError(
142 '_multifile only supports seeking to start, but that '
142 '_multifile only supports seeking to start, but that '
143 'could be fixed if you need it')
143 'could be fixed if you need it')
144 for f in self._fileobjs:
144 for f in self._fileobjs:
145 f.seek(0)
145 f.seek(0)
146 self._index = 0
146 self._index = 0
147
147
148 def makev1commandrequest(ui, requestbuilder, caps, capablefn,
148 def makev1commandrequest(ui, requestbuilder, caps, capablefn,
149 repobaseurl, cmd, args):
149 repobaseurl, cmd, args):
150 """Make an HTTP request to run a command for a version 1 client.
150 """Make an HTTP request to run a command for a version 1 client.
151
151
152 ``caps`` is a set of known server capabilities. The value may be
152 ``caps`` is a set of known server capabilities. The value may be
153 None if capabilities are not yet known.
153 None if capabilities are not yet known.
154
154
155 ``capablefn`` is a function to evaluate a capability.
155 ``capablefn`` is a function to evaluate a capability.
156
156
157 ``cmd``, ``args``, and ``data`` define the command, its arguments, and
157 ``cmd``, ``args``, and ``data`` define the command, its arguments, and
158 raw data to pass to it.
158 raw data to pass to it.
159 """
159 """
160 if cmd == 'pushkey':
160 if cmd == 'pushkey':
161 args['data'] = ''
161 args['data'] = ''
162 data = args.pop('data', None)
162 data = args.pop('data', None)
163 headers = args.pop('headers', {})
163 headers = args.pop('headers', {})
164
164
165 ui.debug("sending %s command\n" % cmd)
165 ui.debug("sending %s command\n" % cmd)
166 q = [('cmd', cmd)]
166 q = [('cmd', cmd)]
167 headersize = 0
167 headersize = 0
168 # Important: don't use self.capable() here or else you end up
168 # Important: don't use self.capable() here or else you end up
169 # with infinite recursion when trying to look up capabilities
169 # with infinite recursion when trying to look up capabilities
170 # for the first time.
170 # for the first time.
171 postargsok = caps is not None and 'httppostargs' in caps
171 postargsok = caps is not None and 'httppostargs' in caps
172
172
173 # Send arguments via POST.
173 # Send arguments via POST.
174 if postargsok and args:
174 if postargsok and args:
175 strargs = urlreq.urlencode(sorted(args.items()))
175 strargs = urlreq.urlencode(sorted(args.items()))
176 if not data:
176 if not data:
177 data = strargs
177 data = strargs
178 else:
178 else:
179 if isinstance(data, bytes):
179 if isinstance(data, bytes):
180 i = io.BytesIO(data)
180 i = io.BytesIO(data)
181 i.length = len(data)
181 i.length = len(data)
182 data = i
182 data = i
183 argsio = io.BytesIO(strargs)
183 argsio = io.BytesIO(strargs)
184 argsio.length = len(strargs)
184 argsio.length = len(strargs)
185 data = _multifile(argsio, data)
185 data = _multifile(argsio, data)
186 headers[r'X-HgArgs-Post'] = len(strargs)
186 headers[r'X-HgArgs-Post'] = len(strargs)
187 elif args:
187 elif args:
188 # Calling self.capable() can infinite loop if we are calling
188 # Calling self.capable() can infinite loop if we are calling
189 # "capabilities". But that command should never accept wire
189 # "capabilities". But that command should never accept wire
190 # protocol arguments. So this should never happen.
190 # protocol arguments. So this should never happen.
191 assert cmd != 'capabilities'
191 assert cmd != 'capabilities'
192 httpheader = capablefn('httpheader')
192 httpheader = capablefn('httpheader')
193 if httpheader:
193 if httpheader:
194 headersize = int(httpheader.split(',', 1)[0])
194 headersize = int(httpheader.split(',', 1)[0])
195
195
196 # Send arguments via HTTP headers.
196 # Send arguments via HTTP headers.
197 if headersize > 0:
197 if headersize > 0:
198 # The headers can typically carry more data than the URL.
198 # The headers can typically carry more data than the URL.
199 encargs = urlreq.urlencode(sorted(args.items()))
199 encargs = urlreq.urlencode(sorted(args.items()))
200 for header, value in encodevalueinheaders(encargs, 'X-HgArg',
200 for header, value in encodevalueinheaders(encargs, 'X-HgArg',
201 headersize):
201 headersize):
202 headers[header] = value
202 headers[header] = value
203 # Send arguments via query string (Mercurial <1.9).
203 # Send arguments via query string (Mercurial <1.9).
204 else:
204 else:
205 q += sorted(args.items())
205 q += sorted(args.items())
206
206
207 qs = '?%s' % urlreq.urlencode(q)
207 qs = '?%s' % urlreq.urlencode(q)
208 cu = "%s%s" % (repobaseurl, qs)
208 cu = "%s%s" % (repobaseurl, qs)
209 size = 0
209 size = 0
210 if util.safehasattr(data, 'length'):
210 if util.safehasattr(data, 'length'):
211 size = data.length
211 size = data.length
212 elif data is not None:
212 elif data is not None:
213 size = len(data)
213 size = len(data)
214 if data is not None and r'Content-Type' not in headers:
214 if data is not None and r'Content-Type' not in headers:
215 headers[r'Content-Type'] = r'application/mercurial-0.1'
215 headers[r'Content-Type'] = r'application/mercurial-0.1'
216
216
217 # Tell the server we accept application/mercurial-0.2 and multiple
217 # Tell the server we accept application/mercurial-0.2 and multiple
218 # compression formats if the server is capable of emitting those
218 # compression formats if the server is capable of emitting those
219 # payloads.
219 # payloads.
220 # Note: Keep this set empty by default, as client advertisement of
220 # Note: Keep this set empty by default, as client advertisement of
221 # protocol parameters should only occur after the handshake.
221 # protocol parameters should only occur after the handshake.
222 protoparams = set()
222 protoparams = set()
223
223
224 mediatypes = set()
224 mediatypes = set()
225 if caps is not None:
225 if caps is not None:
226 mt = capablefn('httpmediatype')
226 mt = capablefn('httpmediatype')
227 if mt:
227 if mt:
228 protoparams.add('0.1')
228 protoparams.add('0.1')
229 mediatypes = set(mt.split(','))
229 mediatypes = set(mt.split(','))
230
230
231 protoparams.add('partial-pull')
231 protoparams.add('partial-pull')
232
232
233 if '0.2tx' in mediatypes:
233 if '0.2tx' in mediatypes:
234 protoparams.add('0.2')
234 protoparams.add('0.2')
235
235
236 if '0.2tx' in mediatypes and capablefn('compression'):
236 if '0.2tx' in mediatypes and capablefn('compression'):
237 # We /could/ compare supported compression formats and prune
237 # We /could/ compare supported compression formats and prune
238 # non-mutually supported or error if nothing is mutually supported.
238 # non-mutually supported or error if nothing is mutually supported.
239 # For now, send the full list to the server and have it error.
239 # For now, send the full list to the server and have it error.
240 comps = [e.wireprotosupport().name for e in
240 comps = [e.wireprotosupport().name for e in
241 util.compengines.supportedwireengines(util.CLIENTROLE)]
241 util.compengines.supportedwireengines(util.CLIENTROLE)]
242 protoparams.add('comp=%s' % ','.join(comps))
242 protoparams.add('comp=%s' % ','.join(comps))
243
243
244 if protoparams:
244 if protoparams:
245 protoheaders = encodevalueinheaders(' '.join(sorted(protoparams)),
245 protoheaders = encodevalueinheaders(' '.join(sorted(protoparams)),
246 'X-HgProto',
246 'X-HgProto',
247 headersize or 1024)
247 headersize or 1024)
248 for header, value in protoheaders:
248 for header, value in protoheaders:
249 headers[header] = value
249 headers[header] = value
250
250
251 varyheaders = []
251 varyheaders = []
252 for header in headers:
252 for header in headers:
253 if header.lower().startswith(r'x-hg'):
253 if header.lower().startswith(r'x-hg'):
254 varyheaders.append(header)
254 varyheaders.append(header)
255
255
256 if varyheaders:
256 if varyheaders:
257 headers[r'Vary'] = r','.join(sorted(varyheaders))
257 headers[r'Vary'] = r','.join(sorted(varyheaders))
258
258
259 req = requestbuilder(pycompat.strurl(cu), data, headers)
259 req = requestbuilder(pycompat.strurl(cu), data, headers)
260
260
261 if data is not None:
261 if data is not None:
262 ui.debug("sending %d bytes\n" % size)
262 ui.debug("sending %d bytes\n" % size)
263 req.add_unredirected_header(r'Content-Length', r'%d' % size)
263 req.add_unredirected_header(r'Content-Length', r'%d' % size)
264
264
265 return req, cu, qs
265 return req, cu, qs
266
266
267 def sendrequest(ui, opener, req):
267 def sendrequest(ui, opener, req):
268 """Send a prepared HTTP request.
268 """Send a prepared HTTP request.
269
269
270 Returns the response object.
270 Returns the response object.
271 """
271 """
272 if (ui.debugflag
272 if (ui.debugflag
273 and ui.configbool('devel', 'debug.peer-request')):
273 and ui.configbool('devel', 'debug.peer-request')):
274 dbg = ui.debug
274 dbg = ui.debug
275 line = 'devel-peer-request: %s\n'
275 line = 'devel-peer-request: %s\n'
276 dbg(line % '%s %s' % (req.get_method(), req.get_full_url()))
276 dbg(line % '%s %s' % (req.get_method(), req.get_full_url()))
277 hgargssize = None
277 hgargssize = None
278
278
279 for header, value in sorted(req.header_items()):
279 for header, value in sorted(req.header_items()):
280 if header.startswith('X-hgarg-'):
280 if header.startswith('X-hgarg-'):
281 if hgargssize is None:
281 if hgargssize is None:
282 hgargssize = 0
282 hgargssize = 0
283 hgargssize += len(value)
283 hgargssize += len(value)
284 else:
284 else:
285 dbg(line % ' %s %s' % (header, value))
285 dbg(line % ' %s %s' % (header, value))
286
286
287 if hgargssize is not None:
287 if hgargssize is not None:
288 dbg(line % ' %d bytes of commands arguments in headers'
288 dbg(line % ' %d bytes of commands arguments in headers'
289 % hgargssize)
289 % hgargssize)
290
290
291 if req.has_data():
291 if req.has_data():
292 data = req.get_data()
292 data = req.get_data()
293 length = getattr(data, 'length', None)
293 length = getattr(data, 'length', None)
294 if length is None:
294 if length is None:
295 length = len(data)
295 length = len(data)
296 dbg(line % ' %d bytes of data' % length)
296 dbg(line % ' %d bytes of data' % length)
297
297
298 start = util.timer()
298 start = util.timer()
299
299
300 try:
300 try:
301 res = opener.open(req)
301 res = opener.open(req)
302 except urlerr.httperror as inst:
302 except urlerr.httperror as inst:
303 if inst.code == 401:
303 if inst.code == 401:
304 raise error.Abort(_('authorization failed'))
304 raise error.Abort(_('authorization failed'))
305 raise
305 raise
306 except httplib.HTTPException as inst:
306 except httplib.HTTPException as inst:
307 ui.debug('http error requesting %s\n' %
307 ui.debug('http error requesting %s\n' %
308 util.hidepassword(req.get_full_url()))
308 util.hidepassword(req.get_full_url()))
309 ui.traceback()
309 ui.traceback()
310 raise IOError(None, inst)
310 raise IOError(None, inst)
311 finally:
311 finally:
312 if ui.configbool('devel', 'debug.peer-request'):
312 if ui.configbool('devel', 'debug.peer-request'):
313 dbg(line % ' finished in %.4f seconds (%s)'
313 dbg(line % ' finished in %.4f seconds (%s)'
314 % (util.timer() - start, res.code))
314 % (util.timer() - start, res.code))
315
315
316 # Insert error handlers for common I/O failures.
316 # Insert error handlers for common I/O failures.
317 _wraphttpresponse(res)
317 _wraphttpresponse(res)
318
318
319 return res
319 return res
320
320
321 def parsev1commandresponse(ui, baseurl, requrl, qs, resp, compressible,
321 def parsev1commandresponse(ui, baseurl, requrl, qs, resp, compressible,
322 allowcbor=False):
322 allowcbor=False):
323 # record the url we got redirected to
323 # record the url we got redirected to
324 respurl = pycompat.bytesurl(resp.geturl())
324 respurl = pycompat.bytesurl(resp.geturl())
325 if respurl.endswith(qs):
325 if respurl.endswith(qs):
326 respurl = respurl[:-len(qs)]
326 respurl = respurl[:-len(qs)]
327 if baseurl.rstrip('/') != respurl.rstrip('/'):
327 if baseurl.rstrip('/') != respurl.rstrip('/'):
328 if not ui.quiet:
328 if not ui.quiet:
329 ui.warn(_('real URL is %s\n') % respurl)
329 ui.warn(_('real URL is %s\n') % respurl)
330
330
331 try:
331 try:
332 proto = pycompat.bytesurl(resp.getheader(r'content-type', r''))
332 proto = pycompat.bytesurl(resp.getheader(r'content-type', r''))
333 except AttributeError:
333 except AttributeError:
334 proto = pycompat.bytesurl(resp.headers.get(r'content-type', r''))
334 proto = pycompat.bytesurl(resp.headers.get(r'content-type', r''))
335
335
336 safeurl = util.hidepassword(baseurl)
336 safeurl = util.hidepassword(baseurl)
337 if proto.startswith('application/hg-error'):
337 if proto.startswith('application/hg-error'):
338 raise error.OutOfBandError(resp.read())
338 raise error.OutOfBandError(resp.read())
339
339
340 # Pre 1.0 versions of Mercurial used text/plain and
340 # Pre 1.0 versions of Mercurial used text/plain and
341 # application/hg-changegroup. We don't support such old servers.
341 # application/hg-changegroup. We don't support such old servers.
342 if not proto.startswith('application/mercurial-'):
342 if not proto.startswith('application/mercurial-'):
343 ui.debug("requested URL: '%s'\n" % util.hidepassword(requrl))
343 ui.debug("requested URL: '%s'\n" % util.hidepassword(requrl))
344 raise error.RepoError(
344 raise error.RepoError(
345 _("'%s' does not appear to be an hg repository:\n"
345 _("'%s' does not appear to be an hg repository:\n"
346 "---%%<--- (%s)\n%s\n---%%<---\n")
346 "---%%<--- (%s)\n%s\n---%%<---\n")
347 % (safeurl, proto or 'no content-type', resp.read(1024)))
347 % (safeurl, proto or 'no content-type', resp.read(1024)))
348
348
349 try:
349 try:
350 subtype = proto.split('-', 1)[1]
350 subtype = proto.split('-', 1)[1]
351
351
352 # Unless we end up supporting CBOR in the legacy wire protocol,
352 # Unless we end up supporting CBOR in the legacy wire protocol,
353 # this should ONLY be encountered for the initial capabilities
353 # this should ONLY be encountered for the initial capabilities
354 # request during handshake.
354 # request during handshake.
355 if subtype == 'cbor':
355 if subtype == 'cbor':
356 if allowcbor:
356 if allowcbor:
357 return respurl, proto, resp
357 return respurl, proto, resp
358 else:
358 else:
359 raise error.RepoError(_('unexpected CBOR response from '
359 raise error.RepoError(_('unexpected CBOR response from '
360 'server'))
360 'server'))
361
361
362 version_info = tuple([int(n) for n in subtype.split('.')])
362 version_info = tuple([int(n) for n in subtype.split('.')])
363 except ValueError:
363 except ValueError:
364 raise error.RepoError(_("'%s' sent a broken Content-Type "
364 raise error.RepoError(_("'%s' sent a broken Content-Type "
365 "header (%s)") % (safeurl, proto))
365 "header (%s)") % (safeurl, proto))
366
366
367 # TODO consider switching to a decompression reader that uses
367 # TODO consider switching to a decompression reader that uses
368 # generators.
368 # generators.
369 if version_info == (0, 1):
369 if version_info == (0, 1):
370 if compressible:
370 if compressible:
371 resp = util.compengines['zlib'].decompressorreader(resp)
371 resp = util.compengines['zlib'].decompressorreader(resp)
372
372
373 elif version_info == (0, 2):
373 elif version_info == (0, 2):
374 # application/mercurial-0.2 always identifies the compression
374 # application/mercurial-0.2 always identifies the compression
375 # engine in the payload header.
375 # engine in the payload header.
376 elen = struct.unpack('B', resp.read(1))[0]
376 elen = struct.unpack('B', resp.read(1))[0]
377 ename = resp.read(elen)
377 ename = resp.read(elen)
378 engine = util.compengines.forwiretype(ename)
378 engine = util.compengines.forwiretype(ename)
379
379
380 resp = engine.decompressorreader(resp)
380 resp = engine.decompressorreader(resp)
381 else:
381 else:
382 raise error.RepoError(_("'%s' uses newer protocol %s") %
382 raise error.RepoError(_("'%s' uses newer protocol %s") %
383 (safeurl, subtype))
383 (safeurl, subtype))
384
384
385 return respurl, proto, resp
385 return respurl, proto, resp
386
386
387 class httppeer(wireprotov1peer.wirepeer):
387 class httppeer(wireprotov1peer.wirepeer):
388 def __init__(self, ui, path, url, opener, requestbuilder, caps):
388 def __init__(self, ui, path, url, opener, requestbuilder, caps):
389 self.ui = ui
389 self.ui = ui
390 self._path = path
390 self._path = path
391 self._url = url
391 self._url = url
392 self._caps = caps
392 self._caps = caps
393 self._urlopener = opener
393 self._urlopener = opener
394 self._requestbuilder = requestbuilder
394 self._requestbuilder = requestbuilder
395
395
396 def __del__(self):
396 def __del__(self):
397 for h in self._urlopener.handlers:
397 for h in self._urlopener.handlers:
398 h.close()
398 h.close()
399 getattr(h, "close_all", lambda: None)()
399 getattr(h, "close_all", lambda: None)()
400
400
401 # Begin of ipeerconnection interface.
401 # Begin of ipeerconnection interface.
402
402
403 def url(self):
403 def url(self):
404 return self._path
404 return self._path
405
405
406 def local(self):
406 def local(self):
407 return None
407 return None
408
408
409 def peer(self):
409 def peer(self):
410 return self
410 return self
411
411
412 def canpush(self):
412 def canpush(self):
413 return True
413 return True
414
414
415 def close(self):
415 def close(self):
416 pass
416 pass
417
417
418 # End of ipeerconnection interface.
418 # End of ipeerconnection interface.
419
419
420 # Begin of ipeercommands interface.
420 # Begin of ipeercommands interface.
421
421
422 def capabilities(self):
422 def capabilities(self):
423 return self._caps
423 return self._caps
424
424
425 # End of ipeercommands interface.
425 # End of ipeercommands interface.
426
426
427 # look up capabilities only when needed
427 # look up capabilities only when needed
428
428
429 def _callstream(self, cmd, _compressible=False, **args):
429 def _callstream(self, cmd, _compressible=False, **args):
430 args = pycompat.byteskwargs(args)
430 args = pycompat.byteskwargs(args)
431
431
432 req, cu, qs = makev1commandrequest(self.ui, self._requestbuilder,
432 req, cu, qs = makev1commandrequest(self.ui, self._requestbuilder,
433 self._caps, self.capable,
433 self._caps, self.capable,
434 self._url, cmd, args)
434 self._url, cmd, args)
435
435
436 resp = sendrequest(self.ui, self._urlopener, req)
436 resp = sendrequest(self.ui, self._urlopener, req)
437
437
438 self._url, ct, resp = parsev1commandresponse(self.ui, self._url, cu, qs,
438 self._url, ct, resp = parsev1commandresponse(self.ui, self._url, cu, qs,
439 resp, _compressible)
439 resp, _compressible)
440
440
441 return resp
441 return resp
442
442
443 def _call(self, cmd, **args):
443 def _call(self, cmd, **args):
444 fp = self._callstream(cmd, **args)
444 fp = self._callstream(cmd, **args)
445 try:
445 try:
446 return fp.read()
446 return fp.read()
447 finally:
447 finally:
448 # if using keepalive, allow connection to be reused
448 # if using keepalive, allow connection to be reused
449 fp.close()
449 fp.close()
450
450
451 def _callpush(self, cmd, cg, **args):
451 def _callpush(self, cmd, cg, **args):
452 # have to stream bundle to a temp file because we do not have
452 # have to stream bundle to a temp file because we do not have
453 # http 1.1 chunked transfer.
453 # http 1.1 chunked transfer.
454
454
455 types = self.capable('unbundle')
455 types = self.capable('unbundle')
456 try:
456 try:
457 types = types.split(',')
457 types = types.split(',')
458 except AttributeError:
458 except AttributeError:
459 # servers older than d1b16a746db6 will send 'unbundle' as a
459 # servers older than d1b16a746db6 will send 'unbundle' as a
460 # boolean capability. They only support headerless/uncompressed
460 # boolean capability. They only support headerless/uncompressed
461 # bundles.
461 # bundles.
462 types = [""]
462 types = [""]
463 for x in types:
463 for x in types:
464 if x in bundle2.bundletypes:
464 if x in bundle2.bundletypes:
465 type = x
465 type = x
466 break
466 break
467
467
468 tempname = bundle2.writebundle(self.ui, cg, None, type)
468 tempname = bundle2.writebundle(self.ui, cg, None, type)
469 fp = httpconnection.httpsendfile(self.ui, tempname, "rb")
469 fp = httpconnection.httpsendfile(self.ui, tempname, "rb")
470 headers = {r'Content-Type': r'application/mercurial-0.1'}
470 headers = {r'Content-Type': r'application/mercurial-0.1'}
471
471
472 try:
472 try:
473 r = self._call(cmd, data=fp, headers=headers, **args)
473 r = self._call(cmd, data=fp, headers=headers, **args)
474 vals = r.split('\n', 1)
474 vals = r.split('\n', 1)
475 if len(vals) < 2:
475 if len(vals) < 2:
476 raise error.ResponseError(_("unexpected response:"), r)
476 raise error.ResponseError(_("unexpected response:"), r)
477 return vals
477 return vals
478 except urlerr.httperror:
478 except urlerr.httperror:
479 # Catch and re-raise these so we don't try and treat them
479 # Catch and re-raise these so we don't try and treat them
480 # like generic socket errors. They lack any values in
480 # like generic socket errors. They lack any values in
481 # .args on Python 3 which breaks our socket.error block.
481 # .args on Python 3 which breaks our socket.error block.
482 raise
482 raise
483 except socket.error as err:
483 except socket.error as err:
484 if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
484 if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
485 raise error.Abort(_('push failed: %s') % err.args[1])
485 raise error.Abort(_('push failed: %s') % err.args[1])
486 raise error.Abort(err.args[1])
486 raise error.Abort(err.args[1])
487 finally:
487 finally:
488 fp.close()
488 fp.close()
489 os.unlink(tempname)
489 os.unlink(tempname)
490
490
491 def _calltwowaystream(self, cmd, fp, **args):
491 def _calltwowaystream(self, cmd, fp, **args):
492 fh = None
492 fh = None
493 fp_ = None
493 fp_ = None
494 filename = None
494 filename = None
495 try:
495 try:
496 # dump bundle to disk
496 # dump bundle to disk
497 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
497 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
498 fh = os.fdopen(fd, r"wb")
498 fh = os.fdopen(fd, r"wb")
499 d = fp.read(4096)
499 d = fp.read(4096)
500 while d:
500 while d:
501 fh.write(d)
501 fh.write(d)
502 d = fp.read(4096)
502 d = fp.read(4096)
503 fh.close()
503 fh.close()
504 # start http push
504 # start http push
505 fp_ = httpconnection.httpsendfile(self.ui, filename, "rb")
505 fp_ = httpconnection.httpsendfile(self.ui, filename, "rb")
506 headers = {r'Content-Type': r'application/mercurial-0.1'}
506 headers = {r'Content-Type': r'application/mercurial-0.1'}
507 return self._callstream(cmd, data=fp_, headers=headers, **args)
507 return self._callstream(cmd, data=fp_, headers=headers, **args)
508 finally:
508 finally:
509 if fp_ is not None:
509 if fp_ is not None:
510 fp_.close()
510 fp_.close()
511 if fh is not None:
511 if fh is not None:
512 fh.close()
512 fh.close()
513 os.unlink(filename)
513 os.unlink(filename)
514
514
515 def _callcompressable(self, cmd, **args):
515 def _callcompressable(self, cmd, **args):
516 return self._callstream(cmd, _compressible=True, **args)
516 return self._callstream(cmd, _compressible=True, **args)
517
517
518 def _abort(self, exception):
518 def _abort(self, exception):
519 raise exception
519 raise exception
520
520
521 def sendv2request(ui, opener, requestbuilder, apiurl, permission, requests):
521 def sendv2request(ui, opener, requestbuilder, apiurl, permission, requests):
522 reactor = wireprotoframing.clientreactor(hasmultiplesend=False,
522 reactor = wireprotoframing.clientreactor(hasmultiplesend=False,
523 buffersends=True)
523 buffersends=True)
524
524
525 url = '%s/%s' % (apiurl, permission)
525 url = '%s/%s' % (apiurl, permission)
526
526
527 if len(requests) > 1:
527 if len(requests) > 1:
528 url += '/multirequest'
528 url += '/multirequest'
529 else:
529 else:
530 url += '/%s' % requests[0][0]
530 url += '/%s' % requests[0][0]
531
531
532 # Request ID to (request, future)
532 # Request ID to (request, future)
533 requestmap = {}
533 requestmap = {}
534
534
535 for command, args, f in requests:
535 for command, args, f in requests:
536 request, action, meta = reactor.callcommand(command, args)
536 request, action, meta = reactor.callcommand(command, args)
537 assert action == 'noop'
537 assert action == 'noop'
538
538
539 requestmap[request.requestid] = (request, f)
539 requestmap[request.requestid] = (request, f)
540
540
541 action, meta = reactor.flushcommands()
541 action, meta = reactor.flushcommands()
542 assert action == 'sendframes'
542 assert action == 'sendframes'
543
543
544 # TODO stream this.
544 # TODO stream this.
545 body = b''.join(map(bytes, meta['framegen']))
545 body = b''.join(map(bytes, meta['framegen']))
546
546
547 # TODO modify user-agent to reflect v2
547 # TODO modify user-agent to reflect v2
548 headers = {
548 headers = {
549 r'Accept': wireprotov2server.FRAMINGTYPE,
549 r'Accept': wireprotov2server.FRAMINGTYPE,
550 r'Content-Type': wireprotov2server.FRAMINGTYPE,
550 r'Content-Type': wireprotov2server.FRAMINGTYPE,
551 }
551 }
552
552
553 req = requestbuilder(pycompat.strurl(url), body, headers)
553 req = requestbuilder(pycompat.strurl(url), body, headers)
554 req.add_unredirected_header(r'Content-Length', r'%d' % len(body))
554 req.add_unredirected_header(r'Content-Length', r'%d' % len(body))
555
555
556 try:
556 try:
557 res = opener.open(req)
557 res = opener.open(req)
558 except urlerr.httperror as e:
558 except urlerr.httperror as e:
559 if e.code == 401:
559 if e.code == 401:
560 raise error.Abort(_('authorization failed'))
560 raise error.Abort(_('authorization failed'))
561
561
562 raise
562 raise
563 except httplib.HTTPException as e:
563 except httplib.HTTPException as e:
564 ui.traceback()
564 ui.traceback()
565 raise IOError(None, e)
565 raise IOError(None, e)
566
566
567 return reactor, requestmap, res
567 return reactor, requestmap, res
568
568
569 class queuedcommandfuture(pycompat.futures.Future):
569 class queuedcommandfuture(pycompat.futures.Future):
570 """Wraps result() on command futures to trigger submission on call."""
570 """Wraps result() on command futures to trigger submission on call."""
571
571
572 def result(self, timeout=None):
572 def result(self, timeout=None):
573 if self.done():
573 if self.done():
574 return pycompat.futures.Future.result(self, timeout)
574 return pycompat.futures.Future.result(self, timeout)
575
575
576 self._peerexecutor.sendcommands()
576 self._peerexecutor.sendcommands()
577
577
578 # sendcommands() will restore the original __class__ and self.result
578 # sendcommands() will restore the original __class__ and self.result
579 # will resolve to Future.result.
579 # will resolve to Future.result.
580 return self.result(timeout)
580 return self.result(timeout)
581
581
582 @zi.implementer(repository.ipeercommandexecutor)
582 @zi.implementer(repository.ipeercommandexecutor)
583 class httpv2executor(object):
583 class httpv2executor(object):
584 def __init__(self, ui, opener, requestbuilder, apiurl, descriptor):
584 def __init__(self, ui, opener, requestbuilder, apiurl, descriptor):
585 self._ui = ui
585 self._ui = ui
586 self._opener = opener
586 self._opener = opener
587 self._requestbuilder = requestbuilder
587 self._requestbuilder = requestbuilder
588 self._apiurl = apiurl
588 self._apiurl = apiurl
589 self._descriptor = descriptor
589 self._descriptor = descriptor
590 self._sent = False
590 self._sent = False
591 self._closed = False
591 self._closed = False
592 self._neededpermissions = set()
592 self._neededpermissions = set()
593 self._calls = []
593 self._calls = []
594 self._futures = weakref.WeakSet()
594 self._futures = weakref.WeakSet()
595 self._responseexecutor = None
595 self._responseexecutor = None
596 self._responsef = None
596 self._responsef = None
597
597
598 def __enter__(self):
598 def __enter__(self):
599 return self
599 return self
600
600
601 def __exit__(self, exctype, excvalue, exctb):
601 def __exit__(self, exctype, excvalue, exctb):
602 self.close()
602 self.close()
603
603
604 def callcommand(self, command, args):
604 def callcommand(self, command, args):
605 if self._sent:
605 if self._sent:
606 raise error.ProgrammingError('callcommand() cannot be used after '
606 raise error.ProgrammingError('callcommand() cannot be used after '
607 'commands are sent')
607 'commands are sent')
608
608
609 if self._closed:
609 if self._closed:
610 raise error.ProgrammingError('callcommand() cannot be used after '
610 raise error.ProgrammingError('callcommand() cannot be used after '
611 'close()')
611 'close()')
612
612
613 # The service advertises which commands are available. So if we attempt
613 # The service advertises which commands are available. So if we attempt
614 # to call an unknown command or pass an unknown argument, we can screen
614 # to call an unknown command or pass an unknown argument, we can screen
615 # for this.
615 # for this.
616 if command not in self._descriptor['commands']:
616 if command not in self._descriptor['commands']:
617 raise error.ProgrammingError(
617 raise error.ProgrammingError(
618 'wire protocol command %s is not available' % command)
618 'wire protocol command %s is not available' % command)
619
619
620 cmdinfo = self._descriptor['commands'][command]
620 cmdinfo = self._descriptor['commands'][command]
621 unknownargs = set(args.keys()) - set(cmdinfo.get('args', {}))
621 unknownargs = set(args.keys()) - set(cmdinfo.get('args', {}))
622
622
623 if unknownargs:
623 if unknownargs:
624 raise error.ProgrammingError(
624 raise error.ProgrammingError(
625 'wire protocol command %s does not accept argument: %s' % (
625 'wire protocol command %s does not accept argument: %s' % (
626 command, ', '.join(sorted(unknownargs))))
626 command, ', '.join(sorted(unknownargs))))
627
627
628 self._neededpermissions |= set(cmdinfo['permissions'])
628 self._neededpermissions |= set(cmdinfo['permissions'])
629
629
630 # TODO we /could/ also validate types here, since the API descriptor
630 # TODO we /could/ also validate types here, since the API descriptor
631 # includes types...
631 # includes types...
632
632
633 f = pycompat.futures.Future()
633 f = pycompat.futures.Future()
634
634
635 # Monkeypatch it so result() triggers sendcommands(), otherwise result()
635 # Monkeypatch it so result() triggers sendcommands(), otherwise result()
636 # could deadlock.
636 # could deadlock.
637 f.__class__ = queuedcommandfuture
637 f.__class__ = queuedcommandfuture
638 f._peerexecutor = self
638 f._peerexecutor = self
639
639
640 self._futures.add(f)
640 self._futures.add(f)
641 self._calls.append((command, args, f))
641 self._calls.append((command, args, f))
642
642
643 return f
643 return f
644
644
645 def sendcommands(self):
645 def sendcommands(self):
646 if self._sent:
646 if self._sent:
647 return
647 return
648
648
649 if not self._calls:
649 if not self._calls:
650 return
650 return
651
651
652 self._sent = True
652 self._sent = True
653
653
654 # Unhack any future types so caller sees a clean type and so we
654 # Unhack any future types so caller sees a clean type and so we
655 # break reference cycle.
655 # break reference cycle.
656 for f in self._futures:
656 for f in self._futures:
657 if isinstance(f, queuedcommandfuture):
657 if isinstance(f, queuedcommandfuture):
658 f.__class__ = pycompat.futures.Future
658 f.__class__ = pycompat.futures.Future
659 f._peerexecutor = None
659 f._peerexecutor = None
660
660
661 # Mark the future as running and filter out cancelled futures.
661 # Mark the future as running and filter out cancelled futures.
662 calls = [(command, args, f)
662 calls = [(command, args, f)
663 for command, args, f in self._calls
663 for command, args, f in self._calls
664 if f.set_running_or_notify_cancel()]
664 if f.set_running_or_notify_cancel()]
665
665
666 # Clear out references, prevent improper object usage.
666 # Clear out references, prevent improper object usage.
667 self._calls = None
667 self._calls = None
668
668
669 if not calls:
669 if not calls:
670 return
670 return
671
671
672 permissions = set(self._neededpermissions)
672 permissions = set(self._neededpermissions)
673
673
674 if 'push' in permissions and 'pull' in permissions:
674 if 'push' in permissions and 'pull' in permissions:
675 permissions.remove('pull')
675 permissions.remove('pull')
676
676
677 if len(permissions) > 1:
677 if len(permissions) > 1:
678 raise error.RepoError(_('cannot make request requiring multiple '
678 raise error.RepoError(_('cannot make request requiring multiple '
679 'permissions: %s') %
679 'permissions: %s') %
680 _(', ').join(sorted(permissions)))
680 _(', ').join(sorted(permissions)))
681
681
682 permission = {
682 permission = {
683 'push': 'rw',
683 'push': 'rw',
684 'pull': 'ro',
684 'pull': 'ro',
685 }[permissions.pop()]
685 }[permissions.pop()]
686
686
687 reactor, requests, resp = sendv2request(
687 reactor, requests, resp = sendv2request(
688 self._ui, self._opener, self._requestbuilder, self._apiurl,
688 self._ui, self._opener, self._requestbuilder, self._apiurl,
689 permission, calls)
689 permission, calls)
690
690
691 # TODO we probably want to validate the HTTP code, media type, etc.
691 # TODO we probably want to validate the HTTP code, media type, etc.
692
692
693 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
693 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
694 self._responsef = self._responseexecutor.submit(self._handleresponse,
694 self._responsef = self._responseexecutor.submit(self._handleresponse,
695 reactor,
695 reactor,
696 requests,
696 requests,
697 resp)
697 resp)
698
698
699 def close(self):
699 def close(self):
700 if self._closed:
700 if self._closed:
701 return
701 return
702
702
703 self.sendcommands()
703 self.sendcommands()
704
704
705 self._closed = True
705 self._closed = True
706
706
707 if not self._responsef:
707 if not self._responsef:
708 return
708 return
709
709
710 try:
710 try:
711 self._responsef.result()
711 self._responsef.result()
712 finally:
712 finally:
713 self._responseexecutor.shutdown(wait=True)
713 self._responseexecutor.shutdown(wait=True)
714 self._responsef = None
714 self._responsef = None
715 self._responseexecutor = None
715 self._responseexecutor = None
716
716
717 # If any of our futures are still in progress, mark them as
717 # If any of our futures are still in progress, mark them as
718 # errored, otherwise a result() could wait indefinitely.
718 # errored, otherwise a result() could wait indefinitely.
719 for f in self._futures:
719 for f in self._futures:
720 if not f.done():
720 if not f.done():
721 f.set_exception(error.ResponseError(
721 f.set_exception(error.ResponseError(
722 _('unfulfilled command response')))
722 _('unfulfilled command response')))
723
723
724 self._futures = None
724 self._futures = None
725
725
726 def _handleresponse(self, reactor, requests, resp):
726 def _handleresponse(self, reactor, requests, resp):
727 # Called in a thread to read the response.
727 # Called in a thread to read the response.
728
728
729 results = {k: [] for k in requests}
729 results = {k: [] for k in requests}
730
730
731 while True:
731 while True:
732 frame = wireprotoframing.readframe(resp)
732 frame = wireprotoframing.readframe(resp)
733 if frame is None:
733 if frame is None:
734 break
734 break
735
735
736 self._ui.note(_('received %r\n') % frame)
736 self._ui.note(_('received %r\n') % frame)
737
737
738 # Guard against receiving a frame with a request ID that we
738 # Guard against receiving a frame with a request ID that we
739 # didn't issue. This should never happen.
739 # didn't issue. This should never happen.
740 request, f = requests.get(frame.requestid, [None, None])
740 request, f = requests.get(frame.requestid, [None, None])
741
741
742 action, meta = reactor.onframerecv(frame)
742 action, meta = reactor.onframerecv(frame)
743
743
744 if action == 'responsedata':
744 if action == 'responsedata':
745 assert request.requestid == meta['request'].requestid
745 assert request.requestid == meta['request'].requestid
746
746
747 result = results[request.requestid]
747 result = results[request.requestid]
748
748
749 if meta['cbor']:
749 if meta['cbor']:
750 payload = util.bytesio(meta['data'])
750 payload = util.bytesio(meta['data'])
751
751
752 decoder = cbor.CBORDecoder(payload)
752 decoder = cbor.CBORDecoder(payload)
753 while payload.tell() + 1 < len(meta['data']):
753 while payload.tell() + 1 < len(meta['data']):
754 try:
754 try:
755 result.append(decoder.decode())
755 result.append(decoder.decode())
756 except Exception:
756 except Exception:
757 f.set_exception_info(*sys.exc_info()[1:])
757 f.set_exception_info(*sys.exc_info()[1:])
758 continue
758 continue
759 else:
759 else:
760 result.append(meta['data'])
760 result.append(meta['data'])
761
761
762 if meta['eos']:
762 if meta['eos']:
763 f.set_result(result)
763 f.set_result(result)
764 del results[request.requestid]
764 del results[request.requestid]
765
765
766 elif action == 'error':
767 e = error.RepoError(meta['message'])
768
769 if f:
770 f.set_exception(e)
771 else:
772 raise e
773
766 else:
774 else:
767 e = error.ProgrammingError('unhandled action: %s' % action)
775 e = error.ProgrammingError('unhandled action: %s' % action)
768
776
769 if f:
777 if f:
770 f.set_exception(e)
778 f.set_exception(e)
771 else:
779 else:
772 raise e
780 raise e
773
781
774 # TODO implement interface for version 2 peers
782 # TODO implement interface for version 2 peers
775 @zi.implementer(repository.ipeerconnection, repository.ipeercapabilities,
783 @zi.implementer(repository.ipeerconnection, repository.ipeercapabilities,
776 repository.ipeerrequests)
784 repository.ipeerrequests)
777 class httpv2peer(object):
785 class httpv2peer(object):
778 def __init__(self, ui, repourl, apipath, opener, requestbuilder,
786 def __init__(self, ui, repourl, apipath, opener, requestbuilder,
779 apidescriptor):
787 apidescriptor):
780 self.ui = ui
788 self.ui = ui
781
789
782 if repourl.endswith('/'):
790 if repourl.endswith('/'):
783 repourl = repourl[:-1]
791 repourl = repourl[:-1]
784
792
785 self._url = repourl
793 self._url = repourl
786 self._apipath = apipath
794 self._apipath = apipath
787 self._apiurl = '%s/%s' % (repourl, apipath)
795 self._apiurl = '%s/%s' % (repourl, apipath)
788 self._opener = opener
796 self._opener = opener
789 self._requestbuilder = requestbuilder
797 self._requestbuilder = requestbuilder
790 self._descriptor = apidescriptor
798 self._descriptor = apidescriptor
791
799
792 # Start of ipeerconnection.
800 # Start of ipeerconnection.
793
801
794 def url(self):
802 def url(self):
795 return self._url
803 return self._url
796
804
797 def local(self):
805 def local(self):
798 return None
806 return None
799
807
800 def peer(self):
808 def peer(self):
801 return self
809 return self
802
810
803 def canpush(self):
811 def canpush(self):
804 # TODO change once implemented.
812 # TODO change once implemented.
805 return False
813 return False
806
814
807 def close(self):
815 def close(self):
808 pass
816 pass
809
817
810 # End of ipeerconnection.
818 # End of ipeerconnection.
811
819
812 # Start of ipeercapabilities.
820 # Start of ipeercapabilities.
813
821
814 def capable(self, name):
822 def capable(self, name):
815 # The capabilities used internally historically map to capabilities
823 # The capabilities used internally historically map to capabilities
816 # advertised from the "capabilities" wire protocol command. However,
824 # advertised from the "capabilities" wire protocol command. However,
817 # version 2 of that command works differently.
825 # version 2 of that command works differently.
818
826
819 # Maps to commands that are available.
827 # Maps to commands that are available.
820 if name in ('branchmap', 'getbundle', 'known', 'lookup', 'pushkey'):
828 if name in ('branchmap', 'getbundle', 'known', 'lookup', 'pushkey'):
821 return True
829 return True
822
830
823 # Other concepts.
831 # Other concepts.
824 if name in ('bundle2',):
832 if name in ('bundle2',):
825 return True
833 return True
826
834
827 return False
835 return False
828
836
829 def requirecap(self, name, purpose):
837 def requirecap(self, name, purpose):
830 if self.capable(name):
838 if self.capable(name):
831 return
839 return
832
840
833 raise error.CapabilityError(
841 raise error.CapabilityError(
834 _('cannot %s; client or remote repository does not support the %r '
842 _('cannot %s; client or remote repository does not support the %r '
835 'capability') % (purpose, name))
843 'capability') % (purpose, name))
836
844
837 # End of ipeercapabilities.
845 # End of ipeercapabilities.
838
846
839 def _call(self, name, **args):
847 def _call(self, name, **args):
840 with self.commandexecutor() as e:
848 with self.commandexecutor() as e:
841 return e.callcommand(name, args).result()
849 return e.callcommand(name, args).result()
842
850
843 def commandexecutor(self):
851 def commandexecutor(self):
844 return httpv2executor(self.ui, self._opener, self._requestbuilder,
852 return httpv2executor(self.ui, self._opener, self._requestbuilder,
845 self._apiurl, self._descriptor)
853 self._apiurl, self._descriptor)
846
854
847 # Registry of API service names to metadata about peers that handle it.
855 # Registry of API service names to metadata about peers that handle it.
848 #
856 #
849 # The following keys are meaningful:
857 # The following keys are meaningful:
850 #
858 #
851 # init
859 # init
852 # Callable receiving (ui, repourl, servicepath, opener, requestbuilder,
860 # Callable receiving (ui, repourl, servicepath, opener, requestbuilder,
853 # apidescriptor) to create a peer.
861 # apidescriptor) to create a peer.
854 #
862 #
855 # priority
863 # priority
856 # Integer priority for the service. If we could choose from multiple
864 # Integer priority for the service. If we could choose from multiple
857 # services, we choose the one with the highest priority.
865 # services, we choose the one with the highest priority.
858 API_PEERS = {
866 API_PEERS = {
859 wireprototypes.HTTP_WIREPROTO_V2: {
867 wireprototypes.HTTP_WIREPROTO_V2: {
860 'init': httpv2peer,
868 'init': httpv2peer,
861 'priority': 50,
869 'priority': 50,
862 },
870 },
863 }
871 }
864
872
865 def performhandshake(ui, url, opener, requestbuilder):
873 def performhandshake(ui, url, opener, requestbuilder):
866 # The handshake is a request to the capabilities command.
874 # The handshake is a request to the capabilities command.
867
875
868 caps = None
876 caps = None
869 def capable(x):
877 def capable(x):
870 raise error.ProgrammingError('should not be called')
878 raise error.ProgrammingError('should not be called')
871
879
872 args = {}
880 args = {}
873
881
874 # The client advertises support for newer protocols by adding an
882 # The client advertises support for newer protocols by adding an
875 # X-HgUpgrade-* header with a list of supported APIs and an
883 # X-HgUpgrade-* header with a list of supported APIs and an
876 # X-HgProto-* header advertising which serializing formats it supports.
884 # X-HgProto-* header advertising which serializing formats it supports.
877 # We only support the HTTP version 2 transport and CBOR responses for
885 # We only support the HTTP version 2 transport and CBOR responses for
878 # now.
886 # now.
879 advertisev2 = ui.configbool('experimental', 'httppeer.advertise-v2')
887 advertisev2 = ui.configbool('experimental', 'httppeer.advertise-v2')
880
888
881 if advertisev2:
889 if advertisev2:
882 args['headers'] = {
890 args['headers'] = {
883 r'X-HgProto-1': r'cbor',
891 r'X-HgProto-1': r'cbor',
884 }
892 }
885
893
886 args['headers'].update(
894 args['headers'].update(
887 encodevalueinheaders(' '.join(sorted(API_PEERS)),
895 encodevalueinheaders(' '.join(sorted(API_PEERS)),
888 'X-HgUpgrade',
896 'X-HgUpgrade',
889 # We don't know the header limit this early.
897 # We don't know the header limit this early.
890 # So make it small.
898 # So make it small.
891 1024))
899 1024))
892
900
893 req, requrl, qs = makev1commandrequest(ui, requestbuilder, caps,
901 req, requrl, qs = makev1commandrequest(ui, requestbuilder, caps,
894 capable, url, 'capabilities',
902 capable, url, 'capabilities',
895 args)
903 args)
896
904
897 resp = sendrequest(ui, opener, req)
905 resp = sendrequest(ui, opener, req)
898
906
899 respurl, ct, resp = parsev1commandresponse(ui, url, requrl, qs, resp,
907 respurl, ct, resp = parsev1commandresponse(ui, url, requrl, qs, resp,
900 compressible=False,
908 compressible=False,
901 allowcbor=advertisev2)
909 allowcbor=advertisev2)
902
910
903 try:
911 try:
904 rawdata = resp.read()
912 rawdata = resp.read()
905 finally:
913 finally:
906 resp.close()
914 resp.close()
907
915
908 if not ct.startswith('application/mercurial-'):
916 if not ct.startswith('application/mercurial-'):
909 raise error.ProgrammingError('unexpected content-type: %s' % ct)
917 raise error.ProgrammingError('unexpected content-type: %s' % ct)
910
918
911 if advertisev2:
919 if advertisev2:
912 if ct == 'application/mercurial-cbor':
920 if ct == 'application/mercurial-cbor':
913 try:
921 try:
914 info = cbor.loads(rawdata)
922 info = cbor.loads(rawdata)
915 except cbor.CBORDecodeError:
923 except cbor.CBORDecodeError:
916 raise error.Abort(_('error decoding CBOR from remote server'),
924 raise error.Abort(_('error decoding CBOR from remote server'),
917 hint=_('try again and consider contacting '
925 hint=_('try again and consider contacting '
918 'the server operator'))
926 'the server operator'))
919
927
920 # We got a legacy response. That's fine.
928 # We got a legacy response. That's fine.
921 elif ct in ('application/mercurial-0.1', 'application/mercurial-0.2'):
929 elif ct in ('application/mercurial-0.1', 'application/mercurial-0.2'):
922 info = {
930 info = {
923 'v1capabilities': set(rawdata.split())
931 'v1capabilities': set(rawdata.split())
924 }
932 }
925
933
926 else:
934 else:
927 raise error.RepoError(
935 raise error.RepoError(
928 _('unexpected response type from server: %s') % ct)
936 _('unexpected response type from server: %s') % ct)
929 else:
937 else:
930 info = {
938 info = {
931 'v1capabilities': set(rawdata.split())
939 'v1capabilities': set(rawdata.split())
932 }
940 }
933
941
934 return respurl, info
942 return respurl, info
935
943
936 def makepeer(ui, path, opener=None, requestbuilder=urlreq.request):
944 def makepeer(ui, path, opener=None, requestbuilder=urlreq.request):
937 """Construct an appropriate HTTP peer instance.
945 """Construct an appropriate HTTP peer instance.
938
946
939 ``opener`` is an ``url.opener`` that should be used to establish
947 ``opener`` is an ``url.opener`` that should be used to establish
940 connections, perform HTTP requests.
948 connections, perform HTTP requests.
941
949
942 ``requestbuilder`` is the type used for constructing HTTP requests.
950 ``requestbuilder`` is the type used for constructing HTTP requests.
943 It exists as an argument so extensions can override the default.
951 It exists as an argument so extensions can override the default.
944 """
952 """
945 u = util.url(path)
953 u = util.url(path)
946 if u.query or u.fragment:
954 if u.query or u.fragment:
947 raise error.Abort(_('unsupported URL component: "%s"') %
955 raise error.Abort(_('unsupported URL component: "%s"') %
948 (u.query or u.fragment))
956 (u.query or u.fragment))
949
957
950 # urllib cannot handle URLs with embedded user or passwd.
958 # urllib cannot handle URLs with embedded user or passwd.
951 url, authinfo = u.authinfo()
959 url, authinfo = u.authinfo()
952 ui.debug('using %s\n' % url)
960 ui.debug('using %s\n' % url)
953
961
954 opener = opener or urlmod.opener(ui, authinfo)
962 opener = opener or urlmod.opener(ui, authinfo)
955
963
956 respurl, info = performhandshake(ui, url, opener, requestbuilder)
964 respurl, info = performhandshake(ui, url, opener, requestbuilder)
957
965
958 # Given the intersection of APIs that both we and the server support,
966 # Given the intersection of APIs that both we and the server support,
959 # sort by their advertised priority and pick the first one.
967 # sort by their advertised priority and pick the first one.
960 #
968 #
961 # TODO consider making this request-based and interface driven. For
969 # TODO consider making this request-based and interface driven. For
962 # example, the caller could say "I want a peer that does X." It's quite
970 # example, the caller could say "I want a peer that does X." It's quite
963 # possible that not all peers would do that. Since we know the service
971 # possible that not all peers would do that. Since we know the service
964 # capabilities, we could filter out services not meeting the
972 # capabilities, we could filter out services not meeting the
965 # requirements. Possibly by consulting the interfaces defined by the
973 # requirements. Possibly by consulting the interfaces defined by the
966 # peer type.
974 # peer type.
967 apipeerchoices = set(info.get('apis', {}).keys()) & set(API_PEERS.keys())
975 apipeerchoices = set(info.get('apis', {}).keys()) & set(API_PEERS.keys())
968
976
969 preferredchoices = sorted(apipeerchoices,
977 preferredchoices = sorted(apipeerchoices,
970 key=lambda x: API_PEERS[x]['priority'],
978 key=lambda x: API_PEERS[x]['priority'],
971 reverse=True)
979 reverse=True)
972
980
973 for service in preferredchoices:
981 for service in preferredchoices:
974 apipath = '%s/%s' % (info['apibase'].rstrip('/'), service)
982 apipath = '%s/%s' % (info['apibase'].rstrip('/'), service)
975
983
976 return API_PEERS[service]['init'](ui, respurl, apipath, opener,
984 return API_PEERS[service]['init'](ui, respurl, apipath, opener,
977 requestbuilder,
985 requestbuilder,
978 info['apis'][service])
986 info['apis'][service])
979
987
980 # Failed to construct an API peer. Fall back to legacy.
988 # Failed to construct an API peer. Fall back to legacy.
981 return httppeer(ui, path, respurl, opener, requestbuilder,
989 return httppeer(ui, path, respurl, opener, requestbuilder,
982 info['v1capabilities'])
990 info['v1capabilities'])
983
991
984 def instance(ui, path, create):
992 def instance(ui, path, create):
985 if create:
993 if create:
986 raise error.Abort(_('cannot create new http repository'))
994 raise error.Abort(_('cannot create new http repository'))
987 try:
995 try:
988 if path.startswith('https:') and not urlmod.has_https:
996 if path.startswith('https:') and not urlmod.has_https:
989 raise error.Abort(_('Python support for SSL and HTTPS '
997 raise error.Abort(_('Python support for SSL and HTTPS '
990 'is not installed'))
998 'is not installed'))
991
999
992 inst = makepeer(ui, path)
1000 inst = makepeer(ui, path)
993
1001
994 return inst
1002 return inst
995 except error.RepoError as httpexception:
1003 except error.RepoError as httpexception:
996 try:
1004 try:
997 r = statichttprepo.instance(ui, "static-" + path, create)
1005 r = statichttprepo.instance(ui, "static-" + path, create)
998 ui.note(_('(falling back to static-http)\n'))
1006 ui.note(_('(falling back to static-http)\n'))
999 return r
1007 return r
1000 except error.RepoError:
1008 except error.RepoError:
1001 raise httpexception # use the original http RepoError instead
1009 raise httpexception # use the original http RepoError instead
General Comments 0
You need to be logged in to leave comments. Login now