~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/sftp.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-08-17 07:52:09 UTC
  • mfrom: (1910.3.4 trivial)
  • Revision ID: pqm@pqm.ubuntu.com-20060817075209-e85a1f9e05ff8b87
(andrew) Trivial fixes to NotImplemented errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
2
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
# Copyright (C) 2005, 2006 Canonical Ltd
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
17
17
 
18
18
"""Implementation of Transport over SFTP, using paramiko."""
19
19
 
20
 
# TODO: Remove the transport-based lock_read and lock_write methods.  They'll
21
 
# then raise TransportNotPossible, which will break remote access to any
22
 
# formats which rely on OS-level locks.  That should be fine as those formats
23
 
# are pretty old, but these combinations may have to be removed from the test
24
 
# suite.  Those formats all date back to 0.7; so we should be able to remove
25
 
# these methods when we officially drop support for those formats.
26
 
 
27
20
import errno
 
21
import getpass
 
22
import itertools
28
23
import os
29
24
import random
 
25
import re
30
26
import select
31
27
import socket
32
28
import stat
 
29
import subprocess
33
30
import sys
34
31
import time
35
32
import urllib
36
33
import urlparse
37
 
import warnings
 
34
import weakref
38
35
 
39
 
from bzrlib import (
40
 
    errors,
41
 
    urlutils,
42
 
    )
43
 
from bzrlib.errors import (FileExists,
44
 
                           NoSuchFile, PathNotChild,
 
36
from bzrlib.config import config_dir, ensure_config_dir_exists
 
37
from bzrlib.errors import (ConnectionError,
 
38
                           FileExists, 
 
39
                           TransportNotPossible, NoSuchFile, PathNotChild,
45
40
                           TransportError,
46
 
                           LockError,
 
41
                           LockError, 
47
42
                           PathError,
48
43
                           ParamikoNotPresent,
49
44
                           )
50
45
from bzrlib.osutils import pathjoin, fancy_rename, getcwd
51
 
from bzrlib.symbol_versioning import (
52
 
        deprecated_function,
53
 
        zero_ninety,
54
 
        )
55
 
from bzrlib.trace import mutter, warning
 
46
from bzrlib.trace import mutter, warning, error
56
47
from bzrlib.transport import (
57
 
    FileFileStream,
58
 
    _file_streams,
59
 
    local,
60
48
    register_urlparse_netloc_protocol,
61
49
    Server,
62
 
    ssh,
63
 
    ConnectedTransport,
 
50
    split_url,
 
51
    Transport,
64
52
    )
65
 
 
66
 
# Disable one particular warning that comes from paramiko in Python2.5; if
67
 
# this is emitted at the wrong time it tends to cause spurious test failures
68
 
# or at least noise in the test case::
69
 
#
70
 
# [1770/7639 in 86s, 1 known failures, 50 skipped, 2 missing features]
71
 
# test_permissions.TestSftpPermissions.test_new_files
72
 
# /var/lib/python-support/python2.5/paramiko/message.py:226: DeprecationWarning: integer argument expected, got float
73
 
#  self.packet.write(struct.pack('>I', n))
74
 
warnings.filterwarnings('ignore',
75
 
        'integer argument expected, got float',
76
 
        category=DeprecationWarning,
77
 
        module='paramiko.message')
 
53
import bzrlib.ui
 
54
import bzrlib.urlutils as urlutils
78
55
 
79
56
try:
80
57
    import paramiko
86
63
                               CMD_HANDLE, CMD_OPEN)
87
64
    from paramiko.sftp_attr import SFTPAttributes
88
65
    from paramiko.sftp_file import SFTPFile
 
66
    from paramiko.sftp_client import SFTPClient
89
67
 
90
68
 
91
69
register_urlparse_netloc_protocol('sftp')
92
70
 
93
71
 
 
72
def _ignore_sigint():
 
73
    # TODO: This should possibly ignore SIGHUP as well, but bzr currently
 
74
    # doesn't handle it itself.
 
75
    # <https://launchpad.net/products/bzr/+bug/41433/+index>
 
76
    import signal
 
77
    signal.signal(signal.SIGINT, signal.SIG_IGN)
 
78
    
 
79
 
 
80
def os_specific_subprocess_params():
 
81
    """Get O/S specific subprocess parameters."""
 
82
    if sys.platform == 'win32':
 
83
        # setting the process group and closing fds is not supported on 
 
84
        # win32
 
85
        return {}
 
86
    else:
 
87
        # We close fds other than the pipes as the child process does not need 
 
88
        # them to be open.
 
89
        #
 
90
        # We also set the child process to ignore SIGINT.  Normally the signal
 
91
        # would be sent to every process in the foreground process group, but
 
92
        # this causes it to be seen only by bzr and not by ssh.  Python will
 
93
        # generate a KeyboardInterrupt in bzr, and we will then have a chance
 
94
        # to release locks or do other cleanup over ssh before the connection
 
95
        # goes away.  
 
96
        # <https://launchpad.net/products/bzr/+bug/5987>
 
97
        #
 
98
        # Running it in a separate process group is not good because then it
 
99
        # can't get non-echoed input of a password or passphrase.
 
100
        # <https://launchpad.net/products/bzr/+bug/40508>
 
101
        return {'preexec_fn': _ignore_sigint,
 
102
                'close_fds': True,
 
103
                }
 
104
 
 
105
 
94
106
_paramiko_version = getattr(paramiko, '__version_info__', (0, 0, 0))
95
107
# don't use prefetch unless paramiko version >= 1.5.5 (there were bugs earlier)
96
108
_default_do_prefetch = (_paramiko_version >= (1, 5, 5))
97
109
 
98
 
 
99
 
@deprecated_function(zero_ninety)
 
110
# Paramiko 1.5 tries to open a socket.AF_UNIX in order to connect
 
111
# to ssh-agent. That attribute doesn't exist on win32 (it does in cygwin)
 
112
# so we get an AttributeError exception. So we will not try to
 
113
# connect to an agent if we are on win32 and using Paramiko older than 1.6
 
114
_use_ssh_agent = (sys.platform != 'win32' or _paramiko_version >= (1, 6, 0))
 
115
 
 
116
 
 
117
_ssh_vendor = None
 
118
def _get_ssh_vendor():
 
119
    """Find out what version of SSH is on the system."""
 
120
    global _ssh_vendor
 
121
    if _ssh_vendor is not None:
 
122
        return _ssh_vendor
 
123
 
 
124
    _ssh_vendor = 'none'
 
125
 
 
126
    if 'BZR_SSH' in os.environ:
 
127
        _ssh_vendor = os.environ['BZR_SSH']
 
128
        if _ssh_vendor == 'paramiko':
 
129
            _ssh_vendor = 'none'
 
130
        return _ssh_vendor
 
131
 
 
132
    try:
 
133
        p = subprocess.Popen(['ssh', '-V'],
 
134
                             stdin=subprocess.PIPE,
 
135
                             stdout=subprocess.PIPE,
 
136
                             stderr=subprocess.PIPE,
 
137
                             **os_specific_subprocess_params())
 
