/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/transport/sftp.py

  • Committer: Michael Hudson
  • Date: 2008-12-10 02:05:30 UTC
  • mto: (3889.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3890.
  • Revision ID: michael.hudson@canonical.com-20081210020530-7lrsz78ln4d08m8l
support -d in the revision-info command

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
 
2
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
 
 
18
"""Implementation of Transport over SFTP, using paramiko."""
 
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
import bisect
 
28
import errno
 
29
import itertools
 
30
import os
 
31
import random
 
32
import select
 
33
import socket
 
34
import stat
 
35
import sys
 
36
import time
 
37
import urllib
 
38
import urlparse
 
39
import warnings
 
40
 
 
41
from bzrlib import (
 
42
    config,
 
43
    errors,
 
44
    urlutils,
 
45
    )
 
46
from bzrlib.errors import (FileExists,
 
47
                           NoSuchFile, PathNotChild,
 
48
                           TransportError,
 
49
                           LockError,
 
50
                           PathError,
 
51
                           ParamikoNotPresent,
 
52
                           )
 
53
from bzrlib.osutils import pathjoin, fancy_rename, getcwd
 
54
from bzrlib.symbol_versioning import (
 
55
        deprecated_function,
 
56
        )
 
57
from bzrlib.trace import mutter, warning
 
58
from bzrlib.transport import (
 
59
    FileFileStream,
 
60
    _file_streams,
 
61
    local,
 
62
    Server,
 
63
    ssh,
 
64
    ConnectedTransport,
 
65
    )
 
66
 
 
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
try:
 
81
    import paramiko
 
82
except ImportError, e:
 
83
    raise ParamikoNotPresent(e)
 
84
else:
 
85
    from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
 
86
                               SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
 
87
                               CMD_HANDLE, CMD_OPEN)
 
88
    from paramiko.sftp_attr import SFTPAttributes
 
89
    from paramiko.sftp_file import SFTPFile
 
90
 
 
91
 
 
92
_paramiko_version = getattr(paramiko, '__version_info__', (0, 0, 0))
 
93
# don't use prefetch unless paramiko version >= 1.5.5 (there were bugs earlier)
 
94
_default_do_prefetch = (_paramiko_version >= (1, 5, 5))
 
95
 
 
96
 
 
97
class SFTPLock(object):
 
98
    """This fakes a lock in a remote location.
 
99
    
 
100
    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 
 
102
    deprecated storage formats.
 
103
    """
 
104
    
 
105
    __slots__ = ['path', 'lock_path', 'lock_file', 'transport']
 
106
 
 
107
    def __init__(self, path, transport):
 
108
        self.lock_file = None
 
109
        self.path = path
 
110
        self.lock_path = path + '.write-lock'
 
111
        self.transport = transport
 
112
        try:
 
113
            # RBC 20060103 FIXME should we be using private methods here ?
 
114
            abspath = transport._remote_path(self.lock_path)
 
115
            self.lock_file = transport._sftp_open_exclusive(abspath)
 
116
        except FileExists:
 
117
            raise LockError('File %r already locked' % (self.path,))
 
118
 
 
119
    def __del__(self):
 
120
        """Should this warn, or actually try to cleanup?"""
 
121
        if self.lock_file:
 
122
            warning("SFTPLock %r not explicitly unlocked" % (self.path,))
 
123
            self.unlock()
 
124
 
 
125
    def unlock(self):
 
126
        if not self.lock_file:
 
127
            return
 
128
        self.lock_file.close()
 
129
        self.lock_file = None
 
130
        try:
 
131
            self.transport.delete(self.lock_path)
 
132
        except (NoSuchFile,):
 
133
            # What specific errors should we catch here?
 
134
            pass
 
135
 
 
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):
 
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
        """
 
150
        self.original_offsets = list(original_offsets)
 
151
        self.relpath = relpath
 
152
 
 
153
    def _get_requests(self):
 
154
        """Break up the offsets into individual requests over sftp.
 
155
 
 
156
        The SFTP spec only requires implementers to support 32kB requests. We
 
157
        could try something larger (openssh supports 64kB), but then we have to
 
158
        handle requests that fail.
 
159
        So instead, we just break up our maximum chunks into 32kB chunks, and
 
160
        asyncronously requests them.
 
161
        Newer versions of paramiko would do the chunking for us, but we want to
 
162
        start processing results right away, so we do it ourselves.
 
163
        """
 
164
        # TODO: Because we issue async requests, we don't 'fudge' any extra
 
165
        #       data.  I'm not 100% sure that is the best choice.
 
166
 
 
167
        # The first thing we do, is to collapse the individual requests as much
 
168
        # as possible, so we don't issues requests <32kB
 
169
        sorted_offsets = sorted(self.original_offsets)
 
170
        coalesced = list(ConnectedTransport._coalesce_offsets(sorted_offsets,
 
171
                                                        limit=0, fudge_factor=0))
 
172
        requests = []
 
173
        for c_offset in coalesced:
 
174
            start = c_offset.start
 
175
            size = c_offset.length
 
176
 
 
177
            # Break this up into 32kB requests
 
178
            while size > 0:
 
179
                next_size = min(size, self._max_request_size)
 
180
                requests.append((start, next_size))
 
181
                size -= next_size
 
182
                start += next_size
 
183
        mutter('SFTP.readv(%s) %s offsets => %s coalesced => %s requests',
 
184
               self.relpath, len(sorted_offsets), len(coalesced),
 
185
               len(requests))
 
186
        return requests
 
187
 
 
188
    def request_and_yield_offsets(self, fp):
 
189
        """Request the data from the remote machine, yielding the results.
 
190
 
 
191
        :param fp: A Paramiko SFTPFile object that supports readv.
 
192
        :return: Yield the data requested by the original readv caller, one by
 
193
            one.
 
