~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/ssh.py

(vila) Forbid more operations on ReadonlyTransportDecorator (Vincent Ladeuil)

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
17
17
 
18
18
"""Foundation SSH support for SFTP and smart server."""
19
19
 
 
20
from __future__ import absolute_import
 
21
 
20
22
import errno
21
23
import getpass
22
24
import logging
24
26
import socket
25
27
import subprocess
26
28
import sys
 
29
from binascii import hexlify
27
30
 
28
31
from bzrlib import (
29
32
    config,
126
129
        elif 'SSH Secure Shell' in version:
127
130
            trace.mutter('ssh implementation is SSH Corp.')
128
131
            vendor = SSHCorpSubprocessVendor()
 
132
        elif 'lsh' in version:
 
133
            trace.mutter('ssh implementation is GNU lsh.')
 
134
            vendor = LSHSubprocessVendor()
129
135
        # As plink user prompts are not handled currently, don't auto-detect
130
136
        # it by inspection below, but keep this vendor detection for if a path
131
137
        # is given in BZR_SSH. See https://bugs.launchpad.net/bugs/414743
132
138
        elif 'plink' in version and progname == 'plink':
133
139
            # Checking if "plink" was the executed argument as Windows
134
 
            # sometimes reports 'ssh -V' incorrectly with 'plink' in it's
 
140
            # sometimes reports 'ssh -V' incorrectly with 'plink' in its
135
141
            # version.  See https://bugs.launchpad.net/bzr/+bug/107155
136
142
            trace.mutter("ssh implementation is Putty's plink.")
137
143
            vendor = PLinkSubprocessVendor()
271
277
class ParamikoVendor(SSHVendor):
272
278
    """Vendor that uses paramiko."""
273
279
 
 
280
    def _hexify(self, s):
 
281
        return hexlify(s).upper()
 
282
 
274
283
    def _connect(self, username, password, host, port):
275
284
        global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
276
285
 
284
293
            self._raise_connection_error(host, port=port, orig_error=e)
285
294
 
286
295
        server_key = t.get_remote_server_key()
287
 
        server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
 
296
        server_key_hex = self._hexify(server_key.get_fingerprint())
288
297
        keytype = server_key.get_name()
289
298
        if host in SYSTEM_HOSTKEYS and keytype in SYSTEM_HOSTKEYS[host]:
290
299
            our_server_key = SYSTEM_HOSTKEYS[host][keytype]
291
 
            our_server_key_hex = paramiko.util.hexify(
292
 
                our_server_key.get_fingerprint())
 
300
            our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
293
301
        elif host in BZR_HOSTKEYS and keytype in BZR_HOSTKEYS[host]:
294
302
            our_server_key = BZR_HOSTKEYS[host][keytype]
295
 
            our_server_key_hex = paramiko.util.hexify(
296
 
                our_server_key.get_fingerprint())
 
303
            our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
297
304
        else:
298
305
            trace.warning('Adding %s host key for %s: %s'
299
306
                          % (keytype, host, server_key_hex))
303
310
            else:
304
311
                BZR_HOSTKEYS.setdefault(host, {})[keytype] = server_key
305
312
            our_server_key = server_key
306
 
            our_server_key_hex = paramiko.util.hexify(
307
 
                our_server_key.get_fingerprint())
 
313
            our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
308
314
            save_host_keys()
309
315
        if server_key != our_server_key:
310
316
            filename1 = os.path.expanduser('~/.ssh/known_hosts')
336
342
            self._raise_connection_error(host, port=port, orig_error=e,
337
343
                                         msg='Unable to invoke remote bzr')
338
344
 
 
345
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
339
346
if paramiko is not None:
340
347
    vendor = ParamikoVendor()
341
348
    register_ssh_vendor('paramiko', vendor)
342
349
    register_ssh_vendor('none', vendor)
343
350
    register_default_ssh_vendor(vendor)
344
 
    _sftp_connection_errors = (EOFError, paramiko.SSHException)
 
351
    _ssh_connection_errors += (paramiko.SSHException,)
345
352
    del vendor
346
 
else:
347
 
    _sftp_connection_errors = (EOFError,)
348
353
 
349
354
 
350
355
class SubprocessVendor(SSHVendor):
351
356
    """Abstract base class for vendors that use pipes to a subprocess."""
352
357
 
 
358
    # In general stderr should be inherited from the parent process so prompts
 
359
    # are visible on the terminal. This can be overriden to another file for
 
360
    # tests, but beware of using PIPE which may hang due to not being read.
 
361
    _stderr_target = None
 
362
 
353
363
    def _connect(self, argv):
354
364
        # Attempt to make a socketpair to use as stdin/stdout for the SSH
355
365
        # subprocess.  We prefer sockets to pipes because they support
357
367
        # whatever) chunks.
358
368
        try:
359
369
            my_sock, subproc_sock = socket.socketpair()
 
370
            osutils.set_fd_cloexec(my_sock)
360
371
        except (AttributeError, socket.error):
361
372
            # This platform doesn't support socketpair(), so just use ordinary
362
373
            # pipes instead.
363
374
            stdin = stdout = subprocess.PIPE
364
 
            sock = None
 
375
            my_sock, subproc_sock = None, None
365
376
        else:
366
377
            stdin = stdout = subproc_sock
367
 
            sock = my_sock
368
378
        proc = subprocess.Popen(argv, stdin=stdin, stdout=stdout,
 
379
                                stderr=self._stderr_target,
369
380
                                **os_specific_subprocess_params())
370
 
        return SSHSubprocessConnection(proc, sock=sock)
 
381
        if subproc_sock is not None:
 
382
            subproc_sock.close()
 
383
        return SSHSubprocessConnection(proc, sock=my_sock)
371
384
 
372
385
    def connect_sftp(self, username, password, host, port):
373
386
        try:
375
388
                                                  subsystem='sftp')
