NOT YET WORKING
[sfa.git] / sfa / client / sfaserverproxy.py
1 # XMLRPC-specific code for SFA Client
2
3 import ssl
4 import xmlrpc.client
5 import http.client
6
7 try:
8     from sfa.util.sfalogging import logger
9 except:
10     import logging
11     logger = logging.getLogger('sfaserverproxy')
12
13 ##
14 # ServerException, ExceptionUnmarshaller
15 #
16 # Used to convert server exception strings back to an exception.
17 #    from usenet, Raghuram Devarakonda
18
19
20 class ServerException(Exception):
21     pass
22
23
24 class ExceptionUnmarshaller(xmlrpc.client.Unmarshaller):
25
26     def close(self):
27         try:
28             return xmlrpc.client.Unmarshaller.close(self)
29         except xmlrpc.client.Fault as e:
30             raise ServerException(e.faultString)
31
32 ##
33 # XMLRPCTransport
34 #
35 # A transport for XMLRPC that works on top of HTTPS
36
37 # targetting only python-2.7 we can get rid of some older code
38
39
40 def sfa_client_ssl_context():
41     ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
42     ssl_context.verify_mode = ssl.CERT_NONE
43     ssl_context.check_hostname = False
44 #    with open("root.gid") as root:
45 #        ssl_context.load_verify_locations(cadata=root.read())
46     return ssl_context
47
48
49 class XMLRPCTransport(xmlrpc.client.Transport):
50
51     def __init__(self, key_file=None, cert_file=None, timeout=None):
52         xmlrpc.client.Transport.__init__(self)
53         self.timeout = timeout
54         self.key_file = key_file
55         self.cert_file = cert_file
56
57     def make_connection(self, host):
58         # create a HTTPS connection object from a host descriptor
59         # host may be a string, or a (host, x509-dict) tuple
60         host, extra_headers, x509 = self.get_host_info(host)
61         conn = http.client.HTTPSConnection(
62             host, port=None,
63             key_file=self.key_file,
64             cert_file=self.cert_file,
65             timeout=self.timeout,
66             context=sfa_client_ssl_context(),
67             check_hostname=False,
68             )
69
70 #        # Some logic to deal with timeouts. It appears that some (or all) versions
71 #        # of python don't set the timeout after the socket is created. We'll do it
72 #        # ourselves by forcing the connection to connect, finding the socket, and
73 #        # calling settimeout() on it. (tested with python 2.6)
74 #        if self.timeout:
75 #            if hasattr(conn, 'set_timeout'):
76 #                conn.set_timeout(self.timeout)
77 #
78 #            if hasattr(conn, "_conn"):
79 #                # HTTPS is a wrapper around HTTPSConnection
80 #                real_conn = conn._conn
81 #            else:
82 #                real_conn = conn
83 #            conn.connect()
84 #            if hasattr(real_conn, "sock") and hasattr(real_conn.sock, "settimeout"):
85 #                real_conn.sock.settimeout(float(self.timeout))
86 #
87         return conn
88
89     def getparser(self):
90         unmarshaller = ExceptionUnmarshaller()
91         parser = xmlrpc.client.ExpatParser(unmarshaller)
92         return parser, unmarshaller
93
94
95 class XMLRPCServerProxy(xmlrpc.client.ServerProxy):
96
97     def __init__(self, url, transport, allow_none=True, verbose=False):
98         # remember url for GetVersion
99         # xxx not sure this is still needed as SfaServerProxy has this too
100         self.url = url
101         xmlrpc.client.ServerProxy.__init__(
102             self, url, transport, allow_none=allow_none,
103             context=sfa_client_ssl_context(), verbose=verbose)
104
105     def __getattr__(self, attr):
106         logger.debug("xml-rpc %s method:%s" % (self.url, attr))
107         return xmlrpc.client.ServerProxy.__getattr__(self, attr)
108
109 # the object on which we can send methods that get sent over xmlrpc
110
111
112 class SfaServerProxy:
113
114     def __init__(self, url, keyfile, certfile, verbose=False, timeout=None):
115         self.url = url
116         self.keyfile = keyfile
117         self.certfile = certfile
118         self.verbose = verbose
119         self.timeout = timeout
120         # an instance of xmlrpc.client.ServerProxy
121         transport = XMLRPCTransport(keyfile, certfile, timeout)
122         self.serverproxy = XMLRPCServerProxy(
123             url, transport, allow_none=True, verbose=verbose)
124
125     # this is python magic to return the code to run when
126     # SfaServerProxy receives a method call
127     # so essentially we send the same method with identical arguments
128     # to the server_proxy object
129     def __getattr__(self, name):
130         def func(*args, **kwds):
131             return getattr(self.serverproxy, name)(*args, **kwds)
132         return func