~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/sftp.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
 
2
# Copyright (C) 2005, 2006 Canonical Ltd
2
3
#
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
12
13
#
13
14
# You should have received a copy of the GNU General Public License
14
15
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
18
"""Implementation of Transport over SFTP, using paramiko."""
18
19
 
23
24
# suite.  Those formats all date back to 0.7; so we should be able to remove
24
25
# these methods when we officially drop support for those formats.
25
26
 
26
 
import bisect
27
27
import errno
28
 
import itertools
29
28
import os
30
29
import random
31
30
import select
35
34
import time
36
35
import urllib
37
36
import urlparse
38
 
import warnings
 
37
import weakref
39
38
 
40
39
from bzrlib import (
41
 
    config,
42
 
    debug,
43
40
    errors,
44
41
    urlutils,
45
42
    )
51
48
                           ParamikoNotPresent,
52
49
                           )
53
50
from bzrlib.osutils import pathjoin, fancy_rename, getcwd
54
 
from bzrlib.symbol_versioning import (
55
 
        deprecated_function,
56
 
        )
57
51
from bzrlib.trace import mutter, warning
58
52
from bzrlib.transport import (
59
 
    FileFileStream,
60
 
    _file_streams,
61
 
    local,
 
53
    register_urlparse_netloc_protocol,
62
54
    Server,
 
55
    split_url,
63
56
    ssh,
64
 
    ConnectedTransport,
 
57
    Transport,
65
58
    )
66
59
 
67
 
# Disable one particular warning that comes from paramiko in Python2.5; if
68
 
# this is emitted at the wrong time it tends to cause spurious test failures
69
 
# or at least noise in the test case::
70
 
#
71
 
# [1770/7639 in 86s, 1 known failures, 50 skipped, 2 missing features]
72
 
# test_permissions.TestSftpPermissions.test_new_files
73
 
# /var/lib/python-support/python2.5/paramiko/message.py:226: DeprecationWarning: integer argument expected, got float
74
 
#  self.packet.write(struct.pack('>I', n))
75
 
warnings.filterwarnings('ignore',
76
 
        'integer argument expected, got float',
77
 
        category=DeprecationWarning,
78
 
        module='paramiko.message')
79
 
 
80
60
try:
81
61
    import paramiko
82
62
except ImportError, e:
89
69
    from paramiko.sftp_file import SFTPFile
90
70
 
91
71
 
 
72
register_urlparse_netloc_protocol('sftp')
 
73
 
 
74
 
 
75
# This is a weakref dictionary, so that we can reuse connections
 
76
# that are still active. Long term, it might be nice to have some
 
77
# sort of expiration policy, such as disconnect if inactive for
 
78
# X seconds. But that requires a lot more fanciness.
 
79
_connected_hosts = weakref.WeakValueDictionary()
 
80
 
 
81
 
92
82
_paramiko_version = getattr(paramiko, '__version_info__', (0, 0, 0))
93
83
# don't use prefetch unless paramiko version >= 1.5.5 (there were bugs earlier)
94
84
_default_do_prefetch = (_paramiko_version >= (1, 5, 5))
95
85
 
96
86
 
 
87
def clear_connection_cache():
 
88
    """Remove all hosts from the SFTP connection cache.
 
89
 
 
90
    Primarily useful for test cases wanting to force garbage collection.
 
91
    """
 
92
    _connected_hosts.clear()
 
93
 
 
94
 
97
95
class SFTPLock(object):
98
96
    """This fakes a lock in a remote location.
99
 
 
 
97
    
100
98
    A present lock is indicated just by the existence of a file.  This
101
 
    doesn't work well on all transports and they are only used in
 
99
    doesn't work well on all transports and they are only used in 
102
100
    deprecated storage formats.
103
101
    """
104
 
 
 
102
    
105
103
    __slots__ = ['path', 'lock_path', 'lock_file', 'transport']
106
104
 
107
105
    def __init__(self, path, transport):
 
106
        assert isinstance(transport, SFTPTransport)
 
107
 
108
108
        self.lock_file = None
109
109
        self.path = path
110
110
        self.lock_path = path + '.write-lock'
134
134
            pass
135
135
 
136
136
 
137
 
class _SFTPReadvHelper(object):
138
 
    """A class to help with managing the state of a readv request."""
139
 
 
140
 
    # See _get_requests for an explanation.
141
 
    _max_request_size = 32768
142
 
 
143
 
    def __init__(self, original_offsets, relpath, _report_activity):
144
 
        """Create a new readv helper.
145
 
 
146
 
        :param original_offsets: The original requests given by the caller of
147
 
            readv()
148
 
        :param relpath: The name of the file (if known)
149
 
        :param _report_activity: A Transport._report_activity bound method,
150
 
            to be called as data arrives.
151
 
        """
152
 
        self.original_offsets = list(original_offsets)
153
 
        self.relpath = relpath
154
 
        self._report_activity = _report_activity
155
 
 
156
 
    def _get_requests(self):
157
 
        """Break up the offsets into individual requests over sftp.
158
 
 
159
 
        The SFTP spec only requires implementers to support 32kB requests. We
160
 
        could try something larger (openssh supports 64kB), but then we have to
161
 
        handle requests that fail.
162
 
        So instead, we just break up our maximum chunks into 32kB chunks, and
163
 
        asyncronously requests them.
164
 
        Newer versions of paramiko would do the chunking for us, but we want to
165
 
        start processing results right away, so we do it ourselves.
166
 
        """
167
 
        # TODO: Because we issue async requests, we don't 'fudge' any extra
168
 
        #       data.  I'm not 100% sure that is the best choice.
169
 
 
170
 
        # The first thing we do, is to collapse the individual requests as much
171
 
        # as possible, so we don't issues requests <32kB
172
 
        sorted_offsets = sorted(self.original_offsets)
173
 
        coalesced = list(ConnectedTransport._coalesce_offsets(sorted_offsets,
174
 
                                                        limit=0, fudge_factor=0))
175
 
        requests = []
176
 
        for c_offset in coalesced:
177
 
            start = c_offset.start
178
 
            size = c_offset.length
179
 
 
180
 
            # Break this up into 32kB requests
181
 
            while size > 0:
182
 
                next_size = min(size, self._max_request_size)
183
 
                requests.append((start, next_size))
184
 
                size -= next_size
185
 
                start += next_size
186
 
        if 'sftp' in debug.debug_flags:
187
 
            mutter('SFTP.readv(%s) %s offsets => %s coalesced => %s requests',
188
 
                self.relpath, len(sorted_offsets), len(coalesced),
189
 
                len(requests))
190
 
        return requests
191
 
 
192
 
    def request_and_yield_offsets(self, fp):
193
 
        """Request the data from the remote machine, yielding the results.
194
 
 
195
 
        :param fp: A Paramiko SFTPFile object that supports readv.
196
 
        :return: Yield the data requested by the original readv caller, one by
197
 
            one.
198
 
        """