194
        """
 
195
        requests = self._get_requests()
 
196
        offset_iter = iter(self.original_offsets)
 
197
        cur_offset, cur_size = offset_iter.next()
 
198
        # paramiko .readv() yields strings that are in the order of the requests
 
199
        # So we track the current request to know where the next data is
 
200
        # being returned from.
 
201
        input_start = None
 
202
        last_end = None
 
203
        buffered_data = []
 
204
        buffered_len = 0
 
205
 
 
206
        # This is used to buffer chunks which we couldn't process yet
 
207
        # It is (start, end, data) tuples.
 
208
        data_chunks = []
 
209
        # Create an 'unlimited' data stream, so we stop based on requests,
 
210
        # rather than just because the data stream ended. This lets us detect
 
211
        # short readv.
 
212
        data_stream = itertools.chain(fp.readv(requests),
 
213
                                      itertools.repeat(None))
 
214
        for (start, length), data in itertools.izip(requests, data_stream):
 
215
            if data is None:
 
216
                if cur_coalesced is not None:
 
217
                    raise errors.ShortReadvError(self.relpath,
 
218
                        start, length, len(data))
 
219
            if len(data) != length:
 
220
                raise errors.ShortReadvError(self.relpath,
 
221
                    start, length, len(data))
 
222
            if last_end is None:
 
223
                # This is the first request, just buffer it
 
224
                buffered_data = [data]
 
225
                buffered_len = length
 
226
                input_start = start
 
227
            elif start == last_end:
 
228
                # The data we are reading fits neatly on the previous
 
229
                # buffer, so this is all part of a larger coalesced range.
 
230
                buffered_data.append(data)
 
231
                buffered_len += length
 
232
            else:
 
233
                # We have an 'interrupt' in the data stream. So we know we are
 
234
                # at a request boundary.
 
235
                if buffered_len > 0:
 
236
                    # We haven't consumed the buffer so far, so put it into
 
237
                    # data_chunks, and continue.
 
238
                    buffered = ''.join(buffered_data)
 
239
                    data_chunks.append((input_start, buffered))
 
240
                input_start = start
 
241
                buffered_data = [data]
 
242
                buffered_len = length
 
243
            last_end = start + length
 
244
            if input_start == cur_offset and cur_size <= buffered_len:
 
245
                # Simplify the next steps a bit by transforming buffered_data
 
246
                # into a single string. We also have the nice property that
 
247
                # when there is only one string ''.join([x]) == x, so there is
 
248
                # no data copying.
 
249
                buffered = ''.join(buffered_data)
 
250
                # Clean out buffered data so that we keep memory
 
251
                # consumption low
 
252
                del buffered_data[:]
 
253
                buffered_offset = 0
 
254
                # TODO: We *could* also consider the case where cur_offset is in
 
255
                #       in the buffered range, even though it doesn't *start*
 
256
                #       the buffered range. But for packs we pretty much always
 
257
                #       read in order, so you won't get any extra data in the
 
258
                #       middle.
 
259
                while (input_start == cur_offset
 
260
                       and (buffered_offset + cur_size) <= buffered_len):
 
261
                    # We've buffered enough data to process this request, spit it
 
262
                    # out
 
263
                    cur_data = buffered[buffered_offset:buffered_offset + cur_size]
 
264
                    # move the direct pointer into our buffered data
 
265
                    buffered_offset += cur_size
 
266
                    # Move the start-of-buffer pointer
 
267
                    input_start += cur_size
 
268
                    # Yield the requested data
 
269
                    yield cur_offset, cur_data
 
270
                    cur_offset, cur_size = offset_iter.next()
 
271
                # at this point, we've consumed as much of buffered as we can,
 
272
                # so break off the portion that we consumed
 
273
                if buffered_offset == len(buffered_data):
 
274
                    # No tail to leave behind
 
275
                    buffered_data = []
 
276
                    buffered_len = 0
 
277
                else:
 
278
                    buffered = buffered[buffered_offset:]
 
279
                    buffered_data = [buffered]
 
280
                    buffered_len = len(buffered)
 
281
        if buffered_len:
 
282
            buffered = ''.join(buffered_data)
 
283
            del buffered_data[:]
 
284
            data_chunks.append((input_start, buffered))
 
285
        if data_chunks:
 
286
            mutter('SFTP readv left with %d out-of-order bytes',
 
287
                   sum(map(lambda x: len(x[1]), data_chunks)))
 
288
            # We've processed all the readv data, at this point, anything we
 
289
            # couldn't process is in data_chunks. This doesn't happen often, so
 
290
            # this code path isn't optimized
 
291
            # We use an interesting process for data_chunks
 
292
            # Specifically if we have "bisect_left([(start, len, entries)],
 
293
            #                                       (qstart,)])
 
294
            # If start == qstart, then we get the specific node. Otherwise we
 
295
            # get the previous node
 
296
            while True:
 
297
                idx = bisect.bisect_left(data_chunks, (cur_offset,))
 
298
                if idx < len(data_chunks) and data_chunks[idx][0] == cur_offset:
 
299
                    # The data starts here
 
300
                    data = data_chunks[idx][1][:cur_size]
 
301
                elif idx > 0:
 
302
                    # The data is in a portion of a previous page
 
303
                    idx -= 1
 
304
                    sub_offset = cur_offset - data_chunks[idx][0]
 
305
                    data = data_chunks[idx][1]
 
306
                    data = data[sub_offset:sub_offset + cur_size]
 
307
                else:
 
308
                    # We are missing the page where the data should be found,
 
309
                    # something is wrong
 
310
                    data = ''
 
311
                if len(data) != cur_size:
 
312
                    raise AssertionError('We must have miscalulated.'
 
313
                        ' We expected %d bytes, but only found %d'
 
314
                        % (cur_size, len(data)))
 
315
                yield cur_offset, data
 
316
                cur_offset, cur_size = offset_iter.next()
 
317
 
 
318
 
 
319
class SFTPTransport(ConnectedTransport):
 
320
    """Transport implementation for SFTP access."""
 
321
 
 
322
    _do_prefetch = _default_do_prefetch
 
323
    # TODO: jam 20060717 Conceivably these could be configurable, either
 
324
    #       by auto-tuning at run-time, or by a configuration (per host??)
 
325
    #       but the performance curve is pretty flat, so just going with
 
326
    #       reasonable defaults.
 
327
    _max_readv_combine = 200
 
328
    # Having to round trip to the server means waiting for a response,
 
329
    # so it is better to download extra bytes.
 
330
    # 8KiB had good performance for both local and remote network operations
 
331
    _bytes_to_read_before_seek = 8192
 
332
 
 
333
    # The sftp spec says that implementations SHOULD allow reads
 
334
    # to be at least 32K. paramiko.readv() does an async request
 
335
    # for the chunks. So we need to keep it within a single request
 
336
    # size for paramiko <= 1.6.1. paramiko 1.6.2 will probably chop
 
337
    # up the request itself, rather than us having to worry about it
 
338
    _max_request_size = 32768
 
339
 
 
340
    def __init__(self, base, _from_transport=None):
 
341
        super(SFTPTransport, self).__init__(base,
 
342
                                            _from_transport=_from_transport)
 
343
 
 
344
    def _remote_path(self, relpath):
 
345
        """Return the path to be passed along the sftp protocol for relpath.
 
