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()
266
274
register_ssh_vendor('loopback', LoopbackVendor())
269
class _ParamikoSSHConnection(object):
270
def __init__(self, channel):
271
self.channel = channel
273
def get_filelike_channels(self):
274
return self.channel.makefile('rb'), self.channel.makefile('wb')
277
return self.channel.close()
280
277
class ParamikoVendor(SSHVendor):
281
278
"""Vendor that uses paramiko."""
280
def _hexify(self, s):
281
return hexlify(s).upper()
283
283
def _connect(self, username, password, host, port):
284
284
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
293
293
self._raise_connection_error(host, port=port, orig_error=e)
295
295
server_key = t.get_remote_server_key()
296
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
296
server_key_hex = self._hexify(server_key.get_fingerprint())
297
297
keytype = server_key.get_name()
298
298
if host in SYSTEM_HOSTKEYS and keytype in SYSTEM_HOSTKEYS[host]:
299
299
our_server_key = SYSTEM_HOSTKEYS[host][keytype]
300
our_server_key_hex = paramiko.util.hexify(
301
our_server_key.get_fingerprint())
300
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
302
301
elif host in BZR_HOSTKEYS and keytype in BZR_HOSTKEYS[host]:
303
302
our_server_key = BZR_HOSTKEYS[host][keytype]
304
our_server_key_hex = paramiko.util.hexify(
305
our_server_key.get_fingerprint())
303
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
307
305
trace.warning('Adding %s host key for %s: %s'
308
306
% (keytype, host, server_key_hex))
345
342
self._raise_connection_error(host, port=port, orig_error=e,
346
343
msg='Unable to invoke remote bzr')
345
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
348
346
if paramiko is not None:
349
347
vendor = ParamikoVendor()
350
348
register_ssh_vendor('paramiko', vendor)
351
349
register_ssh_vendor('none', vendor)
352
350
register_default_ssh_vendor(vendor)
353
_sftp_connection_errors = (EOFError, paramiko.SSHException)
351
_ssh_connection_errors += (paramiko.SSHException,)
356
_sftp_connection_errors = (EOFError,)
359
355
class SubprocessVendor(SSHVendor):
360
356
"""Abstract base class for vendors that use pipes to a subprocess."""
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
363
def _connect(self, argv):
363
proc = subprocess.Popen(argv,
364
stdin=subprocess.PIPE,
365
stdout=subprocess.PIPE,
364
# Attempt to make a socketpair to use as stdin/stdout for the SSH
365
# subprocess. We prefer sockets to pipes because they support
366
# non-blocking short reads, allowing us to optimistically read 64k (or
369
my_sock, subproc_sock = socket.socketpair()
370
osutils.set_fd_cloexec(my_sock)
371
except (AttributeError, socket.error):
372
# This platform doesn't support socketpair(), so just use ordinary
374
stdin = stdout = subprocess.PIPE
375
my_sock, subproc_sock = None, None
377
stdin = stdout = subproc_sock
378
proc = subprocess.Popen(argv, stdin=stdin, stdout=stdout,
379
stderr=self._stderr_target,
366
380
**os_specific_subprocess_params())
367
return SSHSubprocess(proc)
381
if subproc_sock is not None:
383
return SSHSubprocessConnection(proc, sock=my_sock)
369
385
def connect_sftp(self, username, password, host, port):
372
388
subsystem='sftp')
373
389
sock = self._connect(argv)
374
390
return SFTPClient(SocketAsChannelAdapter(sock))
375
except _sftp_connection_errors, e:
376
self._raise_connection_error(host, port=port, orig_error=e)
377
except (OSError, IOError), e:
378
# If the machine is fast enough, ssh can actually exit
379
# before we try and send it the sftp request, which
380
# raises a Broken Pipe
381
if e.errno not in (errno.EPIPE,):
391
except _ssh_connection_errors, e:
383
392
self._raise_connection_error(host, port=port, orig_error=e)
385
394
def connect_ssh(self, username, password, host, port, command):
387
396
argv = self._get_vendor_specific_argv(username, host, port,
389
398
return self._connect(argv)
390
except (EOFError), e:
391
self._raise_connection_error(host, port=port, orig_error=e)
392
except (OSError, IOError), e:
393
# If the machine is fast enough, ssh can actually exit
394
# before we try and send it the sftp request, which
395
# raises a Broken Pipe
396
if e.errno not in (errno.EPIPE,):
399
except _ssh_connection_errors, e:
398
400
self._raise_connection_error(host, port=port, orig_error=e)
400
402
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
451
453
register_ssh_vendor('sshcorp', SSHCorpSubprocessVendor())
456
class LSHSubprocessVendor(SubprocessVendor):
457
"""SSH vendor that uses the 'lsh' executable from GNU"""
459
executable_path = 'lsh'
461
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
463
args = [self.executable_path]
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])
471
args.extend([host] + command)
474
register_ssh_vendor('lsh', LSHSubprocessVendor())
454
477
class PLinkSubprocessVendor(SubprocessVendor):
455
478
"""SSH vendor that uses the 'plink' executable from Putty."""
634
658
# Running it in a separate process group is not good because then it
635
659
# can't get non-echoed input of a password or passphrase.
636
660
# <https://launchpad.net/products/bzr/+bug/40508>
637
return {'preexec_fn': _ignore_sigint,
661
return {'preexec_fn': _ignore_signals,
638
662
'close_fds': True,
642
666
_subproc_weakrefs = set()
644
def _close_ssh_proc(proc):
645
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.
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).
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)
652
class SSHSubprocess(object):
653
"""A socket-like object that talks to an ssh subprocess via pipes."""
655
def __init__(self, proc):
687
# It's ok for the pipe to already be closed, or the process to
688
# already be finished.
692
class SSHConnection(object):
693
"""Abstract base class for SSH connections."""
695
def get_sock_or_pipes(self):
696
"""Returns a (kind, io_object) pair.
698
If kind == 'socket', then io_object is a socket.
700
If kind == 'pipes', then io_object is a pair of file-like objects
701
(read_from, write_to).
703
raise NotImplementedError(self.get_sock_or_pipes)
706
raise NotImplementedError(self.close)
709
class SSHSubprocessConnection(SSHConnection):
710
"""A connection to an ssh subprocess via pipes or a socket.
712
This class is also socket-like enough to be used with
713
SocketAsChannelAdapter (it has 'send' and 'recv' methods).
716
def __init__(self, proc, sock=None):
719
:param proc: a subprocess.Popen
720
:param sock: if proc.stdin/out is a socket from a socketpair, then sock
721
should bzrlib's half of that socketpair. If not passed, proc's
722
stdin/out is assumed to be ordinary pipes.
657
726
# Add a weakref to proc that will attempt to do the same as self.close
658
727
# to avoid leaving processes lingering indefinitely.
659
728
def terminate(ref):
660
729
_subproc_weakrefs.remove(ref)
661
_close_ssh_proc(proc)
730
_close_ssh_proc(proc, sock)
662
731
_subproc_weakrefs.add(weakref.ref(self, terminate))
664
733
def send(self, data):
665
return os.write(self.proc.stdin.fileno(), data)
734
if self._sock is not None:
735
return self._sock.send(data)
737
return os.write(self.proc.stdin.fileno(), data)
667
739
def recv(self, count):
668
return os.read(self.proc.stdout.fileno(), count)
671
_close_ssh_proc(self.proc)
673
def get_filelike_channels(self):
674
return (self.proc.stdout, self.proc.stdin)
740
if self._sock is not None:
741
return self._sock.recv(count)
743
return os.read(self.proc.stdout.fileno(), count)
746
_close_ssh_proc(self.proc, self._sock)
748
def get_sock_or_pipes(self):
749
if self._sock is not None:
750
return 'socket', self._sock
752
return 'pipes', (self.proc.stdout, self.proc.stdin)
755
class _ParamikoSSHConnection(SSHConnection):
756
"""An SSH connection via paramiko."""
758
def __init__(self, channel):
759
self.channel = channel
761
def get_sock_or_pipes(self):
762
return ('socket', self.channel)
765
return self.channel.close()