sshxmlrpc.py 17.3 KB
Newer Older
1 2
#
# Copyright (c) 2004 University of Utah and the Flux Group.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
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
# Some bits of this file are from xmlrpclib.py, which is:
# --------------------------------------------------------------------
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
#
import os
import sys
import types
import urllib
import popen2
import rfc822
import xmlrpclib
59 60
if os.name != "nt":
    import syslog
61 62

# XXX This should come from configure.
63 64 65 66
if os.name != "nt":
    LOG_TESTBED = syslog.LOG_LOCAL5;

import traceback
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

##
# 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

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
##
# Indicates a poorly formatted request from the client.
#
class BadRequest(SSHException):

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

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
##
# 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.
130
        self.myChild = None
131 132 133 134 135
        if streams:
            self.rfile = streams[0]
            self.wfile = streams[1]
            pass
        else:
136
            self.user, ssh_host = urllib.splituser(self.host)
137 138
            # print self.user + " " + self.host + " " + handler
            
139 140 141 142
            # Use ssh unless we're on Windows with no ssh-agent running.
            nt = os.name == "nt"
            use_ssh = not nt or os.environ.has_key("SSH_AGENT_PID")

143 144 145 146
            flags = ""
            if self.user:
                flags = flags + " -l " + self.user
                pass
147
            if use_ssh and ssh_config:
148 149
                flags = flags + " -F " + ssh_config
                pass
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
            args = flags + " " + ssh_host + " " + handler

            if use_ssh:
                cmd = "ssh -x -C -o 'CompressionLevel 5' " + args
                pass
            else:
                # Use the PyTTY plink, equivalent to the ssh command.
                cmd = "plink -x -C " + args
                pass
            
            if not nt:
                # Popen3 objects, and the wait method, are Unix-only.
                self.myChild = popen2.Popen3(cmd, 0)
                self.rfile = self.myChild.fromchild
                self.wfile = self.myChild.tochild
                pass
            else:
                # Open the pipe in Binary mode so it doesn't mess with CR-LFs.
                self.rfile, self.wfile, self.errfile = popen2.popen3(cmd, mode='b')
                pass
            # print "wfile", self.wfile, "rfile", self.rfile
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
            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):
192
        # print "write", stuff
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        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

##
# Use SSH to transport XML-RPC requests/responses
#
class SSHTransport:

    ##
    # @param ssh_config The ssh config file to use when making new connections.
246 247
    # @param user_agent Symbolic name for the program acting on behalf of the
    #   user.
248
    #
249
    def __init__(self, ssh_config=None, user_agent=None):
250 251
        self.connections = {}
        self.ssh_config = ssh_config
252
        self.user_agent = user_agent
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        return
    
    ##
    # Send a request to the destination.
    #
    # @param host The host name on which to execute the request
    # @param handler The python file that will handle the request.
    # @param request_body The XML-RPC encoded request.
    # @param verbose unused.
    # @return The value returned 
    #
    def request(self, host, handler, request_body, verbose=0, path=None):
        # Strip the leading slash in the handler, if there is one.
        if path:
            handler = path + handler
            pass
        elif handler.startswith('/'):
            handler = handler[1:]
            pass

        # Try to get a new connection,
        if not self.connections.has_key((host,handler)):
            if verbose:
                sys.stderr.write("New connection for %s %s\n" %
                                 (host, handler))
                pass
            
            self.connections[(host,handler)] = SSHConnection(host, handler)
            pass
        connection = self.connections[(host,handler)]

        # ... send our request, and
285 286 287
        if self.user_agent:
            connection.putheader("user-agent", self.user_agent)
            pass
288
        connection.putheader("content-length", len(request_body))
289
        connection.putheader("content-type", "text/xml")
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        connection.endheaders()
        connection.write(request_body)
        connection.flush()

        # ... parse the response.
        retval = self.parse_response(connection)

        return retval

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

305 306 307 308 309 310 311 312
    ##
    # @param connection The connection to drop.
    #
    def drop_connection(self, connection):
        del self.connections[(connection.host,connection.handler)]
        connection.close()
        return
    
