/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/sftp.py

Merge from mbp.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>, Canonical Ltd
 
2
 
 
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.
 
7
 
 
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.
 
12
 
 
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
 
16
 
 
17
"""Implementation of Transport over SFTP, using paramiko."""
 
18
 
 
19
import errno
 
20
import getpass
 
21
import os
 
22
import re
 
23
import stat
 
24
import sys
 
25
import urllib
 
26
import urlparse
 
27
import time
 
28
import random
 
29
import subprocess
 
30
import weakref
 
31
 
 
32
from bzrlib.errors import (FileExists, 
 
33
                           TransportNotPossible, NoSuchFile, NonRelativePath,
 
34
                           TransportError,
 
35
                           LockError)
 
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
 
40
 
 
41
try:
 
42
    import paramiko
 
43
except ImportError:
 
44
    error('The SFTP transport requires paramiko.')
 
45
    raise
 
46
else:
 
47
    from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
 
48
                               SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
 
49
                               CMD_HANDLE, CMD_OPEN)
 
50
    from paramiko.sftp_attr import SFTPAttributes
 
51
    from paramiko.sftp_file import SFTPFile
 
52
    from paramiko.sftp_client import SFTPClient
 
53
 
 
54
if 'sftp' not in urlparse.uses_netloc: urlparse.uses_netloc.append('sftp')
 
55
 
 
56
 
 
57
_close_fds = True
 
58
if sys.platform == 'win32':
 
59
    # close_fds not supported on win32
 
60
    _close_fds = False
 
61
 
 
62
_ssh_vendor = None
 
63
def _get_ssh_vendor():
 
64
    """Find out what version of SSH is on the system."""
 
65
    global _ssh_vendor
 
66
    if _ssh_vendor is not None:
 
67
        return _ssh_vendor
 
68
 
 
69
    _ssh_vendor = 'none'
 
70
 
 
71
    try:
 
72
        p = subprocess.Popen(['ssh', '-V'],
 
73
                             close_fds=_close_fds,
 
74
                             stdin=subprocess.PIPE,
 
75
                             stdout=subprocess.PIPE,
 
76
                             stderr=subprocess.PIPE)
 
77
        returncode = p.returncode
 
78
        stdout, stderr = p.communicate()
 
79
    except OSError:
 
80
        returncode = -1
 
81
        stdout = stderr = ''
 
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.')
 
87
        _ssh_vendor = 'ssh'
 
88
 
 
89
    if _ssh_vendor != 'none':
 
90
        return _ssh_vendor
 
91
 
 
92
    # XXX: 20051123 jamesh
 
93
    # A check for putty's plink or lsh would go here.
 
94
 
 
95
    mutter('falling back to paramiko implementation')
 
96
    return _ssh_vendor
 
97
 
 
98
 
 
99
class SFTPSubprocess:
 
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':
 
105
            args = ['ssh',
 
106
                    '-oForwardX11=no', '-oForwardAgent=no',
 
107
                    '-oClearAllForwardings=yes', '-oProtocol=2',
 
108
                    '-oNoHostAuthenticationForLocalhost=yes']
 
109
            if port is not None:
 
110
                args.extend(['-p', str(port)])
 
111
            if user is not None:
 
112
                args.extend(['-l', user])
 
113
            args.extend(['-s', hostname, 'sftp'])
 
114
        elif vendor == 'ssh':
 
115
            args = ['ssh', '-x']
 
116
            if port is not None:
 
117
                args.extend(['-p', str(port)])
 
118
            if user is not None:
 
119
                args.extend(['-l', user])
 
120
            args.extend(['-s', 'sftp', hostname])
 
121
 
 
122
        self.proc = subprocess.Popen(args, close_fds=_close_fds,
 
123
                                     stdin=subprocess.PIPE,
 
124
                                     stdout=subprocess.PIPE)
 
125
 
 
126
    def send(self, data):
 
127
        return os.write(self.proc.stdin.fileno(), data)
 
128
 
 
129
    def recv(self, count):
 
130
        return os.read(self.proc.stdout.fileno(), count)
 
131
 
 
132
    def close(self):
 
133
        self.proc.stdin.close()
 
134
        self.proc.stdout.close()
 
135
        self.proc.wait()
 
136
 
 
137
 
 
138
SYSTEM_HOSTKEYS = {}
 
139
BZR_HOSTKEYS = {}
 
140
 
 
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()
 
146
 
 
147
def load_host_keys():
 
