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 _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);
54 // callback to invoke a caller-defined SSL callback
55 CURLcode ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
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);
63 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
69 size_t curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
71 // only handle single-byte data
72 if (size!=1 || nmemb<5 || !stream)
74 string* cacheTag = reinterpret_cast<string*>(stream);
75 const char* hdr = reinterpret_cast<char*>(ptr);
76 if (strncmp(hdr, "ETag:", 5) == 0) {
78 size_t remaining = nmemb - 5;
79 // skip leading spaces
80 while (remaining > 0) {
88 // append until whitespace
89 while (remaining > 0) {
91 (*cacheTag) += *hdr++;
103 CurlURLInputStream::CurlURLInputStream(const char* url, string* cacheTag)
104 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
105 , fCacheTag(cacheTag)
106 , fURL(url ? url : "")
114 , fDataAvailable(false)
115 , fBufferHeadPtr(fBuffer)
116 , fBufferTailPtr(fBuffer)
121 throw IOException("No URL supplied to CurlURLInputStream constructor.");
125 CurlURLInputStream::CurlURLInputStream(const XMLCh* url, string* cacheTag)
126 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
127 , fCacheTag(cacheTag)
135 , fDataAvailable(false)
136 , fBufferHeadPtr(fBuffer)
137 , fBufferTailPtr(fBuffer)
142 auto_ptr_char temp(url);
146 throw IOException("No URL supplied to CurlURLInputStream constructor.");
150 CurlURLInputStream::CurlURLInputStream(const DOMElement* e, string* cacheTag)
151 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
152 , fCacheTag(cacheTag)
160 , fDataAvailable(false)
161 , fBufferHeadPtr(fBuffer)
162 , fBufferTailPtr(fBuffer)
166 const XMLCh* attr = e->getAttributeNS(NULL, url);
167 if (!attr || !*attr) {
168 attr = e->getAttributeNS(NULL, uri);
170 throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
173 auto_ptr_char temp(attr);
178 CurlURLInputStream::~CurlURLInputStream()
181 // Remove the easy handle from the multi stack
182 curl_multi_remove_handle(fMulti, fEasy);
184 // Cleanup the easy handle
185 curl_easy_cleanup(fEasy);
189 // Cleanup the multi handle
190 curl_multi_cleanup(fMulti);
194 curl_slist_free_all(fHeaders);
197 XMLString::release(&fContentType);
200 void CurlURLInputStream::init(const DOMElement* e)
202 // Allocate the curl multi handle
203 fMulti = curl_multi_init();
205 // Allocate the curl easy handle
206 fEasy = curl_easy_init();
208 if (!fMulti || !fEasy)
209 throw IOException("Failed to allocate libcurl handles.");
211 curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
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
218 curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
219 curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
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);
234 // Install SSL callback.
235 curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
238 curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
240 // Check for cache tag.
243 if (!fCacheTag->empty()) {
244 string hdr("If-None-Match: ");
246 fHeaders = curl_slist_append(fHeaders, hdr.c_str());
247 curl_easy_setopt(fEasy, CURLOPT_HTTPHEADER, fHeaders);
250 curl_easy_setopt(fEasy, CURLOPT_HEADERFUNCTION, curl_header_hook);
251 curl_easy_setopt(fEasy, CURLOPT_HEADERDATA, fCacheTag);
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);
259 // Process TransportOption elements.
261 DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
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);
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);
280 else if (sizeof(off_t) == sizeof(long))
281 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
287 fSavedOptions.push_back(value.get());
288 success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
292 fLog.error("failed to set transport option (%s)", option.get());
295 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
299 // Add easy handle to the multi stack
300 curl_multi_add_handle(fMulti, fEasy);
302 fLog.debug("libcurl trying to fetch %s", fURL.c_str());
304 // Start reading, to get the content type
305 while(fBufferHeadPtr == fBuffer) {
306 int runningHandles = 0;
308 readMore(&runningHandles);
310 catch (XMLException&) {
311 curl_multi_remove_handle(fMulti, fEasy);
312 curl_easy_cleanup(fEasy);
314 curl_multi_cleanup(fMulti);
318 if(runningHandles == 0) break;
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\">"
328 << "</" << URLInputSource::asciiStatusCodeElementName << '>';
329 string specialxml = specialdoc.str();
330 memcpy(fBuffer, specialxml.c_str(), specialxml.length());
331 fBufferHeadPtr += specialxml.length();
335 fStatusCode = 200; // reset to 200 to ensure no special processing occurs
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);
345 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
347 return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
350 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
352 size_t cnt = size * nitems;
353 size_t totalConsumed = 0;
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;
363 //fLog.debug("write callback consuming %d bytes", consume);
365 // If bytes remain, rebuffer as many as possible into our holding buffer
367 totalConsumed += consume;
371 size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
372 consume = (cnt > bufAvail) ? bufAvail : cnt;
373 memcpy(fBufferHeadPtr, buffer, consume);
374 fBufferHeadPtr += consume;
376 totalConsumed += consume;
377 //fLog.debug("write callback rebuffering %d bytes", consume);
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;
387 bool CurlURLInputStream::readMore(int* runningHandles)
389 // Ask the curl to do some work
390 CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
392 // Process messages from curl
394 for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
396 //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
398 if (msg->msg != CURLMSG_DONE)
401 switch (msg->data.result)
404 // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
407 case CURLE_UNSUPPORTED_PROTOCOL:
408 ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
411 case CURLE_COULDNT_RESOLVE_HOST:
412 case CURLE_COULDNT_RESOLVE_PROXY:
413 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
416 case CURLE_COULDNT_CONNECT:
417 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
420 case CURLE_OPERATION_TIMEDOUT:
421 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
424 case CURLE_RECV_ERROR:
425 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
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());
435 // If nothing is running any longer, bail out
436 if(*runningHandles == 0)
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)
452 // Ask curl for the file descriptors to wait on
453 curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
455 // Wait on the file descriptors
459 select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
462 return curlResult == CURLM_CALL_MULTI_PERFORM;
465 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
468 fBytesToRead = maxToRead;
471 for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
473 // First, any buffered data we have available
474 size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
475 bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
478 memcpy(fWritePtr, fBufferTailPtr, bufCnt);
480 fBytesRead += bufCnt;
481 fTotalBytesRead += bufCnt;
482 fBytesToRead -= bufCnt;
484 fBufferTailPtr += bufCnt;
485 if (fBufferTailPtr == fBufferHeadPtr)
486 fBufferHeadPtr = fBufferTailPtr = fBuffer;
488 //fLog.debug("consuming %d buffered bytes", bufCnt);
494 // Check for a non-2xx status that means to ignore the curl response.
495 if (fStatusCode >= 300)
498 // Ask the curl to do some work
499 int runningHandles = 0;
500 tryAgain = readMore(&runningHandles);
502 // If nothing is running any longer, bail out
503 if (runningHandles == 0)