avoid as much as possible accessing logger through class instances, whenever that...
[sfa.git] / sfa / server / xmlrpcapi.py
1 #
2 # SFA XML-RPC and SOAP interfaces
3 #
4
5 import string
6
7 # SOAP support is optional
8 try:
9     import SOAPpy
10     from SOAPpy.Parser import parseSOAPRPC
11     from SOAPpy.Types import faultType
12     from SOAPpy.NS import NS
13     from SOAPpy.SOAPBuilder import buildSOAP
14 except ImportError:
15     SOAPpy = None
16
17 ####################
18 #from sfa.util.faults import SfaNotImplemented, SfaAPIError, SfaInvalidAPIMethod, SfaFault
19 from sfa.util.faults import SfaInvalidAPIMethod, SfaAPIError, SfaFault
20 from sfa.util.sfalogging import logger
21 from sfa.util.py23 import xmlrpc_client
22
23 ####################
24 # See "2.2 Characters" in the XML specification:
25 #
26 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
27 # avoiding
28 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
29
30 invalid_codepoints = range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F)
31 # broke with f24, somehow we get a unicode as an incoming string to be translated
32 str_xml_escape_table = string.maketrans("".join((chr(x) for x in invalid_codepoints)),
33                                         "?" * len(invalid_codepoints))
34 # loosely inspired from
35 # http://stackoverflow.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings
36 unicode_xml_escape_table = { invalid : u"?" for invalid in invalid_codepoints}
37
38 def xmlrpclib_escape(s, replace = string.replace):
39     """
40     xmlrpclib does not handle invalid 7-bit control characters. This
41     function augments xmlrpclib.escape, which by default only replaces
42     '&', '<', and '>' with entities.
43     """
44
45     # This is the standard xmlrpclib.escape function
46     s = replace(s, "&", "&amp;")
47     s = replace(s, "<", "&lt;")
48     s = replace(s, ">", "&gt;",)
49
50     # Replace invalid 7-bit control characters with '?'
51     if isinstance(s, str):
52         return s.translate(str_xml_escape_table)
53     else:
54         return s.translate(unicode_xml_escape_table)
55
56
57 def xmlrpclib_dump(self, value, write):
58     """
59     xmlrpclib cannot marshal instances of subclasses of built-in
60     types. This function overrides xmlrpclib.Marshaller.__dump so that
61     any value that is an instance of one of its acceptable types is
62     marshalled as that type.
63
64     xmlrpclib also cannot handle invalid 7-bit control characters. See
65     above.
66     """
67
68     # Use our escape function
69     args = [self, value, write]
70     if isinstance(value, (str, unicode)):
71         args.append(xmlrpclib_escape)
72
73     try:
74         # Try for an exact match first
75         f = self.dispatch[type(value)]
76     except KeyError:
77         raise
78         # Try for an isinstance() match
79         for Type, f in self.dispatch.iteritems():
80             if isinstance(value, Type):
81                 f(*args)
82                 return
83         raise TypeError("cannot marshal %s objects" % type(value))
84     else:
85         f(*args)
86
87 # You can't hide from me!
88 # Note: not quite  sure if this will still cause
89 # the expected behaviour under python3
90 xmlrpc_client.Marshaller._Marshaller__dump = xmlrpclib_dump
91
92
93 class XmlrpcApi:
94     """
95     The XmlrpcApi class implements a basic xmlrpc (or soap) service
96     """
97
98     protocol = None
99
100     def __init__(self, encoding="utf-8", methods='sfa.methods'):
101
102         self.encoding = encoding
103         self.source = None
104
105         # flat list of method names
106         self.methods_module = methods_module = __import__(
107             methods, fromlist=[methods])
108         self.methods = methods_module.all
109
110     def callable(self, method):
111         """
112         Return a new instance of the specified method.
113         """
114         # Look up method
115         if method not in self.methods:
116             raise SfaInvalidAPIMethod(method)
117
118         # Get new instance of method
119         try:
120             classname = method.split(".")[-1]
121             module = __import__(self.methods_module.__name__ +
122                                 "." + method, globals(), locals(), [classname])
123             callablemethod = getattr(module, classname)(self)
124             return getattr(module, classname)(self)
125         except (ImportError, AttributeError):
126             logger.log_exc("Error importing method: %s" % method)
127             raise SfaInvalidAPIMethod(method)
128
129     def call(self, source, method, *args):
130         """
131         Call the named method from the specified source with the
132         specified arguments.
133         """
134         function = self.callable(method)
135         function.source = source
136         self.source = source
137         return function(*args)
138
139     def handle(self, source, data, method_map):
140         """
141         Handle an XML-RPC or SOAP request from the specified source.
142         """
143         # Parse request into method name and arguments
144         try:
145             interface = xmlrpc_client
146             self.protocol = 'xmlrpc'
147             (args, method) = xmlrpc_client.loads(data)
148             if method in method_map:
149                 method = method_map[method]
150             methodresponse = True
151
152         except Exception as e:
153             if SOAPpy is not None:
154                 self.protocol = 'soap'
155                 interface = SOAPpy
156                 (r, header, body, attrs) = parseSOAPRPC(
157                     data, header=1, body=1, attrs=1)
158                 method = r._name
159                 args = r._aslist()
160                 # XXX Support named arguments
161             else:
162                 raise e
163
164         try:
165             result = self.call(source, method, *args)
166         except SfaFault as fault:
167             result = fault
168             logger.log_exc("XmlrpcApi.handle has caught Exception")
169         except Exception as fault:
170             logger.log_exc("XmlrpcApi.handle has caught Exception")
171             result = SfaAPIError(fault)
172
173         # Return result
174         response = self.prepare_response(result, method)
175         return response
176
177     def prepare_response(self, result, method=""):
178         """
179         convert result to a valid xmlrpc or soap response
180         """
181
182         if self.protocol == 'xmlrpc':
183             if not isinstance(result, SfaFault):
184                 result = (result,)
185             response = xmlrpc_client.dumps(
186                 result, methodresponse=True, encoding=self.encoding, allow_none=1)
187         elif self.protocol == 'soap':
188             if isinstance(result, Exception):
189                 result = faultParameter(
190                     NS.ENV_T + ":Server", "Method Failed", method)
191                 result._setDetail("Fault %d: %s" %
192                                   (result.faultCode, result.faultString))
193             else:
194                 response = buildSOAP(
195                     kw={'%sResponse' % method: {'Result': result}}, encoding=self.encoding)
196         else:
197             if isinstance(result, Exception):
198                 raise result
199
200         return response