148
    """
 
149
    Load system host keys (probably doesn't work on windows) and any
 
150
    "discovered" keys from previous sessions.
 
151
    """
 
152
    global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
153
    try:
 
154
        SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
 
155
    except Exception, e:
 
156
        mutter('failed to load system host keys: ' + str(e))
 
157
    bzr_hostkey_path = os.path.join(config_dir(), 'ssh_host_keys')
 
158
    try:
 
159
        BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
 
160
    except Exception, e:
 
161
        mutter('failed to load bzr host keys: ' + str(e))
 
162
        save_host_keys()
 
163
 
 
164
def save_host_keys():
 
165
    """
 
166
    Save "discovered" host keys in $(config)/ssh_host_keys/.
 
167
    """
 
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())
 
172
    try:
 
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()))
 
178
        f.close()
 
179
    except IOError, e:
 
180
        mutter('failed to save bzr host keys: ' + str(e))
 
181
 
 
182
 
 
183
 
 
184
class SFTPTransportError (TransportError):
 
185
    pass
 
186
 
 
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)
 
192
 
 
193
        self.lock_file = None
 
194
        self.path = path
 
195
        self.lock_path = path + '.write-lock'
 
196
        self.transport = transport
 
197
        try:
 
198
            self.lock_file = transport._sftp_open_exclusive(self.lock_path)
 
199
        except FileExists:
 
200
            raise LockError('File %r already locked' % (self.path,))
 
201
 
 
202
    def __del__(self):
 
203
        """Should this warn, or actually try to cleanup?"""
 
204
        if self.lock_file:
 
205
            warn("SFTPLock %r not explicitly unlocked" % (self.path,))
 
206
            self.unlock()
 
207
 
 
208
    def unlock(self):
 
209
        if not self.lock_file:
 
210
            return
 
211
        self.lock_file.close()
 
212
        self.lock_file = None
 
213
        try:
 
214
            self.transport.delete(self.lock_path)
 
215
        except (NoSuchFile,):
 
216
            # What specific errors should we catch here?
 
217
            pass
 
218
 
 
219
class SFTPTransport (Transport):
 
220
    """
 
221
    Transport implementation for SFTP access.
 
222
    """
 
223
    _do_prefetch = False # Right now Paramiko's prefetch support causes things to hang
 
224
 
 
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:
 
231
            self._sftp_connect()
 
232
        else:
 
233
            # use the same ssh connection, etc
 
234
            self._sftp = clone_from._sftp
 
235
        # super saves 'self.base'
 
236
    
 
237
    def should_cache(self):
 
238
        """
 
239
        Return True if the data pulled across should be cached locally.
 
240
        """
 
241
        return True
 
242
 
 
243
    def clone(self, offset=None):
 
244
        """
 
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.
 
248
        """
 
249
        if offset is None:
 
250
            return SFTPTransport(self.base, self)
 
251
        else:
 
252
            return SFTPTransport(self.abspath(offset), self)
 
253
 
 
254
    def abspath(self, relpath):
 
255
        """
 
256
        Return the full url to the given relative path.
 
257
        
 
258
        @param relpath: the relative path or path components
 
259
        @type relpath: str or list
 
260
        """
 
261
        return self._unparse_url(self._abspath(relpath))
 
262
    
 
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]
 
271
 
 
272
        for p in relpath:
 
273
            if p == '..':
 
274
                if len(basepath) == 0:
 
275
                    # In most filesystems, a request for the parent
 
276
                    # of root, just returns root.
 
277
                    continue
 
278
                basepath.pop()
 
279
            elif p == '.':
 
280
                continue # No-op
 
281
            else:
 
282
                basepath.append(p)
 
283
 
 
284
        path = '/'.join(basepath)
 
285
        # could still be a "relative" path here, but relative on the sftp server
 
286
        return path
 
287
 
 
288
    def relpath(self, abspath):
 
289
        username, password, host, port, path = self._split_url(abspath)
 
290
        error = []
 
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')
 
299
        if error:
 
300
            raise NonRelativePath('path %r is not under base URL %r: %s'
 
301
                           % (abspath, self.base, ', '.join(error)))
 
302
        pl = len(self._path)
 
303
        return path[pl:].lstrip('/')
 
304
 
 
305
    def has(self, relpath):
 
306
        """
 
307
        Does the target location exist?
 
308
        """
 
309
        try:
 
310
            self._sftp.stat(self._abspath(relpath))
 
