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