83d3da9c3c54bc828649e0ad98c335cb7e05a0ba
[shibboleth/xmltooling.git] / xmltooling / soap / impl / CURLSOAPTransport.cpp
1 /*
2  *  Copyright 2001-2007 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 "security/OpenSSLTrustEngine.h"
26 #include "signature/OpenSSLCredentialResolver.h"
27 #include "soap/HTTPSOAPTransport.h"
28 #include "soap/OpenSSLSOAPTransport.h"
29 #include "util/NDC.h"
30 #include "util/Threads.h"
31
32 #include <list>
33 #include <curl/curl.h>
34 #include <log4cpp/Category.hh>
35 #include <openssl/x509_vfy.h>
36
37 using namespace xmlsignature;
38 using namespace xmltooling;
39 using namespace log4cpp;
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(256), m_lock(Mutex::create()),
49             m_log(Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport.CURLPool")) {}
50         ~CURLPool();
51         
52         CURL* get(const string& to, const char* endpoint);
53         void put(const string& 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 = NULL;
65     
66     class XMLTOOL_DLLLOCAL CURLSOAPTransport : public HTTPSOAPTransport, public OpenSSLSOAPTransport
67     {
68     public:
69         CURLSOAPTransport(const KeyInfoSource& peer, const char* endpoint)
70                 : m_peer(peer), m_endpoint(endpoint), m_handle(NULL), m_headers(NULL),
71 #ifndef XMLTOOLING_NO_XMLSEC
72                     m_credResolver(NULL), m_trustEngine(NULL), m_mandatory(false), m_keyResolver(NULL),
73 #endif
74                     m_ssl_callback(NULL), m_ssl_userptr(NULL), m_secure(false) {
75             m_handle = g_CURLPool->get(peer.getName(), 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");
83             m_headers=curl_slist_append(m_headers,"Transport-Encoding: chunked");
84         }
85         
86         virtual ~CURLSOAPTransport() {
87             curl_slist_free_all(m_headers);
88             curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,NULL);
89             curl_easy_setopt(m_handle,CURLOPT_PRIVATE,m_secure ? "secure" : NULL); // Save off security "state".
90             g_CURLPool->put(m_peer.getName(), m_endpoint.c_str(), m_handle);
91         }
92
93         bool isConfidential() const {
94             return m_endpoint.find("https")==0;
95         }
96
97         bool setConnectTimeout(long timeout) const {
98             return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
99         }
100         
101         bool setTimeout(long timeout) const {
102             return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
103         }
104         
105         bool setAuth(transport_auth_t authType, const char* username=NULL, const char* password=NULL) const;
106         
107 #ifndef XMLTOOLING_NO_XMLSEC
108         bool setCredentialResolver(const CredentialResolver* credResolver) const {
109             const OpenSSLCredentialResolver* down = dynamic_cast<const OpenSSLCredentialResolver*>(credResolver);
110             if (!down) {
111                 m_credResolver = NULL;
112                 return (credResolver==NULL);
113             }
114             m_credResolver = down;
115             return true;
116         }
117         
118         bool setTrustEngine(const X509TrustEngine* trustEngine, bool mandatory=true, const KeyResolver* keyResolver=NULL) const {
119             const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
120             if (!down) {
121                 m_trustEngine = NULL;
122                 m_keyResolver = NULL;
123                 return (trustEngine==NULL);
124             }
125             m_trustEngine = down;
126             m_keyResolver = keyResolver;
127             m_mandatory = mandatory;
128             return true;
129         }
130         
131 #endif
132         
133         void send(istream& in);
134         
135         istream& receive() {
136             return m_stream;
137         }
138         
139         bool isSecure() const {
140             return m_secure;
141         }
142
143         void setSecure(bool secure) {
144             m_secure = secure;
145         }
146
147         string getContentType() const;
148         
149         bool setRequestHeader(const char* name, const char* val) const {
150             string temp(name);
151             temp=temp + ": " + val;
152             m_headers=curl_slist_append(m_headers,temp.c_str());
153             return true;
154         }
155         
156         const vector<string>& getResponseHeader(const char* val) const;
157         
158         bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=NULL) const {
159             m_ssl_callback=fn;
160             m_ssl_userptr=userptr;
161             return true;
162         }
163
164     private:        
165         // per-call state
166         const KeyInfoSource& m_peer;
167         string m_endpoint;
168         CURL* m_handle;
169         stringstream m_stream;
170         mutable struct curl_slist* m_headers;
171         map<string,vector<string> > m_response_headers;
172 #ifndef XMLTOOLING_NO_XMLSEC
173         mutable const OpenSSLCredentialResolver* m_credResolver;
174         mutable const OpenSSLTrustEngine* m_trustEngine;
175         mutable bool m_mandatory;
176         mutable const KeyResolver* m_keyResolver;
177 #endif
178         mutable ssl_ctx_callback_fn m_ssl_callback;
179         mutable void* m_ssl_userptr;
180         bool m_secure;
181         
182         friend size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
183         friend CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
184         friend int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
185     };
186
187     // libcurl callback functions
188     size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
189     size_t XMLTOOL_DLLLOCAL curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream);
190     size_t XMLTOOL_DLLLOCAL curl_read_hook( void *ptr, size_t size, size_t nmemb, void *stream);
191     int XMLTOOL_DLLLOCAL curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr);
192     CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
193 #ifndef XMLTOOLING_NO_XMLSEC
194     int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
195 #endif
196
197     SOAPTransport* CURLSOAPTransportFactory(const pair<const KeyInfoSource*,const char*>& dest)
198     {
199         return new CURLSOAPTransport(*dest.first, dest.second);
200     }
201 };
202
203 void xmltooling::registerSOAPTransports()
204 {
205     XMLToolingConfig& conf=XMLToolingConfig::getConfig();
206     conf.SOAPTransportManager.registerFactory("http", CURLSOAPTransportFactory);
207     conf.SOAPTransportManager.registerFactory("https", CURLSOAPTransportFactory);
208 }
209
210 void xmltooling::initSOAPTransports()
211 {
212     g_CURLPool=new CURLPool();
213 }
214
215 void xmltooling::termSOAPTransports()
216 {
217     delete g_CURLPool;
218     g_CURLPool = NULL;
219 }
220
221 CURLPool::~CURLPool()
222 {
223     for (poolmap_t::iterator i=m_bindingMap.begin(); i!=m_bindingMap.end(); i++) {
224         for (vector<CURL*>::iterator j=i->second.begin(); j!=i->second.end(); j++)
225             curl_easy_cleanup(*j);
226     }
227     delete m_lock;
228 }
229
230 CURL* CURLPool::get(const string& to, const char* endpoint)
231 {
232 #ifdef _DEBUG
233     xmltooling::NDC("get");
234 #endif
235     m_log.debug("getting connection handle to %s", endpoint);
236     m_lock->lock();
237     poolmap_t::iterator i=m_bindingMap.find(to + "|" + endpoint);
238     
239     if (i!=m_bindingMap.end()) {
240         // Move this pool to the front of the list.
241         m_pools.remove(&(i->second));
242         m_pools.push_front(&(i->second));
243         
244         // If a free connection exists, return it.
245         if (!(i->second.empty())) {
246             CURL* handle=i->second.back();
247             i->second.pop_back();
248             m_size--;
249             m_lock->unlock();
250             m_log.debug("returning existing connection handle from pool");
251             return handle;
252         }
253     }
254     
255     m_lock->unlock();
256     m_log.debug("nothing free in pool, returning new connection handle");
257     
258     // Create a new connection and set non-varying options.
259     CURL* handle=curl_easy_init();
260     if (!handle)
261         return NULL;
262     curl_easy_setopt(handle,CURLOPT_NOPROGRESS,1);
263     curl_easy_setopt(handle,CURLOPT_NOSIGNAL,1);
264     curl_easy_setopt(handle,CURLOPT_FAILONERROR,1);
265     curl_easy_setopt(handle,CURLOPT_SSLVERSION,3);
266     // Verification of the peer is via TrustEngine only.
267     curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
268     curl_easy_setopt(handle,CURLOPT_SSL_VERIFYHOST,2);
269     curl_easy_setopt(handle,CURLOPT_HEADERFUNCTION,&curl_header_hook);
270     curl_easy_setopt(handle,CURLOPT_READFUNCTION,&curl_read_hook);
271     curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION,&curl_write_hook);
272     curl_easy_setopt(handle,CURLOPT_DEBUGFUNCTION,&curl_debug_hook);
273
274     return handle;
275 }
276
277 void CURLPool::put(const string& to, const char* endpoint, CURL* handle)
278 {
279     string key = to + "|" + endpoint;
280     m_lock->lock();
281     poolmap_t::iterator i=m_bindingMap.find(key);
282     if (i==m_bindingMap.end())
283         m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
284     else
285         i->second.push_back(handle);
286     
287     CURL* killit=NULL;
288     if (++m_size > 256) {
289         // Kick a handle out from the back of the bus.
290         while (true) {
291             vector<CURL*>* corpse=m_pools.back();
292             if (!corpse->empty()) {
293                 killit=corpse->back();
294                 corpse->pop_back();
295                 m_size--;
296                 break;
297             }
298             
299             // Move an empty pool up to the front so we don't keep hitting it.
300             m_pools.pop_back();
301             m_pools.push_front(corpse);
302         }
303     }
304     m_lock->unlock();
305     if (killit) {
306         curl_easy_cleanup(killit);
307 #ifdef _DEBUG
308         xmltooling::NDC("put");
309 #endif
310         m_log.info("conn_pool_max limit reached, dropping an old connection");
311     }
312 }
313
314 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password) const
315 {
316     if (authType==transport_auth_none) {
317         if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
318             return false;
319         return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,NULL)==CURLE_OK);
320     }
321     long flag=0;
322     switch (authType) {
323         case transport_auth_basic:    flag = CURLAUTH_BASIC; break;
324         case transport_auth_digest:   flag = CURLAUTH_DIGEST; break;
325         case transport_auth_ntlm:     flag = CURLAUTH_NTLM; break;
326         case transport_auth_gss:      flag = CURLAUTH_GSSNEGOTIATE; break;
327         default:            return false;
328     }
329     if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
330         return false;
331     string creds = string(username ? username : "") + ':' + (password ? password : "");
332     return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,creds.c_str())==CURLE_OK);
333 }
334
335 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
336 {
337     static vector<string> emptyVector;
338
339     map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
340     if (i!=m_response_headers.end())
341         return i->second;
342     
343     for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
344 #ifdef HAVE_STRCASECMP
345         if (!strcasecmp(j->first.c_str(), name))
346 #else
347         if (!stricmp(j->first.c_str(), name))
348 #endif
349             return j->second;
350     }
351     
352     return emptyVector;
353 }
354
355 string CURLSOAPTransport::getContentType() const
356 {
357     char* content_type=NULL;
358     curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
359     return content_type ? content_type : "";
360 }
361
362 void CURLSOAPTransport::send(istream& in)
363 {
364 #ifdef _DEBUG
365     xmltooling::NDC ndc("send");
366 #endif
367     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".SOAPTransport");
368     Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT".libcurl");
369
370     // By this time, the handle has been prepared with the URL to use and the
371     // caller should have executed any set functions to manipulate it.
372
373     // Setup standard per-call curl properties.
374     curl_easy_setopt(m_handle,CURLOPT_POST,1);
375     curl_easy_setopt(m_handle,CURLOPT_READDATA,&in);
376     curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
377     curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
378
379     char curl_errorbuf[CURL_ERROR_SIZE];
380     curl_errorbuf[0]=0;
381     curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
382     if (log_curl.isDebugEnabled())
383         curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
384
385     // Set request headers (possibly appended by hooks).
386     curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
387
388     if (m_ssl_callback || m_credResolver || m_trustEngine) {
389         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
390         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
391
392         // Restore security "state". Necessary because the callback only runs
393         // when handshakes occur. Even new TCP connections won't execute it.
394         char* priv=NULL;
395         curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
396         if (priv)
397             m_secure=true;
398     }
399     else {
400         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,NULL);
401         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,NULL);
402     }
403     
404     // Make the call.
405     log.debug("sending SOAP message to %s", m_endpoint.c_str());
406     if (curl_easy_perform(m_handle) != CURLE_OK) {
407         throw IOException(
408             string("CURLSOAPTransport failed while contacting SOAP responder: ") +
409                 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
410     }
411 }
412
413 // callback to buffer headers from server
414 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
415 {
416     // only handle single-byte data
417     if (size!=1)
418         return 0;
419     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
420     char* buf = (char*)malloc(nmemb + 1);
421     if (buf) {
422         memset(buf,0,nmemb + 1);
423         memcpy(buf,ptr,nmemb);
424         char* sep=(char*)strchr(buf,':');
425         if (sep) {
426             *(sep++)=0;
427             while (*sep==' ')
428                 *(sep++)=0;
429             char* white=buf+nmemb-1;
430             while (isspace(*white))
431                 *(white--)=0;
432             ctx->m_response_headers[buf].push_back(sep);
433         }
434         free(buf);
435         return nmemb;
436     }
437     return 0;
438 }
439
440 // callback to send data to server
441 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
442 {
443     // *stream is actually an istream object
444     istream& buf=*(reinterpret_cast<istream*>(stream));
445     buf.read(reinterpret_cast<char*>(ptr),size*nmemb);
446     return buf.gcount();
447 }
448
449 // callback to buffer data from server
450 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
451 {
452     size_t len = size*nmemb;
453     reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
454     return len;
455 }
456
457 // callback for curl debug data
458 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
459 {
460     // *ptr is actually a logging object
461     if (!ptr) return 0;
462     CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
463     for (char* ch=data; len && (isprint(*ch) || isspace(*ch)); len--)
464         log << *ch++;
465     log << CategoryStream::ENDLINE;
466     return 0;
467 }
468
469 #ifndef XMLTOOLING_NO_XMLSEC
470 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
471 {
472     Category& log = Category::getInstance("OpenSSL");
473     log.debug("invoking X509 verify callback");
474 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
475     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
476 #else
477     // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
478     // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
479     // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
480     // negative in the SSL structure's int member.
481     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
482         SSL_get_verify_depth(
483             reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
484             )
485         );
486 #endif
487
488      // Bypass name check (handled for us by curl).
489     if (!ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,ctx->m_peer,false,ctx->m_keyResolver)) {
490         log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
491         x509_ctx->error=X509_V_ERR_APPLICATION_VERIFICATION;     // generic error, check log for plugin specifics
492         ctx->setSecure(false);
493         return ctx->m_mandatory ? 0 : 1;
494     }
495     
496     // Signal success. Hopefully it doesn't matter what's actually in the structure now.
497     ctx->setSecure(true);
498     return 1;
499 }
500 #endif
501
502 // callback to invoke a caller-defined SSL callback
503 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
504 {
505     CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
506
507 #ifndef XMLTOOLING_NO_XMLSEC
508     if (conf->m_credResolver)
509         conf->m_credResolver->attach(ssl_ctx);
510
511     if (conf->m_trustEngine) {
512         SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,NULL);
513 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
514         // With 0.9.7, we can pass a callback argument directly.
515         SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
516 #else
517         // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
518         // stuff the argument in the depth property where it will get copied to the context object
519         // that's handed to the callback.
520         SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),NULL);
521         SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
522 #endif
523     }
524 #endif
525         
526     if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
527         return CURLE_SSL_CERTPROBLEM;
528         
529     return CURLE_OK;
530 }