source: fedd/federation/server.py @ 8445caf

axis_examplecompt_changesinfo-ops
Last change on this file since 8445caf was 9556f2a, checked in by Ted Faber <faber@…>, 14 years ago

Deal with ZSI 2.1 by name aliases. The 2.1 function seems the same, so these simply alias the new names to the old if the old are unavailable.

  • Property mode set to 100755
File size: 7.8 KB
Line 
1#!/usr/local/bin/python
2
3import sys
4
5from BaseHTTPServer import BaseHTTPRequestHandler
6
7from ZSI import Fault, ParseException, FaultFromNotUnderstood, \
8    FaultFromZSIException, FaultFromException, ParsedSoap, SoapWriter
9
10from M2Crypto import SSL
11from M2Crypto.SSL.SSLServer import ThreadingSSLServer
12import xmlrpclib
13
14from fedid import fedid
15try:
16    from fedd_services import ns0
17except ImportError:
18    from fedd_server import ns0
19
20from service_error import *
21
22import os.path
23
24import logging
25import traceback
26
27# The SSL server here is based on the implementation described at
28# http://www.xml.com/pub/a/ws/2004/01/20/salz.html
29
30# Turn off the matching of hostname to certificate ID
31SSL.Connection.clientPostConnectionCheck = None
32
33class server(ThreadingSSLServer):
34    """
35    Interface the fedd services to the XMLRPC and SOAP interfaces
36    """
37    def __init__(self, ME, handler, ssl_ctx, impl, debug=False):
38        """
39        Create an SSL server that handles the transport in handler using the
40        credentials in ssl_ctx, and interfacing to the implementation of fedd
41        services in fedd.  ME is the host port pair on which to bind.
42        """
43        ThreadingSSLServer.__init__(self, ME, handler, ssl_ctx)
44        self.impl = impl
45        self.soap_methods = impl.soap_services
46        self.xmlrpc_methods = impl.xmlrpc_services
47        self.get_handler = impl.get_handler
48        self.log = logging.getLogger("fedd")
49        if debug: self.handle_error = self.handle_error_debug
50        else: self.handle_error = self.handle_error_standard
51
52    def handle_error_debug(self, request=None, client_address=None):
53        print '-'*40
54        traceback.print_exc()
55        print '-'*40
56
57
58    def handle_error_standard(self, request=None, address=None):
59        """
60        The default SSLServer prints a stack trace here.  This is a little
61        friendlier.
62        """
63        if request or address:
64            self.log.warn("[fedd] Error on incoming connection: %s %s" % \
65                    (request or "", address or ""))
66        else:
67            self.log.warn("[fedd] Error on incoming connection " + \
68                    "(Likely SSL error)")
69
70class soap_handler(BaseHTTPRequestHandler):
71    """
72    Standard connection between SOAP and the fedd services in impl.
73
74    Much of this is boilerplate from
75    http://www.xml.com/pub/a/ws/2004/01/20/salz.html
76    """
77    server_version = "ZSI/2.0 fedd/0.1 " + BaseHTTPRequestHandler.server_version
78
79    def send_xml(self, text, code=200):
80        """Send an XML document as reply"""
81        self.send_response(code)
82        self.send_header('Content-type', 'text/xml; charset="utf-8"')
83        self.send_header('Content-Length', str(len(text)))
84        self.end_headers()
85        self.wfile.write(text)
86        self.wfile.flush()
87        self.request.socket.close()
88
89    def send_fault(self, f, code=500):
90        """Send a SOAP encoded fault as reply"""
91        self.send_xml(f.AsSOAP(processContents="lax"), code)
92
93    def check_headers(self, ps):
94        """Send a fault for any required envelope headers"""
95        for (uri, localname) in ps.WhatMustIUnderstand():
96            self.send_fault(FaultFromNotUnderstood(uri, lname, 'fedd'))
97            return False
98        return  True
99
100    def check_method(self, ps):
101        """Confirm that this class implements the namespace and SOAP method"""
102        root = ps.body_root
103        if root.namespaceURI not in self.server.impl.soap_namespaces:
104            self.send_fault(Fault(Fault.Client, 
105                'Unknown namespace "%s"' % root.namespaceURI))
106            return False
107
108        if getattr(root, 'localName', None) == None:
109            self.send_fault(Fault(Fault.Client, 'No method"'))
110            return False
111        return True
112
113    def do_POST(self):
114        """Treat an HTTP POST request as a SOAP service call"""
115        try:
116            cl = int(self.headers['content-length'])
117            data = self.rfile.read(cl)
118            ps = ParsedSoap(data)
119        except ParseException, e:
120            self.send_fault(Fault(Fault.Client, str(e)))
121            return
122        except Exception, e:
123            self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
124            return
125        if not self.check_headers(ps): return
126        if not self.check_method(ps): return
127        try:
128            resp = self.soap_dispatch(ps.body_root.localName, ps,
129                    fedid(cert=self.request.get_peer_cert()))
130        except Fault, f:
131            self.send_fault(f)
132            resp = None
133       
134        if resp != None:
135            sw = SoapWriter()
136            sw.serialize(resp)
137            self.send_xml(str(sw))
138
139    def do_GET(self):
140        """
141        If a get handler is registered, use that to retrieve data.
142        """
143        if self.server.get_handler:
144            code = 200
145            fid = fedid(cert=self.request.get_peer_cert())
146            fname, type = self.server.get_handler(self.path, fid)
147            if fname:
148                try:
149                    f = open(fname, "rb")
150                    size = os.path.getsize(fname)
151                except EnvironmentError, e:
152                    code = 404
153                    size = 0
154            else:
155                code = 404
156                size = 0
157        else:
158            code = 404
159            size = 0
160
161        self.send_response(code)
162        if code == 200:
163            if type:
164                self.send_header('Content-type', type)
165            self.send_header('Content-Length', size)
166            self.end_headers()
167            bytes = f.read(4096)
168            while len(bytes):
169                self.wfile.write(bytes)
170                bytes = f.read(4096)
171            self.wfile.flush()
172        self.request.socket.close()
173
174
175    def log_request(self, code=0, size=0):
176        """
177        Log request to the fedd logger
178        """
179        self.server.log.info("Successful SOAP request code %d" % code)
180
181    def soap_dispatch(self, method, req, fid):
182        """
183        The connection to the implementation, using the  method maps
184
185        The implementation provides a mapping from SOAP method name to the
186        method in the implementation that provides the service.
187        """
188        if self.server.soap_methods.has_key(method):
189            try:
190                return self.server.soap_methods[method](req, fid)
191            except service_error, e:
192                de = ns0.faultType_Def(
193                        (ns0.faultType_Def.schema,
194                            "FeddFaultBody")).pyclass()
195                de._code=e.code
196                de._errstr=e.code_string()
197                de._desc=e.desc
198                if  e.is_server_error():
199                    raise Fault(Fault.Server, e.code_string(), detail=de)
200                else:
201                    raise Fault(Fault.Client, e.code_string(), detail=de)
202        else:
203            raise Fault(Fault.Client, "Unknown method: %s" % method)
204
205
206class xmlrpc_handler(BaseHTTPRequestHandler):
207    """
208    Standard connection between XMLRPC and the fedd services in impl.
209
210    Much of this is boilerplate from
211    http://www.xml.com/pub/a/ws/2004/01/20/salz.html
212    """
213    server_version = "ZSI/2.0 fedd/0.1 " + BaseHTTPRequestHandler.server_version
214
215    def send_xml(self, text, code=200):
216        """Send an XML document as reply"""
217        self.send_response(code)
218        self.send_header('Content-type', 'text/xml; charset="utf-8"')
219        self.send_header('Content-Length', str(len(text)))
220        self.end_headers()
221        self.wfile.write(text)
222        self.wfile.flush()
223        # Make sure to close the socket when we're done
224        self.request.socket.close()
225
226    def do_POST(self):
227        """Treat an HTTP POST request as an XMLRPC service call"""
228        # NB: XMLRPC faults are not HTTP errors, so the code is always 200,
229        # unless an HTTP error occurs, which we don't handle.
230
231        resp = None
232        data = None
233        method = None
234        cl = int(self.headers['content-length'])
235        data = self.rfile.read(cl)
236
237        try:
238            params, method = xmlrpclib.loads(data)
239        except xmlrpclib.ResponseError:
240            data = xmlrpclib.dumps(xmlrpclib.Fault("Client", 
241                "Malformed request"), methodresponse=True)
242
243        if method != None:
244            try:
245                resp = self.xmlrpc_dispatch(method, params,
246                            fedid(cert=self.request.get_peer_cert()))
247                data = xmlrpclib.dumps((resp,), encoding='UTF-8', 
248                        methodresponse=True)
249            except xmlrpclib.Fault, f:
250                data = xmlrpclib.dumps(f, methodresponse=True)
251                resp = None
252
253        self.send_xml(data)
254
255    def log_request(self, code=0, size=0):
256        """
257        Log request to the fedd logger
258        """
259        self.server.log.info("Successful XMLRPC request code %d" % code)
260
261
262    def xmlrpc_dispatch(self, method, req, fid):
263        """
264        The connection to the implementation, using the  method maps
265
266        The implementation provides a mapping from XMLRPC method name to the
267        method in the implementation that provides the service.
268        """
269        if self.server.xmlrpc_methods.has_key(method):
270            try:
271                return self.server.xmlrpc_methods[method](req, fid)
272            except service_error, e:
273                raise xmlrpclib.Fault(e.code_string(), e.desc)
274        else:
275            raise xmlrpclib.Fault(100, "Unknown method: %s" % method)
Note: See TracBrowser for help on using the repository browser.