sslxmlrpc_client.py.in 8.36 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#! /usr/bin/env python
#
# EMULAB-COPYRIGHT
# Copyright (c) 2004 University of Utah and the Flux Group.
# All rights reserved.
# 
# 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.
#

import sys
import getopt
19 20 21 22 23 24 25 26 27 28
import os, os.path
import xmlrpclib

TBROOT = "@prefix@"
TBPATH = os.path.join(TBROOT, "lib")

if TBPATH not in sys.path:
    sys.path.append(TBPATH)
    pass

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
from emulabclient import *

from M2Crypto.m2xmlrpclib import SSL_Transport
from M2Crypto import SSL

##
# The package version number
#
PACKAGE_VERSION = 0.1

# Default server and port
XMLRPC_SERVER   = "@BOSSNODE@"
XMLRPC_PORT     = 3069

# User supplied server name.
xmlrpc_server   = XMLRPC_SERVER
xmlrpc_port     = XMLRPC_PORT

# The default RPC module to invoke.
module          = "experiment"

50 51 52
# The default path
path            = TBROOT

53 54 55
# Where to find the default certificate in the users home dir.
default_cert    = "/.ssl/emulab.pem"
certificate     = None;
56 57 58 59

# Debugging output.
debug           = 0

60 61 62
# Raw XML mode
rawmode         = 0

63 64 65 66 67 68
##
# Print the usage statement to stdout.
#
def usage():
    print "Make a request to the Emulab XML-RPC (SSL-based) server."
    print ("Usage: " + sys.argv[0] 
69
                     + " [-hV] [-s server] [-m module] "
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                     + "<method> [param=value ...]")
    print
    print "Options:"
    print "  -h, --help\t\t  Display this help message"
    print "  -V, --version\t\t  Show the version number"
    print "  -s, --server\t\t  Set the server hostname"
    print "  -p, --port\t\t  Set the server port"
    print "  -c, --cert\t\t  Set the certificate to use"
    print "  -m, --module\t\t  Set the RPC module (defaults to experiment)"
    print
    print "Required arguments:"
    print "  method\t\t  The method to execute on the server"
    print "  params\t\t\t  The method arguments in param=value format"
    print
    print "Example:"
    print ("  "
           + sys.argv[0]
           + " -s boss.emulab.net echo \"Hello World!\"")
    return

#
# Process a single command line
#
def do_method(server, method_and_args):
    # Get a pointer to the function we want to invoke.
    methodname = method_and_args[0]
    if methodname.count(".") == 0:
        methodname = module + "." + methodname
        pass
    
    meth = getattr(server, methodname)

    # Pop off the method, and then convert the rest of the arguments.
    # Be sure to add the version.
    method_and_args.pop(0)

    #
    # Convert all params (name=value) into a Dictionary. 
    # 
    params = {}
    for param in method_and_args:
        plist = string.split(param, "=", 1)
        if len(plist) != 2:
            print ("error: Parameter, '"
                   + param
                   + "', is not of the form: param=value!")
            return -1
        value = plist[1]

        #
        # If the first character of the argument looks like a dictionary,
        # try to evaluate it.
        #
123 124 125
        if value.startswith("{"):
            value = eval(value);
            pass
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
    
        params[plist[0]] = value
        pass
    meth_args = [ PACKAGE_VERSION, params ]

    #
    # Make the call. 
    #
    try:
        response = apply(meth, meth_args)
        pass
    except xmlrpclib.Fault, e:
        print e.faultString
        return -1

    #
    # Parse the Response, which is a Dictionary. See EmulabResponse in the
    # emulabclient.py module. The XML standard converts classes to a plain
    # Dictionary, hence the code below. 
    # 
    if len(response["output"]):
        print response["output"]
        pass

    rval = response["code"]

    #
    # If the code indicates failure, look for a "value". Use that as the
    # return value instead of the code. 
    # 
    if rval != RESPONSE_SUCCESS:
        if response["value"]:
            rval = response["value"]
            pass
        pass

    if debug and response["value"]:
        print str(response["value"])
        pass
        
    return rval

#
# Process program arguments.
# 
try:
    # Parse the options,
    opts, req_args =  getopt.getopt(sys.argv[1:],
174
                      "dhVc:s:m:p:r",
175
                      [ "help", "version", "rawmode", "server=", "module=",
176
                        "cert=", "port=", "path="])
