sshxmlrpc.py 11.6 KB
Newer Older
1 2 3 4 5
#
# EMULAB-COPYRIGHT
# Copyright (c) 2004 University of Utah and the Flux Group.
# All rights reserved.
#
6
import os
7 8 9 10
import sys
import types
import urllib
import popen2
11
import rfc822
12 13
import xmlrpclib

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
##
# Base class for exceptions in this module.
#
class SSHException(Exception):
    pass

##
# Indicates a poorly formatted response from the server.
#
class BadResponse(SSHException):

    ##
    # @param host The server host name.
    # @param handler The handler being accessed on the server.
    # @param arg Description of the problem.
    #
    def __init__(self, host, handler, msg):
        self.args = host, handler, msg,
        return
    
    pass

##
# Class used to decode headers.
#
class SSHMessage(rfc822.Message):
    pass

##
# An SSH based connection class.
#
class SSHConnection:

    ##
    # @param host The peer host name.
    # @param handler The handler being accessed.
    # @param streams A pair containing the input and output files respectively.
    # If this value is not given, ssh will be used to connect to the host.
    # @param ssh_config The ssh config file to use when initiating a new
    # connection.
    # 
    def __init__(self, host, handler, streams=None, ssh_config=None):
        # Store information about the peer and
        self.handler = handler
        self.host = host

        # ... initialize the read and write file objects.
        if streams:
            self.myChild = None
            self.rfile = streams[0]
            self.wfile = streams[1]
            pass
        else:
            self.user, self.host = urllib.splituser(self.host)
68
            # print self.user + " " + self.host + " " + handler
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
            
            flags = ""
            if self.user:
                flags = flags + " -l " + self.user
                pass
            if ssh_config:
                flags = flags + " -F " + ssh_config
                pass
            self.myChild = popen2.Popen3("ssh -x "
                                         + flags
                                         + " "
                                         + self.host
                                         + " "
                                         + handler,
                                         1)
            self.rfile = self.myChild.fromchild
            self.wfile = self.myChild.tochild
            pass
        return

    ##
    # @param len The amount of data to read. (Default: 1024)
    # @return The amount of data read.
    #
    def read(self, len=1024):
        return self.rfile.read(len)

    ##
    # @return A line of data or None if there is no more input.
    #
    def readline(self):
        return self.rfile.readline()

    ##
    # @param stuff The data to send to the other side.
    # @return The amount of data written.
    #
    def write(self, stuff):
        return self.wfile.write(stuff)

    ##
    # Flush any write buffers.
    #
    def flush(self):
        self.wfile.flush()
        return

    ##
    # Close the connection.
    #
    def close(self):
        self.rfile.close()
        self.wfile.close()
        if self.myChild:
            self.myChild.wait()
            self.myChild = None
            pass
        return

    ##
    # Send an rfc822 style header to the other side.
    #
    # @param key The header key.
    # @param value The value paired with the given key.
    #
    def putheader(self, key, value):
        self.write("%s: %s\r\n" % (key, str(value)))
        return

    ##
    # Terminate the list of headers so the body can follow.
    #
    def endheaders(self):
        self.write("\r\n")
        self.flush()
        return

    def __repr__(self):
        return "<SSHConnection %s%s>" % (self.host, self.handler)

    __str__ = __repr__

    pass

153 154 155 156
##
# Use SSH to transport XML-RPC requests/responses
#
class SSHTransport:
157 158 159 160 161 162 163 164

    ##
    # @param ssh_config The ssh config file to use when making new connections.
    #
    def __init__(self, ssh_config=None):
        self.connections = {}
        self.ssh_config = ssh_config
        return
165 166 167 168 169
    
    ##
    # Send a request to the destination.
    #
    # @param host The host name on which to execute the request
170
    # @param handler The python file that will handle the request.
171 172 173 174
    # @param request_body The XML-RPC encoded request.
    # @param verbose unused.
    # @return The value returned 
    #
175
    def request(self, host, handler, request_body, verbose=0, path=None):
176
        # Strip the leading slash in the handler, if there is one.
177 178 179 180
        if path:
            handler = path + handler
            pass
        elif handler.startswith('/'):
181 182
            handler = handler[1:]
            pass
183

184 185
        # Try to get a new connection,
        if not self.connections.has_key((host,handler)):
186 187 188 189 190
            if verbose:
                sys.stderr.write("New connection for %s %s\n" %
                                 (host, handler))
                pass
            
191 192 193
            self.connections[(host,handler)] = SSHConnection(host, handler)
            pass
        connection = self.connections[(host,handler)]
194

195 196 197 198 199
        # ... send our request, and
        connection.putheader("content-length", len(request_body))
        connection.endheaders()
        connection.write(request_body)
        connection.flush()
200

201 202
        # ... parse the response.
        retval = self.parse_response(connection)
203 204 205 206 207 208 209 210 211 212 213 214 215 216

        return retval

    ##
    # @return A tuple containing the parser and unmarshaller, in that order
    #
    def getparser(self):
        return xmlrpclib.getparser()

    ##
    # Parse the response from the server.
    #
    # @return The python value returned by the server method.
    #
217
    def parse_response(self, connection):
218 219
        parser, unmarshaller = self.getparser()

