https://issues.shibboleth.net/jira/browse/CPPXT-44
[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                         fSavedOptions.push_back(value.get());
205                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
206                     }
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);
210 # else
211                     else if (sizeof(off_t) == sizeof(long))
212                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
213 # endif
214                     else
215                         success = false;
216 #else
217                     else {
218                         fSavedOptions.push_back(value.get());
219                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
220                     }
221 #endif
222                     if (!success)
223                         fLog.error("failed to set transport option (%s)", option.get());
224                 }
225             }
226             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
227         }
228     }
229
230     // Add easy handle to the multi stack
231     curl_multi_add_handle(fMulti, fEasy);
232
233     fLog.debug("libcurl trying to fetch %s", fURL.c_str());
234
235     // Start reading, to get the content type
236     while(fBufferHeadPtr == fBuffer) {
237         int runningHandles = 0;
238         try {
239             readMore(&runningHandles);
240         }
241         catch (XMLException& ex) {
242             curl_multi_remove_handle(fMulti, fEasy);
243             curl_easy_cleanup(fEasy);
244             fEasy = NULL;
245             curl_multi_cleanup(fMulti);
246             fMulti = NULL;
247             auto_ptr_char msg(ex.getMessage());
248             throw IOException(msg.get());
249         }
250         if(runningHandles == 0) break;
251     }
252
253     // Find the content type
254     char* contentType8 = NULL;
255     curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8);
256     if(contentType8)
257         fContentType = XMLString::transcode(contentType8);
258 }
259
260
261 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
262 {
263     return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
264 }
265
266 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
267 {
268     size_t cnt = size * nitems;
269     size_t totalConsumed = 0;
270
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;
278
279     //fLog.debug("write callback consuming %d bytes", consume);
280
281     // If bytes remain, rebuffer as many as possible into our holding buffer
282     buffer          += consume;
283     totalConsumed   += consume;
284     cnt             -= consume;
285     if (cnt > 0)
286     {
287         size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
288         consume = (cnt > bufAvail) ? bufAvail : cnt;
289         memcpy(fBufferHeadPtr, buffer, consume);
290         fBufferHeadPtr  += consume;
291         buffer          += consume;
292         totalConsumed   += consume;
293         //fLog.debug("write callback rebuffering %d bytes", consume);
294     }
295
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;
301 }
302
303 bool CurlURLInputStream::readMore(int* runningHandles)
304 {
305     // Ask the curl to do some work
306     CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
307
308     // Process messages from curl
309     int msgsInQueue = 0;
310     for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
311     {
312         //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
313
314         if (msg->msg != CURLMSG_DONE)
315             return true;
316
317         switch (msg->data.result)
318         {
319         case CURLE_OK:
320             // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
321             break;
322
323         case CURLE_UNSUPPORTED_PROTOCOL:
324             ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
325             break;
326
327         case CURLE_COULDNT_RESOLVE_HOST:
328         case CURLE_COULDNT_RESOLVE_PROXY:
329             ThrowXML1(NetAccessorException,  XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
330             break;
331
332         case CURLE_COULDNT_CONNECT:
333             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
334             break;
335
336         case CURLE_RECV_ERROR:
337             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
338             break;
339
340         default:
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());
343             break;
344         }
345     }
346
347     // If nothing is running any longer, bail out
348     if(*runningHandles == 0)
349         return false;
350
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)
354     {
355         fd_set readSet;
356         fd_set writeSet;
357         fd_set exceptSet;
358         int fdcnt=0;
359
360         FD_ZERO(&readSet);
361         FD_ZERO(&writeSet);
362         FD_ZERO(&exceptSet);
363
364         // Ask curl for the file descriptors to wait on
365         curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
366
367         // Wait on the file descriptors
368         timeval tv;
369         tv.tv_sec  = 2;
370         tv.tv_usec = 0;
371         select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
372     }
373
374     return curlResult == CURLM_CALL_MULTI_PERFORM;
375 }
376
377 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
378 {
379     fBytesRead = 0;
380     fBytesToRead = maxToRead;
381     fWritePtr = toFill;
382
383     for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
384     {
385         // First, any buffered data we have available
386         size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
387         bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
388         if (bufCnt > 0)
389         {
390             memcpy(fWritePtr, fBufferTailPtr, bufCnt);
391             fWritePtr       += bufCnt;
392             fBytesRead      += bufCnt;
393             fTotalBytesRead += bufCnt;
394             fBytesToRead    -= bufCnt;
395
396             fBufferTailPtr  += bufCnt;
397             if (fBufferTailPtr == fBufferHeadPtr)
398                 fBufferHeadPtr = fBufferTailPtr = fBuffer;
399
400             //fLog.debug("consuming %d buffered bytes", bufCnt);
401
402             tryAgain = true;
403             continue;
404         }
405
406         // Ask the curl to do some work
407         int runningHandles = 0;
408         tryAgain = readMore(&runningHandles);
409
410         // If nothing is running any longer, bail out
411         if (runningHandles == 0)
412             break;
413     }
414
415     return fBytesRead;
416 }