~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/ssh.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-05-21 13:36:51 UTC
  • mfrom: (5243.2.1 readdir_cleanup)
  • Revision ID: pqm@pqm.ubuntu.com-20100521133651-p62dndo2giy5ls21
(lifeless) Some cleanups to the readdir pyrex code for a little efficiency
 and to avoid compile warnings. (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Robey Pointer <robey@lag.net>
 
1
# Copyright (C) 2006-2010 Robey Pointer <robey@lag.net>
2
2
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
126
126
        elif 'SSH Secure Shell' in version:
127
127
            trace.mutter('ssh implementation is SSH Corp.')
128
128
            vendor = SSHCorpSubprocessVendor()
129
 
        elif 'lsh' in version:
130
 
            trace.mutter('ssh implementation is GNU lsh.')
131
 
            vendor = LSHSubprocessVendor()
132
129
        # As plink user prompts are not handled currently, don't auto-detect
133
130
        # it by inspection below, but keep this vendor detection for if a path
134
131
        # is given in BZR_SSH. See https://bugs.launchpad.net/bugs/414743
135
132
        elif 'plink' in version and progname == 'plink':
136
133
            # Checking if "plink" was the executed argument as Windows
137
 
            # sometimes reports 'ssh -V' incorrectly with 'plink' in its
 
134
            # sometimes reports 'ssh -V' incorrectly with 'plink' in it's
138
135
            # version.  See https://bugs.launchpad.net/bzr/+bug/107155
139
136
            trace.mutter("ssh implementation is Putty's plink.")
140
137
            vendor = PLinkSubprocessVendor()
242
239
    def connect_ssh(self, username, password, host, port, command):
243
240
        """Make an SSH connection.
244
241
 
245
 
        :returns: an SSHConnection.
 
242
        :returns: something with a `close` method, and a `get_filelike_channels`
 
243
            method that returns a pair of (read, write) filelike objects.
246
244
        """
247
245
        raise NotImplementedError(self.connect_ssh)
248
246
 
271
269
register_ssh_vendor('loopback', LoopbackVendor())
272
270
 
273
271
 
 
272
class _ParamikoSSHConnection(object):
 
273
    def __init__(self, channel):
 
274
        self.channel = channel
 
275
 
 
276
    def get_filelike_channels(self):
 
277
        return self.channel.makefile('rb'), self.channel.makefile('wb')
 
278
 
 
279
    def close(self):
 
280
        return self.channel.close()
 
281
 
 
282
 
274
283
class ParamikoVendor(SSHVendor):
275
284
    """Vendor that uses paramiko."""
276
285
 
339
348
            self._raise_connection_error(host, port=port, orig_error=e,
340
349
                                         msg='Unable to invoke remote bzr')
341
350
 
342
 
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
343
351
if paramiko is not None:
344
352
    vendor = ParamikoVendor()
345
353
    register_ssh_vendor('paramiko', vendor)
346
354
    register_ssh_vendor('none', vendor)
347
355
    register_default_ssh_vendor(vendor)
348
 
    _ssh_connection_errors += (paramiko.SSHException,)
 
356
    _sftp_connection_errors = (EOFError, paramiko.SSHException)
349
357
    del vendor
 
358
else:
 
359
    _sftp_connection_errors = (EOFError,)
350
360
 
351
361
 
352
362
class SubprocessVendor(SSHVendor):
353
363
    """Abstract base class for vendors that use pipes to a subprocess."""
354
364
 
355
365
    def _connect(self, argv):
356
 
        # Attempt to make a socketpair to use as stdin/stdout for the SSH
357
 
        # subprocess.  We prefer sockets to pipes because they support
358
 
        # non-blocking short reads, allowing us to optimistically read 64k (or
359
 
        # whatever) chunks.
360
 
        try:
361
 
            my_sock, subproc_sock = socket.socketpair()
362
 
            osutils.set_fd_cloexec(my_sock)
363
 
        except (AttributeError, socket.error):
364
 
            # This platform doesn't support socketpair(), so just use ordinary
365
 
            # pipes instead.
366
 
            stdin = stdout = subprocess.PIPE
367
 
            my_sock, subproc_sock = None, None
368
 
        else:
369
 
            stdin = stdout = subproc_sock
370
 
        proc = subprocess.Popen(argv, stdin=stdin, stdout=stdout,
 
366
        proc = subprocess.Popen(argv,
 
367
                                stdin=subprocess.PIPE,
 
368
                                stdout=subprocess.PIPE,
371
369
                                **os_specific_subprocess_params())
372
 
        if subproc_sock is not None:
373
 
            subproc_sock.close()
374
 
        return SSHSubprocessConnection(proc, sock=my_sock)
 
370
        return SSHSubprocess(proc)
375
371
 
376
372
    def connect_sftp(self, username, password, host, port):
377
373
        try:
379
375
                                                  subsystem='sftp')
380
376
            sock = self._connect(argv)
381
377
            return SFTPClient(SocketAsChannelAdapter(sock))
382
 
        except _ssh_connection_errors, e:
 
378
        except _sftp_connection_errors, e:
 
379
            self._raise_connection_error(host, port=port, orig_error=e)
 
380
        except (OSError, IOError), e:
 
381
            # If the machine is fast enough, ssh can actually exit
 
382
            # before we try and send it the sftp request, which
 
383
            # raises a Broken Pipe
 
384
            if e.errno not in (errno.EPIPE,):
 
385
                raise
383
386
            self._raise_connection_error(host, port=port, orig_error=e)
384
387
 
385
388
    def connect_ssh(self, username, password, host, port, command):
387
390
            argv = self._get_vendor_specific_argv(username, host, port,
388
391
                                                  command=command)
389
392
            return self._connect(argv)
390
 
        except _ssh_connection_errors, e:
 
393
        except (EOFError), e:
 
394
            self._raise_connection_error(host, port=port, orig_error=e)
 
395
        except (OSError, IOError), e:
 
396
            # If the machine is fast enough, ssh can actually exit
 
397
            # before we try and send it the sftp request, which
 
398
            # raises a Broken Pipe
 
399
            if e.errno not in (errno.EPIPE,):
 
400
                raise
391
401
            self._raise_connection_error(host, port=port, orig_error=e)
392
402
 
393
403
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
408
418
                                  command=None):