220 221 222 223 224 225 226
        try:
            # Get the headers,
            headers = SSHMessage(connection, False)
            # ... the length of the body, and
            length = int(headers['content-length'])
            # ... read in the body.
            response = connection.read(length)
227
            pass
228 229 230 231 232 233 234 235
        except KeyError, e:
            # Bad header, drop the connection, and
            del self.connections[(connection.host,connection.handler)]
            connection.close()
            # ... tell the user.
            raise BadResponse(connection.host, connection.handler, e.args)
        
        parser.feed(response)
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

        return unmarshaller.close()
    
    pass


##
# A wrapper for objects that should be exported via an XML-RPC interface.  Any
# method calls received via XML-RPC will automatically be translated into real
# python calls.
#
class SSHServerWrapper:

    ##
    # Initialize this object.
    #
    # @param object The object to wrap.
    #
    def __init__(self, object):
255
        self.ssh_connection = os.environ['SSH_CONNECTION'].split()
256 257 258 259 260 261 262 263
        self.myObject = object
        return

    ##
    # Handle a single request from a client.  The method will read the request
    # from the client, dispatch the method, and write the response back to the
    # client.
    #
264
    # @param connection An initialized SSHConnection object.
265
    #
266 267
    def handle_request(self, connection):
        retval = False
268 269
        try:
            # Read the request,
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
            hdrs = SSHMessage(connection, False)
            length = int(hdrs['content-length'])
            params, method = xmlrpclib.loads(connection.read(length))
            try:
                # ... find the corresponding method in the wrapped object,
                meth = getattr(self.myObject, method)
                # ... dispatch the method, and
                if type(meth) == type(self.handle_request):
                    response = apply(meth, params) # It is really a method.
                    pass
                else:
                    response = str(meth) # Is is just a plain variable.
                    pass
                # ... ensure there was a valid response.
                if type(response) != type((  )):
                    response = (response,)
                    pass
287
                pass
288 289 290 291 292
            except:
                # Some other exception happened, convert it to an XML-RPC fault
                response = xmlrpclib.dumps(
                    xmlrpclib.Fault(1,
                                    "%s:%s" % (sys.exc_type, sys.exc_value)))
293
                pass
294 295 296
            else:
                # Everything worked, encode the real response.
                response = xmlrpclib.dumps(response, methodresponse=1)
297 298 299 300 301
                pass
            pass
        except xmlrpclib.Fault, faultobj:
            # An XML-RPC related fault occurred, just encode the response.
            response = xmlrpclib.dumps(faultobj)
302
            retval = True
303 304 305 306 307
            pass
        except:
            # Some other exception happened, convert it to an XML-RPC fault.
            response = xmlrpclib.dumps(
                xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)))
308
            retval = True
309 310 311
            pass

        # Finally, send the reply to the client.
312 313 314 315
        connection.putheader("content-length", len(response))
        connection.endheaders()
        connection.write(response)
        connection.flush()
316

317
        return retval
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    ##
    # Handle all of the user requests.
    #
    # @param streams A pair containing the input and output streams.
    #
    def serve_forever(self, streams):
        # Make a new connection from the streams and handle requests until the
        # streams are closed or there is a protocol error.
        connection = SSHConnection(self.ssh_connection[0], '', streams=streams)
        try:
            done = False
            while not done:
                done = self.handle_request(connection)
                pass
            pass
        finally:
            connection.close()
            pass
        return
    
339 340 341 342
    pass


##
343
# A client-side proxy for XML-RPC servers that are accessible via SSH.
344 345 346 347 348 349 350 351 352 353 354 355
#
class SSHServerProxy:

    ##
    # Initialize the object.
    #
    # @param uri The URI for the server.  Must start with 'ssh'.
    # @param transport A python object that implements the Transport interface.
    # The default is to use a new SSHTransport object.
    # @param encoding Content encoding.
    # @param verbose unused.
    #
356
    def __init__(self, uri, transport=None, encoding=None, verbose=0, path=None):
357 358 359 360 361 362 363 364 365 366 367 368 369 370
        type, uri = urllib.splittype(uri)
        if type not in ("ssh", ):
            raise IOError, "unsupported XML-RPC protocol"

        self.__host, self.__handler = urllib.splithost(uri)

        if transport is None:
            transport = SSHTransport()
            pass
        
        self.__transport = transport

        self.__encoding = encoding
        self.__verbose = verbose
371
        self.__path = path
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        return

    ##
    # Send a request to the server.
    #
    # @param methodname The name of the method.
    # @param params The parameters for the method.
    #
    def __request(self, methodname, params):
        # Convert the method name and parameters to a string,
        request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding)

        # ... use the transport to send the request and receive the reply, and
        response = self.__transport.request(
            self.__host,
            self.__handler,
            request,
389 390
            verbose=self.__verbose,
            path=self.__path
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            )

        # ... ensure there was a valid reply.
        if len(response) == 1:
            response = response[0]
            pass

        return response

    def __repr__(self):
        return (
            "<ServerProxy for %s%s>" %
            (self.__host, self.__handler)
            )

    __str__ = __repr__

    def __getattr__(self, name):
        # magic method dispatcher
        return xmlrpclib._Method(self.__request, name)
411

412
    pass