Rework support for libcurl-based input to parser.
[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/XMLHelper.h>
28
29 #include <xercesc/util/XercesDefs.hpp>
30 #include <xercesc/util/XMLNetAccessor.hpp>
31 #include <xercesc/util/XMLString.hpp>
32 #include <xercesc/util/XMLExceptMsgs.hpp>
33 #include <xercesc/util/Janitor.hpp>
34 #include <xercesc/util/XMLUniDefs.hpp>
35 #include <xercesc/util/TransService.hpp>
36 #include <xercesc/util/TranscodingException.hpp>
37 #include <xercesc/util/PlatformUtils.hpp>
38
39 using namespace xmltooling;
40 using namespace xercesc;
41
42 namespace {
43     static const XMLCh  _CURL[] =           UNICODE_LITERAL_4(C,U,R,L);
44     static const XMLCh _option[] =          UNICODE_LITERAL_6(o,p,t,i,o,n);
45     static const XMLCh _provider[] =        UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
46     static const XMLCh TransportOption[] =  UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
47     static const XMLCh uri[] =              UNICODE_LITERAL_3(u,r,i);
48     static const XMLCh url[] =              UNICODE_LITERAL_3(u,r,l);
49     static const XMLCh verifyHost[] =       UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
50 }
51
52 CurlURLInputStream::CurlURLInputStream(const char* url)
53     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
54     , fURL(url)
55     , fMulti(0)
56     , fEasy(0)
57     , fTotalBytesRead(0)
58     , fWritePtr(0)
59     , fBytesRead(0)
60     , fBytesToRead(0)
61     , fDataAvailable(false)
62     , fBufferHeadPtr(fBuffer)
63     , fBufferTailPtr(fBuffer)
64     , fContentType(0)
65 {
66     init();
67 }
68
69 CurlURLInputStream::CurlURLInputStream(const XMLCh* url)
70     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
71     , fMulti(0)
72     , fEasy(0)
73     , fTotalBytesRead(0)
74     , fWritePtr(0)
75     , fBytesRead(0)
76     , fBytesToRead(0)
77     , fDataAvailable(false)
78     , fBufferHeadPtr(fBuffer)
79     , fBufferTailPtr(fBuffer)
80     , fContentType(0)
81 {
82     auto_ptr_char temp(url);
83     fURL = temp.get();
84     init();
85 }
86
87 CurlURLInputStream::CurlURLInputStream(const DOMElement* e)
88     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
89     , fMulti(0)
90     , fEasy(0)
91     , fTotalBytesRead(0)
92     , fWritePtr(0)
93     , fBytesRead(0)
94     , fBytesToRead(0)
95     , fDataAvailable(false)
96     , fBufferHeadPtr(fBuffer)
97     , fBufferTailPtr(fBuffer)
98     , fContentType(0)
99 {
100     const XMLCh* attr = e->getAttributeNS(NULL, url);
101     if (!attr || !*attr) {
102         attr = e->getAttributeNS(NULL, uri);
103         if (!attr || !*attr)
104             throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
105     }
106
107     auto_ptr_char temp(attr);
108     fURL = temp.get();
109     init(e);
110 }
111
112 CurlURLInputStream::~CurlURLInputStream()
113 {
114     if (fEasy) {
115         // Remove the easy handle from the multi stack
116         curl_multi_remove_handle(fMulti, fEasy);
117
118         // Cleanup the easy handle
119         curl_easy_cleanup(fEasy);
120     }
121
122     if (fMulti) {
123         // Cleanup the multi handle
124         curl_multi_cleanup(fMulti);
125     }
126
127     XMLString::release(&fContentType);
128 }
129
130 void CurlURLInputStream::init(const DOMElement* e)
131 {
132     // Allocate the curl multi handle
133     fMulti = curl_multi_init();
134
135     // Allocate the curl easy handle
136     fEasy = curl_easy_init();
137
138     if (!fMulti || !fEasy)
139         throw IOException("Failed to allocate libcurl handles.");
140
141     curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
142
143     // Set up a way to recieve the data
144     curl_easy_setopt(fEasy, CURLOPT_WRITEDATA, this);                       // Pass this pointer to write function
145     curl_easy_setopt(fEasy, CURLOPT_WRITEFUNCTION, staticWriteCallback);    // Our static write function
146
147     // Do redirects
148     curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
149     curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
150
151     // Default settings.
152     curl_easy_setopt(fEasy, CURLOPT_CONNECTTIMEOUT,15);
153     curl_easy_setopt(fEasy, CURLOPT_TIMEOUT,30);
154     curl_easy_setopt(fEasy, CURLOPT_HTTPAUTH,0);
155     curl_easy_setopt(fEasy, CURLOPT_USERPWD,NULL);
156     curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 2);
157     curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYPEER, 0);
158     curl_easy_setopt(fEasy, CURLOPT_SSL_CIPHER_LIST, "ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
159     curl_easy_setopt(fEasy, CURLOPT_NOPROGRESS, 1);
160     curl_easy_setopt(fEasy, CURLOPT_NOSIGNAL, 1);
161     curl_easy_setopt(fEasy, CURLOPT_FAILONERROR, 1);
162
163     fError[0] = 0;
164     curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
165
166     if (e) {
167         const XMLCh* flag = e->getAttributeNS(NULL, verifyHost);
168         if (flag && (*flag == chLatin_f || *flag == chDigit_0))
169             curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 2);
170
171         // Process TransportOption elements.
172         bool success;
173         DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
174         while (child) {
175             if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(NULL,_provider), _CURL)) {
176                 auto_ptr_char option(child->getAttributeNS(NULL,_option));
177                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
178                 if (option.get() && *option.get() && value.get() && *value.get()) {
179                     // For libcurl, the option is an enum and the value type depends on the option.
180                     CURLoption opt = static_cast<CURLoption>(strtol(option.get(), NULL, 10));
181                     if (opt < CURLOPTTYPE_OBJECTPOINT)
182                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
183 #ifdef CURLOPTTYPE_OFF_T
184                     else if (opt < CURLOPTTYPE_OFF_T)
185                         success = (curl_easy_setopt(fEasy, opt, value.get()) == CURLE_OK);
186                     else if (sizeof(curl_off_t) == sizeof(long))
187                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
188                     else
189                         success = false;
190 #else
191                     else
192                         success = (curl_easy_setopt(fEasy, opt, value.get()) == CURLE_OK);
193 #endif
194                     if (!success)
195                         fLog.error("failed to set transport option (%s)", option.get());
196                 }
197             }
198             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
199         }
200     }
201
202     // Add easy handle to the multi stack
203     curl_multi_add_handle(fMulti, fEasy);
204
205     fLog.debug("libcurl trying to fetch %s", fURL.c_str());
206
207     // Start reading, to get the content type
208     while(fBufferHeadPtr == fBuffer) {
209         int runningHandles = 0;
210         try {
211             readMore(&runningHandles);
212         }
213         catch (XMLException& ex) {
214             curl_multi_remove_handle(fMulti, fEasy);
215             curl_easy_cleanup(fEasy);
216             fEasy = NULL;
217             curl_multi_cleanup(fMulti);
218             fMulti = NULL;
219             auto_ptr_char msg(ex.getMessage());
220             throw IOException(msg.get());
221         }
222         if(runningHandles == 0) break;
223     }
224
225     // Find the content type
226     char* contentType8 = NULL;
227     curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8);
228     if(contentType8)
229         fContentType = XMLString::transcode(contentType8);
230 }
231
232
233 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
234 {
235     return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
236 }
237
238 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
239 {
240     size_t cnt = size * nitems;
241     size_t totalConsumed = 0;
242
243     // Consume as many bytes as possible immediately into the buffer
244     size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
245     memcpy(fWritePtr, buffer, consume);
246     fWritePtr       += consume;
247     fBytesRead      += consume;
248     fTotalBytesRead += consume;
249     fBytesToRead    -= consume;
250
251     //fLog.debug("write callback consuming %d bytes", consume);
252
253     // If bytes remain, rebuffer as many as possible into our holding buffer
254     buffer          += consume;
255     totalConsumed   += consume;
256     cnt             -= consume;
257     if (cnt > 0)
258     {
259         size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
260         consume = (cnt > bufAvail) ? bufAvail : cnt;
261         memcpy(fBufferHeadPtr, buffer, consume);
262         fBufferHeadPtr  += consume;
263         buffer          += consume;
264         totalConsumed   += consume;
265         //fLog.debug("write callback rebuffering %d bytes", consume);
266     }
267
268     // Return the total amount we've consumed. If we don't consume all the bytes
269     // then an error will be generated. Since our buffer size is equal to the
270     // maximum size that curl will write, this should never happen unless there
271     // is a logic error somewhere here.
272     return totalConsumed;
273 }
274
275 bool CurlURLInputStream::readMore(int* runningHandles)
276 {
277     // Ask the curl to do some work
278     CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
279
280     // Process messages from curl
281     int msgsInQueue = 0;
282     for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
283     {
284         //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
285
286         if (msg->msg != CURLMSG_DONE)
287             return true;
288
289         switch (msg->data.result)
290         {
291         case CURLE_OK:
292             // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
293             break;
294
295         case CURLE_UNSUPPORTED_PROTOCOL:
296             ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
297             break;
298
299         case CURLE_COULDNT_RESOLVE_HOST:
300         case CURLE_COULDNT_RESOLVE_PROXY:
301             ThrowXML1(NetAccessorException,  XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
302             break;
303
304         case CURLE_COULDNT_CONNECT:
305             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
306             break;
307
308         case CURLE_RECV_ERROR:
309             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
310             break;
311
312         default:
313             fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
314             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
315             break;
316         }
317     }
318
319     // If nothing is running any longer, bail out
320     if(*runningHandles == 0)
321         return false;
322
323     // If there is no further data to read, and we haven't
324     // read any yet on this invocation, call select to wait for data
325     if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
326     {
327         fd_set readSet;
328         fd_set writeSet;
329         fd_set exceptSet;
330         int fdcnt=0;
331
332         FD_ZERO(&readSet);
333         FD_ZERO(&writeSet);
334         FD_ZERO(&exceptSet);
335
336         // Ask curl for the file descriptors to wait on
337         curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
338
339         // Wait on the file descriptors
340         timeval tv;
341         tv.tv_sec  = 2;
342         tv.tv_usec = 0;
343         select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
344     }
345
346     return curlResult == CURLM_CALL_MULTI_PERFORM;
347 }
348
349 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
350 {
351     fBytesRead = 0;
352     fBytesToRead = maxToRead;
353     fWritePtr = toFill;
354
355     for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
356     {
357         // First, any buffered data we have available
358         size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
359         bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
360         if (bufCnt > 0)
361         {
362             memcpy(fWritePtr, fBufferTailPtr, bufCnt);
363             fWritePtr       += bufCnt;
364             fBytesRead      += bufCnt;
365             fTotalBytesRead += bufCnt;
366             fBytesToRead    -= bufCnt;
367
368             fBufferTailPtr  += bufCnt;
369             if (fBufferTailPtr == fBufferHeadPtr)
370                 fBufferHeadPtr = fBufferTailPtr = fBuffer;
371
372             //fLog.debug("consuming %d buffered bytes", bufCnt);
373
374             tryAgain = true;
375             continue;
376         }
377
378         // Ask the curl to do some work
379         int runningHandles = 0;
380         tryAgain = readMore(&runningHandles);
381
382         // If nothing is running any longer, bail out
383         if (runningHandles == 0)
384             break;
385     }
386
387     return fBytesRead;
388 }