~bzr-pqm/bzr/bzr.dev

2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1
# Copyright (C) 2006 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
17
"""The 'medium' layer for the smart servers and clients.
18
19
"Medium" here is the noun meaning "a means of transmission", not the adjective
20
for "the quality between big and small."
21
22
Media carry the bytes of the requests somehow (e.g. via TCP, wrapped in HTTP, or
23
over SSH), and pass them to and from the protocol logic.  See the overview in
24
bzrlib/transport/smart/__init__.py.
25
"""
26
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
27
import os
28
import socket
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
29
import sys
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
30
import urllib
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
31
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
32
from bzrlib import (
33
    errors,
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
34
    osutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
35
    symbol_versioning,
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
36
    urlutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
37
    )
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
38
from bzrlib.smart.protocol import (
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
39
    MESSAGE_VERSION_THREE,
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
40
    REQUEST_VERSION_TWO,
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
41
    SmartClientRequestProtocolOne,
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
42
    SmartServerRequestProtocolOne,
43
    SmartServerRequestProtocolTwo,
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
44
    build_server_protocol_three
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
45
    )
3066.2.1 by John Arbash Meinel
We don't require paramiko for bzr+ssh.
46
from bzrlib.transport import ssh
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
47
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
48
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
49
def _get_protocol_factory_for_bytes(bytes):
50
    """Determine the right protocol factory for 'bytes'.
51
52
    This will return an appropriate protocol factory depending on the version
53
    of the protocol being used, as determined by inspecting the given bytes.
54
    The bytes should have at least one newline byte (i.e. be a whole line),
55
    otherwise it's possible that a request will be incorrectly identified as
56
    version 1.
57
58
    Typical use would be::
59
60
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
61
         server_protocol = factory(transport, write_func, root_client_path)
62
         server_protocol.accept_bytes(unused_bytes)
63
64
    :param bytes: a str of bytes of the start of the request.
65
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
66
        a callable that takes three args: transport, write_func,
67
        root_client_path.  unused_bytes are any bytes that were not part of a
68
        protocol version marker.
69
    """
70
    if bytes.startswith(MESSAGE_VERSION_THREE):
71
        protocol_factory = build_server_protocol_three
72
        bytes = bytes[len(MESSAGE_VERSION_THREE):]
73
    elif bytes.startswith(REQUEST_VERSION_TWO):
74
        protocol_factory = SmartServerRequestProtocolTwo
75
        bytes = bytes[len(REQUEST_VERSION_TWO):]
76
    else:
77
        protocol_factory = SmartServerRequestProtocolOne
78
    return protocol_factory, bytes
79
80
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
81
class SmartServerStreamMedium(object):
82
    """Handles smart commands coming over a stream.
83
84
    The stream may be a pipe connected to sshd, or a tcp socket, or an
85
    in-process fifo for testing.
86
87
    One instance is created for each connected client; it can serve multiple
88
    requests in the lifetime of the connection.
89
90
    The server passes requests through to an underlying backing transport, 
91
    which will typically be a LocalTransport looking at the server's filesystem.
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
92
93
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
94
        but not used yet, or None if there are no buffered bytes.  Subclasses
95
        should make sure to exhaust this buffer before reading more bytes from
96
        the stream.  See also the _push_back method.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
97
    """
98
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
99
    def __init__(self, backing_transport, root_client_path='/'):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
100
        """Construct new server.
101
102
        :param backing_transport: Transport for the directory served.
103
        """
104
        # backing_transport could be passed to serve instead of __init__
