/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

add single revision tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Implementation of Transport over SFTP, using paramiko."""
18
18
 
28
28
import itertools
29
29
import os
30
30
import random
 
31
import select
 
32
import socket
31
33
import stat
32
34
import sys
33
35
import time
37
39
 
38
40
from bzrlib import (
39
41
    config,
40
 
    debug,
41
42
    errors,
42
43
    urlutils,
43
44
    )
82
83
else:
83
84
    from paramiko.sftp import (SFTP_FLAG_WRITE, SFTP_FLAG_CREATE,
84
85
                               SFTP_FLAG_EXCL, SFTP_FLAG_TRUNC,
85
 
                               SFTP_OK, CMD_HANDLE, CMD_OPEN)
 
86
                               CMD_HANDLE, CMD_OPEN)
86
87
    from paramiko.sftp_attr import SFTPAttributes
87
88
    from paramiko.sftp_file import SFTPFile
88
89
 
94
95
 
95
96
class SFTPLock(object):
96
97
    """This fakes a lock in a remote location.
97
 
 
 
98
    
98
99
    A present lock is indicated just by the existence of a file.  This
99
 
    doesn't work well on all transports and they are only used in
 
100
    doesn't work well on all transports and they are only used in 
100
101
    deprecated storage formats.
101
102
    """
102
 
 
 
103
    
103
104
    __slots__ = ['path', 'lock_path', 'lock_file', 'transport']
104
105
 
105
106
    def __init__(self, path, transport):
181
182
                requests.append((start, next_size))
182
183
                size -= next_size
183
184
                start += next_size
184
 
        if 'sftp' in debug.debug_flags:
185
 
            mutter('SFTP.readv(%s) %s offsets => %s coalesced => %s requests',
186
 
                self.relpath, len(sorted_offsets), len(coalesced),
187
 
                len(requests))
 
185
        mutter('SFTP.readv(%s) %s offsets => %s coalesced => %s requests',
 
186
               self.relpath, len(sorted_offsets), len(coalesced),
 
187
               len(requests))
188
188
        return requests
189
189
 
190
190
    def request_and_yield_offsets(self, fp):
286
286
            del buffered_data[:]
287
287
            data_chunks.append((input_start, buffered))
288
288
        if data_chunks:
289
 
            if 'sftp' in debug.debug_flags:
290
 
                mutter('SFTP readv left with %d out-of-order bytes',
291
 
                    sum(map(lambda x: len(x[1]), data_chunks)))
 
289
            mutter('SFTP readv left with %d out-of-order bytes',
 
290
                   sum(map(lambda x: len(x[1]), data_chunks)))
292
291
            # We've processed all the readv data, at this point, anything we
293
292
            # couldn't process is in data_chunks. This doesn't happen often, so
294
293
            # this code path isn't optimized
347
346
 
348
347
    def _remote_path(self, relpath):
349
348
        """Return the path to be passed along the sftp protocol for relpath.
350
 
 
 
349
        
351
350
        :param relpath: is a urlencoded string.
352
351
        """
353
352
        relative = urlutils.unescape(relpath).encode('utf-8')
404
403
        """
405
404
        try:
406
405
            self._get_sftp().stat(self._remote_path(relpath))
407
 
            # stat result is about 20 bytes, let's say
408
 
            self._report_activity(20, 'read')
409
406
            return True
410
407
        except IOError:
411
408
            return False
416
413
        :param relpath: The relative path to the file
