https://issues.shibboleth.net/jira/browse/CPPXT-37
[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 <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>
39
40 using namespace xmltooling;
41 using namespace xercesc;
42
43 namespace {
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);
51
52     // callback to invoke a caller-defined SSL callback
53     CURLcode ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
54     {
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);
60 #else
61         SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
62 #endif
63
64         return CURLE_OK;
65     }
66 }
67
68 CurlURLInputStream::CurlURLInputStream(const char* url)
69     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
70     , fURL(url)
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     init();
83 }
84
85 CurlURLInputStream::CurlURLInputStream(const XMLCh* url)
86     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
87     , fMulti(0)
88     , fEasy(0)
89     , fTotalBytesRead(0)
90     , fWritePtr(0)
91     , fBytesRead(0)
92     , fBytesToRead(0)
93     , fDataAvailable(false)
94     , fBufferHeadPtr(fBuffer)
95     , fBufferTailPtr(fBuffer)
96     , fContentType(0)
97 {
98     auto_ptr_char temp(url);
99     fURL = temp.get();
100     init();
101 }
102
103 CurlURLInputStream::CurlURLInputStream(const DOMElement* e)
104     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
105     , fMulti(0)
106     , fEasy(0)
107     , fTotalBytesRead(0)
108     , fWritePtr(0)
109     , fBytesRead(0)
110     , fBytesToRead(0)
111     , fDataAvailable(false)
112     , fBufferHeadPtr(fBuffer)
113     , fBufferTailPtr(fBuffer)
114     , fContentType(0)
115 {
116     const XMLCh* attr = e->getAttributeNS(NULL, url);
117     if (!attr || !*attr) {
118         attr = e->getAttributeNS(NULL, uri);
119         if (!attr || !*attr)
120             throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
121     }
122
123     auto_ptr_char temp(attr);
124     fURL = temp.get();
125     init(e);
126 }
127
128 CurlURLInputStream::~CurlURLInputStream()
129 {
130     if (fEasy) {
131         // Remove the easy handle from the multi stack
132         curl_multi_remove_handle(fMulti, fEasy);
133
134         // Cleanup the easy handle
135         curl_easy_cleanup(fEasy);
136     }
137
138     if (fMulti) {
139         // Cleanup the multi handle
140         curl_multi_cleanup(fMulti);
141     }
142
143     XMLString::release(&fContentType);
144 }
145
146 void CurlURLInputStream::init(const DOMElement* e)
147 {
148     // Allocate the curl multi handle
149     fMulti = curl_multi_init();
150
151     // Allocate the curl easy handle
152     fEasy = curl_easy_init();
153
154     if (!fMulti || !fEasy)
155         throw IOException("Failed to allocate libcurl handles.");
156
157     curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
158
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
162
163     // Do redirects
164     curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
165     curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
166
167     // Default settings.
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);
178
179     // Install SSL callback.
180     curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
181
182     fError[0] = 0;
183     curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
184
185     if (e) {
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);
189
190         // Process TransportOption elements.
191         bool success;
192         DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
193         while (child) {
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 # ifdef HAVE_CURL_OFF_T
206                     else if (sizeof(curl_off_t) == sizeof(long))
207                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
208 # else
209                     else if (sizeof(off_t) == sizeof(long))
210                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
211 # endif
212                     else
213                         success = false;
214 #else
215                     else
216                         success = (curl_easy_setopt(fEasy, opt, value.get()) == CURLE_OK);
217 #endif
218                     if (!success)
219                         fLog.error("failed to set transport option (%s)", option.get());
220                 }
221             }
222             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
223         }
224     }
225
226     // Add easy handle to the multi stack
227     curl_multi_add_handle(fMulti, fEasy);
228
229     fLog.debug("libcurl trying to fetch %s", fURL.c_str());
230
231     // Start reading, to get the content type
232     while(fBufferHeadPtr == fBuffer) {
233         int runningHandles = 0;
234         try {
235             readMore(&runningHandles);
236         }
237         catch (XMLException& ex) {
238             curl_multi_remove_handle(fMulti, fEasy);
239             curl_easy_cleanup(fEasy);
240             fEasy = NULL;
241             curl_multi_cleanup(fMulti);
242             fMulti = NULL;
243             auto_ptr_char msg(ex.getMessage());
244             throw IOException(msg.get());
245         }
246         if(runningHandles == 0) break;
247     }
248
249     // Find the content type
250     char* contentType8 = NULL;
251     curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8);
252     if(contentType8)
253         fContentType = XMLString::transcode(contentType8);
254 }
255
256
257 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
258 {
259     return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
260 }
261
262 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
263 {
264     size_t cnt = size * nitems;
265     size_t totalConsumed = 0;
266
267     // Consume as many bytes as possible immediately into the buffer
268     size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
269     memcpy(fWritePtr, buffer, consume);
270     fWritePtr       += consume;
271     fBytesRead      += consume;
272     fTotalBytesRead += consume;
273     fBytesToRead    -= consume;
274
275     //fLog.debug("write callback consuming %d bytes", consume);
276
277     // If bytes remain, rebuffer as many as possible into our holding buffer
278     buffer          += consume;
279     totalConsumed   += consume;
280     cnt             -= consume;
281     if (cnt > 0)
282     {
283         size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
284         consume = (cnt > bufAvail) ? bufAvail : cnt;
285         memcpy(fBufferHeadPtr, buffer, consume);
286         fBufferHeadPtr  += consume;
287         buffer          += consume;
288         totalConsumed   += consume;
289         //fLog.debug("write callback rebuffering %d bytes", consume);
290     }
291
292     // Return the total amount we've consumed. If we don't consume all the bytes
293     // then an error will be generated. Since our buffer size is equal to the
294     // maximum size that curl will write, this should never happen unless there
295     // is a logic error somewhere here.
296     return totalConsumed;
297 }
298
299 bool CurlURLInputStream::readMore(int* runningHandles)
300 {
301     // Ask the curl to do some work
302     CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
303
304     // Process messages from curl
305     int msgsInQueue = 0;
306     for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
307     {
308         //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
309
310         if (msg->msg != CURLMSG_DONE)
311             return true;
312
313         switch (msg->data.result)
314         {
315         case CURLE_OK:
316             // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
317             break;
318
319         case CURLE_UNSUPPORTED_PROTOCOL:
320             ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
321             break;
322
323         case CURLE_COULDNT_RESOLVE_HOST:
324         case CURLE_COULDNT_RESOLVE_PROXY:
325             ThrowXML1(NetAccessorException,  XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
326             break;
327
328         case CURLE_COULDNT_CONNECT:
329             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
330             break;
331
332         case CURLE_RECV_ERROR:
333             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
334             break;
335
336         default:
337             fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
338             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
339             break;
340         }
341     }
342
343     // If nothing is running any longer, bail out
344     if(*runningHandles == 0)
345         return false;
346
347     // If there is no further data to read, and we haven't
348     // read any yet on this invocation, call select to wait for data
349     if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
350     {
351         fd_set readSet;
352         fd_set writeSet;
353         fd_set exceptSet;
354         int fdcnt=0;
355
356         FD_ZERO(&readSet);
357         FD_ZERO(&writeSet);
358         FD_ZERO(&exceptSet);
359
360         // Ask curl for the file descriptors to wait on
361         curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
362
363         // Wait on the file descriptors
364         timeval tv;
365         tv.tv_sec  = 2;
366         tv.tv_usec = 0;
367         select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
368     }
369
370     return curlResult == CURLM_CALL_MULTI_PERFORM;
371 }
372
373 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
374 {
375     fBytesRead = 0;
376     fBytesToRead = maxToRead;
377     fWritePtr = toFill;
378
379     for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
380     {
381         // First, any buffered data we have available
382         size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
383         bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
384         if (bufCnt > 0)
385         {
386             memcpy(fWritePtr, fBufferTailPtr, bufCnt);
387             fWritePtr       += bufCnt;
388             fBytesRead      += bufCnt;
389             fTotalBytesRead += bufCnt;
390             fBytesToRead    -= bufCnt;
391
392             fBufferTailPtr  += bufCnt;
393             if (fBufferTailPtr == fBufferHeadPtr)
394                 fBufferHeadPtr = fBufferTailPtr = fBuffer;
395
396             //fLog.debug("consuming %d buffered bytes", bufCnt);
397
398             tryAgain = true;
399             continue;
400         }
401
402         // Ask the curl to do some work
403         int runningHandles = 0;
404         tryAgain = readMore(&runningHandles);
405
406         // If nothing is running any longer, bail out
407         if (runningHandles == 0)
408             break;
409     }
410
411     return fBytesRead;
412 }