ebf6f85d978220a30678df0bd5a32b5026748eb4
[shibboleth/cpp-xmltooling.git] / xmltooling / soap / impl / CURLSOAPTransport.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * CURLSOAPTransport.cpp
19  *
20  * libcurl-based SOAPTransport implementation
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "logging.h"
26 #include "security/CredentialCriteria.h"
27 #include "security/OpenSSLTrustEngine.h"
28 #include "security/OpenSSLCredential.h"
29 #include "soap/HTTPSOAPTransport.h"
30 #include "soap/OpenSSLSOAPTransport.h"
31 #include "util/NDC.h"
32 #include "util/Threads.h"
33
34 #include <list>
35 #include <curl/curl.h>
36 #include <openssl/x509_vfy.h>
37
38 using namespace xmltooling::logging;
39 using namespace xmltooling;
40 using namespace std;
41
42 namespace xmltooling {
43
44     // Manages cache of socket connections via CURL handles.
45     class XMLTOOL_DLLLOCAL CURLPool
46     {
47     public:
48         CURLPool() : m_size(0), m_lock(Mutex::create()),
49             m_log(Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL")) {}
50         ~CURLPool();
51
52         CURL* get(const SOAPTransport::Address& addr);
53         void put(const char* from, const char* to, const char* endpoint, CURL* handle);
54
55     private:
56         typedef map<string,vector<CURL*> > poolmap_t;
57         poolmap_t m_bindingMap;
58         list< vector<CURL*>* > m_pools;
59         long m_size;
60         Mutex* m_lock;
61         Category& m_log;
62     };
63
64     static XMLTOOL_DLLLOCAL CURLPool* g_CURLPool = NULL;
65
66     class XMLTOOL_DLLLOCAL CURLSOAPTransport : public HTTPSOAPTransport, public OpenSSLSOAPTransport
67     {
68     public:
69         CURLSOAPTransport(const Address& addr)
70             : m_sender(addr.m_from ? addr.m_from : ""), m_peerName(addr.m_to ? addr.m_to : ""), m_endpoint(addr.m_endpoint),
71                 m_handle(NULL), m_headers(NULL),
72 #ifndef XMLTOOLING_NO_XMLSEC
73                     m_cred(NULL), m_trustEngine(NULL), m_peerResolver(NULL), m_mandatory(false),
74 #endif
75                     m_ssl_callback(NULL), m_ssl_userptr(NULL), m_chunked(true), m_authenticated(false) {
76             m_handle = g_CURLPool->get(addr);
77             curl_easy_setopt(m_handle,CURLOPT_URL,addr.m_endpoint);
78             curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,15);
79             curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,30);
80             curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0);
81             curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL);
82             curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,2);
83             curl_easy_setopt(m_handle,CURLOPT_HEADERDATA,this);
84             m_headers=curl_slist_append(m_headers,"Content-Type: text/xml");
85         }
86
87         virtual ~CURLSOAPTransport() {
88             curl_slist_free_all(m_headers);
89             curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,NULL);
90             curl_easy_setopt(m_handle,CURLOPT_PRIVATE,m_authenticated ? "secure" : NULL); // Save off security "state".
91             g_CURLPool->put(m_sender.c_str(), m_peerName.c_str(), m_endpoint.c_str(), m_handle);
92         }
93
94         bool isConfidential() const {
95             return m_endpoint.find("https")==0;
96         }
97
98         bool setConnectTimeout(long timeout) {
99             return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
100         }
101
102         bool setTimeout(long timeout) {
103             return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
104         }
105
106         bool setAuth(transport_auth_t authType, const char* username=NULL, const char* password=NULL);
107
108         bool setVerifyHost(bool verify) {
109             return (curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,verify ? 2 : 0)==CURLE_OK);
110         }
111
112 #ifndef XMLTOOLING_NO_XMLSEC
113         bool setCredential(const Credential* cred=NULL) {
114             const OpenSSLCredential* down = dynamic_cast<const OpenSSLCredential*>(cred);
115             if (!down) {
116                 m_cred = NULL;
117                 return (cred==NULL);
118             }
119             m_cred = down;
120             return true;
121         }
122
123         bool setTrustEngine(
124             const X509TrustEngine* trustEngine=NULL,
125             const CredentialResolver* peerResolver=NULL,
126             CredentialCriteria* criteria=NULL,
127             bool mandatory=true
128             ) {
129             const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
130             if (!down) {
131                 m_trustEngine = NULL;
132                 m_peerResolver = NULL;
133                 m_criteria = NULL;
134                 return (trustEngine==NULL);
135             }
136             m_trustEngine = down;
137             m_peerResolver = peerResolver;
138             m_criteria = criteria;
139             m_mandatory = mandatory;
140             return true;
141         }
142
143 #endif
144
145         bool useChunkedEncoding(bool chunked=true) {
146             m_chunked = chunked;
147             return true;
148         }
149
150         bool setProviderOption(const char* provider, const char* option, const char* value) {
151             if (!provider || strcmp(provider, "CURL"))
152                 return false;
153             // For libcurl, the option is an enum and the value type depends on the option.
154             CURLoption opt = static_cast<CURLoption>(strtol(option, NULL, 10));
155             if (opt < CURLOPTTYPE_OBJECTPOINT)
156                 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
157 #ifdef CURLOPTTYPE_OFF_T
158             else if (opt < CURLOPTTYPE_OFF_T)
159                 return (curl_easy_setopt(m_handle, opt, value) == CURLE_OK);
160 # ifdef HAVE_CURL_OFF_T
161             else if (sizeof(curl_off_t) == sizeof(long))
162                 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
163 # else
164             else if (sizeof(off_t) == sizeof(long))
165                 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
166 # endif
167             return false;
168 #else
169             else
170                 return (curl_easy_setopt(m_handle, opt, value) == CURLE_OK);
171 #endif
172         }
173
174         void send(istream& in) {
175             send(&in);
176         }
177
178         void send(istream* in=NULL);
179
180         istream& receive() {
181             return m_stream;
182         }
183
184         bool isAuthenticated() const {
185             return m_authenticated;
186         }
187
188         void setAuthenticated(bool auth) {
189             m_authenticated = auth;
190         }
191
192         string getContentType() const;
193
194         bool setRequestHeader(const char* name, const char* val) {
195             string temp(name);
196             temp=temp + ": " + val;
197             m_headers=curl_slist_append(m_headers,temp.c_str());
198             return true;
199         }
200
201         const vector<string>& getResponseHeader(const char* val) const;
202
203         bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=NULL) {
204             m_ssl_callback=fn;
205             m_ssl_userptr=userptr;
206             return true;
207         }
208
209     private:
210         // per-call state
211         string m_sender,m_peerName,m_endpoint,m_simplecreds;
212         CURL* m_handle;
213         stringstream m_stream;
214         struct curl_slist* m_headers;
215         map<string,vector<string> > m_response_headers;
216 #ifndef XMLTOOLING_NO_XMLSEC
217         const OpenSSLCredential* m_cred;
218         const OpenSSLTrustEngine* m_trustEngine;
219         const CredentialResolver* m_peerResolver;
220         CredentialCriteria* m_criteria;
221         bool m_mandatory;
222 #endif
223         ssl_ctx_callback_fn m_ssl_callback;
224         void* m_ssl_userptr;
225         bool m_chunked;
226         bool m_authenticated;
227
228         friend size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
229         friend CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
230         friend int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
231     };
232
233     // libcurl callback functions
234     size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
235     size_t XMLTOOL_DLLLOCAL curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream);
236     size_t XMLTOOL_DLLLOCAL curl_read_hook( void *ptr, size_t size, size_t nmemb, void *stream);
237     int XMLTOOL_DLLLOCAL curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr);
238     CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
239 #ifndef XMLTOOLING_NO_XMLSEC
240     int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
241 #endif
242
243     SOAPTransport* CURLSOAPTransportFactory(const SOAPTransport::Address& addr)
244     {
245         return new CURLSOAPTransport(addr);
246     }
247 };
248
249 void xmltooling::registerSOAPTransports()
250 {
251     XMLToolingConfig& conf=XMLToolingConfig::getConfig();
252     conf.SOAPTransportManager.registerFactory("http", CURLSOAPTransportFactory);
253     conf.SOAPTransportManager.registerFactory("https", CURLSOAPTransportFactory);
254 }
255
256 void xmltooling::initSOAPTransports()
257 {
258     g_CURLPool=new CURLPool();
259 }
260
261 void xmltooling::termSOAPTransports()
262 {
263     delete g_CURLPool;
264     g_CURLPool = NULL;
265 }
266
267 CURLPool::~CURLPool()
268 {
269     for (poolmap_t::iterator i=m_bindingMap.begin(); i!=m_bindingMap.end(); i++) {
270         for (vector<CURL*>::iterator j=i->second.begin(); j!=i->second.end(); j++)
271             curl_easy_cleanup(*j);
272     }
273     delete m_lock;
274 }
275
276 CURL* CURLPool::get(const SOAPTransport::Address& addr)
277 {
278 #ifdef _DEBUG
279     xmltooling::NDC("get");
280 #endif
281     m_log.debug("getting connection handle to %s", addr.m_endpoint);
282     string key(addr.m_endpoint);
283     if (addr.m_from)
284         key = key + '|' + addr.m_from;
285     if (addr.m_to)
286         key = key + '|' + addr.m_to;
287     m_lock->lock();
288     poolmap_t::iterator i=m_bindingMap.find(key);
289
290     if (i!=m_bindingMap.end()) {
291         // Move this pool to the front of the list.
292         m_pools.remove(&(i->second));
293         m_pools.push_front(&(i->second));
294
295         // If a free connection exists, return it.
296         if (!(i->second.empty())) {
297             CURL* handle=i->second.back();
298             i->second.pop_back();
299             m_size--;
300             m_lock->unlock();
301             m_log.debug("returning existing connection handle from pool");
302             return handle;
303         }
304     }
305
306     m_lock->unlock();
307     m_log.debug("nothing free in pool, returning new connection handle");
308
309     // Create a new connection and set non-varying options.
310     CURL* handle=curl_easy_init();
311     if (!handle)
312         return NULL;
313     curl_easy_setopt(handle,CURLOPT_NOPROGRESS,1);
314     curl_easy_setopt(handle,CURLOPT_NOSIGNAL,1);
315     curl_easy_setopt(handle,CURLOPT_FAILONERROR,1);
316     curl_easy_setopt(handle,CURLOPT_SSL_CIPHER_LIST,"ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
317     // Verification of the peer is via TrustEngine only.
318     curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
319     curl_easy_setopt(handle,CURLOPT_CAINFO,NULL);
320     curl_easy_setopt(handle,CURLOPT_HEADERFUNCTION,&curl_header_hook);
321     curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION,&curl_write_hook);
322     curl_easy_setopt(handle,CURLOPT_DEBUGFUNCTION,&curl_debug_hook);
323
324     return handle;
325 }
326
327 void CURLPool::put(const char* from, const char* to, const char* endpoint, CURL* handle)
328 {
329     string key(endpoint);
330     if (from)
331         key = key + '|' + from;
332     if (to)
333         key = key + '|' + to;
334     m_lock->lock();
335     poolmap_t::iterator i=m_bindingMap.find(key);
336     if (i==m_bindingMap.end())
337         m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
338     else
339         i->second.push_back(handle);
340
341     CURL* killit=NULL;
342     if (++m_size > 256) {
343         // Kick a handle out from the back of the bus.
344         while (true) {
345             vector<CURL*>* corpse=m_pools.back();
346             if (!corpse->empty()) {
347                 killit=corpse->back();
348                 corpse->pop_back();
349                 m_size--;
350                 break;
351             }
352
353             // Move an empty pool up to the front so we don't keep hitting it.
354             m_pools.pop_back();
355             m_pools.push_front(corpse);
356         }
357     }
358     m_lock->unlock();
359     if (killit) {
360         curl_easy_cleanup(killit);
361 #ifdef _DEBUG
362         xmltooling::NDC("put");
363 #endif
364         m_log.info("conn_pool_max limit reached, dropping an old connection");
365     }
366 }
367
368 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
369 {
370     if (authType==transport_auth_none) {
371         if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
372             return false;
373         return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL)==CURLE_OK);
374     }
375     long flag=0;
376     switch (authType) {
377         case transport_auth_basic:    flag = CURLAUTH_BASIC; break;
378         case transport_auth_digest:   flag = CURLAUTH_DIGEST; break;
379         case transport_auth_ntlm:     flag = CURLAUTH_NTLM; break;
380         case transport_auth_gss:      flag = CURLAUTH_GSSNEGOTIATE; break;
381         default:            return false;
382     }
383     if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
384         return false;
385     m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
386     return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
387 }
388
389 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
390 {
391     static vector<string> emptyVector;
392
393     map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
394     if (i!=m_response_headers.end())
395         return i->second;
396
397     for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
398 #ifdef HAVE_STRCASECMP
399         if (!strcasecmp(j->first.c_str(), name))
400 #else
401         if (!stricmp(j->first.c_str(), name))
402 #endif
403             return j->second;
404     }
405
406     return emptyVector;
407 }
408
409 string CURLSOAPTransport::getContentType() const
410 {
411     char* content_type=NULL;
412     curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
413     return content_type ? content_type : "";
414 }
415
416 void CURLSOAPTransport::send(istream* in)
417 {
418 #ifdef _DEBUG
419     xmltooling::NDC ndc("send");
420 #endif
421     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL");
422     Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT".libcurl");
423
424     // For this implementation, it's sufficient to check for https as a sign of transport security.
425     if (m_mandatory && !isConfidential())
426         throw IOException("Blocking unprotected HTTP request, transport authentication by server required.");
427
428     string msg;
429
430     // By this time, the handle has been prepared with the URL to use and the
431     // caller should have executed any set functions to manipulate it.
432
433     // Setup standard per-call curl properties.
434     curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
435     curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
436     if (m_chunked && in) {
437         curl_easy_setopt(m_handle,CURLOPT_POST,1);
438         m_headers=curl_slist_append(m_headers,"Transfer-Encoding: chunked");
439         curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,&curl_read_hook);
440         curl_easy_setopt(m_handle,CURLOPT_READDATA,in);
441     }
442     else if (in) {
443         char buf[1024];
444         while (*in) {
445             in->read(buf,1024);
446             msg.append(buf,in->gcount());
447         }
448         curl_easy_setopt(m_handle,CURLOPT_POST,1);
449         curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,NULL);
450         curl_easy_setopt(m_handle,CURLOPT_POSTFIELDS,msg.c_str());
451         curl_easy_setopt(m_handle,CURLOPT_POSTFIELDSIZE,msg.length());
452     }
453     else {
454         curl_easy_setopt(m_handle,CURLOPT_HTTPGET,1);
455     }
456
457     char curl_errorbuf[CURL_ERROR_SIZE];
458     curl_errorbuf[0]=0;
459     curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
460     if (log_curl.isDebugEnabled())
461         curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
462
463     // Set request headers.
464     curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
465
466 #ifndef XMLTOOLING_NO_XMLSEC
467     if (m_ssl_callback || m_cred || m_trustEngine) {
468 #else
469     if (m_ssl_callback) {
470 #endif
471         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
472         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
473
474         // Restore security "state". Necessary because the callback only runs
475         // when handshakes occur. Even new TCP connections won't execute it.
476         char* priv=NULL;
477         curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
478         if (priv)
479             m_authenticated=true;
480     }
481     else {
482         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,NULL);
483         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,NULL);
484     }
485
486     // Make the call.
487     log.debug("sending SOAP message to %s", m_endpoint.c_str());
488     if (curl_easy_perform(m_handle) != CURLE_OK) {
489         throw IOException(
490             string("CURLSOAPTransport failed while contacting SOAP endpoint (") + m_endpoint + "): " +
491                 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
492     }
493 }
494
495 // callback to buffer headers from server
496 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
497 {
498     // only handle single-byte data
499     if (size!=1)
500         return 0;
501     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
502     char* buf = (char*)malloc(nmemb + 1);
503     if (buf) {
504         memset(buf,0,nmemb + 1);
505         memcpy(buf,ptr,nmemb);
506         char* sep=(char*)strchr(buf,':');
507         if (sep) {
508             *(sep++)=0;
509             while (*sep==' ')
510                 *(sep++)=0;
511             char* white=buf+nmemb-1;
512             while (isspace(*white))
513                 *(white--)=0;
514             ctx->m_response_headers[buf].push_back(sep);
515         }
516         free(buf);
517         return nmemb;
518     }
519     return 0;
520 }
521
522 // callback to send data to server
523 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
524 {
525     // stream is actually an istream pointer
526     istream* buf=reinterpret_cast<istream*>(stream);
527     buf->read(reinterpret_cast<char*>(ptr),size*nmemb);
528     return buf->gcount();
529 }
530
531 // callback to buffer data from server
532 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
533 {
534     size_t len = size*nmemb;
535     reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
536     return len;
537 }
538
539 // callback for curl debug data
540 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
541 {
542     // *ptr is actually a logging object
543     if (!ptr) return 0;
544     CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
545     for (unsigned char* ch=(unsigned char*)data; len && (isprint(*ch) || isspace(*ch)); len--)
546         log << *ch++;
547     return 0;
548 }
549
550 #ifndef XMLTOOLING_NO_XMLSEC
551 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
552 {
553     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL");
554     log.debug("invoking custom X.509 verify callback");
555 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
556     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
557 #else
558     // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
559     // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
560     // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
561     // negative in the SSL structure's int member.
562     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
563         SSL_get_verify_depth(
564             reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
565             )
566         );
567 #endif
568
569     bool success=false;
570     if (ctx->m_criteria) {
571         ctx->m_criteria->setUsage(Credential::TLS_CREDENTIAL);
572         // Bypass name check (handled for us by curl).
573         ctx->m_criteria->setPeerName(NULL);
574         success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),ctx->m_criteria);
575     }
576     else {
577         // Bypass name check (handled for us by curl).
578         CredentialCriteria cc;
579         cc.setUsage(Credential::TLS_CREDENTIAL);
580         success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),&cc);
581     }
582
583     if (!success) {
584         log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
585         x509_ctx->error=X509_V_ERR_APPLICATION_VERIFICATION;     // generic error, check log for plugin specifics
586         ctx->setAuthenticated(false);
587         return ctx->m_mandatory ? 0 : 1;
588     }
589
590     // Signal success. Hopefully it doesn't matter what's actually in the structure now.
591     ctx->setAuthenticated(true);
592     return 1;
593 }
594 #endif
595
596 // callback to invoke a caller-defined SSL callback
597 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
598 {
599     CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
600
601     // Manually disable SSLv2 so we're not dependent on libcurl to do it.
602     // Also disable the ticket option where implemented, since this breaks a variety
603     // of servers. Newer libcurl also does this for us.
604 #ifdef SSL_OP_NO_TICKET
605     SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_TICKET);
606 #else
607     SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
608 #endif
609
610 #ifndef XMLTOOLING_NO_XMLSEC
611     if (conf->m_cred)
612         conf->m_cred->attach(ssl_ctx);
613
614     if (conf->m_trustEngine) {
615         SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,NULL);
616 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
617         // With 0.9.7, we can pass a callback argument directly.
618         SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
619 #else
620         // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
621         // stuff the argument in the depth property where it will get copied to the context object
622         // that's handed to the callback.
623         SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),NULL);
624         SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
625 #endif
626     }
627 #endif
628
629     if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
630         return CURLE_SSL_CERTPROBLEM;
631
632     return CURLE_OK;
633 }