417
414
        """
418
415
        try:
419
 
            # FIXME: by returning the file directly, we don't pass this
420
 
            # through to report_activity.  We could try wrapping the object
421
 
            # before it's returned.  For readv and get_bytes it's handled in
422
 
            # the higher-level function.
423
 
            # -- mbp 20090126
424
416
            path = self._remote_path(relpath)
425
417
            f = self._get_sftp().file(path, mode='rb')
426
418
            if self._do_prefetch and (getattr(f, 'prefetch', None) is not None):
454
446
            readv = getattr(fp, 'readv', None)
455
447
            if readv:
456
448
                return self._sftp_readv(fp, offsets, relpath)
457
 
            if 'sftp' in debug.debug_flags:
458
 
                mutter('seek and read %s offsets', len(offsets))
 
449
            mutter('seek and read %s offsets', len(offsets))
459
450
            return self._seek_and_read(fp, offsets, relpath)
460
451
        except (IOError, paramiko.SSHException), e:
461
452
            self._translate_io_exception(e, path, ': error retrieving')
507
498
            #      sticky bit. So it is probably best to stop chmodding, and
508
499
            #      just tell users that they need to set the umask correctly.
509
500
            #      The attr.st_mode = mode, in _sftp_open_exclusive
510
 
            #      will handle when the user wants the final mode to be more
511
 
            #      restrictive. And then we avoid a round trip. Unless
 
501
            #      will handle when the user wants the final mode to be more 
 
502
            #      restrictive. And then we avoid a round trip. Unless 
512
503
            #      paramiko decides to expose an async chmod()
513
504
 
514
505
            # This is designed to chmod() right before we close.
515
 
            # Because we set_pipelined() earlier, theoretically we might
 
506
            # Because we set_pipelined() earlier, theoretically we might 
516
507
            # avoid the round trip for fout.close()
517
508
            if mode is not None:
518
509
                self._get_sftp().chmod(tmp_abspath, mode)
560
551
                                                 ': unable to open')
561
552
 
562
553
                # This is designed to chmod() right before we close.
563
 
                # Because we set_pipelined() earlier, theoretically we might
 
554
                # Because we set_pipelined() earlier, theoretically we might 
564
555
                # avoid the round trip for fout.close()
565
556
                if mode is not None:
566
557
                    self._get_sftp().chmod(abspath, mode)
617
608
 
618
609
    def iter_files_recursive(self):
619
610
        """Walk the relative paths of all files in this transport."""
620
 
        # progress is handled by list_dir
621
611
        queue = list(self.list_dir('.'))
622
612
        while queue:
623
613
            relpath = queue.pop(0)
634
624
        else:
635
625
            local_mode = mode
636
626
        try:
637
 
            self._report_activity(len(abspath), 'write')
638
627
            self._get_sftp().mkdir(abspath, local_mode)
639
 
            self._report_activity(1, 'read')
640
628
            if mode is not None:
641
629
                # chmod a dir through sftp will erase any sgid bit set
642
630
                # on the server side.  So, if the bit mode are already
664
652
    def open_write_stream(self, relpath, mode=None):
665
653
        """See Transport.open_write_stream."""
666
654
        # initialise the file to zero-length
667
 
        # this is three round trips, but we don't use this
668
 
        # api more than once per write_group at the moment so
 
655
        # this is three round trips, but we don't use this 
 
656
        # api more than once per write_group at the moment so 
669
657
        # it is a tolerable overhead. Better would be to truncate
670
658
        # the file after opening. RBC 20070805
671
659
        self.put_bytes_non_atomic(relpath, "", mode)
694
682
        :param failure_exc: Paramiko has the super fun ability to raise completely
695
683
                           opaque errors that just set "e.args = ('Failure',)" with
696
684
                           no more information.
697
 
                           If this parameter is set, it defines the exception
 
685
                           If this parameter is set, it defines the exception 
698
686
                           to raise in these cases.
699
687
        """
700
688
        # paramiko seems to generate detailless errors.
709
697
            # strange but true, for the paramiko server.
710
698
            if (e.args == ('Failure',)):
711
699
                raise failure_exc(path, str(e) + more_info)
712
 
            # Can be something like args = ('Directory not empty:
713
 
            # '/srv/bazaar.launchpad.net/blah...: '
714
 
            # [Errno 39] Directory not empty',)
715
 
            if (e.args[0].startswith('Directory not empty: ')
716
 
                or getattr(e, 'errno', None) == errno.ENOTEMPTY):
