BasicXMLRPCServers.py.in 7.44 KB
Newer Older
1
#!/usr/local/bin/python
Mike Hibler's avatar
Mike Hibler committed
2 3
#
# Copyright (c) 2008 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{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/>.
# 
# }}}
Mike Hibler's avatar
Mike Hibler committed
23
# 
24 25

#
26
# A couple simple XMLRPC server extensions.
27 28 29 30 31 32 33 34 35 36 37 38 39 40
#

import os
import pwd
import xmlrpclib
import SimpleXMLRPCServer
import SocketServer
import sys
import types
import exceptions
import traceback

debug = True

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
# XXX: hack.
# Have to override the
# SimpleXMLRPCServer.SimpleXMLRPCDispatcher._marshaled_dispatch method
# so that we can marshal None values.  If SimpleXMLRPCDispatcher changes,
# this will need to be hacked so it complies again...
class AllowNoneOptXMLRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
    #
    # Taken straight from SimpleXMLRPCServer.py in the python stdlib.
    #
    def _marshaled_dispatch(self, data, dispatch_method = None):
        params, method = xmlrpclib.loads(data,)

        # generate response
        try:
            if dispatch_method is not None:
                response = dispatch_method(method, params)
            else:
                response = self._dispatch(method, params)
            # wrap response in a singleton tuple
            response = (response,)
            response = xmlrpclib.dumps(response, methodresponse=1,
                                       allow_none=self._allow_none)
        except Fault, fault:
            response = xmlrpclib.dumps(fault,allow_none=self._allow_none)
        except:
            # report exception back to server
            response = xmlrpclib.dumps(
                xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
                allow_none=self._allow_none
                )

        return response
    
    pass

class NetworkAuthFault(xmlrpclib.Fault):
77 78 79
    pass

class SimpleObjectXMLRPCServer(SocketServer.ThreadingMixIn,
80 81 82
                               SimpleXMLRPCServer.SimpleXMLRPCServer,
                               AllowNoneOptXMLRPCDispatcher,
                               object):
83 84 85 86 87 88 89 90 91 92 93
    """
    Extension to the simple xmlrpc server that registers member functions
    of a class as xmlrpc functions, so they can be called as
    <classname>.<method>.  The whole point is to be compatible with existing
    Emulab xmlrpc infrastructure (i.e., emulabserver.py classes).
    """
    def __init__(self,addr,**kwargs):
        super(SimpleObjectXMLRPCServer,self).__init__(addr,**kwargs)
        self.classfuncs = dict({})
        self.classinitargs = dict({})

94 95
        self._allow_none = True

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
        return

    """
    Register all non-private functions, or only the supplied method names,
    in a class as RPCs.  Passes initargs to __init__ on class instantiation.
    """
    def register_class_functions(self,myclass,methods=None,initargs=()):
        for f in dir(myclass):
            if (type(myclass.__dict__[f]) == types.FunctionType \
                and not f.startswith('_')) \
                or (methods != None and f in methods):
                myname = myclass.__name__ + "." + f
                self.register_function(myclass.__dict__[f],myname)
                self.classfuncs[myname] = myclass
                self.classinitargs[myname] = initargs
                pass
            pass
        return

    """
    Add class object instantiation prior to method calls on the object for
    rpc methods added via register_class_functions; else use normal _dispatch.
    """
    def _dispatch(self,method,params):
        if self.classfuncs.has_key(method):
            try:
                myclass = self.classfuncs[method]
                myargs = self.classinitargs[method]
                obj = myclass(*myargs)
                # ugh, nasty way to get reflectiveness
                return myclass.__dict__[self.funcs[method].func_name](obj,
                                                                      *params)
            except:
                traceback.print_exc()
            pass
        else:
            return super(SimpleObjectXMLRPCServer,self)._dispatch(method,params)
        pass

    pass

class InetAclXMLRPCServer(SimpleObjectXMLRPCServer):

    def __init__(self,addr,netacllist=[],**kwargs):
        super(InetAclXMLRPCServer,self).__init__(addr,**kwargs)

        self.acllist = []
        
        for acl in netacllist:
            explicitmask = False
            sa = acl.split('/')
            matchbits = 32
            if len(sa) > 1:
                explicitmask = True
                matchbits = int(sa[1])
                pass
            
            sa = sa[0].split('.')
            if sa[len(sa)-1] == '':
                sa[len(sa)-1] = 0
                pass
            if (len(sa) < 4):
                for i in range(len(sa)-1,4):
                    sa[i] = 0
                    pass
                pass
            # 192.168/16 == 192.168.0.0
            if not explicitmask:
                for i in range(len(sa)-1,-1,-1):
                    if (sa[i]) == 0:
                        matchbits = matchbits - 8
                    else:
                        break
                    pass
                # 0.0.0.0 == all
                if i == 0:
                    matchbits = 0
                    pass
                pass
                
            shiftamt = 24
            netbits = 0
            for i in range(0,4):
                netbits = netbits | ((int(sa[i]) & 0xff) << shiftamt)
                shiftamt -= 8
                pass

            mask = 0
            for i in range(31,matchbits-1,-1):
                mask |= (0x1 << i)
                pass

            # now we can check addresses via
            # if ((addr|netbits)&mask == netbits); then valid.
            if debug:
                print "allowing from %s: net=%s,mask=%s" \
                      % (str(acl),str(netbits),str(mask))
            self.acllist.append((netbits,mask))
            pass
        
        return

    def verify_request(self,request,client_address):
        if debug:
            print "request = '" + str(request) + "'"
            print "client_address = '" + str(client_address) + "'"
202 203 204 205 206 207 208 209
            pass

        if self.acllist == None or self.acllist == []:
            if debug:
                print "no acls, verify_request returning True"
                pass
            return True

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        (cip,cport) = client_address
        match = False
        clientbits = 0
        sa = cip.split('.')
        shiftamt = 24
        for i in range(0,len(sa)):
            clientbits = clientbits | (int(sa[i]) << shiftamt)
            shiftamt = shiftamt - 8
            pass

        if debug:
            print "client "+cip+": clientbits="+str(clientbits)
        
        for (netbits,mask) in self.acllist:
            if clientbits & mask == netbits & mask:
                match = True
                break
            pass
        if debug:
            print "verify_request returning " + str(match)
        
        return match

    pass