138
        returncode = p.returncode
 
139
        stdout, stderr = p.communicate()
 
140
    except OSError:
 
141
        returncode = -1
 
142
        stdout = stderr = ''
 
143
    if 'OpenSSH' in stderr:
 
144
        mutter('ssh implementation is OpenSSH')
 
145
        _ssh_vendor = 'openssh'
 
146
    elif 'SSH Secure Shell' in stderr:
 
147
        mutter('ssh implementation is SSH Corp.')
 
148
        _ssh_vendor = 'ssh'
 
149
 
 
150
    if _ssh_vendor != 'none':
 
151
        return _ssh_vendor
 
152
 
 
153
    # XXX: 20051123 jamesh
 
154
    # A check for putty's plink or lsh would go here.
 
155
 
 
156
    mutter('falling back to paramiko implementation')
 
157
    return _ssh_vendor
 
158
 
 
159
 
 
160
class SFTPSubprocess:
 
161
    """A socket-like object that talks to an ssh subprocess via pipes."""
 
162
    def __init__(self, hostname, vendor, port=None, user=None):
 
163
        assert vendor in ['openssh', 'ssh']
 
164
        if vendor == 'openssh':
 
165
            args = ['ssh',
 
166
                    '-oForwardX11=no', '-oForwardAgent=no',
 
167
                    '-oClearAllForwardings=yes', '-oProtocol=2',
 
168
                    '-oNoHostAuthenticationForLocalhost=yes']
 
169
            if port is not None:
 
170
                args.extend(['-p', str(port)])
 
171
            if user is not None:
 
172
                args.extend(['-l', user])
 
173
            args.extend(['-s', hostname, 'sftp'])
 
174
        elif vendor == 'ssh':
 
175
            args = ['ssh', '-x']
 
176
            if port is not None:
 
177
                args.extend(['-p', str(port)])
 
178
            if user is not None:
 
179
                args.extend(['-l', user])
 
180
            args.extend(['-s', 'sftp', hostname])
 
181
 
 
182
        self.proc = subprocess.Popen(args,
 
183
                                     stdin=subprocess.PIPE,
 
184
                                     stdout=subprocess.PIPE,
 
185
                                     **os_specific_subprocess_params())
 
186
 
 
187
    def send(self, data):
 
188
        return os.write(self.proc.stdin.fileno(), data)
 
189
 
 
190
    def recv_ready(self):
 
191
        # TODO: jam 20051215 this function is necessary to support the
 
192
        # pipelined() function. In reality, it probably should use
 
193
        # poll() or select() to actually return if there is data
 
194
        # available, otherwise we probably don't get any benefit
 
195
        return True
 
196
 
 
197
    def recv(self, count):
 
198
        return os.read(self.proc.stdout.fileno(), count)
 
199
 
 
200
    def close(self):
 
201
        self.proc.stdin.close()
 
202
        self.proc.stdout.close()
 
203
        self.proc.wait()
 
204
 
 
205
 
 
206
class LoopbackSFTP(object):
 
207
    """Simple wrapper for a socket that pretends to be a paramiko Channel."""
 
208
 
 
209
    def __init__(self, sock):
 
210
        self.__socket = sock
 
211
 
 
212
    def send(self, data):
 
213
        return self.__socket.send(data)
 
214
 
 
215
    def recv(self, n):
 
216
        return self.__socket.recv(n)
 
217
 
 
218
    def recv_ready(self):
 
219
        return True
 
220
 
 
221
    def close(self):
 
222
        self.__socket.close()
 
223
 
 
224
 
 
225
SYSTEM_HOSTKEYS = {}
 
226
BZR_HOSTKEYS = {}
 
227
 
 
228
# This is a weakref dictionary, so that we can reuse connections
 
229
# that are still active. Long term, it might be nice to have some
 
230
# sort of expiration policy, such as disconnect if inactive for
 
231
# X seconds. But that requires a lot more fanciness.
 
232
_connected_hosts = weakref.WeakValueDictionary()
 
233
 
100
234
def clear_connection_cache():
101
235
    """Remove all hosts from the SFTP connection cache.
102
236
 
103
237
    Primarily useful for test cases wanting to force garbage collection.
104
 
    We don't have a global connection cache anymore.
105
 
    """
 
238
    """
 
239
    _connected_hosts.clear()
 
240
 
 
241
 
 
242
def load_host_keys():
 
243
    """
 