346
        
 
347
        :param relpath: is a urlencoded string.
 
348
        """
 
349
        relative = urlutils.unescape(relpath).encode('utf-8')
 
350
        remote_path = self._combine_paths(self._path, relative)
 
351
        # the initial slash should be removed from the path, and treated as a
 
352
        # homedir relative path (the path begins with a double slash if it is
 
353
        # absolute).  see draft-ietf-secsh-scp-sftp-ssh-uri-03.txt
 
354
        # RBC 20060118 we are not using this as its too user hostile. instead
 
355
        # we are following lftp and using /~/foo to mean '~/foo'
 
356
        # vila--20070602 and leave absolute paths begin with a single slash.
 
357
        if remote_path.startswith('/~/'):
 
358
            remote_path = remote_path[3:]
 
359
        elif remote_path == '/~':
 
360
            remote_path = ''
 
361
        return remote_path
 
362
 
 
363
    def _create_connection(self, credentials=None):
 
364
        """Create a new connection with the provided credentials.
 
365
 
 
366
        :param credentials: The credentials needed to establish the connection.
 
367
 
 
368
        :return: The created connection and its associated credentials.
 
369
 
 
370
        The credentials are only the password as it may have been entered
 
371
        interactively by the user and may be different from the one provided
 
372
        in base url at transport creation time.
 
373
        """
 
374
        if credentials is None:
 
375
            password = self._password
 
376
        else:
 
377
            password = credentials
 
378
 
 
379
        vendor = ssh._get_ssh_vendor()
 
380
        user = self._user
 
381
        if user is None:
 
382
            auth = config.AuthenticationConfig()
 
383
            user = auth.get_user('ssh', self._host, self._port)
 
384
        connection = vendor.connect_sftp(self._user, password,
 
385
                                         self._host, self._port)
 
386
        return connection, (user, password)
 
387
 
 
388
    def _get_sftp(self):
 
389
        """Ensures that a connection is established"""
 
390
        connection = self._get_connection()
 
391
        if connection is None:
 
392
            # First connection ever
 
393
            connection, credentials = self._create_connection()
 
394
            self._set_connection(connection, credentials)
 
395
        return connection
 
396
 
 
397
    def has(self, relpath):
 
398
        """
 
399
        Does the target location exist?
 
400
        """
 
401
        try:
 
402
            self._get_sftp().stat(self._remote_path(relpath))
 
403
            return True
 
404
        except IOError:
 
405
            return False
 
406
 
 
407
    def get(self, relpath):
 
408
        """
 
409
        Get the file at the given relative path.
 
410
 
 
411
        :param relpath: The relative path to the file
 
412
        """
 
413
        try:
 
414
            path = self._remote_path(relpath)
 
415
            f = self._get_sftp().file(path, mode='rb')
 
416
            if self._do_prefetch and (getattr(f, 'prefetch', None) is not None):
 
417
                f.prefetch()
 
418
            return f
 
419
        except (IOError, paramiko.SSHException), e:
 
420
            self._translate_io_exception(e, path, ': error retrieving',
 
421
                failure_exc=errors.ReadError)
 
422
 
 
423
    def _readv(self, relpath, offsets):
 
424
        """See Transport.readv()"""
 
425
        # We overload the default readv() because we want to use a file
 
426
        # that does not have prefetch enabled.
 
427
        # Also, if we have a new paramiko, it implements an async readv()
 
428
        if not offsets:
 
429
            return
 
430
 
 
431
        try:
 
432
            path = self._remote_path(relpath)
 
433
            fp = self._get_sftp().file(path, mode='rb')
 
434
            readv = getattr(fp, 'readv', None)
 
435
            if readv:
 
436
                return self._sftp_readv(fp, offsets, relpath)
 
437
            mutter('seek and read %s offsets', len(offsets))
 
438
            return self._seek_and_read(fp, offsets, relpath)
 
439
        except (IOError, paramiko.SSHException), e:
 
440
            self._translate_io_exception(e, path, ': error retrieving')
 
441
 
 
442
    def recommended_page_size(self):
 
443
        """See Transport.recommended_page_size().
 
444
 
 
445
        For SFTP we suggest a large page size to reduce the overhead
 
446
        introduced by latency.
 
447
        """
 
448
        return 64 * 1024
 
449
 
 
450
    def _sftp_readv(self, fp, offsets, relpath='<unknown>'):
 
451
        """Use the readv() member of fp to do async readv.
 
452
 
 
453
        And then read them using paramiko.readv(). paramiko.readv()
 
454
        does not support ranges > 64K, so it caps the request size, and
 
455
        just reads until it gets all the stuff it wants
 
456
        """
 
457
        helper = _SFTPReadvHelper(offsets, relpath)
 
458
        return helper.request_and_yield_offsets(fp)
 
459
 
 
460
    def put_file(self, relpath, f, mode=None):
 
461
        """
 
462
        Copy the file-like object into the location.
 
463
 
 
464
        :param relpath: Location to put the contents, relative to base.
 
465
        :param f:       File-like object.
 
466
        :param mode: The final mode for the file
 