177 178 179 180 181 182 183 184 185 186 187 188
    # ... act on them appropriately, and
    for opt, val in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
            pass
        elif opt in ("-V", "--version"):
            print PACKAGE_VERSION
            sys.exit()
            pass
        elif opt in ("-s", "--server"):
	    xmlrpc_server = val
189 190 191 192 193 194
            #
            # Allow port spec here too.
            #
            if val.find(":") > 0:
                xmlrpc_server,xmlrpc_port = string.split(val, ":", 1)
                pass
195 196 197 198 199 200 201 202 203 204 205 206 207
            pass
        elif opt in ("-p", "--port"):
	    xmlrpc_port = val
            pass
        elif opt in ("-c", "--cert"):
	    certificate = val
            pass
        elif opt in ("-m", "--module"):
	    module = val
            pass
        elif opt in ("-d", "--debug"):
	    debug = 1
            pass
208 209 210
        elif opt in ("--path",):
	    path = val
            pass
211 212 213
        elif opt in ("-r", "--rawmode"):
	    rawmode = 1
            pass
214 215 216 217 218 219 220 221
        pass
    pass
except getopt.error, e:
    print e.args[0]
    usage()
    sys.exit(2)
    pass

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
class MySSL_Transport(SSL_Transport):
    def _parse_response(self, file, sock):
        stuff = ""
        
        while 1:
            if sock:
                response = sock.recv(1024)
            else:
                response = file.read(1024)
            if not response:
                break
            stuff += response
        return stuff
        pass
    pass

class MyServerProxy(xmlrpclib.ServerProxy):
    def raw_request(self, xmlgoo):

        #
        # I could probably play tricks with the getattr method, but
        # not sure what those tricks would be! If I try to access the
        # members by name, the getattr definition in the ServerProxy class
        # tries to turn that into a method lookup at the other end. 
        #
        transport = self.__dict__["_ServerProxy__transport"]
        host      = self.__dict__["_ServerProxy__host"]
        handler   = self.__dict__["_ServerProxy__handler"]
        
        response = transport.request(host, handler, xmlgoo)

        if len(response) == 1:
            response = response[0]

        return response

    pass

260 261 262
#
# Vanilla SSL CTX initialization.
#
263 264 265
if certificate == None:
    certificate = os.environ["HOME"] + default_cert
    pass
266 267 268 269 270 271 272 273 274 275 276
if not os.access(certificate, os.R_OK):
    print "Certificate cannot be accessed: " + certificate
    sys.exit(-1);
    pass
    
ctx = SSL.Context('sslv23')
ctx.load_cert(certificate, certificate)
ctx.set_verify(SSL.verify_none, 16)
ctx.set_allow_unknown_ca(0)

# This is parsed by the Proxy object.
277
URI = "https://" + xmlrpc_server + ":" + str(xmlrpc_port) + path
278
if debug:
279
    print >>sys.stderr, URI
280
    pass
281

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
if rawmode:
    # Get a handle on the server,
    server = MyServerProxy(URI, MySSL_Transport(ctx));

    stuff = ""
    while (True):
        foo = sys.stdin.read(1024 * 16)
        if foo == "":
            break
        stuff += foo
        pass

    #
    # Make the call. 
    #
    try:
        response = server.raw_request(stuff)
        pass
    except xmlrpclib.Fault, e:
        print e.faultString
        sys.exit(-1);
        pass
304

305 306 307 308 309
    print str(response);
    sys.exit(0);
elif len(req_args):
    # Get a handle on the server,
    server = xmlrpclib.ServerProxy(URI, SSL_Transport(ctx));
310 311 312
    # Method and args are on the command line.
    sys.exit(do_method(server, req_args))
else:
313 314
    # Get a handle on the server,
    server = xmlrpclib.ServerProxy(URI, SSL_Transport(ctx));
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    # Prompt the user for input.
    try:
        while True:
            line = raw_input("$ ")
            tokens = line.split(" ")
            if len(tokens) >= 1 and len(tokens[0]) > 0:
                print str(do_method(server, tokens))
                pass
            pass
        pass
    except EOFError:
        pass
    print
    pass