1
# Copyright (C) 2006 Canonical Ltd
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.
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.
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
17
"""The 'medium' layer for the smart servers and clients.
19
"Medium" here is the noun meaning "a means of transmission", not the adjective
20
for "the quality between big and small."
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.
38
from bzrlib.smart.protocol import (
39
MESSAGE_VERSION_THREE,
41
SmartClientRequestProtocolOne,
42
SmartServerRequestProtocolOne,
43
SmartServerRequestProtocolTwo,
44
build_server_protocol_three
46
from bzrlib.transport import ssh
49
def _get_protocol_factory_for_bytes(bytes):
50
"""Determine the right protocol factory for 'bytes'.
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
58
Typical use would be::
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)
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.
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):]
77
protocol_factory = SmartServerRequestProtocolOne
78
return protocol_factory, bytes
81
class SmartServerStreamMedium(object):
82
"""Handles smart commands coming over a stream.
84
The stream may be a pipe connected to sshd, or a tcp socket, or an
85
in-process fifo for testing.
87
One instance is created for each connected client; it can serve multiple
88
requests in the lifetime of the connection.
90
The server passes requests through to an underlying backing transport,
91
which will typically be a LocalTransport looking at the server's filesystem.
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.
99
def __init__(self, backing_transport, root_client_path='/'):
100
"""Construct new server.
102
:param backing_transport: Transport for the directory served.
104
# backing_transport could be passed to serve instead of __init__
105
self.backing_transport = backing_transport
106
self.root_client_path = root_client_path
107
self.finished = False
108
self._push_back_buffer = None
110
def _push_back(self, bytes):
111
"""Return unused bytes to the medium, because they belong to the next
114
This sets the _push_back_buffer to the given bytes.
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,))
122
self._push_back_buffer = bytes
124
def _get_push_back_buffer(self):
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,))
129
bytes = self._push_back_buffer
130
self._push_back_buffer = None
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
139
while not self.finished:
140
server_protocol = self._build_protocol()
141
self._serve_one_request(server_protocol)
143
stderr.write("%s terminating on exception %s\n" % (self, e))
146
def _build_protocol(self):
147
"""Identifies the version of the incoming request, and returns an
148
a protocol object that can interpret it.
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.
153
:returns: a SmartServerRequestProtocol.
155
bytes = self._get_line()
156
protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
157
protocol = protocol_factory(
158
self.backing_transport, self._write_out, self.root_client_path)
159
protocol.accept_bytes(unused_bytes)
162
def _serve_one_request(self, protocol):
163
"""Read one request from input, process, send back a response.
165
:param protocol: a SmartServerRequestProtocol.
168
self._serve_one_request_unguarded(protocol)
169
except KeyboardInterrupt:
172
self.terminate_due_to_error()
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)
178
def _get_bytes(self, desired_count):
179
"""Get some bytes from the medium.
181
:param desired_count: number of bytes we want to read.
183
raise NotImplementedError(self._get_bytes)
186
"""Read bytes from this request's response until a newline byte.
188
This isn't particularly efficient, so should only be used when the
189
expected size of the line is quite short.
191
:returns: a string of bytes ending in a newline (byte 0x0A).
195
while newline_pos == -1:
196
new_bytes = self._get_bytes(1)
199
# Ran out of bytes before receiving a complete line.
201
newline_pos = bytes.find('\n')
202
line = bytes[:newline_pos+1]
203
self._push_back(bytes[newline_pos+1:])
207
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
209
def __init__(self, sock, backing_transport, root_client_path='/'):
212
:param sock: the socket the server will read from. It will be put
215
SmartServerStreamMedium.__init__(
216
self, backing_transport, root_client_path=root_client_path)
217
sock.setblocking(True)
220
def _serve_one_request_unguarded(self, protocol):
221
while protocol.next_read_size():
222
bytes = self._get_bytes(4096)
226
protocol.accept_bytes(bytes)
228
self._push_back(protocol.unused_data)
230
def _get_bytes(self, desired_count):
231
if self._push_back_buffer is not None:
232
return self._get_push_back_buffer()
233
# We ignore the desired_count because on sockets it's more efficient to
235
return self.socket.recv(4096)
237
def terminate_due_to_error(self):
238
# TODO: This should log to a server log file, but no such thing
239
# exists yet. Andrew Bennetts 2006-09-29.
243
def _write_out(self, bytes):
244
osutils.send_all(self.socket, bytes)
247
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
249
def __init__(self, in_file, out_file, backing_transport):
250
"""Construct new server.
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.
256
SmartServerStreamMedium.__init__(self, backing_transport)
257
if sys.platform == 'win32':
258
# force binary mode for files
260
for f in (in_file, out_file):
261
fileno = getattr(f, 'fileno', None)
263
msvcrt.setmode(fileno(), os.O_BINARY)
267
def _serve_one_request_unguarded(self, protocol):
269
bytes_to_read = protocol.next_read_size()
270
if bytes_to_read == 0:
271
# Finished serving this request.
274
bytes = self._get_bytes(bytes_to_read)
276
# Connection has been closed.
280
protocol.accept_bytes(bytes)
282
def _get_bytes(self, desired_count):
283
if self._push_back_buffer is not None:
284
return self._get_push_back_buffer()
285
return self._in.read(desired_count)
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.
293
def _write_out(self, bytes):
294
self._out.write(bytes)
297
class SmartClientMediumRequest(object):
298
"""A request on a SmartClientMedium.
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.
304
request.accept_bytes('123')
305
request.finished_writing()
306
result = request.read_bytes(3)
307
request.finished_reading()
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.
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"
323
def accept_bytes(self, bytes):
324
"""Accept bytes for inclusion in this request.
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.
331
:param bytes: A bytestring.
333
if self._state != "writing":
334
raise errors.WritingCompleted(self)
335
self._accept_bytes(bytes)
337
def _accept_bytes(self, bytes):
338
"""Helper for accept_bytes.
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
344
raise NotImplementedError(self._accept_bytes)
346
def finished_reading(self):
347
"""Inform the request that all desired data has been read.
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.
353
if self._state == "writing":
354
raise errors.WritingNotComplete(self)
355
if self._state != "reading":
356
raise errors.ReadingCompleted(self)
358
self._finished_reading()
360
def _finished_reading(self):
361
"""Helper for finished_reading.
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.
367
raise NotImplementedError(self._finished_reading)
369
def finished_writing(self):
370
"""Finish the writing phase of this request.
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.
375
if self._state != "writing":
376
raise errors.WritingCompleted(self)
377
self._state = "reading"
378
self._finished_writing()
380
def _finished_writing(self):
381
"""Helper for finished_writing.
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.
387
raise NotImplementedError(self._finished_writing)
389
def read_bytes(self, count):
390
"""Read bytes from this requests response.
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
394
a message-based approach to requests, for compatibility with message
395
based mediums like HTTP.
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)
403
def _read_bytes(self, count):
404
"""Helper for read_bytes.
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
410
raise NotImplementedError(self._read_bytes)
413
"""Read bytes from this request's response until a newline byte.
415
This isn't particularly efficient, so should only be used when the
416
expected size of the line is quite short.
418
:returns: a string of bytes ending in a newline (byte 0x0A).
420
# XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
422
while not line or line[-1] != '\n':
423
new_char = self.read_bytes(1)
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)")
433
class SmartClientMedium(object):
434
"""Smart client is a medium for sending smart protocol requests over."""
436
def __init__(self, base):
437
super(SmartClientMedium, self).__init__()
439
self._protocol_version_error = None
440
self._protocol_version = None
441
self._done_hello = False
442
# Be optimistic: we assume the remote end can accept new remote
443
# requests until we get an error saying otherwise. (1.2 adds some
444
# requests that send bodies, which confuses older servers.)
445
self._remote_is_at_least_1_2 = True
447
def protocol_version(self):
448
"""Find out if 'hello' smart request works."""
449
if self._protocol_version_error is not None:
450
raise self._protocol_version_error
451
if not self._done_hello:
453
medium_request = self.get_request()
454
# Send a 'hello' request in protocol version one, for maximum
455
# backwards compatibility.
456
client_protocol = SmartClientRequestProtocolOne(medium_request)
457
client_protocol.query_version()
458
self._done_hello = True
459
except errors.SmartProtocolError, e:
460
# Cache the error, just like we would cache a successful
462
self._protocol_version_error = e
466
def should_probe(self):
467
"""Should RemoteBzrDirFormat.probe_transport send a smart request on
470
Some transports are unambiguously smart-only; there's no need to check
471
if the transport is able to carry smart requests, because that's all
472
it is for. In those cases, this method should return False.
474
But some HTTP transports can sometimes fail to carry smart requests,
475
but still be usuable for accessing remote bzrdirs via plain file
476
accesses. So for those transports, their media should return True here
477
so that RemoteBzrDirFormat can determine if it is appropriate for that
482
def disconnect(self):
483
"""If this medium maintains a persistent connection, close it.
485
The default implementation does nothing.
488
def remote_path_from_transport(self, transport):
489
"""Convert transport into a path suitable for using in a request.
491
Note that the resulting remote path doesn't encode the host name or
492
anything but path, so it is only safe to use it in requests sent over
493
the medium from the matching transport.
495
medium_base = urlutils.join(self.base, '/')
496
rel_url = urlutils.relative_url(medium_base, transport.base)
497
return urllib.unquote(rel_url)
500
class SmartClientStreamMedium(SmartClientMedium):
501
"""Stream based medium common class.
503
SmartClientStreamMediums operate on a stream. All subclasses use a common
504
SmartClientStreamMediumRequest for their requests, and should implement
505
_accept_bytes and _read_bytes to allow the request objects to send and
509
def __init__(self, base):
510
SmartClientMedium.__init__(self, base)
511
self._current_request = None
513
def accept_bytes(self, bytes):
514
self._accept_bytes(bytes)
517
"""The SmartClientStreamMedium knows how to close the stream when it is
523
"""Flush the output stream.
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.
528
raise NotImplementedError(self._flush)
530
def get_request(self):
531
"""See SmartClientMedium.get_request().
533
SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
536
return SmartClientStreamMediumRequest(self)
538
def read_bytes(self, count):
539
return self._read_bytes(count)
542
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
543
"""A client medium using simple pipes.
545
This client does not manage the pipes: it assumes they will always be open.
548
def __init__(self, readable_pipe, writeable_pipe, base):
549
SmartClientStreamMedium.__init__(self, base)
550
self._readable_pipe = readable_pipe
551
self._writeable_pipe = writeable_pipe
553
def _accept_bytes(self, bytes):
554
"""See SmartClientStreamMedium.accept_bytes."""
555
self._writeable_pipe.write(bytes)
558
"""See SmartClientStreamMedium._flush()."""
559
self._writeable_pipe.flush()
561
def _read_bytes(self, count):
562
"""See SmartClientStreamMedium._read_bytes."""
563
return self._readable_pipe.read(count)
566
class SmartSSHClientMedium(SmartClientStreamMedium):
567
"""A client medium using SSH."""
569
def __init__(self, host, port=None, username=None, password=None,
570
base=None, vendor=None, bzr_remote_path=None):
571
"""Creates a client that will connect on the first use.
573
:param vendor: An optional override for the ssh vendor to use. See
574
bzrlib.transport.ssh for details on ssh vendors.
576
SmartClientStreamMedium.__init__(self, base)
577
self._connected = False
579
self._password = password
581
self._username = username
582
self._read_from = None
583
self._ssh_connection = None
584
self._vendor = vendor
585
self._write_to = None
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')
593
def _accept_bytes(self, bytes):
594
"""See SmartClientStreamMedium.accept_bytes."""
595
self._ensure_connection()
596
self._write_to.write(bytes)
598
def disconnect(self):
599
"""See SmartClientMedium.disconnect()."""
600
if not self._connected:
602
self._read_from.close()
603
self._write_to.close()
604
self._ssh_connection.close()
605
self._connected = False
607
def _ensure_connection(self):
608
"""Connect this medium if not already connected."""
611
if self._vendor is None:
612
vendor = ssh._get_ssh_vendor()
614
vendor = self._vendor
615
self._ssh_connection = vendor.connect_ssh(self._username,
616
self._password, self._host, self._port,
617
command=[self._bzr_remote_path, 'serve', '--inet',
618
'--directory=/', '--allow-writes'])
619
self._read_from, self._write_to = \
620
self._ssh_connection.get_filelike_channels()
621
self._connected = True
624
"""See SmartClientStreamMedium._flush()."""
625
self._write_to.flush()
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)
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
639
class SmartTCPClientMedium(SmartClientStreamMedium):
640
"""A client medium using TCP."""
642
def __init__(self, host, port, base):
643
"""Creates a client that will connect on the first use."""
644
SmartClientStreamMedium.__init__(self, base)
645
self._connected = False
650
def _accept_bytes(self, bytes):
651
"""See SmartClientMedium.accept_bytes."""
652
self._ensure_connection()
653
osutils.send_all(self._socket, bytes)
655
def disconnect(self):
656
"""See SmartClientMedium.disconnect()."""
657
if not self._connected:
661
self._connected = False
663
def _ensure_connection(self):
664
"""Connect this medium if not already connected."""
667
self._socket = socket.socket()
668
self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
669
if self._port is None:
670
port = BZR_DEFAULT_PORT
672
port = int(self._port)
674
self._socket.connect((self._host, port))
675
except socket.error, err:
676
# socket errors either have a (string) or (errno, string) as their
678
if type(err.args) is str:
681
err_msg = err.args[1]
682
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
683
(self._host, port, err_msg))
684
self._connected = True
687
"""See SmartClientStreamMedium._flush().
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.
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)
700
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
701
"""A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
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
714
def _accept_bytes(self, bytes):
715
"""See SmartClientMediumRequest._accept_bytes.
717
This forwards to self._medium._accept_bytes because we are operating
718
on the mediums stream.
720
self._medium._accept_bytes(bytes)
722
def _finished_reading(self):
723
"""See SmartClientMediumRequest._finished_reading.
725
This clears the _current_request on self._medium to allow a new
726
request to be created.
728
if self._medium._current_request is not self:
729
raise AssertionError()
730
self._medium._current_request = None
732
def _finished_writing(self):
733
"""See SmartClientMediumRequest._finished_writing.
735
This invokes self._medium._flush to ensure all bytes are transmitted.
737
self._medium._flush()
739
def _read_bytes(self, count):
740
"""See SmartClientMediumRequest._read_bytes.
742
This forwards to self._medium._read_bytes because we are operating
743
on the mediums stream.
745
return self._medium._read_bytes(count)