39
38
from bzrlib.tests import test_server
42
class StubServer(paramiko.ServerInterface):
41
class StubServer (paramiko.ServerInterface):
44
def __init__(self, test_case_server):
43
def __init__(self, test_case):
45
44
paramiko.ServerInterface.__init__(self)
46
self.log = test_case_server.log
45
self._test_case = test_case
48
47
def check_auth_password(self, username, password):
50
self.log('sftpserver - authorizing: %s' % (username,))
49
self._test_case.log('sftpserver - authorizing: %s' % (username,))
51
50
return paramiko.AUTH_SUCCESSFUL
53
52
def check_channel_request(self, kind, chanid):
54
self.log('sftpserver - channel request: %s, %s' % (kind, chanid))
54
'sftpserver - channel request: %s, %s' % (kind, chanid))
55
55
return paramiko.OPEN_SUCCEEDED
58
class StubSFTPHandle(paramiko.SFTPHandle):
58
class StubSFTPHandle (paramiko.SFTPHandle):
62
61
return paramiko.SFTPAttributes.from_stat(
265
class SocketListener(threading.Thread):
267
def __init__(self, callback):
268
threading.Thread.__init__(self)
269
self._callback = callback
270
self._socket = socket.socket()
271
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
272
self._socket.bind(('localhost', 0))
273
self._socket.listen(1)
274
self.host, self.port = self._socket.getsockname()[:2]
275
self._stop_event = threading.Event()
278
# called from outside this thread
279
self._stop_event.set()
280
# use a timeout here, because if the test fails, the server thread may
281
# never notice the stop_event.
286
trace.mutter('SocketListener %r has started', self)
288
readable, writable_unused, exception_unused = \
289
select.select([self._socket], [], [], 0.1)
290
if self._stop_event.isSet():
291
trace.mutter('SocketListener %r has stopped', self)
293
if len(readable) == 0:
296
s, addr_unused = self._socket.accept()
297
trace.mutter('SocketListener %r has accepted connection %r',
299
# because the loopback socket is inline, and transports are
300
# never explicitly closed, best to launch a new thread.
301
threading.Thread(target=self._callback, args=(s,)).start()
302
except socket.error, x:
303
sys.excepthook(*sys.exc_info())
304
trace.warning('Socket error during accept() '
305
'within unit test server thread: %r' % x)
307
# probably a failed test; unit test thread will log the
309
sys.excepthook(*sys.exc_info())
311
'Exception from within unit test server thread: %r' % x)
267
314
class SocketDelay(object):
268
315
"""A socket decorator to make TCP appear slower.
339
386
return bytes_sent
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):
389
class SFTPServer(test_server.TestServer):
433
390
"""Common code for SFTP server facilities."""
435
392
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
393
self._original_vendor = None
395
self._server_homedir = None
396
self._listener = None
442
398
self._vendor = ssh.ParamikoVendor()
443
399
self._server_interface = server_interface
444
self._host_key = None
446
402
self.add_latency = 0
448
self._server_homedir = None
451
404
def _get_sftp_url(self, path):
452
405
"""Calculate an sftp url to this server for path."""
453
return "sftp://foo:bar@%s:%s/%s" % (self.host, self.port, path)
406
return 'sftp://foo:bar@%s:%d/%s' % (self._listener.host,
407
self._listener.port, path)
455
409
def log(self, message):
456
410
"""StubServer uses this to log when a new server is created."""
457
411
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
413
def _run_server_entry(self, sock):
414
"""Entry point for all implementations of _run_server.
416
If self.add_latency is > 0.000001 then sock is given a latency adding
419
if self.add_latency > 0.000001:
420
sock = SocketDelay(sock, self.add_latency)
421
return self._run_server(sock)
423
def _run_server(self, s):
424
ssh_server = paramiko.Transport(s)
425
key_file = osutils.pathjoin(self._homedir, 'test_rsa.key')
426
f = open(key_file, 'w')
427
f.write(STUB_SERVER_KEY)
429
host_key = paramiko.RSAKey.from_private_key_file(key_file)
430
ssh_server.add_server_key(host_key)
431
server = self._server_interface(self)
432
ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
433
StubSFTPServer, root=self._root,
434
home=self._server_homedir)
435
event = threading.Event()
436
ssh_server.start_server(event, server)
476
439
def start_server(self, backing_server=None):
477
440
# XXX: TODO: make sftpserver back onto backing_server rather than local
532
495
def __init__(self):
533
496
super(SFTPServerWithoutSSH, self).__init__()
534
497
self._vendor = ssh.LoopbackVendor()
535
self.request_handler_class = TestingSFTPWithoutSSHConnectionHandler
499
def _run_server(self, sock):
500
# Re-import these as locals, so that they're still accessible during
501
# interpreter shutdown (when all module globals get set to None, leading
502
# to confusing errors like "'NoneType' object has no attribute 'error'".
503
class FakeChannel(object):
504
def get_transport(self):
506
def get_log_channel(self):
510
def get_hexdump(self):
515
server = paramiko.SFTPServer(
516
FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
517
root=self._root, home=self._server_homedir)
519
server.start_subsystem(
520
'sftp', None, ssh.SocketAsChannelAdapter(sock))
521
except socket.error, e:
522
if (len(e.args) > 0) and (e.args[0] == errno.EPIPE):
523
# it's okay for the client to disconnect abruptly
524
# (bug in paramiko 1.6: it should absorb this exception)
529
# This typically seems to happen during interpreter shutdown, so
530
# most of the useful ways to report this error are won't work.
531
# Writing the exception type, and then the text of the exception,
532
# seems to be the best we can do.
534
sys.stderr.write('\nEXCEPTION %r: ' % (e.__class__,))
535
sys.stderr.write('%s\n\n' % (e,))
536
server.finish_subsystem()
541
539
class SFTPAbsoluteServer(SFTPServerWithoutSSH):