467
        """
 
468
        final_path = self._remote_path(relpath)
 
469
        return self._put(final_path, f, mode=mode)
 
470
 
 
471
    def _put(self, abspath, f, mode=None):
 
472
        """Helper function so both put() and copy_abspaths can reuse the code"""
 
473
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
 
474
                        os.getpid(), random.randint(0,0x7FFFFFFF))
 
475
        fout = self._sftp_open_exclusive(tmp_abspath, mode=mode)
 
476
        closed = False
 
477
        try:
 
478
            try:
 
479
                fout.set_pipelined(True)
 
480
                length = self._pump(f, fout)
 
481
            except (IOError, paramiko.SSHException), e:
 
482
                self._translate_io_exception(e, tmp_abspath)
 
483
            # XXX: This doesn't truly help like we would like it to.
 
484
            #      The problem is that openssh strips sticky bits. So while we
 
485
            #      can properly set group write permission, we lose the group
 
486
            #      sticky bit. So it is probably best to stop chmodding, and
 
487
            #      just tell users that they need to set the umask correctly.
 
488
            #      The attr.st_mode = mode, in _sftp_open_exclusive
 
489
            #      will handle when the user wants the final mode to be more 
 
490
            #      restrictive. And then we avoid a round trip. Unless 
 
491
            #      paramiko decides to expose an async chmod()
 
492
 
 
493
            # This is designed to chmod() right before we close.
 
494
            # Because we set_pipelined() earlier, theoretically we might 
 
495
            # avoid the round trip for fout.close()
 
496
            if mode is not None:
 
497
                self._get_sftp().chmod(tmp_abspath, mode)
 
498
            fout.close()
 
499
            closed = True
 
500
            self._rename_and_overwrite(tmp_abspath, abspath)
 
501
            return length
 
502
        except Exception, e:
 
503
            # If we fail, try to clean up the temporary file
 
504
            # before we throw the exception
 
505
            # but don't let another exception mess things up
 
506
            # Write out the traceback, because otherwise
 
507
            # the catch and throw destroys it
 
508
            import traceback
 
509
            mutter(traceback.format_exc())
 
510
            try:
 
511
                if not closed:
 
512
                    fout.close()
 
513
                self._get_sftp().remove(tmp_abspath)
 
514
            except:
 
515
                # raise the saved except
 
516
                raise e
 
517
            # raise the original with its traceback if we can.
 
518
            raise
 
519
 
 
520
    def _put_non_atomic_helper(self, relpath, writer, mode=None,
 
521
                               create_parent_dir=False,
 
522
                               dir_mode=None):
 
523
        abspath = self._remote_path(relpath)
 
524
 
 
525
        # TODO: jam 20060816 paramiko doesn't publicly expose a way to
 
526
        #       set the file mode at create time. If it does, use it.
 
527
        #       But for now, we just chmod later anyway.
 
528
 
 
529
        def _open_and_write_file():
 
530
            """Try to open the target file, raise error on failure"""
 
531
            fout = None
 
532
            try:
 
533
                try:
 
534
                    fout = self._get_sftp().file(abspath, mode='wb')
 
535
                    fout.set_pipelined(True)
 
536
                    writer(fout)
 
537
                except (paramiko.SSHException, IOError), e:
 
538
                    self._translate_io_exception(e, abspath,
 
539
                                                 ': unable to open')
 
540
 
 
541
                # This is designed to chmod() right before we close.
 
542
                # Because we set_pipelined() earlier, theoretically we might 
 
543
                # avoid the round trip for fout.close()
 
544
                if mode is not None:
 
545
                    self._get_sftp().chmod(abspath, mode)
 
546
            finally:
 
547
                if fout is not None:
 
548
                    fout.close()
 
549
 
 
550
        if not create_parent_dir:
 
551
            _open_and_write_file()
 
552
            return
 
553
 
 
554
        # Try error handling to create the parent directory if we need to
 
555
        try:
 
556
            _open_and_write_file()
 
557
        except NoSuchFile:
 
558
            # Try to create the parent directory, and then go back to
 
559
            # writing the file
 
560
            parent_dir = os.path.dirname(abspath)
 
561
            self._mkdir(parent_dir, dir_mode)
 
562
            _open_and_write_file()
 
563
 
 
564
    def put_file_non_atomic(self, relpath, f, mode=None,
 
565
                            create_parent_dir=False,
 
566
                            dir_mode=None):
 
567
        """Copy the file-like object into the target location.
 
568
 
 
569
        This function is not strictly safe to use. It is only meant to
 
570
        be used when you already know that the target does not exist.
 
571
        It is not safe, because it will open and truncate the remote
 
572
        file. So there may be a time when the file has invalid contents.
 
573
 
 
574
        :param relpath: The remote location to put the contents.
 
575
        :param f:       File-like object.
 
576
        :param mode:    Possible access permissions for new file.
 
577
                        None means do not set remote permissions.
 
578
        :param create_parent_dir: If we cannot create the target file because
 
579
                        the parent directory does not exist, go ahead and
 
580
                        create it, and then try again.
 
