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"
25 #include "security/CredentialCriteria.h"
26 #include "security/OpenSSLTrustEngine.h"
27 #include "security/OpenSSLCredential.h"
28 #include "soap/HTTPSOAPTransport.h"
29 #include "soap/OpenSSLSOAPTransport.h"
31 #include "util/Threads.h"
34 #include <curl/curl.h>
35 #include <log4cpp/Category.hh>
36 #include <openssl/x509_vfy.h>
38 using namespace xmltooling;
39 using namespace log4cpp;
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.CURLPool")) {}
52 CURL* get(const char* to, const char* endpoint);
53 void put(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 char* peerName, const char* endpoint)
70 : m_peerName(peerName ? peerName : ""), m_endpoint(endpoint), m_handle(NULL), m_headers(NULL),
71 #ifndef XMLTOOLING_NO_XMLSEC
72 m_cred(NULL), m_trustEngine(NULL), m_peerResolver(NULL), m_mandatory(false),
74 m_ssl_callback(NULL), m_ssl_userptr(NULL), m_chunked(true), m_secure(false) {
75 m_handle = g_CURLPool->get(peerName, endpoint);
76 curl_easy_setopt(m_handle,CURLOPT_URL,endpoint);
77 curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,15);
78 curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,30);
79 curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0);
80 curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL);
81 curl_easy_setopt(m_handle,CURLOPT_HEADERDATA,this);
82 m_headers=curl_slist_append(m_headers,"Content-Type: text/xml");
85 virtual ~CURLSOAPTransport() {
86 curl_slist_free_all(m_headers);
87 curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,NULL);
88 curl_easy_setopt(m_handle,CURLOPT_PRIVATE,m_secure ? "secure" : NULL); // Save off security "state".
89 g_CURLPool->put(m_peerName.c_str(), m_endpoint.c_str(), m_handle);
92 bool isConfidential() const {
93 return m_endpoint.find("https")==0;
96 bool setConnectTimeout(long timeout) {
97 return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
100 bool setTimeout(long timeout) {
101 return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
104 bool setAuth(transport_auth_t authType, const char* username=NULL, const char* password=NULL);
106 #ifndef XMLTOOLING_NO_XMLSEC
107 bool setCredential(const Credential* cred=NULL) {
108 const OpenSSLCredential* down = dynamic_cast<const OpenSSLCredential*>(cred);
118 const X509TrustEngine* trustEngine=NULL,
119 const CredentialResolver* peerResolver=NULL,
120 CredentialCriteria* criteria=NULL,
123 const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
125 m_trustEngine = NULL;
126 m_peerResolver = NULL;
128 return (trustEngine==NULL);
130 m_trustEngine = down;
131 m_peerResolver = peerResolver;
132 m_criteria = criteria;
133 m_mandatory = mandatory;
139 bool useChunkedEncoding(bool chunked=true) {
144 void send(istream& in);
150 bool isSecure() const {
154 void setSecure(bool secure) {
158 string getContentType() const;
160 bool setRequestHeader(const char* name, const char* val) {
162 temp=temp + ": " + val;
163 m_headers=curl_slist_append(m_headers,temp.c_str());
167 const vector<string>& getResponseHeader(const char* val) const;
169 bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=NULL) {
171 m_ssl_userptr=userptr;
177 string m_peerName,m_endpoint,m_simplecreds;
179 stringstream m_stream;
180 struct curl_slist* m_headers;
181 map<string,vector<string> > m_response_headers;
182 #ifndef XMLTOOLING_NO_XMLSEC
183 const OpenSSLCredential* m_cred;
184 const OpenSSLTrustEngine* m_trustEngine;
185 const CredentialResolver* m_peerResolver;
186 CredentialCriteria* m_criteria;
189 ssl_ctx_callback_fn m_ssl_callback;
194 friend size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
195 friend CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
196 friend int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
199 // libcurl callback functions
200 size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
201 size_t XMLTOOL_DLLLOCAL curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream);
202 size_t XMLTOOL_DLLLOCAL curl_read_hook( void *ptr, size_t size, size_t nmemb, void *stream);
203 int XMLTOOL_DLLLOCAL curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr);
204 CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
205 #ifndef XMLTOOLING_NO_XMLSEC
206 int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
209 SOAPTransport* CURLSOAPTransportFactory(const pair<const char*,const char*>& dest)
211 return new CURLSOAPTransport(dest.first, dest.second);
215 void xmltooling::registerSOAPTransports()
217 XMLToolingConfig& conf=XMLToolingConfig::getConfig();
218 conf.SOAPTransportManager.registerFactory("http", CURLSOAPTransportFactory);
219 conf.SOAPTransportManager.registerFactory("https", CURLSOAPTransportFactory);
222 void xmltooling::initSOAPTransports()
224 g_CURLPool=new CURLPool();
227 void xmltooling::termSOAPTransports()
233 CURLPool::~CURLPool()
235 for (poolmap_t::iterator i=m_bindingMap.begin(); i!=m_bindingMap.end(); i++) {
236 for (vector<CURL*>::iterator j=i->second.begin(); j!=i->second.end(); j++)
237 curl_easy_cleanup(*j);
242 CURL* CURLPool::get(const char* to, const char* endpoint)
245 xmltooling::NDC("get");
247 m_log.debug("getting connection handle to %s", endpoint);
249 poolmap_t::iterator i=m_bindingMap.find(string(to) + "|" + endpoint);
251 if (i!=m_bindingMap.end()) {
252 // Move this pool to the front of the list.
253 m_pools.remove(&(i->second));
254 m_pools.push_front(&(i->second));
256 // If a free connection exists, return it.
257 if (!(i->second.empty())) {
258 CURL* handle=i->second.back();
259 i->second.pop_back();
262 m_log.debug("returning existing connection handle from pool");
268 m_log.debug("nothing free in pool, returning new connection handle");
270 // Create a new connection and set non-varying options.
271 CURL* handle=curl_easy_init();
274 curl_easy_setopt(handle,CURLOPT_NOPROGRESS,1);
275 curl_easy_setopt(handle,CURLOPT_NOSIGNAL,1);
276 curl_easy_setopt(handle,CURLOPT_FAILONERROR,1);
277 curl_easy_setopt(handle,CURLOPT_SSLVERSION,3);
278 // Verification of the peer is via TrustEngine only.
279 curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
280 curl_easy_setopt(handle,CURLOPT_SSL_VERIFYHOST,2);
281 curl_easy_setopt(handle,CURLOPT_HEADERFUNCTION,&curl_header_hook);
282 curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION,&curl_write_hook);
283 curl_easy_setopt(handle,CURLOPT_DEBUGFUNCTION,&curl_debug_hook);
288 void CURLPool::put(const char* to, const char* endpoint, CURL* handle)
290 string key = string(to) + "|" + endpoint;
292 poolmap_t::iterator i=m_bindingMap.find(key);
293 if (i==m_bindingMap.end())
294 m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
296 i->second.push_back(handle);
299 if (++m_size > 256) {
300 // Kick a handle out from the back of the bus.
302 vector<CURL*>* corpse=m_pools.back();
303 if (!corpse->empty()) {
304 killit=corpse->back();
310 // Move an empty pool up to the front so we don't keep hitting it.
312 m_pools.push_front(corpse);
317 curl_easy_cleanup(killit);
319 xmltooling::NDC("put");
321 m_log.info("conn_pool_max limit reached, dropping an old connection");
325 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
327 if (authType==transport_auth_none) {
328 if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
330 return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL)==CURLE_OK);
334 case transport_auth_basic: flag = CURLAUTH_BASIC; break;
335 case transport_auth_digest: flag = CURLAUTH_DIGEST; break;
336 case transport_auth_ntlm: flag = CURLAUTH_NTLM; break;
337 case transport_auth_gss: flag = CURLAUTH_GSSNEGOTIATE; break;
338 default: return false;
340 if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
342 m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
343 return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
346 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
348 static vector<string> emptyVector;
350 map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
351 if (i!=m_response_headers.end())
354 for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
355 #ifdef HAVE_STRCASECMP
356 if (!strcasecmp(j->first.c_str(), name))
358 if (!stricmp(j->first.c_str(), name))
366 string CURLSOAPTransport::getContentType() const
368 char* content_type=NULL;
369 curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
370 return content_type ? content_type : "";
373 void CURLSOAPTransport::send(istream& in)
376 xmltooling::NDC ndc("send");
378 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport");
379 Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT".libcurl");
383 // By this time, the handle has been prepared with the URL to use and the
384 // caller should have executed any set functions to manipulate it.
386 // Setup standard per-call curl properties.
387 curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
388 curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
389 curl_easy_setopt(m_handle,CURLOPT_POST,1);
391 m_headers=curl_slist_append(m_headers,"Transfer-Encoding: chunked");
392 curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,&curl_read_hook);
393 curl_easy_setopt(m_handle,CURLOPT_READDATA,&in);
399 msg.append(buf,in.gcount());
401 curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,NULL);
402 curl_easy_setopt(m_handle,CURLOPT_POSTFIELDS,msg.c_str());
403 curl_easy_setopt(m_handle,CURLOPT_POSTFIELDSIZE,msg.length());
406 char curl_errorbuf[CURL_ERROR_SIZE];
408 curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
409 if (log_curl.isDebugEnabled())
410 curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
412 // Set request headers.
413 curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
415 #ifndef XMLTOOLING_NO_XMLSEC
416 if (m_ssl_callback || m_cred || m_trustEngine) {
418 if (m_ssl_callback) {
420 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
421 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
423 // Restore security "state". Necessary because the callback only runs
424 // when handshakes occur. Even new TCP connections won't execute it.
426 curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
431 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,NULL);
432 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,NULL);
436 log.debug("sending SOAP message to %s", m_endpoint.c_str());
437 if (curl_easy_perform(m_handle) != CURLE_OK) {
439 string("CURLSOAPTransport failed while contacting SOAP responder: ") +
440 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
444 // callback to buffer headers from server
445 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
447 // only handle single-byte data
450 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
451 char* buf = (char*)malloc(nmemb + 1);
453 memset(buf,0,nmemb + 1);
454 memcpy(buf,ptr,nmemb);
455 char* sep=(char*)strchr(buf,':');
460 char* white=buf+nmemb-1;
461 while (isspace(*white))
463 ctx->m_response_headers[buf].push_back(sep);
471 // callback to send data to server
472 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
474 // *stream is actually an istream object
475 istream& buf=*(reinterpret_cast<istream*>(stream));
476 buf.read(reinterpret_cast<char*>(ptr),size*nmemb);
480 // callback to buffer data from server
481 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
483 size_t len = size*nmemb;
484 reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
488 // callback for curl debug data
489 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
491 // *ptr is actually a logging object
493 CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
494 for (char* ch=data; len && (isprint(*ch) || isspace(*ch)); len--)
496 log << CategoryStream::ENDLINE;
500 #ifndef XMLTOOLING_NO_XMLSEC
501 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
503 Category& log = Category::getInstance("OpenSSL");
504 log.debug("invoking X509 verify callback");
505 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
506 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
508 // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
509 // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
510 // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
511 // negative in the SSL structure's int member.
512 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
513 SSL_get_verify_depth(
514 reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
520 if (ctx->m_criteria) {
521 ctx->m_criteria->setUsage(CredentialCriteria::TLS_CREDENTIAL);
522 // Bypass name check (handled for us by curl).
523 ctx->m_criteria->setPeerName(NULL);
524 success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),ctx->m_criteria);
527 // Bypass name check (handled for us by curl).
528 CredentialCriteria cc;
529 cc.setUsage(CredentialCriteria::TLS_CREDENTIAL);
530 success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),&cc);
534 log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
535 x509_ctx->error=X509_V_ERR_APPLICATION_VERIFICATION; // generic error, check log for plugin specifics
536 ctx->setSecure(false);
537 return ctx->m_mandatory ? 0 : 1;
540 // Signal success. Hopefully it doesn't matter what's actually in the structure now.
541 ctx->setSecure(true);
546 // callback to invoke a caller-defined SSL callback
547 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
549 CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
551 #ifndef XMLTOOLING_NO_XMLSEC
553 conf->m_cred->attach(ssl_ctx);
555 if (conf->m_trustEngine) {
556 SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,NULL);
557 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
558 // With 0.9.7, we can pass a callback argument directly.
559 SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
561 // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
562 // stuff the argument in the depth property where it will get copied to the context object
563 // that's handed to the callback.
564 SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),NULL);
565 SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
570 if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
571 return CURLE_SSL_CERTPROBLEM;