https://issues.shibboleth.net/jira/browse/CPPXT-52
[shibboleth/cpp-xmltooling.git] / xmltooling / util / CurlURLInputStream.cpp
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 /**
19  * xmltooling/util/CurlURLInputStream.cpp
20  *
21  * Asynchronous use of curl to fetch data from a URL.
22  */
23
24 #include "internal.h"
25
26 #include <xmltooling/util/CurlURLInputStream.h>
27 #include <xmltooling/util/ParserPool.h>
28 #include <xmltooling/util/XMLHelper.h>
29
30 #include <openssl/ssl.h>
31 #include <xercesc/util/XercesDefs.hpp>
32 #include <xercesc/util/XMLNetAccessor.hpp>
33 #include <xercesc/util/XMLString.hpp>
34 #include <xercesc/util/XMLExceptMsgs.hpp>
35 #include <xercesc/util/Janitor.hpp>
36 #include <xercesc/util/XMLUniDefs.hpp>
37 #include <xercesc/util/TransService.hpp>
38 #include <xercesc/util/TranscodingException.hpp>
39 #include <xercesc/util/PlatformUtils.hpp>
40
41 using namespace xmltooling;
42 using namespace xercesc;
43 using namespace std;
44
45 namespace {
46     static const XMLCh  _CURL[] =           UNICODE_LITERAL_4(C,U,R,L);
47     static const XMLCh _option[] =          UNICODE_LITERAL_6(o,p,t,i,o,n);
48     static const XMLCh _provider[] =        UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
49     static const XMLCh TransportOption[] =  UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
50     static const XMLCh uri[] =              UNICODE_LITERAL_3(u,r,i);
51     static const XMLCh url[] =              UNICODE_LITERAL_3(u,r,l);
52     static const XMLCh verifyHost[] =       UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
53
54     // callback to invoke a caller-defined SSL callback
55     CURLcode ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
56     {
57         // Manually disable SSLv2 so we're not dependent on libcurl to do it.
58         // Also disable the ticket option where implemented, since this breaks a variety
59         // of servers. Newer libcurl also does this for us.
60 #ifdef SSL_OP_NO_TICKET
61         SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_TICKET);
62 #else
63         SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
64 #endif
65
66         return CURLE_OK;
67     }
68
69     size_t curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
70     {
71         // only handle single-byte data
72         if (size!=1 || nmemb<5 || !stream)
73             return nmemb;
74         string* cacheTag = reinterpret_cast<string*>(stream);
75         const char* hdr = reinterpret_cast<char*>(ptr);
76         if (strncmp(hdr, "ETag:", 5) == 0) {
77             hdr += 5;
78             size_t remaining = nmemb - 5;
79             // skip leading spaces
80             while (remaining > 0) {
81                 if (*hdr == ' ') {
82                     ++hdr;
83                     --remaining;
84                     continue;
85                 }
86                 break;
87             }
88             // append until whitespace
89             while (remaining > 0) {
90                 if (!isspace(*hdr)) {
91                     (*cacheTag) += *hdr++;
92                     --remaining;
93                     continue;
94                 }
95                 break;
96             }
97         }
98
99         return nmemb;
100     }
101 }
102
103 CurlURLInputStream::CurlURLInputStream(const char* url, string* cacheTag)
104     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
105     , fCacheTag(cacheTag)
106     , fURL(url ? url : "")
107     , fMulti(0)
108     , fEasy(0)
109     , fHeaders(0)
110     , fTotalBytesRead(0)
111     , fWritePtr(0)
112     , fBytesRead(0)
113     , fBytesToRead(0)
114     , fDataAvailable(false)
115     , fBufferHeadPtr(fBuffer)
116     , fBufferTailPtr(fBuffer)
117     , fContentType(0)
118     , fStatusCode(200)
119 {
120     if (fURL.empty())
121         throw IOException("No URL supplied to CurlURLInputStream constructor.");
122     init();
123 }
124
125 CurlURLInputStream::CurlURLInputStream(const XMLCh* url, string* cacheTag)
126     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
127     , fCacheTag(cacheTag)
128     , fMulti(0)
129     , fEasy(0)
130     , fHeaders(0)
131     , fTotalBytesRead(0)
132     , fWritePtr(0)
133     , fBytesRead(0)
134     , fBytesToRead(0)
135     , fDataAvailable(false)
136     , fBufferHeadPtr(fBuffer)
137     , fBufferTailPtr(fBuffer)
138     , fContentType(0)
139     , fStatusCode(200)
140 {
141     if (url) {
142         auto_ptr_char temp(url);
143         fURL = temp.get();
144     }
145     if (fURL.empty())
146         throw IOException("No URL supplied to CurlURLInputStream constructor.");
147     init();
148 }
149
150 CurlURLInputStream::CurlURLInputStream(const DOMElement* e, string* cacheTag)
151     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
152     , fCacheTag(cacheTag)
153     , fMulti(0)
154     , fEasy(0)
155     , fHeaders(0)
156     , fTotalBytesRead(0)
157     , fWritePtr(0)
158     , fBytesRead(0)
159     , fBytesToRead(0)
160     , fDataAvailable(false)
161     , fBufferHeadPtr(fBuffer)
162     , fBufferTailPtr(fBuffer)
163     , fContentType(0)
164     , fStatusCode(200)
165 {
166     const XMLCh* attr = e->getAttributeNS(NULL, url);
167     if (!attr || !*attr) {
168         attr = e->getAttributeNS(NULL, uri);
169         if (!attr || !*attr)
170             throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
171     }
172
173     auto_ptr_char temp(attr);
174     fURL = temp.get();
175     init(e);
176 }
177
178 CurlURLInputStream::~CurlURLInputStream()
179 {
180     if (fEasy) {
181         // Remove the easy handle from the multi stack
182         curl_multi_remove_handle(fMulti, fEasy);
183
184         // Cleanup the easy handle
185         curl_easy_cleanup(fEasy);
186     }
187
188     if (fMulti) {
189         // Cleanup the multi handle
190         curl_multi_cleanup(fMulti);
191     }
192
193     if (fHeaders) {
194         curl_slist_free_all(fHeaders);
195     }
196
197     XMLString::release(&fContentType);
198 }
199
200 void CurlURLInputStream::init(const DOMElement* e)
201 {
202     // Allocate the curl multi handle
203     fMulti = curl_multi_init();
204
205     // Allocate the curl easy handle
206     fEasy = curl_easy_init();
207
208     if (!fMulti || !fEasy)
209         throw IOException("Failed to allocate libcurl handles.");
210
211     curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
212
213     // Set up a way to recieve the data
214     curl_easy_setopt(fEasy, CURLOPT_WRITEDATA, this);                       // Pass this pointer to write function
215     curl_easy_setopt(fEasy, CURLOPT_WRITEFUNCTION, staticWriteCallback);    // Our static write function
216
217     // Do redirects
218     curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
219     curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
220
221     // Default settings.
222     curl_easy_setopt(fEasy, CURLOPT_CONNECTTIMEOUT,30);
223     curl_easy_setopt(fEasy, CURLOPT_TIMEOUT,60);
224     curl_easy_setopt(fEasy, CURLOPT_HTTPAUTH,0);
225     curl_easy_setopt(fEasy, CURLOPT_USERPWD,NULL);
226     curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 2);
227     curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYPEER, 0);
228     curl_easy_setopt(fEasy, CURLOPT_CAINFO, NULL);
229     curl_easy_setopt(fEasy, CURLOPT_SSL_CIPHER_LIST, "ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
230     curl_easy_setopt(fEasy, CURLOPT_NOPROGRESS, 1);
231     curl_easy_setopt(fEasy, CURLOPT_NOSIGNAL, 1);
232     curl_easy_setopt(fEasy, CURLOPT_FAILONERROR, 1);
233
234     // Install SSL callback.
235     curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
236
237     fError[0] = 0;
238     curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
239
240     // Check for cache tag.
241     if (fCacheTag) {
242         // Outgoing tag.
243         if (!fCacheTag->empty()) {
244             string hdr("If-None-Match: ");
245             hdr += *fCacheTag;
246             fHeaders = curl_slist_append(fHeaders, hdr.c_str());
247             curl_easy_setopt(fEasy, CURLOPT_HTTPHEADER, fHeaders);
248         }
249         // Incoming tag.
250         curl_easy_setopt(fEasy, CURLOPT_HEADERFUNCTION, curl_header_hook);
251         curl_easy_setopt(fEasy, CURLOPT_HEADERDATA, fCacheTag);
252     }
253
254     if (e) {
255         const XMLCh* flag = e->getAttributeNS(NULL, verifyHost);
256         if (flag && (*flag == chLatin_f || *flag == chDigit_0))
257             curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 0);
258
259         // Process TransportOption elements.
260         bool success;
261         DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
262         while (child) {
263             if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(NULL,_provider), _CURL)) {
264                 auto_ptr_char option(child->getAttributeNS(NULL,_option));
265                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
266                 if (option.get() && *option.get() && value.get() && *value.get()) {
267                     // For libcurl, the option is an enum and the value type depends on the option.
268                     CURLoption opt = static_cast<CURLoption>(strtol(option.get(), NULL, 10));
269                     if (opt < CURLOPTTYPE_OBJECTPOINT)
270                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
271 #ifdef CURLOPTTYPE_OFF_T
272                     else if (opt < CURLOPTTYPE_OFF_T) {
273                         fSavedOptions.push_back(value.get());
274                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
275                     }
276 # ifdef HAVE_CURL_OFF_T
277                     else if (sizeof(curl_off_t) == sizeof(long))
278                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
279 # else
280                     else if (sizeof(off_t) == sizeof(long))
281                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
282 # endif
283                     else
284                         success = false;
285 #else
286                     else {
287                         fSavedOptions.push_back(value.get());
288                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
289                     }
290 #endif
291                     if (!success)
292                         fLog.error("failed to set transport option (%s)", option.get());
293                 }
294             }
295             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
296         }
297     }
298
299     // Add easy handle to the multi stack
300     curl_multi_add_handle(fMulti, fEasy);
301
302     fLog.debug("libcurl trying to fetch %s", fURL.c_str());
303
304     // Start reading, to get the content type
305     while(fBufferHeadPtr == fBuffer) {
306         int runningHandles = 0;
307         try {
308             readMore(&runningHandles);
309         }
310         catch (XMLException&) {
311             curl_multi_remove_handle(fMulti, fEasy);
312             curl_easy_cleanup(fEasy);
313             fEasy = NULL;
314             curl_multi_cleanup(fMulti);
315             fMulti = NULL;
316             throw;
317         }
318         if(runningHandles == 0) break;
319     }
320
321     // Check for a response code.
322     if (curl_easy_getinfo(fEasy, CURLINFO_RESPONSE_CODE, &fStatusCode) == CURLE_OK) {
323         if (fStatusCode >= 300 ) {
324             // Short-circuit usual processing by storing a special XML document in the buffer.
325             ostringstream specialdoc;
326             specialdoc << '<' << URLInputSource::asciiStatusCodeElementName << " xmlns=\"http://www.opensaml.org/xmltooling\">"
327                 << fStatusCode
328                 << "</" << URLInputSource::asciiStatusCodeElementName << '>';
329             string specialxml = specialdoc.str();
330             memcpy(fBuffer, specialxml.c_str(), specialxml.length());
331             fBufferHeadPtr += specialxml.length();
332         }
333     }
334     else {
335         fStatusCode = 200;  // reset to 200 to ensure no special processing occurs
336     }
337
338     // Find the content type
339     char* contentType8 = NULL;
340     if(curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8) == CURLE_OK && contentType8)
341         fContentType = XMLString::transcode(contentType8);
342 }
343
344
345 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
346 {
347     return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
348 }
349
350 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
351 {
352     size_t cnt = size * nitems;
353     size_t totalConsumed = 0;
354
355     // Consume as many bytes as possible immediately into the buffer
356     size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
357     memcpy(fWritePtr, buffer, consume);
358     fWritePtr       += consume;
359     fBytesRead      += consume;
360     fTotalBytesRead += consume;
361     fBytesToRead    -= consume;
362
363     //fLog.debug("write callback consuming %d bytes", consume);
364
365     // If bytes remain, rebuffer as many as possible into our holding buffer
366     buffer          += consume;
367     totalConsumed   += consume;
368     cnt             -= consume;
369     if (cnt > 0)
370     {
371         size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
372         consume = (cnt > bufAvail) ? bufAvail : cnt;
373         memcpy(fBufferHeadPtr, buffer, consume);
374         fBufferHeadPtr  += consume;
375         buffer          += consume;
376         totalConsumed   += consume;
377         //fLog.debug("write callback rebuffering %d bytes", consume);
378     }
379
380     // Return the total amount we've consumed. If we don't consume all the bytes
381     // then an error will be generated. Since our buffer size is equal to the
382     // maximum size that curl will write, this should never happen unless there
383     // is a logic error somewhere here.
384     return totalConsumed;
385 }
386
387 bool CurlURLInputStream::readMore(int* runningHandles)
388 {
389     // Ask the curl to do some work
390     CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
391
392     // Process messages from curl
393     int msgsInQueue = 0;
394     for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
395     {
396         //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
397
398         if (msg->msg != CURLMSG_DONE)
399             return true;
400
401         switch (msg->data.result)
402         {
403         case CURLE_OK:
404             // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
405             break;
406
407         case CURLE_UNSUPPORTED_PROTOCOL:
408             ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
409             break;
410
411         case CURLE_COULDNT_RESOLVE_HOST:
412         case CURLE_COULDNT_RESOLVE_PROXY:
413             ThrowXML1(NetAccessorException,  XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
414             break;
415
416         case CURLE_COULDNT_CONNECT:
417             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
418             break;
419
420         case CURLE_OPERATION_TIMEDOUT:
421             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
422             break;
423
424         case CURLE_RECV_ERROR:
425             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
426             break;
427
428         default:
429             fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
430             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
431             break;
432         }
433     }
434
435     // If nothing is running any longer, bail out
436     if(*runningHandles == 0)
437         return false;
438
439     // If there is no further data to read, and we haven't
440     // read any yet on this invocation, call select to wait for data
441     if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
442     {
443         fd_set readSet;
444         fd_set writeSet;
445         fd_set exceptSet;
446         int fdcnt=0;
447
448         FD_ZERO(&readSet);
449         FD_ZERO(&writeSet);
450         FD_ZERO(&exceptSet);
451
452         // Ask curl for the file descriptors to wait on
453         curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
454
455         // Wait on the file descriptors
456         timeval tv;
457         tv.tv_sec  = 2;
458         tv.tv_usec = 0;
459         select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
460     }
461
462     return curlResult == CURLM_CALL_MULTI_PERFORM;
463 }
464
465 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
466 {
467     fBytesRead = 0;
468     fBytesToRead = maxToRead;
469     fWritePtr = toFill;
470
471     for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
472     {
473         // First, any buffered data we have available
474         size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
475         bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
476         if (bufCnt > 0)
477         {
478             memcpy(fWritePtr, fBufferTailPtr, bufCnt);
479             fWritePtr       += bufCnt;
480             fBytesRead      += bufCnt;
481             fTotalBytesRead += bufCnt;
482             fBytesToRead    -= bufCnt;
483
484             fBufferTailPtr  += bufCnt;
485             if (fBufferTailPtr == fBufferHeadPtr)
486                 fBufferHeadPtr = fBufferTailPtr = fBuffer;
487
488             //fLog.debug("consuming %d buffered bytes", bufCnt);
489
490             tryAgain = true;
491             continue;
492         }
493
494         // Check for a non-2xx status that means to ignore the curl response.
495         if (fStatusCode >= 300)
496             break;
497
498         // Ask the curl to do some work
499         int runningHandles = 0;
500         tryAgain = readMore(&runningHandles);
501
502         // If nothing is running any longer, bail out
503         if (runningHandles == 0)
504             break;
505     }
506
507     return fBytesRead;
508 }