244
    Load system host keys (probably doesn't work on windows) and any
 
245
    "discovered" keys from previous sessions.
 
246
    """
 
247
    global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
248
    try:
 
249
        SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
 
250
    except Exception, e:
 
251
        mutter('failed to load system host keys: ' + str(e))
 
252
    bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
 
253
    try:
 
254
        BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
 
255
    except Exception, e:
 
256
        mutter('failed to load bzr host keys: ' + str(e))
 
257
        save_host_keys()
 
258
 
 
259
 
 
260
def save_host_keys():
 
261
    """
 
262
    Save "discovered" host keys in $(config)/ssh_host_keys/.
 
263
    """
 
264
    global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
265
    bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
 
266
    ensure_config_dir_exists()
 
267
 
 
268
    try:
 
269
        f = open(bzr_hostkey_path, 'w')
 
270
        f.write('# SSH host keys collected by bzr\n')
 
271
        for hostname, keys in BZR_HOSTKEYS.iteritems():
 
272
            for keytype, key in keys.iteritems():
 
273
                f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
 
274
        f.close()
 
275
    except IOError, e:
 
276
        mutter('failed to save bzr host keys: ' + str(e))
 
277
 
106
278
 
107
279
class SFTPLock(object):
108
 
    """This fakes a lock in a remote location.
109
 
    
110
 
    A present lock is indicated just by the existence of a file.  This
111
 
    doesn't work well on all transports and they are only used in 
112
 
    deprecated storage formats.
113
 
    """
114
 
    
 
280
    """This fakes a lock in a remote location."""
115
281
    __slots__ = ['path', 'lock_path', 'lock_file', 'transport']
116
 
 
117
282
    def __init__(self, path, transport):
118
283
        assert isinstance(transport, SFTPTransport)
119
284
 
146
311
            pass
147
312
 
148
313
 
149
 
class SFTPTransport(ConnectedTransport):
 
314
class SFTPTransport(Transport):
150
315
    """Transport implementation for SFTP access."""
151
316
 
152
317
    _do_prefetch = _default_do_prefetch
167
332
    # up the request itself, rather than us having to worry about it
168
333
    _max_request_size = 32768
169
334
 
170
 
    def __init__(self, base, _from_transport=None):
 
335
    def __init__(self, base, clone_from=None):
171
336
        assert base.startswith('sftp://')
172
 
        super(SFTPTransport, self).__init__(base,
173
 
                                            _from_transport=_from_transport)
174
 
 
 
337
        self._parse_url(base)
 
338
        base = self._unparse_url()
 
339
        if base[-1] != '/':
 
340
            base += '/'
 
341
        super(SFTPTransport, self).__init__(base)
 
342
        if clone_from is None:
 
343
            self._sftp_connect()
 
344
        else:
 
345
            # use the same ssh connection, etc
 
346
            self._sftp = clone_from._sftp
 
347
        # super saves 'self.base'
 
348
    
 
349
    def should_cache(self):
 
350
        """
 
351
        Return True if the data pulled across should be cached locally.
 
352
        """
 
353
        return True
 
354
 
 
355
    def clone(self, offset=None):
 
356
        """
 
357
        Return a new SFTPTransport with root at self.base + offset.
 
358
        We share the same SFTP session between such transports, because it's
 
359
        fairly expensive to set them up.
 
360
        """
 
361
        if offset is None:
 
362
            return SFTPTransport(self.base, self)
 
363
        else:
 
364
            return SFTPTransport(self.abspath(offset), self)
 
365
 
 
366
    def abspath(self, relpath):
 
367
        """
 
368
        Return the full url to the given relative path.
 
369
        
 
370
        @param relpath: the relative path or path components
 
371
        @type relpath: str or list
 
372
        """
 
373
        return self._unparse_url(self._remote_path(relpath))
 
374
    
175
375
    def _remote_path(self, relpath):
176
376
        """Return the path to be passed along the sftp protocol for relpath.
177
377
        
178
 
        :param relpath: is a urlencoded string.
179
 
        """
180
 
        relative = urlutils.unescape(relpath).encode('utf-8')
181
 
        remote_path = self._combine_paths(self._path, relative)
182
 
        # the initial slash should be removed from the path, and treated as a
183
 
        # homedir relative path (the path begins with a double slash if it is
184
 
        # absolute).  see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
185
 
        # RBC 20060118 we are not using this as its too user hostile. instead
186
 
        # we are following lftp and using /~/foo to mean '~/foo'
187
 
        # vila--20070602 and leave absolute paths begin with a single slash.
188
 
        if remote_path.startswith('/~/'):
189
 
            remote_path = remote_path[3:]
190
 
        elif remote_path == '/~':
191
 
            remote_path = ''
192
 
        return remote_path
193
 
 
194
 
    def _create_connection(self, credentials=None):
195
 
        """Create a new connection with the provided credentials.
196
 
 
197
 
        :param credentials: The credentials needed to establish the connection.
198
 
 
199
 
        :return: The created connection and its associated credentials.
200
 
 
201
 
        The credentials are only the password as it may have been entered
202
 
        interactively by the user and may be different from the one provided
203
 
        in base url at transport creation time.
204
 
        """
205
 
        if credentials is None:
206
 
            password = self._password
207
 
        else:
208
 
            password = credentials
209
 
 
210
 
        vendor = ssh._get_ssh_vendor()
211
 
        connection = vendor.connect_sftp(self._user, password,
212
 
                                         self._host, self._port)
213
 
        return connection, password
214
 
 
215
 
    def _get_sftp(self):
216
 
        """Ensures that a connection is established"""
217
 
        connection = self._get_connection()
218
 
        if connection is None:
219
 
            # First connection ever
220
 
            connection, credentials = self._create_connection()
221
 
            self._set_connection(connection, credentials)
222
 
        return connection
 
378
        relpath is a urlencoded string.
 
379
        """
 
380
        # FIXME: share the common code across transports
 
381
        assert isinstance(relpath, basestring)
 
382
        relpath = urlutils.unescape(relpath).split('/')
 
383
        basepath = self._path.split('/')
 
384
        if len(basepath) > 0 and basepath[-1] == '':
 
385
            basepath = basepath[:-1]
 
386
 
 
387
        for p in relpath:
 
388
            if p == '..':
 
389
                if len(basepath) == 0:
 
390
                    # In most filesystems, a request for the parent
 
391
                    # of root, just returns root.
 
392
                    continue
 
393
                basepath.pop()
 
394
            elif p == '.':
 
395
                continue # No-op
 
396
            else:
 
397
                basepath.append(p)
 
398
 
 
399
        path = '/'.join(basepath)
 
400
        # mutter('relpath => remotepath %s => %s', relpath, path)
 
401
        return path
 
402
 
 
403
    def relpath(self, abspath):
 
404
        username, password, host, port, path = self._split_url(abspath)
 
405
        error = []
 
406
        if (username != self._username):
 
407
            error.append('username mismatch')
 
408
        if (host != self._host):
 
409
            error.append('host mismatch')
 
410
        if (port != self._port):
 
411
            error.append('port mismatch')
 
412
        if (not path.startswith(self._path)):
 
413
            error.append('path mismatch')
 
414
        if error:
 
415
            extra = ': ' + ', '.join(error)
 
416
            raise PathNotChild(abspath, self.base, extra=extra)
 
417
        pl = len(self._path)
 
418
        return path[pl:].strip('/')
223
419
 
224
420
    def has(self, relpath):
225
421
        """
226
422
        Does the target location exist?
227
423
        """
228
424
        try:
229
 
            self._get_sftp().stat(self._remote_path(relpath))
 
425
            self._sftp.stat(self._remote_path(relpath))
230
426
            return True
231
427
        except IOError:
232
428
            return False
239
435
        """
240
436
        try:
241
437
            path = self._remote_path(relpath)
242
 
            f = self._get_sftp().file(path, mode='rb')
 
438
            f = self._sftp.file(path, mode='rb')
243
439
            if self._do_prefetch and (getattr(f, 'prefetch', None) is not None):
244
440
                f.prefetch()
245
441
            return f
246
442
        except (IOError, paramiko.SSHException), e:
247
 
            self._translate_io_exception(e, path, ': error retrieving',
248
 
                failure_exc=errors.ReadError)
 
443
            self._translate_io_exception(e, path, ': error retrieving')
249
444
 
250
 
    def _readv(self, relpath, offsets):
 
445
    def readv(self, relpath, offsets):
251
446
        """See Transport.readv()"""
252
447
        # We overload the default readv() because we want to use a file
253
448
        # that does not have prefetch enabled.
257
452
 
258
453
        try:
259
454
            path = self._remote_path(relpath)
260
 
            fp = self._get_sftp().file(path, mode='rb')
 
455
            fp = self._sftp.file(path, mode='rb')
261
456
            readv = getattr(fp, 'readv', None)
262
457
            if readv:
263
 
                return self._sftp_readv(fp, offsets, relpath)
 
458
                return self._sftp_readv(fp, offsets)
264
459
            mutter('seek and read %s offsets', len(offsets))
265
 
            return self._seek_and_read(fp, offsets, relpath)
 
460
            return self._seek_and_read(fp, offsets)
266
461
        except (IOError, paramiko.SSHException), e:
267
462
            self._translate_io_exception(e, path, ': error retrieving')
268
463
 
269
 
    def recommended_page_size(self):
270
 
        """See Transport.recommended_page_size().
271
 
 
272
 
        For SFTP we suggest a large page size to reduce the overhead
273
 
        introduced by latency.
274
 
        """
275
 
        return 64 * 1024
276
 
 
277
 
    def _sftp_readv(self, fp, offsets, relpath='<unknown>'):
 
464
    def _sftp_readv(self, fp, offsets):
278
465
        """Use the readv() member of fp to do async readv.
279
466
 
280
467
        And then read them using paramiko.readv(). paramiko.readv()
367
554
                yield cur_offset_and_size[0], this_data
368
555
                cur_offset_and_size = offset_stack.next()
369
556
 
370
 
            # We read a coalesced entry, so mark it as done
371
 
            cur_coalesced = None
372
557
            # Now that we've read all of the data for this coalesced section
373
558
            # on to the next
374
559
            cur_coalesced = cur_coalesced_stack.next()
375
560
 
376
 
        if cur_coalesced is not None:
377
 
            raise errors.ShortReadvError(relpath, cur_coalesced.start,
378
 
                cur_coalesced.length, len(data))
379
 
 
380
 
    def put_file(self, relpath, f, mode=None):
 
561
    def put(self, relpath, f, mode=None):
381
562
        """
382
 
        Copy the file-like object into the location.
 
563
        Copy the file-like or string object into the location.
383
564
 
384
565
        :param relpath: Location to put the contents, relative to base.
385
 
        :param f:       File-like object.
 
566
        :param f:       File-like or string object.
386
567
        :param mode: The final mode for the file
387
568
        """
388
569
        final_path = self._remote_path(relpath)
389
 
        return self._put(final_path, f, mode=mode)
 
570
        self._put(final_path, f, mode=mode)
390
571
 
391
572
    def _put(self, abspath, f, mode=None):
392
573
        """Helper function so both put() and copy_abspaths can reuse the code"""
397
578
        try:
398
579
            try:
399
580
                fout.set_pipelined(True)
400
 
                length = self._pump(f, fout)
 
581
                self._pump(f, fout)
401
582
            except (IOError, paramiko.SSHException), e:
402
583
                self._translate_io_exception(e, tmp_abspath)
403
 
            # XXX: This doesn't truly help like we would like it to.
404
 
            #      The problem is that openssh strips sticky bits. So while we
405
 
            #      can properly set group write permission, we lose the group
406
 
            #      sticky bit. So it is probably best to stop chmodding, and
407
 
            #      just tell users that they need to set the umask correctly.
408
 
            #      The attr.st_mode = mode, in _sftp_open_exclusive
409
 
            #      will handle when the user wants the final mode to be more 
410
 
            #      restrictive. And then we avoid a round trip. Unless 
411
 
            #      paramiko decides to expose an async chmod()
412
 
 
413
 
            # This is designed to chmod() right before we close.
414
 
            # Because we set_pipelined() earlier, theoretically we might 
415
 
            # avoid the round trip for fout.close()
416
584
            if mode is not None:
417
 
                self._get_sftp().chmod(tmp_abspath, mode)
 
585
                self._sftp.chmod(tmp_abspath, mode)
418
586
            fout.close()
419
587
            closed = True
420
588
            self._rename_and_overwrite(tmp_abspath, abspath)
421
 
            return length
422
589
        except Exception, e:
423
590
            # If we fail, try to clean up the temporary file
424
591
            # before we throw the exception
430
597
            try:
431
598
                if not closed:
432
599
                    fout.close()
433
 
                self._get_sftp().remove(tmp_abspath)
 
600
                self._sftp.remove(tmp_abspath)
434
601
            except:
435
602
                # raise the saved except
436
603
                raise e
437
604
            # raise the original with its traceback if we can.
438
605
            raise
439
606
 
440
 
    def _put_non_atomic_helper(self, relpath, writer, mode=None,
441
 
                               create_parent_dir=False,
442
 
                               dir_mode=None):
443
 
        abspath = self._remote_path(relpath)
444
 
 
445
 
        # TODO: jam 20060816 paramiko doesn't publicly expose a way to
446
 
        #       set the file mode at create time. If it does, use it.
447
 
        #       But for now, we just chmod later anyway.
448
 
 
449
 
        def _open_and_write_file():
450
 
            """Try to open the target file, raise error on failure"""
451
 
            fout = None
452
 
            try:
453
 
                try:
454
 
                    fout = self._get_sftp().file(abspath, mode='wb')
455
 
                    fout.set_pipelined(True)
456
 
                    writer(fout)
457
 
                except (paramiko.SSHException, IOError), e:
458
 
                    self._translate_io_exception(e, abspath,
459
 
                                                 ': unable to open')
460
 
 
461
 
                # This is designed to chmod() right before we close.
462
 
                # Because we set_pipelined() earlier, theoretically we might 
463
 
                # avoid the round trip for fout.close()
464
 
                if mode is not None:
465
 
                    self._get_sftp().chmod(abspath, mode)
466
 
            finally:
467
 
                if fout is not None:
468
 
                    fout.close()
469
 
 
470
 
        if not create_parent_dir:
471
 
            _open_and_write_file()
472
 
            return
473
 
 
474
 
        # Try error handling to create the parent directory if we need to
475
 
        try:
476
 
            _open_and_write_file()
477
 
        except NoSuchFile:
478
 
            # Try to create the parent directory, and then go back to
479
 
            # writing the file
480
 
            parent_dir = os.path.dirname(abspath)
481
 
            self._mkdir(parent_dir, dir_mode)
482
 
            _open_and_write_file()
483
 
 
484
 
    def put_file_non_atomic(self, relpath, f, mode=None,
485
 
                            create_parent_dir=False,
486
 
                            dir_mode=None):
487
 
        """Copy the file-like object into the target location.
488
 
 
489
 
        This function is not strictly safe to use. It is only meant to
490
 
        be used when you already know that the target does not exist.
491
 
        It is not safe, because it will open and truncate the remote
492
 
        file. So there may be a time when the file has invalid contents.
493
 
 
494
 
        :param relpath: The remote location to put the contents.
495
 
        :param f:       File-like object.
496
 
        :param mode:    Possible access permissions for new file.
497
 
                        None means do not set remote permissions.
498
 
        :param create_parent_dir: If we cannot create the target file because
499
 
                        the parent directory does not exist, go ahead and
500
 
                        create it, and then try again.
501
 
        """
502
 
        def writer(fout):
503
 
            self._pump(f, fout)
504
 
        self._put_non_atomic_helper(relpath, writer, mode=mode,
505
 
                                    create_parent_dir=create_parent_dir,
506
 
                                    dir_mode=dir_mode)
507
 
 
508
 
    def put_bytes_non_atomic(self, relpath, bytes, mode=None,
509
 
                             create_parent_dir=False,
510
 
                             dir_mode=None):
511
 
        def writer(fout):
512
 
            fout.write(bytes)
513
 
        self._put_non_atomic_helper(relpath, writer, mode=mode,
514
 
                                    create_parent_dir=create_parent_dir,
515
 
                                    dir_mode=dir_mode)
516
 
 
517
607
    def iter_files_recursive(self):
518
608
        """Walk the relative paths of all files in this transport."""
519
609
        queue = list(self.list_dir('.'))
520
610
        while queue:
521
 
            relpath = queue.pop(0)
 
611
            relpath = urllib.quote(queue.pop(0))
522
612
            st = self.stat(relpath)
523
613
            if stat.S_ISDIR(st.st_mode):
524
614
                for i, basename in enumerate(self.list_dir(relpath)):
526
616
            else:
527
617
                yield relpath
528
618
 
529
 
    def _mkdir(self, abspath, mode=None):
530
 
        if mode is None:
531
 
            local_mode = 0777
532
 
        else:
533
 
            local_mode = mode
534
 
        try:
535
 
            self._get_sftp().mkdir(abspath, local_mode)
536
 
            if mode is not None:
537
 
                self._get_sftp().chmod(abspath, mode=mode)
538
 
        except (paramiko.SSHException, IOError), e:
539
 
            self._translate_io_exception(e, abspath, ': unable to mkdir',
540
 
                failure_exc=FileExists)
541
 
 
542
619
    def mkdir(self, relpath, mode=None):
543
620
        """Create a directory at the given path."""
544
 
        self._mkdir(self._remote_path(relpath), mode=mode)
545
 
 
546
 
    def open_write_stream(self, relpath, mode=None):
547
 
        """See Transport.open_write_stream."""
548
 
        # initialise the file to zero-length
549
 
        # this is three round trips, but we don't use this 
550
 
        # api more than once per write_group at the moment so 
551
 
        # it is a tolerable overhead. Better would be to truncate
552
 
        # the file after opening. RBC 20070805
553
 
        self.put_bytes_non_atomic(relpath, "", mode)
554
 
        abspath = self._remote_path(relpath)
555
 
        # TODO: jam 20060816 paramiko doesn't publicly expose a way to
556
 
        #       set the file mode at create time. If it does, use it.
557
 
        #       But for now, we just chmod later anyway.
558
 
        handle = None
 
621
        path = self._remote_path(relpath)
559
622
        try:
560
 
            handle = self._get_sftp().file(abspath, mode='wb')
561
 
            handle.set_pipelined(True)
 
623
            # In the paramiko documentation, it says that passing a mode flag 
 
624
            # will filtered against the server umask.
 
625
            # StubSFTPServer does not do this, which would be nice, because it is
 
626
            # what we really want :)
 
627
            # However, real servers do use umask, so we really should do it that way
 
628
            self._sftp.mkdir(path)
 
629
            if mode is not None:
 
630
                self._sftp.chmod(path, mode=mode)
562
631
        except (paramiko.SSHException, IOError), e:
563
 
            self._translate_io_exception(e, abspath,
564
 
                                         ': unable to open')
565
 
        _file_streams[self.abspath(relpath)] = handle
566
 
        return FileFileStream(self, relpath, handle)
 
632
            self._translate_io_exception(e, path, ': unable to mkdir',
 
633
                failure_exc=FileExists)
567
634
 
568
 
    def _translate_io_exception(self, e, path, more_info='',
 
635
    def _translate_io_exception(self, e, path, more_info='', 
569
636
                                failure_exc=PathError):
570
637
        """Translate a paramiko or IOError into a friendlier exception.
571
638
 
581
648
        """
582
649
        # paramiko seems to generate detailless errors.
583
650
        self._translate_error(e, path, raise_generic=False)
584
 
        if getattr(e, 'args', None) is not None:
 
651
        if hasattr(e, 'args'):
585
652
            if (e.args == ('No such file or directory',) or
586
653
                e.args == ('No such file',)):
587
654
                raise NoSuchFile(path, str(e) + more_info)
591
658
            if (e.args == ('Failure',)):
592
659
                raise failure_exc(path, str(e) + more_info)
593
660
            mutter('Raising exception with args %s', e.args)
594
 
        if getattr(e, 'errno', None) is not None:
 
661
        if hasattr(e, 'errno'):
595
662
            mutter('Raising exception with errno %s', e.errno)
596
663
        raise e
597
664
 
598
 
    def append_file(self, relpath, f, mode=None):
 
665
    def append(self, relpath, f, mode=None):
599
666
        """
600
667
        Append the text in the file-like object into the final
601
668
        location.
602
669
        """
603
670
        try:
604
671
            path = self._remote_path(relpath)
605
 
            fout = self._get_sftp().file(path, 'ab')
 
672
            fout = self._sftp.file(path, 'ab')
606
673
            if mode is not None:
607
 
                self._get_sftp().chmod(path, mode)
 
674
                self._sftp.chmod(path, mode)
608
675
            result = fout.tell()
609
676
            self._pump(f, fout)
610
677
            return result
614
681
    def rename(self, rel_from, rel_to):
615
682
        """Rename without special overwriting"""
616
683
        try:
617
 
            self._get_sftp().rename(self._remote_path(rel_from),
 
684
            self._sftp.rename(self._remote_path(rel_from),
618
685
                              self._remote_path(rel_to))
619
686
        except (IOError, paramiko.SSHException), e:
620
687
            self._translate_io_exception(e, rel_from,
626
693
        Using the implementation provided by osutils.
627
694
        """
628
695
        try:
629
 
            sftp = self._get_sftp()
630
696
            fancy_rename(abs_from, abs_to,
631
 
                         rename_func=sftp.rename,
632
 
                         unlink_func=sftp.remove)
 
697
                    rename_func=self._sftp.rename,
 
698
                    unlink_func=self._sftp.remove)
633
699
        except (IOError, paramiko.SSHException), e:
634
 
            self._translate_io_exception(e, abs_from,
635
 
                                         ': unable to rename to %r' % (abs_to))
 
700
            self._translate_io_exception(e, abs_from, ': unable to rename to %r' % (abs_to))
636
701
 
637
702
    def move(self, rel_from, rel_to):
638
703
        """Move the item at rel_from to the location at rel_to"""
644
709
        """Delete the item at relpath"""
645
710
        path = self._remote_path(relpath)
646
711
        try:
647
 
            self._get_sftp().remove(path)
 
712
            self._sftp.remove(path)
648
713
        except (IOError, paramiko.SSHException), e:
649
714
            self._translate_io_exception(e, path, ': unable to delete')
650
715
            
651
 
    def external_url(self):
652
 
        """See bzrlib.transport.Transport.external_url."""
653
 
        # the external path for SFTP is the base
654
 
        return self.base
655
 
 
656
716
    def listable(self):
657
717
        """Return True if this store supports listing."""
658
718
        return True
662
722
        Return a list of all files at the given location.
663
723
        """
664
724
        # does anything actually use this?
665
 
        # -- Unknown
666
 
        # This is at least used by copy_tree for remote upgrades.
667
 
        # -- David Allouche 2006-08-11
668
725
        path = self._remote_path(relpath)
669
726
        try:
670
 
            entries = self._get_sftp().listdir(path)
 
727
            return self._sftp.listdir(path)
671
728
        except (IOError, paramiko.SSHException), e:
672
729
            self._translate_io_exception(e, path, ': failed to list_dir')
673
 
        return [urlutils.escape(entry) for entry in entries]
674
730
 
675
731
    def rmdir(self, relpath):
676
732
        """See Transport.rmdir."""
677
733
        path = self._remote_path(relpath)
678
734
        try:
679
 
            return self._get_sftp().rmdir(path)
 
735
            return self._sftp.rmdir(path)
680
736
        except (IOError, paramiko.SSHException), e:
681
737
            self._translate_io_exception(e, path, ': failed to rmdir')
682
738
 
684
740
        """Return the stat information for a file."""
685
741
        path = self._remote_path(relpath)
686
742
        try:
687
 
            return self._get_sftp().stat(path)
 
743
            return self._sftp.stat(path)
688
744
        except (IOError, paramiko.SSHException), e:
689
745
            self._translate_io_exception(e, path, ': unable to stat')
690
746
 
714
770
        # that we have taken the lock.
715
771
        return SFTPLock(relpath, self)
716
772
 
 
773
    def _unparse_url(self, path=None):
 
774
        if path is None:
 
775
            path = self._path
 
776
        path = urllib.quote(path)
 
777
        # handle homedir paths
 
778
        if not path.startswith('/'):
 
779
            path = "/~/" + path
 
780
        netloc = urllib.quote(self._host)
 
781
        if self._username is not None:
 
782
            netloc = '%s@%s' % (urllib.quote(self._username), netloc)
 
783
        if self._port is not None:
 
784
            netloc = '%s:%d' % (netloc, self._port)
 
785
        return urlparse.urlunparse(('sftp', netloc, path, '', '', ''))
 
786
 
 
787
    def _split_url(self, url):
 
788
        (scheme, username, password, host, port, path) = split_url(url)
 
789
        assert scheme == 'sftp'
 
790
 
 
791
        # the initial slash should be removed from the path, and treated
 
792
        # as a homedir relative path (the path begins with a double slash
 
793
        # if it is absolute).
 
794
        # see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
 
795
        # RBC 20060118 we are not using this as its too user hostile. instead
 
796
        # we are following lftp and using /~/foo to mean '~/foo'.
 
797
        # handle homedir paths
 
798
        if path.startswith('/~/'):
 
799
            path = path[3:]
 
800
        elif path == '/~':
 
801
            path = ''
 
802
        return (username, password, host, port, path)
 
803
 
 
804
    def _parse_url(self, url):
 
805
        (self._username, self._password,
 
806
         self._host, self._port, self._path) = self._split_url(url)
 
807
 
 
808
    def _sftp_connect(self):
 
809
        """Connect to the remote sftp server.
 
810
        After this, self._sftp should have a valid connection (or
 
811
        we raise an TransportError 'could not connect').
 
812
 
 
813
        TODO: Raise a more reasonable ConnectionFailed exception
 
814
        """
 
815
        global _connected_hosts
 
816
 
 
817
        idx = (self._host, self._port, self._username)
 
818
        try:
 
819
            self._sftp = _connected_hosts[idx]
 
820
            return
 
821
        except KeyError:
 
822
            pass
 
823
        
 
824
        vendor = _get_ssh_vendor()
 
825
        if vendor == 'loopback':
 
826
            sock = socket.socket()
 
827
            try:
 
828
                sock.connect((self._host, self._port))
 
829
            except socket.error, e:
 
830
                raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
 
831
                                      % (self._host, self._port, e))
 
832
            self._sftp = SFTPClient(LoopbackSFTP(sock))
 
833
        elif vendor != 'none':
 
834
            try:
 
835
                sock = SFTPSubprocess(self._host, vendor, self._port,
 
836
                                      self._username)
 
837
                self._sftp = SFTPClient(sock)
 
838
            except (EOFError, paramiko.SSHException), e:
 
839
                raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
 
840
                                      % (self._host, self._port, e))
 
841
            except (OSError, IOError), e:
 
842
                # If the machine is fast enough, ssh can actually exit
 
843
                # before we try and send it the sftp request, which
 
844
                # raises a Broken Pipe
 
845
                if e.errno not in (errno.EPIPE,):
 
846
                    raise
 
847
                raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
 
848
                                      % (self._host, self._port, e))
 
849
        else:
 
850
            self._paramiko_connect()
 
851
 
 
852
        _connected_hosts[idx] = self._sftp
 
853
 
 
854
    def _paramiko_connect(self):
 
855
        global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
856
        
 
857
        load_host_keys()
 
858
 
 
859
        try:
 
860
            t = paramiko.Transport((self._host, self._port or 22))
 
861
            t.set_log_channel('bzr.paramiko')
 
862
            t.start_client()
 
863
        except (paramiko.SSHException, socket.error), e:
 
864
            raise ConnectionError('Unable to reach SSH host %s:%s: %s' 
 
865
                                  % (self._host, self._port, e))
 
866
            
 
867
        server_key = t.get_remote_server_key()
 
868
        server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
 
869
        keytype = server_key.get_name()
 
870
        if SYSTEM_HOSTKEYS.has_key(self._host) and SYSTEM_HOSTKEYS[self._host].has_key(keytype):
 
871
            our_server_key = SYSTEM_HOSTKEYS[self._host][keytype]
 
872
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
 
873
        elif BZR_HOSTKEYS.has_key(self._host) and BZR_HOSTKEYS[self._host].has_key(keytype):
 
874
            our_server_key = BZR_HOSTKEYS[self._host][keytype]
 
875
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
 
876
        else:
 
877
            warning('Adding %s host key for %s: %s' % (keytype, self._host, server_key_hex))
 
878
            if not BZR_HOSTKEYS.has_key(self._host):
 
879
                BZR_HOSTKEYS[self._host] = {}
 
880
            BZR_HOSTKEYS[self._host][keytype] = server_key
 
881
            our_server_key = server_key
 
882
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
 
883
            save_host_keys()
 
884
        if server_key != our_server_key:
 
885
            filename1 = os.path.expanduser('~/.ssh/known_hosts')
 
886
            filename2 = pathjoin(config_dir(), 'ssh_host_keys')
 
887
            raise TransportError('Host keys for %s do not match!  %s != %s' % \
 
888
                (self._host, our_server_key_hex, server_key_hex),
 
889
                ['Try editing %s or %s' % (filename1, filename2)])
 
890
 
 
891
        self._sftp_auth(t)
 
892
        
 
893
        try:
 
894
            self._sftp = t.open_sftp_client()
 
895
        except paramiko.SSHException, e:
 
896
            raise ConnectionError('Unable to start sftp client %s:%d' %
 
897
                                  (self._host, self._port), e)
 
898
 
 
899
    def _sftp_auth(self, transport):
 
900
        # paramiko requires a username, but it might be none if nothing was supplied
 
901
        # use the local username, just in case.
 
902
        # We don't override self._username, because if we aren't using paramiko,
 
903
        # the username might be specified in ~/.ssh/config and we don't want to
 
904
        # force it to something else
 
905
        # Also, it would mess up the self.relpath() functionality
 
906
        username = self._username or getpass.getuser()
 
907
 
 
908
        if _use_ssh_agent:
 
909
            agent = paramiko.Agent()
 
910
            for key in agent.get_keys():
 
911
                mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
 
912
                try:
 
913
                    transport.auth_publickey(username, key)
 
914
                    return
 
915
                except paramiko.SSHException, e:
 
916
                    pass
 
917
        
 
918
        # okay, try finding id_rsa or id_dss?  (posix only)
 
919
        if self._try_pkey_auth(transport, paramiko.RSAKey, username, 'id_rsa'):
 
920
            return
 
921
        if self._try_pkey_auth(transport, paramiko.DSSKey, username, 'id_dsa'):
 
922
            return
 
923
 
 
924
        if self._password:
 
925
            try:
 
926
                transport.auth_password(username, self._password)
 
927
                return
 
928
            except paramiko.SSHException, e:
 
929
                pass
 
930
 
 
931
            # FIXME: Don't keep a password held in memory if you can help it
 
932
            #self._password = None
 
933
 
 
934
        # give up and ask for a password
 
935
        password = bzrlib.ui.ui_factory.get_password(
 
936
                prompt='SSH %(user)s@%(host)s password',
 
937
                user=username, host=self._host)
 
938
        try:
 
939
            transport.auth_password(username, password)
 
940
        except paramiko.SSHException, e:
 
941
            raise ConnectionError('Unable to authenticate to SSH host as %s@%s' %
 
942
                                  (username, self._host), e)
 
943
 
 
944
    def _try_pkey_auth(self, transport, pkey_class, username, filename):
 
945
        filename = os.path.expanduser('~/.ssh/' + filename)
 
946
        try:
 
947
            key = pkey_class.from_private_key_file(filename)
 
948
            transport.auth_publickey(username, key)
 
949
            return True
 
950
        except paramiko.PasswordRequiredException:
 
951
            password = bzrlib.ui.ui_factory.get_password(
 
952
                    prompt='SSH %(filename)s password',
 
953
                    filename=filename)
 
954
            try:
 
955
                key = pkey_class.from_private_key_file(filename, password)
 
956
                transport.auth_publickey(username, key)
 
957
                return True
 
958
            except paramiko.SSHException:
 
959
                mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
 
960
        except paramiko.SSHException:
 
961
            mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
 
962
        except IOError:
 
963
            pass
 
964
        return False
 
965
 
717
966
    def _sftp_open_exclusive(self, abspath, mode=None):
718
967
        """Open a remote path exclusively.
719
968
 
728
977
        :param abspath: The remote absolute path where the file should be opened
729
978
        :param mode: The mode permissions bits for the new file
730
979
        """
731
 
        # TODO: jam 20060816 Paramiko >= 1.6.2 (probably earlier) supports
732
 
        #       using the 'x' flag to indicate SFTP_FLAG_EXCL.
733
 
        #       However, there is no way to set the permission mode at open 
734
 
        #       time using the sftp_client.file() functionality.
735
 
        path = self._get_sftp()._adjust_cwd(abspath)
 
980
        path = self._sftp._adjust_cwd(abspath)
736
981
        # mutter('sftp abspath %s => %s', abspath, path)
737
982
        attr = SFTPAttributes()
738
983
        if mode is not None:
740
985
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE 
741
986
                | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
742
987
        try:
743
 
            t, msg = self._get_sftp()._request(CMD_OPEN, path, omode, attr)
 
988
            t, msg = self._sftp._request(CMD_OPEN, path, omode, attr)
744
989
            if t != CMD_HANDLE:
745
990
                raise TransportError('Expected an SFTP handle')
746
991
            handle = msg.get_string()
747
 
            return SFTPFile(self._get_sftp(), handle, 'wb', -1)
 
992
            return SFTPFile(self._sftp, handle, 'wb', -1)
748
993
        except (paramiko.SSHException, IOError), e:
749
994
            self._translate_io_exception(e, abspath, ': unable to open',
750
995
                failure_exc=FileExists)
751
996
 
752
 
    def _can_roundtrip_unix_modebits(self):
753
 
        if sys.platform == 'win32':
754
 
            # anyone else?
755
 
            return False
756
 
        else:
757
 
            return True
758
997
 
759
998
# ------------- server test implementation --------------
 
999
import socket
760
1000
import threading
761
1001
 
762
1002
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
825
1065
                        x)