717
 
                raise errors.DirectoryNotEmpty(path, str(e))
718
700
            mutter('Raising exception with args %s', e.args)
719
701
        if getattr(e, 'errno', None) is not None:
720
702
            mutter('Raising exception with errno %s', e.errno)
747
729
 
748
730
    def _rename_and_overwrite(self, abs_from, abs_to):
749
731
        """Do a fancy rename on the remote server.
750
 
 
 
732
        
751
733
        Using the implementation provided by osutils.
752
734
        """
753
735
        try:
772
754
            self._get_sftp().remove(path)
773
755
        except (IOError, paramiko.SSHException), e:
774
756
            self._translate_io_exception(e, path, ': unable to delete')
775
 
 
 
757
            
776
758
    def external_url(self):
777
759
        """See bzrlib.transport.Transport.external_url."""
778
760
        # the external path for SFTP is the base
793
775
        path = self._remote_path(relpath)
794
776
        try:
795
777
            entries = self._get_sftp().listdir(path)
796
 
            self._report_activity(sum(map(len, entries)), 'read')
797
778
        except (IOError, paramiko.SSHException), e:
798
779
            self._translate_io_exception(e, path, ': failed to list_dir')
799
780
        return [urlutils.escape(entry) for entry in entries]
810
791
        """Return the stat information for a file."""
811
792
        path = self._remote_path(relpath)
812
793
        try:
813
 
            return self._get_sftp().lstat(path)
 
794
            return self._get_sftp().stat(path)
814
795
        except (IOError, paramiko.SSHException), e:
815
796
            self._translate_io_exception(e, path, ': unable to stat')
816
797
 
817
 
    def readlink(self, relpath):
818
 
        """See Transport.readlink."""
819
 
        path = self._remote_path(relpath)
820
 
        try:
821
 
            return self._get_sftp().readlink(path)
822
 
        except (IOError, paramiko.SSHException), e:
823
 
            self._translate_io_exception(e, path, ': unable to readlink')
824
 
 
825
 
    def symlink(self, source, link_name):
826
 
        """See Transport.symlink."""
827
 
        try:
828
 
            conn = self._get_sftp()
829
 
            sftp_retval = conn.symlink(source, link_name)
830
 
            if SFTP_OK != sftp_retval:
831
 
                raise TransportError(
832
 
                    '%r: unable to create symlink to %r' % (link_name, source),
833
 
                    sftp_retval
834
 
                )
835
 
        except (IOError, paramiko.SSHException), e:
836
 
            self._translate_io_exception(e, link_name,
837
 
                                         ': unable to create symlink to %r' % (source))
838
 
 
839
798
    def lock_read(self, relpath):
840
799
        """
841
800
        Lock the given file for shared (read) access.
878
837
        """
879
838
        # TODO: jam 20060816 Paramiko >= 1.6.2 (probably earlier) supports
880
839
        #       using the 'x' flag to indicate SFTP_FLAG_EXCL.
881
 
        #       However, there is no way to set the permission mode at open
 
840
        #       However, there is no way to set the permission mode at open 
882
841
        #       time using the sftp_client.file() functionality.
883
842
        path = self._get_sftp()._adjust_cwd(abspath)
884
843
        # mutter('sftp abspath %s => %s', abspath, path)
885
844
        attr = SFTPAttributes()
886
845
        if mode is not None:
887
846
            attr.st_mode = mode
888
 
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
 
847
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE 
889
848
                | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
890
849
        try:
891
850
            t, msg = self._get_sftp()._request(CMD_OPEN, path, omode, attr)
904
863
        else:
905
864
            return True
906
865
 
 
866
# ------------- server test implementation --------------
 
867
import threading
 
868
 
 
869
from bzrlib.tests.stub_sftp import StubServer, StubSFTPServer
 
