https://issues.shibboleth.net/jira/browse/SSPCPP-647
[shibboleth/cpp-xmltooling.git] / xmltooling / soap / impl / CURLSOAPTransport.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * CURLSOAPTransport.cpp
23  *
24  * libcurl-based SOAPTransport implementation.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "logging.h"
30 #include "security/CredentialCriteria.h"
31 #include "security/OpenSSLTrustEngine.h"
32 #include "security/OpenSSLCredential.h"
33 #include "soap/HTTPSOAPTransport.h"
34 #include "soap/OpenSSLSOAPTransport.h"
35 #include "util/NDC.h"
36 #include "util/Threads.h"
37
38 #include <list>
39 #include <curl/curl.h>
40 #include <openssl/x509_vfy.h>
41
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace xmltooling {
47
48     // Manages cache of socket connections via CURL handles.
49     class XMLTOOL_DLLLOCAL CURLPool
50     {
51     public:
52         CURLPool() : m_size(0), m_lock(Mutex::create()),
53             m_log(Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL")) {}
54         ~CURLPool();
55
56         CURL* get(const SOAPTransport::Address& addr);
57         void put(const char* from, const char* to, const char* endpoint, CURL* handle);
58
59     private:
60         typedef map<string,vector<CURL*> > poolmap_t;
61         poolmap_t m_bindingMap;
62         list< vector<CURL*>* > m_pools;
63         long m_size;
64         Mutex* m_lock;
65         Category& m_log;
66     };
67
68     static XMLTOOL_DLLLOCAL CURLPool* g_CURLPool = nullptr;
69
70     class XMLTOOL_DLLLOCAL CURLSOAPTransport : public HTTPSOAPTransport, public OpenSSLSOAPTransport
71     {
72     public:
73         CURLSOAPTransport(const Address& addr)
74             : m_sender(addr.m_from ? addr.m_from : ""), m_peerName(addr.m_to ? addr.m_to : ""), m_endpoint(addr.m_endpoint),
75                 m_handle(nullptr), m_keepHandle(false), m_headers(nullptr),
76 #ifndef XMLTOOLING_NO_XMLSEC
77                     m_cred(nullptr), m_trustEngine(nullptr), m_peerResolver(nullptr), m_mandatory(false),
78 #endif
79                     m_openssl_ops(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3), m_ssl_callback(nullptr), m_ssl_userptr(nullptr),
80                     m_chunked(true), m_authenticated(false), m_cacheTag(nullptr) {
81             m_handle = g_CURLPool->get(addr);
82             curl_easy_setopt(m_handle,CURLOPT_URL,addr.m_endpoint);
83             curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,15);
84             curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,30);
85             curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0);
86             curl_easy_setopt(m_handle,CURLOPT_USERPWD,nullptr);
87             curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,2);
88             curl_easy_setopt(m_handle,CURLOPT_HEADERDATA,this);
89             m_headers=curl_slist_append(m_headers,"Content-Type: text/xml");
90         }
91
92         virtual ~CURLSOAPTransport() {
93             curl_slist_free_all(m_headers);
94             if (m_keepHandle) {
95                 curl_easy_setopt(m_handle, CURLOPT_USERAGENT, nullptr);
96                 curl_easy_setopt(m_handle, CURLOPT_ERRORBUFFER, nullptr);
97                 curl_easy_setopt(m_handle, CURLOPT_PRIVATE, m_authenticated ? "secure" : nullptr); // Save off security "state".
98                 g_CURLPool->put(m_sender.c_str(), m_peerName.c_str(), m_endpoint.c_str(), m_handle);
99             }
100             else {
101                 curl_easy_cleanup(m_handle);
102             }
103         }
104
105         bool isConfidential() const {
106             return m_endpoint.find("https")==0;
107         }
108
109         bool setConnectTimeout(long timeout) {
110             return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
111         }
112
113         bool setTimeout(long timeout) {
114             return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
115         }
116
117         bool setAuth(transport_auth_t authType, const char* username=nullptr, const char* password=nullptr);
118
119         bool setVerifyHost(bool verify) {
120             return (curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,verify ? 2 : 0)==CURLE_OK);
121         }
122
123 #ifndef XMLTOOLING_NO_XMLSEC
124         bool setCredential(const Credential* cred=nullptr) {
125             const OpenSSLCredential* down = dynamic_cast<const OpenSSLCredential*>(cred);
126             if (!down) {
127                 m_cred = nullptr;
128                 return (cred==nullptr);
129             }
130             m_cred = down;
131             return true;
132         }
133
134         bool setTrustEngine(
135             const X509TrustEngine* trustEngine=nullptr,
136             const CredentialResolver* peerResolver=nullptr,
137             CredentialCriteria* criteria=nullptr,
138             bool mandatory=true
139             ) {
140             const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
141             if (!down) {
142                 m_trustEngine = nullptr;
143                 m_peerResolver = nullptr;
144                 m_criteria = nullptr;
145                 return (trustEngine==nullptr);
146             }
147             m_trustEngine = down;
148             m_peerResolver = peerResolver;
149             m_criteria = criteria;
150             m_mandatory = mandatory;
151             return true;
152         }
153
154 #endif
155
156         bool useChunkedEncoding(bool chunked=true) {
157             m_chunked = chunked;
158             return true;
159         }
160
161         bool followRedirects(bool follow, unsigned int maxRedirs) {
162             return (
163                 curl_easy_setopt(m_handle, CURLOPT_FOLLOWLOCATION, (follow ? 1 : 0)) == CURLE_OK &&
164                 curl_easy_setopt(m_handle, CURLOPT_MAXREDIRS, (follow ? maxRedirs : 0)) == CURLE_OK
165                 );
166         }
167
168         bool setCacheTag(string* cacheTag) {
169             m_cacheTag = cacheTag;
170             return true;
171         }
172
173         bool setProviderOption(const char* provider, const char* option, const char* value);
174
175         void send(istream& in) {
176             send(&in);
177         }
178
179         void send(istream* in=nullptr);
180
181         istream& receive() {
182             return m_stream;
183         }
184
185         bool isAuthenticated() const {
186             return m_authenticated;
187         }
188
189         void setAuthenticated(bool auth) {
190             m_authenticated = auth;
191         }
192
193         string getContentType() const;
194         long getStatusCode() const;
195
196         bool setRequestHeader(const char* name, const char* val) {
197             string temp(name);
198             temp=temp + ": " + val;
199             m_headers=curl_slist_append(m_headers,temp.c_str());
200             return true;
201         }
202
203         const vector<string>& getResponseHeader(const char* val) const;
204
205         bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=nullptr) {
206             m_ssl_callback=fn;
207             m_ssl_userptr=userptr;
208             return true;
209         }
210
211     private:
212         // per-call state
213         string m_sender,m_peerName,m_endpoint,m_simplecreds;
214         CURL* m_handle;
215         bool m_keepHandle;
216         stringstream m_stream;
217         struct curl_slist* m_headers;
218                 string m_useragent;
219         map<string,vector<string> > m_response_headers;
220         vector<string> m_saved_options;
221 #ifndef XMLTOOLING_NO_XMLSEC
222         const OpenSSLCredential* m_cred;
223         const OpenSSLTrustEngine* m_trustEngine;
224         const CredentialResolver* m_peerResolver;
225         CredentialCriteria* m_criteria;
226         bool m_mandatory;
227 #endif
228         int m_openssl_ops;
229         ssl_ctx_callback_fn m_ssl_callback;
230         void* m_ssl_userptr;
231         bool m_chunked;
232         bool m_authenticated;
233         string* m_cacheTag;
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::initSOAPTransports()
257 {
258     g_CURLPool=new CURLPool();
259 }
260
261 void xmltooling::termSOAPTransports()
262 {
263     delete g_CURLPool;
264     g_CURLPool = nullptr;
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 nullptr;
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     // This may (but probably won't) help with < 7.20 bug in DNS caching.
317     curl_easy_setopt(handle,CURLOPT_DNS_CACHE_TIMEOUT,120);
318     curl_easy_setopt(handle,CURLOPT_SSL_CIPHER_LIST,"ALL:!aNULL:!LOW:!EXPORT:!RC4:!SSLv2");
319     // Verification of the peer is via TrustEngine only.
320     curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
321     curl_easy_setopt(handle,CURLOPT_CAINFO,nullptr);
322     curl_easy_setopt(handle,CURLOPT_HEADERFUNCTION,&curl_header_hook);
323     curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION,&curl_write_hook);
324     curl_easy_setopt(handle,CURLOPT_DEBUGFUNCTION,&curl_debug_hook);
325     return handle;
326 }
327
328 void CURLPool::put(const char* from, const char* to, const char* endpoint, CURL* handle)
329 {
330     string key(endpoint);
331     if (from)
332         key = key + '|' + from;
333     if (to)
334         key = key + '|' + to;
335     m_lock->lock();
336     poolmap_t::iterator i=m_bindingMap.find(key);
337     if (i==m_bindingMap.end())
338         m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
339     else
340         i->second.push_back(handle);
341
342     CURL* killit=nullptr;
343     if (++m_size > 256) {
344         // Kick a handle out from the back of the bus.
345         while (true) {
346             vector<CURL*>* corpse=m_pools.back();
347             if (!corpse->empty()) {
348                 killit=corpse->back();
349                 corpse->pop_back();
350                 m_size--;
351                 break;
352             }
353
354             // Move an empty pool up to the front so we don't keep hitting it.
355             m_pools.pop_back();
356             m_pools.push_front(corpse);
357         }
358     }
359     m_lock->unlock();
360     if (killit) {
361         curl_easy_cleanup(killit);
362 #ifdef _DEBUG
363         xmltooling::NDC("put");
364 #endif
365         m_log.info("conn_pool_max limit reached, dropping an old connection");
366     }
367 }
368
369 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
370 {
371     if (authType==transport_auth_none) {
372         if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
373             return false;
374         return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,nullptr)==CURLE_OK);
375     }
376     long flag=0;
377     switch (authType) {
378         case transport_auth_basic:    flag = CURLAUTH_BASIC; break;
379         case transport_auth_digest:   flag = CURLAUTH_DIGEST; break;
380         case transport_auth_ntlm:     flag = CURLAUTH_NTLM; break;
381         case transport_auth_gss:      flag = CURLAUTH_GSSNEGOTIATE; break;
382         default:            return false;
383     }
384     if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
385         return false;
386     m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
387     return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
388 }
389
390 bool CURLSOAPTransport::setProviderOption(const char* provider, const char* option, const char* value)
391 {
392     if (!provider || !option || !value) {
393         return false;
394     }
395     else if (!strcmp(provider, "OpenSSL")) {
396         if (!strcmp(option, "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION") && (*value=='1' || *value=='t')) {
397             // If the new option to enable buggy rengotiation is available, set it.
398             // Otherwise, signal false if this is newer than 0.9.8k, because that
399             // means it's 0.9.8l, which blocks renegotiation, and therefore will
400             // not honor this request. Older versions are buggy, so behave as though
401             // the flag was set anyway, so we signal true.
402 #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
403             m_openssl_ops |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
404             return true;
405 #elif (OPENSSL_VERSION_NUMBER > 0x009080bfL)
406             return false;
407 #else
408             return true;
409 #endif
410         }
411         return false;
412     }
413     else if (strcmp(provider, "CURL")) {
414         return false;
415     }
416
417     // For libcurl, the option is an enum and the value type depends on the option.
418     CURLoption opt = static_cast<CURLoption>(strtol(option, nullptr, 10));
419     if (opt < CURLOPTTYPE_OBJECTPOINT)
420         return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
421 #ifdef CURLOPTTYPE_OFF_T
422     else if (opt < CURLOPTTYPE_OFF_T) {
423         if (value)
424             m_saved_options.push_back(value);
425         return (curl_easy_setopt(m_handle, opt, value ? m_saved_options.back().c_str() : nullptr) == CURLE_OK);
426     }
427 # ifdef HAVE_CURL_OFF_T
428     else if (sizeof(curl_off_t) == sizeof(long))
429         return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
430 # else
431     else if (sizeof(off_t) == sizeof(long))
432         return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
433 # endif
434     return false;
435 #else
436     else {
437         if (value)
438             m_saved_options.push_back(value);
439         return (curl_easy_setopt(m_handle, opt, value ? m_saved_options.back().c_str() : nullptr) == CURLE_OK);
440     }
441 #endif
442 }
443
444 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
445 {
446     static vector<string> emptyVector;
447
448     map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
449     if (i!=m_response_headers.end())
450         return i->second;
451
452     for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
453 #ifdef HAVE_STRCASECMP
454         if (!strcasecmp(j->first.c_str(), name))
455 #else
456         if (!stricmp(j->first.c_str(), name))
457 #endif
458             return j->second;
459     }
460
461     return emptyVector;
462 }
463
464 string CURLSOAPTransport::getContentType() const
465 {
466     char* content_type=nullptr;
467     curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
468     return content_type ? content_type : "";
469 }
470
471 long CURLSOAPTransport::getStatusCode() const
472 {
473     long code=200;
474     if (curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &code) != CURLE_OK)
475         code = 200;
476     return code;
477 }
478
479 void CURLSOAPTransport::send(istream* in)
480 {
481 #ifdef _DEBUG
482     xmltooling::NDC ndc("send");
483 #endif
484     Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL");
485     Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT ".libcurl");
486
487     // For this implementation, it's sufficient to check for https as a sign of transport security.
488     if (m_mandatory && !isConfidential())
489         throw IOException("Blocking unprotected HTTP request, transport authentication by server required.");
490
491     string msg;
492
493     // By this time, the handle has been prepared with the URL to use and the
494     // caller should have executed any set functions to manipulate it.
495
496     // Setup standard per-call curl properties.
497     curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
498     curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
499     if (m_chunked && in) {
500         curl_easy_setopt(m_handle,CURLOPT_POST,1);
501         m_headers=curl_slist_append(m_headers,"Transfer-Encoding: chunked");
502         curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,&curl_read_hook);
503         curl_easy_setopt(m_handle,CURLOPT_READDATA,in);
504     }
505     else if (in) {
506         char buf[1024];
507         while (*in) {
508             in->read(buf,1024);
509             msg.append(buf,in->gcount());
510         }
511         curl_easy_setopt(m_handle,CURLOPT_POST,1);
512         curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,nullptr);
513         curl_easy_setopt(m_handle,CURLOPT_POSTFIELDS,msg.c_str());
514         curl_easy_setopt(m_handle,CURLOPT_POSTFIELDSIZE,msg.length());
515     }
516     else {
517         curl_easy_setopt(m_handle,CURLOPT_HTTPGET,1);
518         curl_easy_setopt(m_handle,CURLOPT_FOLLOWLOCATION,1);
519         curl_easy_setopt(m_handle,CURLOPT_MAXREDIRS,6);
520     }
521
522     char curl_errorbuf[CURL_ERROR_SIZE];
523     curl_errorbuf[0]=0;
524     curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
525     if (log_curl.isDebugEnabled())
526         curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
527
528     // Check for cache tag.
529     if (m_cacheTag && !m_cacheTag->empty()) {
530         string hdr("If-None-Match: ");
531         hdr += *m_cacheTag;
532         m_headers = curl_slist_append(m_headers, hdr.c_str());
533     }
534
535     m_useragent = XMLToolingConfig::getConfig().user_agent;
536     if (!m_useragent.empty()) {
537         curl_version_info_data* curlver = curl_version_info(CURLVERSION_NOW);
538
539         if (curlver) {
540             m_useragent = m_useragent + " libcurl/" + curlver->version + ' ' + curlver->ssl_version;
541         }
542
543         curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_useragent.c_str());
544     }
545
546     // Set request headers.
547     curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
548
549 #ifndef XMLTOOLING_NO_XMLSEC
550     if (m_ssl_callback || m_cred || m_trustEngine) {
551 #else
552     if (m_ssl_callback) {
553 #endif
554         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
555         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
556
557         // Restore security "state". Necessary because the callback only runs
558         // when handshakes occur. Even new TCP connections won't execute it.
559         char* priv=nullptr;
560         curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
561         if (priv)
562             m_authenticated=true;
563     }
564     else {
565         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,nullptr);
566         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,nullptr);
567     }
568
569     // Make the call.
570     log.debug("sending SOAP message to %s", m_endpoint.c_str());
571     CURLcode code = curl_easy_perform(m_handle);
572     if (code != CURLE_OK) {
573         if (code == CURLE_SSL_CIPHER) {
574             log.error("on Red Hat 6+, make sure libcurl used is built with OpenSSL");
575         }
576         throw IOException(
577             string("CURLSOAPTransport failed while contacting SOAP endpoint (") + m_endpoint + "): " +
578                 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
579     }
580
581     // This won't prevent every possible failed connection from being kept, but it's something.
582     m_keepHandle = true;
583
584     // Check for outgoing cache tag.
585     if (m_cacheTag) {
586         const vector<string>& tags = getResponseHeader("ETag");
587         if (!tags.empty())
588             *m_cacheTag = tags.front();
589     }
590 }
591
592 // callback to buffer headers from server
593 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
594 {
595     // only handle single-byte data
596     if (size!=1)
597         return 0;
598     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
599     char* buf = (char*)malloc(nmemb + 1);
600     if (buf) {
601         memset(buf,0,nmemb + 1);
602         memcpy(buf,ptr,nmemb);
603         char* sep=(char*)strchr(buf,':');
604         if (sep) {
605             *(sep++)=0;
606             while (*sep==' ')
607                 *(sep++)=0;
608             char* white=buf+nmemb-1;
609             while (isspace(*white))
610                 *(white--)=0;
611             ctx->m_response_headers[buf].push_back(sep);
612         }
613         free(buf);
614         return nmemb;
615     }
616     return 0;
617 }
618
619 // callback to send data to server
620 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
621 {
622     // stream is actually an istream pointer
623     istream* buf=reinterpret_cast<istream*>(stream);
624     buf->read(reinterpret_cast<char*>(ptr),size*nmemb);
625     return buf->gcount();
626 }
627
628 // callback to buffer data from server
629 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
630 {
631     size_t len = size*nmemb;
632     reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
633     return len;
634 }
635
636 // callback for curl debug data
637 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
638 {
639     // *ptr is actually a logging object
640     if (!ptr) return 0;
641     CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
642     for (unsigned char* ch=(unsigned char*)data; len && (isprint(*ch) || isspace(*ch)); len--)
643         log << *ch++;
644     return 0;
645 }
646
647 #ifndef XMLTOOLING_NO_XMLSEC
648 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
649 {
650     Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL");
651     log.debug("invoking custom X.509 verify callback");
652 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
653     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
654 #else
655     // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
656     // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
657     // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
658     // negative in the SSL structure's int member.
659     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
660         SSL_get_verify_depth(
661             reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
662             )
663         );
664 #endif
665
666     bool success=false;
667     if (ctx->m_criteria) {
668         ctx->m_criteria->setUsage(Credential::TLS_CREDENTIAL);
669         // Bypass name check (handled for us by curl).
670         ctx->m_criteria->setPeerName(nullptr);
671         success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),ctx->m_criteria);
672     }
673     else {
674         // Bypass name check (handled for us by curl).
675         CredentialCriteria cc;
676         cc.setUsage(Credential::TLS_CREDENTIAL);
677         success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),&cc);
678     }
679
680     if (!success) {
681         log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
682         if (x509_ctx->cert) {
683             BIO* b = BIO_new(BIO_s_mem());
684             X509_print(b, x509_ctx->cert);
685             BUF_MEM* bptr = nullptr;
686             BIO_get_mem_ptr(b, &bptr);
687             if (bptr && bptr->length > 0) {
688                 string s(bptr->data, bptr->length);
689                 if (ctx->m_mandatory)
690                     log.error(s);
691                 else
692                     log.debug(s);
693             }
694             BIO_free(b);
695         }
696         x509_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;     // generic error, check log for plugin specifics
697         ctx->setAuthenticated(false);
698         return ctx->m_mandatory ? 0 : 1;
699     }
700
701     // Signal success. Hopefully it doesn't matter what's actually in the structure now.
702     ctx->setAuthenticated(true);
703     return 1;
704 }
705 #endif
706
707 // callback to invoke a caller-defined SSL callback
708 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
709 {
710     CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
711
712     // Default flags manually disable SSLv2 and SSLv3 so we're not dependent on libcurl
713     // to do it. Also disable the ticket option where implemented, since this breaks a
714     // variety of servers. Newer libcurl also does this for us.
715 #ifdef SSL_OP_NO_TICKET
716     SSL_CTX_set_options(ssl_ctx, conf->m_openssl_ops|SSL_OP_NO_TICKET);
717 #else
718     SSL_CTX_set_options(ssl_ctx, conf->m_openssl_ops);
719 #endif
720
721 #ifndef XMLTOOLING_NO_XMLSEC
722     if (conf->m_cred)
723         conf->m_cred->attach(ssl_ctx);
724
725     if (conf->m_trustEngine) {
726         SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,nullptr);
727 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
728         // With 0.9.7, we can pass a callback argument directly.
729         SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
730 #else
731         // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
732         // stuff the argument in the depth property where it will get copied to the context object
733         // that's handed to the callback.
734         SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),nullptr);
735         SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
736 #endif
737     }
738 #endif
739
740     if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
741         return CURLE_SSL_CERTPROBLEM;
742
743     return CURLE_OK;
744 }