826
1066
 
827
1067
 
828
 
class SocketDelay(object):
829
 
    """A socket decorator to make TCP appear slower.
830
 
 
831
 
    This changes recv, send, and sendall to add a fixed latency to each python
832
 
    call if a new roundtrip is detected. That is, when a recv is called and the
833
 
    flag new_roundtrip is set, latency is charged. Every send and send_all
834
 
    sets this flag.
835
 
 
836
 
    In addition every send, sendall and recv sleeps a bit per character send to
837
 
    simulate bandwidth.
838
 
 
839
 
    Not all methods are implemented, this is deliberate as this class is not a
840
 
    replacement for the builtin sockets layer. fileno is not implemented to
841
 
    prevent the proxy being bypassed. 
842
 
    """
843
 
 
844
 
    simulated_time = 0
845
 
    _proxied_arguments = dict.fromkeys([
846
 
        "close", "getpeername", "getsockname", "getsockopt", "gettimeout",
847
 
        "setblocking", "setsockopt", "settimeout", "shutdown"])
848
 
 
849
 
    def __init__(self, sock, latency, bandwidth=1.0, 
850
 
                 really_sleep=True):
851
 
        """ 
852
 
        :param bandwith: simulated bandwith (MegaBit)
853
 
        :param really_sleep: If set to false, the SocketDelay will just
854
 
        increase a counter, instead of calling time.sleep. This is useful for
855
 
        unittesting the SocketDelay.
856
 
        """
