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,15);
169 curl_easy_setopt(fEasy, CURLOPT_TIMEOUT,30);
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 success = (curl_easy_setopt(fEasy, opt, value.get()) == CURLE_OK);
205 else if (sizeof(curl_off_t) == sizeof(long))
206 success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
211 success = (curl_easy_setopt(fEasy, opt, value.get()) == CURLE_OK);
214 fLog.error("failed to set transport option (%s)", option.get());
217 child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
221 // Add easy handle to the multi stack
222 curl_multi_add_handle(fMulti, fEasy);
224 fLog.debug("libcurl trying to fetch %s", fURL.c_str());
226 // Start reading, to get the content type
227 while(fBufferHeadPtr == fBuffer) {
228 int runningHandles = 0;
230 readMore(&runningHandles);
232 catch (XMLException& ex) {
233 curl_multi_remove_handle(fMulti, fEasy);
234 curl_easy_cleanup(fEasy);
236 curl_multi_cleanup(fMulti);
238 auto_ptr_char msg(ex.getMessage());
239 throw IOException(msg.get());
241 if(runningHandles == 0) break;
244 // Find the content type
245 char* contentType8 = NULL;
246 curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8);
248 fContentType = XMLString::transcode(contentType8);
252 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
254 return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
257 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
259 size_t cnt = size * nitems;
260 size_t totalConsumed = 0;
262 // Consume as many bytes as possible immediately into the buffer
263 size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
264 memcpy(fWritePtr, buffer, consume);
265 fWritePtr += consume;
266 fBytesRead += consume;
267 fTotalBytesRead += consume;
268 fBytesToRead -= consume;
270 //fLog.debug("write callback consuming %d bytes", consume);
272 // If bytes remain, rebuffer as many as possible into our holding buffer
274 totalConsumed += consume;
278 size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
279 consume = (cnt > bufAvail) ? bufAvail : cnt;
280 memcpy(fBufferHeadPtr, buffer, consume);
281 fBufferHeadPtr += consume;
283 totalConsumed += consume;
284 //fLog.debug("write callback rebuffering %d bytes", consume);
287 // Return the total amount we've consumed. If we don't consume all the bytes
288 // then an error will be generated. Since our buffer size is equal to the
289 // maximum size that curl will write, this should never happen unless there
290 // is a logic error somewhere here.
291 return totalConsumed;
294 bool CurlURLInputStream::readMore(int* runningHandles)
296 // Ask the curl to do some work
297 CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
299 // Process messages from curl
301 for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
303 //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
305 if (msg->msg != CURLMSG_DONE)
308 switch (msg->data.result)
311 // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
314 case CURLE_UNSUPPORTED_PROTOCOL:
315 ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
318 case CURLE_COULDNT_RESOLVE_HOST:
319 case CURLE_COULDNT_RESOLVE_PROXY:
320 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
323 case CURLE_COULDNT_CONNECT:
324 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
327 case CURLE_RECV_ERROR:
328 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
332 fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
333 ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
338 // If nothing is running any longer, bail out
339 if(*runningHandles == 0)
342 // If there is no further data to read, and we haven't
343 // read any yet on this invocation, call select to wait for data
344 if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
355 // Ask curl for the file descriptors to wait on
356 curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
358 // Wait on the file descriptors
362 select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
365 return curlResult == CURLM_CALL_MULTI_PERFORM;
368 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
371 fBytesToRead = maxToRead;
374 for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
376 // First, any buffered data we have available
377 size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
378 bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
381 memcpy(fWritePtr, fBufferTailPtr, bufCnt);
383 fBytesRead += bufCnt;
384 fTotalBytesRead += bufCnt;
385 fBytesToRead -= bufCnt;
387 fBufferTailPtr += bufCnt;
388 if (fBufferTailPtr == fBufferHeadPtr)
389 fBufferHeadPtr = fBufferTailPtr = fBuffer;
391 //fLog.debug("consuming %d buffered bytes", bufCnt);
397 // Ask the curl to do some work
398 int runningHandles = 0;
399 tryAgain = readMore(&runningHandles);
401 // If nothing is running any longer, bail out
402 if (runningHandles == 0)