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."""
35
from bzrlib.config import config_dir, ensure_config_dir_exists
36
from bzrlib.errors import (ConnectionError,
38
TransportNotPossible, NoSuchFile, PathNotChild,
44
from bzrlib.osutils import pathjoin, fancy_rename, getcwd
45
from bzrlib.trace import mutter, warning, error
46
from bzrlib.transport import (
47
register_urlparse_netloc_protocol,
53
import bzrlib.urlutils as urlutils
57
except ImportError, e:
58
raise ParamikoNotPresent(e)
60
from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
61
SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
63
from paramiko.sftp_attr import SFTPAttributes
64
from paramiko.sftp_file import SFTPFile
65
from paramiko.sftp_client import SFTPClient
68
register_urlparse_netloc_protocol('sftp')
72
# TODO: This should possibly ignore SIGHUP as well, but bzr currently
73
# doesn't handle it itself.
74
# <https://launchpad.net/products/bzr/+bug/41433/+index>
76
signal.signal(signal.SIGINT, signal.SIG_IGN)
79
def os_specific_subprocess_params():
80
"""Get O/S specific subprocess parameters."""
81
if sys.platform == 'win32':
82
# setting the process group and closing fds is not supported on
86
# We close fds other than the pipes as the child process does not need
89
# We also set the child process to ignore SIGINT. Normally the signal
90
# would be sent to every process in the foreground process group, but
91
# this causes it to be seen only by bzr and not by ssh. Python will
92
# generate a KeyboardInterrupt in bzr, and we will then have a chance
93
# to release locks or do other cleanup over ssh before the connection
95
# <https://launchpad.net/products/bzr/+bug/5987>
97
# Running it in a separate process group is not good because then it
98
# can't get non-echoed input of a password or passphrase.
99
# <https://launchpad.net/products/bzr/+bug/40508>
100
return {'preexec_fn': _ignore_sigint,
105
_paramiko_version = getattr(paramiko, '__version_info__', (0, 0, 0))
106
# don't use prefetch unless paramiko version >= 1.5.5 (there were bugs earlier)
107
_default_do_prefetch = (_paramiko_version >= (1, 5, 5))
109
# Paramiko 1.5 tries to open a socket.AF_UNIX in order to connect
110
# to ssh-agent. That attribute doesn't exist on win32 (it does in cygwin)
111
# so we get an AttributeError exception. So we will not try to
112
# connect to an agent if we are on win32 and using Paramiko older than 1.6
113
_use_ssh_agent = (sys.platform != 'win32' or _paramiko_version >= (1, 6, 0))
117
def _get_ssh_vendor():
118
"""Find out what version of SSH is on the system."""
120
if _ssh_vendor is not None:
125
if 'BZR_SSH' in os.environ:
126
_ssh_vendor = os.environ['BZR_SSH']
127
if _ssh_vendor == 'paramiko':
132
p = subprocess.Popen(['ssh', '-V'],
133
stdin=subprocess.PIPE,
134
stdout=subprocess.PIPE,
135
stderr=subprocess.PIPE,
136
**os_specific_subprocess_params())
137
returncode = p.returncode
138
stdout, stderr = p.communicate()
142
if 'OpenSSH' in stderr:
143
mutter('ssh implementation is OpenSSH')
144
_ssh_vendor = 'openssh'
145
elif 'SSH Secure Shell' in stderr:
146
mutter('ssh implementation is SSH Corp.')
149
if _ssh_vendor != 'none':
152
# XXX: 20051123 jamesh
153
# A check for putty's plink or lsh would go here.
155
mutter('falling back to paramiko implementation')
159
class SFTPSubprocess:
160
"""A socket-like object that talks to an ssh subprocess via pipes."""
161
def __init__(self, hostname, vendor, port=None, user=None):
162
assert vendor in ['openssh', 'ssh']
163
if vendor == 'openssh':
165
'-oForwardX11=no', '-oForwardAgent=no',
166
'-oClearAllForwardings=yes', '-oProtocol=2',
167
'-oNoHostAuthenticationForLocalhost=yes']
169
args.extend(['-p', str(port)])
171
args.extend(['-l', user])
172
args.extend(['-s', hostname, 'sftp'])
173
elif vendor == 'ssh':
176
args.extend(['-p', str(port)])
178
args.extend(['-l', user])
179
args.extend(['-s', 'sftp', hostname])
181
self.proc = subprocess.Popen(args,
182
stdin=subprocess.PIPE,
183
stdout=subprocess.PIPE,
184
**os_specific_subprocess_params())
186
def send(self, data):
187
return os.write(self.proc.stdin.fileno(), data)
189
def recv_ready(self):
190
# TODO: jam 20051215 this function is necessary to support the
191
# pipelined() function. In reality, it probably should use
192
# poll() or select() to actually return if there is data
193
# available, otherwise we probably don't get any benefit
196
def recv(self, count):
197
return os.read(self.proc.stdout.fileno(), count)
200
self.proc.stdin.close()
201
self.proc.stdout.close()
205
class LoopbackSFTP(object):
206
"""Simple wrapper for a socket that pretends to be a paramiko Channel."""
208
def __init__(self, sock):
211
def send(self, data):
212
return self.__socket.send(data)
215
return self.__socket.recv(n)
217
def recv_ready(self):
221
self.__socket.close()
227
# This is a weakref dictionary, so that we can reuse connections
228
# that are still active. Long term, it might be nice to have some
229
# sort of expiration policy, such as disconnect if inactive for
230
# X seconds. But that requires a lot more fanciness.
231
_connected_hosts = weakref.WeakValueDictionary()
233
def clear_connection_cache():
234
"""Remove all hosts from the SFTP connection cache.
236
Primarily useful for test cases wanting to force garbage collection.
238
_connected_hosts.clear()
241
def load_host_keys():
243
Load system host keys (probably doesn't work on windows) and any
244
"discovered" keys from previous sessions.
246
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
248
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
250
mutter('failed to load system host keys: ' + str(e))
251
bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
253
BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
255
mutter('failed to load bzr host keys: ' + str(e))
259
def save_host_keys():
261
Save "discovered" host keys in $(config)/ssh_host_keys/.
263
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
264
bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
265
ensure_config_dir_exists()
268
f = open(bzr_hostkey_path, 'w')
269
f.write('# SSH host keys collected by bzr\n')
270
for hostname, keys in BZR_HOSTKEYS.iteritems():
271
for keytype, key in keys.iteritems():
272
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
275
mutter('failed to save bzr host keys: ' + str(e))
278
class SFTPLock(object):
279
"""This fakes a lock in a remote location."""
280
__slots__ = ['path', 'lock_path', 'lock_file', 'transport']
281
def __init__(self, path, transport):
282
assert isinstance(transport, SFTPTransport)
284
self.lock_file = None
286
self.lock_path = path + '.write-lock'
287
self.transport = transport
289
# RBC 20060103 FIXME should we be using private methods here ?
290
abspath = transport._remote_path(self.lock_path)
291
self.lock_file = transport._sftp_open_exclusive(abspath)
293
raise LockError('File %r already locked' % (self.path,))
296
"""Should this warn, or actually try to cleanup?"""
298
warning("SFTPLock %r not explicitly unlocked" % (self.path,))
302
if not self.lock_file:
304
self.lock_file.close()
305
self.lock_file = None
307
self.transport.delete(self.lock_path)
308
except (NoSuchFile,):
309
# What specific errors should we catch here?
313
class SFTPTransport (Transport):
315
Transport implementation for SFTP access.
317
_do_prefetch = _default_do_prefetch
319
def __init__(self, base, clone_from=None):
320
assert base.startswith('sftp://')
321
self._parse_url(base)
322
base = self._unparse_url()
325
super(SFTPTransport, self).__init__(base)
326
if clone_from is None:
329
# use the same ssh connection, etc
330
self._sftp = clone_from._sftp
331
# super saves 'self.base'
333
def should_cache(self):
335
Return True if the data pulled across should be cached locally.
339
def clone(self, offset=None):
341
Return a new SFTPTransport with root at self.base + offset.
342
We share the same SFTP session between such transports, because it's
343
fairly expensive to set them up.
346
return SFTPTransport(self.base, self)
348
return SFTPTransport(self.abspath(offset), self)
350
def abspath(self, relpath):
352
Return the full url to the given relative path.
354
@param relpath: the relative path or path components
355
@type relpath: str or list
357
return self._unparse_url(self._remote_path(relpath))
359
def _remote_path(self, relpath):
360
"""Return the path to be passed along the sftp protocol for relpath.
362
relpath is a urlencoded string.
364
# FIXME: share the common code across transports
365
assert isinstance(relpath, basestring)
366
relpath = urlutils.unescape(relpath).split('/')
367
basepath = self._path.split('/')
368
if len(basepath) > 0 and basepath[-1] == '':
369
basepath = basepath[:-1]
373
if len(basepath) == 0:
374
# In most filesystems, a request for the parent
375
# of root, just returns root.
383
path = '/'.join(basepath)
384
# mutter('relpath => remotepath %s => %s', relpath, path)
387
def relpath(self, abspath):
388
username, password, host, port, path = self._split_url(abspath)
390
if (username != self._username):
391
error.append('username mismatch')
392
if (host != self._host):
393
error.append('host mismatch')
394
if (port != self._port):
395
error.append('port mismatch')
396
if (not path.startswith(self._path)):
397
error.append('path mismatch')
399
extra = ': ' + ', '.join(error)
400
raise PathNotChild(abspath, self.base, extra=extra)
402
return path[pl:].strip('/')
404
def has(self, relpath):
406
Does the target location exist?
409
self._sftp.stat(self._remote_path(relpath))
414
def get(self, relpath):
416
Get the file at the given relative path.
418
:param relpath: The relative path to the file
421
path = self._remote_path(relpath)
422
f = self._sftp.file(path, mode='rb')
423
if self._do_prefetch and (getattr(f, 'prefetch', None) is not None):
426
except (IOError, paramiko.SSHException), e:
427
self._translate_io_exception(e, path, ': error retrieving')
429
def get_partial(self, relpath, start, length=None):
431
Get just part of a file.
433
:param relpath: Path to the file, relative to base
434
:param start: The starting position to read from
435
:param length: The length to read. A length of None indicates
436
read to the end of the file.
437
:return: A file-like object containing at least the specified bytes.
438
Some implementations may return objects which can be read
439
past this length, but this is not guaranteed.
441
# TODO: implement get_partial_multi to help with knit support
442
f = self.get(relpath)
444
if self._do_prefetch and hasattr(f, 'prefetch'):
448
def put(self, relpath, f, mode=None):
450
Copy the file-like or string object into the location.
452
:param relpath: Location to put the contents, relative to base.
453
:param f: File-like or string object.
454
:param mode: The final mode for the file
456
final_path = self._remote_path(relpath)
457
self._put(final_path, f, mode=mode)
459
def _put(self, abspath, f, mode=None):
460
"""Helper function so both put() and copy_abspaths can reuse the code"""
461
tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
462
os.getpid(), random.randint(0,0x7FFFFFFF))
463
fout = self._sftp_open_exclusive(tmp_abspath, mode=mode)
467
fout.set_pipelined(True)
469
except (IOError, paramiko.SSHException), e:
470
self._translate_io_exception(e, tmp_abspath)
472
self._sftp.chmod(tmp_abspath, mode)
475
self._rename_and_overwrite(tmp_abspath, abspath)
477
# If we fail, try to clean up the temporary file
478
# before we throw the exception
479
# but don't let another exception mess things up
480
# Write out the traceback, because otherwise
481
# the catch and throw destroys it
483
mutter(traceback.format_exc())
487
self._sftp.remove(tmp_abspath)
489
# raise the saved except
491
# raise the original with its traceback if we can.
494
def iter_files_recursive(self):
495
"""Walk the relative paths of all files in this transport."""
496
queue = list(self.list_dir('.'))
498
relpath = urllib.quote(queue.pop(0))
499
st = self.stat(relpath)
500
if stat.S_ISDIR(st.st_mode):
501
for i, basename in enumerate(self.list_dir(relpath)):
502
queue.insert(i, relpath+'/'+basename)
506
def mkdir(self, relpath, mode=None):
507
"""Create a directory at the given path."""
508
path = self._remote_path(relpath)
510
# In the paramiko documentation, it says that passing a mode flag
511
# will filtered against the server umask.
512
# StubSFTPServer does not do this, which would be nice, because it is
513
# what we really want :)
514
# However, real servers do use umask, so we really should do it that way
515
self._sftp.mkdir(path)
517
self._sftp.chmod(path, mode=mode)
518
except (paramiko.SSHException, IOError), e:
519
self._translate_io_exception(e, path, ': unable to mkdir',
520
failure_exc=FileExists)
522
def _translate_io_exception(self, e, path, more_info='',
523
failure_exc=PathError):
524
"""Translate a paramiko or IOError into a friendlier exception.
526
:param e: The original exception
527
:param path: The path in question when the error is raised
528
:param more_info: Extra information that can be included,
529
such as what was going on
530
:param failure_exc: Paramiko has the super fun ability to raise completely
531
opaque errors that just set "e.args = ('Failure',)" with
533
If this parameter is set, it defines the exception
534
to raise in these cases.
536
# paramiko seems to generate detailless errors.
537
self._translate_error(e, path, raise_generic=False)
538
if hasattr(e, 'args'):
539
if (e.args == ('No such file or directory',) or
540
e.args == ('No such file',)):
541
raise NoSuchFile(path, str(e) + more_info)
542
if (e.args == ('mkdir failed',)):
543
raise FileExists(path, str(e) + more_info)
544
# strange but true, for the paramiko server.
545
if (e.args == ('Failure',)):
546
raise failure_exc(path, str(e) + more_info)
547
mutter('Raising exception with args %s', e.args)
548
if hasattr(e, 'errno'):
549
mutter('Raising exception with errno %s', e.errno)
552
def append(self, relpath, f, mode=None):
554
Append the text in the file-like object into the final
558
path = self._remote_path(relpath)
559
fout = self._sftp.file(path, 'ab')
561
self._sftp.chmod(path, mode)
565
except (IOError, paramiko.SSHException), e:
566
self._translate_io_exception(e, relpath, ': unable to append')
568
def rename(self, rel_from, rel_to):
569
"""Rename without special overwriting"""
571
self._sftp.rename(self._remote_path(rel_from),
572
self._remote_path(rel_to))
573
except (IOError, paramiko.SSHException), e:
574
self._translate_io_exception(e, rel_from,
575
': unable to rename to %r' % (rel_to))
577
def _rename_and_overwrite(self, abs_from, abs_to):
578
"""Do a fancy rename on the remote server.
580
Using the implementation provided by osutils.
583
fancy_rename(abs_from, abs_to,
584
rename_func=self._sftp.rename,
585
unlink_func=self._sftp.remove)
586
except (IOError, paramiko.SSHException), e:
587
self._translate_io_exception(e, abs_from, ': unable to rename to %r' % (abs_to))
589
def move(self, rel_from, rel_to):
590
"""Move the item at rel_from to the location at rel_to"""
591
path_from = self._remote_path(rel_from)
592
path_to = self._remote_path(rel_to)
593
self._rename_and_overwrite(path_from, path_to)
595
def delete(self, relpath):
596
"""Delete the item at relpath"""
597
path = self._remote_path(relpath)
599
self._sftp.remove(path)
600
except (IOError, paramiko.SSHException), e:
601
self._translate_io_exception(e, path, ': unable to delete')
604
"""Return True if this store supports listing."""
607
def list_dir(self, relpath):
609
Return a list of all files at the given location.
611
# does anything actually use this?
612
path = self._remote_path(relpath)
614
return self._sftp.listdir(path)
615
except (IOError, paramiko.SSHException), e:
616
self._translate_io_exception(e, path, ': failed to list_dir')
618
def rmdir(self, relpath):
619
"""See Transport.rmdir."""
620
path = self._remote_path(relpath)
622
return self._sftp.rmdir(path)
623
except (IOError, paramiko.SSHException), e:
624
self._translate_io_exception(e, path, ': failed to rmdir')
626
def stat(self, relpath):
627
"""Return the stat information for a file."""
628
path = self._remote_path(relpath)
630
return self._sftp.stat(path)
631
except (IOError, paramiko.SSHException), e:
632
self._translate_io_exception(e, path, ': unable to stat')
634
def lock_read(self, relpath):
636
Lock the given file for shared (read) access.
637
:return: A lock object, which has an unlock() member function
639
# FIXME: there should be something clever i can do here...
640
class BogusLock(object):
641
def __init__(self, path):
645
return BogusLock(relpath)
647
def lock_write(self, relpath):
649
Lock the given file for exclusive (write) access.
650
WARNING: many transports do not support this, so trying avoid using it
652
:return: A lock object, which has an unlock() member function
654
# This is a little bit bogus, but basically, we create a file
655
# which should not already exist, and if it does, we assume
656
# that there is a lock, and if it doesn't, the we assume
657
# that we have taken the lock.
658
return SFTPLock(relpath, self)
660
def _unparse_url(self, path=None):
663
path = urllib.quote(path)
664
# handle homedir paths
665
if not path.startswith('/'):
667
netloc = urllib.quote(self._host)
668
if self._username is not None:
669
netloc = '%s@%s' % (urllib.quote(self._username), netloc)
670
if self._port is not None:
671
netloc = '%s:%d' % (netloc, self._port)
672
return urlparse.urlunparse(('sftp', netloc, path, '', '', ''))
674
def _split_url(self, url):
675
(scheme, username, password, host, port, path) = split_url(url)
676
assert scheme == 'sftp'
678
# the initial slash should be removed from the path, and treated
679
# as a homedir relative path (the path begins with a double slash
680
# if it is absolute).
681
# see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
682
# RBC 20060118 we are not using this as its too user hostile. instead
683
# we are following lftp and using /~/foo to mean '~/foo'.
684
# handle homedir paths
685
if path.startswith('/~/'):
689
return (username, password, host, port, path)
691
def _parse_url(self, url):
692
(self._username, self._password,
693
self._host, self._port, self._path) = self._split_url(url)
695
def _sftp_connect(self):
696
"""Connect to the remote sftp server.
697
After this, self._sftp should have a valid connection (or
698
we raise an TransportError 'could not connect').
700
TODO: Raise a more reasonable ConnectionFailed exception
702
global _connected_hosts
704
idx = (self._host, self._port, self._username)
706
self._sftp = _connected_hosts[idx]
711
vendor = _get_ssh_vendor()
712
if vendor == 'loopback':
713
sock = socket.socket()
715
sock.connect((self._host, self._port))
716
except socket.error, e:
717
raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
718
% (self._host, self._port, e))
719
self._sftp = SFTPClient(LoopbackSFTP(sock))
720
elif vendor != 'none':
721
sock = SFTPSubprocess(self._host, vendor, self._port,
723
self._sftp = SFTPClient(sock)
725
self._paramiko_connect()
727
_connected_hosts[idx] = self._sftp
729
def _paramiko_connect(self):
730
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
735
t = paramiko.Transport((self._host, self._port or 22))
736
t.set_log_channel('bzr.paramiko')
738
except paramiko.SSHException, e:
739
raise ConnectionError('Unable to reach SSH host %s:%s: %s'
740
% (self._host, self._port, e))
742
server_key = t.get_remote_server_key()
743
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
744
keytype = server_key.get_name()
745
if SYSTEM_HOSTKEYS.has_key(self._host) and SYSTEM_HOSTKEYS[self._host].has_key(keytype):
746
our_server_key = SYSTEM_HOSTKEYS[self._host][keytype]
747
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
748
elif BZR_HOSTKEYS.has_key(self._host) and BZR_HOSTKEYS[self._host].has_key(keytype):
749
our_server_key = BZR_HOSTKEYS[self._host][keytype]
750
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
752
warning('Adding %s host key for %s: %s' % (keytype, self._host, server_key_hex))
753
if not BZR_HOSTKEYS.has_key(self._host):
754
BZR_HOSTKEYS[self._host] = {}
755
BZR_HOSTKEYS[self._host][keytype] = server_key
756
our_server_key = server_key
757
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
759
if server_key != our_server_key:
760
filename1 = os.path.expanduser('~/.ssh/known_hosts')
761
filename2 = pathjoin(config_dir(), 'ssh_host_keys')
762
raise TransportError('Host keys for %s do not match! %s != %s' % \
763
(self._host, our_server_key_hex, server_key_hex),
764
['Try editing %s or %s' % (filename1, filename2)])
769
self._sftp = t.open_sftp_client()
770
except paramiko.SSHException, e:
771
raise ConnectionError('Unable to start sftp client %s:%d' %
772
(self._host, self._port), e)
774
def _sftp_auth(self, transport):
775
# paramiko requires a username, but it might be none if nothing was supplied
776
# use the local username, just in case.
777
# We don't override self._username, because if we aren't using paramiko,
778
# the username might be specified in ~/.ssh/config and we don't want to
779
# force it to something else
780
# Also, it would mess up the self.relpath() functionality
781
username = self._username or getpass.getuser()
784
agent = paramiko.Agent()
785
for key in agent.get_keys():
786
mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
788
transport.auth_publickey(username, key)
790
except paramiko.SSHException, e:
793
# okay, try finding id_rsa or id_dss? (posix only)
794
if self._try_pkey_auth(transport, paramiko.RSAKey, username, 'id_rsa'):
796
if self._try_pkey_auth(transport, paramiko.DSSKey, username, 'id_dsa'):
801
transport.auth_password(username, self._password)
803
except paramiko.SSHException, e:
806
# FIXME: Don't keep a password held in memory if you can help it
807
#self._password = None
809
# give up and ask for a password
810
password = bzrlib.ui.ui_factory.get_password(
811
prompt='SSH %(user)s@%(host)s password',
812
user=username, host=self._host)
814
transport.auth_password(username, password)
815
except paramiko.SSHException, e:
816
raise ConnectionError('Unable to authenticate to SSH host as %s@%s' %
817
(username, self._host), e)
819
def _try_pkey_auth(self, transport, pkey_class, username, filename):
820
filename = os.path.expanduser('~/.ssh/' + filename)
822
key = pkey_class.from_private_key_file(filename)
823
transport.auth_publickey(username, key)
825
except paramiko.PasswordRequiredException:
826
password = bzrlib.ui.ui_factory.get_password(
827
prompt='SSH %(filename)s password',
830
key = pkey_class.from_private_key_file(filename, password)
831
transport.auth_publickey(username, key)
833
except paramiko.SSHException:
834
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
835
except paramiko.SSHException:
836
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
841
def _sftp_open_exclusive(self, abspath, mode=None):
842
"""Open a remote path exclusively.
844
SFTP supports O_EXCL (SFTP_FLAG_EXCL), which fails if
845
the file already exists. However it does not expose this
846
at the higher level of SFTPClient.open(), so we have to
849
WARNING: This breaks the SFTPClient abstraction, so it
850
could easily break against an updated version of paramiko.
852
:param abspath: The remote absolute path where the file should be opened
853
:param mode: The mode permissions bits for the new file
855
path = self._sftp._adjust_cwd(abspath)
856
# mutter('sftp abspath %s => %s', abspath, path)
857
attr = SFTPAttributes()
860
omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
861
| SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
863
t, msg = self._sftp._request(CMD_OPEN, path, omode, attr)
865
raise TransportError('Expected an SFTP handle')
866
handle = msg.get_string()
867
return SFTPFile(self._sftp, handle, 'wb', -1)
868
except (paramiko.SSHException, IOError), e:
869
self._translate_io_exception(e, abspath, ': unable to open',
870
failure_exc=FileExists)
873
# ------------- server test implementation --------------
877
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
879
STUB_SERVER_KEY = """
880
-----BEGIN RSA PRIVATE KEY-----
881
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
882
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
883
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
884
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
885
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
886
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
887
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
888
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
889
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
890
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
891
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
892
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
893
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
894
-----END RSA PRIVATE KEY-----
898
class SocketListener(threading.Thread):
900
def __init__(self, callback):
901
threading.Thread.__init__(self)
902
self._callback = callback
903
self._socket = socket.socket()
904
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
905
self._socket.bind(('localhost', 0))
906
self._socket.listen(1)
907
self.port = self._socket.getsockname()[1]
908
self._stop_event = threading.Event()
911
# called from outside this thread
912
self._stop_event.set()
913
# use a timeout here, because if the test fails, the server thread may
914
# never notice the stop_event.
920
readable, writable_unused, exception_unused = \
921
select.select([self._socket], [], [], 0.1)
922
if self._stop_event.isSet():
924
if len(readable) == 0:
927
s, addr_unused = self._socket.accept()
928
# because the loopback socket is inline, and transports are
929
# never explicitly closed, best to launch a new thread.
930
threading.Thread(target=self._callback, args=(s,)).start()
931
except socket.error, x:
932
sys.excepthook(*sys.exc_info())
933
warning('Socket error during accept() within unit test server'
936
# probably a failed test; unit test thread will log the
938
sys.excepthook(*sys.exc_info())
939
warning('Exception from within unit test server thread: %r' %
943
class SFTPServer(Server):
944
"""Common code for SFTP server facilities."""
947
self._original_vendor = None
949
self._server_homedir = None
950
self._listener = None
952
self._vendor = 'none'
956
def _get_sftp_url(self, path):
957
"""Calculate an sftp url to this server for path."""
958
return 'sftp://foo:bar@localhost:%d/%s' % (self._listener.port, path)
960
def log(self, message):
961
"""StubServer uses this to log when a new server is created."""
962
self.logs.append(message)
964
def _run_server(self, s):
965
ssh_server = paramiko.Transport(s)
966
key_file = pathjoin(self._homedir, 'test_rsa.key')
967
f = open(key_file, 'w')
968
f.write(STUB_SERVER_KEY)
970
host_key = paramiko.RSAKey.from_private_key_file(key_file)
971
ssh_server.add_server_key(host_key)
972
server = StubServer(self)
973
ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
974
StubSFTPServer, root=self._root,
975
home=self._server_homedir)
976
event = threading.Event()
977
ssh_server.start_server(event, server)
982
self._original_vendor = _ssh_vendor
983
_ssh_vendor = self._vendor
984
if sys.platform == 'win32':
985
# Win32 needs to use the UNICODE api
986
self._homedir = getcwd()
988
# But Linux SFTP servers should just deal in bytestreams
989
self._homedir = os.getcwd()
990
if self._server_homedir is None:
991
self._server_homedir = self._homedir
993
if sys.platform == 'win32':
995
self._listener = SocketListener(self._run_server)
996
self._listener.setDaemon(True)
997
self._listener.start()
1000
"""See bzrlib.transport.Server.tearDown."""
1002
self._listener.stop()
1003
_ssh_vendor = self._original_vendor
1005
def get_bogus_url(self):
1006
"""See bzrlib.transport.Server.get_bogus_url."""
1007
# this is chosen to try to prevent trouble with proxies, wierd dns,
1009
return 'sftp://127.0.0.1:1/'
1013
class SFTPFullAbsoluteServer(SFTPServer):
1014
"""A test server for sftp transports, using absolute urls and ssh."""
1017
"""See bzrlib.transport.Server.get_url."""
1018
return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1021
class SFTPServerWithoutSSH(SFTPServer):
1022
"""An SFTP server that uses a simple TCP socket pair rather than SSH."""
1025
super(SFTPServerWithoutSSH, self).__init__()
1026
self._vendor = 'loopback'
1028
def _run_server(self, sock):
1029
class FakeChannel(object):
1030
def get_transport(self):
1032
def get_log_channel(self):
1036
def get_hexdump(self):
1041
server = paramiko.SFTPServer(FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
1042
root=self._root, home=self._server_homedir)
1044
server.start_subsystem('sftp', None, sock)
1045
except socket.error, e:
1046
if (len(e.args) > 0) and (e.args[0] == errno.EPIPE):
1047
# it's okay for the client to disconnect abruptly
1048
# (bug in paramiko 1.6: it should absorb this exception)
1052
except Exception, e:
1053
import sys; sys.stderr.write('\nEXCEPTION %r\n\n' % e.__class__)
1054
server.finish_subsystem()
1057
class SFTPAbsoluteServer(SFTPServerWithoutSSH):
1058
"""A test server for sftp transports, using absolute urls."""
1061
"""See bzrlib.transport.Server.get_url."""
1062
if sys.platform == 'win32':
1063
return self._get_sftp_url(urlutils.escape(self._homedir))
1065
return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1068
class SFTPHomeDirServer(SFTPServerWithoutSSH):
1069
"""A test server for sftp transports, using homedir relative urls."""
1072
"""See bzrlib.transport.Server.get_url."""
1073
return self._get_sftp_url("~/")
1076
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
1077
"""A test servere for sftp transports, using absolute urls to non-home."""
1080
self._server_homedir = '/dev/noone/runs/tests/here'
1081
super(SFTPSiblingAbsoluteServer, self).setUp()
1084
def get_test_permutations():
1085
"""Return the permutations to be used in testing."""
1086
return [(SFTPTransport, SFTPAbsoluteServer),
1087
(SFTPTransport, SFTPHomeDirServer),
1088
(SFTPTransport, SFTPSiblingAbsoluteServer),