~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/ssh.py

  • Committer: Robert Collins
  • Date: 2007-07-04 08:08:13 UTC
  • mfrom: (2572 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2587.
  • Revision ID: robertc@robertcollins.net-20070704080813-wzebx0r88fvwj5rq
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
2
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
27
27
from bzrlib.config import config_dir, ensure_config_dir_exists
28
28
from bzrlib.errors import (ConnectionError,
29
29
                           ParamikoNotPresent,
 
30
                           SocketConnectionError,
 
31
                           SSHVendorNotFound,
30
32
                           TransportError,
31
33
                           UnknownSSH,
32
34
                           )
38
40
try:
39
41
    import paramiko
40
42
except ImportError, e:
41
 
    raise ParamikoNotPresent(e)
 
43
    # If we have an ssh subprocess, we don't strictly need paramiko for all ssh
 
44
    # access
 
45
    paramiko = None
42
46
else:
43
47
    from paramiko.sftp_client import SFTPClient
44
48
 
55
59
# connect to an agent if we are on win32 and using Paramiko older than 1.6
56
60
_use_ssh_agent = (sys.platform != 'win32' or _paramiko_version >= (1, 6, 0))
57
61
 
58
 
_ssh_vendors = {}
59
 
 
60
 
def register_ssh_vendor(name, vendor):
61
 
    """Register SSH vendor."""
62
 
    _ssh_vendors[name] = vendor
63
 
 
64
 
    
65
 
_ssh_vendor = None
66
 
def _get_ssh_vendor():
67
 
    """Find out what version of SSH is on the system."""
68
 
    global _ssh_vendor
69
 
    if _ssh_vendor is not None:
70
 
        return _ssh_vendor
71
 
 
72
 
    if 'BZR_SSH' in os.environ:
73
 
        vendor_name = os.environ['BZR_SSH']
 
62
 
 
63
class SSHVendorManager(object):
 
64
    """Manager for manage SSH vendors."""
 
65
 
 
66
    # Note, although at first sign the class interface seems similar to
 
67
    # bzrlib.registry.Registry it is not possible/convenient to directly use
 
68
    # the Registry because the class just has "get()" interface instead of the
 
69
    # Registry's "get(key)".
 
70
 
 
71
    def __init__(self):
 
72
        self._ssh_vendors = {}
 
73
        self._cached_ssh_vendor = None
 
74
        self._default_ssh_vendor = None
 
75
 
 
76
    def register_default_vendor(self, vendor):
 
77
        """Register default SSH vendor."""
 
78
        self._default_ssh_vendor = vendor
 
79
 
 
80
    def register_vendor(self, name, vendor):
 
81
        """Register new SSH vendor by name."""
 
82
        self._ssh_vendors[name] = vendor
 
83
 
 
84
    def clear_cache(self):
 
85
        """Clear previously cached lookup result."""
 
86
        self._cached_ssh_vendor = None
 
87
 
 
88
    def _get_vendor_by_environment(self, environment=None):
 
89
        """Return the vendor or None based on BZR_SSH environment variable.
 
90
 
 
91
        :raises UnknownSSH: if the BZR_SSH environment variable contains
 
92
                            unknown vendor name
 
93
        """
 
94
        if environment is None:
 
95
            environment = os.environ
 
96
        if 'BZR_SSH' in environment:
 
97
            vendor_name = environment['BZR_SSH']
 
98
            try:
 
99
                vendor = self._ssh_vendors[vendor_name]
 
100
            except KeyError:
 
101
                raise UnknownSSH(vendor_name)
 
102
            return vendor
 
103
        return None
 
104
 
 
105
    def _get_ssh_version_string(self, args):
 
106
        """Return SSH version string from the subprocess."""
74
107
        try:
75
 
            _ssh_vendor = _ssh_vendors[vendor_name]
76
 
        except KeyError:
77
 
            raise UnknownSSH(vendor_name)
78
 
        return _ssh_vendor
79
 
 
80
 
    try:
81
 
        p = subprocess.Popen(['ssh', '-V'],
82
 
                             stdin=subprocess.PIPE,
83
 
                             stdout=subprocess.PIPE,
84
 
                             stderr=subprocess.PIPE,
85
 
                             **os_specific_subprocess_params())
86
 
        returncode = p.returncode
87
 
        stdout, stderr = p.communicate()
88
 
    except OSError:
89
 
        returncode = -1
90
 
        stdout = stderr = ''
91
 
    if 'OpenSSH' in stderr:
92
 
        mutter('ssh implementation is OpenSSH')
93
 
        _ssh_vendor = OpenSSHSubprocessVendor()
94
 
    elif 'SSH Secure Shell' in stderr:
95
 
        mutter('ssh implementation is SSH Corp.')
96
 
        _ssh_vendor = SSHCorpSubprocessVendor()
97
 
 
98
 
    if _ssh_vendor is not None:
99
 
        return _ssh_vendor
100
 
 
101
 
    # XXX: 20051123 jamesh
102
 
    # A check for putty's plink or lsh would go here.
103
 
 
104
 
    mutter('falling back to paramiko implementation')
105
 
    _ssh_vendor = ParamikoVendor()
106
 
    return _ssh_vendor
107
 
 
 
108
            p = subprocess.Popen(args,
 
109
                                 stdout=subprocess.PIPE,
 
110
                                 stderr=subprocess.PIPE,
 
111
                                 **os_specific_subprocess_params())
 
112
            stdout, stderr = p.communicate()
 
113
        except OSError:
 
114
            stdout = stderr = ''
 
115
        return stdout + stderr
 
116
 
 
117
    def _get_vendor_by_version_string(self, version):
 
118
        """Return the vendor or None based on output from the subprocess.
 
119
 
 
120
        :param version: The output of 'ssh -V' like command.
 
121
        """
 
122
        vendor = None
 
123
        if 'OpenSSH' in version:
 
124
            mutter('ssh implementation is OpenSSH')
 
125
            vendor = OpenSSHSubprocessVendor()
 
126
        elif 'SSH Secure Shell' in version:
 
127
            mutter('ssh implementation is SSH Corp.')
 
128
            vendor = SSHCorpSubprocessVendor()
 
129
        elif 'plink' in version:
 
130
            mutter("ssh implementation is Putty's plink.")
 
131
            vendor = PLinkSubprocessVendor()
 
132
        return vendor
 
133
 
 
134
    def _get_vendor_by_inspection(self):
 
135
        """Return the vendor or None by checking for known SSH implementations."""
 
136
        for args in [['ssh', '-V'], ['plink', '-V']]:
 
137
            version = self._get_ssh_version_string(args)
 
138
            vendor = self._get_vendor_by_version_string(version)
 
139
            if vendor is not None:
 
140
                return vendor
 
141
        return None
 
142
 
 
143
    def get_vendor(self, environment=None):
 
144
        """Find out what version of SSH is on the system.
 
145
 
 
146
        :raises SSHVendorNotFound: if no any SSH vendor is found
 
147
        :raises UnknownSSH: if the BZR_SSH environment variable contains
 
148
                            unknown vendor name
 
149
        """
 
150
        if self._cached_ssh_vendor is None:
 
151
            vendor = self._get_vendor_by_environment(environment)
 
152
            if vendor is None:
 
153
                vendor = self._get_vendor_by_inspection()
 
154
                if vendor is None:
 
155
                    mutter('falling back to default implementation')
 
156
                    vendor = self._default_ssh_vendor
 
157
                    if vendor is None:
 
158
                        raise SSHVendorNotFound()
 
159
            self._cached_ssh_vendor = vendor
 
160
        return self._cached_ssh_vendor
 
161
 
 
162
_ssh_vendor_manager = SSHVendorManager()
 
163
_get_ssh_vendor = _ssh_vendor_manager.get_vendor
 
164
register_default_ssh_vendor = _ssh_vendor_manager.register_default_vendor
 
165
register_ssh_vendor = _ssh_vendor_manager.register_vendor
108
166
 
109
167
 
110
168
def _ignore_sigint():
113
171
    # <https://launchpad.net/products/bzr/+bug/41433/+index>
114
172
    import signal
115
173
    signal.signal(signal.SIGINT, signal.SIG_IGN)
116
 
    
117
174
 
118
175
 
119
176
class LoopbackSFTP(object):
161
218
        """
162
219
        raise NotImplementedError(self.connect_ssh)
163
220
        
 
221
    def _raise_connection_error(self, host, port=None, orig_error=None,
 
222
                                msg='Unable to connect to SSH host'):
 
223
        """Raise a SocketConnectionError with properly formatted host.
 
224
 
 
225
        This just unifies all the locations that try to raise ConnectionError,
 
226
        so that they format things properly.
 
227
        """
 
228
        raise SocketConnectionError(host=host, port=port, msg=msg,
 
229
                                    orig_error=orig_error)
 
230
 
164
231
 
165
232
class LoopbackVendor(SSHVendor):
166
233
    """SSH "vendor" that connects over a plain TCP socket, not SSH."""
170
237
        try:
171
238
            sock.connect((host, port))
172
239
        except socket.error, e:
173
 
            raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
174
 
                                  % (host, port, e))
 
240
            self._raise_connection_error(host, port=port, orig_error=e)
175
241
        return SFTPClient(LoopbackSFTP(sock))
176
242
 
177
243
register_ssh_vendor('loopback', LoopbackVendor())
201
267
            t.set_log_channel('bzr.paramiko')
202
268
            t.start_client()
203
269
        except (paramiko.SSHException, socket.error), e:
204
 
            raise ConnectionError('Unable to reach SSH host %s:%s: %s' 
205
 
                                  % (host, port, e))
 
270
            self._raise_connection_error(host, port=port, orig_error=e)
206
271
            
207
272
        server_key = t.get_remote_server_key()
208
273
        server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
215
280
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
216
281
        else:
217
282
            warning('Adding %s host key for %s: %s' % (keytype, host, server_key_hex))
218
 
            if host not in BZR_HOSTKEYS:
219
 
                BZR_HOSTKEYS[host] = {}
220
 
            BZR_HOSTKEYS[host][keytype] = server_key
 
283
            add = getattr(BZR_HOSTKEYS, 'add', None)
 
284
            if add is not None: # paramiko >= 1.X.X
 
285
                BZR_HOSTKEYS.add(host, keytype, server_key)
 
286
            else:
 
287
                BZR_HOSTKEYS.setdefault(host, {})[keytype] = server_key
221
288
            our_server_key = server_key
222
289
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
223
290
            save_host_keys()
236
303
        try:
237
304
            return t.open_sftp_client()
238
305
        except paramiko.SSHException, e:
239
 
            raise ConnectionError('Unable to start sftp client %s:%d' %
240
 
                                  (host, port), e)
 
306
            self._raise_connection_error(host, port=port, orig_error=e,
 
307
                                         msg='Unable to start sftp client')
241
308
 
242
309
    def connect_ssh(self, username, password, host, port, command):
243
310
        t = self._connect(username, password, host, port)
247
314
            channel.exec_command(cmdline)
248
315
            return _ParamikoSSHConnection(channel)
249
316
        except paramiko.SSHException, e:
250
 
            raise ConnectionError('Unable to invoke remote bzr %s:%d' %
251
 
                                  (host, port), e)
 
317
            self._raise_connection_error(host, port=port, orig_error=e,
 
318
                                         msg='Unable to invoke remote bzr')
252
319
 
253
 
register_ssh_vendor('paramiko', ParamikoVendor())
 
320
if paramiko is not None:
 
321
    vendor = ParamikoVendor()
 
322
    register_ssh_vendor('paramiko', vendor)
 
323
    register_ssh_vendor('none', vendor)
 
324
    register_default_ssh_vendor(vendor)
 
325
    del vendor
254
326
 
255
327
 
256
328
class SubprocessVendor(SSHVendor):
270
342
            sock = self._connect(argv)
271
343
            return SFTPClient(sock)
272
344
        except (EOFError, paramiko.SSHException), e:
273
 
            raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
274
 
                                  % (host, port, e))
 
345
            self._raise_connection_error(host, port=port, orig_error=e)
275
346
        except (OSError, IOError), e:
276
347
            # If the machine is fast enough, ssh can actually exit
277
348
            # before we try and send it the sftp request, which
278
349
            # raises a Broken Pipe
279
350
            if e.errno not in (errno.EPIPE,):
280
351
                raise
281
 
            raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
282
 
                                  % (host, port, e))
 
352
            self._raise_connection_error(host, port=port, orig_error=e)
283
353
 
284
354
    def connect_ssh(self, username, password, host, port, command):
285
355
        try:
287
357
                                                  command=command)
288
358
            return self._connect(argv)
289
359
        except (EOFError), e:
290
 
            raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
291
 
                                  % (host, port, e))
 
360
            self._raise_connection_error(host, port=port, orig_error=e)
292
361
        except (OSError, IOError), e:
293
362
            # If the machine is fast enough, ssh can actually exit
294
363
            # before we try and send it the sftp request, which
295
364
            # raises a Broken Pipe
296
365
            if e.errno not in (errno.EPIPE,):
297
366
                raise
298
 
            raise ConnectionError('Unable to connect to SSH host %s:%s: %s'
299
 
                                  % (host, port, e))
 
367
            self._raise_connection_error(host, port=port, orig_error=e)
300
368
 
301
369
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
302
370
                                  command=None):
306
374
        """
307
375
        raise NotImplementedError(self._get_vendor_specific_argv)
308
376
 
309
 
register_ssh_vendor('none', ParamikoVendor())
310
 
 
311
377
 
312
378
class OpenSSHSubprocessVendor(SubprocessVendor):
313
379
    """SSH vendor that uses the 'ssh' executable from OpenSSH."""
360
426
register_ssh_vendor('ssh', SSHCorpSubprocessVendor())
361
427
 
362
428
 
 
429
class PLinkSubprocessVendor(SubprocessVendor):
 
430
    """SSH vendor that uses the 'plink' executable from Putty."""
 
431
 
 
432
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
 
433
                                  command=None):
 
434
        assert subsystem is not None or command is not None, (
 
435
            'Must specify a command or subsystem')
 
436
        if subsystem is not None:
 
437
            assert command is None, (
 
438
                'subsystem and command are mutually exclusive')
 
439
        args = ['plink', '-x', '-a', '-ssh', '-2']
 
440
        if port is not None:
 
441
            args.extend(['-P', str(port)])
 
442
        if username is not None:
 
443
            args.extend(['-l', username])
 
444
        if subsystem is not None:
 
445
            args.extend(['-s', host, subsystem])
 
446
        else:
 
447
            args.extend([host] + command)
 
448
        return args
 
449
 
 
450
register_ssh_vendor('plink', PLinkSubprocessVendor())
 
451
 
 
452
 
363
453
def _paramiko_auth(username, password, host, paramiko_transport):
364
454
    # paramiko requires a username, but it might be none if nothing was supplied
365
455
    # use the local username, just in case.