199
 
        requests = self._get_requests()
200
 
        offset_iter = iter(self.original_offsets)
201
 
        cur_offset, cur_size = offset_iter.next()
202
 
        # paramiko .readv() yields strings that are in the order of the requests
203
 
        # So we track the current request to know where the next data is
204
 
        # being returned from.
205
 
        input_start = None
206
 
        last_end = None
207
 
        buffered_data = []
208
 
        buffered_len = 0
209
 
 
210
 
        # This is used to buffer chunks which we couldn't process yet
211
 
        # It is (start, end, data) tuples.
212
 
        data_chunks = []
213
 
        # Create an 'unlimited' data stream, so we stop based on requests,
214
 
        # rather than just because the data stream ended. This lets us detect
215
 
        # short readv.
216
 
        data_stream = itertools.chain(fp.readv(requests),
217
 
                                      itertools.repeat(None))
218
 
        for (start, length), data in itertools.izip(requests, data_stream):
219
 
            if data is None:
220
 
                if cur_coalesced is not None:
221
 
                    raise errors.ShortReadvError(self.relpath,
222
 
                        start, length, len(data))
223
 
            if len(data) != length:
224
 
                raise errors.ShortReadvError(self.relpath,
225
 
                    start, length, len(data))
226
 
            self._report_activity(length, 'read')
227
 
            if last_end is None:
228
 
                # This is the first request, just buffer it
229
 
                buffered_data = [data]
230
 
                buffered_len = length
231
 
                input_start = start
232
 
            elif start == last_end:
233
 
                # The data we are reading fits neatly on the previous
234
 
                # buffer, so this is all part of a larger coalesced range.
235
 
                buffered_data.append(data)
236
 
                buffered_len += length
237
 
            else:
238
 
                # We have an 'interrupt' in the data stream. So we know we are
239
 
                # at a request boundary.
240
 
                if buffered_len > 0:
241
 
                    # We haven't consumed the buffer so far, so put it into
242
 
                    # data_chunks, and continue.
243
 
                    buffered = ''.join(buffered_data)
244
 
                    data_chunks.append((input_start, buffered))
245
 
                input_start = start
246
 
                buffered_data = [data]
247
 
                buffered_len = length
248
 
            last_end = start + length
249
 
            if input_start == cur_offset and cur_size <= buffered_len:
250
 
                # Simplify the next steps a bit by transforming buffered_data
251
 
                # into a single string. We also have the nice property that
252
 
                # when there is only one string ''.join([x]) == x, so there is
253
 
                # no data copying.
254
 
                buffered = ''.join(buffered_data)
255
 
                # Clean out buffered data so that we keep memory
256
 
                # consumption low
257
 
                del buffered_data[:]
258
 
                buffered_offset = 0
259
 
                # TODO: We *could* also consider the case where cur_offset is in
260
 
                #       in the buffered range, even though it doesn't *start*
261
 
                #       the buffered range. But for packs we pretty much always
262
 
                #       read in order, so you won't get any extra data in the
263
 
                #       middle.
264
 
                while (input_start == cur_offset
265
 
                       and (buffered_offset + cur_size) <= buffered_len):
266
 
                    # We've buffered enough data to process this request, spit it
267
 
                    # out
268
 
                    cur_data = buffered[buffered_offset:buffered_offset + cur_size]
269
 
                    # move the direct pointer into our buffered data
270
 
                    buffered_offset += cur_size
271
 
                    # Move the start-of-buffer pointer
272
 
                    input_start += cur_size
273
 
                    # Yield the requested data
274
 
                    yield cur_offset, cur_data
275
 
                    cur_offset, cur_size = offset_iter.next()
276
 
                # at this point, we've consumed as much of buffered as we can,
277
 
                # so break off the portion that we consumed
278
 
                if buffered_offset == len(buffered_data):
279
 
                    # No tail to leave behind
280
 
                    buffered_data = []
281
 
                    buffered_len = 0
282
 
                else:
283
 
                    buffered = buffered[buffered_offset:]
284
 
                    buffered_data = [buffered]
285
 
                    buffered_len = len(buffered)
286
 
        if buffered_len:
287
 
            buffered = ''.join(buffered_data)
288
 
            del buffered_data[:]
289
 
            data_chunks.append((input_start, buffered))
290
 
        if data_chunks:
291
 
            if 'sftp' in debug.debug_flags:
292
 
                mutter('SFTP readv left with %d out-of-order bytes',
293
 
                    sum(map(lambda x: len(x[1]), data_chunks)))
294
 
            # We've processed all the readv data, at this point, anything we
295
 
            # couldn't process is in data_chunks. This doesn't happen often, so
296
 
            # this code path isn't optimized
297
 
            # We use an interesting process for data_chunks
298
 
            # Specifically if we have "bisect_left([(start, len, entries)],
299
 
            #                                       (qstart,)])
300
 
            # If start == qstart, then we get the specific node. Otherwise we
301
 
            # get the previous node
302
 
            while True:
303
 
                idx = bisect.bisect_left(data_chunks, (cur_offset,))
304
 
                if idx < len(data_chunks) and data_chunks[idx][0] == cur_offset:
305
 
                    # The data starts here
306
 
                    data = data_chunks[idx][1][:cur_size]
307
 
                elif idx > 0:
308
 
                    # The data is in a portion of a previous page
309
 
                    idx -= 1
310
 
                    sub_offset = cur_offset - data_chunks[idx][0]
311
 
                    data = data_chunks[idx][1]
312
 
                    data = data[sub_offset:sub_offset + cur_size]
313
 
                else:
314
 
                    # We are missing the page where the data should be found,
315
 
                    # something is wrong
316
 
                    data = ''
317
 
                if len(data) != cur_size:
318
 
                    raise AssertionError('We must have miscalulated.'
319
 
                        ' We expected %d bytes, but only found %d'
320
 
                        % (cur_size, len(data)))
321
 
                yield cur_offset, data
322
 
                cur_offset, cur_size = offset_iter.next()
323
 
 
324
 
 
325
 
class SFTPTransport(ConnectedTransport):
 
137
class SFTPUrlHandling(Transport):
 
138
    """Mix-in that does common handling of SSH/SFTP URLs."""
 
139
 
 
140
    def __init__(self, base):
 
141
        self._parse_url(base)
 
142
        base = self._unparse_url(self._path)
 
143
        if base[-1] != '/':
 
144
            base += '/'
 
145
        super(SFTPUrlHandling, self).__init__(base)
 
146
 
 
147
    def _parse_url(self, url):
 
148
        (self._scheme,
 
149
         self._username, self._password,
 
150
         self._host, self._port, self._path) = self._split_url(url)
 
151
 
 
152
    def _unparse_url(self, path):
 
