2 # Replacement for xmlrpclib.SafeTransport, which does not validate
3 # SSL certificates. Requires PyCurl.
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
14 from tempfile import NamedTemporaryFile
16 class PyCurlTransport(xmlrpclib.Transport):
17 def __init__(self, uri, cert = None, timeout = 300):
18 xmlrpclib.Transport.__init__(self)
19 self.curl = pycurl.Curl()
22 self.curl.setopt(pycurl.NOSIGNAL, 1)
25 self.curl.setopt(pycurl.FOLLOWLOCATION, 1)
29 self.curl.setopt(pycurl.URL, str(uri))
31 # Set certificate path
33 if os.path.exists(cert):
36 # Keep a reference so that it does not get deleted
37 self.cert = NamedTemporaryFile(prefix = "cert")
40 cert_path = self.cert.name
41 self.curl.setopt(pycurl.CAINFO, cert_path)
42 self.curl.setopt(pycurl.SSL_VERIFYPEER, 2)
44 # Set connection timeout
46 self.curl.setopt(pycurl.CONNECTTIMEOUT, timeout)
47 self.curl.setopt(pycurl.TIMEOUT, timeout)
49 # Set request callback
53 self.curl.setopt(pycurl.WRITEFUNCTION, body)
55 def request(self, host, handler, request_body, verbose = 1):
57 self.curl.setopt(pycurl.VERBOSE, verbose)
60 self.curl.setopt(pycurl.POST, 1)
61 self.curl.setopt(pycurl.POSTFIELDS, request_body)
65 errcode = self.curl.getinfo(pycurl.HTTP_CODE)
68 errmsg="<no known errmsg>"
69 except pycurl.error, err:
70 (errcode, errmsg) = err
73 raise Exception, "PyCurl: SSL certificate validation failed"
75 raise Exception, "PyCurl: HTTP error %d -- %r" % (errcode,errmsg)
78 p, u = self.getparser()