1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>, 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
"""Implementation of Transport over SFTP, using paramiko."""
32
from bzrlib.config import config_dir, ensure_config_dir_exists
33
from bzrlib.errors import (ConnectionError,
35
TransportNotPossible, NoSuchFile, PathNotChild,
39
from bzrlib.osutils import pathjoin, fancy_rename
40
from bzrlib.trace import mutter, warning, error
41
from bzrlib.transport import Transport, Server, urlescape
47
error('The SFTP transport requires paramiko.')
50
from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
51
SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
53
from paramiko.sftp_attr import SFTPAttributes
54
from paramiko.sftp_file import SFTPFile
55
from paramiko.sftp_client import SFTPClient
57
if 'sftp' not in urlparse.uses_netloc: urlparse.uses_netloc.append('sftp')
61
if sys.platform == 'win32':
62
# close_fds not supported on win32
66
def _get_ssh_vendor():
67
"""Find out what version of SSH is on the system."""
69
if _ssh_vendor is not None:
75
p = subprocess.Popen(['ssh', '-V'],
77
stdin=subprocess.PIPE,
78
stdout=subprocess.PIPE,
79
stderr=subprocess.PIPE)
80
returncode = p.returncode
81
stdout, stderr = p.communicate()
85
if 'OpenSSH' in stderr:
86
mutter('ssh implementation is OpenSSH')
87
_ssh_vendor = 'openssh'
88
elif 'SSH Secure Shell' in stderr:
89
mutter('ssh implementation is SSH Corp.')
92
if _ssh_vendor != 'none':
95
# XXX: 20051123 jamesh
96
# A check for putty's plink or lsh would go here.
98
mutter('falling back to paramiko implementation')
102
class SFTPSubprocess:
103
"""A socket-like object that talks to an ssh subprocess via pipes."""
104
def __init__(self, hostname, vendor, port=None, user=None):
105
assert vendor in ['openssh', 'ssh']
106
if vendor == 'openssh':
108
'-oForwardX11=no', '-oForwardAgent=no',
109
'-oClearAllForwardings=yes', '-oProtocol=2',
110
'-oNoHostAuthenticationForLocalhost=yes']
112
args.extend(['-p', str(port)])
114
args.extend(['-l', user])
115
args.extend(['-s', hostname, 'sftp'])
116
elif vendor == 'ssh':
119
args.extend(['-p', str(port)])
121
args.extend(['-l', user])
122
args.extend(['-s', 'sftp', hostname])
124
self.proc = subprocess.Popen(args, close_fds=_close_fds,
125
stdin=subprocess.PIPE,
126
stdout=subprocess.PIPE)
128
def send(self, data):
129
return os.write(self.proc.stdin.fileno(), data)
131
def recv_ready(self):
132
# TODO: jam 20051215 this function is necessary to support the
133
# pipelined() function. In reality, it probably should use
134
# poll() or select() to actually return if there is data
135
# available, otherwise we probably don't get any benefit
138
def recv(self, count):
139
return os.read(self.proc.stdout.fileno(), count)
142
self.proc.stdin.close()
143
self.proc.stdout.close()
150
# This is a weakref dictionary, so that we can reuse connections
151
# that are still active. Long term, it might be nice to have some
152
# sort of expiration policy, such as disconnect if inactive for
153
# X seconds. But that requires a lot more fanciness.
154
_connected_hosts = weakref.WeakValueDictionary()
156
def load_host_keys():
158
Load system host keys (probably doesn't work on windows) and any
159
"discovered" keys from previous sessions.
161
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
163
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
165
mutter('failed to load system host keys: ' + str(e))
166
bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
168
BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
170
mutter('failed to load bzr host keys: ' + str(e))
173
def save_host_keys():
175
Save "discovered" host keys in $(config)/ssh_host_keys/.
177
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
178
bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
179
ensure_config_dir_exists()
182
f = open(bzr_hostkey_path, 'w')
183
f.write('# SSH host keys collected by bzr\n')
184
for hostname, keys in BZR_HOSTKEYS.iteritems():
185
for keytype, key in keys.iteritems():
186
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
189
mutter('failed to save bzr host keys: ' + str(e))
192
class SFTPLock(object):
193
"""This fakes a lock in a remote location."""
194
__slots__ = ['path', 'lock_path', 'lock_file', 'transport']
195
def __init__(self, path, transport):
196
assert isinstance(transport, SFTPTransport)
198
self.lock_file = None
200
self.lock_path = path + '.write-lock'
201
self.transport = transport
203
# RBC 20060103 FIXME should we be using private methods here ?
204
abspath = transport._remote_path(self.lock_path)
205
self.lock_file = transport._sftp_open_exclusive(abspath)
207
raise LockError('File %r already locked' % (self.path,))
210
"""Should this warn, or actually try to cleanup?"""
212
warn("SFTPLock %r not explicitly unlocked" % (self.path,))
216
if not self.lock_file:
218
self.lock_file.close()
219
self.lock_file = None
221
self.transport.delete(self.lock_path)
222
except (NoSuchFile,):
223
# What specific errors should we catch here?
228
class SFTPTransport (Transport):
230
Transport implementation for SFTP access.
232
_do_prefetch = False # Right now Paramiko's prefetch support causes things to hang
234
def __init__(self, base, clone_from=None):
235
assert base.startswith('sftp://')
236
self._parse_url(base)
237
base = self._unparse_url()
240
super(SFTPTransport, self).__init__(base)
241
if clone_from is None:
244
# use the same ssh connection, etc
245
self._sftp = clone_from._sftp
246
# super saves 'self.base'
248
def should_cache(self):
250
Return True if the data pulled across should be cached locally.
254
def clone(self, offset=None):
256
Return a new SFTPTransport with root at self.base + offset.
257
We share the same SFTP session between such transports, because it's
258
fairly expensive to set them up.
261
return SFTPTransport(self.base, self)
263
return SFTPTransport(self.abspath(offset), self)
265
def abspath(self, relpath):
267
Return the full url to the given relative path.
269
@param relpath: the relative path or path components
270
@type relpath: str or list
272
return self._unparse_url(self._remote_path(relpath))
274
def _remote_path(self, relpath):
275
"""Return the path to be passed along the sftp protocol for relpath.
277
relpath is a urlencoded string.
279
# FIXME: share the common code across transports
280
assert isinstance(relpath, basestring)
281
relpath = urllib.unquote(relpath).split('/')
282
basepath = self._path.split('/')
283
if len(basepath) > 0 and basepath[-1] == '':
284
basepath = basepath[:-1]
288
if len(basepath) == 0:
289
# In most filesystems, a request for the parent
290
# of root, just returns root.
298
path = '/'.join(basepath)
301
def relpath(self, abspath):
302
username, password, host, port, path = self._split_url(abspath)
304
if (username != self._username):
305
error.append('username mismatch')
306
if (host != self._host):
307
error.append('host mismatch')
308
if (port != self._port):
309
error.append('port mismatch')
310
if (not path.startswith(self._path)):
311
error.append('path mismatch')
313
extra = ': ' + ', '.join(error)
314
raise PathNotChild(abspath, self.base, extra=extra)
316
return path[pl:].strip('/')
318
def has(self, relpath):
320
Does the target location exist?
323
self._sftp.stat(self._remote_path(relpath))
328
def get(self, relpath, decode=False):
330
Get the file at the given relative path.
332
:param relpath: The relative path to the file
335
path = self._remote_path(relpath)
336
f = self._sftp.file(path, mode='rb')
337
if self._do_prefetch and hasattr(f, 'prefetch'):
340
except (IOError, paramiko.SSHException), e:
341
self._translate_io_exception(e, path, ': error retrieving')
343
def get_partial(self, relpath, start, length=None):
345
Get just part of a file.
347
:param relpath: Path to the file, relative to base
348
:param start: The starting position to read from
349
:param length: The length to read. A length of None indicates
350
read to the end of the file.
351
:return: A file-like object containing at least the specified bytes.
352
Some implementations may return objects which can be read
353
past this length, but this is not guaranteed.
355
# TODO: implement get_partial_multi to help with knit support
356
f = self.get(relpath)
358
if self._do_prefetch and hasattr(f, 'prefetch'):
362
def put(self, relpath, f, mode=None):
364
Copy the file-like or string object into the location.
366
:param relpath: Location to put the contents, relative to base.
367
:param f: File-like or string object.
368
:param mode: The final mode for the file
370
final_path = self._remote_path(relpath)
371
self._put(final_path, f, mode=mode)
373
def _put(self, abspath, f, mode=None):
374
"""Helper function so both put() and copy_abspaths can reuse the code"""
375
tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
376
os.getpid(), random.randint(0,0x7FFFFFFF))
377
fout = self._sftp_open_exclusive(tmp_abspath, mode=mode)
381
fout.set_pipelined(True)
383
except (IOError, paramiko.SSHException), e:
384
self._translate_io_exception(e, tmp_abspath)
386
self._sftp.chmod(tmp_abspath, mode)
389
self._rename(tmp_abspath, abspath)
391
# If we fail, try to clean up the temporary file
392
# before we throw the exception
393
# but don't let another exception mess things up
394
# Write out the traceback, because otherwise
395
# the catch and throw destroys it
397
mutter(traceback.format_exc())
401
self._sftp.remove(tmp_abspath)
403
# raise the saved except
405
# raise the original with its traceback if we can.
408
def iter_files_recursive(self):
409
"""Walk the relative paths of all files in this transport."""
410
queue = list(self.list_dir('.'))
412
relpath = urllib.quote(queue.pop(0))
413
st = self.stat(relpath)
414
if stat.S_ISDIR(st.st_mode):
415
for i, basename in enumerate(self.list_dir(relpath)):
416
queue.insert(i, relpath+'/'+basename)
420
def mkdir(self, relpath, mode=None):
421
"""Create a directory at the given path."""
423
path = self._remote_path(relpath)
424
# In the paramiko documentation, it says that passing a mode flag
425
# will filtered against the server umask.
426
# StubSFTPServer does not do this, which would be nice, because it is
427
# what we really want :)
428
# However, real servers do use umask, so we really should do it that way
429
self._sftp.mkdir(path)
431
self._sftp.chmod(path, mode=mode)
432
except (paramiko.SSHException, IOError), e:
433
self._translate_io_exception(e, path, ': unable to mkdir',
434
failure_exc=FileExists)
436
def _translate_io_exception(self, e, path, more_info='', failure_exc=NoSuchFile):
437
"""Translate a paramiko or IOError into a friendlier exception.
439
:param e: The original exception
440
:param path: The path in question when the error is raised
441
:param more_info: Extra information that can be included,
442
such as what was going on
443
:param failure_exc: Paramiko has the super fun ability to raise completely
444
opaque errors that just set "e.args = ('Failure',)" with
446
This sometimes means FileExists, but it also sometimes
449
# paramiko seems to generate detailless errors.
450
self._translate_error(e, path, raise_generic=False)
451
if hasattr(e, 'args'):
452
if (e.args == ('No such file or directory',) or
453
e.args == ('No such file',)):
454
raise NoSuchFile(path, str(e) + more_info)
455
if (e.args == ('mkdir failed',)):
456
raise FileExists(path, str(e) + more_info)
457
# strange but true, for the paramiko server.
458
if (e.args == ('Failure',)):
459
raise failure_exc(path, str(e) + more_info)
460
mutter('Raising exception with args %s', e.args)
461
if hasattr(e, 'errno'):
462
mutter('Raising exception with errno %s', e.errno)
465
def append(self, relpath, f):
467
Append the text in the file-like object into the final
471
path = self._remote_path(relpath)
472
fout = self._sftp.file(path, 'ab')
474
except (IOError, paramiko.SSHException), e:
475
self._translate_io_exception(e, relpath, ': unable to append')
477
def _rename(self, abs_from, abs_to):
478
"""Do a fancy rename on the remote server.
480
Using the implementation provided by osutils.
483
fancy_rename(abs_from, abs_to,
484
rename_func=self._sftp.rename,
485
unlink_func=self._sftp.remove)
486
except (IOError, paramiko.SSHException), e:
487
self._translate_io_exception(e, abs_from, ': unable to rename to %r' % (abs_to))
489
def move(self, rel_from, rel_to):
490
"""Move the item at rel_from to the location at rel_to"""
491
path_from = self._remote_path(rel_from)
492
path_to = self._remote_path(rel_to)
493
self._rename(path_from, path_to)
495
def delete(self, relpath):
496
"""Delete the item at relpath"""
497
path = self._remote_path(relpath)
499
self._sftp.remove(path)
500
except (IOError, paramiko.SSHException), e:
501
self._translate_io_exception(e, path, ': unable to delete')
504
"""Return True if this store supports listing."""
507
def list_dir(self, relpath):
509
Return a list of all files at the given location.
511
# does anything actually use this?
512
path = self._remote_path(relpath)
514
return self._sftp.listdir(path)
515
except (IOError, paramiko.SSHException), e:
516
self._translate_io_exception(e, path, ': failed to list_dir')
518
def rmdir(self, relpath):
519
"""See Transport.rmdir."""
520
path = self._remote_path(relpath)
522
return self._sftp.rmdir(path)
523
except (IOError, paramiko.SSHException), e:
524
self._translate_io_exception(e, path, ': failed to rmdir')
526
def stat(self, relpath):
527
"""Return the stat information for a file."""
528
path = self._remote_path(relpath)
530
return self._sftp.stat(path)
531
except (IOError, paramiko.SSHException), e:
532
self._translate_io_exception(e, path, ': unable to stat')
534
def lock_read(self, relpath):
536
Lock the given file for shared (read) access.
537
:return: A lock object, which has an unlock() member function
539
# FIXME: there should be something clever i can do here...
540
class BogusLock(object):
541
def __init__(self, path):
545
return BogusLock(relpath)
547
def lock_write(self, relpath):
549
Lock the given file for exclusive (write) access.
550
WARNING: many transports do not support this, so trying avoid using it
552
:return: A lock object, which has an unlock() member function
554
# This is a little bit bogus, but basically, we create a file
555
# which should not already exist, and if it does, we assume
556
# that there is a lock, and if it doesn't, the we assume
557
# that we have taken the lock.
558
return SFTPLock(relpath, self)
560
def _unparse_url(self, path=None):
563
path = urllib.quote(path)
564
# handle homedir paths
565
if not path.startswith('/'):
567
netloc = urllib.quote(self._host)
568
if self._username is not None:
569
netloc = '%s@%s' % (urllib.quote(self._username), netloc)
570
if self._port is not None:
571
netloc = '%s:%d' % (netloc, self._port)
573
return urlparse.urlunparse(('sftp', netloc, path, '', '', ''))
575
def _split_url(self, url):
576
if isinstance(url, unicode):
577
url = url.encode('utf-8')
578
(scheme, netloc, path, params,
579
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
580
assert scheme == 'sftp'
581
username = password = host = port = None
583
username, host = netloc.split('@', 1)
585
username, password = username.split(':', 1)
586
password = urllib.unquote(password)
587
username = urllib.unquote(username)
592
host, port = host.rsplit(':', 1)
596
# TODO: Should this be ConnectionError?
597
raise TransportError('%s: invalid port number' % port)
598
host = urllib.unquote(host)
600
path = urllib.unquote(path)
602
# the initial slash should be removed from the path, and treated
603
# as a homedir relative path (the path begins with a double slash
604
# if it is absolute).
605
# see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
606
# RBC 20060118 we are not using this as its too user hostile. instead
607
# we are following lftp and using /~/foo to mean '~/foo'.
608
# handle homedir paths
609
if path.startswith('/~/'):
613
return (username, password, host, port, path)
615
def _parse_url(self, url):
616
(self._username, self._password,
617
self._host, self._port, self._path) = self._split_url(url)
619
def _sftp_connect(self):
620
"""Connect to the remote sftp server.
621
After this, self._sftp should have a valid connection (or
622
we raise an TransportError 'could not connect').
624
TODO: Raise a more reasonable ConnectionFailed exception
626
global _connected_hosts
628
idx = (self._host, self._port, self._username)
630
self._sftp = _connected_hosts[idx]
635
vendor = _get_ssh_vendor()
637
sock = SFTPSubprocess(self._host, vendor, self._port,
639
self._sftp = SFTPClient(sock)
641
self._paramiko_connect()
643
_connected_hosts[idx] = self._sftp
645
def _paramiko_connect(self):
646
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
651
t = paramiko.Transport((self._host, self._port or 22))
653
except paramiko.SSHException, e:
654
raise ConnectionError('Unable to reach SSH host %s:%d' %
655
(self._host, self._port), e)
657
server_key = t.get_remote_server_key()
658
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
659
keytype = server_key.get_name()
660
if SYSTEM_HOSTKEYS.has_key(self._host) and SYSTEM_HOSTKEYS[self._host].has_key(keytype):
661
our_server_key = SYSTEM_HOSTKEYS[self._host][keytype]
662
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
663
elif BZR_HOSTKEYS.has_key(self._host) and BZR_HOSTKEYS[self._host].has_key(keytype):
664
our_server_key = BZR_HOSTKEYS[self._host][keytype]
665
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
667
warning('Adding %s host key for %s: %s' % (keytype, self._host, server_key_hex))
668
if not BZR_HOSTKEYS.has_key(self._host):
669
BZR_HOSTKEYS[self._host] = {}
670
BZR_HOSTKEYS[self._host][keytype] = server_key
671
our_server_key = server_key
672
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
674
if server_key != our_server_key:
675
filename1 = os.path.expanduser('~/.ssh/known_hosts')
676
filename2 = pathjoin(config_dir(), 'ssh_host_keys')
677
raise TransportError('Host keys for %s do not match! %s != %s' % \
678
(self._host, our_server_key_hex, server_key_hex),
679
['Try editing %s or %s' % (filename1, filename2)])
684
self._sftp = t.open_sftp_client()
685
except paramiko.SSHException, e:
686
raise ConnectionError('Unable to start sftp client %s:%d' %
687
(self._host, self._port), e)
689
def _sftp_auth(self, transport):
690
# paramiko requires a username, but it might be none if nothing was supplied
691
# use the local username, just in case.
692
# We don't override self._username, because if we aren't using paramiko,
693
# the username might be specified in ~/.ssh/config and we don't want to
694
# force it to something else
695
# Also, it would mess up the self.relpath() functionality
696
username = self._username or getpass.getuser()
698
# Paramiko tries to open a socket.AF_UNIX in order to connect
699
# to ssh-agent. That attribute doesn't exist on win32 (it does in cygwin)
700
# so we get an AttributeError exception. For now, just don't try to
701
# connect to an agent if we are on win32
702
if sys.platform != 'win32':
703
agent = paramiko.Agent()
704
for key in agent.get_keys():
705
mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
707
transport.auth_publickey(username, key)
709
except paramiko.SSHException, e:
712
# okay, try finding id_rsa or id_dss? (posix only)
713
if self._try_pkey_auth(transport, paramiko.RSAKey, username, 'id_rsa'):
715
if self._try_pkey_auth(transport, paramiko.DSSKey, username, 'id_dsa'):
720
transport.auth_password(username, self._password)
722
except paramiko.SSHException, e:
725
# FIXME: Don't keep a password held in memory if you can help it
726
#self._password = None
728
# give up and ask for a password
729
password = bzrlib.ui.ui_factory.get_password(
730
prompt='SSH %(user)s@%(host)s password',
731
user=username, host=self._host)
733
transport.auth_password(username, password)
734
except paramiko.SSHException, e:
735
raise ConnectionError('Unable to authenticate to SSH host as %s@%s' %
736
(username, self._host), e)
738
def _try_pkey_auth(self, transport, pkey_class, username, filename):
739
filename = os.path.expanduser('~/.ssh/' + filename)
741
key = pkey_class.from_private_key_file(filename)
742
transport.auth_publickey(username, key)
744
except paramiko.PasswordRequiredException:
745
password = bzrlib.ui.ui_factory.get_password(
746
prompt='SSH %(filename)s password',
749
key = pkey_class.from_private_key_file(filename, password)
750
transport.auth_publickey(username, key)
752
except paramiko.SSHException:
753
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
754
except paramiko.SSHException:
755
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
760
def _sftp_open_exclusive(self, abspath, mode=None):
761
"""Open a remote path exclusively.
763
SFTP supports O_EXCL (SFTP_FLAG_EXCL), which fails if
764
the file already exists. However it does not expose this
765
at the higher level of SFTPClient.open(), so we have to
768
WARNING: This breaks the SFTPClient abstraction, so it
769
could easily break against an updated version of paramiko.
771
:param abspath: The remote absolute path where the file should be opened
772
:param mode: The mode permissions bits for the new file
774
path = self._sftp._adjust_cwd(abspath)
775
attr = SFTPAttributes()
778
omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
779
| SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
781
t, msg = self._sftp._request(CMD_OPEN, path, omode, attr)
783
raise TransportError('Expected an SFTP handle')
784
handle = msg.get_string()
785
return SFTPFile(self._sftp, handle, 'wb', -1)
786
except (paramiko.SSHException, IOError), e:
787
self._translate_io_exception(e, abspath, ': unable to open',
788
failure_exc=FileExists)
791
# ------------- server test implementation --------------
795
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
797
STUB_SERVER_KEY = """
798
-----BEGIN RSA PRIVATE KEY-----
799
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
800
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
801
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
802
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
803
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
804
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
805
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
806
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
807
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
808
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
809
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
810
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
811
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
812
-----END RSA PRIVATE KEY-----
816
class SingleListener(threading.Thread):
818
def __init__(self, callback):
819
threading.Thread.__init__(self)
820
self._callback = callback
821
self._socket = socket.socket()
822
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
823
self._socket.bind(('localhost', 0))
824
self._socket.listen(1)
825
self.port = self._socket.getsockname()[1]
826
self.stop_event = threading.Event()
829
s, _ = self._socket.accept()
830
# now close the listen socket
832
self._callback(s, self.stop_event)
835
self.stop_event.set()
836
# We should consider waiting for the other thread
837
# to stop, because otherwise we get spurious
838
# bzr: ERROR: Socket exception: Connection reset by peer (54)
839
# because the test suite finishes before the thread has a chance
840
# to close. (Especially when only running a few tests)
843
class SFTPServer(Server):
844
"""Common code for SFTP server facilities."""
846
def _get_sftp_url(self, path):
847
"""Calculate a sftp url to this server for path."""
848
return 'sftp://foo:bar@localhost:%d/%s' % (self._listener.port, path)
851
self._original_vendor = None
853
self._server_homedir = None
854
self._listener = None
859
def log(self, message):
860
"""What to do here? do we need this? Its for the StubServer.."""
861
self.logs.append(message)
863
def _run_server(self, s, stop_event):
864
ssh_server = paramiko.Transport(s)
865
key_file = os.path.join(self._homedir, 'test_rsa.key')
866
file(key_file, 'w').write(STUB_SERVER_KEY)
867
host_key = paramiko.RSAKey.from_private_key_file(key_file)
868
ssh_server.add_server_key(host_key)
869
server = StubServer(self)
870
ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
871
StubSFTPServer, root=self._root,
872
home=self._server_homedir)
873
event = threading.Event()
874
ssh_server.start_server(event, server)
876
stop_event.wait(30.0)
879
"""See bzrlib.transport.Server.setUp."""
880
# XXX: 20051124 jamesh
881
# The tests currently pop up a password prompt when an external ssh
882
# is used. This forces the use of the paramiko implementation.
884
self._original_vendor = _ssh_vendor
886
self._homedir = os.getcwdu()
887
if self._server_homedir is None:
888
self._server_homedir = self._homedir
890
# FIXME WINDOWS: _root should be _server_homedir[0]:/
891
self._listener = SingleListener(self._run_server)
892
self._listener.setDaemon(True)
893
self._listener.start()
896
"""See bzrlib.transport.Server.tearDown."""
898
self._listener.stop()
899
_ssh_vendor = self._original_vendor
902
class SFTPAbsoluteServer(SFTPServer):
903
"""A test server for sftp transports, using absolute urls."""
906
"""See bzrlib.transport.Server.get_url."""
907
return self._get_sftp_url(urlescape(self._homedir[1:]))
910
class SFTPHomeDirServer(SFTPServer):
911
"""A test server for sftp transports, using homedir relative urls."""
914
"""See bzrlib.transport.Server.get_url."""
915
return self._get_sftp_url("~/")
918
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
919
"""A test servere for sftp transports, using absolute urls to non-home."""
922
self._server_homedir = '/dev/noone/runs/tests/here'
923
super(SFTPSiblingAbsoluteServer, self).setUp()
926
def get_test_permutations():
927
"""Return the permutations to be used in testing."""
928
return [(SFTPTransport, SFTPAbsoluteServer),
929
(SFTPTransport, SFTPHomeDirServer),
930
(SFTPTransport, SFTPSiblingAbsoluteServer),