sshxmlrpc.py 32.6 KB
Newer Older
1 2
#! /usr/bin/env python

3 4 5 6 7
#
# EMULAB-COPYRIGHT
# Copyright (c) 2004 University of Utah and the Flux Group.
# All rights reserved.
#
8 9 10 11 12 13 14 15 16
# Permission to use, copy, modify and distribute this software is hereby
# granted provided that (1) source code retains these copyright, permission,
# and disclaimer notices, and (2) redistributions including binaries
# reproduce the notices in supporting documentation.
#
# THE UNIVERSITY OF UTAH ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
# CONDITION.  THE UNIVERSITY OF UTAH DISCLAIMS ANY LIABILITY OF ANY KIND
# FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
#
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
# 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.
# --------------------------------------------------------------------
#
46 47 48 49
import sys
import types
import urllib
import popen2
50
import rfc822
51
import xmlrpclib
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
import os, os.path

VERSION = 0.5

##
## BEGIN Debugging setup
##

SSHXMLRPC_DEBUG = os.environ.get("SSHXMLRPC_DEBUG", "")

# SSHXMLRPC_DEBUG = "all"

if "all" in SSHXMLRPC_DEBUG:
    SSHXMLRPC_DEBUG = "config,connect,io,ssh"
    pass

def __sxrdebug__(key, *args):
    if key in SSHXMLRPC_DEBUG:
        sys.stderr.write("sshxmlrpc.py: " + "".join(args) + "\n")
        pass
    return

##
## END Debugging setup
##



__sxrdebug__("config", "OS ", os.name)
81

82
if os.name != "nt":
83
    import syslog
84
    LOG_TESTBED = syslog.LOG_LOCAL5;
85
    pass
86

87 88
import traceback

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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206


##
## BEGIN Self-configuration
##

##
# Search the user's PATH for the given command.
#
# @param command The command name to search for.
# @return The full path to the command or None if the command was not found.
#
def conf_which(command):
    if os.path.exists(command) and os.path.isfile(command):
        return command
    for path in os.environ.get('PATH', os.defpath).split(os.pathsep):
        fullpath = os.path.join(path, command)
        if os.path.exists(fullpath) and os.path.isfile(fullpath):
            return fullpath
        pass
    return None

##
# Search for several commands in the user's PATH and return the first match.
#
# @param possible_commands The list of commands to search for.
# @return The first command that matched, or None if no match was found.
#
def conf_detect(possible_commands):
    for cmd in possible_commands:
        if len(cmd) > 0:
            cmd_no_flags = cmd.split()[0]
            retval = conf_which(cmd_no_flags)
            if retval is not None:
                return cmd
            pass
        pass
    return None

# The default identity for the user.
DEFAULT_SSH_IDENTITY = os.path.join(os.path.expanduser("~"),
                                    ".ssh",
                                    "identity")

__sxrdebug__("config", "DEFAULT_SSH_IDENTITY - ", str(DEFAULT_SSH_IDENTITY))

##
# Check if the user can perform a passphrase-less login.
#
# @param identity The identity to check.
# @return True if the user can perform a passphraseless login.
#
def conf_passphraseless_login(identity=None):
    if os.environ.get("SSH_AUTH_SOCK", "") == "":
        # No agent, check for a passphrase-less key and then
        if SSHKEYGEN_COMMAND is not None:
            if not identity or (identity == ""):
                identity = DEFAULT_SSH_IDENTITY
                pass
            rc = os.system(SSHKEYGEN_COMMAND
                           + " -p -P \"\" -N \"\" -f "
                           + identity
                           + " > /dev/null 2>&1")
            if rc != 0:
                retval = False
                pass
            else:
                retval = True
                pass
            pass
        # ... complain.
        elif os.name != "nt":
            retval = False
            pass
        pass
    else:
        retval = True
        pass
    
    return retval

# Find a suitable "ssh" command and
SSH_COMMAND = conf_detect([
    os.environ.get("SSHXMLRPC_SSH", ""),
    "ssh -T -x -C -o 'CompressionLevel 5' %(-F)s %(-l)s %(-i)s %(-v)s %(-1)s %(-2)s",
    "plink -x -C %(-l)s %(-i)s %(-v)s %(-1)s %(-2)s",
    ])