105
        self.backing_transport = backing_transport
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
106
        self.root_client_path = root_client_path
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
107
        self.finished = False
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
108
        self._push_back_buffer = None
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
109
110
    def _push_back(self, bytes):
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
111
        """Return unused bytes to the medium, because they belong to the next
112
        request(s).
113
114
        This sets the _push_back_buffer to the given bytes.
115
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
116
        if self._push_back_buffer is not None:
117
            raise AssertionError(
118
                "_push_back called when self._push_back_buffer is %r"
119
                % (self._push_back_buffer,))
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
120
        if bytes == '':
121
            return
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
122
        self._push_back_buffer = bytes
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
123
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
124
    def _get_push_back_buffer(self):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
125
        if self._push_back_buffer == '':
126
            raise AssertionError(
127
                '%s._push_back_buffer should never be the empty string, '
128
                'which can be confused with EOF' % (self,))
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
129
        bytes = self._push_back_buffer
130
        self._push_back_buffer = None
131
        return bytes
132
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
133
    def serve(self):
134
        """Serve requests until the client disconnects."""
135
        # Keep a reference to stderr because the sys module's globals get set to
136
        # None during interpreter shutdown.
137
        from sys import stderr
138
        try:
139
            while not self.finished:
2432.2.3 by Andrew Bennetts
Merge from bzr.dev.
140
                server_protocol = self._build_protocol()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
141
                self._serve_one_request(server_protocol)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
142
        except Exception, e:
143
            stderr.write("%s terminating on exception %s\n" % (self, e))
144
            raise
145
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
146
    def _build_protocol(self):
2432.2.8 by Andrew Bennetts
NEWS entry, greatly improved docstring in bzrlib.smart.
147
        """Identifies the version of the incoming request, and returns an
148
        a protocol object that can interpret it.
149
150
        If more bytes than the version prefix of the request are read, they will
151
        be fed into the protocol before it is returned.
152
153
        :returns: a SmartServerRequestProtocol.
154
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
155
        bytes = self._get_line()
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
156
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
157
        protocol = protocol_factory(
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
158
            self.backing_transport, self._write_out, self.root_client_path)
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
159
        protocol.accept_bytes(unused_bytes)
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
160
        return protocol
161
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
162
    def _serve_one_request(self, protocol):
163
        """Read one request from input, process, send back a response.
164
        
165
        :param protocol: a SmartServerRequestProtocol.
166
        """
167
        try:
168
            self._serve_one_request_unguarded(protocol)
169
        except KeyboardInterrupt:
170
            raise
171
        except Exception, e:
172
            self.terminate_due_to_error()
173
174
    def terminate_due_to_error(self):
175
        """Called when an unhandled exception from the protocol occurs."""
176
        raise NotImplementedError(self.terminate_due_to_error)
177
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
178
    def _get_bytes(self, desired_count):
179
        """Get some bytes from the medium.
180
181
        :param desired_count: number of bytes we want to read.
182
        """
183
        raise NotImplementedError(self._get_bytes)
184
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
185
    def _get_line(self):
186
        """Read bytes from this request's response until a newline byte.
187
        
188
        This isn't particularly efficient, so should only be used when the
189
        expected size of the line is quite short.
190
191
        :returns: a string of bytes ending in a newline (byte 0x0A).
192
        """
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
193
        newline_pos = -1
194
        bytes = ''
195
        while newline_pos == -1:
196
            new_bytes = self._get_bytes(1)
197
            bytes += new_bytes
198
            if new_bytes == '':
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
199
                # Ran out of bytes before receiving a complete line.
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
200
                return bytes
201
            newline_pos = bytes.find('\n')
202
        line = bytes[:newline_pos+1]
203
        self._push_back(bytes[newline_pos+1:])
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
204
        return line
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
205
 
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
206
207
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
208
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
209
    def __init__(self, sock, backing_transport, root_client_path='/'):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
210
        """Constructor.
211
212
        :param sock: the socket the server will read from.  It will be put
213
            into blocking mode.
214
        """
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
215
        SmartServerStreamMedium.__init__(
216
            self, backing_transport, root_client_path=root_client_path)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
217
        sock.setblocking(True)
218
        self.socket = sock
219
220
    def _serve_one_request_unguarded(self, protocol):
221
        while protocol.next_read_size():
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
222
            bytes = self._get_bytes(4096)
223
            if bytes == '':
224
                self.finished = True
225
                return
