/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 breezy/transport/sftp.py

  • Committer: Jelmer Vernooij
  • Date: 2019-03-04 00:16:27 UTC
  • mfrom: (7293 work)
  • mto: This revision was merged to the branch mainline in revision 7318.
  • Revision ID: jelmer@jelmer.uk-20190304001627-v6u7o6pf97tukhek
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
42
42
    urlutils,
43
43
    )
44
44
from ..errors import (FileExists,
45
 
                           NoSuchFile,
46
 
                           TransportError,
47
 
                           LockError,
48
 
                           PathError,
49
 
                           ParamikoNotPresent,
50
 
                           )
 
45
                      NoSuchFile,
 
46
                      TransportError,
 
47
                      LockError,
 
48
                      PathError,
 
49
                      ParamikoNotPresent,
 
50
                      )
51
51
from ..osutils import fancy_rename
52
52
from ..sixish import (
53
53
    zip,
69
69
# /var/lib/python-support/python2.5/paramiko/message.py:226: DeprecationWarning: integer argument expected, got float
70
70
#  self.packet.write(struct.pack('>I', n))
71
71
warnings.filterwarnings('ignore',
72
 
        'integer argument expected, got float',
73
 
        category=DeprecationWarning,
74
 
        module='paramiko.message')
 
72
                        'integer argument expected, got float',
 
73
                        category=DeprecationWarning,
 
74
                        module='paramiko.message')
75
75
 
76
76
try:
77
77
    import paramiko
193
193
        # as possible, so we don't issues requests <32kB
194
194
        sorted_offsets = sorted(self.original_offsets)
195
195
        coalesced = list(ConnectedTransport._coalesce_offsets(sorted_offsets,
196
 
                                                        limit=0, fudge_factor=0))
 
196
                                                              limit=0, fudge_factor=0))
197
197
        requests = []
198
198
        for c_offset in coalesced:
199
199
            start = c_offset.start
207
207
                start += next_size
208
208
        if 'sftp' in debug.debug_flags:
209
209
            mutter('SFTP.readv(%s) %s offsets => %s coalesced => %s requests',
210
 
                self.relpath, len(sorted_offsets), len(coalesced),
211
 
                len(requests))
 
210
                   self.relpath, len(sorted_offsets), len(coalesced),
 
211
                   len(requests))
212
212
        return requests
213
213
 
214
214
    def request_and_yield_offsets(self, fp):
241
241
            if data is None:
242
242
                if cur_coalesced is not None:
243
243
                    raise errors.ShortReadvError(self.relpath,
244
 
                        start, length, len(data))
 
244
                                                 start, length, len(data))
245
245
            if len(data) != length:
246
246
                raise errors.ShortReadvError(self.relpath,
247
 
                    start, length, len(data))
 
247
                                             start, length, len(data))
248
248
            self._report_activity(length, 'read')
249
249
            if last_end is None:
250
250
                # This is the first request, just buffer it
317
317
        if data_chunks:
318
318
            if 'sftp' in debug.debug_flags:
319
319
                mutter('SFTP readv left with %d out-of-order bytes',
320
 
                    sum(len(x[1]) for x in data_chunks))
 
320
                       sum(len(x[1]) for x in data_chunks))
321
321
            # We've processed all the readv data, at this point, anything we
322
322
            # couldn't process is in data_chunks. This doesn't happen often, so
323
323
            # this code path isn't optimized
343
343
                    data = ''
344
344
                if len(data) != cur_size:
345
345
                    raise AssertionError('We must have miscalulated.'
346
 
                        ' We expected %d bytes, but only found %d'
347
 
                        % (cur_size, len(data)))
 
346
                                         ' We expected %d bytes, but only found %d'
 
347
                                         % (cur_size, len(data)))
348
348
                yield cur_offset, data
349
349
                try:
350
350
                    cur_offset, cur_size = next(offset_iter)
411
411
        if user is None:
412
412
            auth = config.AuthenticationConfig()
413
413
            user = auth.get_user('ssh', self._parsed_url.host,
414
 
                self._parsed_url.port)
 
414
                                 self._parsed_url.port)
415
415
        connection = vendor.connect_sftp(self._parsed_url.user, password,
416
 
            self._parsed_url.host, self._parsed_url.port)
 
416
                                         self._parsed_url.host, self._parsed_url.port)
417
417
        return connection, (user, password)
418
418
 
419
419
    def disconnect(self):
456
456
            return f
457
457
        except (IOError, paramiko.SSHException) as e:
458
458
            self._translate_io_exception(e, path, ': error retrieving',
459
 
                failure_exc=errors.ReadError)
 
459
                                         failure_exc=errors.ReadError)
460
460
 
461
461
    def get_bytes(self, relpath):
462
462
        # reimplement this here so that we can report how many bytes came back
517
517
    def _put(self, abspath, f, mode=None):
518
518
        """Helper function so both put() and copy_abspaths can reuse the code"""
519
519
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
520
 
                        os.getpid(), random.randint(0, 0x7FFFFFFF))
 
520
                                             os.getpid(), random.randint(0, 0x7FFFFFFF))
521
521
        fout = self._sftp_open_exclusive(tmp_abspath, mode=mode)
