/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/bzr/smart/client.py

  • Committer: Martin
  • Date: 2018-08-21 00:53:34 UTC
  • mto: This revision was merged to the branch mainline in revision 7074.
  • Revision ID: gzlist@googlemail.com-20180821005334-e1ogxakojyybpwib
Fix recursion check in C bencode implementation

Hard to get Cython to do the right thing but by inverting the
return code can use the standard except handling.

Avoid going through a Python call when encoding, which requires
the encode recursion check to work too.

Adjust tests to use a smaller limit to be more managable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
import bzrlib
18
 
from bzrlib.smart import message, protocol
19
 
from bzrlib.trace import warning
20
 
from bzrlib import (
 
17
from __future__ import absolute_import
 
18
 
 
19
from ... import lazy_import
 
20
lazy_import.lazy_import(globals(), """
 
21
from breezy.bzr.smart import request as _mod_request
 
22
""")
 
23
 
 
24
import breezy
 
25
from . import message, protocol
 
26
from ... import (
 
27
    debug,
21
28
    errors,
22
29
    hooks,
 
30
    trace,
23
31
    )
24
32
 
25
33
 
32
40
        """
33
41
        self._medium = medium
34
42
        if headers is None:
35
 
            self._headers = {'Software version': bzrlib.__version__}
 
43
            self._headers = {b'Software version': breezy.__version__.encode('utf-8')}
36
44
        else:
37
45
            self._headers = dict(headers)
38
46
 
39
47
    def __repr__(self):
40
48
        return '%s(%r)' % (self.__class__.__name__, self._medium)
41
49
 
42
 
    def _send_request(self, protocol_version, method, args, body=None,
43
 
                      readv_body=None, body_stream=None):
44
 
        encoder, response_handler = self._construct_protocol(
45
 
            protocol_version)
46
 
        encoder.set_headers(self._headers)
47
 
        if body is not None:
48
 
            if readv_body is not None:
49
 
                raise AssertionError(
50
 
                    "body and readv_body are mutually exclusive.")
51
 
            if body_stream is not None:
52
 
                raise AssertionError(
53
 
                    "body and body_stream are mutually exclusive.")
54
 
            encoder.call_with_body_bytes((method, ) + args, body)
55
 
        elif readv_body is not None:
56
 
            if body_stream is not None:
57
 
                raise AssertionError(
58
 
                    "readv_body and body_stream are mutually exclusive.")
59
 
            encoder.call_with_body_readv_array((method, ) + args, readv_body)
60
 
        elif body_stream is not None:
61
 
            encoder.call_with_body_stream((method, ) + args, body_stream)
62
 
        else:
63
 
            encoder.call(method, *args)
64
 
        return response_handler
65
 
 
66
 
    def _run_call_hooks(self, method, args, body, readv_body):
67
 
        if not _SmartClient.hooks['call']:
68
 
            return
69
 
        params = CallHookParams(method, args, body, readv_body, self._medium)
70
 
        for hook in _SmartClient.hooks['call']:
71
 
            hook(params)
72
 
 
73
50
    def _call_and_read_response(self, method, args, body=None, readv_body=None,
74
51
            body_stream=None, expect_response_body=True):
75
 
        self._run_call_hooks(method, args, body, readv_body)
76
 
        if self._medium._protocol_version is not None:
77
 
            response_handler = self._send_request(
78
 
                self._medium._protocol_version, method, args, body=body,
79
 
                readv_body=readv_body, body_stream=body_stream)
80
 
            return (response_handler.read_response_tuple(
81
 
                        expect_body=expect_response_body),
82
 
                    response_handler)
83
 
        else:
84
 
            for protocol_version in [3, 2]:
85
 
                if protocol_version == 2:
86
 
                    # If v3 doesn't work, the remote side is older than 1.6.
87
 
                    self._medium._remember_remote_is_before((1, 6))
88
 
                response_handler = self._send_request(
89
 
                    protocol_version, method, args, body=body,
90
 
                    readv_body=readv_body, body_stream=body_stream)
91
 
                try:
92
 
                    response_tuple = response_handler.read_response_tuple(
93
 
                        expect_body=expect_response_body)
94
 
                except errors.UnexpectedProtocolVersionMarker, err:
95
 
                    # TODO: We could recover from this without disconnecting if
96
 
                    # we recognise the protocol version.
97
 
                    warning(
98
 
                        'Server does not understand Bazaar network protocol %d,'
99
 
                        ' reconnecting.  (Upgrade the server to avoid this.)'
100
 
                        % (protocol_version,))
101
 
                    self._medium.disconnect()
102
 
                    continue
103
 
                except errors.ErrorFromSmartServer:
104
 
                    # If we received an error reply from the server, then it
105
 
                    # must be ok with this protocol version.
106
 
                    self._medium._protocol_version = protocol_version
107
 
                    raise
108
 
                else:
109
 
                    self._medium._protocol_version = protocol_version
110
 
                    return response_tuple, response_handler
111
 
            raise errors.SmartProtocolError(
112
 
                'Server is not a Bazaar server: ' + str(err))
113
 
 
114
 
    def _construct_protocol(self, version):
115
 
        request = self._medium.get_request()
116
 
        if version == 3:
117
 
            request_encoder = protocol.ProtocolThreeRequester(request)
118
 
            response_handler = message.ConventionalResponseHandler()
119
 
            response_proto = protocol.ProtocolThreeDecoder(
120
 
                response_handler, expect_version_marker=True)
121
 
            response_handler.setProtoAndMediumRequest(response_proto, request)
122
 
        elif version == 2:
123
 
            request_encoder = protocol.SmartClientRequestProtocolTwo(request)
124
 
            response_handler = request_encoder
125
 
        else:
126
 
            request_encoder = protocol.SmartClientRequestProtocolOne(request)
127
 
            response_handler = request_encoder
128
 
        return request_encoder, response_handler
 
52
        request = _SmartClientRequest(self, method, args, body=body,
 
53
            readv_body=readv_body, body_stream=body_stream,
 
54
            expect_response_body=expect_response_body)
 
55
        return request.call_and_read_response()
129
56
 
130
57
    def call(self, method, *args):
131
58
        """Call a method on the remote server."""
146
73
 
147
74
    def call_with_body_bytes(self, method, args, body):
148
75
        """Call a method on the remote server with body bytes."""
149
 
        if type(method) is not str:
 
76
        if not isinstance(method, bytes):
150
77
            raise TypeError('method must be a byte string, not %r' % (method,))
151
78
        for arg in args:
152
 
            if type(arg) is not str:
 
79
            if not isinstance(arg, bytes):
153
80
                raise TypeError('args must be byte strings, not %r' % (args,))
154
 
        if type(body) is not str:
 
81
        if not isinstance(body, bytes):
155
82
            raise TypeError('body must be byte string, not %r' % (body,))
156
83
        response, response_handler = self._call_and_read_response(
157
84
            method, args, body=body, expect_response_body=False)
159
86
 
160
87
    def call_with_body_bytes_expecting_body(self, method, args, body):
161
88
        """Call a method on the remote server with body bytes."""
162
 
        if type(method) is not str:
 
89
        if not isinstance(method, bytes):
163
90
            raise TypeError('method must be a byte string, not %r' % (method,))
164
91
        for arg in args:
165
 
            if type(arg) is not str:
 
92
            if not isinstance(arg, bytes):
166
93
                raise TypeError('args must be byte strings, not %r' % (args,))
167
 
        if type(body) is not str:
 
94
        if not isinstance(body, bytes):
168
95
            raise TypeError('body must be byte string, not %r' % (body,))
169
96
        response, response_handler = self._call_and_read_response(
170
97
            method, args, body=body, expect_response_body=True)
188
115
        anything but path, so it is only safe to use it in requests sent over
189
116
        the medium from the matching transport.
190
117
        """
191
 
        return self._medium.remote_path_from_transport(transport)
 
118
        return self._medium.remote_path_from_transport(transport).encode('utf-8')
 
119
 
 
120
 
 
121
class _SmartClientRequest(object):
 
122
    """Encapsulate the logic for a single request.
 
123
 
 
124
    This class handles things like reconnecting and sending the request a
 
125
    second time when the connection is reset in the middle. It also handles the
 
126
    multiple requests that get made if we don't know what protocol the server
 
127
    supports yet.
 
128
 
 
129
    Generally, you build up one of these objects, passing in the arguments that
 
130
    you want to send to the server, and then use 'call_and_read_response' to
 
131
    get the response from the server.
 
132
    """
 
133
 
 
134
    def __init__(self, client, method, args, body=None, readv_body=None,
 
135
                 body_stream=None, expect_response_body=True):
 
136
        self.client = client
 
137
        self.method = method
 
138
        self.args = args
 
139
        self.body = body
 
140
        self.readv_body = readv_body
 
141
        self.body_stream = body_stream
 
142
        self.expect_response_body = expect_response_body
 
143
 
 
144
    def call_and_read_response(self):
 
145
        """Send the request to the server, and read the initial response.
 
146
 
 
147
        This doesn't read all of the body content of the response, instead it
 
148
        returns (response_tuple, response_handler). response_tuple is the 'ok',
 
149
        or 'error' information, and 'response_handler' can be used to get the
 
150
        content stream out.
 
151
        """
 
152
        self._run_call_hooks()
 
153
        protocol_version = self.client._medium._protocol_version
 
154
        if protocol_version is None:
 
155
            return self._call_determining_protocol_version()
 
156
        else:
 
157
            return self._call(protocol_version)
 
158
 
 
159
    def _is_safe_to_send_twice(self):
 
160
        """Check if the current method is re-entrant safe."""
 
161
        if self.body_stream is not None or 'noretry' in debug.debug_flags:
 
162
            # We can't restart a body stream that has already been consumed.
 
163
            return False
 
164
        request_type = _mod_request.request_handlers.get_info(self.method)
 
165
        if request_type in ('read', 'idem', 'semi'):
 
166
            return True
 
167
        # If we have gotten this far, 'stream' cannot be retried, because we
 
168
        # already consumed the local stream.
 
169
        if request_type in ('semivfs', 'mutate', 'stream'):
 
170
            return False
 
171
        trace.mutter('Unknown request type: %s for method %s'
 
172
                     % (request_type, self.method))
 
173
        return False
 
174
 
 
175
    def _run_call_hooks(self):
 
176
        if not _SmartClient.hooks['call']:
 
177
            return
 
178
        params = CallHookParams(self.method, self.args, self.body,
 
179
                                self.readv_body, self.client._medium)
 
180
        for hook in _SmartClient.hooks['call']:
 
181
            hook(params)
 
182
 
 
183
    def _call(self, protocol_version):
 
184
        """We know the protocol version.
 
185
 
 
186
        So this just sends the request, and then reads the response. This is
 
187
        where the code will be to retry requests if the connection is closed.
 
188
        """
 
189
        response_handler = self._send(protocol_version)
 
190
        try:
 
191
            response_tuple = response_handler.read_response_tuple(
 
192
                expect_body=self.expect_response_body)
 
193
        except errors.ConnectionReset as e:
 
194
            self.client._medium.reset()
 
195
            if not self._is_safe_to_send_twice():
 
196
                raise
 
197
            trace.warning('ConnectionReset reading response for %r, retrying'
 
198
                          % (self.method,))
 
199
            trace.log_exception_quietly()
 
200
            encoder, response_handler = self._construct_protocol(
 
201
                protocol_version)
 
202
            self._send_no_retry(encoder)
 
203
            response_tuple = response_handler.read_response_tuple(
 
204
                expect_body=self.expect_response_body)
 
205
        return (response_tuple, response_handler)
 
206
 
 
207
    def _call_determining_protocol_version(self):
 
208
        """Determine what protocol the remote server supports.
 
209
 
 
210
        We do this by placing a request in the most recent protocol, and
 
211
        handling the UnexpectedProtocolVersionMarker from the server.
 
212
        """
 
213
        last_err = None
 
214
        for protocol_version in [3, 2]:
 
215
            if protocol_version == 2:
 
216
                # If v3 doesn't work, the remote side is older than 1.6.
 
217
                self.client._medium._remember_remote_is_before((1, 6))
 
218
            try:
 
219
                response_tuple, response_handler = self._call(protocol_version)
 
220
            except errors.UnexpectedProtocolVersionMarker as err:
 
221
                # TODO: We could recover from this without disconnecting if
 
222
                # we recognise the protocol version.
 
223
                trace.warning(
 
224
                    'Server does not understand Bazaar network protocol %d,'
 
225
                    ' reconnecting.  (Upgrade the server to avoid this.)'
 
226
                    % (protocol_version,))
 
227
                self.client._medium.disconnect()
 
228
                last_err = err
 
229
                continue
 
230
            except errors.ErrorFromSmartServer:
 
231
                # If we received an error reply from the server, then it
 
232
                # must be ok with this protocol version.
 
233
                self.client._medium._protocol_version = protocol_version
 
234
                raise
 
235
            else:
 
236
                self.client._medium._protocol_version = protocol_version
 
237
                return response_tuple, response_handler
 
238
        raise errors.SmartProtocolError(
 
239
            'Server is not a Bazaar server: ' + str(last_err))
 
240
 
 
241
    def _construct_protocol(self, version):
 
242
        """Build the encoding stack for a given protocol version."""
 
243
        request = self.client._medium.get_request()
 
244
        if version == 3:
 
245
            request_encoder = protocol.ProtocolThreeRequester(request)
 
246
            response_handler = message.ConventionalResponseHandler()
 
247
            response_proto = protocol.ProtocolThreeDecoder(
 
248
                response_handler, expect_version_marker=True)
 
249
            response_handler.setProtoAndMediumRequest(response_proto, request)
 
250
        elif version == 2:
 
251
            request_encoder = protocol.SmartClientRequestProtocolTwo(request)
 
252
            response_handler = request_encoder
 
253
        else:
 
254
            request_encoder = protocol.SmartClientRequestProtocolOne(request)
 
255
            response_handler = request_encoder
 
256
        return request_encoder, response_handler
 
257
 
 
258
    def _send(self, protocol_version):
 
259
        """Encode the request, and send it to the server.
 
260
 
 
261
        This will retry a request if we get a ConnectionReset while sending the
 
262
        request to the server. (Unless we have a body_stream that we have
 
263
        already started consuming, since we can't restart body_streams)
 
264
 
 
265
        :return: response_handler as defined by _construct_protocol
 
266
        """
 
267
        encoder, response_handler = self._construct_protocol(protocol_version)
 
268
        try:
 
269
            self._send_no_retry(encoder)
 
270
        except errors.ConnectionReset as e:
 
271
            # If we fail during the _send_no_retry phase, then we can
 
272
            # be confident that the server did not get our request, because we
 
273
            # haven't started waiting for the reply yet. So try the request
 
274
            # again. We only issue a single retry, because if the connection
 
275
            # really is down, there is no reason to loop endlessly.
 
276
 
 
277
            # Connection is dead, so close our end of it.
 
278
            self.client._medium.reset()
 
279
            if (('noretry' in debug.debug_flags)
 
280
                or (self.body_stream is not None
 
281
                    and encoder.body_stream_started)):
 
282
                # We can't restart a body_stream that has been partially
 
283
                # consumed, so we don't retry.
 
284
                # Note: We don't have to worry about
 
285
                #   SmartClientRequestProtocolOne or Two, because they don't
 
286
                #   support client-side body streams.
 
287
                raise
 
288
            trace.warning('ConnectionReset calling %r, retrying'
 
289
                          % (self.method,))
 
290
            trace.log_exception_quietly()
 
291
            encoder, response_handler = self._construct_protocol(
 
292
                protocol_version)
 
293
            self._send_no_retry(encoder)
 
294
        return response_handler
 
295
 
 
296
    def _send_no_retry(self, encoder):
 
297
        """Just encode the request and try to send it."""
 
298
        encoder.set_headers(self.client._headers)
 
299
        if self.body is not None:
 
300
            if self.readv_body is not None:
 
301
                raise AssertionError(
 
302
                    "body and readv_body are mutually exclusive.")
 
303
            if self.body_stream is not None:
 
304
                raise AssertionError(
 
305
                    "body and body_stream are mutually exclusive.")
 
306
            encoder.call_with_body_bytes((self.method, ) + self.args, self.body)
 
307
        elif self.readv_body is not None:
 
308
            if self.body_stream is not None:
 
309
                raise AssertionError(
 
310
                    "readv_body and body_stream are mutually exclusive.")
 
311
            encoder.call_with_body_readv_array((self.method, ) + self.args,
 
312
                                               self.readv_body)
 
313
        elif self.body_stream is not None:
 
314
            encoder.call_with_body_stream((self.method, ) + self.args,
 
315
                                          self.body_stream)
 
316
        else:
 
317
            encoder.call(self.method, *self.args)
192
318
 
193
319
 
194
320
class SmartClientHooks(hooks.Hooks):
195
321
 
196
322
    def __init__(self):
197
 
        hooks.Hooks.__init__(self)
198
 
        self.create_hook(hooks.HookPoint('call',
 
323
        hooks.Hooks.__init__(self, "breezy.bzr.smart.client", "_SmartClient.hooks")
 
324
        self.add_hook('call',
199
325
            "Called when the smart client is submitting a request to the "
200
 
            "smart server. Called with a bzrlib.smart.client.CallHookParams "
 
326
            "smart server. Called with a breezy.bzr.smart.client.CallHookParams "
201
327
            "object. Streaming request bodies, and responses, are not "
202
 
            "accessible.", None, None))
 
328
            "accessible.", None)
203
329
 
204
330
 
205
331
_SmartClient.hooks = SmartClientHooks()
215
341
        self.medium = medium
216
342
 
217
343
    def __repr__(self):
218
 
        attrs = dict((k, v) for (k, v) in self.__dict__.iteritems()
 
344
        attrs = dict((k, v) for k, v in self.__dict__.items()
219
345
                     if v is not None)
220
346
        return '<%s %r>' % (self.__class__.__name__, attrs)
221
347
 
222
348
    def __eq__(self, other):
223
 
        if type(other) is not type(self):
 
349
        if not isinstance(other, type(self)):
224
350
            return NotImplemented
225
351
        return self.__dict__ == other.__dict__
226
352