153
        """Return a URL for a path relative to this transport.
 
154
        """
 
155
        path = urllib.quote(path)
 
156
        # handle homedir paths
 
157
        if not path.startswith('/'):
 
158
            path = "/~/" + path
 
159
        netloc = urllib.quote(self._host)
 
160
        if self._username is not None:
 
161
            netloc = '%s@%s' % (urllib.quote(self._username), netloc)
 
162
        if self._port is not None:
 
163
            netloc = '%s:%d' % (netloc, self._port)
 
164
        return urlparse.urlunparse((self._scheme, netloc, path, '', '', ''))
 
165
 
 
166
    def _split_url(self, url):
 
167
        (scheme, username, password, host, port, path) = split_url(url)
 
168
        ## assert scheme == 'sftp'
 
169
 
 
170
        # the initial slash should be removed from the path, and treated
 
171
        # as a homedir relative path (the path begins with a double slash
 
172
        # if it is absolute).
 
173
        # see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
 
174
        # RBC 20060118 we are not using this as its too user hostile. instead
 
175
        # we are following lftp and using /~/foo to mean '~/foo'.
 
176
        # handle homedir paths
 
177
        if path.startswith('/~/'):
 
178
            path = path[3:]
 
179
        elif path == '/~':
 
180
            path = ''
 
181
        return (scheme, username, password, host, port, path)
 
182
 
 
183
    def abspath(self, relpath):
 
184
        """Return the full url to the given relative path.
 
185
        
 
186
        @param relpath: the relative path or path components
 
187
        @type relpath: str or list
 
188
        """
 
189
        return self._unparse_url(self._remote_path(relpath))
 
190
    
 
191
    def _remote_path(self, relpath):
 
192
        """Return the path to be passed along the sftp protocol for relpath.
 
193
        
 
194
        :param relpath: is a urlencoded string.
 
195
        """
 
196
        return self._combine_paths(self._path, relpath)
 
197
 
 
198
 
 
199
class SFTPTransport(SFTPUrlHandling):
326
200
    """Transport implementation for SFTP access."""
327
201
 
328
202
    _do_prefetch = _default_do_prefetch
343
217
    # up the request itself, rather than us having to worry about it
344
218
    _max_request_size = 32768
345
219
 
346
 
    def __init__(self, base, _from_transport=None):
347
 
        super(SFTPTransport, self).__init__(base,
348
 
                                            _from_transport=_from_transport)
 
220
    def __init__(self, base, clone_from=None):
 
221
        super(SFTPTransport, self).__init__(base)
 
222
        if clone_from is None:
 
223
            self._sftp_connect()
 
224
        else:
 
225
            # use the same ssh connection, etc
 
226
            self._sftp = clone_from._sftp
 
227
        # super saves 'self.base'
 
228
    
 
229
    def should_cache(self):
 
230
        """
 
231
        Return True if the data pulled across should be cached locally.
 
232
        """
 
233
        return True
 
234
 
 
235
    def clone(self, offset=None):
 
236
        """
 
237
        Return a new SFTPTransport with root at self.base + offset.
 
238
        We share the same SFTP session between such transports, because it's
 
239
        fairly expensive to set them up.
 
240
        """
 
241
        if offset is None:
 
242
            return SFTPTransport(self.base, self)
 
243
        else:
 
244
            return SFTPTransport(self.abspath(offset), self)
349
245
 
350
246
    def _remote_path(self, relpath):
351
247
        """Return the path to be passed along the sftp protocol for relpath.
352
 
 
353
 
        :param relpath: is a urlencoded string.
354
 
        """
355
 
        relative = urlutils.unescape(relpath).encode('utf-8')
356
 
        remote_path = self._combine_paths(self._path, relative)
357
 
        # the initial slash should be removed from the path, and treated as a
358
 
        # homedir relative path (the path begins with a double slash if it is
359
 
        # absolute).  see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
360
 
        # RBC 20060118 we are not using this as its too user hostile. instead
361
 
        # we are following lftp and using /~/foo to mean '~/foo'
362
 
        # vila--20070602 and leave absolute paths begin with a single slash.
363
 
        if remote_path.startswith('/~/'):
364
 
            remote_path = remote_path[3:]
365
 
        elif remote_path == '/~':
366
 
            remote_path = ''
367
 
        return remote_path
368
 
 
369
 
    def _create_connection(self, credentials=None):
370
 
        """Create a new connection with the provided credentials.
371
 
 
372
 
        :param credentials: The credentials needed to establish the connection.
373
 
 
374
 
        :return: The created connection and its associated credentials.
375
 
 
376
 
        The credentials are only the password as it may have been entered
377
 
        interactively by the user and may be different from the one provided
378
 
        in base url at transport creation time.
379
 
        """
380
 
        if credentials is None:
381
 
            password = self._password
 
248
        
 
249
        relpath is a urlencoded string.
 
250
 
 
251
        :return: a path prefixed with / for regular abspath-based urls, or a
 
252
            path that does not begin with / for urls which begin with /~/.
 