857
 
        self.sock = sock
858
 
        self.latency = latency
859
 
        self.really_sleep = really_sleep
860
 
        self.time_per_byte = 1 / (bandwidth / 8.0 * 1024 * 1024) 
861
 
        self.new_roundtrip = False
862
 
 
863
 
    def sleep(self, s):
864
 
        if self.really_sleep:
865
 
            time.sleep(s)
866
 
        else:
867
 
            SocketDelay.simulated_time += s
868
 
 
869
 
    def __getattr__(self, attr):
870
 
        if attr in SocketDelay._proxied_arguments:
871
 
            return getattr(self.sock, attr)
872
 
        raise AttributeError("'SocketDelay' object has no attribute %r" %
873
 
                             attr)
874
 
 
875
 
    def dup(self):
876
 
        return SocketDelay(self.sock.dup(), self.latency, self.time_per_byte,
877
 
                           self._sleep)
878
 
 
879
 
    def recv(self, *args):
880
 
        data = self.sock.recv(*args)
881
 
        if data and self.new_roundtrip:
882
 
            self.new_roundtrip = False
883
 
            self.sleep(self.latency)
884
 
        self.sleep(len(data) * self.time_per_byte)
885
 
        return data
886
 
 
887
 
    def sendall(self, data, flags=0):