870
 
 
871
STUB_SERVER_KEY = """
 
872
-----BEGIN RSA PRIVATE KEY-----
 
873
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
 
874
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVVhMpouqPAYQ15N37K/ir5XY+9m/
 
875
d8ufMCkjeXsQkKqFbAlQcnWMCRnOoPHS3I4vi6hmnDDeeYTSRvfLbW0fhwIBIwKB
 
876
gBIiOqZYaoqbeD9OS9z2K9KR2atlTxGxOJPXiP4ESqP3NVScWNwyZ3NXHpyrJLa0
 
877
EbVtzsQhLn6rF+TzXnOlcipFvjsem3iYzCpuChfGQ6SovTcOjHV9z+hnpXvQ/fon
 
878
soVRZY65wKnF7IAoUwTmJS9opqgrN6kRgCd3DASAMd1bAkEA96SBVWFt/fJBNJ9H
 
879
tYnBKZGw0VeHOYmVYbvMSstssn8un+pQpUm9vlG/bp7Oxd/m+b9KWEh2xPfv6zqU
 
880
avNwHwJBANqzGZa/EpzF4J8pGti7oIAPUIDGMtfIcmqNXVMckrmzQ2vTfqtkEZsA
 
881
4rE1IERRyiJQx6EJsz21wJmGV9WJQ5kCQQDwkS0uXqVdFzgHO6S++tjmjYcxwr3g
 
882
H0CoFYSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
 
883
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
 
884
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
 
885
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
 
886
-----END RSA PRIVATE KEY-----
 
887
"""
 
888
 
 
889
 
 
890
class SocketListener(threading.Thread):
 
891
 
 
892
    def __init__(self, callback):
 
893
        threading.Thread.__init__(self)
 
894
        self._callback = callback
 
895
        self._socket = socket.socket()
 
896
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 
897
        self._socket.bind(('localhost', 0))
 
898
        self._socket.listen(1)
 
899
        self.port = self._socket.getsockname()[1]
 
900
        self._stop_event = threading.Event()
 
901
 
 
902
    def stop(self):
 
903
        # called from outside this thread
 
904
        self._stop_event.set()
 
905
        # use a timeout here, because if the test fails, the server thread may
 
906
        # never notice the stop_event.
 
907
        self.join(5.0)
 
908
        self._socket.close()
 
909
 
 
910
    def run(self):
 
911
        while True:
 
912
            readable, writable_unused, exception_unused = \
 
913
                select.select([self._socket], [], [], 0.1)
 
914
            if self._stop_event.isSet():
 
915
                return
 
916
            if len(readable) == 0:
 
917
                continue
 
918
            try:
 
919
                s, addr_unused = self._socket.accept()
 
920
                # because the loopback socket is inline, and transports are
 
921
                # never explicitly closed, best to launch a new thread.
 
922
                threading.Thread(target=self._callback, args=(s,)).start()
 
923
            except socket.error, x:
 
924
                sys.excepthook(*sys.exc_info())
 
925
                warning('Socket error during accept() within unit test server'
 
926
                        ' thread: %r' % x)
 
927
            except Exception, x:
 
928
                # probably a failed test; unit test thread will log the
 
929
                # failure/error
 
930
                sys.excepthook(*sys.exc_info())
 
931
                warning('Exception from within unit test server thread: %r' % 
 
932
                        x)
 
933
 
 
934
 
 
935
class SocketDelay(object):
 
936
    """A socket decorator to make TCP appear slower.
 
937
 
 
938
    This changes recv, send, and sendall to add a fixed latency to each python
 
939
    call if a new roundtrip is detected. That is, when a recv is called and the
 
940
    flag new_roundtrip is set, latency is charged. Every send and send_all
 
941
    sets this flag.
 
942
 
 
943
    In addition every send, sendall and recv sleeps a bit per character send to
 
944
    simulate bandwidth.
 
945
 
 
946
    Not all methods are implemented, this is deliberate as this class is not a
 
947
    replacement for the builtin sockets layer. fileno is not implemented to
 
948
    prevent the proxy being bypassed. 
 
949
    """
 
950
 
 
951
    simulated_time = 0
 
