Null out curl CA list to prevent misleading access to it.
[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_CAINFO, NULL);
175     curl_easy_setopt(fEasy, CURLOPT_SSL_CIPHER_LIST, "ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
176     curl_easy_setopt(fEasy, CURLOPT_NOPROGRESS, 1);
177     curl_easy_setopt(fEasy, CURLOPT_NOSIGNAL, 1);
178     curl_easy_setopt(fEasy, CURLOPT_FAILONERROR, 1);
179
180     // Install SSL callback.
181     curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
182
183     fError[0] = 0;
184     curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
185
186     if (e) {
187         const XMLCh* flag = e->getAttributeNS(NULL, verifyHost);
188         if (flag && (*flag == chLatin_f || *flag == chDigit_0))
189             curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 0);
190
191         // Process TransportOption elements.
192         bool success;
193         DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
194         while (child) {
195             if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(NULL,_provider), _CURL)) {
196                 auto_ptr_char option(child->getAttributeNS(NULL,_option));
197                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
198                 if (option.get() && *option.get() && value.get() && *value.get()) {
199                     // For libcurl, the option is an enum and the value type depends on the option.
200                     CURLoption opt = static_cast<CURLoption>(strtol(option.get(), NULL, 10));
201                     if (opt < CURLOPTTYPE_OBJECTPOINT)
202                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
203 #ifdef CURLOPTTYPE_OFF_T
204                     else if (opt < CURLOPTTYPE_OFF_T) {
205                         fSavedOptions.push_back(value.get());
206                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
207                     }
208 # ifdef HAVE_CURL_OFF_T
209                     else if (sizeof(curl_off_t) == sizeof(long))
210                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
211 # else
212                     else if (sizeof(off_t) == sizeof(long))
213                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), NULL, 10)) == CURLE_OK);
214 # endif
215                     else
216                         success = false;
217 #else
218                     else {
219                         fSavedOptions.push_back(value.get());
220                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
221                     }
222 #endif
223                     if (!success)
224                         fLog.error("failed to set transport option (%s)", option.get());
225                 }
226             }
227             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
228         }
229     }
230
231     // Add easy handle to the multi stack
232     curl_multi_add_handle(fMulti, fEasy);
233
234     fLog.debug("libcurl trying to fetch %s", fURL.c_str());
235
236     // Start reading, to get the content type
237     while(fBufferHeadPtr == fBuffer) {
238         int runningHandles = 0;
239         try {
240             readMore(&runningHandles);
241         }
242         catch (XMLException& ex) {
243             curl_multi_remove_handle(fMulti, fEasy);
244             curl_easy_cleanup(fEasy);
245             fEasy = NULL;
246             curl_multi_cleanup(fMulti);
247             fMulti = NULL;
248             auto_ptr_char msg(ex.getMessage());
249             throw IOException(msg.get());
250         }
251         if(runningHandles == 0) break;
252     }
253
254     // Find the content type
255     char* contentType8 = NULL;
256     curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8);
257     if(contentType8)
258         fContentType = XMLString::transcode(contentType8);
259 }
260
261
262 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
263 {
264     return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
265 }
266
267 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
268 {
269     size_t cnt = size * nitems;
270     size_t totalConsumed = 0;
271
272     // Consume as many bytes as possible immediately into the buffer
273     size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
274     memcpy(fWritePtr, buffer, consume);
275     fWritePtr       += consume;
276     fBytesRead      += consume;
277     fTotalBytesRead += consume;
278     fBytesToRead    -= consume;
279
280     //fLog.debug("write callback consuming %d bytes", consume);
281
282     // If bytes remain, rebuffer as many as possible into our holding buffer
283     buffer          += consume;
284     totalConsumed   += consume;
285     cnt             -= consume;
286     if (cnt > 0)
287     {
288         size_t bufAvail = sizeof(fBuffer) - (fBufferHeadPtr - fBuffer);
289         consume = (cnt > bufAvail) ? bufAvail : cnt;
290         memcpy(fBufferHeadPtr, buffer, consume);
291         fBufferHeadPtr  += consume;
292         buffer          += consume;
293         totalConsumed   += consume;
294         //fLog.debug("write callback rebuffering %d bytes", consume);
295     }
296
297     // Return the total amount we've consumed. If we don't consume all the bytes
298     // then an error will be generated. Since our buffer size is equal to the
299     // maximum size that curl will write, this should never happen unless there
300     // is a logic error somewhere here.
301     return totalConsumed;
302 }
303
304 bool CurlURLInputStream::readMore(int* runningHandles)
305 {
306     // Ask the curl to do some work
307     CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
308
309     // Process messages from curl
310     int msgsInQueue = 0;
311     for (CURLMsg* msg = NULL; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != NULL; )
312     {
313         //fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
314
315         if (msg->msg != CURLMSG_DONE)
316             return true;
317
318         switch (msg->data.result)
319         {
320         case CURLE_OK:
321             // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
322             break;
323
324         case CURLE_UNSUPPORTED_PROTOCOL:
325             ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
326             break;
327
328         case CURLE_COULDNT_RESOLVE_HOST:
329         case CURLE_COULDNT_RESOLVE_PROXY:
330             ThrowXML1(NetAccessorException,  XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
331             break;
332
333         case CURLE_COULDNT_CONNECT:
334             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
335             break;
336
337         case CURLE_RECV_ERROR:
338             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
339             break;
340
341         default:
342             fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
343             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
344             break;
345         }
346     }
347
348     // If nothing is running any longer, bail out
349     if(*runningHandles == 0)
350         return false;
351
352     // If there is no further data to read, and we haven't
353     // read any yet on this invocation, call select to wait for data
354     if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
355     {
356         fd_set readSet;
357         fd_set writeSet;
358         fd_set exceptSet;
359         int fdcnt=0;
360
361         FD_ZERO(&readSet);
362         FD_ZERO(&writeSet);
363         FD_ZERO(&exceptSet);
364
365         // Ask curl for the file descriptors to wait on
366         curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
367
368         // Wait on the file descriptors
369         timeval tv;
370         tv.tv_sec  = 2;
371         tv.tv_usec = 0;
372         select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
373     }
374
375     return curlResult == CURLM_CALL_MULTI_PERFORM;
376 }
377
378 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
379 {
380     fBytesRead = 0;
381     fBytesToRead = maxToRead;
382     fWritePtr = toFill;
383
384     for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
385     {
386         // First, any buffered data we have available
387         size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
388         bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
389         if (bufCnt > 0)
390         {
391             memcpy(fWritePtr, fBufferTailPtr, bufCnt);
392             fWritePtr       += bufCnt;
393             fBytesRead      += bufCnt;
394             fTotalBytesRead += bufCnt;
395             fBytesToRead    -= bufCnt;
396
397             fBufferTailPtr  += bufCnt;
398             if (fBufferTailPtr == fBufferHeadPtr)
399                 fBufferHeadPtr = fBufferTailPtr = fBuffer;
400
401             //fLog.debug("consuming %d buffered bytes", bufCnt);
402
403             tryAgain = true;
404             continue;
405         }
406
407         // Ask the curl to do some work
408         int runningHandles = 0;
409         tryAgain = readMore(&runningHandles);
410
411         // If nothing is running any longer, bail out
412         if (runningHandles == 0)
413             break;
414     }
415
416     return fBytesRead;
417 }