311
            return True
 
312
        except IOError:
 
313
            return False
 
314
 
 
315
    def get(self, relpath, decode=False):
 
316
        """
 
317
        Get the file at the given relative path.
 
318
 
 
319
        :param relpath: The relative path to the file
 
320
        """
 
321
        try:
 
322
            path = self._abspath(relpath)
 
323
            f = self._sftp.file(path)
 
324
            if self._do_prefetch and hasattr(f, 'prefetch'):
 
325
                f.prefetch()
 
326
            return f
 
327
        except (IOError, paramiko.SSHException), x:
 
328
            raise NoSuchFile('Error retrieving %s: %s' % (path, str(x)), x)
 
329
 
 
330
    def get_partial(self, relpath, start, length=None):
 
331
        """
 
332
        Get just part of a file.
 
333
 
 
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.
 
341
        """
 
342
        # TODO: implement get_partial_multi to help with knit support
 
343
        f = self.get(relpath)
 
344
        f.seek(start)
 
345
        if self._do_prefetch and hasattr(f, 'prefetch'):
 
346
            f.prefetch()
 
347
        return f
 
348
 
 
349
    def put(self, relpath, f):
 
350
        """
 
351
        Copy the file-like or string object into the location.
 
352
 
 
353
        :param relpath: Location to put the contents, relative to base.
 
354
        :param f:       File-like or string object.
 
355
        """
 
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)
 
361
 
 
362
        try:
 
363
            try:
 
364
                self._pump(f, fout)
 
365
            except IOError, e:
 
366
                self._translate_io_exception(e, relpath)
 
367
            except paramiko.SSHException, x:
 
368
                raise SFTPTransportError('Unable to write file %r' % (relpath,), x)
 
369
        except Exception, e:
 
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
 
373
            try:
 
374
                fout.close()
 
375
                self._sftp.remove(tmp_abspath)
 
376
            except:
 
377
                pass
 
378
            raise e
 
379
        else:
 
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)
 
383
            try:
 
384
                self._sftp.rename(final_path, tmp_safety)
 
385
                file_existed = True
 
386
            except:
 
387
                file_existed = False
 
388
            success = False
 
389
            try:
 
390
                try:
 
391
                    self._sftp.rename(tmp_abspath, final_path)
 
392
                except IOError, e:
 
393
                    self._translate_io_exception(e, relpath)
 
394
                except paramiko.SSHException, x:
 
395
                    raise SFTPTransportError('Unable to rename into file %r' % (path,), x) 
 
396
                else:
 
397
                    success = True
 
398
            finally:
 
399
                if file_existed:
 
400
                    if success:
 
401
                        self._sftp.unlink(tmp_safety)
 
402
                    else:
 
403
                        self._sftp.rename(tmp_safety, final_path)
 
404
 
 
405
    def iter_files_recursive(self):
 
406
        """Walk the relative paths of all files in this transport."""
 
407
        queue = list(self.list_dir('.'))
 
408
        while queue:
 
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)
 
414
            else:
 
415
                yield relpath
 
416
 
 
417
    def mkdir(self, relpath):
 
418
        """Create a directory at the given path."""
 
419
        try:
 
420
            path = self._abspath(relpath)
 
421
            self._sftp.mkdir(path)
 
422
        except IOError, e:
 
423
            self._translate_io_exception(e, relpath)
 
424
        except (IOError, paramiko.SSHException), x:
 
425
            raise SFTPTransportError('Unable to mkdir %r' % (path,), x)
 
426
 
 
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)
 
438
        raise
 
439
 
 
440
    def append(self, relpath, f):
 
441
        """
 
442
        Append the text in the file-like object into the final
 
443
        location.
 
444
        """
 
445
        try:
 
446
            path = self._abspath(relpath)
 
447
            fout = self._sftp.file(path, 'ab')
 
448
            self._pump(f, fout)
 
449
        except (IOError, paramiko.SSHException), x:
 
450
            raise SFTPTransportError('Unable to append file %r' % (path,), x)
 
451
 
 
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)
 
457
 
 
458
    def _copy_abspaths(self, path_from, path_to):
 
459
        """Copy files given an absolute path
 
460
 
 
461
        :param path_from: Path on remote server to read
 
462
        :param path_to: Path on remote server to write
 
463
        :return: None
 
464
 
 
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
 
469
        """
 
470
        try:
 
471
            fin = self._sftp.file(path_from, 'rb')
 
472
            try:
 