409
419
        args = [self.executable_path,
410
420
                '-oForwardX11=no', '-oForwardAgent=no',
411
 
                '-oClearAllForwardings=yes',
 
421
                '-oClearAllForwardings=yes', '-oProtocol=2',
412
422
                '-oNoHostAuthenticationForLocalhost=yes']
413
423
        if port is not None:
414
424
            args.extend(['-p', str(port)])
444
454
register_ssh_vendor('sshcorp', SSHCorpSubprocessVendor())
445
455
 
446
456
 
447
 
class LSHSubprocessVendor(SubprocessVendor):
448
 
    """SSH vendor that uses the 'lsh' executable from GNU"""
449
 
 
450
 
    executable_path = 'lsh'
451
 
 
452
 
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
453
 
                                  command=None):
454
 
        args = [self.executable_path]
455
 
        if port is not None:
456
 
            args.extend(['-p', str(port)])
457
 
        if username is not None:
458
 
            args.extend(['-l', username])
459
 
        if subsystem is not None:
460
 
            args.extend(['--subsystem', subsystem, host])
461
 
        else:
462
 
            args.extend([host] + command)
463
 
        return args
464
 
 
465
 
register_ssh_vendor('lsh', LSHSubprocessVendor())
466
 
 
467
 
 
468
457
class PLinkSubprocessVendor(SubprocessVendor):
469
458
    """SSH vendor that uses the 'plink' executable from Putty."""
470
459
 
573
562
        return True
574
563
    except paramiko.PasswordRequiredException:
575
564
        password = ui.ui_factory.get_password(
576
 
            prompt=u'SSH %(filename)s password',
577
 
            filename=filename.decode(osutils._fs_enc))
 
565
            prompt='SSH %(filename)s password', filename=filename)
578
566
        try:
579
567
            key = pkey_class.from_private_key_file(filename, password)
580
568
            paramiko_transport.auth_publickey(username, key)
656
644
import weakref
657
645
_subproc_weakrefs = set()
658
646
 
659
 
def _close_ssh_proc(proc, sock):
660
 
    """Carefully close stdin/stdout and reap the SSH process.
661
 
 
662
 
    If the pipes are already closed and/or the process has already been
663
 
    wait()ed on, that's ok, and no error is raised.  The goal is to do our best
664
 
    to clean up (whether or not a clean up was already tried).
665
 
    """
666
 
    funcs = []
