1
# Copyright (C) 2006-2010 Robey Pointer <robey@lag.net>
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
2
2
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
4
4
# This program is free software; you can redistribute it and/or modify
131
131
# is given in BZR_SSH. See https://bugs.launchpad.net/bugs/414743
132
132
elif 'plink' in version and progname == 'plink':
133
133
# Checking if "plink" was the executed argument as Windows
134
# sometimes reports 'ssh -V' incorrectly with 'plink' in its
134
# sometimes reports 'ssh -V' incorrectly with 'plink' in it's
135
135
# version. See https://bugs.launchpad.net/bzr/+bug/107155
136
136
trace.mutter("ssh implementation is Putty's plink.")
137
137
vendor = PLinkSubprocessVendor()
173
173
register_ssh_vendor = _ssh_vendor_manager.register_vendor
176
def _ignore_signals():
176
def _ignore_sigint():
177
177
# TODO: This should possibly ignore SIGHUP as well, but bzr currently
178
178
# doesn't handle it itself.
179
179
# <https://launchpad.net/products/bzr/+bug/41433/+index>
181
181
signal.signal(signal.SIGINT, signal.SIG_IGN)
182
# GZ 2010-02-19: Perhaps make this check if breakin is installed instead
183
if signal.getsignal(signal.SIGQUIT) != signal.SIG_DFL:
184
signal.signal(signal.SIGQUIT, signal.SIG_IGN)
187
184
class SocketAsChannelAdapter(object):
239
236
def connect_ssh(self, username, password, host, port, command):
240
237
"""Make an SSH connection.
242
:returns: an SSHConnection.
239
:returns: something with a `close` method, and a `get_filelike_channels`
240
method that returns a pair of (read, write) filelike objects.
244
242
raise NotImplementedError(self.connect_ssh)
268
266
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()
271
280
class ParamikoVendor(SSHVendor):
272
281
"""Vendor that uses paramiko."""
336
345
self._raise_connection_error(host, port=port, orig_error=e,
337
346
msg='Unable to invoke remote bzr')
339
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
340
348
if paramiko is not None:
341
349
vendor = ParamikoVendor()
342
350
register_ssh_vendor('paramiko', vendor)
343
351
register_ssh_vendor('none', vendor)
344
352
register_default_ssh_vendor(vendor)
345
_ssh_connection_errors += (paramiko.SSHException,)
353
_sftp_connection_errors = (EOFError, paramiko.SSHException)
356
_sftp_connection_errors = (EOFError,)
349
359
class SubprocessVendor(SSHVendor):
350
360
"""Abstract base class for vendors that use pipes to a subprocess."""
352
362
def _connect(self, argv):
353
# Attempt to make a socketpair to use as stdin/stdout for the SSH
354
# subprocess. We prefer sockets to pipes because they support
355
# non-blocking short reads, allowing us to optimistically read 64k (or
358
my_sock, subproc_sock = socket.socketpair()
359
except (AttributeError, socket.error):
360
# This platform doesn't support socketpair(), so just use ordinary
362
stdin = stdout = subprocess.PIPE
365
stdin = stdout = subproc_sock
367
proc = subprocess.Popen(argv, stdin=stdin, stdout=stdout,
363
proc = subprocess.Popen(argv,
364
stdin=subprocess.PIPE,
365
stdout=subprocess.PIPE,
368
366
**os_specific_subprocess_params())
369
return SSHSubprocessConnection(proc, sock=sock)
367
return SSHSubprocess(proc)
371
369
def connect_sftp(self, username, password, host, port):
374
372
subsystem='sftp')
375
373
sock = self._connect(argv)
376
374
return SFTPClient(SocketAsChannelAdapter(sock))
377
except _ssh_connection_errors, e:
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,):
378
383
self._raise_connection_error(host, port=port, orig_error=e)
380
385
def connect_ssh(self, username, password, host, port, command):
382
387
argv = self._get_vendor_specific_argv(username, host, port,
384
389
return self._connect(argv)
385
except _ssh_connection_errors, e:
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,):
386
398
self._raise_connection_error(host, port=port, orig_error=e)
388
400
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
622
634
# Running it in a separate process group is not good because then it
623
635
# can't get non-echoed input of a password or passphrase.
624
636
# <https://launchpad.net/products/bzr/+bug/40508>
625
return {'preexec_fn': _ignore_signals,
637
return {'preexec_fn': _ignore_sigint,
626
638
'close_fds': True,
630
642
_subproc_weakrefs = set()
632
644
def _close_ssh_proc(proc):
633
"""Carefully close stdin/stdout and reap the SSH process.
635
If the pipes are already closed and/or the process has already been
636
wait()ed on, that's ok, and no error is raised. The goal is to do our best
637
to clean up (whether or not a clean up was already tried).
639
dotted_names = ['stdin.close', 'stdout.close', 'wait']
640
for dotted_name in dotted_names:
641
attrs = dotted_name.split('.')
645
obj = getattr(obj, attr)
646
except AttributeError:
647
# It's ok for proc.stdin or proc.stdout to be None.
645
for func in [proc.stdin.close, proc.stdout.close, proc.wait]:
652
# It's ok for the pipe to already be closed, or the process to
653
# already be finished.
657
class SSHConnection(object):
658
"""Abstract base class for SSH connections."""
660
def get_sock_or_pipes(self):
661
"""Returns a (kind, io_object) pair.
663
If kind == 'socket', then io_object is a socket.
665
If kind == 'pipes', then io_object is a pair of file-like objects
666
(read_from, write_to).
668
raise NotImplementedError(self.get_sock_or_pipes)
671
raise NotImplementedError(self.close)
674
class SSHSubprocessConnection(SSHConnection):
675
"""A connection to an ssh subprocess via pipes or a socket.
677
This class is also socket-like enough to be used with
678
SocketAsChannelAdapter (it has 'send' and 'recv' methods).
681
def __init__(self, proc, sock=None):
684
:param proc: a subprocess.Popen
685
:param sock: if proc.stdin/out is a socket from a socketpair, then sock
686
should bzrlib's half of that socketpair. If not passed, proc's
687
stdin/out is assumed to be ordinary pipes.
652
class SSHSubprocess(object):
653
"""A socket-like object that talks to an ssh subprocess via pipes."""
655
def __init__(self, proc):
691
657
# Add a weakref to proc that will attempt to do the same as self.close
692
658
# to avoid leaving processes lingering indefinitely.
693
659
def terminate(ref):
696
662
_subproc_weakrefs.add(weakref.ref(self, terminate))
698
664
def send(self, data):
699
if self._sock is not None:
700
return self._sock.send(data)
702
return os.write(self.proc.stdin.fileno(), data)
665
return os.write(self.proc.stdin.fileno(), data)
704
667
def recv(self, count):
705
if self._sock is not None:
706
return self._sock.recv(count)
708
return os.read(self.proc.stdout.fileno(), count)
668
return os.read(self.proc.stdout.fileno(), count)
711
671
_close_ssh_proc(self.proc)
713
def get_sock_or_pipes(self):
714
if self._sock is not None:
715
return 'socket', self._sock
717
return 'pipes', (self.proc.stdout, self.proc.stdin)
720
class _ParamikoSSHConnection(SSHConnection):
721
"""An SSH connection via paramiko."""
723
def __init__(self, channel):
724
self.channel = channel
726
def get_sock_or_pipes(self):
727
return ('socket', self.channel)
730
return self.channel.close()
673
def get_filelike_channels(self):
674
return (self.proc.stdout, self.proc.stdin)