sshxmlrpc.py 32.8 KB
Newer Older
Timothy Stack's avatar
Timothy Stack committed
1 2
#! /usr/bin/env python

3 4
#
# Copyright (c) 2004 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{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/>.
# 
# }}}
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
# 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.
# --------------------------------------------------------------------
#
54 55 56 57
import sys
import types
import urllib
import popen2
58
import rfc822
59
import xmlrpclib
Timothy Stack's avatar
Timothy Stack committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
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)
89

90
if os.name != "nt":
Timothy Stack's avatar
Timothy Stack committed
91
    import syslog
92
    LOG_TESTBED = syslog.LOG_LOCAL5;
Timothy Stack's avatar
Timothy Stack committed
93
    pass
94

95 96
import traceback

Timothy Stack's avatar
Timothy Stack committed
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 207 208 209 210 211 212 213 214


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



215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
##
# 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

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
##
# 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

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
##
# 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.
    # 
Timothy Stack's avatar
Timothy Stack committed
271 272
    def __init__(self, host, handler, streams=None, ssh_config=None,
                 ssh_identity=None, ssh_opts={}):
273 274 275
        # Store information about the peer and
        self.handler = handler
        self.host = host
Timothy Stack's avatar
Timothy Stack committed
276
        self.last_lines = []
277 278 279 280 281

        # ... initialize the read and write file objects.
        if streams:
            self.rfile = streams[0]
            self.wfile = streams[1]
Timothy Stack's avatar
Timothy Stack committed
282 283
            self.errfile = None
            self.closed = False
284 285
            pass
        else:
Timothy Stack's avatar
Timothy Stack committed
286 287 288 289 290
            if not conf_passphraseless_login(ssh_identity):
                sys.stderr.write("sshxmlrpc.py: warning - No agent or "
                                 "passphrase-less key found, "
                                 "continuing anyways...\n")
                pass
291
            
Timothy Stack's avatar
Timothy Stack committed
292
            self.user, ssh_host = urllib.splituser(self.host)
293

Timothy Stack's avatar
Timothy Stack committed
294 295 296
            all_opts = { "-l" : "", "-i" : "", "-F" : "", "-v" : "",
                         "-1" : "", "-2" : "" }
            all_opts.update(ssh_opts)
297
            if self.user:
Timothy Stack's avatar
Timothy Stack committed
298
                all_opts["-l"] = "-l " + self.user
299
                pass
Timothy Stack's avatar
Timothy Stack committed
300 301
            if ssh_identity:
                all_opts["-i"] = "-i " + ssh_identity
302
                pass
Timothy Stack's avatar
Timothy Stack committed
303 304
            if ssh_config:
                all_opts["-F"] = "-F " + ssh_config
305
                pass
Timothy Stack's avatar
Timothy Stack committed
306 307
            if "ssh" in SSHXMLRPC_DEBUG:
                all_opts["-v"] = "-vvv"
308
                pass
Timothy Stack's avatar
Timothy Stack committed
309 310 311 312 313 314 315 316 317
            
            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
318
            pass
Timothy Stack's avatar
Timothy Stack committed
319
        
320 321 322 323 324 325 326
        return

    ##
    # @param len The amount of data to read. (Default: 1024)
    # @return The amount of data read.
    #
    def read(self, len=1024):
Timothy Stack's avatar
Timothy Stack committed
327 328 329 330
        retval = self.rfile.read(len)

        __sxrdebug__("io", "read - ", retval)
        return retval
331 332 333 334 335

    ##
    # @return A line of data or None if there is no more input.
    #
    def readline(self):
Timothy Stack's avatar
Timothy Stack committed
336 337 338 339 340 341 342 343 344 345 346 347 348
        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
349 350 351 352 353 354

    ##
    # @param stuff The data to send to the other side.
    # @return The amount of data written.
    #
    def write(self, stuff):
Timothy Stack's avatar
Timothy Stack committed
355 356
        __sxrdebug__("io", "write - ", stuff)
        
357 358 359 360 361 362
        return self.wfile.write(stuff)

    ##
    # Flush any write buffers.
    #
    def flush(self):
Timothy Stack's avatar
Timothy Stack committed
363 364
        __sxrdebug__("io", "flush")
        
365 366 367 368 369 370 371
        self.wfile.flush()
        return

    ##
    # Close the connection.
    #
    def close(self):
Timothy Stack's avatar
Timothy Stack committed
372 373
        __sxrdebug__("connect", "close - ", self.host)
        
374
        self.wfile.close()
375
        self.rfile.close()
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
        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

Timothy Stack's avatar
Timothy Stack committed
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 428 429 430 431 432 433 434 435
    ##
    # 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

436 437 438 439 440 441 442
    def __repr__(self):
        return "<SSHConnection %s%s>" % (self.host, self.handler)

    __str__ = __repr__

    pass

443 444 445 446
##
# Use SSH to transport XML-RPC requests/responses
#
class SSHTransport:
447 448 449

    ##
    # @param ssh_config The ssh config file to use when making new connections.
450 451
    # @param user_agent Symbolic name for the program acting on behalf of the
    #   user.
Timothy Stack's avatar
Timothy Stack committed
452
    # @param ssh_opts List of additional options to pass to SSH_COMMAND.
453
    #
Timothy Stack's avatar
Timothy Stack committed
454 455
    def __init__(self, ssh_config=None, user_agent=None, ssh_identity=None,
                 ssh_opts={}):
456 457
        self.connections = {}
        self.ssh_config = ssh_config
Timothy Stack's avatar
Timothy Stack committed
458 459 460 461 462 463 464 465
        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
466
        return
467

Timothy Stack's avatar
Timothy Stack committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    ##
    # 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))
487
            pass