667
 
    for closeable in (proc.stdin, proc.stdout, sock):
668
 
        # We expect that either proc (a subprocess.Popen) will have stdin and
669
 
        # stdout streams to close, or that we will have been passed a socket to
670
 
        # close, with the option not in use being None.
671
 
        if closeable is not None:
672
 
            funcs.append(closeable.close)
673
 
    funcs.append(proc.wait)
674
 
    for func in funcs:
 
647
def _close_ssh_proc(proc):
 
648
    for func in [proc.stdin.close, proc.stdout.close, proc.wait]:
675
649
        try:
676
650
            func()
677
651
        except OSError:
678
 
            # It's ok for the pipe to already be closed, or the process to
679
 
            # already be finished.
680
 
            continue
681
 
 
682
 
 
683
 
class SSHConnection(object):
684
 
    """Abstract base class for SSH connections."""
685
 
 
686
 
    def get_sock_or_pipes(self):
687
 
        """Returns a (kind, io_object) pair.
688
 
 
689
 
        If kind == 'socket', then io_object is a socket.
690
 
 
691
 
        If kind == 'pipes', then io_object is a pair of file-like objects
692
 
        (read_from, write_to).
693
 
        """
694
 
        raise NotImplementedError(self.get_sock_or_pipes)
695
 
 
696
 
    def close(self):
697
 
        raise NotImplementedError(self.close)
698
 
 
699
 
 
700
 
class SSHSubprocessConnection(SSHConnection):
701
 
    """A connection to an ssh subprocess via pipes or a socket.
702
 
 
703
 
    This class is also socket-like enough to be used with
704
 
    SocketAsChannelAdapter (it has 'send' and 'recv' methods).
705
 
    """
706
 
 
707
 
    def __init__(self, proc, sock=None):
708
 
        """Constructor.
709
 
 
710
 
        :param proc: a subprocess.Popen
711
 
        :param sock: if proc.stdin/out is a socket from a socketpair, then sock
712
 
            should bzrlib's half of that socketpair.  If not passed, proc's
713
 
            stdin/out is assumed to be ordinary pipes.
714
 
        """
 
652
            pass
 
653
 
 
654
 
 
655
class SSHSubprocess(object):
 
656
    """A socket-like object that talks to an ssh subprocess via pipes."""
 
657
 
 
658
    def __init__(self, proc):
715
659
        self.proc = proc
716
 
        self._sock = sock
717
660
        # Add a weakref to proc that will attempt to do the same as self.close
718
661
        # to avoid leaving processes lingering indefinitely.
719
662
        def terminate(ref):
720
663
            _subproc_weakrefs.remove(ref)
721
 
            _close_ssh_proc(proc, sock)
 
664
            _close_ssh_proc(proc)
722
665
        _subproc_weakrefs.add(weakref.ref(self, terminate))
723
666
 
724
667
    def send(self, data):
725
 
        if self._sock is not None:
726
 
            return self._sock.send(data)
727
 
        else:
728
 
            return os.write(self.proc.stdin.fileno(), data)
 
668
        return os.write(self.proc.stdin.fileno(), data)
729
669
 
730
670
    def recv(self, count):
731
 
        if self._sock is not None:
732
 
            return self._sock.recv(count)
733
 
        else:
734
 
            return os.read(self.proc.stdout.fileno(), count)
735
 
 
736
 
    def close(self):
737
 
        _close_ssh_proc(self.proc, self._sock)
738
 
 
739
 
    def get_sock_or_pipes(self):
740
 
        if self._sock is not None:
741
 
            return 'socket', self._sock
742
 
        else:
743
 
            return 'pipes', (self.proc.stdout, self.proc.stdin)
744
 
 
745
 
 
746
 
class _ParamikoSSHConnection(SSHConnection):
747
 
    """An SSH connection via paramiko."""
748
 
 
749
 
    def __init__(self, channel):
750
 
        self.channel = channel
751
 
 
752
 
    def get_sock_or_pipes(self):
753
 
        return ('socket', self.channel)
754
 
 
755
 
    def close(self):
756
 
        return self.channel.close()
757
 
 
 
671
        return os.read(self.proc.stdout.fileno(), count)
 
672
 
 
673
    def close(self):
 
674
        _close_ssh_proc(self.proc)
 
675
 
 
676
    def get_filelike_channels(self):
 
677
        return (self.proc.stdout, self.proc.stdin)
758
678