source: TI12-security/trunk/EsgPyDapClient/esg/pydap/client.py @ 6863

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/EsgPyDapClient/esg/pydap/client.py@6863
Revision 6863, 2.2 KB checked in by pjkersha, 10 years ago (diff)

Initial check in of ESG secured PyDAP client. Will refactor to use PyOpenSSL

Line 
1'''
2Created on 11 May 2010
3
4@author: pjkersha
5'''
6import urllib2
7from M2Crypto import SSL, m2urllib2
8from myproxy.client import MyProxyClient
9
10import logging
11import re
12import os
13import getpass
14from urlparse import urlparse
15import pydap.lib
16from pydap.exceptions import ClientError
17
18url = 'http://ndg3beta.badc.rl.ac.uk/'
19cert_file = os.path.expanduser('~/.globus/badc_cert.pem')
20
21testfile = 'dap/rapid/chime/co2_1pc/1day/chime_co2_1pc_daily_0060_197.oc.nc'
22
23def make_cert():
24
25    # Get a proxy certificate from the CEDA MyProxy instance
26    mp = MyProxyClient(hostname='<CEDA MyProxy Service>', serverCNPrefix='')
27    username = getpass.getuser()
28    password = getpass.getpass()
29    cert, key = mp.logon(username, password)
30
31    # Save the certificate
32    cert_fh = open(cert_file, 'w')
33    cert_fh.write(key)
34    cert_fh.write(cert)
35    cert_fh.close()
36
37def init():
38    install_ndg_client(cert_file)
39    import pydap.client
40
41
42def secure_init(certfile, keyfile=None):
43    # keyfile assumed to be the same as certfile if it's omitted
44    if keyfile is None:
45        keyfile = certfile
46       
47    ctx = SSL.Context('sslv3')
48    ctx.load_cert(certfile=certfile, keyfile=keyfile)
49
50    #!TODO: persistant cookiejar
51    opener = m2urllib2.build_opener(ctx, urllib2.HTTPCookieProcessor())
52    urllib2.install_opener(opener)
53
54
55def install_ndg_client(certfile, keyfile=None):
56    # Create special opener with support for Cookies.
57    secure_init(certfile, keyfile)
58
59    def new_request(url):
60        log = logging.getLogger('pydap')
61        log.info('Opening %s' % url)
62        r = urllib2.urlopen(url)
63
64        resp = r.headers.dict
65        resp['status'] = str(r.code)
66        data = r.read()
67
68        # When an error is returned, we parse the error message from the
69        # server and return it in a ``ClientError`` exception.
70        if resp.get("content-description") == "dods_error":
71            m = re.search('code = (?P<code>\d+);\s*message = "(?P<msg>.*)"',
72                    data, re.DOTALL | re.MULTILINE)
73            msg = 'Server error %(code)s: "%(msg)s"' % m.groupdict()
74            raise ClientError(msg)
75
76        return resp, data
77
78    from pydap.util import http
79    http.request = new_request
80
81def get():
82    return pydap.client.open_url(url + testfile)
83
Note: See TracBrowser for help on using the repository browser.