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