1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
2
# Copyright (C) 2005, 2006 Canonical Ltd
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Implementation of Transport over SFTP, using paramiko."""
34
from bzrlib.config import config_dir, ensure_config_dir_exists
35
from bzrlib.errors import (ConnectionError,
37
TransportNotPossible, NoSuchFile, PathNotChild,
43
from bzrlib.osutils import pathjoin, fancy_rename
44
from bzrlib.trace import mutter, warning, error
45
from bzrlib.transport import (
46
register_urlparse_netloc_protocol,
52
import bzrlib.urlutils as urlutils
56
except ImportError, e:
57
raise ParamikoNotPresent(e)
59
from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
60
SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
62
from paramiko.sftp_attr import SFTPAttributes
63
from paramiko.sftp_file import SFTPFile
64
from paramiko.sftp_client import SFTPClient
67
register_urlparse_netloc_protocol('sftp')
71
# TODO: This should possibly ignore SIGHUP as well, but bzr currently
72
# doesn't handle it itself.
73
# <https://launchpad.net/products/bzr/+bug/41433/+index>
75
signal.signal(signal.SIGINT, signal.SIG_IGN)
78
def os_specific_subprocess_params():
79
"""Get O/S specific subprocess parameters."""
80
if sys.platform == 'win32':
81
# setting the process group and closing fds is not supported on
85
# We close fds other than the pipes as the child process does not need
88
# We also set the child process to ignore SIGINT. Normally the signal
89
# would be sent to every process in the foreground process group, but
90
# this causes it to be seen only by bzr and not by ssh. Python will
91
# generate a KeyboardInterrupt in bzr, and we will then have a chance
92
# to release locks or do other cleanup over ssh before the connection
94
# <https://launchpad.net/products/bzr/+bug/5987>
96
# Running it in a separate process group is not good because then it
97
# can't get non-echoed input of a password or passphrase.
98
# <https://launchpad.net/products/bzr/+bug/40508>
99
return {'preexec_fn': _ignore_sigint,
104
# don't use prefetch unless paramiko version >= 1.5.2 (there were bugs earlier)
105
_default_do_prefetch = False
106
if getattr(paramiko, '__version_info__', (0, 0, 0)) >= (1, 5, 5):
107
_default_do_prefetch = True
111
def _get_ssh_vendor():
112
"""Find out what version of SSH is on the system."""
114
if _ssh_vendor is not None:
119
if 'BZR_SSH' in os.environ:
120
_ssh_vendor = os.environ['BZR_SSH']
121
if _ssh_vendor == 'paramiko':
126
p = subprocess.Popen(['ssh', '-V'],
127
stdin=subprocess.PIPE,
128
stdout=subprocess.PIPE,
129
stderr=subprocess.PIPE,
130
**os_specific_subprocess_params())
131
returncode = p.returncode
132
stdout, stderr = p.communicate()
136
if 'OpenSSH' in stderr:
137
mutter('ssh implementation is OpenSSH')
138
_ssh_vendor = 'openssh'
139
elif 'SSH Secure Shell' in stderr:
140
mutter('ssh implementation is SSH Corp.')
143
if _ssh_vendor != 'none':
146
# XXX: 20051123 jamesh
147
# A check for putty's plink or lsh would go here.
149
mutter('falling back to paramiko implementation')
153
class SFTPSubprocess:
154
"""A socket-like object that talks to an ssh subprocess via pipes."""
155
def __init__(self, hostname, vendor, port=None, user=None):
156
assert vendor in ['openssh', 'ssh']
157
if vendor == 'openssh':
159
'-oForwardX11=no', '-oForwardAgent=no',
160
'-oClearAllForwardings=yes', '-oProtocol=2',
161
'-oNoHostAuthenticationForLocalhost=yes']
163
args.extend(['-p', str(port)])
165
args.extend(['-l', user])
166
args.extend(['-s', hostname, 'sftp'])
167
elif vendor == 'ssh':
170
args.extend(['-p', str(port)])
172
args.extend(['-l', user])
173
args.extend(['-s', 'sftp', hostname])
175
self.proc = subprocess.Popen(args,
176
stdin=subprocess.PIPE,
177
stdout=subprocess.PIPE,
178
**os_specific_subprocess_params())
180
def send(self, data):
181
return os.write(self.proc.stdin.fileno(), data)
183
def recv_ready(self):
184
# TODO: jam 20051215 this function is necessary to support the
185
# pipelined() function. In reality, it probably should use
186
# poll() or select() to actually return if there is data
187
# available, otherwise we probably don't get any benefit
190
def recv(self, count):
191
return os.read(self.proc.stdout.fileno(), count)
194
self.proc.stdin.close()
195
self.proc.stdout.close()
199
class LoopbackSFTP(object):
200
"""Simple wrapper for a socket that pretends to be a paramiko Channel."""
202
def __init__(self, sock):
205
def send(self, data):
206
return self.__socket.send(data)
209
return self.__socket.recv(n)
211
def recv_ready(self):
215
self.__socket.close()
221
# This is a weakref dictionary, so that we can reuse connections
222
# that are still active. Long term, it might be nice to have some
223
# sort of expiration policy, such as disconnect if inactive for
224
# X seconds. But that requires a lot more fanciness.
225
_connected_hosts = weakref.WeakValueDictionary()
227
def clear_connection_cache():
228
"""Remove all hosts from the SFTP connection cache.
230
Primarily useful for test cases wanting to force garbage collection.
232
_connected_hosts.clear()
235
def load_host_keys():
237
Load system host keys (probably doesn't work on windows) and any
238
"discovered" keys from previous sessions.
240
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
242
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
244
mutter('failed to load system host keys: ' + str(e))
245
bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
247
BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
249
mutter('failed to load bzr host keys: ' + str(e))
253
def save_host_keys():
255
Save "discovered" host keys in $(config)/ssh_host_keys/.
257
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
258
bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
259
ensure_config_dir_exists()
262
f = open(bzr_hostkey_path, 'w')
263
f.write('# SSH host keys collected by bzr\n')
264
for hostname, keys in BZR_HOSTKEYS.iteritems():
265
for keytype, key in keys.iteritems():
266
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
269
mutter('failed to save bzr host keys: ' + str(e))
272
class SFTPLock(object):
273
"""This fakes a lock in a remote location."""
274
__slots__ = ['path', 'lock_path', 'lock_file', 'transport']
275
def __init__(self, path, transport):
276
assert isinstance(transport, SFTPTransport)
278
self.lock_file = None
280
self.lock_path = path + '.write-lock'
281
self.transport = transport
283
# RBC 20060103 FIXME should we be using private methods here ?
284
abspath = transport._remote_path(self.lock_path)
285
self.lock_file = transport._sftp_open_exclusive(abspath)
287
raise LockError('File %r already locked' % (self.path,))
290
"""Should this warn, or actually try to cleanup?"""
292
warning("SFTPLock %r not explicitly unlocked" % (self.path,))
296
if not self.lock_file:
298
self.lock_file.close()
299
self.lock_file = None
301
self.transport.delete(self.lock_path)
302
except (NoSuchFile,):
303
# What specific errors should we catch here?
307
class SFTPTransport (Transport):
309
Transport implementation for SFTP access.
311
_do_prefetch = _default_do_prefetch
313
def __init__(self, base, clone_from=None):
314
assert base.startswith('sftp://')
315
self._parse_url(base)
316
base = self._unparse_url()
319
super(SFTPTransport, self).__init__(base)
320
if clone_from is None:
323
# use the same ssh connection, etc
324
self._sftp = clone_from._sftp
325
# super saves 'self.base'
327
def should_cache(self):
329
Return True if the data pulled across should be cached locally.
333
def clone(self, offset=None):
335
Return a new SFTPTransport with root at self.base + offset.
336
We share the same SFTP session between such transports, because it's
337
fairly expensive to set them up.
340
return SFTPTransport(self.base, self)
342
return SFTPTransport(self.abspath(offset), self)
344
def abspath(self, relpath):
346
Return the full url to the given relative path.
348
@param relpath: the relative path or path components
349
@type relpath: str or list
351
return self._unparse_url(self._remote_path(relpath))
353
def _remote_path(self, relpath):
354
"""Return the path to be passed along the sftp protocol for relpath.
356
relpath is a urlencoded string.
358
# FIXME: share the common code across transports
359
assert isinstance(relpath, basestring)
360
relpath = urlutils.unescape(relpath).split('/')
361
basepath = self._path.split('/')
362
if len(basepath) > 0 and basepath[-1] == '':
363
basepath = basepath[:-1]
367
if len(basepath) == 0:
368
# In most filesystems, a request for the parent
369
# of root, just returns root.
377
path = '/'.join(basepath)
380
def relpath(self, abspath):
381
username, password, host, port, path = self._split_url(abspath)
383
if (username != self._username):
384
error.append('username mismatch')
385
if (host != self._host):
386
error.append('host mismatch')
387
if (port != self._port):
388
error.append('port mismatch')
389
if (not path.startswith(self._path)):
390
error.append('path mismatch')
392
extra = ': ' + ', '.join(error)
393
raise PathNotChild(abspath, self.base, extra=extra)
395
return path[pl:].strip('/')
397
def has(self, relpath):
399
Does the target location exist?
402
self._sftp.stat(self._remote_path(relpath))
407
def get(self, relpath):
409
Get the file at the given relative path.
411
:param relpath: The relative path to the file
414
path = self._remote_path(relpath)
415
f = self._sftp.file(path, mode='rb')
416
if self._do_prefetch and (getattr(f, 'prefetch', None) is not None):
419
except (IOError, paramiko.SSHException), e:
420
self._translate_io_exception(e, path, ': error retrieving')
422
def get_partial(self, relpath, start, length=None):
424
Get just part of a file.
426
:param relpath: Path to the file, relative to base
427
:param start: The starting position to read from
428
:param length: The length to read. A length of None indicates
429
read to the end of the file.
430
:return: A file-like object containing at least the specified bytes.
431
Some implementations may return objects which can be read
432
past this length, but this is not guaranteed.
434
# TODO: implement get_partial_multi to help with knit support
435
f = self.get(relpath)
437
if self._do_prefetch and hasattr(f, 'prefetch'):
441
def put(self, relpath, f, mode=None):
443
Copy the file-like or string object into the location.
445
:param relpath: Location to put the contents, relative to base.
446
:param f: File-like or string object.
447
:param mode: The final mode for the file
449
final_path = self._remote_path(relpath)
450
self._put(final_path, f, mode=mode)
452
def _put(self, abspath, f, mode=None):
453
"""Helper function so both put() and copy_abspaths can reuse the code"""
454
tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
455
os.getpid(), random.randint(0,0x7FFFFFFF))
456
fout = self._sftp_open_exclusive(tmp_abspath, mode=mode)
460
fout.set_pipelined(True)
462
except (IOError, paramiko.SSHException), e:
463
self._translate_io_exception(e, tmp_abspath)
465
self._sftp.chmod(tmp_abspath, mode)
468
self._rename_and_overwrite(tmp_abspath, abspath)
470
# If we fail, try to clean up the temporary file
471
# before we throw the exception
472
# but don't let another exception mess things up
473
# Write out the traceback, because otherwise
474
# the catch and throw destroys it
476
mutter(traceback.format_exc())
480
self._sftp.remove(tmp_abspath)
482
# raise the saved except
484
# raise the original with its traceback if we can.
487
def iter_files_recursive(self):
488
"""Walk the relative paths of all files in this transport."""
489
queue = list(self.list_dir('.'))
491
relpath = urllib.quote(queue.pop(0))
492
st = self.stat(relpath)
493
if stat.S_ISDIR(st.st_mode):
494
for i, basename in enumerate(self.list_dir(relpath)):
495
queue.insert(i, relpath+'/'+basename)
499
def mkdir(self, relpath, mode=None):
500
"""Create a directory at the given path."""
502
path = self._remote_path(relpath)
503
# In the paramiko documentation, it says that passing a mode flag
504
# will filtered against the server umask.
505
# StubSFTPServer does not do this, which would be nice, because it is
506
# what we really want :)
507
# However, real servers do use umask, so we really should do it that way
508
self._sftp.mkdir(path)
510
self._sftp.chmod(path, mode=mode)
511
except (paramiko.SSHException, IOError), e:
512
self._translate_io_exception(e, path, ': unable to mkdir',
513
failure_exc=FileExists)
515
def _translate_io_exception(self, e, path, more_info='',
516
failure_exc=PathError):
517
"""Translate a paramiko or IOError into a friendlier exception.
519
:param e: The original exception
520
:param path: The path in question when the error is raised
521
:param more_info: Extra information that can be included,
522
such as what was going on
523
:param failure_exc: Paramiko has the super fun ability to raise completely
524
opaque errors that just set "e.args = ('Failure',)" with
526
If this parameter is set, it defines the exception
527
to raise in these cases.
529
# paramiko seems to generate detailless errors.
530
self._translate_error(e, path, raise_generic=False)
531
if hasattr(e, 'args'):
532
if (e.args == ('No such file or directory',) or
533
e.args == ('No such file',)):
534
raise NoSuchFile(path, str(e) + more_info)
535
if (e.args == ('mkdir failed',)):
536
raise FileExists(path, str(e) + more_info)
537
# strange but true, for the paramiko server.
538
if (e.args == ('Failure',)):
539
raise failure_exc(path, str(e) + more_info)
540
mutter('Raising exception with args %s', e.args)
541
if hasattr(e, 'errno'):
542
mutter('Raising exception with errno %s', e.errno)
545
def append(self, relpath, f, mode=None):
547
Append the text in the file-like object into the final
551
path = self._remote_path(relpath)
552
fout = self._sftp.file(path, 'ab')
554
self._sftp.chmod(path, mode)
558
except (IOError, paramiko.SSHException), e:
559
self._translate_io_exception(e, relpath, ': unable to append')
561
def rename(self, rel_from, rel_to):
562
"""Rename without special overwriting"""
564
self._sftp.rename(self._remote_path(rel_from),
565
self._remote_path(rel_to))
566
except (IOError, paramiko.SSHException), e:
567
self._translate_io_exception(e, rel_from,
568
': unable to rename to %r' % (rel_to))
570
def _rename_and_overwrite(self, abs_from, abs_to):
571
"""Do a fancy rename on the remote server.
573
Using the implementation provided by osutils.
576
fancy_rename(abs_from, abs_to,
577
rename_func=self._sftp.rename,
578
unlink_func=self._sftp.remove)
579
except (IOError, paramiko.SSHException), e:
580
self._translate_io_exception(e, abs_from, ': unable to rename to %r' % (abs_to))
582
def move(self, rel_from, rel_to):
583
"""Move the item at rel_from to the location at rel_to"""
584
path_from = self._remote_path(rel_from)
585
path_to = self._remote_path(rel_to)
586
self._rename_and_overwrite(path_from, path_to)
588
def delete(self, relpath):
589
"""Delete the item at relpath"""
590
path = self._remote_path(relpath)
592
self._sftp.remove(path)
593
except (IOError, paramiko.SSHException), e:
594
self._translate_io_exception(e, path, ': unable to delete')
597
"""Return True if this store supports listing."""
600
def list_dir(self, relpath):
602
Return a list of all files at the given location.
604
# does anything actually use this?
605
path = self._remote_path(relpath)
607
return self._sftp.listdir(path)
608
except (IOError, paramiko.SSHException), e:
609
self._translate_io_exception(e, path, ': failed to list_dir')
611
def rmdir(self, relpath):
612
"""See Transport.rmdir."""
613
path = self._remote_path(relpath)
615
return self._sftp.rmdir(path)
616
except (IOError, paramiko.SSHException), e:
617
self._translate_io_exception(e, path, ': failed to rmdir')
619
def stat(self, relpath):
620
"""Return the stat information for a file."""
621
path = self._remote_path(relpath)
623
return self._sftp.stat(path)
624
except (IOError, paramiko.SSHException), e:
625
self._translate_io_exception(e, path, ': unable to stat')
627
def lock_read(self, relpath):
629
Lock the given file for shared (read) access.
630
:return: A lock object, which has an unlock() member function
632
# FIXME: there should be something clever i can do here...
633
class BogusLock(object):
634
def __init__(self, path):
638
return BogusLock(relpath)
640
def lock_write(self, relpath):
642
Lock the given file for exclusive (write) access.
643
WARNING: many transports do not support this, so trying avoid using it
645
:return: A lock object, which has an unlock() member function
647
# This is a little bit bogus, but basically, we create a file
648
# which should not already exist, and if it does, we assume
649
# that there is a lock, and if it doesn't, the we assume
650
# that we have taken the lock.
651
return SFTPLock(relpath, self)
653
def _unparse_url(self, path=None):
656
path = urllib.quote(path)
657
# handle homedir paths
658
if not path.startswith('/'):
660
netloc = urllib.quote(self._host)
661
if self._username is not None:
662
netloc = '%s@%s' % (urllib.quote(self._username), netloc)
663
if self._port is not None:
664
netloc = '%s:%d' % (netloc, self._port)
665
return urlparse.urlunparse(('sftp', netloc, path, '', '', ''))
667
def _split_url(self, url):
668
(scheme, username, password, host, port, path) = split_url(url)
669
assert scheme == 'sftp'
671
# the initial slash should be removed from the path, and treated
672
# as a homedir relative path (the path begins with a double slash
673
# if it is absolute).
674
# see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
675
# RBC 20060118 we are not using this as its too user hostile. instead
676
# we are following lftp and using /~/foo to mean '~/foo'.
677
# handle homedir paths
678
if path.startswith('/~/'):
682
return (username, password, host, port, path)
684
def _parse_url(self, url):
685
(self._username, self._password,
686
self._host, self._port, self._path) = self._split_url(url)
688
def _sftp_connect(self):
689
"""Connect to the remote sftp server.
690
After this, self._sftp should have a valid connection (or
691
we raise an TransportError 'could not connect').
693
TODO: Raise a more reasonable ConnectionFailed exception
695
global _connected_hosts
697
idx = (self._host, self._port, self._username)
699
self._sftp = _connected_hosts[idx]
704
vendor = _get_ssh_vendor()
705
if vendor == 'loopback':
706
sock = socket.socket()
708
sock.connect((self._host, self._port))
709
except socket.error, e:
710
raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
711
% (self._host, self._port, e))
712
self._sftp = SFTPClient(LoopbackSFTP(sock))
713
elif vendor != 'none':
714
sock = SFTPSubprocess(self._host, vendor, self._port,
716
self._sftp = SFTPClient(sock)
718
self._paramiko_connect()
720
_connected_hosts[idx] = self._sftp
722
def _paramiko_connect(self):
723
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
728
t = paramiko.Transport((self._host, self._port or 22))
729
t.set_log_channel('bzr.paramiko')
731
except paramiko.SSHException, e:
732
raise ConnectionError('Unable to reach SSH host %s:%s: %s'
733
% (self._host, self._port, e))
735
server_key = t.get_remote_server_key()
736
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
737
keytype = server_key.get_name()
738
if SYSTEM_HOSTKEYS.has_key(self._host) and SYSTEM_HOSTKEYS[self._host].has_key(keytype):
739
our_server_key = SYSTEM_HOSTKEYS[self._host][keytype]
740
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
741
elif BZR_HOSTKEYS.has_key(self._host) and BZR_HOSTKEYS[self._host].has_key(keytype):
742
our_server_key = BZR_HOSTKEYS[self._host][keytype]
743
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
745
warning('Adding %s host key for %s: %s' % (keytype, self._host, server_key_hex))
746
if not BZR_HOSTKEYS.has_key(self._host):
747
BZR_HOSTKEYS[self._host] = {}
748
BZR_HOSTKEYS[self._host][keytype] = server_key
749
our_server_key = server_key
750
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
752
if server_key != our_server_key:
753
filename1 = os.path.expanduser('~/.ssh/known_hosts')
754
filename2 = pathjoin(config_dir(), 'ssh_host_keys')
755
raise TransportError('Host keys for %s do not match! %s != %s' % \
756
(self._host, our_server_key_hex, server_key_hex),
757
['Try editing %s or %s' % (filename1, filename2)])
762
self._sftp = t.open_sftp_client()
763
except paramiko.SSHException, e:
764
raise ConnectionError('Unable to start sftp client %s:%d' %
765
(self._host, self._port), e)
767
def _sftp_auth(self, transport):
768
# paramiko requires a username, but it might be none if nothing was supplied
769
# use the local username, just in case.
770
# We don't override self._username, because if we aren't using paramiko,
771
# the username might be specified in ~/.ssh/config and we don't want to
772
# force it to something else
773
# Also, it would mess up the self.relpath() functionality
774
username = self._username or getpass.getuser()
776
# Paramiko tries to open a socket.AF_UNIX in order to connect
777
# to ssh-agent. That attribute doesn't exist on win32 (it does in cygwin)
778
# so we get an AttributeError exception. For now, just don't try to
779
# connect to an agent if we are on win32
780
if sys.platform != 'win32':
781
agent = paramiko.Agent()
782
for key in agent.get_keys():
783
mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
785
transport.auth_publickey(username, key)
787
except paramiko.SSHException, e:
790
# okay, try finding id_rsa or id_dss? (posix only)
791
if self._try_pkey_auth(transport, paramiko.RSAKey, username, 'id_rsa'):
793
if self._try_pkey_auth(transport, paramiko.DSSKey, username, 'id_dsa'):
798
transport.auth_password(username, self._password)
800
except paramiko.SSHException, e:
803
# FIXME: Don't keep a password held in memory if you can help it
804
#self._password = None
806
# give up and ask for a password
807
password = bzrlib.ui.ui_factory.get_password(
808
prompt='SSH %(user)s@%(host)s password',
809
user=username, host=self._host)
811
transport.auth_password(username, password)
812
except paramiko.SSHException, e:
813
raise ConnectionError('Unable to authenticate to SSH host as %s@%s' %
814
(username, self._host), e)
816
def _try_pkey_auth(self, transport, pkey_class, username, filename):
817
filename = os.path.expanduser('~/.ssh/' + filename)
819
key = pkey_class.from_private_key_file(filename)
820
transport.auth_publickey(username, key)
822
except paramiko.PasswordRequiredException:
823
password = bzrlib.ui.ui_factory.get_password(
824
prompt='SSH %(filename)s password',
827
key = pkey_class.from_private_key_file(filename, password)
828
transport.auth_publickey(username, key)
830
except paramiko.SSHException:
831
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
832
except paramiko.SSHException:
833
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
838
def _sftp_open_exclusive(self, abspath, mode=None):
839
"""Open a remote path exclusively.
841
SFTP supports O_EXCL (SFTP_FLAG_EXCL), which fails if
842
the file already exists. However it does not expose this
843
at the higher level of SFTPClient.open(), so we have to
846
WARNING: This breaks the SFTPClient abstraction, so it
847
could easily break against an updated version of paramiko.
849
:param abspath: The remote absolute path where the file should be opened
850
:param mode: The mode permissions bits for the new file
852
path = self._sftp._adjust_cwd(abspath)
853
attr = SFTPAttributes()
856
omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
857
| SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
859
t, msg = self._sftp._request(CMD_OPEN, path, omode, attr)
861
raise TransportError('Expected an SFTP handle')
862
handle = msg.get_string()
863
return SFTPFile(self._sftp, handle, 'wb', -1)
864
except (paramiko.SSHException, IOError), e:
865
self._translate_io_exception(e, abspath, ': unable to open',
866
failure_exc=FileExists)
869
# ------------- server test implementation --------------
873
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
875
STUB_SERVER_KEY = """
876
-----BEGIN RSA PRIVATE KEY-----
877
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
878
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
879
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
880
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
881
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
882
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
883
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
884
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
885
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
886
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
887
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
888
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
889
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
890
-----END RSA PRIVATE KEY-----
894
class SocketListener(threading.Thread):
896
def __init__(self, callback):
897
threading.Thread.__init__(self)
898
self._callback = callback
899
self._socket = socket.socket()
900
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
901
self._socket.bind(('localhost', 0))
902
self._socket.listen(1)
903
self.port = self._socket.getsockname()[1]
904
self._stop_event = threading.Event()
907
# called from outside this thread
908
self._stop_event.set()
909
# use a timeout here, because if the test fails, the server thread may
910
# never notice the stop_event.
916
readable, writable_unused, exception_unused = \
917
select.select([self._socket], [], [], 0.1)
918
if self._stop_event.isSet():
920
if len(readable) == 0:
923
s, addr_unused = self._socket.accept()
924
# because the loopback socket is inline, and transports are
925
# never explicitly closed, best to launch a new thread.
926
threading.Thread(target=self._callback, args=(s,)).start()
927
except socket.error, x:
928
sys.excepthook(*sys.exc_info())
929
warning('Socket error during accept() within unit test server'
932
# probably a failed test; unit test thread will log the
934
sys.excepthook(*sys.exc_info())
935
warning('Exception from within unit test server thread: %r' %
939
class SFTPServer(Server):
940
"""Common code for SFTP server facilities."""
943
self._original_vendor = None
945
self._server_homedir = None
946
self._listener = None
948
self._vendor = 'none'
952
def _get_sftp_url(self, path):
953
"""Calculate an sftp url to this server for path."""
954
return 'sftp://foo:bar@localhost:%d/%s' % (self._listener.port, path)
956
def log(self, message):
957
"""StubServer uses this to log when a new server is created."""
958
self.logs.append(message)
960
def _run_server(self, s):
961
ssh_server = paramiko.Transport(s)
962
key_file = os.path.join(self._homedir, 'test_rsa.key')
963
f = open(key_file, 'w')
964
f.write(STUB_SERVER_KEY)
966
host_key = paramiko.RSAKey.from_private_key_file(key_file)
967
ssh_server.add_server_key(host_key)
968
server = StubServer(self)
969
ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
970
StubSFTPServer, root=self._root,
971
home=self._server_homedir)
972
event = threading.Event()
973
ssh_server.start_server(event, server)
978
self._original_vendor = _ssh_vendor
979
_ssh_vendor = self._vendor
980
self._homedir = os.getcwd()
981
if self._server_homedir is None:
982
self._server_homedir = self._homedir
984
# FIXME WINDOWS: _root should be _server_homedir[0]:/
985
self._listener = SocketListener(self._run_server)
986
self._listener.setDaemon(True)
987
self._listener.start()
990
"""See bzrlib.transport.Server.tearDown."""
992
self._listener.stop()
993
_ssh_vendor = self._original_vendor
995
def get_bogus_url(self):
996
"""See bzrlib.transport.Server.get_bogus_url."""
997
# this is chosen to try to prevent trouble with proxies, wierd dns,
999
return 'sftp://127.0.0.1:1/'
1003
class SFTPFullAbsoluteServer(SFTPServer):
1004
"""A test server for sftp transports, using absolute urls and ssh."""
1007
"""See bzrlib.transport.Server.get_url."""
1008
return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1011
class SFTPServerWithoutSSH(SFTPServer):
1012
"""An SFTP server that uses a simple TCP socket pair rather than SSH."""
1015
super(SFTPServerWithoutSSH, self).__init__()
1016
self._vendor = 'loopback'
1018
def _run_server(self, sock):
1019
class FakeChannel(object):
1020
def get_transport(self):
1022
def get_log_channel(self):
1026
def get_hexdump(self):
1031
server = paramiko.SFTPServer(FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
1032
root=self._root, home=self._server_homedir)
1033
server.start_subsystem('sftp', None, sock)
1034
server.finish_subsystem()
1037
class SFTPAbsoluteServer(SFTPServerWithoutSSH):
1038
"""A test server for sftp transports, using absolute urls."""
1041
"""See bzrlib.transport.Server.get_url."""
1042
return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1045
class SFTPHomeDirServer(SFTPServerWithoutSSH):
1046
"""A test server for sftp transports, using homedir relative urls."""
1049
"""See bzrlib.transport.Server.get_url."""
1050
return self._get_sftp_url("~/")
1053
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
1054
"""A test servere for sftp transports, using absolute urls to non-home."""
1057
self._server_homedir = '/dev/noone/runs/tests/here'
1058
super(SFTPSiblingAbsoluteServer, self).setUp()
1061
def get_test_permutations():
1062
"""Return the permutations to be used in testing."""
1063
return [(SFTPTransport, SFTPAbsoluteServer),
1064
(SFTPTransport, SFTPHomeDirServer),
1065
(SFTPTransport, SFTPSiblingAbsoluteServer),