2 * Copyright 2001-2007 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * CURLSOAPTransport.cpp
20 * libcurl-based SOAPTransport implementation
24 #include "exceptions.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"
32 #include "util/Threads.h"
35 #include <curl/curl.h>
36 #include <openssl/x509_vfy.h>
38 using namespace xmltooling::logging;
39 using namespace xmltooling;
42 namespace xmltooling {
44 // Manages cache of socket connections via CURL handles.
45 class XMLTOOL_DLLLOCAL CURLPool
48 CURLPool() : m_size(0), m_lock(Mutex::create()),
49 m_log(Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL")) {}
52 CURL* get(const SOAPTransport::Address& addr);
53 void put(const char* from, const char* to, const char* endpoint, CURL* handle);
56 typedef map<string,vector<CURL*> > poolmap_t;
57 poolmap_t m_bindingMap;
58 list< vector<CURL*>* > m_pools;
64 static XMLTOOL_DLLLOCAL CURLPool* g_CURLPool = NULL;
66 class XMLTOOL_DLLLOCAL CURLSOAPTransport : public HTTPSOAPTransport, public OpenSSLSOAPTransport
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),
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");
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);
94 bool isConfidential() const {
95 return m_endpoint.find("https")==0;
98 bool setConnectTimeout(long timeout) {
99 return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
102 bool setTimeout(long timeout) {
103 return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
106 bool setAuth(transport_auth_t authType, const char* username=NULL, const char* password=NULL);
108 bool setVerifyHost(bool verify) {
109 return (curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,verify ? 2 : 0)==CURLE_OK);
112 #ifndef XMLTOOLING_NO_XMLSEC
113 bool setCredential(const Credential* cred=NULL) {
114 const OpenSSLCredential* down = dynamic_cast<const OpenSSLCredential*>(cred);
124 const X509TrustEngine* trustEngine=NULL,
125 const CredentialResolver* peerResolver=NULL,
126 CredentialCriteria* criteria=NULL,
129 const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
131 m_trustEngine = NULL;
132 m_peerResolver = NULL;
134 return (trustEngine==NULL);
136 m_trustEngine = down;
137 m_peerResolver = peerResolver;
138 m_criteria = criteria;
139 m_mandatory = mandatory;
145 bool useChunkedEncoding(bool chunked=true) {
150 bool setProviderOption(const char* provider, const char* option, const char* value) {
151 if (!provider || strcmp(provider, "CURL"))
153 // For libcurl, the option is an enum and the value type depends on the option.
154 CURLoption opt = static_cast<CURLoption>(strtol(option, NULL, 10));
155 if (opt < CURLOPTTYPE_OBJECTPOINT)
156 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
157 #ifdef CURLOPTTYPE_OFF_T
158 else if (opt < CURLOPTTYPE_OFF_T)
159 return (curl_easy_setopt(m_handle, opt, value) == CURLE_OK);
160 else if (sizeof(curl_off_t) == sizeof(long))
161 return (curl_easy_setopt(m_handle, opt, strtol(value, NULL, 10)) == CURLE_OK);
165 return (curl_easy_setopt(m_handle, opt, value) == CURLE_OK);
169 void send(istream& in) {
173 void send(istream* in=NULL);
179 bool isAuthenticated() const {
180 return m_authenticated;
183 void setAuthenticated(bool auth) {
184 m_authenticated = auth;
187 string getContentType() const;
189 bool setRequestHeader(const char* name, const char* val) {
191 temp=temp + ": " + val;
192 m_headers=curl_slist_append(m_headers,temp.c_str());
196 const vector<string>& getResponseHeader(const char* val) const;
198 bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=NULL) {
200 m_ssl_userptr=userptr;
206 string m_sender,m_peerName,m_endpoint,m_simplecreds;
208 stringstream m_stream;
209 struct curl_slist* m_headers;
210 map<string,vector<string> > m_response_headers;
211 #ifndef XMLTOOLING_NO_XMLSEC
212 const OpenSSLCredential* m_cred;
213 const OpenSSLTrustEngine* m_trustEngine;
214 const CredentialResolver* m_peerResolver;
215 CredentialCriteria* m_criteria;
218 ssl_ctx_callback_fn m_ssl_callback;
221 bool m_authenticated;
223 friend size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
224 friend CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
225 friend int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
228 // libcurl callback functions
229 size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
230 size_t XMLTOOL_DLLLOCAL curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream);
231 size_t XMLTOOL_DLLLOCAL curl_read_hook( void *ptr, size_t size, size_t nmemb, void *stream);
232 int XMLTOOL_DLLLOCAL curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr);
233 CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
234 #ifndef XMLTOOLING_NO_XMLSEC
235 int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
238 SOAPTransport* CURLSOAPTransportFactory(const SOAPTransport::Address& addr)
240 return new CURLSOAPTransport(addr);
244 void xmltooling::registerSOAPTransports()
246 XMLToolingConfig& conf=XMLToolingConfig::getConfig();
247 conf.SOAPTransportManager.registerFactory("http", CURLSOAPTransportFactory);
248 conf.SOAPTransportManager.registerFactory("https", CURLSOAPTransportFactory);
251 void xmltooling::initSOAPTransports()
253 g_CURLPool=new CURLPool();
256 void xmltooling::termSOAPTransports()
262 CURLPool::~CURLPool()
264 for (poolmap_t::iterator i=m_bindingMap.begin(); i!=m_bindingMap.end(); i++) {
265 for (vector<CURL*>::iterator j=i->second.begin(); j!=i->second.end(); j++)
266 curl_easy_cleanup(*j);
271 CURL* CURLPool::get(const SOAPTransport::Address& addr)
274 xmltooling::NDC("get");
276 m_log.debug("getting connection handle to %s", addr.m_endpoint);
277 string key(addr.m_endpoint);
279 key = key + '|' + addr.m_from;
281 key = key + '|' + addr.m_to;
283 poolmap_t::iterator i=m_bindingMap.find(key);
285 if (i!=m_bindingMap.end()) {
286 // Move this pool to the front of the list.
287 m_pools.remove(&(i->second));
288 m_pools.push_front(&(i->second));
290 // If a free connection exists, return it.
291 if (!(i->second.empty())) {
292 CURL* handle=i->second.back();
293 i->second.pop_back();
296 m_log.debug("returning existing connection handle from pool");
302 m_log.debug("nothing free in pool, returning new connection handle");
304 // Create a new connection and set non-varying options.
305 CURL* handle=curl_easy_init();
308 curl_easy_setopt(handle,CURLOPT_NOPROGRESS,1);
309 curl_easy_setopt(handle,CURLOPT_NOSIGNAL,1);
310 curl_easy_setopt(handle,CURLOPT_FAILONERROR,1);
311 curl_easy_setopt(handle,CURLOPT_SSL_CIPHER_LIST,"ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
312 // Verification of the peer is via TrustEngine only.
313 curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
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);
321 void CURLPool::put(const char* from, const char* to, const char* endpoint, CURL* handle)
323 string key(endpoint);
325 key = key + '|' + from;
327 key = key + '|' + to;
329 poolmap_t::iterator i=m_bindingMap.find(key);
330 if (i==m_bindingMap.end())
331 m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
333 i->second.push_back(handle);
336 if (++m_size > 256) {
337 // Kick a handle out from the back of the bus.
339 vector<CURL*>* corpse=m_pools.back();
340 if (!corpse->empty()) {
341 killit=corpse->back();
347 // Move an empty pool up to the front so we don't keep hitting it.
349 m_pools.push_front(corpse);
354 curl_easy_cleanup(killit);
356 xmltooling::NDC("put");
358 m_log.info("conn_pool_max limit reached, dropping an old connection");
362 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
364 if (authType==transport_auth_none) {
365 if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
367 return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL)==CURLE_OK);
371 case transport_auth_basic: flag = CURLAUTH_BASIC; break;
372 case transport_auth_digest: flag = CURLAUTH_DIGEST; break;
373 case transport_auth_ntlm: flag = CURLAUTH_NTLM; break;
374 case transport_auth_gss: flag = CURLAUTH_GSSNEGOTIATE; break;
375 default: return false;
377 if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
379 m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
380 return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
383 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
385 static vector<string> emptyVector;
387 map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
388 if (i!=m_response_headers.end())
391 for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
392 #ifdef HAVE_STRCASECMP
393 if (!strcasecmp(j->first.c_str(), name))
395 if (!stricmp(j->first.c_str(), name))
403 string CURLSOAPTransport::getContentType() const
405 char* content_type=NULL;
406 curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
407 return content_type ? content_type : "";
410 void CURLSOAPTransport::send(istream* in)
413 xmltooling::NDC ndc("send");
415 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL");
416 Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT".libcurl");
418 // For this implementation, it's sufficient to check for https as a sign of transport security.
419 if (m_mandatory && !isConfidential())
420 throw IOException("Blocking unprotected HTTP request, transport authentication by server required.");
424 // By this time, the handle has been prepared with the URL to use and the
425 // caller should have executed any set functions to manipulate it.
427 // Setup standard per-call curl properties.
428 curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
429 curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
430 if (m_chunked && in) {
431 curl_easy_setopt(m_handle,CURLOPT_POST,1);
432 m_headers=curl_slist_append(m_headers,"Transfer-Encoding: chunked");
433 curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,&curl_read_hook);
434 curl_easy_setopt(m_handle,CURLOPT_READDATA,in);
440 msg.append(buf,in->gcount());
442 curl_easy_setopt(m_handle,CURLOPT_POST,1);
443 curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,NULL);
444 curl_easy_setopt(m_handle,CURLOPT_POSTFIELDS,msg.c_str());
445 curl_easy_setopt(m_handle,CURLOPT_POSTFIELDSIZE,msg.length());
448 curl_easy_setopt(m_handle,CURLOPT_HTTPGET,1);
451 char curl_errorbuf[CURL_ERROR_SIZE];
453 curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
454 if (log_curl.isDebugEnabled())
455 curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
457 // Set request headers.
458 curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
460 #ifndef XMLTOOLING_NO_XMLSEC
461 if (m_ssl_callback || m_cred || m_trustEngine) {
463 if (m_ssl_callback) {
465 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
466 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
468 // Restore security "state". Necessary because the callback only runs
469 // when handshakes occur. Even new TCP connections won't execute it.
471 curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
473 m_authenticated=true;
476 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,NULL);
477 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,NULL);
481 log.debug("sending SOAP message to %s", m_endpoint.c_str());
482 if (curl_easy_perform(m_handle) != CURLE_OK) {
484 string("CURLSOAPTransport failed while contacting SOAP endpoint (") + m_endpoint + "): " +
485 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
489 // callback to buffer headers from server
490 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
492 // only handle single-byte data
495 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
496 char* buf = (char*)malloc(nmemb + 1);
498 memset(buf,0,nmemb + 1);
499 memcpy(buf,ptr,nmemb);
500 char* sep=(char*)strchr(buf,':');
505 char* white=buf+nmemb-1;
506 while (isspace(*white))
508 ctx->m_response_headers[buf].push_back(sep);
516 // callback to send data to server
517 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
519 // stream is actually an istream pointer
520 istream* buf=reinterpret_cast<istream*>(stream);
521 buf->read(reinterpret_cast<char*>(ptr),size*nmemb);
522 return buf->gcount();
525 // callback to buffer data from server
526 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
528 size_t len = size*nmemb;
529 reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
533 // callback for curl debug data
534 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
536 // *ptr is actually a logging object
538 CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
539 for (unsigned char* ch=(unsigned char*)data; len && (isprint(*ch) || isspace(*ch)); len--)
544 #ifndef XMLTOOLING_NO_XMLSEC
545 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
547 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURL");
548 log.debug("invoking custom X.509 verify callback");
549 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
550 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
552 // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
553 // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
554 // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
555 // negative in the SSL structure's int member.
556 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
557 SSL_get_verify_depth(
558 reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
564 if (ctx->m_criteria) {
565 ctx->m_criteria->setUsage(Credential::TLS_CREDENTIAL);
566 // Bypass name check (handled for us by curl).
567 ctx->m_criteria->setPeerName(NULL);
568 success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),ctx->m_criteria);
571 // Bypass name check (handled for us by curl).
572 CredentialCriteria cc;
573 cc.setUsage(Credential::TLS_CREDENTIAL);
574 success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),&cc);
578 log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
579 x509_ctx->error=X509_V_ERR_APPLICATION_VERIFICATION; // generic error, check log for plugin specifics
580 ctx->setAuthenticated(false);
581 return ctx->m_mandatory ? 0 : 1;
584 // Signal success. Hopefully it doesn't matter what's actually in the structure now.
585 ctx->setAuthenticated(true);
590 // callback to invoke a caller-defined SSL callback
591 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
593 CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
595 // Manually disable SSLv2 so we're not dependent on libcurl to do it.
596 // Also disable the ticket option where implemented, since this breaks a variety
597 // of servers. Newer libcurl also does this for us.
598 #ifdef SSL_OP_NO_TICKET
599 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_TICKET);
601 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
604 #ifndef XMLTOOLING_NO_XMLSEC
606 conf->m_cred->attach(ssl_ctx);
608 if (conf->m_trustEngine) {
609 SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,NULL);
610 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
611 // With 0.9.7, we can pass a callback argument directly.
612 SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
614 // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
615 // stuff the argument in the depth property where it will get copied to the context object
616 // that's handed to the callback.
617 SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),NULL);
618 SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
623 if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
624 return CURLE_SSL_CERTPROBLEM;