__sxrdebug__("config", "SSH_COMMAND - ", str(SSH_COMMAND))

# ... error out if we don't.
if SSH_COMMAND is None:
    sys.stderr.write("sshxmlrpc.py: Unable to locate a suitable SSH command\n")
    if os.environ.has_key("SSHXMLRPC_SSH"):
        sys.stderr.write("sshxmlrpc.py: '"
                         + os.environ["SSHXMLRPC_SSH"]
                         + "' was not found.\n")
        pass
    else:
        sys.stderr.write("sshxmlrpc.py: Set the SSHXMLRPC_SSH environment "
                         "variable to a suitable binary (e.g. ssh/plink)\n")
        pass
    raise ImportError, "suitable ssh not found in path: %(PATH)s" % os.environ

# Find ssh-keygen so we can do some tests when a connection is made.
SSHKEYGEN_COMMAND = conf_detect([
    os.environ.get("SSHXMLRPC_SSHKEYGEN", ""),
    "ssh-keygen",
    ])

__sxrdebug__("config", "SSHKEYGEN_COMMAND - ", str(SSHKEYGEN_COMMAND))

##
## END Self-configuration
##



207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
##
# 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

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
##
# 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

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
##
# 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.
    # 
263 264
    def __init__(self, host, handler, streams=None, ssh_config=None,
                 ssh_identity=None, ssh_opts={}):
265 266 267
        # Store information about the peer and
        self.handler = handler
        self.host = host
268
        self.last_lines = []
269 270 271 272 273

        # ... initialize the read and write file objects.
        if streams:
            self.rfile = streams[0]
            self.wfile = streams[1]
274 275
            self.errfile = None
            self.closed = False
276 277
            pass
        else:
278 279 280 281 282
            if not conf_passphraseless_login(ssh_identity):
                sys.stderr.write("sshxmlrpc.py: warning - No agent or "
                                 "passphrase-less key found, "
                                 "continuing anyways...\n")
                pass
283
            
284
            self.user, ssh_host = urllib.splituser(self.host)
285

286 287 288
            all_opts = { "-l" : "", "-i" : "", "-F" : "", "-v" : "",
                         "-1" : "", "-2" : "" }
            all_opts.update(ssh_opts)
289
            if self.user:
290
                all_opts["-l"] = "-l " + self.user
291
                pass
292 293
            if ssh_identity:
                all_opts["-i"] = "-i " + ssh_identity
294
                pass
295 296
            if ssh_config:
                all_opts["-F"] = "-F " + ssh_config
297
                pass
298 299
            if "ssh" in SSHXMLRPC_DEBUG:
                all_opts["-v"] = "-vvv"
300
                pass
301 302 303 304 305 306 307 308 309
            
            args = (SSH_COMMAND % all_opts) + " " + ssh_host + " " + handler
            
            __sxrdebug__("connect", "open - ", args)
            
            # Open the pipe in Binary mode so it doesn't mess with CR-LFs.
            self.rfile, self.wfile, self.errfile = popen2.popen3(
                args, mode='b')
            self.closed = False
310
            pass
311
        
312 313 314 315 316 317 318
        return

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

        __sxrdebug__("io", "read - ", retval)
        return retval
323 324 325 326 327

    ##
    # @return A line of data or None if there is no more input.
    #
    def readline(self):
328 329 330 331 332 333 334 335 336 337 338 339 340
        retval = self.rfile.readline()
        if len(retval) > 0:
            self.last_lines.append(retval)
            if len(self.last_lines) > 5:
                self.last_lines.pop(0)
                pass
            pass
        else:
            self.closed = True
            pass
        
        __sxrdebug__("io", "readline - ", retval)
        return retval
341 342 343 344 345 346

    ##
    # @param stuff The data to send to the other side.
    # @return The amount of data written.
    #
    def write(self, stuff):
347 348
        __sxrdebug__("io", "write - ", stuff)
        
349 350 351 352 353 354
        return self.wfile.write(stuff)

    ##
    # Flush any write buffers.
    #
    def flush(self):
355 356
        __sxrdebug__("io", "flush")
        
