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