952
    _proxied_arguments = dict.fromkeys([
 
953
        "close", "getpeername", "getsockname", "getsockopt", "gettimeout",
 
954
        "setblocking", "setsockopt", "settimeout", "shutdown"])
 
955
 
 
956
    def __init__(self, sock, latency, bandwidth=1.0, 
 
957
                 really_sleep=True):
 
958
        """ 
 
959
        :param bandwith: simulated bandwith (MegaBit)
 
960
        :param really_sleep: If set to false, the SocketDelay will just
 
961
        increase a counter, instead of calling time.sleep. This is useful for
 
962
        unittesting the SocketDelay.
 
963
        """
 
964
        self.sock = sock
 
965
        self.latency = latency
 
966
        self.really_sleep = really_sleep
 
967
        self.time_per_byte = 1 / (bandwidth / 8.0 * 1024 * 1024) 
 
968
        self.new_roundtrip = False
 
969
 
 
970
    def sleep(self, s):
 
971
        if self.really_sleep:
 
972
            time.sleep(s)
 
973
        else:
 
974
            SocketDelay.simulated_time += s
 
975
 
 
976
    def __getattr__(self, attr):
 
977
        if attr in SocketDelay._proxied_arguments:
 
978
            return getattr(self.sock, attr)
 
979
        raise AttributeError("'SocketDelay' object has no attribute %r" %
 
980
                             attr)
 
981
 
 
982
    def dup(self):
 
983
        return SocketDelay(self.sock.dup(), self.latency, self.time_per_byte,
 
984
                           self._sleep)
 
985
 
 
986
    def recv(self, *args):
 
987
        data = self.sock.recv(*args)
 
988
        if data and self.new_roundtrip:
 
989
            self.new_roundtrip = False
 
990
            self.sleep(self.latency)
 
991
        self.sleep(len(data) * self.time_per_byte)
 
992
        return data
 
993
 
 
994
    def sendall(self, data, flags=0):
 
995
        if not self.new_roundtrip:
 
996
            self.new_roundtrip = True
 
997
            self.sleep(self.latency)
 
998
        self.sleep(len(data) * self.time_per_byte)
 
999
        return self.sock.sendall(data, flags)
 
1000
 
 
1001
    def send(self, data, flags=0):
 
1002
        if not self.new_roundtrip:
 
1003
            self.new_roundtrip = True
 
1004
            self.sleep(self.latency)
 
1005
        bytes_sent = self.sock.send(data, flags)
 
1006
        self.sleep(bytes_sent * self.time_per_byte)
 
1007
        return bytes_sent
 
1008
 
 
1009
 
 
1010
class SFTPServer(Server):
 
1011
    """Common code for SFTP server facilities."""
 
1012
 
 
1013
    def __init__(self, server_interface=StubServer):
 
1014
        self._original_vendor = None
 
1015
        self._homedir = None
 
1016
        self._server_homedir = None
 
1017
        self._listener = None
 
1018
        self._root = None
 
1019
        self._vendor = ssh.ParamikoVendor()
 
1020
        self._server_interface = server_interface
 
1021
        # sftp server logs
 
1022
        self.logs = []
 
1023
        self.add_latency = 0
 
1024
 
 
1025
    def _get_sftp_url(self, path):
 
1026
        """Calculate an sftp url to this server for path."""
 
1027
        return 'sftp://foo:bar@localhost:%d/%s' % (self._listener.port, path)
 
1028
 
 
1029
    def log(self, message):
 
1030
        """StubServer uses this to log when a new server is created."""
 
1031
        self.logs.append(message)
 
1032
 
 
1033
    def _run_server_entry(self, sock):
 
1034
        """Entry point for all implementations of _run_server.
 
1035
        
 
1036
        If self.add_latency is > 0.000001 then sock is given a latency adding
 
1037
        decorator.
 
1038
        """
 
1039
        if self.add_latency > 0.000001:
 
1040
            sock = SocketDelay(sock, self.add_latency)
 