Timothy Stack's avatar
Timothy Stack committed
488 489 490 491 492
        connection.endheaders()
        connection.flush()

        return self.parse_headers(connection, verbose=verbose)

493 494 495 496
    ##
    # Send a request to the destination.
    #
    # @param host The host name on which to execute the request
497
    # @param handler The python file that will handle the request.
498
    # @param request_body The XML-RPC encoded request.
Timothy Stack's avatar
Timothy Stack committed
499
    # @return The value returned by the peer method.
500
    #
Timothy Stack's avatar
Timothy Stack committed
501 502
    def request(self, host, handler, request_body, path=None):
        handler = self.munge_handler(handler, path)
503

504
        # Try to get a new connection,
Timothy Stack's avatar
Timothy Stack committed
505
        connection = self.get_connection((host,handler))
506

507
        # ... send our request, and
Timothy Stack's avatar
Timothy Stack committed
508
        connection.putheader("user-agent", self.user_agent)
509
        connection.putheader("content-length", len(request_body))
510
        connection.putheader("content-type", "text/xml")
511 512 513
        connection.endheaders()
        connection.write(request_body)
        connection.flush()
514

515 516
        # ... parse the response.
        retval = self.parse_response(connection)
517 518 519 520 521 522 523 524 525

        return retval

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

Timothy Stack's avatar
Timothy Stack committed
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 559 560 561 562
    ##
    # 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]

563 564 565 566 567 568 569
    ##
    # @param connection The connection to drop.
    #
    def drop_connection(self, connection):
        del self.connections[(connection.host,connection.handler)]
        connection.close()
        return
Timothy Stack's avatar
Timothy Stack committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

    ##
    # 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
593
    
594 595 596 597 598
    ##
    # Parse the response from the server.
    #
    # @return The python value returned by the server method.
    #
599
    def parse_response(self, connection):
600 601
        parser, unmarshaller = self.getparser()

602 603
        try:
            # Get the headers,
Timothy Stack's avatar
Timothy Stack committed
604 605
            headers = self.parse_headers(connection)
            
606 607 608 609 610
            # ... the length of the body, and
            length = int(headers['content-length'])
            # ... read in the body.
            response = connection.read(length)
        except KeyError, e:
Timothy Stack's avatar
Timothy Stack committed
611 612 613 614
            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, ">> ")
615
            # Bad header, drop the connection, and
616
            self.drop_connection(connection)
617
            # ... tell the user.
618
            raise BadResponse(connection.host, connection.handler, e.args[0])
Timothy Stack's avatar
Timothy Stack committed
619

620
        parser.feed(response)
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637

        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.
Timothy Stack's avatar
Timothy Stack committed
638 639
    # @param probe_response The value to send back to clients in the
    # 'probe-response' header.
640
    #
Timothy Stack's avatar
Timothy Stack committed
641 642 643
    def __init__(self, object, probe_response=None):
        self.ssh_connection = os.environ.get(
            "SSH_CONNECTION", "stdin 0 stdout 0").split()
644
        self.myObject = object
Timothy Stack's avatar
Timothy Stack committed
645 646 647 648
        self.probe_response = probe_response
        if self.probe_response is None:
            self.probe_response = sys.argv[0] + " " + str(VERSION)
            pass
649 650 651 652

        #
        # Init syslog
        #
653 654 655 656 657
        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]);
Timothy Stack's avatar
Timothy Stack committed
658 659
            pass
        
660 661 662 663 664 665 666
        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.
    #
667
    # @param connection An initialized SSHConnection object.
668
    #
669 670
    def handle_request(self, connection):
        retval = False
671
        try:
Timothy Stack's avatar
Timothy Stack committed
672
            # Read the request headers,
673
            hdrs = SSHMessage(connection, False)
Timothy Stack's avatar
Timothy Stack committed
674 675

            # ... make sure they are sane,
676
            if hdrs.status != "":
Timothy Stack's avatar
Timothy Stack committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
                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
701
            if not hdrs.has_key('content-length'):
Timothy Stack's avatar
Timothy Stack committed
702 703 704
                sys.stderr.write("server error: expecting content-length "
                                 "header, received:\n")
                connection.dump_last_lines(sys.stderr, "<< ")
705 706
                raise BadRequest(connection.host,
                                 "missing content-length header")
Timothy Stack's avatar
Timothy Stack committed
707

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

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

769
        return retval
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    ##
    # 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()
788 789 790
            if os.name != "nt":
                syslog.syslog(syslog.LOG_INFO, "Connection closed");
                syslog.closelog()
Timothy Stack's avatar
Timothy Stack committed
791
                pass
792 793
            pass
        return
Timothy Stack's avatar
Timothy Stack committed
794 795 796

    def serve_stdio_forever(self):
        return self.serve_forever((sys.stdin, sys.stdout))
797
    
798 799 800 801
    pass


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

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

        if transport is None:
Timothy Stack's avatar
Timothy Stack committed
832 833 834
            transport = SSHTransport(user_agent=user_agent,
                                     ssh_identity=ssh_identity,
                                     ssh_opts=ssh_opts)
835 836 837 838 839
            pass
        
        self.__transport = transport

        self.__encoding = encoding
840
        self.__path = path
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        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,
858
            path=self.__path
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
            )

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

880 881 882 883
    # Locally handle "if not server:".
    def __nonzero__(self):
        return True

884
    pass
Timothy Stack's avatar
Timothy Stack committed
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 929 930 931 932 933 934 935 936

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",
937 938 939
                                      "user-agent=",
                                      "identity=",
                                      "ssh-opts="])
Timothy Stack's avatar
Timothy Stack committed
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 1039 1040 1041 1042 1043 1044 1045 1046

        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