d759973740b552b3f1548f1c94aac883f9253e94
[sfa.git] / sfa / util / xmlrpcprotocol.py
1 # XMLRPC-specific code for SFA Client
2
3 import xmlrpclib
4
5 ##
6 # ServerException, ExceptionUnmarshaller
7 #
8 # Used to convert server exception strings back to an exception.
9 #    from usenet, Raghuram Devarakonda
10
11 class ServerException(Exception):
12     pass
13
14 class ExceptionUnmarshaller(xmlrpclib.Unmarshaller):
15     def close(self):
16         try:
17             return xmlrpclib.Unmarshaller.close(self)
18         except xmlrpclib.Fault, e:
19             raise ServerException(e.faultString)
20
21 ##
22 # XMLRPCTransport
23 #
24 # A transport for XMLRPC that works on top of HTTPS
25
26 class XMLRPCTransport(xmlrpclib.Transport):
27     key_file = None
28     cert_file = None
29     def make_connection(self, host):
30         # create a HTTPS connection object from a host descriptor
31         # host may be a string, or a (host, x509-dict) tuple
32         import httplib
33         host, extra_headers, x509 = self.get_host_info(host)
34         try:
35             HTTPS = httplib.HTTPS()
36         except AttributeError:
37             raise NotImplementedError(
38                 "your version of httplib doesn't support HTTPS"
39                 )
40         else:
41             return httplib.HTTPS(host, None, key_file=self.key_file, cert_file=self.cert_file) #**(x509 or {}))
42
43     def getparser(self):
44         unmarshaller = ExceptionUnmarshaller()
45         parser = xmlrpclib.ExpatParser(unmarshaller)
46         return parser, unmarshaller
47
48 class XMLRPCServerProxy(xmlrpclib.ServerProxy):
49     def __init__(self, url, transport, allow_none=True, options=None):
50         self.options = options
51         verbose = False
52         if self.options and self.options.debug:
53             verbose = True
54         xmlrpclib.ServerProxy.__init__(self, url, transport, allow_none=allow_none, verbose=verbose)
55
56     def __getattr__(self, attr):
57         if self.options.verbose:
58             print "Calling xml-rpc method:", attr
59         return xmlrpclib.ServerProxy.__getattr__(self, attr)
60
61
62 def get_server(url, key_file, cert_file, options=None):
63     transport = XMLRPCTransport()
64     transport.key_file = key_file
65     transport.cert_file = cert_file
66
67     return XMLRPCServerProxy(url, transport, allow_none=True, options=options)
68