888
 
        if not self.new_roundtrip:
889
 
            self.new_roundtrip = True
890
 
            self.sleep(self.latency)
891
 
        self.sleep(len(data) * self.time_per_byte)
892
 
        return self.sock.sendall(data, flags)
893
 
 
894
 
    def send(self, data, flags=0):
895
 
        if not self.new_roundtrip:
896
 
            self.new_roundtrip = True
897
 
            self.sleep(self.latency)
898
 
        bytes_sent = self.sock.send(data, flags)
899
 
        self.sleep(bytes_sent * self.time_per_byte)
900
 
        return bytes_sent
901
 
 
902
 
 
903
1068
class SFTPServer(Server):
904
1069
    """Common code for SFTP server facilities."""
905
1070
 
906
 
    def __init__(self, server_interface=StubServer):
 
1071
    def __init__(self):
907
1072
        self._original_vendor = None
908
1073
        self._homedir = None
909
1074
        self._server_homedir = None
910
1075
        self._listener = None
911
1076
        self._root = None
912
 
        self._vendor = ssh.ParamikoVendor()
913
 
        self._server_interface = server_interface
 
1077
        self._vendor = 'none'
914
1078
        # sftp server logs
915
1079
        self.logs = []
916
 
        self.add_latency = 0
917
1080
 