473
                fout = self._sftp.file(path_to, 'wb')
 
474
                try:
 
475
                    fout.set_pipelined(True)
 
476
                    self._pump(fin, fout)
 
477
                finally:
 
478
                    fout.close()
 
479
            finally:
 
480
                fin.close()
 
481
        except (IOError, paramiko.SSHException), x:
 
482
            raise SFTPTransportError('Unable to copy %r to %r' % (path_from, path_to), x)
 
483
 
 
484
    def copy_to(self, relpaths, other, pb=None):
 
485
        """Copy a set of entries from self into another Transport.
 
486
 
 
487
        :param relpaths: A list/generator of entries to be copied.
 
488
        """
 
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
 
492
 
 
493
            total = self._get_total(relpaths)
 
494
            count = 0
 
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)
 
500
                count += 1
 
501
            return count
 
502
        else:
 
503
            return super(SFTPTransport, self).copy_to(relpaths, other, pb=pb)
 
504
 
 
505
        # The dummy implementation just does a simple get + put
 
506
        def copy_entry(path):
 
507
            other.put(path, self.get(path))
 
508
 
 
509
        return self._iterate_over(relpaths, copy_entry, pb, 'copy_to', expand=False)
 
510
 
 
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)
 
515
        try:
 
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)
 
519
 
 
520
    def delete(self, relpath):
 
521
        """Delete the item at relpath"""
 
522
        path = self._abspath(relpath)
 
523
        try:
 
524
            self._sftp.remove(path)
 
525
        except (IOError, paramiko.SSHException), x:
 
526
            raise SFTPTransportError('Unable to delete %r' % (path,), x)
 
527
            
 
528
    def listable(self):
 
529
        """Return True if this store supports listing."""
 
530
        return True
 
531
 
 
532
    def list_dir(self, relpath):
 
533
        """
 
534
        Return a list of all files at the given location.
 
535
        """
 
536
        # does anything actually use this?
 
537
        path = self._abspath(relpath)
 
538
        try:
 
539
            return self._sftp.listdir(path)
 
540
        except (IOError, paramiko.SSHException), x:
 
541
            raise SFTPTransportError('Unable to list folder %r' % (path,), x)
 
542
 
 
543
    def stat(self, relpath):
 
544
        """Return the stat information for a file."""
 
545
        path = self._abspath(relpath)
 
546
        try:
 
547
            return self._sftp.stat(path)
 
548
        except (IOError, paramiko.SSHException), x:
 
549
            raise SFTPTransportError('Unable to stat %r' % (path,), x)
 
550
 
 
551
    def lock_read(self, relpath):
 
552
        """
 
553
        Lock the given file for shared (read) access.
 
554
        :return: A lock object, which has an unlock() member function
 
555
        """
 
556
        # FIXME: there should be something clever i can do here...
 
557
        class BogusLock(object):
 
558
            def __init__(self, path):
 
559
                self.path = path
 
560
            def unlock(self):
 
561
                pass
 
562
        return BogusLock(relpath)
 
563
 
 
564
    def lock_write(self, relpath):
 
565
        """
 
566
        Lock the given file for exclusive (write) access.
 
567
        WARNING: many transports do not support this, so trying avoid using it
 
568
 
 
569
        :return: A lock object, which has an unlock() member function
 
570
        """
 
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)
 
576
 
 
577
 
 
578
    def _unparse_url(self, path=None):
 
579
        if path is None:
 
580
            path = self._path
 
581
        path = urllib.quote(path)
 
582
        if path.startswith('/'):
 
583
            path = '/%2F' + path[1:]
 
584
        else:
 
585
            path = '/' + path
 
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)
 
591
 
 
592
        return urlparse.urlunparse(('sftp', netloc, path, '', '', ''))
 
593
 
 
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
 
601
        if '@' in netloc:
 
602
            username, host = netloc.split('@', 1)
 
603
            if ':' in username:
 
604
                username, password = username.split(':', 1)
 
605
                password = urllib.unquote(password)
 
606
            username = urllib.unquote(username)
 
607
        else:
 
608
            host = netloc
 
609
 
 
610
        if ':' in host:
 
611
            host, port = host.rsplit(':', 1)
 
612
            try:
 
613
                port = int(port)
 
614
            except ValueError:
 
615
                raise SFTPTransportError('%s: invalid port number' % port)
 
616
        host = urllib.unquote(host)
 
617
 
 
618
        path = urllib.unquote(path)
 