1041
        return self._run_server(sock)
 
1042
 
 
1043
    def _run_server(self, s):
 
1044
        ssh_server = paramiko.Transport(s)
 
1045
        key_file = pathjoin(self._homedir, 'test_rsa.key')
 
1046
        f = open(key_file, 'w')
 
1047
        f.write(STUB_SERVER_KEY)
 
1048
        f.close()
 
1049
        host_key = paramiko.RSAKey.from_private_key_file(key_file)
 
1050
        ssh_server.add_server_key(host_key)
 
1051
        server = self._server_interface(self)
 
1052
        ssh_server.set_subsystem_handler('sftp', paramiko.SFTPServer,
 
1053
                                         StubSFTPServer, root=self._root,
 
1054
                                         home=self._server_homedir)
 
1055
        event = threading.Event()
 
1056
        ssh_server.start_server(event, server)
 
1057
        event.wait(5.0)
 
1058
    
 
1059
    def setUp(self, backing_server=None):
 
1060
        # XXX: TODO: make sftpserver back onto backing_server rather than local
 
1061
        # disk.
 
1062
        if not (backing_server is None or
 
1063
                isinstance(backing_server, local.LocalURLServer)):
 
1064
            raise AssertionError(
 
1065
                "backing_server should not be %r, because this can only serve the "
 
1066
                "local current working directory." % (backing_server,))
 
1067
        self._original_vendor = ssh._ssh_vendor_manager._cached_ssh_vendor
 
1068
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._vendor
 
1069
        if sys.platform == 'win32':
 
1070
            # Win32 needs to use the UNICODE api
 
1071
            self._homedir = getcwd()
 
1072
        else:
 
1073
            # But Linux SFTP servers should just deal in bytestreams
 
1074
            self._homedir = os.getcwd()
 
1075
        if self._server_homedir is None:
 
1076
            self._server_homedir = self._homedir
 
1077
        self._root = '/'
 
1078
        if sys.platform == 'win32':
 
1079
            self._root = ''
 
1080
        self._listener = SocketListener(self._run_server_entry)
 
1081
        self._listener.setDaemon(True)
 
1082
        self._listener.start()
 
1083
 
 
1084
    def tearDown(self):
 
1085
        """See bzrlib.transport.Server.tearDown."""
 
1086
        self._listener.stop()
 
1087
        ssh._ssh_vendor_manager._cached_ssh_vendor = self._original_vendor
 
1088
 
 
1089
    def get_bogus_url(self):
 
1090
        """See bzrlib.transport.Server.get_bogus_url."""
 
1091
        # this is chosen to try to prevent trouble with proxies, wierd dns, etc
 
1092
        # we bind a random socket, so that we get a guaranteed unused port
 
1093
        # we just never listen on that port
 
1094
        s = socket.socket()
 
1095
        s.bind(('localhost', 0))
 
1096
        return 'sftp://%s:%s/' % s.getsockname()
 
1097
 
 
1098
 
 
1099
class SFTPFullAbsoluteServer(SFTPServer):
 
1100
    """A test server for sftp transports, using absolute urls and ssh."""
 
1101
 
 
1102
    def get_url(self):
 
1103
        """See bzrlib.transport.Server.get_url."""
 
1104
        homedir = self._homedir
 
1105
        if sys.platform != 'win32':
 
1106
            # Remove the initial '/' on all platforms but win32
 
1107
            homedir = homedir[1:]
 
1108
        return self._get_sftp_url(urlutils.escape(homedir))
 
1109
 
 
1110
 
 
1111
class SFTPServerWithoutSSH(SFTPServer):
 
1112
    """An SFTP server that uses a simple TCP socket pair rather than SSH."""
 
1113
 
 
1114
    def __init__(self):
 
1115
        super(SFTPServerWithoutSSH, self).__init__()
 
1116
        self._vendor = ssh.LoopbackVendor()
 
1117
 
 
1118
    def _run_server(self, sock):
 
1119
        # Re-import these as locals, so that they're still accessible during
 
