/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: Martin Pool
  • Date: 2009-01-13 05:16:26 UTC
  • mfrom: (3936 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3940.
  • Revision ID: mbp@sourcefrog.net-20090113051626-0d5q6luqdoyx4xaf
Fix recommend_upgrade ui and merge trunk

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