918
1081
    def _get_sftp_url(self, path):
919
1082
        """Calculate an sftp url to this server for path."""
923
1086
        """StubServer uses this to log when a new server is created."""
924
1087
        self.logs.append(message)
925
1088
 
926
 
    def _run_server_entry(self, sock):
927
 
        """Entry point for all implementations of _run_server.
928
 
        
929
 
        If self.add_latency is > 0.000001 then sock is given a latency adding
930
 
        decorator.
931
 
        """
932
 
        if self.add_latency > 0.000001:
933
 
            sock = SocketDelay(sock, self.add_latency)
934
 
        return self._run_server(sock)
935
 
 
936
1089
    def _run_server(self, s):
937
1090
        ssh_server = paramiko.Transport(s)
938
1091
        key_file = pathjoin(self._homedir, 'test_rsa.key')
941
1094
        f.close()
942
1095
        host_key = paramiko.RSAKey.from_private_key_file(key_file)
943
1096
        ssh_server.add_server_key(host_key)
944
 
        server = self._server_interface(self)
 
1097
        server = StubServer(self)
945
1098
        ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
946
1099
                                         StubSFTPServer, root=self._root,
947
1100
                                         home=self._server_homedir)
949
1102
        ssh_server.start_server(event, server)
950
1103
        event.wait(5.0)