581
        """
 
582
        def writer(fout):
 
583
            self._pump(f, fout)
 
584
        self._put_non_atomic_helper(relpath, writer, mode=mode,
 
585
                                    create_parent_dir=create_parent_dir,
 
586
                                    dir_mode=dir_mode)
 
587
 
 
588
    def put_bytes_non_atomic(self, relpath, bytes, mode=None,
 
589
                             create_parent_dir=False,
 
590
                             dir_mode=None):
 
591
        def writer(fout):
 
592
            fout.write(bytes)
 
593
        self._put_non_atomic_helper(relpath, writer, mode=mode,
 
594
                                    create_parent_dir=create_parent_dir,
 
595
                                    dir_mode=dir_mode)
 
596
 
 
597
    def iter_files_recursive(self):
 
598
        """Walk the relative paths of all files in this transport."""
 
599
        queue = list(self.list_dir('.'))
 
600
        while queue:
 
601
            relpath = queue.pop(0)
 
602
            st = self.stat(relpath)
 
603
            if stat.S_ISDIR(st.st_mode):
 
604
                for i, basename in enumerate(self.list_dir(relpath)):
 
605
                    queue.insert(i, relpath+'/'+basename)
 
606
            else:
 
607
                yield relpath
 
608
 
 
609
    def _mkdir(self, abspath, mode=None):
 
610
        if mode is None:
 
611
            local_mode = 0777
 
612
        else:
 
613
            local_mode = mode
 
614
        try:
 
615
            self._get_sftp().mkdir(abspath, local_mode)
 
616
            if mode is not None:
 
617
                # chmod a dir through sftp will erase any sgid bit set
 
618
                # on the server side.  So, if the bit mode are already
 
619
                # set, avoid the chmod.  If the mode is not fine but
 
620
                # the sgid bit is set, report a warning to the user
 
621
                # with the umask fix.
 
622
                stat = self._get_sftp().lstat(abspath)
 
623
                mode = mode & 0777 # can't set special bits anyway
 
624
                if mode != stat.st_mode & 0777:
 
625
                    if stat.st_mode & 06000:
 
626
                        warning('About to chmod %s over sftp, which will result'
 
627
                                ' in its suid or sgid bits being cleared.  If'
 
628
                                ' you want to preserve those bits, change your '
 
629
                                ' environment on the server to use umask 0%03o.'
 
630
                                % (abspath, 0777 - mode))
 
631
                    self._get_sftp().chmod(abspath, mode=mode)
 
632
        except (paramiko.SSHException, IOError), e:
 
633
            self._translate_io_exception(e, abspath, ': unable to mkdir',
 
634
                failure_exc=FileExists)
 
635
 
 
636
    def mkdir(self, relpath, mode=None):
 
637
        """Create a directory at the given path."""
 
638
        self._mkdir(self._remote_path(relpath), mode=mode)
 
639
 
 
640
    def open_write_stream(self, relpath, mode=None):
 
641
        """See Transport.open_write_stream."""
 
642
        # initialise the file to zero-length
 
643
        # this is three round trips, but we don't use this 
 
644
        # api more than once per write_group at the moment so 
 
645
        # it is a tolerable overhead. Better would be to truncate
 
646
        # the file after opening. RBC 20070805
 
647
        self.put_bytes_non_atomic(relpath, "", mode)
 
648
        abspath = self._remote_path(relpath)
 
649
        # TODO: jam 20060816 paramiko doesn't publicly expose a way to
 
650
        #       set the file mode at create time. If it does, use it.
 
651
        #       But for now, we just chmod later anyway.
 
652
        handle = None
 
653
        try:
 
654
            handle = self._get_sftp().file(abspath, mode='wb')
 
655
            handle.set_pipelined(True)
 
656
        except (paramiko.SSHException, IOError), e:
 
657
            self._translate_io_exception(e, abspath,
 
658
                                         ': unable to open')
 
659
        _file_streams[self.abspath(relpath)] = handle
 
660
        return FileFileStream(self, relpath, handle)
 
661
 
 
662
    def _translate_io_exception(self, e, path, more_info='',
 
663
                                failure_exc=PathError):
 
664
        """Translate a paramiko or IOError into a friendlier exception.
 
665
 
 
666
        :param e: The original exception
 
667
        :param path: The path in question when the error is raised
 
668
        :param more_info: Extra information that can be included,
 
669
                          such as what was going on
 
670
        :param failure_exc: Paramiko has the super fun ability to raise completely
 
671
                           opaque errors that just set "e.args = ('Failure',)" with
 
672
                           no more information.
 
673
                           If this parameter is set, it defines the exception 
 
674
                           to raise in these cases.
 
675
        """
 
676
        # paramiko seems to generate detailless errors.
 
677
        self._translate_error(e, path, raise_generic=False)
 
678
        if getattr(e, 'args', None) is not None:
 
679
            if (e.args == ('No such file or directory',) or
 
680
                e.args == ('No such file',)):
 
681
                raise NoSuchFile(path, str(e) + more_info)
 
682
            if (e.args == ('mkdir failed',) or
 
683
                e.args[0].startswith('syserr: File exists')):
 
684
                raise FileExists(path, str(e) + more_info)
 
685
            # strange but true, for the paramiko server.
 
686
            if (e.args == ('Failure',)):
 
687
                raise failure_exc(path, str(e) + more_info)
 
688
            mutter('Raising exception with args %s', e.args)
 
689
        if getattr(e, 'errno', None) is not None:
 
690
            mutter('Raising exception with errno %s', e.errno)
 
691
        raise e
 
692
 
 
693
    def append_file(self, relpath, f, mode=None):
 
694
        """
 
695
        Append the text in the file-like object into the final
 
696
        location.
 
697
        """
 
698
        try:
 
699
            path = self._remote_path(relpath)
 
700
            fout = self._get_sftp().file(path, 'ab')
 
701
            if mode is not None:
 
702
                self._get_sftp().chmod(path, mode)
 
703
            result = fout.tell()
 
704
            self._pump(f, fout)
 
705
            return result
 
706
        except (IOError, paramiko.SSHException), e:
 
707
            self._translate_io_exception(e, relpath, ': unable to append')
 
708
 
 
709
    def rename(self, rel_from, rel_to):
 
710
        """Rename without special overwriting"""
 
711
        try:
 
712
            self._get_sftp().rename(self._remote_path(rel_from),
 
713
                              self._remote_path(rel_to))
 
714
        except (IOError, paramiko.SSHException), e:
 
715
            self._translate_io_exception(e, rel_from,
 
716
                    ': unable to rename to %r' % (rel_to))
 
717
 
 
718
    def _rename_and_overwrite(self, abs_from, abs_to):
 
719
        """Do a fancy rename on the remote server.
 
720
        
 
721
        Using the implementation provided by osutils.
 
722
        """
 
723
        try:
 
724
            sftp = self._get_sftp()
 
725
            fancy_rename(abs_from, abs_to,
 
726
                         rename_func=sftp.rename,
 
727
                         unlink_func=sftp.remove)
 
728
        except (IOError, paramiko.SSHException), e:
 
729
            self._translate_io_exception(e, abs_from,
 
730
                                         ': unable to rename to %r' % (abs_to))
 
731
 
 
732
    def move(self, rel_from, rel_to):
 
733
        """Move the item at rel_from to the location at rel_to"""
 
734
        path_from = self._remote_path(rel_from)
 
735
        path_to = self._remote_path(rel_to)
 
736
        self._rename_and_overwrite(path_from, path_to)
 
737
 
 
738
    def delete(self, relpath):
 
739
        """Delete the item at relpath"""
 
740
        path = self._remote_path(relpath)
 
741
        try:
 
742
            self._get_sftp().remove(path)
 
743
        except (IOError, paramiko.SSHException), e:
 
744
            self._translate_io_exception(e, path, ': unable to delete')
 
745
            
 
746
    def external_url(self):
 
747
        """See bzrlib.transport.Transport.external_url."""
 
748
        # the external path for SFTP is the base
 
749
        return self.base
 
750
 
 
751
    def listable(self):
 
752
        """Return True if this store supports listing."""
 
753
        return True
 
754
 
 
755
    def list_dir(self, relpath):
 
756
        """
 
