https://issues.shibboleth.net/jira/browse/CPPXT-47
[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                 if (value)
160                     m_saved_options.push_back(value);
161                 return (curl_easy_setopt(m_handle, opt, value ? m_saved_options.back().c_str() : NULL) == CURLE_OK);
162             }
163 # ifdef HAVE_CURL_OFF_T
164             else if (sizeof(curl_off_t) == sizeof(long))
165                 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
166 # else
167             else if (sizeof(off_t) == sizeof(long))
168                 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
169 # endif
170             return false;
171 #else
172             else {
173                 if (value)
174                     m_saved_options.push_back(value);
175                 return (curl_easy_setopt(m_handle, opt, value ? m_saved_options.back().c_str() : NULL) == CURLE_OK);
176             }
177 #endif
178         }
179
180         void send(istream& in) {
181             send(&in);
182         }
183
184         void send(istream* in=NULL);
185
186         istream& receive() {
187             return m_stream;
188         }
189
190         bool isAuthenticated() const {
191             return m_authenticated;
192         }
193
194         void setAuthenticated(bool auth) {
195             m_authenticated = auth;
196         }
197
198         string getContentType() const;
199
200         bool setRequestHeader(const char* name, const char* val) {
201             string temp(name);
202             temp=temp + ": " + val;
203             m_headers=curl_slist_append(m_headers,temp.c_str());
204             return true;
205         }
206
207         const vector<string>& getResponseHeader(const char* val) const;
208
209         bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=NULL) {
210             m_ssl_callback=fn;
211             m_ssl_userptr=userptr;
212             return true;
213         }
214
215     private:
216         // per-call state
217         string m_sender,m_peerName,m_endpoint,m_simplecreds;
218         CURL* m_handle;
219         stringstream m_stream;
220         struct curl_slist* m_headers;
221         map<string,vector<string> > m_response_headers;
222         vector<string> m_saved_options;
223 #ifndef XMLTOOLING_NO_XMLSEC
224         const OpenSSLCredential* m_cred;
225         const OpenSSLTrustEngine* m_trustEngine;
226         const CredentialResolver* m_peerResolver;
227         CredentialCriteria* m_criteria;
228         bool m_mandatory;
229 #endif
230         ssl_ctx_callback_fn m_ssl_callback;
231         void* m_ssl_userptr;
232         bool m_chunked;
233         bool m_authenticated;
234
235         friend size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
236         friend CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
237         friend int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
238     };
239
240     // libcurl callback functions
241     size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
242     size_t XMLTOOL_DLLLOCAL curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream);
243     size_t XMLTOOL_DLLLOCAL curl_read_hook( void *ptr, size_t size, size_t nmemb, void *stream);
244     int XMLTOOL_DLLLOCAL curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr);
245     CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
246 #ifndef XMLTOOLING_NO_XMLSEC
247     int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
248 #endif
249
250     SOAPTransport* CURLSOAPTransportFactory(const SOAPTransport::Address& addr)
251     {
252         return new CURLSOAPTransport(addr);
253     }
254 };
255
256 void xmltooling::registerSOAPTransports()
257 {
258     XMLToolingConfig& conf=XMLToolingConfig::getConfig();
259     conf.SOAPTransportManager.registerFactory("http", CURLSOAPTransportFactory);
260     conf.SOAPTransportManager.registerFactory("https", CURLSOAPTransportFactory);
261 }
262
263 void xmltooling::initSOAPTransports()
264 {
265     g_CURLPool=new CURLPool();
266 }
267
268 void xmltooling::termSOAPTransports()
269 {
270     delete g_CURLPool;
271     g_CURLPool = NULL;
272 }
273
274 OpenSSLSOAPTransport::OpenSSLSOAPTransport()
275 {
276 }
277
278 OpenSSLSOAPTransport::~OpenSSLSOAPTransport()
279 {
280 }
281
282 CURLPool::~CURLPool()
283 {
284     for (poolmap_t::iterator i=m_bindingMap.begin(); i!=m_bindingMap.end(); i++) {
285         for (vector<CURL*>::iterator j=i->second.begin(); j!=i->second.end(); j++)
286             curl_easy_cleanup(*j);
287     }
288     delete m_lock;
289 }
290
291 CURL* CURLPool::get(const SOAPTransport::Address& addr)
292 {
293 #ifdef _DEBUG
294     xmltooling::NDC("get");
295 #endif
296     m_log.debug("getting connection handle to %s", addr.m_endpoint);
297     string key(addr.m_endpoint);
298     if (addr.m_from)
299         key = key + '|' + addr.m_from;
300     if (addr.m_to)
301         key = key + '|' + addr.m_to;
302     m_lock->lock();
303     poolmap_t::iterator i=m_bindingMap.find(key);
304
305     if (i!=m_bindingMap.end()) {
306         // Move this pool to the front of the list.
307         m_pools.remove(&(i->second));
308         m_pools.push_front(&(i->second));
309
310         // If a free connection exists, return it.
311         if (!(i->second.empty())) {
312             CURL* handle=i->second.back();
313             i->second.pop_back();
314             m_size--;
315             m_lock->unlock();
316             m_log.debug("returning existing connection handle from pool");
317             return handle;
318         }
319     }
320
321     m_lock->unlock();
322     m_log.debug("nothing free in pool, returning new connection handle");
323
324     // Create a new connection and set non-varying options.
325     CURL* handle=curl_easy_init();
326     if (!handle)
327         return NULL;
328     curl_easy_setopt(handle,CURLOPT_NOPROGRESS,1);
329     curl_easy_setopt(handle,CURLOPT_NOSIGNAL,1);
330     curl_easy_setopt(handle,CURLOPT_FAILONERROR,1);
331     curl_easy_setopt(handle,CURLOPT_SSL_CIPHER_LIST,"ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
332     // Verification of the peer is via TrustEngine only.
333     curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
334     curl_easy_setopt(handle,CURLOPT_CAINFO,NULL);
335     curl_easy_setopt(handle,CURLOPT_HEADERFUNCTION,&curl_header_hook);
336     curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION,&curl_write_hook);
337     curl_easy_setopt(handle,CURLOPT_DEBUGFUNCTION,&curl_debug_hook);
338
339     return handle;
340 }
341
342 void CURLPool::put(const char* from, const char* to, const char* endpoint, CURL* handle)
343 {
344     string key(endpoint);
345     if (from)
346         key = key + '|' + from;
347     if (to)
348         key = key + '|' + to;
349     m_lock->lock();
350     poolmap_t::iterator i=m_bindingMap.find(key);
351     if (i==m_bindingMap.end())
352         m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
353     else
354         i->second.push_back(handle);
355
356     CURL* killit=NULL;
357     if (++m_size > 256) {
358         // Kick a handle out from the back of the bus.
359         while (true) {
360             vector<CURL*>* corpse=m_pools.back();
361             if (!corpse->empty()) {
362                 killit=corpse->back();
363                 corpse->pop_back();
364                 m_size--;
365                 break;
366             }
367
368             // Move an empty pool up to the front so we don't keep hitting it.
369             m_pools.pop_back();
370             m_pools.push_front(corpse);
371         }
372     }
373     m_lock->unlock();
374     if (killit) {
375         curl_easy_cleanup(killit);
376 #ifdef _DEBUG
377         xmltooling::NDC("put");
378 #endif
379         m_log.info("conn_pool_max limit reached, dropping an old connection");
380     }
381 }
382
383 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
384 {
385     if (authType==transport_auth_none) {
386         if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
387             return false;
388         return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL)==CURLE_OK);
389     }
390     long flag=0;
391     switch (authType) {
392         case transport_auth_basic:    flag = CURLAUTH_BASIC; break;
393         case transport_auth_digest:   flag = CURLAUTH_DIGEST; break;
394         case transport_auth_ntlm:     flag = CURLAUTH_NTLM; break;
395         case transport_auth_gss:      flag = CURLAUTH_GSSNEGOTIATE; break;
396         default:            return false;
397     }
398     if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
399         return false;
400     m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
401     return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
402 }
403
404 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
405 {
406     static vector<string> emptyVector;
407
408     map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
409     if (i!=m_response_headers.end())
410         return i->second;
411
412     for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
413 #ifdef HAVE_STRCASECMP
414         if (!strcasecmp(j->first.c_str(), name))
415 #else
416         if (!stricmp(j->first.c_str(), name))
417 #endif
418             return j->second;
419     }
420
421     return emptyVector;
422 }
423
424 string CURLSOAPTransport::getContentType() const
425 {
426     char* content_type=NULL;
427     curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
428     return content_type ? content_type : "";
429 }
430
431 void CURLSOAPTransport::send(istream* in)
432 {
433 #ifdef _DEBUG
434     xmltooling::NDC ndc("send");
435 #endif
436     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL");
437     Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT".libcurl");
438
439     // For this implementation, it's sufficient to check for https as a sign of transport security.
440     if (m_mandatory && !isConfidential())
441         throw IOException("Blocking unprotected HTTP request, transport authentication by server required.");
442
443     string msg;
444
445     // By this time, the handle has been prepared with the URL to use and the
446     // caller should have executed any set functions to manipulate it.
447
448     // Setup standard per-call curl properties.
449     curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
450     curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
451     if (m_chunked && in) {
452         curl_easy_setopt(m_handle,CURLOPT_POST,1);
453         m_headers=curl_slist_append(m_headers,"Transfer-Encoding: chunked");
454         curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,&curl_read_hook);
455         curl_easy_setopt(m_handle,CURLOPT_READDATA,in);
456     }
457     else if (in) {
458         char buf[1024];
459         while (*in) {
460             in->read(buf,1024);
461             msg.append(buf,in->gcount());
462         }
463         curl_easy_setopt(m_handle,CURLOPT_POST,1);
464         curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,NULL);
465         curl_easy_setopt(m_handle,CURLOPT_POSTFIELDS,msg.c_str());
466         curl_easy_setopt(m_handle,CURLOPT_POSTFIELDSIZE,msg.length());
467     }
468     else {
469         curl_easy_setopt(m_handle,CURLOPT_HTTPGET,1);
470     }
471
472     char curl_errorbuf[CURL_ERROR_SIZE];
473     curl_errorbuf[0]=0;
474     curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
475     if (log_curl.isDebugEnabled())
476         curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
477
478     // Set request headers.
479     curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
480
481 #ifndef XMLTOOLING_NO_XMLSEC
482     if (m_ssl_callback || m_cred || m_trustEngine) {
483 #else
484     if (m_ssl_callback) {
485 #endif
486         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
487         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
488
489         // Restore security "state". Necessary because the callback only runs
490         // when handshakes occur. Even new TCP connections won't execute it.
491         char* priv=NULL;
492         curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
493         if (priv)
494             m_authenticated=true;
495     }
496     else {
497         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,NULL);
498         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,NULL);
499     }
500
501     // Make the call.
502     log.debug("sending SOAP message to %s", m_endpoint.c_str());
503     if (curl_easy_perform(m_handle) != CURLE_OK) {
504         throw IOException(
505             string("CURLSOAPTransport failed while contacting SOAP endpoint (") + m_endpoint + "): " +
506                 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
507     }
508 }
509
510 // callback to buffer headers from server
511 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
512 {
513     // only handle single-byte data
514     if (size!=1)
515         return 0;
516     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
517     char* buf = (char*)malloc(nmemb + 1);
518     if (buf) {
519         memset(buf,0,nmemb + 1);
520         memcpy(buf,ptr,nmemb);
521         char* sep=(char*)strchr(buf,':');
522         if (sep) {
523             *(sep++)=0;
524             while (*sep==' ')
525                 *(sep++)=0;
526             char* white=buf+nmemb-1;
527             while (isspace(*white))
528                 *(white--)=0;
529             ctx->m_response_headers[buf].push_back(sep);
530         }
531         free(buf);
532         return nmemb;
533     }
534     return 0;
535 }
536
537 // callback to send data to server
538 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
539 {
540     // stream is actually an istream pointer
541     istream* buf=reinterpret_cast<istream*>(stream);
542     buf->read(reinterpret_cast<char*>(ptr),size*nmemb);
543     return buf->gcount();
544 }
545
546 // callback to buffer data from server
547 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
548 {
549     size_t len = size*nmemb;
550     reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
551     return len;
552 }
553
554 // callback for curl debug data
555 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
556 {
557     // *ptr is actually a logging object
558     if (!ptr) return 0;
559     CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
560     for (unsigned char* ch=(unsigned char*)data; len && (isprint(*ch) || isspace(*ch)); len--)
561         log << *ch++;
562     return 0;
563 }
564
565 #ifndef XMLTOOLING_NO_XMLSEC
566 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
567 {
568     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL");
569     log.debug("invoking custom X.509 verify callback");
570 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
571     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
572 #else
573     // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
574     // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
575     // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
576     // negative in the SSL structure's int member.
577     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
578         SSL_get_verify_depth(
579             reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
580             )
581         );
582 #endif
583
584     bool success=false;
585     if (ctx->m_criteria) {
586         ctx->m_criteria->setUsage(Credential::TLS_CREDENTIAL);
587         // Bypass name check (handled for us by curl).
588         ctx->m_criteria->setPeerName(NULL);
589         success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),ctx->m_criteria);
590     }
591     else {
592         // Bypass name check (handled for us by curl).
593         CredentialCriteria cc;
594         cc.setUsage(Credential::TLS_CREDENTIAL);
595         success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),&cc);
596     }
597
598     if (!success) {
599         log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
600         x509_ctx->error=X509_V_ERR_APPLICATION_VERIFICATION;     // generic error, check log for plugin specifics
601         ctx->setAuthenticated(false);
602         return ctx->m_mandatory ? 0 : 1;
603     }
604
605     // Signal success. Hopefully it doesn't matter what's actually in the structure now.
606     ctx->setAuthenticated(true);
607     return 1;
608 }
609 #endif
610
611 // callback to invoke a caller-defined SSL callback
612 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
613 {
614     CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
615
616     // Manually disable SSLv2 so we're not dependent on libcurl to do it.
617     // Also disable the ticket option where implemented, since this breaks a variety
618     // of servers. Newer libcurl also does this for us.
619 #ifdef SSL_OP_NO_TICKET
620     SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_TICKET);
621 #else
622     SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
623 #endif
624
625 #ifndef XMLTOOLING_NO_XMLSEC
626     if (conf->m_cred)
627         conf->m_cred->attach(ssl_ctx);
628
629     if (conf->m_trustEngine) {
630         SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,NULL);
631 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
632         // With 0.9.7, we can pass a callback argument directly.
633         SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
634 #else
635         // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
636         // stuff the argument in the depth property where it will get copied to the context object
637         // that's handed to the callback.
638         SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),NULL);
639         SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
640 #endif
641     }
642 #endif
643
644     if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
645         return CURLE_SSL_CERTPROBLEM;
646
647     return CURLE_OK;
648 }