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.errors import (FileExists,
33
TransportNotPossible, NoSuchFile, NonRelativePath,
36
from bzrlib.config import config_dir
37
from bzrlib.trace import mutter, warning, error
38
from bzrlib.transport import Transport, register_transport
39
from bzrlib.ui import ui_factory
44
error('The SFTP transport requires paramiko.')
47
from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
48
SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
50
from paramiko.sftp_attr import SFTPAttributes
51
from paramiko.sftp_file import SFTPFile
52
from paramiko.sftp_client import SFTPClient
54
if 'sftp' not in urlparse.uses_netloc: urlparse.uses_netloc.append('sftp')
58
if sys.platform == 'win32':
59
# close_fds not supported on win32
63
def _get_ssh_vendor():
64
"""Find out what version of SSH is on the system."""
66
if _ssh_vendor is not None:
72
p = subprocess.Popen(['ssh', '-V'],
74
stdin=subprocess.PIPE,
75
stdout=subprocess.PIPE,
76
stderr=subprocess.PIPE)
77
returncode = p.returncode
78
stdout, stderr = p.communicate()
82
if 'OpenSSH' in stderr:
83
mutter('ssh implementation is OpenSSH')
84
_ssh_vendor = 'openssh'
85
elif 'SSH Secure Shell' in stderr:
86
mutter('ssh implementation is SSH Corp.')
89
if _ssh_vendor != 'none':
92
# XXX: 20051123 jamesh
93
# A check for putty's plink or lsh would go here.
95
mutter('falling back to paramiko implementation')
100
"""A socket-like object that talks to an ssh subprocess via pipes."""
101
def __init__(self, hostname, port=None, user=None):
102
vendor = _get_ssh_vendor()
103
assert vendor in ['openssh', 'ssh']
104
if vendor == 'openssh':
106
'-oForwardX11=no', '-oForwardAgent=no',
107
'-oClearAllForwardings=yes', '-oProtocol=2',
108
'-oNoHostAuthenticationForLocalhost=yes']
110
args.extend(['-p', str(port)])
112
args.extend(['-l', user])
113
args.extend(['-s', hostname, 'sftp'])
114
elif vendor == 'ssh':
117
args.extend(['-p', str(port)])
119
args.extend(['-l', user])
120
args.extend(['-s', 'sftp', hostname])
122
self.proc = subprocess.Popen(args, close_fds=_close_fds,
123
stdin=subprocess.PIPE,
124
stdout=subprocess.PIPE)
126
def send(self, data):
127
return os.write(self.proc.stdin.fileno(), data)
129
def recv(self, count):
130
return os.read(self.proc.stdout.fileno(), count)
133
self.proc.stdin.close()
134
self.proc.stdout.close()
141
# This is a weakref dictionary, so that we can reuse connections
142
# that are still active. Long term, it might be nice to have some
143
# sort of expiration policy, such as disconnect if inactive for
144
# X seconds. But that requires a lot more fanciness.
145
_connected_hosts = weakref.WeakValueDictionary()
147
def load_host_keys():
149
Load system host keys (probably doesn't work on windows) and any
150
"discovered" keys from previous sessions.
152
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
154
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
156
mutter('failed to load system host keys: ' + str(e))
157
bzr_hostkey_path = os.path.join(config_dir(), 'ssh_host_keys')
159
BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
161
mutter('failed to load bzr host keys: ' + str(e))
164
def save_host_keys():
166
Save "discovered" host keys in $(config)/ssh_host_keys/.
168
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
169
bzr_hostkey_path = os.path.join(config_dir(), 'ssh_host_keys')
170
if not os.path.isdir(config_dir()):
171
os.mkdir(config_dir())
173
f = open(bzr_hostkey_path, 'w')
174
f.write('# SSH host keys collected by bzr\n')
175
for hostname, keys in BZR_HOSTKEYS.iteritems():
176
for keytype, key in keys.iteritems():
177
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
180
mutter('failed to save bzr host keys: ' + str(e))
184
class SFTPTransportError (TransportError):
187
class SFTPLock(object):
188
"""This fakes a lock in a remote location."""
189
__slots__ = ['path', 'lock_path', 'lock_file', 'transport']
190
def __init__(self, path, transport):
191
assert isinstance(transport, SFTPTransport)
193
self.lock_file = None
195
self.lock_path = path + '.write-lock'
196
self.transport = transport
198
self.lock_file = transport._sftp_open_exclusive(self.lock_path)
200
raise LockError('File %r already locked' % (self.path,))
203
"""Should this warn, or actually try to cleanup?"""
205
warn("SFTPLock %r not explicitly unlocked" % (self.path,))
209
if not self.lock_file:
211
self.lock_file.close()
212
self.lock_file = None
214
self.transport.delete(self.lock_path)
215
except (NoSuchFile,):
216
# What specific errors should we catch here?
219
class SFTPTransport (Transport):
221
Transport implementation for SFTP access.
223
_do_prefetch = False # Right now Paramiko's prefetch support causes things to hang
225
def __init__(self, base, clone_from=None):
226
assert base.startswith('sftp://')
227
self._parse_url(base)
228
base = self._unparse_url()
229
super(SFTPTransport, self).__init__(base)
230
if clone_from is None:
233
# use the same ssh connection, etc
234
self._sftp = clone_from._sftp
235
# super saves 'self.base'
237
def should_cache(self):
239
Return True if the data pulled across should be cached locally.
243
def clone(self, offset=None):
245
Return a new SFTPTransport with root at self.base + offset.
246
We share the same SFTP session between such transports, because it's
247
fairly expensive to set them up.
250
return SFTPTransport(self.base, self)
252
return SFTPTransport(self.abspath(offset), self)
254
def abspath(self, relpath):
256
Return the full url to the given relative path.
258
@param relpath: the relative path or path components
259
@type relpath: str or list
261
return self._unparse_url(self._abspath(relpath))
263
def _abspath(self, relpath):
264
"""Return the absolute path segment without the SFTP URL."""
265
# FIXME: share the common code across transports
266
assert isinstance(relpath, basestring)
267
relpath = [urllib.unquote(relpath)]
268
basepath = self._path.split('/')
269
if len(basepath) > 0 and basepath[-1] == '':
270
basepath = basepath[:-1]
274
if len(basepath) == 0:
275
# In most filesystems, a request for the parent
276
# of root, just returns root.
284
path = '/'.join(basepath)
285
# could still be a "relative" path here, but relative on the sftp server
288
def relpath(self, abspath):
289
username, password, host, port, path = self._split_url(abspath)
291
if (username != self._username):
292
error.append('username mismatch')
293
if (host != self._host):
294
error.append('host mismatch')
295
if (port != self._port):
296
error.append('port mismatch')
297
if (not path.startswith(self._path)):
298
error.append('path mismatch')
300
raise NonRelativePath('path %r is not under base URL %r: %s'
301
% (abspath, self.base, ', '.join(error)))
303
return path[pl:].lstrip('/')
305
def has(self, relpath):
307
Does the target location exist?
310
self._sftp.stat(self._abspath(relpath))
315
def get(self, relpath, decode=False):
317
Get the file at the given relative path.
319
:param relpath: The relative path to the file
322
path = self._abspath(relpath)
323
f = self._sftp.file(path)
324
if self._do_prefetch and hasattr(f, 'prefetch'):
327
except (IOError, paramiko.SSHException), x:
328
raise NoSuchFile('Error retrieving %s: %s' % (path, str(x)), x)
330
def get_partial(self, relpath, start, length=None):
332
Get just part of a file.
334
:param relpath: Path to the file, relative to base
335
:param start: The starting position to read from
336
:param length: The length to read. A length of None indicates
337
read to the end of the file.
338
:return: A file-like object containing at least the specified bytes.
339
Some implementations may return objects which can be read
340
past this length, but this is not guaranteed.
342
# TODO: implement get_partial_multi to help with knit support
343
f = self.get(relpath)
345
if self._do_prefetch and hasattr(f, 'prefetch'):
349
def put(self, relpath, f):
351
Copy the file-like or string object into the location.
353
:param relpath: Location to put the contents, relative to base.
354
:param f: File-like or string object.
356
final_path = self._abspath(relpath)
357
tmp_relpath = '%s.tmp.%.9f.%d.%d' % (relpath, time.time(),
358
os.getpid(), random.randint(0,0x7FFFFFFF))
359
tmp_abspath = self._abspath(tmp_relpath)
360
fout = self._sftp_open_exclusive(tmp_relpath)
366
self._translate_io_exception(e, relpath)
367
except paramiko.SSHException, x:
368
raise SFTPTransportError('Unable to write file %r' % (relpath,), x)
370
# If we fail, try to clean up the temporary file
371
# before we throw the exception
372
# but don't let another exception mess things up
375
self._sftp.remove(tmp_abspath)
380
# sftp rename doesn't allow overwriting, so play tricks:
381
tmp_safety = 'bzr.tmp.%.9f.%d.%d' % (time.time(), os.getpid(), random.randint(0, 0x7FFFFFFF))
382
tmp_safety = self._abspath(tmp_safety)
384
self._sftp.rename(final_path, tmp_safety)
391
self._sftp.rename(tmp_abspath, final_path)
393
self._translate_io_exception(e, relpath)
394
except paramiko.SSHException, x:
395
raise SFTPTransportError('Unable to rename into file %r' % (path,), x)
401
self._sftp.unlink(tmp_safety)
403
self._sftp.rename(tmp_safety, final_path)
405
def iter_files_recursive(self):
406
"""Walk the relative paths of all files in this transport."""
407
queue = list(self.list_dir('.'))
409
relpath = urllib.quote(queue.pop(0))
410
st = self.stat(relpath)
411
if stat.S_ISDIR(st.st_mode):
412
for i, basename in enumerate(self.list_dir(relpath)):
413
queue.insert(i, relpath+'/'+basename)
417
def mkdir(self, relpath):
418
"""Create a directory at the given path."""
420
path = self._abspath(relpath)
421
self._sftp.mkdir(path)
423
self._translate_io_exception(e, relpath)
424
except (IOError, paramiko.SSHException), x:
425
raise SFTPTransportError('Unable to mkdir %r' % (path,), x)
427
def _translate_io_exception(self, e, relpath):
428
# paramiko seems to generate detailless errors.
429
if (e.errno == errno.ENOENT or
430
e.args == ('No such file or directory',) or
431
e.args == ('No such file',)):
432
raise NoSuchFile(relpath)
433
if (e.args == ('mkdir failed',)):
434
raise FileExists(relpath)
435
# strange but true, for the paramiko server.
436
if (e.args == ('Failure',)):
437
raise FileExists(relpath)
440
def append(self, relpath, f):
442
Append the text in the file-like object into the final
446
path = self._abspath(relpath)
447
fout = self._sftp.file(path, 'ab')
449
except (IOError, paramiko.SSHException), x:
450
raise SFTPTransportError('Unable to append file %r' % (path,), x)
452
def copy(self, rel_from, rel_to):
453
"""Copy the item at rel_from to the location at rel_to"""
454
path_from = self._abspath(rel_from)
455
path_to = self._abspath(rel_to)
456
self._copy_abspaths(path_from, path_to)
458
def _copy_abspaths(self, path_from, path_to):
459
"""Copy files given an absolute path
461
:param path_from: Path on remote server to read
462
:param path_to: Path on remote server to write
465
TODO: Should the destination location be atomically created?
466
This has not been specified
467
TODO: This should use some sort of remote copy, rather than
468
pulling the data locally, and then writing it remotely
471
fin = self._sftp.file(path_from, 'rb')
473
fout = self._sftp.file(path_to, 'wb')
475
fout.set_pipelined(True)
476
self._pump(fin, fout)
481
except (IOError, paramiko.SSHException), x:
482
raise SFTPTransportError('Unable to copy %r to %r' % (path_from, path_to), x)
484
def copy_to(self, relpaths, other, pb=None):
485
"""Copy a set of entries from self into another Transport.
487
:param relpaths: A list/generator of entries to be copied.
489
if isinstance(other, SFTPTransport) and other._sftp is self._sftp:
490
# Both from & to are on the same remote filesystem
491
# We can use a remote copy, instead of pulling locally, and pushing
493
total = self._get_total(relpaths)
495
for path in relpaths:
496
path_from = self._abspath(relpath)
497
path_to = other._abspath(relpath)
498
self._update_pb(pb, 'copy-to', count, total)
499
self._copy_abspaths(path_from, path_to)
503
return super(SFTPTransport, self).copy_to(relpaths, other, pb=pb)
505
# The dummy implementation just does a simple get + put
506
def copy_entry(path):
507
other.put(path, self.get(path))
509
return self._iterate_over(relpaths, copy_entry, pb, 'copy_to', expand=False)
511
def move(self, rel_from, rel_to):
512
"""Move the item at rel_from to the location at rel_to"""
513
path_from = self._abspath(rel_from)
514
path_to = self._abspath(rel_to)
516
self._sftp.rename(path_from, path_to)
517
except (IOError, paramiko.SSHException), x:
518
raise SFTPTransportError('Unable to move %r to %r' % (path_from, path_to), x)
520
def delete(self, relpath):
521
"""Delete the item at relpath"""
522
path = self._abspath(relpath)
524
self._sftp.remove(path)
525
except (IOError, paramiko.SSHException), x:
526
raise SFTPTransportError('Unable to delete %r' % (path,), x)
529
"""Return True if this store supports listing."""
532
def list_dir(self, relpath):
534
Return a list of all files at the given location.
536
# does anything actually use this?
537
path = self._abspath(relpath)
539
return self._sftp.listdir(path)
540
except (IOError, paramiko.SSHException), x:
541
raise SFTPTransportError('Unable to list folder %r' % (path,), x)
543
def stat(self, relpath):
544
"""Return the stat information for a file."""
545
path = self._abspath(relpath)
547
return self._sftp.stat(path)
548
except (IOError, paramiko.SSHException), x:
549
raise SFTPTransportError('Unable to stat %r' % (path,), x)
551
def lock_read(self, relpath):
553
Lock the given file for shared (read) access.
554
:return: A lock object, which has an unlock() member function
556
# FIXME: there should be something clever i can do here...
557
class BogusLock(object):
558
def __init__(self, path):
562
return BogusLock(relpath)
564
def lock_write(self, relpath):
566
Lock the given file for exclusive (write) access.
567
WARNING: many transports do not support this, so trying avoid using it
569
:return: A lock object, which has an unlock() member function
571
# This is a little bit bogus, but basically, we create a file
572
# which should not already exist, and if it does, we assume
573
# that there is a lock, and if it doesn't, the we assume
574
# that we have taken the lock.
575
return SFTPLock(relpath, self)
578
def _unparse_url(self, path=None):
581
path = urllib.quote(path)
582
if path.startswith('/'):
583
path = '/%2F' + path[1:]
586
netloc = urllib.quote(self._host)
587
if self._username is not None:
588
netloc = '%s@%s' % (urllib.quote(self._username), netloc)
589
if self._port is not None:
590
netloc = '%s:%d' % (netloc, self._port)
592
return urlparse.urlunparse(('sftp', netloc, path, '', '', ''))
594
def _split_url(self, url):
595
if isinstance(url, unicode):
596
url = url.encode('utf-8')
597
(scheme, netloc, path, params,
598
query, fragment) = urlparse.urlparse(url, allow_fragments=False)
599
assert scheme == 'sftp'
600
username = password = host = port = None
602
username, host = netloc.split('@', 1)
604
username, password = username.split(':', 1)
605
password = urllib.unquote(password)
606
username = urllib.unquote(username)
611
host, port = host.rsplit(':', 1)
615
raise SFTPTransportError('%s: invalid port number' % port)
616
host = urllib.unquote(host)
618
path = urllib.unquote(path)
620
# the initial slash should be removed from the path, and treated
621
# as a homedir relative path (the path begins with a double slash
622
# if it is absolute).
623
# see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
624
if path.startswith('/'):
627
return (username, password, host, port, path)
629
def _parse_url(self, url):
630
(self._username, self._password,
631
self._host, self._port, self._path) = self._split_url(url)
633
def _sftp_connect(self):
634
"""Connect to the remote sftp server.
635
After this, self._sftp should have a valid connection (or
636
we raise an SFTPTransportError 'could not connect').
638
TODO: Raise a more reasonable ConnectionFailed exception
640
global _connected_hosts
642
idx = (self._host, self._port, self._username)
644
self._sftp = _connected_hosts[idx]
649
vendor = _get_ssh_vendor()
651
sock = SFTPSubprocess(self._host, self._port, self._username)
652
self._sftp = SFTPClient(sock)
654
self._paramiko_connect()
656
_connected_hosts[idx] = self._sftp
658
def _paramiko_connect(self):
659
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
664
t = paramiko.Transport((self._host, self._port))
666
except paramiko.SSHException:
667
raise SFTPTransportError('Unable to reach SSH host %s:%d' % (self._host, self._port))
669
server_key = t.get_remote_server_key()
670
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
671
keytype = server_key.get_name()
672
if SYSTEM_HOSTKEYS.has_key(self._host) and SYSTEM_HOSTKEYS[self._host].has_key(keytype):
673
our_server_key = SYSTEM_HOSTKEYS[self._host][keytype]
674
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
675
elif BZR_HOSTKEYS.has_key(self._host) and BZR_HOSTKEYS[self._host].has_key(keytype):
676
our_server_key = BZR_HOSTKEYS[self._host][keytype]
677
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
679
warning('Adding %s host key for %s: %s' % (keytype, self._host, server_key_hex))
680
if not BZR_HOSTKEYS.has_key(self._host):
681
BZR_HOSTKEYS[self._host] = {}
682
BZR_HOSTKEYS[self._host][keytype] = server_key
683
our_server_key = server_key
684
our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
686
if server_key != our_server_key:
687
filename1 = os.path.expanduser('~/.ssh/known_hosts')
688
filename2 = os.path.join(config_dir(), 'ssh_host_keys')
689
raise SFTPTransportError('Host keys for %s do not match! %s != %s' % \
690
(self._host, our_server_key_hex, server_key_hex),
691
['Try editing %s or %s' % (filename1, filename2)])
696
self._sftp = t.open_sftp_client()
697
except paramiko.SSHException:
698
raise BzrError('Unable to find path %s on SFTP server %s' % \
699
(self._path, self._host))
701
def _sftp_auth(self, transport):
702
# paramiko requires a username, but it might be none if nothing was supplied
703
# use the local username, just in case.
704
# We don't override self._username, because if we aren't using paramiko,
705
# the username might be specified in ~/.ssh/config and we don't want to
706
# force it to something else
707
# Also, it would mess up the self.relpath() functionality
708
username = self._username or getpass.getuser()
710
agent = paramiko.Agent()
711
for key in agent.get_keys():
712
mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
714
transport.auth_publickey(username, key)
716
except paramiko.SSHException, e:
719
# okay, try finding id_rsa or id_dss? (posix only)
720
if self._try_pkey_auth(transport, paramiko.RSAKey, username, 'id_rsa'):
722
if self._try_pkey_auth(transport, paramiko.DSSKey, username, 'id_dsa'):
728
transport.auth_password(username, self._password)
730
except paramiko.SSHException, e:
733
# FIXME: Don't keep a password held in memory if you can help it
734
#self._password = None
736
# give up and ask for a password
737
password = ui_factory.get_password(prompt='SSH %(user)s@%(host)s password',
738
user=username, host=self._host)
740
transport.auth_password(username, password)
741
except paramiko.SSHException:
742
raise SFTPTransportError('Unable to authenticate to SSH host as %s@%s' % \
743
(username, self._host))
745
def _try_pkey_auth(self, transport, pkey_class, username, filename):
746
filename = os.path.expanduser('~/.ssh/' + filename)
748
key = pkey_class.from_private_key_file(filename)
749
transport.auth_publickey(username, key)
751
except paramiko.PasswordRequiredException:
752
password = ui_factory.get_password(prompt='SSH %(filename)s password',
755
key = pkey_class.from_private_key_file(filename, password)
756
transport.auth_publickey(username, key)
758
except paramiko.SSHException:
759
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
760
except paramiko.SSHException:
761
mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
766
def _sftp_open_exclusive(self, relpath):
767
"""Open a remote path exclusively.
769
SFTP supports O_EXCL (SFTP_FLAG_EXCL), which fails if
770
the file already exists. However it does not expose this
771
at the higher level of SFTPClient.open(), so we have to
774
WARNING: This breaks the SFTPClient abstraction, so it
775
could easily break against an updated version of paramiko.
777
:param relpath: The relative path, where the file should be opened
779
path = self._sftp._adjust_cwd(self._abspath(relpath))
780
attr = SFTPAttributes()
781
mode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
782
| SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
784
t, msg = self._sftp._request(CMD_OPEN, path, mode, attr)
786
raise SFTPTransportError('Expected an SFTP handle')
787
handle = msg.get_string()
788
return SFTPFile(self._sftp, handle, 'w', -1)
790
self._translate_io_exception(e, relpath)
791
except paramiko.SSHException, x:
792
raise SFTPTransportError('Unable to open file %r' % (path,), x)