357 358 359 360 361 362 363
        self.wfile.flush()
        return

    ##
    # Close the connection.
    #
    def close(self):
364 365
        __sxrdebug__("connect", "close - ", self.host)
        
366
        self.wfile.close()
367
        self.rfile.close()
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        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

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    ##
    # Dump the standard error from the peer to the given file pointer with the
    # given prefix.
    #
    # @param fp The file pointer where the output should be written or None if
    # you just want to drain the pipe.
    # @param prefix Prefix to prepend to every line. (optional)
    #
    def dump_stderr(self, fp, prefix=""):
        if self.errfile:
            while True:
                line = self.errfile.readline()
                if not line:
                    break
                if fp:
                    fp.write(prefix + line)
                    pass
                pass
            pass
        return

    ##
    # Dump the last five lines of input read from the peer.  Helpful for
    # debugging connections and what not.
    #
    # @param fp The file pointer where the output should be written.
    # @param prefix Prefix to prepend to every line. (optional)
    #
    def dump_last_lines(self, fp, prefix=""):
        if len(self.last_lines) < 5:
            for lpc in range(len(self.last_lines), 5):
                if not self.readline():
                    break
                pass
            pass
        for line in self.last_lines:
            fp.write(prefix + line)
            pass
        return

428 429 430 431 432 433 434
    def __repr__(self):
        return "<SSHConnection %s%s>" % (self.host, self.handler)

    __str__ = __repr__

    pass

435 436 437 438
##
# Use SSH to transport XML-RPC requests/responses
#
class SSHTransport:
439 440 441

    ##
    # @param ssh_config The ssh config file to use when making new connections.
442 443
    # @param user_agent Symbolic name for the program acting on behalf of the
    #   user.
444
    # @param ssh_opts List of additional options to pass to SSH_COMMAND.
445
    #
446 447
    def __init__(self, ssh_config=None, user_agent=None, ssh_identity=None,
                 ssh_opts={}):
448 449
        self.connections = {}
        self.ssh_config = ssh_config
450 451 452 453 454 455 456 457
        if user_agent:
            self.user_agent = user_agent
            pass
        else:
            self.user_agent = sys.argv[0]
            pass
        self.ssh_identity = ssh_identity
        self.ssh_opts = ssh_opts
458
        return
459

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    ##
    # Probe the peer and return their response headers.  Useful for making sure
    # the other side is what we expect it to be.
    #
    # @param host The host to contact.
    # @param handler The XML-RPC handler.
    # @param hdrs A dictionary of additional headers to send to the peer, these
    # will be included in their response.
    # @return The response headers from the peer.
    # @throws BadResponse if there was a problem interpreting the other side's
    # response.
    #
    def probe(self, host, handler, hdrs={}, verbose=False):
        handler = self.munge_handler(handler)
        
        connection = self.get_connection((host, handler))
        connection.putheader("probe", self.user_agent)
        for (key, value) in hdrs.items():
            connection.putheader(key, str(value))
479
            pass
480 481 482 483 484
        connection.endheaders()
        connection.flush()

        return self.parse_headers(connection, verbose=verbose)

485 486 487 488
    ##
    # Send a request to the destination.
    #
    # @param host The host name on which to execute the request
489
    # @param handler The python file that will handle the request.
490
    # @param request_body The XML-RPC encoded request.
491
    # @return The value returned by the peer method.
492
    #
493 494
    def request(self, host, handler, request_body, path=None):
        handler = self.munge_handler(handler, path)
495

496
        # Try to get a new connection,
497
        connection = self.get_connection((host,handler))
498

499
        # ... send our request, and
500
        connection.putheader("user-agent", self.user_agent)
501
        connection.putheader("content-length", len(request_body))
502
        connection.putheader("content-type", "text/xml")
503 504 505
        connection.endheaders()
        connection.write(request_body)
        connection.flush()
506

507 508
        # ... parse the response.
        retval = self.parse_response(connection)