226
            protocol.accept_bytes(bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
227
        
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
228
        self._push_back(protocol.unused_data)
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
229
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
230
    def _get_bytes(self, desired_count):
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
231
        if self._push_back_buffer is not None:
232
            return self._get_push_back_buffer()
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
233
        # We ignore the desired_count because on sockets it's more efficient to
234
        # read 4k at a time.
235
        return self.socket.recv(4096)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
236
    
237
    def terminate_due_to_error(self):
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
238
        # TODO: This should log to a server log file, but no such thing
239
        # exists yet.  Andrew Bennetts 2006-09-29.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
240
        self.socket.close()
241
        self.finished = True
242
243
    def _write_out(self, bytes):
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
244
        osutils.send_all(self.socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
245
246
247
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
248
249
    def __init__(self, in_file, out_file, backing_transport):
250
        """Construct new server.
251
252
        :param in_file: Python file from which requests can be read.
253
        :param out_file: Python file to write responses.
254
        :param backing_transport: Transport for the directory served.
255
        """
256
        SmartServerStreamMedium.__init__(self, backing_transport)
2018.5.161 by Andrew Bennetts
Reinstate forcing binary mode on windows in SmartServerStreamMedium.
257
        if sys.platform == 'win32':
258
            # force binary mode for files
259
            import msvcrt
260
            for f in (in_file, out_file):
261
                fileno = getattr(f, 'fileno', None)
262
                if fileno:
263
                    msvcrt.setmode(fileno(), os.O_BINARY)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
264
        self._in = in_file
265
        self._out = out_file
266
267
    def _serve_one_request_unguarded(self, protocol):
268
        while True:
269
            bytes_to_read = protocol.next_read_size()
270
            if bytes_to_read == 0:
271
                # Finished serving this request.
272
                self._out.flush()
273
                return
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
274
            bytes = self._get_bytes(bytes_to_read)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
275
            if bytes == '':
276
                # Connection has been closed.
277
                self.finished = True
278
                self._out.flush()
279
                return
280
            protocol.accept_bytes(bytes)
281
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
282
    def _get_bytes(self, desired_count):
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
283
        if self._push_back_buffer is not None:
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
284
            return self._get_push_back_buffer()
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
285
        return self._in.read(desired_count)
286
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
287
    def terminate_due_to_error(self):
288
        # TODO: This should log to a server log file, but no such thing
289
        # exists yet.  Andrew Bennetts 2006-09-29.
290
        self._out.close()
291
        self.finished = True
292
293
    def _write_out(self, bytes):
294
        self._out.write(bytes)
295
296
297
class SmartClientMediumRequest(object):
298
    """A request on a SmartClientMedium.
299
300
    Each request allows bytes to be provided to it via accept_bytes, and then
301
    the response bytes to be read via read_bytes.
302
303
    For instance:
304
    request.accept_bytes('123')
305
    request.finished_writing()
306
    result = request.read_bytes(3)
307
    request.finished_reading()
308
309
    It is up to the individual SmartClientMedium whether multiple concurrent
310
    requests can exist. See SmartClientMedium.get_request to obtain instances 
311
    of SmartClientMediumRequest, and the concrete Medium you are using for 
312
    details on concurrency and pipelining.
313
    """
314
315
    def __init__(self, medium):
316
        """Construct a SmartClientMediumRequest for the medium medium."""
317
        self._medium = medium
318
        # we track state by constants - we may want to use the same
319
        # pattern as BodyReader if it gets more complex.
320
        # valid states are: "writing", "reading", "done"
321
        self._state = "writing"
322
323
    def accept_bytes(self, bytes):
324
        """Accept bytes for inclusion in this request.
325
326
        This method may not be be called after finished_writing() has been
327
        called.  It depends upon the Medium whether or not the bytes will be
328
        immediately transmitted. Message based Mediums will tend to buffer the
329
        bytes until finished_writing() is called.
330
331
        :param bytes: A bytestring.
332
        """
333
        if self._state != "writing":
334
            raise errors.WritingCompleted(self)
335
        self._accept_bytes(bytes)
336
337
    def _accept_bytes(self, bytes):
338
        """Helper for accept_bytes.
339
340
        Accept_bytes checks the state of the request to determing if bytes
341
        should be accepted. After that it hands off to _accept_bytes to do the
342
        actual acceptance.
343
        """
344
        raise NotImplementedError(self._accept_bytes)
345
346
    def finished_reading(self):
347
        """Inform the request that all desired data has been read.
348
349
        This will remove the request from the pipeline for its medium (if the
350
        medium supports pipelining) and any further calls to methods on the
351
        request will raise ReadingCompleted.
352
        """
353
        if self._state == "writing":
354
            raise errors.WritingNotComplete(self)
355
        if self._state != "reading":
356
            raise errors.ReadingCompleted(self)
357
        self._state = "done"
358
        self._finished_reading()
359
360
    def _finished_reading(self):
361
        """Helper for finished_reading.
362
363
        finished_reading checks the state of the request to determine if 
364
        finished_reading is allowed, and if it is hands off to _finished_reading
365
        to perform the action.
366
        """
367
        raise NotImplementedError(self._finished_reading)
368
369
    def finished_writing(self):
370
        """Finish the writing phase of this request.
371
372
        This will flush all pending data for this request along the medium.
373
        After calling finished_writing, you may not call accept_bytes anymore.
374
        """
375
        if self._state != "writing":
376
            raise errors.WritingCompleted(self)
377
        self._state = "reading"
378
        self._finished_writing()
379
380
    def _finished_writing(self):
381
        """Helper for finished_writing.
382
383
        finished_writing checks the state of the request to determine if 
384
        finished_writing is allowed, and if it is hands off to _finished_writing
385
        to perform the action.
386
        """
387
        raise NotImplementedError(self._finished_writing)
388
389
    def read_bytes(self, count):
390
        """Read bytes from this requests response.
391
392
        This method will block and wait for count bytes to be read. It may not
393
        be invoked until finished_writing() has been called - this is to ensure
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
394
        a message-based approach to requests, for compatibility with message
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
395
        based mediums like HTTP.
396
        """
397
        if self._state == "writing":
398
            raise errors.WritingNotComplete(self)
399
        if self._state != "reading":
400
            raise errors.ReadingCompleted(self)
401
        return self._read_bytes(count)
402
403
    def _read_bytes(self, count):
404
        """Helper for read_bytes.
405
406
        read_bytes checks the state of the request to determing if bytes
407
        should be read. After that it hands off to _read_bytes to do the
408
        actual read.
409
        """
410
        raise NotImplementedError(self._read_bytes)
411
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
412
    def read_line(self):
413
        """Read bytes from this request's response until a newline byte.
414
        
415
        This isn't particularly efficient, so should only be used when the
416
        expected size of the line is quite short.
417
418
        :returns: a string of bytes ending in a newline (byte 0x0A).
419
        """
420
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
421
        line = ''
422
        while not line or line[-1] != '\n':
423
            new_char = self.read_bytes(1)
424
            line += new_char
425
            if new_char == '':
3195.2.1 by Andrew Bennetts
Improve test coverage, and fix a bug revealed by the improved coverage.
426
                # end of file encountered reading from server
427
                raise errors.ConnectionReset(
428
                    "please check connectivity and permissions",
429
                    "(and try -Dhpss if further diagnosis is required)")
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
430
        return line
431
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
432
433
class SmartClientMedium(object):
434
    """Smart client is a medium for sending smart protocol requests over."""
435
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
436
    def __init__(self, base):
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
437
        super(SmartClientMedium, self).__init__()
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
438
        self.base = base
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
439
        self._protocol_version_error = None
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
440
        self._protocol_version = None
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
441
        self._done_hello = False
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
442
443
    def protocol_version(self):
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
444
        """Find out if 'hello' smart request works."""
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
445
        if self._protocol_version_error is not None:
446
            raise self._protocol_version_error
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
447
        if not self._done_hello:
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
448
            try:
449
                medium_request = self.get_request()
450
                # Send a 'hello' request in protocol version one, for maximum
451
                # backwards compatibility.
452
                client_protocol = SmartClientRequestProtocolOne(medium_request)
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
453
                client_protocol.query_version()
454
                self._done_hello = True
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
455
            except errors.SmartProtocolError, e:
456
                # Cache the error, just like we would cache a successful
457
                # result.
458
                self._protocol_version_error = e
459
                raise
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
460
        return '2'
461
462
    def should_probe(self):
463
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
464
        this medium?
465
466
        Some transports are unambiguously smart-only; there's no need to check
467
        if the transport is able to carry smart requests, because that's all
468
        it is for.  In those cases, this method should return False.
469
470
        But some HTTP transports can sometimes fail to carry smart requests,
471
        but still be usuable for accessing remote bzrdirs via plain file
472
        accesses.  So for those transports, their media should return True here
473
        so that RemoteBzrDirFormat can determine if it is appropriate for that
474
        transport.
475
        """
476
        return False
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
477
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
478
    def disconnect(self):
479
        """If this medium maintains a persistent connection, close it.
480
        
481
        The default implementation does nothing.
482
        """
483
        
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
484
    def remote_path_from_transport(self, transport):
485
        """Convert transport into a path suitable for using in a request.
486
        
487
        Note that the resulting remote path doesn't encode the host name or
488
        anything but path, so it is only safe to use it in requests sent over
489
        the medium from the matching transport.
490
        """
491
        medium_base = urlutils.join(self.base, '/')
492
        rel_url = urlutils.relative_url(medium_base, transport.base)
493
        return urllib.unquote(rel_url)
494
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
495
496
class SmartClientStreamMedium(SmartClientMedium):
497
    """Stream based medium common class.
498
499
    SmartClientStreamMediums operate on a stream. All subclasses use a common
500
    SmartClientStreamMediumRequest for their requests, and should implement
501
    _accept_bytes and _read_bytes to allow the request objects to send and
502
    receive bytes.
503
    """
504
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
505
    def __init__(self, base):
506
        SmartClientMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
507
        self._current_request = None
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
508
        # Be optimistic: we assume the remote end can accept new remote
509
        # requests until we get an error saying otherwise.  (1.2 adds some
510
        # requests that send bodies, which confuses older servers.)
511
        self._remote_is_at_least_1_2 = True
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
512
513
    def accept_bytes(self, bytes):
514
        self._accept_bytes(bytes)
515
516
    def __del__(self):
517
        """The SmartClientStreamMedium knows how to close the stream when it is
518
        finished with it.
519
        """
520
        self.disconnect()
521
522
    def _flush(self):
523
        """Flush the output stream.
524
        
525
        This method is used by the SmartClientStreamMediumRequest to ensure that
526
        all data for a request is sent, to avoid long timeouts or deadlocks.
527
        """
528
        raise NotImplementedError(self._flush)
529
530
    def get_request(self):
531
        """See SmartClientMedium.get_request().
532
533
        SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
534
        for get_request.
535
        """
536
        return SmartClientStreamMediumRequest(self)
537
538
    def read_bytes(self, count):
539
        return self._read_bytes(count)
540
541
542
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
543
    """A client medium using simple pipes.
544
    
545
    This client does not manage the pipes: it assumes they will always be open.
546
    """
547
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
548
    def __init__(self, readable_pipe, writeable_pipe, base):
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
549
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
550
        self._readable_pipe = readable_pipe
551
        self._writeable_pipe = writeable_pipe
552
553
    def _accept_bytes(self, bytes):
554
        """See SmartClientStreamMedium.accept_bytes."""
555
        self._writeable_pipe.write(bytes)
556
557
    def _flush(self):
558
        """See SmartClientStreamMedium._flush()."""
559
        self._writeable_pipe.flush()
560
561
    def _read_bytes(self, count):
562
        """See SmartClientStreamMedium._read_bytes."""
563
        return self._readable_pipe.read(count)
564
565
566
class SmartSSHClientMedium(SmartClientStreamMedium):
567
    """A client medium using SSH."""
568
    
569
    def __init__(self, host, port=None, username=None, password=None,
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
570
            base=None, vendor=None, bzr_remote_path=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
571
        """Creates a client that will connect on the first use.
572
        
573
        :param vendor: An optional override for the ssh vendor to use. See
574
            bzrlib.transport.ssh for details on ssh vendors.
575
        """
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
576
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
577
        self._connected = False
578
        self._host = host
579
        self._password = password
580
        self._port = port
581
        self._username = username
582
        self._read_from = None
583
        self._ssh_connection = None
584
        self._vendor = vendor
585
        self._write_to = None
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
586
        self._bzr_remote_path = bzr_remote_path
587
        if self._bzr_remote_path is None:
588
            symbol_versioning.warn(
589
                'bzr_remote_path is required as of bzr 0.92',
590
                DeprecationWarning, stacklevel=2)
591
            self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
592
593
    def _accept_bytes(self, bytes):
594
        """See SmartClientStreamMedium.accept_bytes."""
595
        self._ensure_connection()
596
        self._write_to.write(bytes)
597
598
    def disconnect(self):
599
        """See SmartClientMedium.disconnect()."""
600
        if not self._connected:
601
            return
602
        self._read_from.close()
603
        self._write_to.close()
604
        self._ssh_connection.close()
605
        self._connected = False
606
607
    def _ensure_connection(self):
608
        """Connect this medium if not already connected."""
609
        if self._connected:
610
            return
611
        if self._vendor is None:
612
            vendor = ssh._get_ssh_vendor()
613
        else:
614
            vendor = self._vendor
615
        self._ssh_connection = vendor.connect_ssh(self._username,
616
                self._password, self._host, self._port,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
617
                command=[self._bzr_remote_path, 'serve', '--inet',
618
                         '--directory=/', '--allow-writes'])
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
619
        self._read_from, self._write_to = \
620
            self._ssh_connection.get_filelike_channels()
621
        self._connected = True
622
623
    def _flush(self):
624
        """See SmartClientStreamMedium._flush()."""
625
        self._write_to.flush()
626
627
    def _read_bytes(self, count):
628
        """See SmartClientStreamMedium.read_bytes."""
629
        if not self._connected:
630
            raise errors.MediumNotConnected(self)
631
        return self._read_from.read(count)
632
633
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
634
# Port 4155 is the default port for bzr://, registered with IANA.
635
BZR_DEFAULT_INTERFACE = '0.0.0.0'
636
BZR_DEFAULT_PORT = 4155
637
638
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
639
class SmartTCPClientMedium(SmartClientStreamMedium):
640
    """A client medium using TCP."""
641
    
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
642
    def __init__(self, host, port, base):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
643
        """Creates a client that will connect on the first use."""
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
644
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
645
        self._connected = False
646
        self._host = host
647
        self._port = port
648
        self._socket = None
649
650
    def _accept_bytes(self, bytes):
651
        """See SmartClientMedium.accept_bytes."""
652
        self._ensure_connection()
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
653
        osutils.send_all(self._socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
654
655
    def disconnect(self):
656
        """See SmartClientMedium.disconnect()."""
657
        if not self._connected:
658
            return
659
        self._socket.close()
660
        self._socket = None
661
        self._connected = False
662
663
    def _ensure_connection(self):
664
        """Connect this medium if not already connected."""
665
        if self._connected:
666
            return
667
        self._socket = socket.socket()
668
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
669
        if self._port is None:
670
            port = BZR_DEFAULT_PORT
671
        else:
672
            port = int(self._port)
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
673
        try:
674
            self._socket.connect((self._host, port))
675
        except socket.error, err:
676
            # socket errors either have a (string) or (errno, string) as their
677
            # args.
678
            if type(err.args) is str:
679
                err_msg = err.args
680
            else:
681
                err_msg = err.args[1]
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
682
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
683
                    (self._host, port, err_msg))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
684
        self._connected = True
685
686
    def _flush(self):
687
        """See SmartClientStreamMedium._flush().
688
        
689
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
690
        add a means to do a flush, but that can be done in the future.
691
        """
692
693
    def _read_bytes(self, count):
694
        """See SmartClientMedium.read_bytes."""
695
        if not self._connected:
696
            raise errors.MediumNotConnected(self)
697
        return self._socket.recv(count)
698
699
700
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
701
    """A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
702
703
    def __init__(self, medium):
704
        SmartClientMediumRequest.__init__(self, medium)
705
        # check that we are safe concurrency wise. If some streams start
706
        # allowing concurrent requests - i.e. via multiplexing - then this
707
        # assert should be moved to SmartClientStreamMedium.get_request,
708
        # and the setting/unsetting of _current_request likewise moved into
709
        # that class : but its unneeded overhead for now. RBC 20060922
710
        if self._medium._current_request is not None:
711
            raise errors.TooManyConcurrentRequests(self._medium)
712
        self._medium._current_request = self
713
714
    def _accept_bytes(self, bytes):
715
        """See SmartClientMediumRequest._accept_bytes.
716
        
717
        This forwards to self._medium._accept_bytes because we are operating
718
        on the mediums stream.
719
        """
720
        self._medium._accept_bytes(bytes)
721
722
    def _finished_reading(self):
723
        """See SmartClientMediumRequest._finished_reading.
724
725
        This clears the _current_request on self._medium to allow a new 
726
        request to be created.
727
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
728
        if self._medium._current_request is not self:
729
            raise AssertionError()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
730
        self._medium._current_request = None
731
        
732
    def _finished_writing(self):
733
        """See SmartClientMediumRequest._finished_writing.
734
735
        This invokes self._medium._flush to ensure all bytes are transmitted.
736
        """
737
        self._medium._flush()
738
739
    def _read_bytes(self, count):
740
        """See SmartClientMediumRequest._read_bytes.
741
        
742
        This forwards to self._medium._read_bytes because we are operating
743
        on the mediums stream.
744
        """
745
        return self._medium._read_bytes(count)
3245.4.32 by Andrew Bennetts
Undo trivial whitespace change relative to bzr.dev.
746