313 314 315 316 317 318 319 320 321 322 323
    ##
    # Parse the response from the server.
    #
    # @return The python value returned by the server method.
    #
    def parse_response(self, connection):
        parser, unmarshaller = self.getparser()

        try:
            # Get the headers,
            headers = SSHMessage(connection, False)
324 325 326 327 328
            if headers.status != "":
                self.drop_connection(connection)
                raise BadResponse(connection.host,
                                  connection.handler,
                                  headers.status)
329 330 331 332 333 334 335
            # ... the length of the body, and
            length = int(headers['content-length'])
            # ... read in the body.
            response = connection.read(length)
            pass
        except KeyError, e:
            # Bad header, drop the connection, and
336
            self.drop_connection(connection)
337
            # ... tell the user.
338
            raise BadResponse(connection.host, connection.handler, e.args[0])
339
        
340
        # print "response /"+response+"/"
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        parser.feed(response)

        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):
        self.ssh_connection = os.environ['SSH_CONNECTION'].split()
        self.myObject = object

        #
        # Init syslog
        #
367 368 369 370 371
        if os.name != "nt":
            syslog.openlog("sshxmlrpc", syslog.LOG_PID, LOG_TESTBED);
            syslog.syslog(syslog.LOG_INFO,
                          "Connect by " + os.environ['USER'] + " from " +
                          self.ssh_connection[0]);
372 373 374 375 376 377 378 379 380 381 382 383 384 385
        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.
    #
    # @param connection An initialized SSHConnection object.
    #
    def handle_request(self, connection):
        retval = False
        try:
            # Read the request,
            hdrs = SSHMessage(connection, False)
386 387 388 389 390 391 392 393 394 395 396 397 398 399
            if hdrs.status != "":
                #sys.stderr.write("server error: Expecting rfc822 headers.\n");
                raise BadRequest(connection.host, hdrs.status)
            if not hdrs.has_key('content-length'):
                sys.stderr.write("server error: "
                                 + "expecting content-length header\n")
                raise BadRequest(connection.host,
                                 "missing content-length header")
            if hdrs.has_key('user-agent'):
                user_agent = hdrs['user-agent']
                pass
            else:
                user_agent = "unknown"
                pass
400 401
            length = int(hdrs['content-length'])
            params, method = xmlrpclib.loads(connection.read(length))
402 403 404 405 406 407
            if os.name != "nt":
                syslog.syslog(syslog.LOG_INFO,
                              "Calling method '"
                              + method
                              + "'; user-agent="
                              + user_agent);
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
            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
                pass
            except:
424
                traceback.print_exc()
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
                # 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)))
                pass
            else:
                # Everything worked, encode the real response.
                response = xmlrpclib.dumps(response, methodresponse=1)
                pass
            pass
        except xmlrpclib.Fault, faultobj:
            # An XML-RPC related fault occurred, just encode the response.
            response = xmlrpclib.dumps(faultobj)
            retval = True
            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)))
            retval = True
            pass

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

        return retval

    ##
    # 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()
472 473 474
            if os.name != "nt":
                syslog.syslog(syslog.LOG_INFO, "Connection closed");
                syslog.closelog()
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
            pass
        return
    
    pass


##
# A client-side proxy for XML-RPC servers that are accessible via SSH.
#
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.
494 495
    # @param user_agent Symbolic name for the program acting on behalf of the
    #   user.
496
    #
497 498 499 500 501 502 503
    def __init__(self,
                 uri,
                 transport=None,
                 encoding=None,
                 verbose=0,
                 path=None,
                 user_agent=None):
504 505 506 507 508 509 510
        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:
511
            transport = SSHTransport(user_agent=user_agent)
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
            pass
        
        self.__transport = transport

        self.__encoding = encoding
        self.__verbose = verbose
        self.__path = path
        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,
            verbose=self.__verbose,
            path=self.__path
            )

        # ... 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)

559 560 561 562
    # Locally handle "if not server:".
    def __nonzero__(self):
        return True

563
    pass