376
389
            sock = self._connect(argv)
377
390
            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
 
391
        except _ssh_connection_errors, e:
386
392
            self._raise_connection_error(host, port=port, orig_error=e)
387
393
 
388
394
    def connect_ssh(self, username, password, host, port, command):
390
396
            argv = self._get_vendor_specific_argv(username, host, port,
391
397
                                                  command=command)
392
398
            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
 
399
        except _ssh_connection_errors, e:
401
400
            self._raise_connection_error(host, port=port, orig_error=e)
402
401
 
403
402
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
418
417
                                  command=None):
419
418
        args = [self.executable_path,
420
419
                '-oForwardX11=no', '-oForwardAgent=no',
421
 
                '-oClearAllForwardings=yes', '-oProtocol=2',
 
420
                '-oClearAllForwardings=yes',
422
421
                '-oNoHostAuthenticationForLocalhost=yes']
423
422
        if port is not None:
424
423
            args.extend(['-p', str(port)])
454
453
register_ssh_vendor('sshcorp', SSHCorpSubprocessVendor())
455
454
 
456
455
 
 
456
class LSHSubprocessVendor(SubprocessVendor):
 
457
    """SSH vendor that uses the 'lsh' executable from GNU"""
 
458
 
 
459
    executable_path = 'lsh'
 
460
 
 
461
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
 
462
                                  command=None):
 
463
        args = [self.executable_path]
 
464
        if port is not None:
 
465
            args.extend(['-p', str(port)])
 
466
        if username is not None:
 
467
            args.extend(['-l', username])
 
468
        if subsystem is not None:
 
469
            args.extend(['--subsystem', subsystem, host])
 
470
        else:
 
471
            args.extend([host] + command)
 
472
        return args
 
473
 
 
474
register_ssh_vendor('lsh', LSHSubprocessVendor())
 
475
 
 
476
 
457
477
class PLinkSubprocessVendor(SubprocessVendor):
458
478
    """SSH vendor that uses the 'plink' executable from Putty."""
459
479
 
486
506
        agent = paramiko.Agent()
487
507
        for key in agent.get_keys():
488
508
            trace.mutter('Trying SSH agent key %s'
489
 
                         % paramiko.util.hexify(key.get_fingerprint()))
 
509
                         % self._hexify(key.get_fingerprint()))
490
510
            try:
491
511
                paramiko_transport.auth_publickey(username, key)
492
512
                return
562
582
        return True
563
583
    except paramiko.PasswordRequiredException:
564
584
        password = ui.ui_factory.get_password(
565
 
            prompt='SSH %(filename)s password', filename=filename)
 
585
            prompt=u'SSH %(filename)s password',
 
586
            filename=filename.decode(osutils._fs_enc))
566
587
        try:
567
588
            key = pkey_class.from_private_key_file(filename, password)
568
589
            paramiko_transport.auth_publickey(username, key)
644
665
import weakref
645
666
_subproc_weakrefs = set()
646
667
 
647
 
def _close_ssh_proc(proc):
648
 
    for func in [proc.stdin.close, proc.stdout.close, proc.wait]:
 
668
def _close_ssh_proc(proc, sock):
 
669
    """Carefully close stdin/stdout and reap the SSH process.
 
670
 
 
671
    If the pipes are already closed and/or the process has already been
 
672
    wait()ed on, that's ok, and no error is raised.  The goal is to do our best
 
673
    to clean up (whether or not a clean up was already tried).
 
674
    """
 
675
    funcs = []
 
676
    for closeable in (proc.stdin, proc.stdout, sock):
 
677
        # We expect that either proc (a subprocess.Popen) will have stdin and
 
678
        # stdout streams to close, or that we will have been passed a socket to
 
679
        # close, with the option not in use being None.
 
680
        if closeable is not None:
 
681
            funcs.append(closeable.close)
 
682
    funcs.append(proc.wait)
 
683
    for func in funcs:
649
684
        try:
650
685
            func()
651
686
        except OSError:
652
 
            pass
 
687
            # It's ok for the pipe to already be closed, or the process to
 
688
            # already be finished.
 
689
            continue
653
690
 
654
691
 
655
692
class SSHConnection(object):
690
727
        # to avoid leaving processes lingering indefinitely.
691
728
        def terminate(ref):
692
729
            _subproc_weakrefs.remove(ref)
693
 
            _close_ssh_proc(proc)
 
730
            _close_ssh_proc(proc, sock)
694
731
        _subproc_weakrefs.add(weakref.ref(self, terminate))
695
732
 
696
733
    def send(self, data):
706
743
            return os.read(self.proc.stdout.fileno(), count)
707
744
 
708
745
    def close(self):
709
 
        _close_ssh_proc(self.proc)
 
746
        _close_ssh_proc(self.proc, self._sock)
710
747
 
711
748
    def get_sock_or_pipes(self):
712
749
        if self._sock is not None: