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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * xmltooling/util/CurlURLInputStream.cpp
21 * Asynchronous use of curl to fetch data from a URL.
26 #include <xmltooling/util/CurlURLInputStream.h>
27 #include <xmltooling/util/ParserPool.h>
28 #include <xmltooling/util/XMLHelper.h>
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>
41 using namespace xmltooling;
42 using namespace xercesc;
46 static const XMLCh _CURL[] = UNICODE_LITERAL_4(C,U,R,L);
47 static const XMLCh _OpenSSL[] = UNICODE_LITERAL_7(O,p,e,n,S,S,L);
48 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
49 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
50 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
51 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
52 static const XMLCh url[] = UNICODE_LITERAL_3(u,r,l);
53 static const XMLCh verifyHost[] = UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
55 // callback to invoke a caller-defined SSL callback
56 CURLcode ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
58 CurlURLInputStream* str = reinterpret_cast<CurlURLInputStream*>(userptr);
60 // Default flags manually disable SSLv2 so we're not dependent on libcurl to do it.
61 // Also disable the ticket option where implemented, since this breaks a variety
62 // of servers. Newer libcurl also does this for us.
63 #ifdef SSL_OP_NO_TICKET
64 SSL_CTX_set_options(ssl_ctx, str->getOpenSSLOps()|SSL_OP_NO_TICKET);
66 SSL_CTX_set_options(ssl_ctx, str->getOpenSSLOps());
72 size_t curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
74 // only handle single-byte data
75 if (size!=1 || nmemb<5 || !stream)
77 string* cacheTag = reinterpret_cast<string*>(stream);
78 const char* hdr = reinterpret_cast<char*>(ptr);
79 if (strncmp(hdr, "ETag:", 5) == 0) {
81 size_t remaining = nmemb - 5;
82 // skip leading spaces
83 while (remaining > 0) {
91 // append until whitespace
93 while (remaining > 0) {
95 (*cacheTag) += *hdr++;
102 if (!cacheTag->empty())
103 *cacheTag = "If-None-Match: " + *cacheTag;
105 else if (cacheTag->empty() && strncmp(hdr, "Last-Modified:", 14) == 0) {
107 size_t remaining = nmemb - 14;
108 // skip leading spaces
109 while (remaining > 0) {
117 // append until whitespace
118 while (remaining > 0) {
119 if (!isspace(*hdr)) {
120 (*cacheTag) += *hdr++;
127 if (!cacheTag->empty())
128 *cacheTag = "If-Modified-Since: " + *cacheTag;
135 CurlURLInputStream::CurlURLInputStream(const char* url, string* cacheTag)
136 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
137 , fCacheTag(cacheTag)
138 , fOpenSSLOps(SSL_OP_ALL|SSL_OP_NO_SSLv2)
139 , fURL(url ? url : "")
147 , fDataAvailable(false)
156 throw IOException("No URL supplied to CurlURLInputStream constructor.");
160 CurlURLInputStream::CurlURLInputStream(const XMLCh* url, string* cacheTag)
161 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
162 , fCacheTag(cacheTag)
163 , fOpenSSLOps(SSL_OP_ALL|SSL_OP_NO_SSLv2)
171 , fDataAvailable(false)
180 auto_ptr_char temp(url);
184 throw IOException("No URL supplied to CurlURLInputStream constructor.");
188 CurlURLInputStream::CurlURLInputStream(const DOMElement* e, string* cacheTag)
189 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
190 , fCacheTag(cacheTag)
191 , fOpenSSLOps(SSL_OP_ALL|SSL_OP_NO_SSLv2)
199 , fDataAvailable(false)
207 const XMLCh* attr = e->getAttributeNS(nullptr, url);
208 if (!attr || !*attr) {
209 attr = e->getAttributeNS(nullptr, uri);
211 throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
214 auto_ptr_char temp(attr);
219 CurlURLInputStream::~CurlURLInputStream()
222 // Remove the easy handle from the multi stack
223 curl_multi_remove_handle(fMulti, fEasy);
225 // Cleanup the easy handle
226 curl_easy_cleanup(fEasy);
230 // Cleanup the multi handle
231 curl_multi_cleanup(fMulti);
235 curl_slist_free_all(fHeaders);
238 XMLString::release(&fContentType);
242 void CurlURLInputStream::init(const DOMElement* e)
244 // Allocate the curl multi handle
245 fMulti = curl_multi_init();
247 // Allocate the curl easy handle
248 fEasy = curl_easy_init();
250 if (!fMulti || !fEasy)
251 throw IOException("Failed to allocate libcurl handles.");
253 curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
255 // Set up a way to recieve the data
256 curl_easy_setopt(fEasy, CURLOPT_WRITEDATA, this); // Pass this pointer to write function
257 curl_easy_setopt(fEasy, CURLOPT_WRITEFUNCTION, staticWriteCallback); // Our static write function
260 curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
261 curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
264 curl_easy_setopt(fEasy, CURLOPT_CONNECTTIMEOUT, 10);
265 curl_easy_setopt(fEasy, CURLOPT_TIMEOUT, 60);
266 curl_easy_setopt(fEasy, CURLOPT_HTTPAUTH, 0);
267 curl_easy_setopt(fEasy, CURLOPT_USERPWD, nullptr);
268 curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 2);
269 curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYPEER, 0);
270 curl_easy_setopt(fEasy, CURLOPT_CAINFO, nullptr);
271 curl_easy_setopt(fEasy, CURLOPT_SSL_CIPHER_LIST, "ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
272 curl_easy_setopt(fEasy, CURLOPT_NOPROGRESS, 1);
273 curl_easy_setopt(fEasy, CURLOPT_NOSIGNAL, 1);
274 curl_easy_setopt(fEasy, CURLOPT_FAILONERROR, 1);
275 curl_easy_setopt(fEasy, CURLOPT_ENCODING, "");
277 // Install SSL callback.
278 curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
279 curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_DATA, this);
282 curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
284 // Check for cache tag.
287 if (!fCacheTag->empty()) {
288 fHeaders = curl_slist_append(fHeaders, fCacheTag->c_str());
289 curl_easy_setopt(fEasy, CURLOPT_HTTPHEADER, fHeaders);
292 curl_easy_setopt(fEasy, CURLOPT_HEADERFUNCTION, curl_header_hook);
293 curl_easy_setopt(fEasy, CURLOPT_HEADERDATA, fCacheTag);
297 const XMLCh* flag = e->getAttributeNS(nullptr, verifyHost);
298 if (flag && (*flag == chLatin_f || *flag == chDigit_0))
299 curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 0);
301 // Process TransportOption elements.
303 DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
305 if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(nullptr,_provider), _OpenSSL)) {
306 auto_ptr_char option(child->getAttributeNS(nullptr,_option));
307 auto_ptr_char value(child->getFirstChild()->getNodeValue());
308 if (option.get() && value.get() && !strcmp(option.get(), "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION") &&
309 (*value.get()=='1' || *value.get()=='t')) {
310 // If the new option to enable buggy rengotiation is available, set it.
311 // Otherwise, signal false if this is newer than 0.9.8k, because that
312 // means it's 0.9.8l, which blocks renegotiation, and therefore will
313 // not honor this request. Older versions are buggy, so behave as though
314 // the flag was set anyway, so we signal true.
315 #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
316 fOpenSSLOps |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
318 #elif (OPENSSL_VERSION_NUMBER > 0x009080bfL)
328 fLog.error("failed to set OpenSSL transport option (%s)", option.get());
330 else if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(nullptr,_provider), _CURL)) {
331 auto_ptr_char option(child->getAttributeNS(nullptr,_option));
332 auto_ptr_char value(child->getFirstChild()->getNodeValue());
333 if (option.get() && *option.get() && value.get() && *value.get()) {
334 // For libcurl, the option is an enum and the value type depends on the option.
335 CURLoption opt = static_cast<CURLoption>(strtol(option.get(), nullptr, 10));
336 if (opt < CURLOPTTYPE_OBJECTPOINT)
337 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), nullptr, 10)) == CURLE_OK);
338 #ifdef CURLOPTTYPE_OFF_T
339 else if (opt < CURLOPTTYPE_OFF_T) {
340 fSavedOptions.push_back(value.get());
341 success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
343 # ifdef HAVE_CURL_OFF_T
344 else if (sizeof(curl_off_t) == sizeof(long))
345 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), nullptr, 10)) == CURLE_OK);
347 else if (sizeof(off_t) == sizeof(long))
348 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), nullptr, 10)) == CURLE_OK);
354 fSavedOptions.push_back(value.get());
355 success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
359 fLog.error("failed to set CURL transport option (%s)", option.get());
362 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
366 // Add easy handle to the multi stack
367 curl_multi_add_handle(fMulti, fEasy);
369 fLog.debug("libcurl trying to fetch %s", fURL.c_str());
371 // Start reading, to get the content type
372 while(fBufferHeadPtr == fBuffer) {
373 int runningHandles = 0;
375 readMore(&runningHandles);
377 catch (XMLException&) {
378 curl_multi_remove_handle(fMulti, fEasy);
379 curl_easy_cleanup(fEasy);
381 curl_multi_cleanup(fMulti);
385 if(runningHandles == 0) break;
388 // Check for a response code.
389 if (curl_easy_getinfo(fEasy, CURLINFO_RESPONSE_CODE, &fStatusCode) == CURLE_OK) {
390 if (fStatusCode >= 300 ) {
391 // Short-circuit usual processing by storing a special XML document in the buffer.
392 ostringstream specialdoc;
393 specialdoc << '<' << URLInputSource::asciiStatusCodeElementName << " xmlns=\"http://www.opensaml.org/xmltooling\">"
395 << "</" << URLInputSource::asciiStatusCodeElementName << '>';
396 string specialxml = specialdoc.str();
397 fBufferTailPtr = fBuffer = reinterpret_cast<XMLByte*>(malloc(specialxml.length()));
399 curl_multi_remove_handle(fMulti, fEasy);
400 curl_easy_cleanup(fEasy);
402 curl_multi_cleanup(fMulti);
406 memcpy(fBuffer, specialxml.c_str(), specialxml.length());
407 fBufferHeadPtr = fBuffer + specialxml.length();
411 fStatusCode = 200; // reset to 200 to ensure no special processing occurs
414 // Find the content type
415 char* contentType8 = nullptr;
416 if(curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8) == CURLE_OK && contentType8)
417 fContentType = XMLString::transcode(contentType8);
421 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
423 return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
426 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
428 size_t cnt = size * nitems;
429 size_t totalConsumed = 0;
431 // Consume as many bytes as possible immediately into the buffer
432 size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
433 memcpy(fWritePtr, buffer, consume);
434 fWritePtr += consume;
435 fBytesRead += consume;
436 fTotalBytesRead += consume;
437 fBytesToRead -= consume;
439 fLog.debug("write callback consuming %u bytes", consume);
441 // If bytes remain, rebuffer as many as possible into our holding buffer
443 totalConsumed += consume;
447 size_t bufAvail = fBufferSize - (fBufferHeadPtr - fBuffer);
448 if (bufAvail < cnt) {
449 // Enlarge the buffer. TODO: limit max size
450 XMLByte* newbuf = reinterpret_cast<XMLByte*>(realloc(fBuffer, fBufferSize + (cnt - bufAvail)));
452 fBufferSize = fBufferSize + (cnt - bufAvail);
453 fLog.debug("enlarged buffer to %u bytes", fBufferSize);
454 fBufferHeadPtr = newbuf + (fBufferHeadPtr - fBuffer);
455 fBuffer = fBufferTailPtr = newbuf;
458 memcpy(fBufferHeadPtr, buffer, cnt);
459 fBufferHeadPtr += cnt;
461 totalConsumed += cnt;
462 fLog.debug("write callback rebuffering %u bytes", cnt);
465 // Return the total amount we've consumed. If we don't consume all the bytes
466 // then an error will be generated. Since our buffer size is equal to the
467 // maximum size that curl will write, this should never happen unless there
468 // is a logic error somewhere here.
469 return totalConsumed;
472 bool CurlURLInputStream::readMore(int* runningHandles)
474 // Ask the curl to do some work
475 CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
477 // Process messages from curl
479 for (CURLMsg* msg = nullptr; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != nullptr; )
481 fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
483 if (msg->msg != CURLMSG_DONE)
486 switch (msg->data.result)
489 // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
492 case CURLE_UNSUPPORTED_PROTOCOL:
493 ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
496 case CURLE_COULDNT_RESOLVE_HOST:
497 case CURLE_COULDNT_RESOLVE_PROXY:
498 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
501 case CURLE_COULDNT_CONNECT:
502 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
505 case CURLE_OPERATION_TIMEDOUT:
506 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
509 case CURLE_RECV_ERROR:
510 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
514 fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
515 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
520 // If nothing is running any longer, bail out
521 if(*runningHandles == 0)
524 // If there is no further data to read, and we haven't
525 // read any yet on this invocation, call select to wait for data
526 if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
537 // Ask curl for the file descriptors to wait on
538 curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
540 // Wait on the file descriptors
544 select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
547 return curlResult == CURLM_CALL_MULTI_PERFORM;
550 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
553 fBytesToRead = maxToRead;
556 for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
558 // First, any buffered data we have available
559 size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
560 bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
563 memcpy(fWritePtr, fBufferTailPtr, bufCnt);
565 fBytesRead += bufCnt;
566 fTotalBytesRead += bufCnt;
567 fBytesToRead -= bufCnt;
569 fBufferTailPtr += bufCnt;
570 if (fBufferTailPtr == fBufferHeadPtr)
571 fBufferHeadPtr = fBufferTailPtr = fBuffer;
573 fLog.debug("consuming %d buffered bytes", bufCnt);
579 // Check for a non-2xx status that means to ignore the curl response.
580 if (fStatusCode >= 300)
583 // Ask the curl to do some work
584 int runningHandles = 0;
585 tryAgain = readMore(&runningHandles);
587 // If nothing is running any longer, bail out
588 if (runningHandles == 0)