253
        """
 
254
        # how does this work? 
 
255
        # it processes relpath with respect to 
 
256
        # our state:
 
257
        # firstly we create a path to evaluate: 
 
258
        # if relpath is an abspath or homedir path, its the entire thing
 
259
        # otherwise we join our base with relpath
 
260
        # then we eliminate all empty segments (double //'s) outside the first
 
261
        # two elements of the list. This avoids problems with trailing 
 
262
        # slashes, or other abnormalities.
 
263
        # finally we evaluate the entire path in a single pass
 
264
        # '.'s are stripped,
 
265
        # '..' result in popping the left most already 
 
266
        # processed path (which can never be empty because of the check for
 
267
        # abspath and homedir meaning that its not, or that we've used our
 
268
        # path. If the pop would pop the root, we ignore it.
 
269
 
 
270
        # Specific case examinations:
 
271
        # remove the special casefor ~: if the current root is ~/ popping of it
 
272
        # = / thus our seed for a ~ based path is ['', '~']
 
273
        # and if we end up with [''] then we had basically ('', '..') (which is
 
274
        # '/..' so we append '' if the length is one, and assert that the first
 
275
        # element is still ''. Lastly, if we end with ['', '~'] as a prefix for
 
276
        # the output, we've got a homedir path, so we strip that prefix before
 
277
        # '/' joining the resulting list.
 
278
        #
 
279
        # case one: '/' -> ['', ''] cannot shrink
 
280
        # case two: '/' + '../foo' -> ['', 'foo'] (take '', '', '..', 'foo')
 
281
        #           and pop the second '' for the '..', append 'foo'
 
282
        # case three: '/~/' -> ['', '~', ''] 
 
283
        # case four: '/~/' + '../foo' -> ['', '~', '', '..', 'foo'],
 
284
        #           and we want to get '/foo' - the empty path in the middle
 
285
        #           needs to be stripped, then normal path manipulation will 
 
286
        #           work.
 
287
        # case five: '/..' ['', '..'], we want ['', '']
 
288
        #            stripping '' outside the first two is ok
 
289
        #            ignore .. if its too high up
 
290
        #
 
291
        # lastly this code is possibly reusable by FTP, but not reusable by
 
292
        # local paths: ~ is resolvable correctly, nor by HTTP or the smart
 
293
        # server: ~ is resolved remotely.
 
294
        # 
 
295
        # however, a version of this that acts on self.base is possible to be
 
296
        # written which manipulates the URL in canonical form, and would be
 
297
        # reusable for all transports, if a flag for allowing ~/ at all was
 
298
        # provided.
 
299
        assert isinstance(relpath, basestring)
 
300
        relpath = urlutils.unescape(relpath)
 
301
 
 
302
        # case 1)
 
303
        if relpath.startswith('/'):
 
304
            # abspath - normal split is fine.
 
305
            current_path = relpath.split('/')
 
306
        elif relpath.startswith('~/'):
 
307
            # root is homedir based: normal split and prefix '' to remote the
 
308
            # special case
 
309
            current_path = [''].extend(relpath.split('/'))
382
310
        else:
383
 
            password = credentials
384
 
 
385
 
        vendor = ssh._get_ssh_vendor()
386
 
        user = self._user
387
 
        if user is None:
388
 
            auth = config.AuthenticationConfig()
389
 
            user = auth.get_user('ssh', self._host, self._port)
390
 
        connection = vendor.connect_sftp(self._user, password,
391
 
                                         self._host, self._port)
392
 
        return connection, (user, password)
393
 
 
394
 
    def _get_sftp(self):
395
 
        """Ensures that a connection is established"""
396
 
        connection = self._get_connection()
397
 
        if connection is None:
398
 
            # First connection ever
399
 
            connection, credentials = self._create_connection()
400
 
            self._set_connection(connection, credentials)
401
 
        return connection
 
311
            # root is from the current directory:
 
312
            if self._path.startswith('/'):
 
313
                # abspath, take the regular split
 
314
                current_path = []
 
315
            else:
 
316
                # homedir based, add the '', '~' not present in self._path
 
317
                current_path = ['', '~']
 
318
            # add our current dir
 
319
            current_path.extend(self._path.split('/'))
 
320
            # add the users relpath
 
321
            current_path.extend(relpath.split('/'))
 
322
        # strip '' segments that are not in the first one - the leading /.
 
323
        to_process = current_path[:1]
 
324
        for segment in current_path[1:]:
 
325
            if segment != '':
 
326
                to_process.append(segment)
 
327
 
 
328
        # process '.' and '..' segments into output_path.
 
329
        output_path = []
 
330
        for segment in to_process:
 
331
            if segment == '..':
 
332
                # directory pop. Remove a directory 
 
333
                # as long as we are not at the root
 
334
                if len(output_path) > 1:
 
335
                    output_path.pop()
 
336
                # else: pass
 
337
                # cannot pop beyond the root, so do nothing
 
338
            elif segment == '.':
 
339
                continue # strip the '.' from the output.
 
340
            else:
 
341
                # this will append '' to output_path for the root elements,
 
342
                # which is appropriate: its why we strip '' in the first pass.
 
343
                output_path.append(segment)
 
344
 
 
345
        # check output special cases:
 
346
        if output_path == ['']:
 
347
            # [''] -> ['', '']
 
348
            output_path = ['', '']
 
349
        elif output_path[:2] == ['', '~']:
 
350
            # ['', '~', ...] -> ...
 
351
            output_path = output_path[2:]
 
352
        path = '/'.join(output_path)
 
353
        return path
 
354
 
 
355
    def relpath(self, abspath):
 
356
        scheme, username, password, host, port, path = self._split_url(abspath)
 
357
        error = []
 
358
        if (username != self._username):
 
359
            error.append('username mismatch')
 
360
        if (host != self._host):
 
361
            error.append('host mismatch')
 
362
        if (port != self._port):
 
363
            error.append('port mismatch')
 
364
        if (not path.startswith(self._path)):
 
365
            error.append('path mismatch')
 
366
        if error:
 
367
            extra = ': ' + ', '.join(error)
 
368
            raise PathNotChild(abspath, self.base, extra=extra)
 
369
        pl = len(self._path)
 
370
        return path[pl:].strip('/')
402
371
 
403
372
    def has(self, relpath):
404
373
        """
405
374
        Does the target location exist?
406
375
        """
407
376
        try:
408
 
            self._get_sftp().stat(self._remote_path(relpath))
409
 
            # stat result is about 20 bytes, let's say
410
 
            self._report_activity(20, 'read')
 
377
            self._sftp.stat(self._remote_path(relpath))
411
378
            return True
412
379
        except IOError:
413
380
            return False
414
381
 
415
382
    def get(self, relpath):
416
 
        """Get the file at the given relative path.
 
383
        """
 
384
        Get the file at the given relative path.
417
385
 
418
386
        :param relpath: The relative path to the file
419
387
        """
420
388
        try:
421
 
            # FIXME: by returning the file directly, we don't pass this
422
 
            # through to report_activity.  We could try wrapping the object
423
 
            # before it's returned.  For readv and get_bytes it's handled in
424
 
            # the higher-level function.
425
 
            # -- mbp 20090126
426
389
            path = self._remote_path(relpath)
427
 
            f = self._get_sftp().file(path, mode='rb')
 
390
            f = self._sftp.file(path, mode='rb')
428
391
            if self._do_prefetch and (getattr(f, 'prefetch', None) is not None):
429
392
                f.prefetch()
430
393
            return f
431
394
        except (IOError, paramiko.SSHException), e:
432
 
            self._translate_io_exception(e, path, ': error retrieving',
433
 
                failure_exc=errors.ReadError)
434
 
 
435
 
    def get_bytes(self, relpath):
436
 
        # reimplement this here so that we can report how many bytes came back
437
 
        f = self.get(relpath)
438
 
        try:
439
 
            bytes = f.read()
440
 
            self._report_activity(len(bytes), 'read')
441
 
            return bytes
442
 
        finally:
443
 
            f.close()
444
 
 
445
 
    def _readv(self, relpath, offsets):
 
395
            self._translate_io_exception(e, path, ': error retrieving')
 
396
 
 
397
    def readv(self, relpath, offsets):
446
398
        """See Transport.readv()"""
447
399
        # We overload the default readv() because we want to use a file
448
400
        # that does not have prefetch enabled.
452
404
 
453
405
        try:
454
406
            path = self._remote_path(relpath)
455
 
            fp = self._get_sftp().file(path, mode='rb')
 
407
            fp = self._sftp.file(path, mode='rb')
456
408
            readv = getattr(fp, 'readv', None)