522
522
        closed = False
523
523
        try:
653
653
            st = self.stat(relpath)
654
654
            if stat.S_ISDIR(st.st_mode):
655
655
                for i, basename in enumerate(self.list_dir(relpath)):
656
 
                    queue.insert(i, relpath+'/'+basename)
 
656
                    queue.insert(i, relpath + '/' + basename)
657
657
            else:
658
658
                yield relpath
659
659
 
673
673
                # the sgid bit is set, report a warning to the user
674
674
                # with the umask fix.
675
675
                stat = self._get_sftp().lstat(abspath)
676
 
                mode = mode & 0o777 # can't set special bits anyway
 
676
                mode = mode & 0o777  # can't set special bits anyway
677
677
                if mode != stat.st_mode & 0o777:
678
678
                    if stat.st_mode & 0o6000:
679
679
                        warning('About to chmod %s over sftp, which will result'
684
684
                    self._get_sftp().chmod(abspath, mode=mode)
685
685
        except (paramiko.SSHException, IOError) as e:
686
686
            self._translate_io_exception(e, abspath, ': unable to mkdir',
687
 
                failure_exc=FileExists)
 
687
                                         failure_exc=FileExists)
688
688
 
689
689
    def mkdir(self, relpath, mode=None):
690
690
        """Create a directory at the given path."""
730
730
        self._translate_error(e, path, raise_generic=False)
731
731
        if getattr(e, 'args', None) is not None:
732
732
            if (e.args == ('No such file or directory',) or
733
 
                e.args == ('No such file',)):
 
733
                    e.args == ('No such file',)):
734
734
                raise NoSuchFile(path, str(e) + more_info)
735
735
            if (e.args == ('mkdir failed',) or
736
 
                e.args[0].startswith('syserr: File exists')):
 
736
                    e.args[0].startswith('syserr: File exists')):
737
737
                raise FileExists(path, str(e) + more_info)
738
738
            # strange but true, for the paramiko server.
739
739
            if (e.args == ('Failure',)):
742
742
            # '/srv/bazaar.launchpad.net/blah...: '
743
743
            # [Errno 39] Directory not empty',)
744
744
            if (e.args[0].startswith('Directory not empty: ')
745
 
                or getattr(e, 'errno', None) == errno.ENOTEMPTY):
 
745
                    or getattr(e, 'errno', None) == errno.ENOTEMPTY):
746
746
                raise errors.DirectoryNotEmpty(path, str(e))
747
747
            if e.args == ('Operation unsupported',):
748
748
                raise errors.TransportNotPossible()
771
771
        """Rename without special overwriting"""
772
772
        try:
773
773
            self._get_sftp().rename(self._remote_path(rel_from),
774
 
                              self._remote_path(rel_to))
 
774
                                    self._remote_path(rel_to))
775
775
        except (IOError, paramiko.SSHException) as e:
776
776
            self._translate_io_exception(e, rel_from,
777
 
                    ': unable to rename to %r' % (rel_to))
 
777
                                         ': unable to rename to %r' % (rel_to))
778
778
 
779
779
    def _rename_and_overwrite(self, abs_from, abs_to):
780
780
        """Do a fancy rename on the remote server.
849
849
        """See Transport.readlink."""
850
850
        path = self._remote_path(relpath)
851
851
        try:
852
 
            return self._get_sftp().readlink(path)
 
852
            return self._get_sftp().readlink(self._remote_path(path))
853
853
        except (IOError, paramiko.SSHException) as e:
854
854
            self._translate_io_exception(e, path, ': unable to readlink')
855
855
 
857
857
        """See Transport.symlink."""
858
858
        try:
859
859
            conn = self._get_sftp()
860
 
            sftp_retval = conn.symlink(source, link_name)
 
860
            sftp_retval = conn.symlink(source, self._remote_path(link_name))
861
861
        except (IOError, paramiko.SSHException) as e:
862
862
            self._translate_io_exception(e, link_name,
863
863
                                         ': unable to create symlink to %r' % (source))
871
871
        class BogusLock(object):
872
872
            def __init__(self, path):
873
873
                self.path = path
 
874
 
874
875
            def unlock(self):
875
876
                pass
 
877
 
876
878
            def __exit__(self, exc_type, exc_val, exc_tb):
877
879
                return False
 
880
 
878
881
            def __enter__(self):
879
882
                pass
880
883
        return BogusLock(relpath)
916
919
        if mode is not None:
917
920
            attr.st_mode = mode
918
921
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
919
 
                | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
 
922
                 | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
920
923
        try:
921
924
            t, msg = self._get_sftp()._request(CMD_OPEN, path, omode, attr)
922
925
            if t != CMD_HANDLE:
925
928
            return SFTPFile(self._get_sftp(), handle, 'wb', -1)
926
929
        except (paramiko.SSHException, IOError) as e:
927
930
            self._translate_io_exception(e, abspath, ': unable to open',
928
 
                failure_exc=FileExists)
 
931
                                         failure_exc=FileExists)
929
932
 
930
933
    def _can_roundtrip_unix_modebits(self):
931
934
        if sys.platform == 'win32':