757
        Return a list of all files at the given location.
 
758
        """
 
759
        # does anything actually use this?
 
760
        # -- Unknown
 
761
        # This is at least used by copy_tree for remote upgrades.
 
762
        # -- David Allouche 2006-08-11
 
763
        path = self._remote_path(relpath)
 
764
        try:
 
765
            entries = self._get_sftp().listdir(path)
 
766
        except (IOError, paramiko.SSHException), e:
 
767
            self._translate_io_exception(e, path, ': failed to list_dir')
 
768
        return [urlutils.escape(entry) for entry in entries]
 
769
 
 
770
    def rmdir(self, relpath):
 
771
        """See Transport.rmdir."""
 
772
        path = self._remote_path(relpath)
 
773
        try:
 
774
            return self._get_sftp().rmdir(path)
 
775
        except (IOError, paramiko.SSHException), e:
 
776
            self._translate_io_exception(e, path, ': failed to rmdir')
 
777
 
 
778
    def stat(self, relpath):
 
779
        """Return the stat information for a file."""
 
780
        path = self._remote_path(relpath)
 
781
        try:
 
782
            return self._get_sftp().stat(path)
 
783
        except (IOError, paramiko.SSHException), e:
 
784
            self._translate_io_exception(e, path, ': unable to stat')
 
785
 
 
786
    def lock_read(self, relpath):
 
787
        """
 
788
        Lock the given file for shared (read) access.
 
789
        :return: A lock object, which has an unlock() member function
 
790
        """
 
791
        # FIXME: there should be something clever i can do here...
 
792
        class BogusLock(object):
 
793
            def __init__(self, path):
 
794
                self.path = path
 
795
            def unlock(self):
 
796
                pass
 
797
        return BogusLock(relpath)
 
798
 
 
799
    def lock_write(self, relpath):
 
800
        """
 
801
        Lock the given file for exclusive (write) access.
 
802
        WARNING: many transports do not support this, so trying avoid using it
 
803
 
 
804
        :return: A lock object, which has an unlock() member function
 
805
        """
 
806
        # This is a little bit bogus, but basically, we create a file
 
807
        # which should not already exist, and if it does, we assume
 
808
        # that there is a lock, and if it doesn't, the we assume
 
809
        # that we have taken the lock.
 
810
        return SFTPLock(relpath, self)
 
811
 
 
812
    def _sftp_open_exclusive(self, abspath, mode=None):
 
813
        """Open a remote path exclusively.
 
814
 
 
815
        SFTP supports O_EXCL (SFTP_FLAG_EXCL), which fails if
 
816
        the file already exists. However it does not expose this
 
817
        at the higher level of SFTPClient.open(), so we have to
 
818
        sneak away with it.
 
819
 
 
820
        WARNING: This breaks the SFTPClient abstraction, so it
 
821
        could easily break against an updated version of paramiko.
 
822
 
 
823
        :param abspath: The remote absolute path where the file should be opened
 
824
        :param mode: The mode permissions bits for the new file
 
825
        """
 
826
        # TODO: jam 20060816 Paramiko >= 1.6.2 (probably earlier) supports
 
827
        #       using the 'x' flag to indicate SFTP_FLAG_EXCL.
 
828
        #       However, there is no way to set the permission mode at open 
 
829
        #       time using the sftp_client.file() functionality.
 
830
        path = self._get_sftp()._adjust_cwd(abspath)
 
831
        # mutter('sftp abspath %s => %s', abspath, path)
 
832
        attr = SFTPAttributes()
 
833
        if mode is not None:
 
834
            attr.st_mode = mode
 
835
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE 
 
836
                | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
 
837
        try:
 
838
            t, msg = self._get_sftp()._request(CMD_OPEN, path, omode, attr)
 
839
            if t != CMD_HANDLE:
 
840
                raise TransportError('Expected an SFTP handle')
 
841
            handle = msg.get_string()
 
842
            return SFTPFile(self._get_sftp(), handle, 'wb', -1)
 
843
        except (paramiko.SSHException, IOError), e:
 
844
            self._translate_io_exception(e, abspath, ': unable to open',
 
845
                failure_exc=FileExists)
 
846
 
 
847
    def _can_roundtrip_unix_modebits(self):
 
848
        if sys.platform == 'win32':
 
849
            # anyone else?
 
850
            return False
 
851
        else:
 
852
            return True
 
853
 
 
854
# ------------- server test implementation --------------
 
855
import threading
 
856
 
 
857
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
 
858
 
 
859
STUB_SERVER_KEY = """
 
860
-----BEGIN RSA PRIVATE KEY-----
 
861
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
 
862
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
 
863
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
 
864
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
 
865
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
 
866
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
 
867
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
 
868
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
 
869
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
 
870
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
 
871
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
 
872
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
 
873
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
 
874
-----END RSA PRIVATE KEY-----
 
875
"""
 
876
 
 
877
 
 
878
class SocketListener(threading.Thread):
 
879
 
 
880
    def __init__(self, callback):
 
881
        threading.Thread.__init__(self)
 
882
        self._callback = callback
 
883
        self._socket = socket.socket()
 
884
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 
885
        self._socket.bind(('localhost', 0))
 
886
        self._socket.listen(1)
 
887
        self.port = self._socket.getsockname()[1]
 
888
        self._stop_event = threading.Event()
 
889
 
 
890
    def stop(self):
 
891
        # called from outside this thread
 
892
        self._stop_event.set()
 
893
        # use a timeout here, because if the test fails, the server thread may
 
894
        # never notice the stop_event.
 
895
        self.join(5.0)
 
896
        self._socket.close()
 
897
 
 
898
    def run(self):
 
899
        while True:
 
900
            readable, writable_unused, exception_unused = \
 
901
                select.select([self._socket], [], [], 0.1)
 
902
            if self._stop_event.isSet():
 
903
                return
 
904
            if len(readable) == 0:
 
905
                continue
 
906
            try:
 
907
                s, addr_unused = self._socket.accept()
 
908
                # because the loopback socket is inline, and transports are
 
909
                # never explicitly closed, best to launch a new thread.
 
910
                threading.Thread(target=self._callback, args=(s,)).start()
 
911
            except socket.error, x:
 
912
                sys.excepthook(*sys.exc_info())
 
913
                warning('Socket error during accept() within unit test server'
 
914
                        ' thread: %r' % x)
 
915
            except Exception, x:
 
916
                # probably a failed test; unit test thread will log the
 
917
                # failure/error
 
918
                sys.excepthook(*sys.exc_info())
 
919
                warning('Exception from within unit test server thread: %r' % 
 
920
                        x)
 
921
 
 
922
 
 
923
class SocketDelay(object):
 
924
    """A socket decorator to make TCP appear slower.
 