457
409
            if readv:
458
410
                return self._sftp_readv(fp, offsets, relpath)
459
 
            if 'sftp' in debug.debug_flags:
460
 
                mutter('seek and read %s offsets', len(offsets))
 
411
            mutter('seek and read %s offsets', len(offsets))
461
412
            return self._seek_and_read(fp, offsets, relpath)
462
413
        except (IOError, paramiko.SSHException), e:
463
414
            self._translate_io_exception(e, path, ': error retrieving')
464
415
 
465
 
    def recommended_page_size(self):
466
 
        """See Transport.recommended_page_size().
467
 
 
468
 
        For SFTP we suggest a large page size to reduce the overhead
469
 
        introduced by latency.
470
 
        """
471
 
        return 64 * 1024
472
 
 
473
 
    def _sftp_readv(self, fp, offsets, relpath):
 
416
    def _sftp_readv(self, fp, offsets, relpath='<unknown>'):
474
417
        """Use the readv() member of fp to do async readv.
475
418
 
476
 
        Then read them using paramiko.readv(). paramiko.readv()
 
419
        And then read them using paramiko.readv(). paramiko.readv()
477
420
        does not support ranges > 64K, so it caps the request size, and
478
 
        just reads until it gets all the stuff it wants.
 
421
        just reads until it gets all the stuff it wants
479
422
        """
480
 
        helper = _SFTPReadvHelper(offsets, relpath, self._report_activity)
481
 
        return helper.request_and_yield_offsets(fp)
 
423
        offsets = list(offsets)
 
424
        sorted_offsets = sorted(offsets)
 
425
 
 
426
        # The algorithm works as follows:
 
427
        # 1) Coalesce nearby reads into a single chunk
 
428
        #    This generates a list of combined regions, the total size
 
429
        #    and the size of the sub regions. This coalescing step is limited
 
430
        #    in the number of nearby chunks to combine, and is allowed to
 
431
        #    skip small breaks in the requests. Limiting it makes sure that
 
432
        #    we can start yielding some data earlier, and skipping means we
 
433
        #    make fewer requests. (Beneficial even when using async)
 
434
        # 2) Break up this combined regions into chunks that are smaller
 
435
        #    than 64KiB. Technically the limit is 65536, but we are a
 
436
        #    little bit conservative. This is because sftp has a maximum
 
437
        #    return chunk size of 64KiB (max size of an unsigned short)
 
438
        # 3) Issue a readv() to paramiko to create an async request for
 
439
        #    all of this data
 
440
        # 4) Read in the data as it comes back, until we've read one
 
441
        #    continuous section as determined in step 1
 
442
        # 5) Break up the full sections into hunks for the original requested
 
443
        #    offsets. And put them in a cache
 
444
        # 6) Check if the next request is in the cache, and if it is, remove
 
445
        #    it from the cache, and yield its data. Continue until no more
 
446
        #    entries are in the cache.
 
447
        # 7) loop back to step 4 until all data has been read
 
448
        #
 
449
        # TODO: jam 20060725 This could be optimized one step further, by
 
450
        #       attempting to yield whatever data we have read, even before
 
451
        #       the first coallesced section has been fully processed.
 
452
 
 
453
        # When coalescing for use with readv(), we don't really need to
 
454
        # use any fudge factor, because the requests are made asynchronously
 
455
        coalesced = list(self._coalesce_offsets(sorted_offsets,
 
456
                               limit=self._max_readv_combine,
 
457
                               fudge_factor=0,
 
458
                               ))
 
459
        requests = []
 
460
        for c_offset in coalesced:
 
461
            start = c_offset.start
 
462
            size = c_offset.length
 
463
 
 
464
            # We need to break this up into multiple requests
 
465
            while size > 0:
 
466
                next_size = min(size, self._max_request_size)
 
467
                requests.append((start, next_size))
 
468
                size -= next_size
 
469
                start += next_size
 
470
 
 
471
        mutter('SFTP.readv() %s offsets => %s coalesced => %s requests',
 
472
                len(offsets), len(coalesced), len(requests))
 
473
 
 
474
        # Queue the current read until we have read the full coalesced section
 
475
        cur_data = []
 
476
        cur_data_len = 0
 
477
        cur_coalesced_stack = iter(coalesced)
 
478
        cur_coalesced = cur_coalesced_stack.next()
 
479
 
 
480
        # Cache the results, but only until they have been fulfilled
 
481
        data_map = {}
 
482
        # turn the list of offsets into a stack
 
483
        offset_stack = iter(offsets)
 
484
        cur_offset_and_size = offset_stack.next()
 
485
 
 
486
        for data in fp.readv(requests):
 
487
            cur_data += data
 
488
            cur_data_len += len(data)
 
489
 
 
490
            if cur_data_len < cur_coalesced.length:
 
491
                continue
 
492
            assert cur_data_len == cur_coalesced.length, \
 
493
                "Somehow we read too much: %s != %s" % (cur_data_len,
 
494
                                                        cur_coalesced.length)
 
495
            all_data = ''.join(cur_data)
 
496
            cur_data = []
 
497
            cur_data_len = 0
 
498
 
 
499
            for suboffset, subsize in cur_coalesced.ranges:
 
500
                key = (cur_coalesced.start+suboffset, subsize)
 
501
                data_map[key] = all_data[suboffset:suboffset+subsize]
 
502
 
 
503
            # Now that we've read some data, see if we can yield anything back
 
504
            while cur_offset_and_size in data_map:
 
505
                this_data = data_map.pop(cur_offset_and_size)
 
506
                yield cur_offset_and_size[0], this_data
 
507
                cur_offset_and_size = offset_stack.next()
 
508
 
 
509
            # We read a coalesced entry, so mark it as done
 
510
            cur_coalesced = None
 
511
            # Now that we've read all of the data for this coalesced section
 
512
            # on to the next
 
513
            cur_coalesced = cur_coalesced_stack.next()
 
514
 
 
515
        if cur_coalesced is not None:
 
516
            raise errors.ShortReadvError(relpath, cur_coalesced.start,
 
517
                cur_coalesced.length, len(data))
482
518
 
483
519
    def put_file(self, relpath, f, mode=None):
484
520
        """
489
525
        :param mode: The final mode for the file
490
526
        """
491
527
        final_path = self._remote_path(relpath)
492
 
        return self._put(final_path, f, mode=mode)
 
528
        self._put(final_path, f, mode=mode)
493
529
 
494
530
    def _put(self, abspath, f, mode=None):
495
531
        """Helper function so both put() and copy_abspaths can reuse the code"""
500
536
        try:
501
537
            try:
502
538
                fout.set_pipelined(True)
503
 
                length = self._pump(f, fout)
 
539
                self._pump(f, fout)
504
540
            except (IOError, paramiko.SSHException), e:
505
541
                self._translate_io_exception(e, tmp_abspath)
506
542
            # XXX: This doesn't truly help like we would like it to.
509
545
            #      sticky bit. So it is probably best to stop chmodding, and
510
546
            #      just tell users that they need to set the umask correctly.
511
547
            #      The attr.st_mode = mode, in _sftp_open_exclusive
512
 
            #      will handle when the user wants the final mode to be more
513
 
            #      restrictive. And then we avoid a round trip. Unless
 
548
            #      will handle when the user wants the final mode to be more 
 
549
            #      restrictive. And then we avoid a round trip. Unless 
514
550
            #      paramiko decides to expose an async chmod()
515
551
 
516
552
            # This is designed to chmod() right before we close.
517
 
            # Because we set_pipelined() earlier, theoretically we might
 
553
            # Because we set_pipelined() earlier, theoretically we might 
518
554
            # avoid the round trip for fout.close()
519
555
            if mode is not None:
520
 
                self._get_sftp().chmod(tmp_abspath, mode)
 
556
                self._sftp.chmod(tmp_abspath, mode)
521
557
            fout.close()
522
558
            closed = True
523
559
            self._rename_and_overwrite(tmp_abspath, abspath)
524
 
            return length
525
560
        except Exception, e:
526
561
            # If we fail, try to clean up the temporary file
527
562
            # before we throw the exception
533
568
            try:
534
569
                if not closed:
535
570
                    fout.close()
536
 
                self._get_sftp().remove(tmp_abspath)
 
571
                self._sftp.remove(tmp_abspath)
537
572
            except:
538
573
                # raise the saved except
539
574
                raise e
554
589
            fout = None
555
590
            try:
556
591
                try:
557
 
                    fout = self._get_sftp().file(abspath, mode='wb')
 
592
                    fout = self._sftp.file(abspath, mode='wb')
558
593
                    fout.set_pipelined(True)
559
594
                    writer(fout)
560
595
                except (paramiko.SSHException, IOError), e:
562
597
                                                 ': unable to open')
563
598
 
564
599
                # This is designed to chmod() right before we close.
565
 
                # Because we set_pipelined() earlier, theoretically we might
 
600
                # Because we set_pipelined() earlier, theoretically we might 
566
601
                # avoid the round trip for fout.close()
567
602
                if mode is not None:
568
 
                    self._get_sftp().chmod(abspath, mode)
 
603
                    self._sftp.chmod(abspath, mode)
569
604
            finally:
570
605
                if fout is not None:
571
606
                    fout.close()
619
654
 
620
655
    def iter_files_recursive(self):
621
656
        """Walk the relative paths of all files in this transport."""
622
 
        # progress is handled by list_dir
623
657
        queue = list(self.list_dir('.'))
624
658
        while queue:
625
659
            relpath = queue.pop(0)
636
670
        else:
637
671
            local_mode = mode
638
672
        try:
639
 
            self._report_activity(len(abspath), 'write')
640
 
            self._get_sftp().mkdir(abspath, local_mode)
641
 
            self._report_activity(1, 'read')
 
673
            self._sftp.mkdir(abspath, local_mode)
642
674
            if mode is not None:
643
 
                # chmod a dir through sftp will erase any sgid bit set
644
 
                # on the server side.  So, if the bit mode are already
645
 
                # set, avoid the chmod.  If the mode is not fine but
646
 
                # the sgid bit is set, report a warning to the user
647
 
                # with the umask fix.
648
 
                stat = self._get_sftp().lstat(abspath)
649
 
                mode = mode & 0777 # can't set special bits anyway
650
 
                if mode != stat.st_mode & 0777:
651
 
                    if stat.st_mode & 06000:
652
 
                        warning('About to chmod %s over sftp, which will result'
653
 
                                ' in its suid or sgid bits being cleared.  If'
654
 
                                ' you want to preserve those bits, change your '
655
 
                                ' environment on the server to use umask 0%03o.'
656
 
                                % (abspath, 0777 - mode))
657
 
                    self._get_sftp().chmod(abspath, mode=mode)
 
675
                self._sftp.chmod(abspath, mode=mode)
658
676
        except (paramiko.SSHException, IOError), e:
659
677
            self._translate_io_exception(e, abspath, ': unable to mkdir',
660
678
                failure_exc=FileExists)
663
681
        """Create a directory at the given path."""
664
682
        self._mkdir(self._remote_path(relpath), mode=mode)
665
683
 
666
 
    def open_write_stream(self, relpath, mode=None):
667
 
        """See Transport.open_write_stream."""
668
 
        # initialise the file to zero-length
669
 
        # this is three round trips, but we don't use this
670
 
        # api more than once per write_group at the moment so
671
 
        # it is a tolerable overhead. Better would be to truncate
672
 
        # the file after opening. RBC 20070805
673
 
        self.put_bytes_non_atomic(relpath, "", mode)
674
 
        abspath = self._remote_path(relpath)
675
 
        # TODO: jam 20060816 paramiko doesn't publicly expose a way to
676
 
        #       set the file mode at create time. If it does, use it.
677
 
        #       But for now, we just chmod later anyway.
678
 
        handle = None
679
 
        try:
680
 
            handle = self._get_sftp().file(abspath, mode='wb')
681
 
            handle.set_pipelined(True)
682
 
        except (paramiko.SSHException, IOError), e:
683
 
            self._translate_io_exception(e, abspath,
684
 
                                         ': unable to open')
685
 
        _file_streams[self.abspath(relpath)] = handle
686
 
        return FileFileStream(self, relpath, handle)