1120
        # interpreter shutdown (when all module globals get set to None, leading
 
1121
        # to confusing errors like "'NoneType' object has no attribute 'error'".
 
1122
        class FakeChannel(object):
 
1123
            def get_transport(self):
 
1124
                return self
 
1125
            def get_log_channel(self):
 
1126
                return 'paramiko'
 
1127
            def get_name(self):
 
1128
                return '1'
 
1129
            def get_hexdump(self):
 
1130
                return False
 
1131
            def close(self):
 
1132
                pass
 
1133
 
 
1134
        server = paramiko.SFTPServer(
 
1135
            FakeChannel(), 'sftp', StubServer(self), StubSFTPServer,
 
1136
            root=self._root, home=self._server_homedir)
 
1137
        try:
 
1138
            server.start_subsystem(
 
1139
                'sftp', None, ssh.SocketAsChannelAdapter(sock))
 
1140
        except socket.error, e:
 
1141
            if (len(e.args) > 0) and (e.args[0] == errno.EPIPE):
 
1142
                # it's okay for the client to disconnect abruptly
 
1143
                # (bug in paramiko 1.6: it should absorb this exception)
 
1144
                pass
 
1145
            else:
 
1146
                raise
 
1147
        except Exception, e:
 
1148
            # This typically seems to happen during interpreter shutdown, so
 
1149
            # most of the useful ways to report this error are won't work.
 
1150
            # Writing the exception type, and then the text of the exception,
 
1151
            # seems to be the best we can do.
 
1152
            import sys
 
1153
            sys.stderr.write('\nEXCEPTION %r: ' % (e.__class__,))
 
1154
            sys.stderr.write('%s\n\n' % (e,))
 
1155
        server.finish_subsystem()
 
1156
 
 
1157
 
 
1158
class SFTPAbsoluteServer(SFTPServerWithoutSSH):
 
1159
    """A test server for sftp transports, using absolute urls."""
 
1160
 
 
1161
    def get_url(self):
 
1162
        """See bzrlib.transport.Server.get_url."""
 
1163
        homedir = self._homedir
 
1164
        if sys.platform != 'win32':
 
1165
            # Remove the initial '/' on all platforms but win32
 
1166
            homedir = homedir[1:]
 
1167
        return self._get_sftp_url(urlutils.escape(homedir))
 
1168
 
 
1169
 
 
1170
class SFTPHomeDirServer(SFTPServerWithoutSSH):
 
1171
    """A test server for sftp transports, using homedir relative urls."""
 
1172
 
 
1173
    def get_url(self):
 
1174
        """See bzrlib.transport.Server.get_url."""
 
1175
        return self._get_sftp_url("~/")
 
1176
 
 
1177
 
 
1178
class SFTPSiblingAbsoluteServer(SFTPAbsoluteServer):
 
1179
    """A test server for sftp transports where only absolute paths will work.
 
1180
 
 
1181
    It does this by serving from a deeply-nested directory that doesn't exist.
 
1182
    """
 
1183
 
 
1184
    def setUp(self, backing_server=None):
 
1185
        self._server_homedir = '/dev/noone/runs/tests/here'
 
1186
        super(SFTPSiblingAbsoluteServer, self).setUp(backing_server)
 
1187
 
907
1188
 
908
1189
def get_test_permutations():
909
1190
    """Return the permutations to be used in testing."""
910
 
    from bzrlib.tests import stub_sftp
911
 
    return [(SFTPTransport, stub_sftp.SFTPAbsoluteServer),
912
 
            (SFTPTransport, stub_sftp.SFTPHomeDirServer),
913
 
            (SFTPTransport, stub_sftp.SFTPSiblingAbsoluteServer),
 
1191
    return [(SFTPTransport, SFTPAbsoluteServer),
 
1192
            (SFTPTransport, SFTPHomeDirServer),
 
1193
            (SFTPTransport, SFTPSiblingAbsoluteServer),
914
1194
            ]