925
 
 
926
    This changes recv, send, and sendall to add a fixed latency to each python
 
927
    call if a new roundtrip is detected. That is, when a recv is called and the
 
928
    flag new_roundtrip is set, latency is charged. Every send and send_all
 
929
    sets this flag.
 
930
 
 
931
    In addition every send, sendall and recv sleeps a bit per character send to
 
932
    simulate bandwidth.
 
933
 
 
934
    Not all methods are implemented, this is deliberate as this class is not a
 
935
    replacement for the builtin sockets layer. fileno is not implemented to
 
936
    prevent the proxy being bypassed. 
 
937
    """
 
938
 
 
939
    simulated_time = 0
 
940
    _proxied_arguments = dict.fromkeys([
 
941
        "close", "getpeername", "getsockname", "getsockopt", "gettimeout",
 
942
        "setblocking", "setsockopt", "settimeout", "shutdown"])
 
943
 
 
944
    def __init__(self, sock, latency, bandwidth=1.0, 
 
945
                 really_sleep=True):
 
946
        """ 
 
947
        :param bandwith: simulated bandwith (MegaBit)
 
948
        :param really_sleep: If set to false, the SocketDelay will just
 
949
        increase a counter, instead of calling time.sleep. This is useful for
 
950
        unittesting the SocketDelay.
 
951
        """
 
952
        self.sock = sock
 
953
        self.latency = latency
 
954
        self.really_sleep = really_sleep
 
955
        self.time_per_byte = 1 / (bandwidth / 8.0 * 1024 * 1024) 
 
956
        self.new_roundtrip = False
 
957
 
 
958
    def sleep(self, s):
 
959
        if self.really_sleep:
 
960
            time.sleep(s)
 
961
        else:
 
962
            SocketDelay.simulated_time += s
 
963
 
 
964
    def __getattr__(self, attr):
 
965
        if attr in SocketDelay._proxied_arguments:
 
966
            return getattr(self.sock, attr)
 
967
        raise AttributeError("'SocketDelay' object has no attribute %r" %
 
968
                             attr)
 
969
 
 
970
    def dup(self):
 
971
        return SocketDelay(self.sock.dup(), self.latency, self.time_per_byte,
 
972
                           self._sleep)
 
973
 
 
974
    def recv(self, *args):
 
975
        data = self.sock.recv(*args)
 
976
        if data and self.new_roundtrip:
 
977
            self.new_roundtrip = False
 
978
            self.sleep(self.latency)
 
979
        self.sleep(len(data) * self.time_per_byte)
 
980
        return data
 
981
 
 
982
    def sendall(self, data, flags=0):
 
983
        if not self.new_roundtrip:
 
984
            self.new_roundtrip = True
 
985
            self.sleep(self.latency)
 
986
        self.sleep(len(data) * self.time_per_byte)
 
987
        return self.sock.sendall(data, flags)
 
988
 
 
989
    def send(self, data, flags=0):
 
990
        if not self.new_roundtrip:
 
991
            self.new_roundtrip = True
 
992
            self.sleep(self.latency)
 
993
        bytes_sent = self.sock.send(data, flags)
 
994
        self.sleep(bytes_sent * self.time_per_byte)
 
995
        return bytes_sent
 
996
 
 
997
 
 
998
class SFTPServer(Server):
 
999
    """Common code for SFTP server facilities."""
 
1000
 
 
1001
    def __init__(self, server_interface=StubServer):
 
1002
        self._original_vendor = None
 
1003
        self._homedir = None
 
1004
        self._server_homedir = None
 
1005
        self._listener = None
 
1006
        self._root = None
 
1007
        self._vendor = ssh.ParamikoVendor()
 
1008
        self._server_interface = server_interface
 
1009
        # sftp server logs
 
1010
        self.logs = []
 
1011
        self.add_latency = 0
 
1012
 
 
1013
    def _get_sftp_url(self, path):
 
1014
        """Calculate an sftp url to this server for path."""
 
1015
        return 'sftp://foo:bar@localhost:%d/%s' % (self._listener.port, path)
 
1016
 
 
1017
    def log(self, message):
 
1018
        """StubServer uses this to log when a new server is created."""
 
1019
        self.logs.append(message)
 
1020
 
 
1021
    def _run_server_entry(self, sock):
 
1022
        """Entry point for all implementations of _run_server.
 
1023
        
 
1024
        If self.add_latency is > 0.000001 then sock is given a latency adding
 
1025
        decorator.
 