509 510 511 512 513 514 515 516 517

        return retval

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

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
    ##
    # Munge the handler which means stripping the first slash, if it is there.
    #
    # @param handler The handler to munge.
    # @return The munged handler string.
    #
    def munge_handler(self, handler, path=None):
        # Strip the leading slash in the handler, if there is one.
        if path:
            retval = path + handler
            pass
        elif handler.startswith('/'):
            retval = handler[1:]
            pass
        else:
            retval = handler
            pass
        
        return retval

    ##
    # Get a cached connection or make a new one.
    #
    # @param pair The host/handler pair that identifies the connection.
    # @return An SSHConnection object for the given pair.
    #
    def get_connection(self, pair):
        if not self.connections.has_key(pair):
            __sxrdebug__("connect",
                         "new connection for ", pair[0], " ", pair[1])
            
            self.connections[pair] = SSHConnection(
                pair[0], pair[1],
                ssh_identity=self.ssh_identity, ssh_opts=self.ssh_opts)
            pass
        return self.connections[pair]

555 556 557 558 559 560 561
    ##
    # @param connection The connection to drop.
    #
    def drop_connection(self, connection):
        del self.connections[(connection.host,connection.handler)]
        connection.close()
        return
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

    ##
    # Parse the headers from the peer.
    #
    # @param connection The connection to read the headers from.
    # @param verbose Be verbose in providing error information. (default: True)
    #
    def parse_headers(self, connection, verbose=True):
        retval = SSHMessage(connection, False)
        if retval.status != "":
            if verbose:
                connection.dump_stderr(sys.stderr,
                                       connection.host + ",stderr: ")
                sys.stderr.write("sshxmlrpc.py: Error while reading headers, "
                                 "expected rfc822 headers, received:\n")
                connection.dump_last_lines(sys.stderr, ">> ")
                pass
            self.drop_connection(connection)
            raise BadResponse(connection.host,
                              connection.handler,
                              retval.status)
        
        return retval
585
    
586 587 588 589 590
    ##
    # Parse the response from the server.
    #
    # @return The python value returned by the server method.
    #
591
    def parse_response(self, connection):
592 593
        parser, unmarshaller = self.getparser()

594 595
        try:
            # Get the headers,
596 597
            headers = self.parse_headers(connection)
            
598 599 600 601 602
            # ... the length of the body, and
            length = int(headers['content-length'])
            # ... read in the body.
            response = connection.read(length)
        except KeyError, e:
603 604 605 606
            connection.dump_stderr(sys.stderr, connection.host + ",stderr: ")
            sys.stderr.write("sshxmlrpc.py: Error while reading headers, "
                             + "expected rfc822 headers, received:\n")
            connection.dump_last_lines(sys.stderr, ">> ")
607
            # Bad header, drop the connection, and
608
            self.drop_connection(connection)
609
            # ... tell the user.
610
            raise BadResponse(connection.host, connection.handler, e.args[0])
611

612
        parser.feed(response)
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

        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.
630 631
    # @param probe_response The value to send back to clients in the
    # 'probe-response' header.
632
    #
633 634 635
    def __init__(self, object, probe_response=None):
        self.ssh_connection = os.environ.get(
            "SSH_CONNECTION", "stdin 0 stdout 0").split()
636
        self.myObject = object
637 638 639 640
        self.probe_response = probe_response
        if self.probe_response is None:
            self.probe_response = sys.argv[0] + " " + str(VERSION)
            pass
641 642 643 644

        #
        # Init syslog
        #
645 646 647 648 649
        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]);
650 651
            pass
        
652 653 654 655 656 657 658
        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.
    #
659
    # @param connection An initialized SSHConnection object.
660
    #
661 662
    def handle_request(self, connection):
        retval = False
663
        try:
664
            # Read the request headers,
665
            hdrs = SSHMessage(connection, False)
666 667

            # ... make sure they are sane,
668
            if hdrs.status != "":
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
                if not connection.closed:
                    sys.stderr.write("server error: Expecting rfc822 headers, "
                                     "received:\n");
                    connection.dump_last_lines(sys.stderr, "<< ")
                    sys.stderr.write("conn " + `connection.closed` + "\n")
                    sys.stderr.write("server error: " + hdrs.status)
                    raise BadRequest(connection.host, hdrs.status)
                else:
                    return True
                pass

            # ... respond to probes immediately,
            if hdrs.has_key("probe"):
                connection.putheader("probe-response", self.probe_response)
                del hdrs["content-length"]
                connection.putheader("content-length", 0)
                for (key, value) in hdrs.items():
                    connection.putheader(key, value)
                    pass
                connection.endheaders()
                connection.flush()
                return retval

            # ... check for required headers, and