687
 
 
688
 
    def _translate_io_exception(self, e, path, more_info='',
 
684
    def _translate_io_exception(self, e, path, more_info='', 
689
685
                                failure_exc=PathError):
690
686
        """Translate a paramiko or IOError into a friendlier exception.
691
687
 
696
692
        :param failure_exc: Paramiko has the super fun ability to raise completely
697
693
                           opaque errors that just set "e.args = ('Failure',)" with
698
694
                           no more information.
699
 
                           If this parameter is set, it defines the exception
 
695
                           If this parameter is set, it defines the exception 
700
696
                           to raise in these cases.
701
697
        """
702
698
        # paramiko seems to generate detailless errors.
705
701
            if (e.args == ('No such file or directory',) or
706
702
                e.args == ('No such file',)):
707
703
                raise NoSuchFile(path, str(e) + more_info)
708
 
            if (e.args == ('mkdir failed',) or
709
 
                e.args[0].startswith('syserr: File exists')):
 
704
            if (e.args == ('mkdir failed',)):
710
705
                raise FileExists(path, str(e) + more_info)
711
706
            # strange but true, for the paramiko server.
712
707
            if (e.args == ('Failure',)):
723
718
        """
724
719
        try:
725
720
            path = self._remote_path(relpath)
726
 
            fout = self._get_sftp().file(path, 'ab')
 
721
            fout = self._sftp.file(path, 'ab')
727
722
            if mode is not None:
728
 
                self._get_sftp().chmod(path, mode)
 
723
                self._sftp.chmod(path, mode)
729
724
            result = fout.tell()
730
725
            self._pump(f, fout)
731
726
            return result
735
730
    def rename(self, rel_from, rel_to):
736
731
        """Rename without special overwriting"""
737
732
        try:
738
 
            self._get_sftp().rename(self._remote_path(rel_from),
 
733
            self._sftp.rename(self._remote_path(rel_from),
739
734
                              self._remote_path(rel_to))
740
735
        except (IOError, paramiko.SSHException), e:
741
736
            self._translate_io_exception(e, rel_from,
743
738
 
744
739
    def _rename_and_overwrite(self, abs_from, abs_to):
745
740
        """Do a fancy rename on the remote server.
746
 
 
 
741
        
747
742
        Using the implementation provided by osutils.
748
743
        """
749
744
        try:
750
 
            sftp = self._get_sftp()
751
745
            fancy_rename(abs_from, abs_to,
752
 
                         rename_func=sftp.rename,
753
 
                         unlink_func=sftp.remove)
 
746
                    rename_func=self._sftp.rename,
 
747
                    unlink_func=self._sftp.remove)
754
748
        except (IOError, paramiko.SSHException), e:
755
 
            self._translate_io_exception(e, abs_from,
756
 
                                         ': unable to rename to %r' % (abs_to))
 
749
            self._translate_io_exception(e, abs_from, ': unable to rename to %r' % (abs_to))
757
750
 
758
751
    def move(self, rel_from, rel_to):
759
752
        """Move the item at rel_from to the location at rel_to"""
765
758
        """Delete the item at relpath"""
766
759
        path = self._remote_path(relpath)
767
760
        try:
768
 
            self._get_sftp().remove(path)
 
761
            self._sftp.remove(path)
769
762
        except (IOError, paramiko.SSHException), e:
770
763
            self._translate_io_exception(e, path, ': unable to delete')
771
 
 
772
 
    def external_url(self):
773
 
        """See bzrlib.transport.Transport.external_url."""
774
 
        # the external path for SFTP is the base
775
 
        return self.base
776
 
 
 
764
            
777
765
    def listable(self):
778
766
        """Return True if this store supports listing."""
779
767
        return True
788
776
        # -- David Allouche 2006-08-11
789
777
        path = self._remote_path(relpath)
790
778
        try:
791
 
            entries = self._get_sftp().listdir(path)
792
 
            self._report_activity(sum(map(len, entries)), 'read')
 
779
            entries = self._sftp.listdir(path)
793
780
        except (IOError, paramiko.SSHException), e:
794
781
            self._translate_io_exception(e, path, ': failed to list_dir')
795
782
        return [urlutils.escape(entry) for entry in entries]
798
785
        """See Transport.rmdir."""
799
786
        path = self._remote_path(relpath)
800
787
        try:
801
 
            return self._get_sftp().rmdir(path)
 
788
            return self._sftp.rmdir(path)
802
789
        except (IOError, paramiko.SSHException), e:
803
790
            self._translate_io_exception(e, path, ': failed to rmdir')
804
791
 
806
793
        """Return the stat information for a file."""
807
794
        path = self._remote_path(relpath)
808
795
        try:
809
 
            return self._get_sftp().stat(path)
 
796
            return self._sftp.stat(path)
810
797
        except (IOError, paramiko.SSHException), e:
811
798
            self._translate_io_exception(e, path, ': unable to stat')
812
799
 
836
823
        # that we have taken the lock.
837
824
        return SFTPLock(relpath, self)
838
825
 
 
826
    def _sftp_connect(self):
 
827
        """Connect to the remote sftp server.
 
828
        After this, self._sftp should have a valid connection (or
 
829
        we raise an TransportError 'could not connect').
 
830
 
 
831
        TODO: Raise a more reasonable ConnectionFailed exception
 
832
        """
 
833
        self._sftp = _sftp_connect(self._host, self._port, self._username,
 
834
                self._password)
 
835
 
839
836
    def _sftp_open_exclusive(self, abspath, mode=None):
840
837
        """Open a remote path exclusively.
841
838
 
852
849
        """
853
850
        # TODO: jam 20060816 Paramiko >= 1.6.2 (probably earlier) supports
854
851
        #       using the 'x' flag to indicate SFTP_FLAG_EXCL.
855
 
        #       However, there is no way to set the permission mode at open
 
852
        #       However, there is no way to set the permission mode at open 
856
853
        #       time using the sftp_client.file() functionality.
857
 
        path = self._get_sftp()._adjust_cwd(abspath)
 
854
        path = self._sftp._adjust_cwd(abspath)
858
855
        # mutter('sftp abspath %s => %s', abspath, path)
859
856
        attr = SFTPAttributes()
860
857
        if mode is not None:
861
858
            attr.st_mode = mode
862
 
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
 
859
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE 
863
860
                | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
864
861
        try:
865
 
            t, msg = self._get_sftp()._request(CMD_OPEN, path, omode, attr)
 
862
            t, msg = self._sftp._request(CMD_OPEN, path, omode, attr)
866
863
            if t != CMD_HANDLE:
867
864
                raise TransportError('Expected an SFTP handle')
868
865
            handle = msg.get_string()
869
 
            return SFTPFile(self._get_sftp(), handle, 'wb', -1)
 
866
            return SFTPFile(self._sftp, handle, 'wb', -1)
870
867
        except (paramiko.SSHException, IOError), e:
871
868
            self._translate_io_exception(e, abspath, ': unable to open',
872
869
                failure_exc=FileExists)
943
940
                # probably a failed test; unit test thread will log the
944
941
                # failure/error
945
942
                sys.excepthook(*sys.exc_info())
946
 
                warning('Exception from within unit test server thread: %r' %
 
943
                warning('Exception from within unit test server thread: %r' % 
947
944
                        x)
948
945
 
949
946
 
960
957
 
961
958
    Not all methods are implemented, this is deliberate as this class is not a
962
959
    replacement for the builtin sockets layer. fileno is not implemented to
963
 
    prevent the proxy being bypassed.
 
960
    prevent the proxy being bypassed. 
964
961
    """
965
962
 
966
963
    simulated_time = 0
968
965
        "close", "getpeername", "getsockname", "getsockopt", "gettimeout",
969
966
        "setblocking", "setsockopt", "settimeout", "shutdown"])
970
967
 
