/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/ssh.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-15 11:53:48 UTC
  • mto: This revision was merged to the branch mainline in revision 6375.
  • Revision ID: jelmer@samba.org-20111215115348-murs91ipn8jbw6y0
Add tests for default_email behaviour.

Show diffs side-by-side

added added

removed removed

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