1026
        """
 
1027
        if self.add_latency > 0.000001:
 
1028
            sock = SocketDelay(sock, self.add_latency)
 
1029
        return self._run_server(sock)
 
1030
 
 
1031
    def _run_server(self, s):
 
1032
        ssh_server = paramiko.Transport(s)
 
1033
        key_file = pathjoin(self._homedir, 'test_rsa.key')
 
1034
        f = open(key_file, 'w')
 
1035
        f.write(STUB_SERVER_KEY)
 
1036
        f.close()
 
1037
        host_key = paramiko.RSAKey.from_private_key_file(key_file)
 
1038
        ssh_server.add_server_key(host_key)
 
1039
        server = self._server_interface(self)
 
1040
        ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
 
1041
                                         StubSFTPServer, root=self._root,
 
1042
                                         home=self._server_homedir)
 
1043
        event = threading.Event()
 
1044
        ssh_server.start_server(event, server)
 
1045
        event.wait(5.0)
 
1046
    
 
1047
    def setUp(self, backing_server=None):
 
1048
        # XXX: TODO: make sftpserver back onto backing_server rather than local
 
1049
        # disk.
 
1050
        if not (backing_server is None or
 
1051
                isinstance(backing_server, local.LocalURLServer)):
 
1052
            raise AssertionError(
 
1053
                "backing_server should not be %r, because this can only serve the "
 
1054
                "local current working directory." % (backing_server,))
 
1055
        self._original_vendor = ssh._ssh_vendor_manager._cached_ssh_vendor
 
1056
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._vendor
 
1057
        if sys.platform == 'win32':
 
1058
            # Win32 needs to use the UNICODE api
 
1059
            self._homedir = getcwd()
 
1060
        else:
 
1061
            # But Linux SFTP servers should just deal in bytestreams
 
1062
            self._homedir = os.getcwd()
 
1063
        if self._server_homedir is None:
 
1064
            self._server_homedir = self._homedir
 
1065
        self._root = '/'
 
1066
        if sys.platform == 'win32':
 
1067
            self._root = ''
 
1068
        self._listener = SocketListener(self._run_server_entry)
 
1069
        self._listener.setDaemon(True)
 
1070
        self._listener.start()
 
1071
 
 
1072
    def tearDown(self):
 
1073
        """See bzrlib.transport.Server.tearDown."""
 
1074
        self._listener.stop()
 
1075
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._original_vendor
 
1076
 
 
1077
    def get_bogus_url(self):
 
1078
        """See bzrlib.transport.Server.get_bogus_url."""
 
1079
        # this is chosen to try to prevent trouble with proxies, wierd dns, etc
 
1080
        # we bind a random socket, so that we get a guaranteed unused port
 
1081
        # we just never listen on that port
 
1082
        s = socket.socket()
 
1083
        s.bind(('localhost', 0))
 
1084
        return 'sftp://%s:%s/' % s.getsockname()
 
1085
 
 
1086
 
 
1087
class SFTPFullAbsoluteServer(SFTPServer):
 
1088
    """A test server for sftp transports, using absolute urls and ssh."""
 
1089
 
 
1090
    def get_url(self):
 
1091
        """See bzrlib.transport.Server.get_url."""
 
1092
        homedir = self._homedir
 
1093
        if sys.platform != 'win32':
 
1094
            # Remove the initial '/' on all platforms but win32
 
1095
            homedir = homedir[1:]
 
1096
        return self._get_sftp_url(urlutils.escape(homedir))
 
1097
 
 
1098
 
 
1099
class SFTPServerWithoutSSH(SFTPServer):
 
1100
    """An SFTP server that uses a simple TCP socket pair rather than SSH."""
 
1101
 
 
1102
    def __init__(self):
 
1103
        super(SFTPServerWithoutSSH, self).__init__()
 
1104
        self._vendor = ssh.LoopbackVendor()
 
1105
 
 
1106
    def _run_server(self, sock):
 
1107
        # Re-import these as locals, so that they're still accessible during
 
1108
        # interpreter shutdown (when all module globals get set to None, leading
 
1109
        # to confusing errors like "'NoneType' object has no attribute 'error'".
 
1110
        class FakeChannel(object):
 
1111
            def get_transport(self):
 
1112
                return self
 
1113
            def get_log_channel(self):
 
1114
                return 'paramiko'
 
1115
            def get_name(self):
 
1116
                return '1'
 
1117
            def get_hexdump(self):
 
1118
                return False
 
1119
            def close(self):
 
1120
                pass
 
1121
 
 
1122
        server = paramiko.SFTPServer(
 
1123
            FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
 
1124
            root=self._root, home=self._server_homedir)
 
1125
        try:
 
1126
            server.start_subsystem(
 
1127
                'sftp', None, ssh.SocketAsChannelAdapter(sock))
 
1128
        except socket.error, e:
 
1129
            if (len(e.args) > 0) and (e.args[0] == errno.EPIPE):
 
1130
                # it's okay for the client to disconnect abruptly
 
1131
                # (bug in paramiko 1.6: it should absorb this exception)
 
1132
                pass
 
1133
            else:
 
1134
                raise
 
1135
        except Exception, e:
 
1136
            # This typically seems to happen during interpreter shutdown, so
 
1137
            # most of the useful ways to report this error are won't work.
 
1138
            # Writing the exception type, and then the text of the exception,
 
1139
            # seems to be the best we can do.
 
1140
            import sys
 
1141
            sys.stderr.write('\nEXCEPTION %r: ' % (e.__class__,))
 
1142
            sys.stderr.write('%s\n\n' % (e,))
 
1143
        server.finish_subsystem()
 
1144
 
 
1145
 
 
1146
class SFTPAbsoluteServer(SFTPServerWithoutSSH):
 
1147
    """A test server for sftp transports, using absolute urls."""
 
1148
 
 
1149
    def get_url(self):
 
1150
        """See bzrlib.transport.Server.get_url."""
 
1151
        homedir = self._homedir
 
1152
        if sys.platform != 'win32':
 
1153
            # Remove the initial '/' on all platforms but win32
 
1154
            homedir = homedir[1:]
 
1155
        return self._get_sftp_url(urlutils.escape(homedir))
 
1156
 
 
1157
 
 
1158
class SFTPHomeDirServer(SFTPServerWithoutSSH):
 
1159
    """A test server for sftp transports, using homedir relative urls."""
 
1160
 
 
1161
    def get_url(self):
 
1162
        """See bzrlib.transport.Server.get_url."""
 
1163
        return self._get_sftp_url("~/")
 
1164
 
 
1165
 
 
1166
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
 
1167
    """A test server for sftp transports where only absolute paths will work.
 
1168
 
 
1169
    It does this by serving from a deeply-nested directory that doesn't exist.
 
1170
    """
 
1171
 
 
1172
    def setUp(self, backing_server=None):
 
1173
        self._server_homedir = '/dev/noone/runs/tests/here'
 
1174
        super(SFTPSiblingAbsoluteServer, self).setUp(backing_server)
 
1175
 
 
1176
 
 
1177
def get_test_permutations():
 
1178
    """Return the permutations to be used in testing."""
 
1179
    return [(SFTPTransport, SFTPAbsoluteServer),
 
1180
            (SFTPTransport, SFTPHomeDirServer),
 
1181
            (SFTPTransport, SFTPSiblingAbsoluteServer),
 
1182
            ]