619
 
 
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('/'):
 
625
            path = path[1:]
 
626
 
 
627
        return (username, password, host, port, path)
 
628
 
 
629
    def _parse_url(self, url):
 
630
        (self._username, self._password,
 
631
         self._host, self._port, self._path) = self._split_url(url)
 
632
 
 
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').
 
637
 
 
638
        TODO: Raise a more reasonable ConnectionFailed exception
 
639
        """
 
640
        global _connected_hosts
 
641
 
 
642
        idx = (self._host, self._port, self._username)
 
643
        try:
 
644
            self._sftp = _connected_hosts[idx]
 
645
            return
 
646
        except KeyError:
 
647
            pass
 
648
        
 
649
        vendor = _get_ssh_vendor()
 
650
        if vendor != 'none':
 
651
            sock = SFTPSubprocess(self._host, self._port, self._username)
 
652
            self._sftp = SFTPClient(sock)
 
653
        else:
 
654
            self._paramiko_connect()
 
655
 
 
656
        _connected_hosts[idx] = self._sftp
 
657
 
 
658
    def _paramiko_connect(self):
 
659
        global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
660
        
 
661
        load_host_keys()
 
662
 
 
663
        try:
 
664
            t = paramiko.Transport((self._host, self._port))
 
665
            t.start_client()
 
666
        except paramiko.SSHException:
 
667
            raise SFTPTransportError('Unable to reach SSH host %s:%d' % (self._host, self._port))
 
668
            
 
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())
 
678
        else:
 
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())
 
685
            save_host_keys()
 
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)])
 
692
 
 
693
        self._sftp_auth(t)
 
694
        
 
695
        try:
 
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))
 
700
 
 
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()
 
709
 
 
710
        agent = paramiko.Agent()
 
711
        for key in agent.get_keys():
 
712
            mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
 
713
            try:
 
714
                transport.auth_publickey(username, key)
 
715
                return
 
716
            except paramiko.SSHException, e:
 
717
                pass
 
718
        
 
719
        # okay, try finding id_rsa or id_dss?  (posix only)
 
720
        if self._try_pkey_auth(transport, paramiko.RSAKey, username, 'id_rsa'):
 
721
            return
 
722
        if self._try_pkey_auth(transport, paramiko.DSSKey, username, 'id_dsa'):
 
723
            return
 
724
 
 
725
 
 
726
        if self._password:
 
727
            try:
 
728
                transport.auth_password(username, self._password)
 
729
                return
 
730
            except paramiko.SSHException, e:
 
731
                pass
 
732
 
 
733
            # FIXME: Don't keep a password held in memory if you can help it
 
734
            #self._password = None
 
735
 
 
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)
 
739
        try:
 
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))
 
744
 
 
745
    def _try_pkey_auth(self, transport, pkey_class, username, filename):
 
746
        filename = os.path.expanduser('~/.ssh/' + filename)
 
747
        try:
 
748
            key = pkey_class.from_private_key_file(filename)
 
749
            transport.auth_publickey(username, key)
 
750
            return True
 
751
        except paramiko.PasswordRequiredException:
 
752
            password = ui_factory.get_password(prompt='SSH %(filename)s password',
 
753
                                               filename=filename)
 
754
            try:
 
755
                key = pkey_class.from_private_key_file(filename, password)
 
756
                transport.auth_publickey(username, key)
 
757
                return True
 
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),))
 
762
        except IOError:
 
763
            pass
 
764
        return False
 
765
 
 
766
    def _sftp_open_exclusive(self, relpath):
 
767
        """Open a remote path exclusively.
 
768
 
 
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
 
772
        sneak away with it.
 
773
 
 
774
        WARNING: This breaks the SFTPClient abstraction, so it
 
775
        could easily break against an updated version of paramiko.
 
776
 
 
777
        :param relpath: The relative path, where the file should be opened
 
778
        """
 
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)
 
783
        try:
 
784
            t, msg = self._sftp._request(CMD_OPEN, path, mode, attr)
 
785
            if t != CMD_HANDLE:
 
786
                raise SFTPTransportError('Expected an SFTP handle')
 
787
            handle = msg.get_string()
 
788
            return SFTPFile(self._sftp, handle, 'w', -1)
 
789
        except IOError, e:
 
790
            self._translate_io_exception(e, relpath)
 
791
        except paramiko.SSHException, x:
 
792
            raise SFTPTransportError('Unable to open file %r' % (path,), x)
 
793