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/XMLHelper.h>
29 #include <openssl/ssl.h>
30 #include <xercesc/util/XercesDefs.hpp>
31 #include <xercesc/util/XMLNetAccessor.hpp>
32 #include <xercesc/util/XMLString.hpp>
33 #include <xercesc/util/XMLExceptMsgs.hpp>
34 #include <xercesc/util/Janitor.hpp>
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xercesc/util/TransService.hpp>
37 #include <xercesc/util/TranscodingException.hpp>
38 #include <xercesc/util/PlatformUtils.hpp>
40 using namespace xmltooling;
41 using namespace xercesc;
44 static const XMLCh _CURL[] = UNICODE_LITERAL_4(C,U,R,L);
45 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
46 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
47 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
48 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
49 static const XMLCh url[] = UNICODE_LITERAL_3(u,r,l);
50 static const XMLCh verifyHost[] = UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
52 // callback to invoke a caller-defined SSL callback
53 CURLcode ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
55 // Manually disable SSLv2 so we're not dependent on libcurl to do it.
56 // Also disable the ticket option where implemented, since this breaks a variety
57 // of servers. Newer libcurl also does this for us.
58 #ifdef SSL_OP_NO_TICKET
59 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_TICKET);
61 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
68 CurlURLInputStream::CurlURLInputStream(const char* url)
69 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
77 , fDataAvailable(false)
78 , fBufferHeadPtr(fBuffer)
79 , fBufferTailPtr(fBuffer)
85 CurlURLInputStream::CurlURLInputStream(const XMLCh* url)
86 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
93 , fDataAvailable(false)
94 , fBufferHeadPtr(fBuffer)
95 , fBufferTailPtr(fBuffer)
98 auto_ptr_char temp(url);
103 CurlURLInputStream::CurlURLInputStream(const DOMElement* e)
104 : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
111 , fDataAvailable(false)
112 , fBufferHeadPtr(fBuffer)
113 , fBufferTailPtr(fBuffer)
116 const XMLCh* attr = e->getAttributeNS(NULL, url);
117 if (!attr || !*attr) {
118 attr = e->getAttributeNS(NULL, uri);
120 throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
123 auto_ptr_char temp(attr);
128 CurlURLInputStream::~CurlURLInputStream()
131 // Remove the easy handle from the multi stack
132 curl_multi_remove_handle(fMulti, fEasy);
134 // Cleanup the easy handle
135 curl_easy_cleanup(fEasy);
139 // Cleanup the multi handle
140 curl_multi_cleanup(fMulti);
143 XMLString::release(&fContentType);
146 void CurlURLInputStream::init(const DOMElement* e)
148 // Allocate the curl multi handle
149 fMulti = curl_multi_init();
151 // Allocate the curl easy handle
152 fEasy = curl_easy_init();
154 if (!fMulti || !fEasy)
155 throw IOException("Failed to allocate libcurl handles.");
157 curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
159 // Set up a way to recieve the data
160 curl_easy_setopt(fEasy, CURLOPT_WRITEDATA, this); // Pass this pointer to write function
161 curl_easy_setopt(fEasy, CURLOPT_WRITEFUNCTION, staticWriteCallback); // Our static write function
164 curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
165 curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
168 curl_easy_setopt(fEasy, CURLOPT_CONNECTTIMEOUT,30);
169 curl_easy_setopt(fEasy, CURLOPT_TIMEOUT,60);
170 curl_easy_setopt(fEasy, CURLOPT_HTTPAUTH,0);
171 curl_easy_setopt(fEasy, CURLOPT_USERPWD,NULL);
172 curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 2);
173 curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYPEER, 0);
174 curl_easy_setopt(fEasy, CURLOPT_SSL_CIPHER_LIST, "ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
175 curl_easy_setopt(fEasy, CURLOPT_NOPROGRESS, 1);
176 curl_easy_setopt(fEasy, CURLOPT_NOSIGNAL, 1);
177 curl_easy_setopt(fEasy, CURLOPT_FAILONERROR, 1);
179 // Install SSL callback.
180 curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
183 curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
186 const XMLCh* flag = e->getAttributeNS(NULL, verifyHost);
187 if (flag && (*flag == chLatin_f || *flag == chDigit_0))
188 curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 0);
190 // Process TransportOption elements.
192 DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
194 if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(NULL,_provider), _CURL)) {
195 auto_ptr_char option(child->getAttributeNS(NULL,_option));
196 auto_ptr_char value(child->getFirstChild()->getNodeValue());
197 if (option.get() && *option.get() && value.get() && *value.get()) {
198 // For libcurl, the option is an enum and the value type depends on the option.
199 CURLoption opt = static_cast<CURLoption>(strtol(option.get(), NULL, 10));
200 if (opt < CURLOPTTYPE_OBJECTPOINT)
201 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
202 #ifdef CURLOPTTYPE_OFF_T
203 else if (opt < CURLOPTTYPE_OFF_T) {
204 fSavedOptions.push_back(value.get());
205 success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
207 # ifdef HAVE_CURL_OFF_T
208 else if (sizeof(curl_off_t) == sizeof(long))
209 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
211 else if (sizeof(off_t) == sizeof(long))
212 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
218 fSavedOptions.push_back(value.get());
219 success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
223 fLog.error("failed to set transport option (%s)", option.get());
226 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
230 // Add easy handle to the multi stack
231 curl_multi_add_handle(fMulti, fEasy);
233 fLog.debug("libcurl trying to fetch %s", fURL.c_str());
235 // Start reading, to get the content type
236 while(fBufferHeadPtr == fBuffer) {
237 int runningHandles = 0;
239 readMore(&runningHandles);
241 catch (XMLException& ex) {
242 curl_multi_remove_handle(fMulti, fEasy);
243 curl_easy_cleanup(fEasy);
245 curl_multi_cleanup(fMulti);
247 auto_ptr_char msg(ex.getMessage());
248 throw IOException(msg.get());
250 if(runningHandles == 0) break;
253 // Find the content type
254 char* contentType8 = NULL;
255 curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8);
257 fContentType = XMLString::transcode(contentType8);
261 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
263 return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
266 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
268 size_t cnt = size * nitems;
269 size_t totalConsumed = 0;
271 // Consume as many bytes as possible immediately into the buffer
272 size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
273 memcpy(fWritePtr, buffer, consume);
274 fWritePtr += consume;
275 fBytesRead += consume;
276 fTotalBytesRead += consume;
277 fBytesToRead -= consume;
279 //fLog.debug("write callback consuming %d bytes", consume);
281 // If bytes remain, rebuffer as many as possible into our holding buffer
283 totalConsumed += consume;
287 size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
288 consume = (cnt > bufAvail) ? bufAvail : cnt;
289 memcpy(fBufferHeadPtr, buffer, consume);
290 fBufferHeadPtr += consume;
292 totalConsumed += consume;
293 //fLog.debug("write callback rebuffering %d bytes", consume);
296 // Return the total amount we've consumed. If we don't consume all the bytes
297 // then an error will be generated. Since our buffer size is equal to the
298 // maximum size that curl will write, this should never happen unless there
299 // is a logic error somewhere here.
300 return totalConsumed;
303 bool CurlURLInputStream::readMore(int* runningHandles)
305 // Ask the curl to do some work
306 CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
308 // Process messages from curl
310 for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
312 //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
314 if (msg->msg != CURLMSG_DONE)
317 switch (msg->data.result)
320 // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
323 case CURLE_UNSUPPORTED_PROTOCOL:
324 ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
327 case CURLE_COULDNT_RESOLVE_HOST:
328 case CURLE_COULDNT_RESOLVE_PROXY:
329 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
332 case CURLE_COULDNT_CONNECT:
333 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
336 case CURLE_RECV_ERROR:
337 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
341 fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
342 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
347 // If nothing is running any longer, bail out
348 if(*runningHandles == 0)
351 // If there is no further data to read, and we haven't
352 // read any yet on this invocation, call select to wait for data
353 if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
364 // Ask curl for the file descriptors to wait on
365 curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
367 // Wait on the file descriptors
371 select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
374 return curlResult == CURLM_CALL_MULTI_PERFORM;
377 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
380 fBytesToRead = maxToRead;
383 for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
385 // First, any buffered data we have available
386 size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
387 bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
390 memcpy(fWritePtr, fBufferTailPtr, bufCnt);
392 fBytesRead += bufCnt;
393 fTotalBytesRead += bufCnt;
394 fBytesToRead -= bufCnt;
396 fBufferTailPtr += bufCnt;
397 if (fBufferTailPtr == fBufferHeadPtr)
398 fBufferHeadPtr = fBufferTailPtr = fBuffer;
400 //fLog.debug("consuming %d buffered bytes", bufCnt);
406 // Ask the curl to do some work
407 int runningHandles = 0;
408 tryAgain = readMore(&runningHandles);
410 // If nothing is running any longer, bail out
411 if (runningHandles == 0)