951
1104
    
952
 
    def setUp(self, backing_server=None):
953
 
        # XXX: TODO: make sftpserver back onto backing_server rather than local
954
 
        # disk.
955
 
        assert (backing_server is None or
956
 
                isinstance(backing_server, local.LocalURLServer)), (
957
 
            "backing_server should not be %r, because this can only serve the "
958
 
            "local current working directory." % (backing_server,))
959
 
        self._original_vendor = ssh._ssh_vendor_manager._cached_ssh_vendor
960
 
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._vendor
 
1105
    def setUp(self):
 
1106
        global _ssh_vendor
 
1107
        self._original_vendor = _ssh_vendor
 
1108
        _ssh_vendor = self._vendor
961
1109
        if sys.platform == 'win32':
962
1110
            # Win32 needs to use the UNICODE api
963
1111
            self._homedir = getcwd()
969
1117
        self._root = '/'
970
1118
        if sys.platform == 'win32':
971
1119
            self._root = ''
972
 
        self._listener = SocketListener(self._run_server_entry)
 
1120
        self._listener = SocketListener(self._run_server)
973
1121
        self._listener.setDaemon(True)
974
1122
        self._listener.start()
975
1123
 
976
1124
    def tearDown(self):
977
1125
        """See bzrlib.transport.Server.tearDown."""
 
1126
        global _ssh_vendor
978
1127
        self._listener.stop()
979
 
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._original_vendor
 
1128
        _ssh_vendor = self._original_vendor
980
1129
 
981
1130
    def get_bogus_url(self):
982
1131
        """See bzrlib.transport.Server.get_bogus_url."""
993
1142
 
994
1143
    def get_url(self):
995
1144
        """See bzrlib.transport.Server.get_url."""
996
 
        homedir = self._homedir
997
 
        if sys.platform != 'win32':
998
 
            # Remove the initial '/' on all platforms but win32
999
 
            homedir = homedir[1:]
1000
 
        return self._get_sftp_url(urlutils.escape(homedir))
 
1145
        return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1001
1146
 
1002
1147
 
1003
1148
class SFTPServerWithoutSSH(SFTPServer):
1005
1150
 
1006
1151
    def __init__(self):
1007
1152
        super(SFTPServerWithoutSSH, self).__init__()
1008
 
        self._vendor = ssh.LoopbackVendor()
 
1153
        self._vendor = 'loopback'
1009
1154
 
1010
1155
    def _run_server(self, sock):
1011
 
        # Re-import these as locals, so that they're still accessible during
1012
 
        # interpreter shutdown (when all module globals get set to None, leading
1013
 
        # to confusing errors like "'NoneType' object has no attribute 'error'".
1014
1156
        class FakeChannel(object):
1015
1157
            def get_transport(self):
1016
1158
                return self
1035
1177
            else:
1036
1178
                raise
1037
1179
        except Exception, e:
1038
 
            # This typically seems to happen during interpreter shutdown, so
1039
 
            # most of the useful ways to report this error are won't work.
1040
 
            # Writing the exception type, and then the text of the exception,
1041
 
            # seems to be the best we can do.
1042
 
            import sys
1043
 
            sys.stderr.write('\nEXCEPTION %r: ' % (e.__class__,))
1044
 
            sys.stderr.write('%s\n\n' % (e,))
 
1180
            import sys; sys.stderr.write('\nEXCEPTION %r\n\n' % e.__class__)
1045
1181
        server.finish_subsystem()
1046
1182
 
1047
1183
 
1050
1186
 
1051
1187
    def get_url(self):
1052
1188
        """See bzrlib.transport.Server.get_url."""
1053
 
        homedir = self._homedir
1054
 
        if sys.platform != 'win32':
1055
 
            # Remove the initial '/' on all platforms but win32
1056
 
            homedir = homedir[1:]
1057
 
        return self._get_sftp_url(urlutils.escape(homedir))
 
1189
        if sys.platform == 'win32':
 
1190
            return self._get_sftp_url(urlutils.escape(self._homedir))
 
1191
        else:
 
1192
            return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1058
1193
 
1059
1194
 
1060
1195
class SFTPHomeDirServer(SFTPServerWithoutSSH):
1066
1201
 
1067
1202
 
1068
1203
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
1069
 
    """A test server for sftp transports where only absolute paths will work.
1070
 
 
1071
 
    It does this by serving from a deeply-nested directory that doesn't exist.
1072
 
    """
1073
 
 
1074
 
    def setUp(self, backing_server=None):
 
1204
    """A test servere for sftp transports, using absolute urls to non-home."""
 
1205
 
 
1206
    def setUp(self):
1075
1207
        self._server_homedir = '/dev/noone/runs/tests/here'
1076
 
        super(SFTPSiblingAbsoluteServer, self).setUp(backing_server)
 
1208
        super(SFTPSiblingAbsoluteServer, self).setUp()
1077
1209
 
1078
1210
 
1079
1211
def get_test_permutations():