diff options
author | Karl MacMillan <kmacmillan@mentalrootkit.com> | 2007-07-31 12:09:38 -0400 |
---|---|---|
committer | Karl MacMillan <kmacmillan@mentalrootkit.com> | 2007-07-31 12:09:38 -0400 |
commit | 7d95cd612c1b340add692038c835e7cd8d8ad18b (patch) | |
tree | 144813760c6ff19d85285496293270385af74fde /ipa-server/xmlrpc-server | |
parent | 1d8d4222ab05ee7cf84203d4917174f7fbca1200 (diff) | |
download | freeipa.git-7d95cd612c1b340add692038c835e7cd8d8ad18b.tar.gz freeipa.git-7d95cd612c1b340add692038c835e7cd8d8ad18b.tar.xz freeipa.git-7d95cd612c1b340add692038c835e7cd8d8ad18b.zip |
Final reorginzation to reflect packaging.
Diffstat (limited to 'ipa-server/xmlrpc-server')
-rw-r--r-- | ipa-server/xmlrpc-server/Makefile | 12 | ||||
-rw-r--r-- | ipa-server/xmlrpc-server/README | 0 | ||||
-rw-r--r-- | ipa-server/xmlrpc-server/funcs.py | 170 | ||||
-rw-r--r-- | ipa-server/xmlrpc-server/ipa.conf | 24 | ||||
-rw-r--r-- | ipa-server/xmlrpc-server/ipaxmlrpc.py | 274 |
5 files changed, 480 insertions, 0 deletions
diff --git a/ipa-server/xmlrpc-server/Makefile b/ipa-server/xmlrpc-server/Makefile new file mode 100644 index 00000000..10b796ea --- /dev/null +++ b/ipa-server/xmlrpc-server/Makefile @@ -0,0 +1,12 @@ +SHAREDIR = $(DESTDIR)/usr/share/ipa/ipaserver +HTTPDIR = $(DESTDIR)/etc/httpd/conf.d/ + +all: ; + +install: + -mkdir -p $(SHAREDIR) + install -m 644 *.py $(SHAREDIR) + install -m 644 ipa.conf $(HTTPDIR) + +clean: + rm -f *~ *.pyc diff --git a/ipa-server/xmlrpc-server/README b/ipa-server/xmlrpc-server/README new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/ipa-server/xmlrpc-server/README diff --git a/ipa-server/xmlrpc-server/funcs.py b/ipa-server/xmlrpc-server/funcs.py new file mode 100644 index 00000000..78180a49 --- /dev/null +++ b/ipa-server/xmlrpc-server/funcs.py @@ -0,0 +1,170 @@ +# Authors: Rob Crittenden <rcritten@redhat.com> +# +# Copyright (C) 2007 Red Hat +# see file 'COPYING' for use and warranty information +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; version 2 only +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import sys +sys.path.append("/usr/share/ipa") + +import ldap +import ipaserver.dsinstance +import ipaserver.ipaldap +import pdb +import string +from types import * +import xmlrpclib + +# FIXME, this needs to be auto-discovered +host = 'localhost' +port = 389 +binddn = "cn=directory manager" +bindpw = "freeipa" + +basedn = "dc=greyoak,dc=com" +scope = ldap.SCOPE_SUBTREE + +def get_user (username): + """Get a specific user's entry. Return as a dict of values. + Multi-valued fields are represented as lists. + """ + ent="" + + # FIXME: Is this the filter we want or should it be more specific? + filter = "(uid=" username ")" + try: + m1 = ipaserver.ipaldap.IPAdmin(host,port,binddn,bindpw) + ent = m1.getEntry(basedn, scope, filter, None) + except ldap.LDAPError, e: + raise xmlrpclib.Fault(1, e) + except ipaserver.ipaldap.NoSuchEntryError: + raise xmlrpclib.Fault(2, "No such user") + + # Convert to LDIF + entry = str(ent) + + # Strip off any junk + entry = entry.strip() + + # Don't need to identify binary fields and this breaks the parser so + # remove double colons + entry = entry.replace('::', ':') + specs = [spec.split(':') for spec in entry.split('\n')] + + # Convert into a dict. We need to handle multi-valued attributes as well + # so we'll convert those into lists. + user={} + for (k,v) in specs: + k = k.lower() + if user.get(k) is not None: + if isinstance(user[k],list): + user[k].append(v.strip()) + else: + first = user[k] + user[k] = [] + user[k].append(first) + user[k].append(v.strip()) + else: + user[k] = v.strip() + + return user +# return str(ent) # return as LDIF + +def add_user (user): + """Add a user in LDAP""" + dn="uid=%s,ou=users,ou=default,dc=greyoak,dc=com" % user['uid'] + entry = ipaserver.ipaldap.Entry(dn) + + # some required objectclasses + entry.setValues('objectClass', 'top', 'posixAccount', 'shadowAccount', 'account', 'person', 'inetOrgPerson', 'organizationalPerson', 'krbPrincipalAux', 'krbTicketPolicyAux') + + # Fill in shadow fields + entry.setValue('shadowMin', '0') + entry.setValue('shadowMax', '99999') + entry.setValue('shadowWarning', '7') + entry.setValue('shadowExpire', '-1') + entry.setValue('shadowInactive', '-1') + entry.setValue('shadowFlag', '-1') + + # FIXME: calculate shadowLastChange + + # fill in our new entry with everything sent by the user + for u in user: + entry.setValues(u, user[u]) + + try: + m1 = ipaserver.ipaldap.IPAdmin(host,port,binddn,bindpw) + res = m1.addEntry(entry) + return res + except ldap.ALREADY_EXISTS: + raise xmlrpclib.Fault(3, "User already exists") + return None + except ldap.LDAPError, e: + raise xmlrpclib.Fault(1, str(e)) + return None + +def get_add_schema (): + """Get the list of fields to be used when adding users in the GUI.""" + + # FIXME: this needs to be pulled from LDAP + fields = [] + + field1 = { + "name": "uid" , + "label": "Login:", + "type": "text", + "validator": "text", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "userPassword" , + "label": "Password:", + "type": "password", + "validator": "String", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "gn" , + "label": "First name:", + "type": "text", + "validator": "string", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "sn" , + "label": "Last name:", + "type": "text", + "validator": "string", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "mail" , + "label": "E-mail address:", + "type": "text", + "validator": "email", + "required": "true" + } + fields.append(field1) + + return fields diff --git a/ipa-server/xmlrpc-server/ipa.conf b/ipa-server/xmlrpc-server/ipa.conf new file mode 100644 index 00000000..5a130418 --- /dev/null +++ b/ipa-server/xmlrpc-server/ipa.conf @@ -0,0 +1,24 @@ +# LoadModule auth_kerb_module modules/mod_auth_kerb.so + +Alias /ipa "/usr/share/ipa/ipaserver/XMLRPC" + +<Directory "/usr/share/ipaserver"> +# AuthType Kerberos +# AuthName "Kerberos Login" +# KrbMethodNegotiate on +# KrbMethodK5Passwd off +# KrbServiceName HTTP +# KrbAuthRealms GREYOAK.COM +# Krb5KeyTab /etc/httpd/conf/ipa.keytab +# KrbSaveCredentials on +# Require valid-user + ErrorDocument 401 /errors/unauthorized.html + + SetHandler mod_python + PythonHandler ipaxmlrpc + + PythonDebug Off + + # this is pointless to use since it would just reload ipaxmlrpc.py + PythonAutoReload Off +</Directory> diff --git a/ipa-server/xmlrpc-server/ipaxmlrpc.py b/ipa-server/xmlrpc-server/ipaxmlrpc.py new file mode 100644 index 00000000..1dc15956 --- /dev/null +++ b/ipa-server/xmlrpc-server/ipaxmlrpc.py @@ -0,0 +1,274 @@ +# mod_python script + +# ipaxmlrpc - an XMLRPC interface for ipa. +# Copyright (c) 2007 Red Hat +# +# IPA is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; +# version 2.1 of the License. +# +# This software 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this software; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +# Based on kojixmlrpc - an XMLRPC interface for koji by +# Mike McLean <mikem@redhat.com> +# +# Authors: +# Rob Crittenden <rcritten@redhat.com> + +import sys +import time +import traceback +import pprint +from xmlrpclib import Marshaller,loads,dumps,Fault +from mod_python import apache + +import ipaserver +import funcs +import string +import base64 + +# +# An override so we can base64 encode all outgoing values. +# This is set by calling: Marshaller._Marshaller__dump = xmlrpclib_dump +# +# Not currently used. +# +def xmlrpclib_escape(s, replace = string.replace): + """ + xmlrpclib only handles certain characters. Lets encode the whole + blob + """ + + return base64.encodestring(s) + +def xmlrpclib_dump(self, value, write): + """ + xmlrpclib cannot marshal instances of subclasses of built-in + types. This function overrides xmlrpclib.Marshaller.__dump so that + any value that is an instance of one of its acceptable types is + marshalled as that type. + + xmlrpclib also cannot handle invalid 7-bit control characters. See + above. + """ + + # Use our escape function + args = [self, value, write] + if isinstance(value, (str, unicode)): + args.append(xmlrpclib_escape) + + try: + # Try for an exact match first + f = self.dispatch[type(value)] + except KeyError: + # Try for an isinstance() match + for Type, f in self.dispatch.iteritems(): + if isinstance(value, Type): + f(*args) + return + raise TypeError, "cannot marshal %s objects" % type(value) + else: + f(*args) + + +class ModXMLRPCRequestHandler(object): + """Simple XML-RPC handler for mod_python environment""" + + def __init__(self): + self.funcs = {} + self.traceback = False + #introspection functions + self.register_function(self.list_api, name="_listapi") + self.register_function(self.system_listMethods, name="system.listMethods") + self.register_function(self.system_methodSignature, name="system.methodSignature") + self.register_function(self.system_methodHelp, name="system.methodHelp") + self.register_function(self.multiCall) + + def register_function(self, function, name = None): + if name is None: + name = function.__name__ + self.funcs[name] = function + + def register_module(self, instance, prefix=None): + """Register all the public functions in an instance with prefix prepended + + For example + h.register_module(exports,"pub.sys") + will register the methods of exports with names like + pub.sys.method1 + pub.sys.method2 + ...etc + """ + for name in dir(instance): + if name.startswith('_'): + continue + function = getattr(instance, name) + if not callable(function): + continue + if prefix is not None: + name = "%s.%s" %(prefix,name) + self.register_function(function, name=name) + + def register_instance(self,instance): + self.register_module(instance) + + def _marshaled_dispatch(self, data): + """Dispatches an XML-RPC method from marshalled (XML) data.""" + + params, method = loads(data) + + # special case +# if method == "get_user": +# Marshaller._Marshaller__dump = xmlrpclib_dump + + start = time.time() + # generate response + try: + response = self._dispatch(method, params) + # wrap response in a singleton tuple + response = (response,) + response = dumps(response, methodresponse=1, allow_none=1) + except Fault, fault: + self.traceback = True + response = dumps(fault) + except: + self.traceback = True + # report exception back to server + e_class, e = sys.exc_info()[:2] + faultCode = getattr(e_class,'faultCode',1) + tb_str = ''.join(traceback.format_exception(*sys.exc_info())) + faultString = tb_str + response = dumps(Fault(faultCode, faultString)) + + return response + + def _dispatch(self,method,params): + func = self.funcs.get(method,None) + if func is None: + raise Fault(1, "Invalid method: %s" % method) + params,opts = ipaserver.decode_args(*params) + + ret = func(*params,**opts) + + return ret + + def multiCall(self, calls): + """Execute a multicall. Execute each method call in the calls list, collecting + results and errors, and return those as a list.""" + results = [] + for call in calls: + try: + result = self._dispatch(call['methodName'], call['params']) + except Fault, fault: + results.append({'faultCode': fault.faultCode, 'faultString': fault.faultString}) + except: + # transform unknown exceptions into XML-RPC Faults + # don't create a reference to full traceback since this creates + # a circular reference. + exc_type, exc_value = sys.exc_info()[:2] + faultCode = getattr(exc_type, 'faultCode', 1) + faultString = ', '.join(exc_value.args) + trace = traceback.format_exception(*sys.exc_info()) + # traceback is not part of the multicall spec, but we include it for debugging purposes + results.append({'faultCode': faultCode, 'faultString': faultString, 'traceback': trace}) + else: + results.append([result]) + + return results + + def list_api(self): + funcs = [] + for name,func in self.funcs.items(): + #the keys in self.funcs determine the name of the method as seen over xmlrpc + #func.__name__ might differ (e.g. for dotted method names) + args = self._getFuncArgs(func) + funcs.append({'name': name, + 'doc': func.__doc__, + 'args': args}) + return funcs + + def _getFuncArgs(self, func): + args = [] + for x in range(0, func.func_code.co_argcount): + if x == 0 and func.func_code.co_varnames[x] == "self": + continue + if func.func_defaults and func.func_code.co_argcount - x <= len(func.func_defaults): + args.append((func.func_code.co_varnames[x], func.func_defaults[x - func.func_code.co_argcount len(func.func_defaults)])) + else: + args.append(func.func_code.co_varnames[x]) + return args + + def system_listMethods(self): + return self.funcs.keys() + + def system_methodSignature(self, method): + #it is not possible to autogenerate this data + return 'signatures not supported' + + def system_methodHelp(self, method): + func = self.funcs.get(method) + if func is None: + return "" + arglist = [] + for arg in self._getFuncArgs(func): + if isinstance(arg,str): + arglist.append(arg) + else: + arglist.append('%s=%s' % (arg[0], arg[1])) + ret = '%s(%s)' % (method, ", ".join(arglist)) + if func.__doc__: + ret = "\ndescription: %s" % func.__doc__ + return ret + + def handle_request(self,req): + """Handle a single XML-RPC request""" + + # XMLRPC uses POST only. Reject anything else + if req.method != 'POST': + req.allow_methods(['POST'],1) + raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED + + response = self._marshaled_dispatch(req.read()) + + req.content_type = "text/xml" + req.set_content_length(len(response)) + req.write(response) + + +# +# mod_python handler +# + +def handler(req, profiling=False): + if profiling: + import profile, pstats, StringIO, tempfile + global _profiling_req + _profiling_req = req + temp = tempfile.NamedTemporaryFile() + profile.run("import ipxmlrpc; ipaxmlrpc.handler(ipaxmlrpc._profiling_req, False)", temp.name) + stats = pstats.Stats(temp.name) + strstream = StringIO.StringIO() + sys.stdout = strstream + stats.sort_stats("time") + stats.print_stats() + req.write("<pre>" strstream.getvalue() "</pre>") + _profiling_req = None + else: + opts = req.get_options() + try: + h = ModXMLRPCRequestHandler() + h.register_function(funcs.get_user) + h.register_function(funcs.add_user) + h.register_function(funcs.get_add_schema) + h.handle_request(req) + finally: + pass + return apache.OK |