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