23
from paramiko import ServerInterface, SFTPServerInterface, SFTPServer, SFTPAttributes, \
24
SFTPHandle, SFTP_OK, AUTH_SUCCESSFUL, OPEN_SUCCEEDED
27
from bzrlib.osutils import pathjoin
28
from bzrlib.trace import mutter
31
class StubServer (ServerInterface):
33
def __init__(self, test_case):
34
ServerInterface.__init__(self)
35
self._test_case = test_case
36
from bzrlib.transport import (
39
from bzrlib.tests import test_server
42
class StubServer(paramiko.ServerInterface):
44
def __init__(self, test_case_server):
45
paramiko.ServerInterface.__init__(self)
46
self.log = test_case_server.log
37
48
def check_auth_password(self, username, password):
39
self._test_case.log('sftpserver - authorizing: %s' % (username,))
40
return AUTH_SUCCESSFUL
50
self.log('sftpserver - authorizing: %s' % (username,))
51
return paramiko.AUTH_SUCCESSFUL
42
53
def check_channel_request(self, kind, chanid):
43
self._test_case.log('sftpserver - channel request: %s, %s' % (kind, chanid))
47
class StubSFTPHandle (SFTPHandle):
54
self.log('sftpserver - channel request: %s, %s' % (kind, chanid))
55
return paramiko.OPEN_SUCCEEDED
58
class StubSFTPHandle(paramiko.SFTPHandle):
50
return SFTPAttributes.from_stat(os.fstat(self.readfile.fileno()))
62
return paramiko.SFTPAttributes.from_stat(
63
os.fstat(self.readfile.fileno()))
52
return SFTPServer.convert_errno(e.errno)
65
return paramiko.SFTPServer.convert_errno(e.errno)
54
67
def chattr(self, attr):
55
68
# python doesn't have equivalents to fchown or fchmod, so we have to
56
69
# use the stored filename
57
mutter('Changing permissions on %s to %s', self.filename, attr)
70
trace.mutter('Changing permissions on %s to %s', self.filename, attr)
59
SFTPServer.set_file_attr(self.filename, attr)
72
paramiko.SFTPServer.set_file_attr(self.filename, attr)
61
return SFTPServer.convert_errno(e.errno)
64
class StubSFTPServer (SFTPServerInterface):
74
return paramiko.SFTPServer.convert_errno(e.errno)
77
class StubSFTPServer(paramiko.SFTPServerInterface):
66
79
def __init__(self, server, root, home=None):
67
SFTPServerInterface.__init__(self, server)
80
paramiko.SFTPServerInterface.__init__(self, server)
68
81
# All paths are actually relative to 'root'.
69
82
# this is like implementing chroot().
213
227
if attr is not None:
214
228
attr._flags &= ~attr.FLAG_PERMISSIONS
215
SFTPServer.set_file_attr(path, attr)
229
paramiko.SFTPServer.set_file_attr(path, attr)
216
230
except OSError, e:
217
return SFTPServer.convert_errno(e.errno)
231
return paramiko.SFTPServer.convert_errno(e.errno)
232
return paramiko.SFTP_OK
220
234
def rmdir(self, path):
221
235
path = self._realpath(path)
224
238
except OSError, e:
225
return SFTPServer.convert_errno(e.errno)
239
return paramiko.SFTPServer.convert_errno(e.errno)
240
return paramiko.SFTP_OK
228
242
# removed: chattr, symlink, readlink
229
243
# (nothing in bzr's sftp transport uses those)
246
# ------------- server test implementation --------------
248
STUB_SERVER_KEY = """
249
-----BEGIN RSA PRIVATE KEY-----
250
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
251
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
252
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
253
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
254
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
255
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
256
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
257
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
258
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
259
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
260
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
261
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
262
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
263
-----END RSA PRIVATE KEY-----
267
class SocketDelay(object):
268
"""A socket decorator to make TCP appear slower.
270
This changes recv, send, and sendall to add a fixed latency to each python
271
call if a new roundtrip is detected. That is, when a recv is called and the
272
flag new_roundtrip is set, latency is charged. Every send and send_all
275
In addition every send, sendall and recv sleeps a bit per character send to
278
Not all methods are implemented, this is deliberate as this class is not a
279
replacement for the builtin sockets layer. fileno is not implemented to
280
prevent the proxy being bypassed.
284
_proxied_arguments = dict.fromkeys([
285
"close", "getpeername", "getsockname", "getsockopt", "gettimeout",
286
"setblocking", "setsockopt", "settimeout", "shutdown"])
288
def __init__(self, sock, latency, bandwidth=1.0,
291
:param bandwith: simulated bandwith (MegaBit)
292
:param really_sleep: If set to false, the SocketDelay will just
293
increase a counter, instead of calling time.sleep. This is useful for
294
unittesting the SocketDelay.
297
self.latency = latency
298
self.really_sleep = really_sleep
299
self.time_per_byte = 1 / (bandwidth / 8.0 * 1024 * 1024)
300
self.new_roundtrip = False
303
if self.really_sleep:
306
SocketDelay.simulated_time += s
308
def __getattr__(self, attr):
309
if attr in SocketDelay._proxied_arguments:
310
return getattr(self.sock, attr)
311
raise AttributeError("'SocketDelay' object has no attribute %r" %
315
return SocketDelay(self.sock.dup(), self.latency, self.time_per_byte,
318
def recv(self, *args):
319
data = self.sock.recv(*args)
320
if data and self.new_roundtrip:
321
self.new_roundtrip = False
322
self.sleep(self.latency)
323
self.sleep(len(data) * self.time_per_byte)
326
def sendall(self, data, flags=0):
327
if not self.new_roundtrip:
328
self.new_roundtrip = True
329
self.sleep(self.latency)
330
self.sleep(len(data) * self.time_per_byte)
331
return self.sock.sendall(data, flags)
333
def send(self, data, flags=0):
334
if not self.new_roundtrip:
335
self.new_roundtrip = True
336
self.sleep(self.latency)
337
bytes_sent = self.sock.send(data, flags)
338
self.sleep(bytes_sent * self.time_per_byte)
342
class TestingSFTPConnectionHandler(SocketServer.BaseRequestHandler):
345
self.wrap_for_latency()
346
tcs = self.server.test_case_server
347
ptrans = paramiko.Transport(self.request)
348
self.paramiko_transport = ptrans
349
# Set it to a channel under 'bzr' so that we get debug info
350
ptrans.set_log_channel('bzr.paramiko.transport')
351
ptrans.add_server_key(tcs.get_host_key())
352
ptrans.set_subsystem_handler('sftp', paramiko.SFTPServer,
353
StubSFTPServer, root=tcs._root,
354
home=tcs._server_homedir)
355
server = tcs._server_interface(tcs)
356
# This blocks until the key exchange has been done
357
ptrans.start_server(None, server)
360
# Wait for the conversation to finish, when the paramiko.Transport
362
# TODO: Consider timing out after XX seconds rather than hanging.
363
# Also we could check paramiko_transport.active and possibly
364
# paramiko_transport.getException().
365
self.paramiko_transport.join()
367
def wrap_for_latency(self):
368
tcs = self.server.test_case_server
370
# Give the socket (which the request really is) a latency adding
372
self.request = SocketDelay(self.request, tcs.add_latency)
375
class TestingSFTPWithoutSSHConnectionHandler(TestingSFTPConnectionHandler):
378
self.wrap_for_latency()
379
# Re-import these as locals, so that they're still accessible during
380
# interpreter shutdown (when all module globals get set to None, leading
381
# to confusing errors like "'NoneType' object has no attribute 'error'".
382
class FakeChannel(object):
383
def get_transport(self):
385
def get_log_channel(self):
386
return 'bzr.paramiko'
389
def get_hexdump(self):
394
tcs = self.server.test_case_server
395
sftp_server = paramiko.SFTPServer(
396
FakeChannel(), 'sftp', StubServer(tcs), StubSFTPServer,
397
root=tcs._root, home=tcs._server_homedir)
398
self.sftp_server = sftp_server
399
sys_stderr = sys.stderr # Used in error reporting during shutdown
401
sftp_server.start_subsystem(
402
'sftp', None, ssh.SocketAsChannelAdapter(self.request))
403
except socket.error, e:
404
if (len(e.args) > 0) and (e.args[0] == errno.EPIPE):
405
# it's okay for the client to disconnect abruptly
406
# (bug in paramiko 1.6: it should absorb this exception)
411
# This typically seems to happen during interpreter shutdown, so
412
# most of the useful ways to report this error won't work.
413
# Writing the exception type, and then the text of the exception,
414
# seems to be the best we can do.
415
# FIXME: All interpreter shutdown errors should have been related
416
# to daemon threads, cleanup needed -- vila 20100623
417
sys_stderr.write('\nEXCEPTION %r: ' % (e.__class__,))
418
sys_stderr.write('%s\n\n' % (e,))
421
self.sftp_server.finish_subsystem()
424
class TestingSFTPServer(test_server.TestingThreadingTCPServer):
426
def __init__(self, server_address, request_handler_class, test_case_server):
427
test_server.TestingThreadingTCPServer.__init__(
428
self, server_address, request_handler_class)
429
self.test_case_server = test_case_server
432
class SFTPServer(test_server.TestingTCPServerInAThread):
433
"""Common code for SFTP server facilities."""
435
def __init__(self, server_interface=StubServer):
436
self.host = '127.0.0.1'
438
super(SFTPServer, self).__init__((self.host, self.port),
440
TestingSFTPConnectionHandler)
441
self._original_vendor = None
442
self._vendor = ssh.ParamikoVendor()
443
self._server_interface = server_interface
444
self._host_key = None
448
self._server_homedir = None
451
def _get_sftp_url(self, path):
452
"""Calculate an sftp url to this server for path."""
453
return "sftp://foo:bar@%s:%s/%s" % (self.host, self.port, path)
455
def log(self, message):
456
"""StubServer uses this to log when a new server is created."""
457
self.logs.append(message)
459
def create_server(self):
460
server = self.server_class((self.host, self.port),
461
self.request_handler_class,
465
def get_host_key(self):
466
if self._host_key is None:
467
key_file = osutils.pathjoin(self._homedir, 'test_rsa.key')
468
f = open(key_file, 'w')
470
f.write(STUB_SERVER_KEY)
473
self._host_key = paramiko.RSAKey.from_private_key_file(key_file)
474
return self._host_key
476
def start_server(self, backing_server=None):
477
# XXX: TODO: make sftpserver back onto backing_server rather than local
479
if not (backing_server is None or
480
isinstance(backing_server, test_server.LocalURLServer)):
481
raise AssertionError(
482
'backing_server should not be %r, because this can only serve '
483
'the local current working directory.' % (backing_server,))
484
self._original_vendor = ssh._ssh_vendor_manager._cached_ssh_vendor
485
ssh._ssh_vendor_manager._cached_ssh_vendor = self._vendor
486
if sys.platform == 'win32':
487
# Win32 needs to use the UNICODE api
488
self._homedir = os.getcwdu()
489
# Normalize the path or it will be wrongly escaped
490
self._homedir = osutils.normpath(self._homedir)
492
# But unix SFTP servers should just deal in bytestreams
493
self._homedir = os.getcwd()
494
if self._server_homedir is None:
495
self._server_homedir = self._homedir
497
if sys.platform == 'win32':
499
super(SFTPServer, self).start_server()
501
def stop_server(self):
503
super(SFTPServer, self).stop_server()
505
ssh._ssh_vendor_manager._cached_ssh_vendor = self._original_vendor
507
def get_bogus_url(self):
508
"""See bzrlib.transport.Server.get_bogus_url."""
509
# this is chosen to try to prevent trouble with proxies, weird dns, etc
510
# we bind a random socket, so that we get a guaranteed unused port
511
# we just never listen on that port
513
s.bind(('localhost', 0))
514
return 'sftp://%s:%s/' % s.getsockname()
517
class SFTPFullAbsoluteServer(SFTPServer):
518
"""A test server for sftp transports, using absolute urls and ssh."""
521
"""See bzrlib.transport.Server.get_url."""
522
homedir = self._homedir
523
if sys.platform != 'win32':
524
# Remove the initial '/' on all platforms but win32
525
homedir = homedir[1:]
526
return self._get_sftp_url(urlutils.escape(homedir))
529
class SFTPServerWithoutSSH(SFTPServer):
530
"""An SFTP server that uses a simple TCP socket pair rather than SSH."""
533
super(SFTPServerWithoutSSH, self).__init__()
534
self._vendor = ssh.LoopbackVendor()
535
self.request_handler_class = TestingSFTPWithoutSSHConnectionHandler
541
class SFTPAbsoluteServer(SFTPServerWithoutSSH):
542
"""A test server for sftp transports, using absolute urls."""
545
"""See bzrlib.transport.Server.get_url."""
546
homedir = self._homedir
547
if sys.platform != 'win32':
548
# Remove the initial '/' on all platforms but win32
549
homedir = homedir[1:]
550
return self._get_sftp_url(urlutils.escape(homedir))
553
class SFTPHomeDirServer(SFTPServerWithoutSSH):
554
"""A test server for sftp transports, using homedir relative urls."""
557
"""See bzrlib.transport.Server.get_url."""
558
return self._get_sftp_url("~/")
561
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
562
"""A test server for sftp transports where only absolute paths will work.
564
It does this by serving from a deeply-nested directory that doesn't exist.
567
def create_server(self):
568
# FIXME: Can't we do that in a cleaner way ? -- vila 20100623
569
server = super(SFTPSiblingAbsoluteServer, self).create_server()
570
server._server_homedir = '/dev/noone/runs/tests/here'