693
            if not hdrs.has_key('content-length'):
694 695 696
                sys.stderr.write("server error: expecting content-length "
                                 "header, received:\n")
                connection.dump_last_lines(sys.stderr, "<< ")
697 698
                raise BadRequest(connection.host,
                                 "missing content-length header")
699

700 701 702 703 704 705
            if hdrs.has_key('user-agent'):
                user_agent = hdrs['user-agent']
                pass
            else:
                user_agent = "unknown"
                pass
706 707
            
            # ... start reading the body.
708 709
            length = int(hdrs['content-length'])
            params, method = xmlrpclib.loads(connection.read(length))
710 711 712 713 714 715
            if os.name != "nt":
                syslog.syslog(syslog.LOG_INFO,
                              "Calling method '"
                              + method
                              + "'; user-agent="
                              + user_agent);
716 717 718 719 720 721 722 723 724 725 726 727 728 729
            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
730
                pass
731
            except:
732
                traceback.print_exc()
733 734 735 736
                # 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)))
737
                pass
738 739 740
            else:
                # Everything worked, encode the real response.
                response = xmlrpclib.dumps(response, methodresponse=1)
741 742 743 744 745
                pass
            pass
        except xmlrpclib.Fault, faultobj:
            # An XML-RPC related fault occurred, just encode the response.
            response = xmlrpclib.dumps(faultobj)
746
            retval = True
747 748 749 750 751
            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)))
752
            retval = True
753 754 755
            pass

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

761
        return retval
762

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    ##
    # 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()
780 781 782
            if os.name != "nt":
                syslog.syslog(syslog.LOG_INFO, "Connection closed");
                syslog.closelog()
783
                pass
784 785
            pass
        return
786 787 788

    def serve_stdio_forever(self):
        return self.serve_forever((sys.stdin, sys.stdout))
789
    
790 791 792 793
    pass


##
794
# A client-side proxy for XML-RPC servers that are accessible via SSH.
795 796 797 798 799 800 801 802 803 804
#
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.
805 806
    # @param user_agent Symbolic name for the program acting on behalf of the
    #   user.
807
    # @param ssh_opts List of additional options to pass to SSH_COMMAND.
808
    #
809 810 811 812 813
    def __init__(self,
                 uri,
                 transport=None,
                 encoding=None,
                 path=None,
814 815 816
                 user_agent=None,
                 ssh_identity=None,
                 ssh_opts={}):
817 818
        type, uri = urllib.splittype(uri)
        if type not in ("ssh", ):
819
            raise IOError, "unsupported XML-RPC protocol: " + `type`
820 821 822 823

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

        if transport is None:
824 825 826
            transport = SSHTransport(user_agent=user_agent,
                                     ssh_identity=ssh_identity,
                                     ssh_opts=ssh_opts)
827 828 829 830 831
            pass
        
        self.__transport = transport

        self.__encoding = encoding
832
        self.__path = path
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
        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,
850
            path=self.__path
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
            )

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

872 873 874 875
    # Locally handle "if not server:".
    def __nonzero__(self):
        return True

876
    pass
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928