971
 
    def __init__(self, sock, latency, bandwidth=1.0,
 
968
    def __init__(self, sock, latency, bandwidth=1.0, 
972
969
                 really_sleep=True):
973
 
        """
 
970
        """ 
974
971
        :param bandwith: simulated bandwith (MegaBit)
975
972
        :param really_sleep: If set to false, the SocketDelay will just
976
973
        increase a counter, instead of calling time.sleep. This is useful for
979
976
        self.sock = sock
980
977
        self.latency = latency
981
978
        self.really_sleep = really_sleep
982
 
        self.time_per_byte = 1 / (bandwidth / 8.0 * 1024 * 1024)
 
979
        self.time_per_byte = 1 / (bandwidth / 8.0 * 1024 * 1024) 
983
980
        self.new_roundtrip = False
984
981
 
985
982
    def sleep(self, s):
1047
1044
 
1048
1045
    def _run_server_entry(self, sock):
1049
1046
        """Entry point for all implementations of _run_server.
1050
 
 
 
1047
        
1051
1048
        If self.add_latency is > 0.000001 then sock is given a latency adding
1052
1049
        decorator.
1053
1050
        """
1070
1067
        event = threading.Event()
1071
1068
        ssh_server.start_server(event, server)
1072
1069
        event.wait(5.0)
1073
 
 
1074
 
    def setUp(self, backing_server=None):
1075
 
        # XXX: TODO: make sftpserver back onto backing_server rather than local
1076
 
        # disk.
1077
 
        if not (backing_server is None or
1078
 
                isinstance(backing_server, local.LocalURLServer)):
1079
 
            raise AssertionError(
1080
 
                "backing_server should not be %r, because this can only serve the "
1081
 
                "local current working directory." % (backing_server,))
1082
 
        self._original_vendor = ssh._ssh_vendor_manager._cached_ssh_vendor
1083
 
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._vendor
 
1070
    
 
1071
    def setUp(self):
 
1072
        self._original_vendor = ssh._ssh_vendor
 
1073
        ssh._ssh_vendor = self._vendor
1084
1074
        if sys.platform == 'win32':
1085
1075
            # Win32 needs to use the UNICODE api
1086
1076
            self._homedir = getcwd()
1099
1089
    def tearDown(self):
1100
1090
        """See bzrlib.transport.Server.tearDown."""
1101
1091
        self._listener.stop()
1102
 
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._original_vendor
 
1092
        ssh._ssh_vendor = self._original_vendor
1103
1093
 
1104
1094
    def get_bogus_url(self):
1105
1095
        """See bzrlib.transport.Server.get_bogus_url."""
1116
1106
 
1117
1107
    def get_url(self):
1118
1108
        """See bzrlib.transport.Server.get_url."""
1119
 
        homedir = self._homedir
1120
 
        if sys.platform != 'win32':
1121
 
            # Remove the initial '/' on all platforms but win32
1122
 
            homedir = homedir[1:]
1123
 
        return self._get_sftp_url(urlutils.escape(homedir))
 
1109
        return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1124
1110
 
1125
1111
 
1126
1112
class SFTPServerWithoutSSH(SFTPServer):
1146
1132
            def close(self):
1147
1133
                pass
1148
1134
 
1149
 
        server = paramiko.SFTPServer(
1150
 
            FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
1151
 
            root=self._root, home=self._server_homedir)
 
1135
        server = paramiko.SFTPServer(FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
 
1136
                                     root=self._root, home=self._server_homedir)
1152
1137
        try:
1153
 
            server.start_subsystem(
1154
 
                'sftp', None, ssh.SocketAsChannelAdapter(sock))
 
1138
            server.start_subsystem('sftp', None, sock)
1155
1139
        except socket.error, e:
1156
1140
            if (len(e.args) > 0) and (e.args[0] == errno.EPIPE):
1157
1141
                # it's okay for the client to disconnect abruptly
1160
1144
            else:
1161
1145
                raise
1162
1146
        except Exception, e:
1163
 
            # This typically seems to happen during interpreter shutdown, so
1164
 
            # most of the useful ways to report this error are won't work.
1165
 
            # Writing the exception type, and then the text of the exception,
1166
 
            # seems to be the best we can do.
1167
 
            import sys
1168
 
            sys.stderr.write('\nEXCEPTION %r: ' % (e.__class__,))
1169
 
            sys.stderr.write('%s\n\n' % (e,))
 
1147
            import sys; sys.stderr.write('\nEXCEPTION %r\n\n' % e.__class__)
1170
1148
        server.finish_subsystem()
1171
1149
 
1172
1150
 
1175
1153
 
1176
1154
    def get_url(self):
1177
1155
        """See bzrlib.transport.Server.get_url."""
1178
 
        homedir = self._homedir
1179
 
        if sys.platform != 'win32':
1180
 
            # Remove the initial '/' on all platforms but win32
1181
 
            homedir = homedir[1:]
1182
 
        return self._get_sftp_url(urlutils.escape(homedir))
 
1156
        if sys.platform == 'win32':
 
1157
            return self._get_sftp_url(urlutils.escape(self._homedir))
 
1158
        else:
 
1159
            return self._get_sftp_url(urlutils.escape(self._homedir[1:]))
1183
1160
 
1184
1161
 
1185
1162
class SFTPHomeDirServer(SFTPServerWithoutSSH):
1191
1168
 
1192
1169
 
1193
1170
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
1194
 
    """A test server for sftp transports where only absolute paths will work.
1195
 
 
1196
 
    It does this by serving from a deeply-nested directory that doesn't exist.
1197
 
    """
1198
 
 
1199
 
    def setUp(self, backing_server=None):
 
1171
    """A test servere for sftp transports, using absolute urls to non-home."""
 
1172
 
 
1173
    def setUp(self):
1200
1174
        self._server_homedir = '/dev/noone/runs/tests/here'
1201
 
        super(SFTPSiblingAbsoluteServer, self).setUp(backing_server)
 
1175
        super(SFTPSiblingAbsoluteServer, self).setUp()
 
1176
 
 
1177
 
 
1178
def _sftp_connect(host, port, username, password):
 
1179
    """Connect to the remote sftp server.
 
1180
 
 
1181
    :raises: a TransportError 'could not connect'.
 
1182
 
 
1183
    :returns: an paramiko.sftp_client.SFTPClient
 
1184
 
 
1185
    TODO: Raise a more reasonable ConnectionFailed exception
 
1186
    """
 
1187
    idx = (host, port, username)
 
1188
    try:
 
1189
        return _connected_hosts[idx]
 
1190
    except KeyError:
 
1191
        pass
 
1192
    
 
1193
    sftp = _sftp_connect_uncached(host, port, username, password)
 
1194
    _connected_hosts[idx] = sftp
 
1195
    return sftp
 
1196
 
 
1197
def _sftp_connect_uncached(host, port, username, password):
 
1198
    vendor = ssh._get_ssh_vendor()
 
1199
    sftp = vendor.connect_sftp(username, password, host, port)
 
1200
    return sftp
1202
1201
 
1203
1202
 
1204
1203
def get_test_permutations():