1"""M2Crypto-enhanced transport for PickleRPC
2
3This lets you use M2Crypto for SSL encryption.
4
5Based on m2xmlrpclib.py which is
6Copyright (c) 1999-2002 Ng Pheng Siong. All rights reserved.
7"""
8
9from MiscUtils import StringIO
10from PickleRPC import Transport
11from M2Crypto import SSL, httpslib, m2urllib
12
13__version__ = 1  # version of M2PickleRPC
14
15
16class M2Transport(Transport):
17
18    user_agent = "M2PickleRPC.py/%s - %s" % (__version__, Transport.user_agent)
19
20    def __init__(self, ssl_context=None):
21        if ssl_context is None:
22            self.ssl_ctx = SSL.Context('sslv23')
23        else:
24            self.ssl_ctx = ssl_context
25
26    def make_connection(self, host):
27        _host, _port = m2urllib.splitport(host)
28        return httpslib.HTTPS(_host, int(_port), ssl_context=self.ssl_ctx)
29
30    # @@ workarounds below are necessary because M2Crypto seems to
31    # return from fileobject.read() early!  So we have to call it
32    # over and over to get the full data.
33
34    def parse_response(self, f):
35        """Workaround M2Crypto issue mentioned above."""
36        sio = StringIO()
37        while 1:
38            chunk = f.read()
39            if not chunk:
40                break
41            sio.write(chunk)
42        sio.seek(0)
43        return Transport.parse_response(self, sio)
44
45    def parse_response_gzip(self, f):
46        """Workaround M2Crypto issue mentioned above."""
47        sio = StringIO()
48        while 1:
49            chunk = f.read()
50            if not chunk:
51                break
52            sio.write(chunk)
53        sio.seek(0)
54        return Transport.parse_response_gzip(self, sio)
55