if __name__ == "__main__":
    import time
    import getopt

    def usage():
        print "SSH-based XML-RPC module/client."
        print "Usage: sshxmlrpc.py [-hVq] [-u agent] [-i id] [-s opts] [<URL>]"
        print "       sshxmlrpc.py [-u agent] [-i id] [-s opts] [<URL> <method>]"
        print
        print "Options:"
        print "  -h, --help\t\t  Display this help message"
        print "  -V, --version\t\t  Show the version number"
        print "  -q, --quiet\t\t  Be less verbose"
        print "  -u, --user-agent agent  Specify the user agent"
        print "  -i, --identity id\t  Specify the SSH identity to use"
        print "  -s, --ssh-opts opts\t  Specify additional SSH options"
        print "                     \t  The format is 'opt=value' (e.g. l=stack)"
        print
        print "Required arguments:"
        print "  URL\t\t\t  The URL of the server."
        print "  method\t\t  The method name to call."
        print
        print "Environment Variables:"
        print "  SSHXMLRPC_DEBUG\t  Activate debugging for the listed aspects."
        print "                 \t  (e.g. all,config,connect,io,ssh)"
        print "  SSHXMLRPC_SSH\t\t  Specify the ssh command to use."
        print "  SSHXMLRPC_SSHKEYGEN\t  Specify the ssh-keygen command."
        print
        print "Examples:"
        print "  $ sshxmlrpc.py ssh://localhost/server.py"
        print
        print "Configuration:"
        print "  ssh command\t\t" + SSH_COMMAND
        print "    ( The '%(-X)s' portions of the command are substituted    )"
        print "    ( with the corresponding flags before the command is run. )"
        print "    ( Do not include them if your version of SSH does not     )"
        print "    ( fully support them.                                     )"
        print "  ssh-keygen command\t" + SSHKEYGEN_COMMAND
        return

    verbose = True
    user_agent = None
    ssh_identity = None
    ssh_opts = {}
    
    try:
        opts, extra = getopt.getopt(sys.argv[1:],
                                    "hVqu:i:s:",
                                    [ "help",
                                      "version",
                                      "quiet",
929 930 931
                                      "user-agent=",
                                      "identity=",
                                      "ssh-opts="])
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

        for opt, val in opts:
            if opt in ("-h", "--help"):
                usage()
                sys.exit()
                pass
            elif opt in ("-V", "--version"):
                print VERSION
                sys.exit()
                pass
            elif opt in ("-q", "--quiet"):
                verbose = False
                pass
            elif opt in ("-u", "--user-agent"):
                user_agent = val
                pass
            elif opt in ("-i", "--identity"):
                ssh_identity = val
                pass
            elif opt in ("-s", "--ssh-opts"):
                so = val.split("=")
                if len(so) == 2:
                    so_key, so_value = so
                    pass
                else:
                    so_key = so[0]
                    so_value = None
                    pass
                so_key = "-" + so_key
                if so_value:
                    ssh_opts[so_key] = so_key + " " + so_value
                    pass
                else:
                    ssh_opts[so_key] = so_key
                    pass
                pass
            else:
                assert not "unhandled option"
                pass
            pass
        pass
    except getopt.error, e:
        print e.args[0]
        usage()
        sys.exit(2)
        pass

    # Print usage if there are no arguments,
    if len(extra) == 0:
        usage()
        sys.exit()
        pass
    # ... check the URL, then
    elif not extra[0].startswith("ssh://"):
        print "Invalid url: " + extra[0]
        usage()
        sys.exit(2)
        pass
    # ... probe the URL or
    elif len(extra) == 1:
        try:
            st = SSHTransport(user_agent=user_agent,
                              ssh_identity=ssh_identity,
                              ssh_opts=ssh_opts)
            type, uri = urllib.splittype(extra[0])
            host, handler = urllib.splithost(uri)
            rc = st.probe(host, handler,
                          { "date" : time.ctime(time.time()) },
                          verbose)
            secs = time.mktime(time.strptime(rc["date"]))
            
            print "Probe results for: " + extra[0]
            print "  response time=%.2f s" % (time.time() - secs)
            print "Response Headers"
            for pair in rc.items():
                print "  %s: %s" % pair
                pass
            pass
        except BadResponse, e:
            print ("sshxmlrpc.py: error - bad response from "
                   + extra[0]
                   + "; "
                   + e[2])
            sys.exit(1)
            pass
        pass
    # ... call a method.
    else:
        try:
            sp = SSHServerProxy(extra[0],
                                ssh_identity=ssh_identity,
                                user_agent=user_agent,
                                ssh_opts=ssh_opts)
            method_name = extra[1]
            method_args = extra[2:]
            method = getattr(sp, method_name)
            print str(apply(method, method_args))
            pass
        except BadResponse, e:
            print ("sshxmlrpc.py: error - bad response from "
                   + extra[0]
                   + "; "
                   + e[2])
            sys.exit(1)
            pass
        pass
    pass