6d54cf0b35256a99daf31f3dd6dcd9f4d4e7eb01
[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/ParserPool.h>
28 #include <xmltooling/util/XMLHelper.h>
29
30 #include <openssl/ssl.h>
31 #include <xercesc/util/XercesDefs.hpp>
32 #include <xercesc/util/XMLNetAccessor.hpp>
33 #include <xercesc/util/XMLString.hpp>
34 #include <xercesc/util/XMLExceptMsgs.hpp>
35 #include <xercesc/util/Janitor.hpp>
36 #include <xercesc/util/XMLUniDefs.hpp>
37 #include <xercesc/util/TransService.hpp>
38 #include <xercesc/util/TranscodingException.hpp>
39 #include <xercesc/util/PlatformUtils.hpp>
40
41 using namespace xmltooling;
42 using namespace xercesc;
43 using namespace std;
44
45 namespace {
46     static const XMLCh _CURL[] =            UNICODE_LITERAL_4(C,U,R,L);
47     static const XMLCh _OpenSSL[] =         UNICODE_LITERAL_7(O,p,e,n,S,S,L);
48     static const XMLCh _option[] =          UNICODE_LITERAL_6(o,p,t,i,o,n);
49     static const XMLCh _provider[] =        UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
50     static const XMLCh TransportOption[] =  UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
51     static const XMLCh uri[] =              UNICODE_LITERAL_3(u,r,i);
52     static const XMLCh url[] =              UNICODE_LITERAL_3(u,r,l);
53     static const XMLCh verifyHost[] =       UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
54
55     // callback to invoke a caller-defined SSL callback
56     CURLcode ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
57     {
58         CurlURLInputStream* str = reinterpret_cast<CurlURLInputStream*>(userptr);
59
60         // Default flags manually disable SSLv2 so we're not dependent on libcurl to do it.
61         // Also disable the ticket option where implemented, since this breaks a variety
62         // of servers. Newer libcurl also does this for us.
63 #ifdef SSL_OP_NO_TICKET
64         SSL_CTX_set_options(ssl_ctx, str->getOpenSSLOps()|SSL_OP_NO_TICKET);
65 #else
66         SSL_CTX_set_options(ssl_ctx, str->getOpenSSLOps());
67 #endif
68
69         return CURLE_OK;
70     }
71
72     size_t curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
73     {
74         // only handle single-byte data
75         if (size!=1 || nmemb<5 || !stream)
76             return nmemb;
77         string* cacheTag = reinterpret_cast<string*>(stream);
78         const char* hdr = reinterpret_cast<char*>(ptr);
79         if (strncmp(hdr, "ETag:", 5) == 0) {
80             hdr += 5;
81             size_t remaining = nmemb - 5;
82             // skip leading spaces
83             while (remaining > 0) {
84                 if (*hdr == ' ') {
85                     ++hdr;
86                     --remaining;
87                     continue;
88                 }
89                 break;
90             }
91             // append until whitespace
92             cacheTag->erase();
93             while (remaining > 0) {
94                 if (!isspace(*hdr)) {
95                     (*cacheTag) += *hdr++;
96                     --remaining;
97                     continue;
98                 }
99                 break;
100             }
101
102             if (!cacheTag->empty())
103                 *cacheTag = "If-None-Match: " + *cacheTag;
104         }
105         else if (cacheTag->empty() && strncmp(hdr, "Last-Modified:", 14) == 0) {
106             hdr += 14;
107             size_t remaining = nmemb - 14;
108             // skip leading spaces
109             while (remaining > 0) {
110                 if (*hdr == ' ') {
111                     ++hdr;
112                     --remaining;
113                     continue;
114                 }
115                 break;
116             }
117             // append until whitespace
118             while (remaining > 0) {
119                 if (!isspace(*hdr)) {
120                     (*cacheTag) += *hdr++;
121                     --remaining;
122                     continue;
123                 }
124                 break;
125             }
126
127             if (!cacheTag->empty())
128                 *cacheTag = "If-Modified-Since: " + *cacheTag;
129         }
130
131         return nmemb;
132     }
133 }
134
135 CurlURLInputStream::CurlURLInputStream(const char* url, string* cacheTag)
136     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
137     , fCacheTag(cacheTag)
138     , fURL(url ? url : "")
139     , fOpenSSLOps(SSL_OP_ALL|SSL_OP_NO_SSLv2)
140     , fMulti(0)
141     , fEasy(0)
142     , fHeaders(0)
143     , fTotalBytesRead(0)
144     , fWritePtr(0)
145     , fBytesRead(0)
146     , fBytesToRead(0)
147     , fDataAvailable(false)
148     , fBuffer(0)
149     , fBufferHeadPtr(0)
150     , fBufferTailPtr(0)
151     , fBufferSize(0)
152     , fContentType(0)
153     , fStatusCode(200)
154 {
155     if (fURL.empty())
156         throw IOException("No URL supplied to CurlURLInputStream constructor.");
157     init();
158 }
159
160 CurlURLInputStream::CurlURLInputStream(const XMLCh* url, string* cacheTag)
161     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
162     , fCacheTag(cacheTag)
163     , fOpenSSLOps(SSL_OP_ALL|SSL_OP_NO_SSLv2)
164     , fMulti(0)
165     , fEasy(0)
166     , fHeaders(0)
167     , fTotalBytesRead(0)
168     , fWritePtr(0)
169     , fBytesRead(0)
170     , fBytesToRead(0)
171     , fDataAvailable(false)
172     , fBuffer(0)
173     , fBufferHeadPtr(0)
174     , fBufferTailPtr(0)
175     , fBufferSize(0)
176     , fContentType(0)
177     , fStatusCode(200)
178 {
179     if (url) {
180         auto_ptr_char temp(url);
181         fURL = temp.get();
182     }
183     if (fURL.empty())
184         throw IOException("No URL supplied to CurlURLInputStream constructor.");
185     init();
186 }
187
188 CurlURLInputStream::CurlURLInputStream(const DOMElement* e, string* cacheTag)
189     : fLog(logging::Category::getInstance(XMLTOOLING_LOGCAT".libcurl.InputStream"))
190     , fCacheTag(cacheTag)
191     , fOpenSSLOps(SSL_OP_ALL|SSL_OP_NO_SSLv2)
192     , fMulti(0)
193     , fEasy(0)
194     , fHeaders(0)
195     , fTotalBytesRead(0)
196     , fWritePtr(0)
197     , fBytesRead(0)
198     , fBytesToRead(0)
199     , fDataAvailable(false)
200     , fBuffer(0)
201     , fBufferHeadPtr(0)
202     , fBufferTailPtr(0)
203     , fBufferSize(0)
204     , fContentType(0)
205     , fStatusCode(200)
206 {
207     const XMLCh* attr = e->getAttributeNS(nullptr, url);
208     if (!attr || !*attr) {
209         attr = e->getAttributeNS(nullptr, uri);
210         if (!attr || !*attr)
211             throw IOException("No URL supplied via DOM to CurlURLInputStream constructor.");
212     }
213
214     auto_ptr_char temp(attr);
215     fURL = temp.get();
216     init(e);
217 }
218
219 CurlURLInputStream::~CurlURLInputStream()
220 {
221     if (fEasy) {
222         // Remove the easy handle from the multi stack
223         curl_multi_remove_handle(fMulti, fEasy);
224
225         // Cleanup the easy handle
226         curl_easy_cleanup(fEasy);
227     }
228
229     if (fMulti) {
230         // Cleanup the multi handle
231         curl_multi_cleanup(fMulti);
232     }
233
234     if (fHeaders) {
235         curl_slist_free_all(fHeaders);
236     }
237
238     XMLString::release(&fContentType);
239     free(fBuffer);
240 }
241
242 void CurlURLInputStream::init(const DOMElement* e)
243 {
244     // Allocate the curl multi handle
245     fMulti = curl_multi_init();
246
247     // Allocate the curl easy handle
248     fEasy = curl_easy_init();
249
250     if (!fMulti || !fEasy)
251         throw IOException("Failed to allocate libcurl handles.");
252
253     curl_easy_setopt(fEasy, CURLOPT_URL, fURL.c_str());
254
255     // Set up a way to recieve the data
256     curl_easy_setopt(fEasy, CURLOPT_WRITEDATA, this);                       // Pass this pointer to write function
257     curl_easy_setopt(fEasy, CURLOPT_WRITEFUNCTION, staticWriteCallback);    // Our static write function
258
259     // Do redirects
260     curl_easy_setopt(fEasy, CURLOPT_FOLLOWLOCATION, 1);
261     curl_easy_setopt(fEasy, CURLOPT_MAXREDIRS, 6);
262
263     // Default settings.
264     curl_easy_setopt(fEasy, CURLOPT_CONNECTTIMEOUT, 10);
265     curl_easy_setopt(fEasy, CURLOPT_TIMEOUT, 60);
266     curl_easy_setopt(fEasy, CURLOPT_HTTPAUTH, 0);
267     curl_easy_setopt(fEasy, CURLOPT_USERPWD, nullptr);
268     curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 2);
269     curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYPEER, 0);
270     curl_easy_setopt(fEasy, CURLOPT_CAINFO, nullptr);
271     curl_easy_setopt(fEasy, CURLOPT_SSL_CIPHER_LIST, "ALL:!aNULL:!LOW:!EXPORT:!SSLv2");
272     curl_easy_setopt(fEasy, CURLOPT_NOPROGRESS, 1);
273     curl_easy_setopt(fEasy, CURLOPT_NOSIGNAL, 1);
274     curl_easy_setopt(fEasy, CURLOPT_FAILONERROR, 1);
275     curl_easy_setopt(fEasy, CURLOPT_ENCODING, "");
276
277     // Install SSL callback.
278     curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
279     curl_easy_setopt(fEasy, CURLOPT_SSL_CTX_DATA, this);
280
281     fError[0] = 0;
282     curl_easy_setopt(fEasy, CURLOPT_ERRORBUFFER, fError);
283
284     // Check for cache tag.
285     if (fCacheTag) {
286         // Outgoing tag.
287         if (!fCacheTag->empty()) {
288             fHeaders = curl_slist_append(fHeaders, fCacheTag->c_str());
289         }
290         // Incoming tag.
291         curl_easy_setopt(fEasy, CURLOPT_HEADERFUNCTION, curl_header_hook);
292         curl_easy_setopt(fEasy, CURLOPT_HEADERDATA, fCacheTag);
293     }
294
295     // Add User-Agent as a header for now. TODO: Add private member to hold the
296     // value for the standard UA option.
297     string ua = string("User-Agent: ") + XMLToolingConfig::getConfig().user_agent +
298         " libcurl/" + LIBCURL_VERSION + ' ' + OPENSSL_VERSION_TEXT;
299     fHeaders = curl_slist_append(fHeaders, ua.c_str());
300
301     // Add User-Agent and cache headers.
302     curl_easy_setopt(fEasy, CURLOPT_HTTPHEADER, fHeaders);
303
304     if (e) {
305         const XMLCh* flag = e->getAttributeNS(nullptr, verifyHost);
306         if (flag && (*flag == chLatin_f || *flag == chDigit_0))
307             curl_easy_setopt(fEasy, CURLOPT_SSL_VERIFYHOST, 0);
308
309         // Process TransportOption elements.
310         bool success;
311         DOMElement* child = XMLHelper::getLastChildElement(e, TransportOption);
312         while (child) {
313             if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(nullptr,_provider), _OpenSSL)) {
314                 auto_ptr_char option(child->getAttributeNS(nullptr,_option));
315                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
316                 if (option.get() && value.get() && !strcmp(option.get(), "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION") &&
317                     (*value.get()=='1' || *value.get()=='t')) {
318                     // If the new option to enable buggy rengotiation is available, set it.
319                     // Otherwise, signal false if this is newer than 0.9.8k, because that
320                     // means it's 0.9.8l, which blocks renegotiation, and therefore will
321                     // not honor this request. Older versions are buggy, so behave as though
322                     // the flag was set anyway, so we signal true.
323 #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
324                     fOpenSSLOps |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
325                     success = true;
326 #elif (OPENSSL_VERSION_NUMBER > 0x009080bfL)
327                     success = false;
328 #else
329                     success = true;
330 #endif
331                 }
332                 else {
333                     success = false;
334                 }
335                 if (!success)
336                     fLog.error("failed to set OpenSSL transport option (%s)", option.get());
337             }
338             else if (child->hasChildNodes() && XMLString::equals(child->getAttributeNS(nullptr,_provider), _CURL)) {
339                 auto_ptr_char option(child->getAttributeNS(nullptr,_option));
340                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
341                 if (option.get() && *option.get() && value.get() && *value.get()) {
342                     // For libcurl, the option is an enum and the value type depends on the option.
343                     CURLoption opt = static_cast<CURLoption>(strtol(option.get(), nullptr, 10));
344                     if (opt < CURLOPTTYPE_OBJECTPOINT)
345                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), nullptr, 10)) == CURLE_OK);
346 #ifdef CURLOPTTYPE_OFF_T
347                     else if (opt < CURLOPTTYPE_OFF_T) {
348                         fSavedOptions.push_back(value.get());
349                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
350                     }
351 # ifdef HAVE_CURL_OFF_T
352                     else if (sizeof(curl_off_t) == sizeof(long))
353                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), nullptr, 10)) == CURLE_OK);
354 # else
355                     else if (sizeof(off_t) == sizeof(long))
356                         success = (curl_easy_setopt(fEasy, opt, strtol(value.get(), nullptr, 10)) == CURLE_OK);
357 # endif
358                     else
359                         success = false;
360 #else
361                     else {
362                         fSavedOptions.push_back(value.get());
363                         success = (curl_easy_setopt(fEasy, opt, fSavedOptions.back().c_str()) == CURLE_OK);
364                     }
365 #endif
366                     if (!success)
367                         fLog.error("failed to set CURL transport option (%s)", option.get());
368                 }
369             }
370             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
371         }
372     }
373
374     // Add easy handle to the multi stack
375     curl_multi_add_handle(fMulti, fEasy);
376
377     fLog.debug("libcurl trying to fetch %s", fURL.c_str());
378
379     // Start reading, to get the content type
380     while(fBufferHeadPtr == fBuffer) {
381         int runningHandles = 0;
382         try {
383             readMore(&runningHandles);
384         }
385         catch (XMLException&) {
386             curl_multi_remove_handle(fMulti, fEasy);
387             curl_easy_cleanup(fEasy);
388             fEasy = nullptr;
389             curl_multi_cleanup(fMulti);
390             fMulti = nullptr;
391             throw;
392         }
393         if(runningHandles == 0) break;
394     }
395
396     // Check for a response code.
397     if (curl_easy_getinfo(fEasy, CURLINFO_RESPONSE_CODE, &fStatusCode) == CURLE_OK) {
398         if (fStatusCode >= 300 ) {
399             // Short-circuit usual processing by storing a special XML document in the buffer.
400             ostringstream specialdoc;
401             specialdoc << '<' << URLInputSource::asciiStatusCodeElementName << " xmlns=\"http://www.opensaml.org/xmltooling\">"
402                 << fStatusCode
403                 << "</" << URLInputSource::asciiStatusCodeElementName << '>';
404             string specialxml = specialdoc.str();
405             fBufferTailPtr = fBuffer = reinterpret_cast<XMLByte*>(malloc(specialxml.length()));
406             if (!fBuffer) {
407                 curl_multi_remove_handle(fMulti, fEasy);
408                 curl_easy_cleanup(fEasy);
409                 fEasy = nullptr;
410                 curl_multi_cleanup(fMulti);
411                 fMulti = nullptr;
412                 throw bad_alloc();
413             }
414             memcpy(fBuffer, specialxml.c_str(), specialxml.length());
415             fBufferHeadPtr = fBuffer + specialxml.length();
416         }
417     }
418     else {
419         fStatusCode = 200;  // reset to 200 to ensure no special processing occurs
420     }
421
422     // Find the content type
423     char* contentType8 = nullptr;
424     if(curl_easy_getinfo(fEasy, CURLINFO_CONTENT_TYPE, &contentType8) == CURLE_OK && contentType8)
425         fContentType = XMLString::transcode(contentType8);
426 }
427
428
429 size_t CurlURLInputStream::staticWriteCallback(char* buffer, size_t size, size_t nitems, void* outstream)
430 {
431     return ((CurlURLInputStream*)outstream)->writeCallback(buffer, size, nitems);
432 }
433
434 size_t CurlURLInputStream::writeCallback(char* buffer, size_t size, size_t nitems)
435 {
436     size_t cnt = size * nitems;
437     size_t totalConsumed = 0;
438
439     // Consume as many bytes as possible immediately into the buffer
440     size_t consume = (cnt > fBytesToRead) ? fBytesToRead : cnt;
441     memcpy(fWritePtr, buffer, consume);
442     fWritePtr       += consume;
443     fBytesRead      += consume;
444     fTotalBytesRead += consume;
445     fBytesToRead    -= consume;
446
447     fLog.debug("write callback consuming %u bytes", consume);
448
449     // If bytes remain, rebuffer as many as possible into our holding buffer
450     buffer          += consume;
451     totalConsumed   += consume;
452     cnt             -= consume;
453     if (cnt > 0)
454     {
455         size_t bufAvail = fBufferSize - (fBufferHeadPtr - fBuffer);
456         if (bufAvail < cnt) {
457             // Enlarge the buffer. TODO: limit max size
458             XMLByte* newbuf = reinterpret_cast<XMLByte*>(realloc(fBuffer, fBufferSize + (cnt - bufAvail)));
459             if (newbuf) {
460                 fBufferSize = fBufferSize + (cnt - bufAvail);
461                 fLog.debug("enlarged buffer to %u bytes", fBufferSize);
462                 fBufferHeadPtr = newbuf + (fBufferHeadPtr - fBuffer);
463                 fBuffer = fBufferTailPtr = newbuf;
464             }
465         }
466         memcpy(fBufferHeadPtr, buffer, cnt);
467         fBufferHeadPtr  += cnt;
468         buffer          += cnt;
469         totalConsumed   += cnt;
470         fLog.debug("write callback rebuffering %u bytes", cnt);
471     }
472
473     // Return the total amount we've consumed. If we don't consume all the bytes
474     // then an error will be generated. Since our buffer size is equal to the
475     // maximum size that curl will write, this should never happen unless there
476     // is a logic error somewhere here.
477     return totalConsumed;
478 }
479
480 bool CurlURLInputStream::readMore(int* runningHandles)
481 {
482     // Ask the curl to do some work
483     CURLMcode curlResult = curl_multi_perform(fMulti, runningHandles);
484
485     // Process messages from curl
486     int msgsInQueue = 0;
487     for (CURLMsg* msg = nullptr; (msg = curl_multi_info_read(fMulti, &msgsInQueue)) != nullptr; )
488     {
489         fLog.debug("msg %d, %d from curl", msg->msg, msg->data.result);
490
491         if (msg->msg != CURLMSG_DONE)
492             return true;
493
494         switch (msg->data.result)
495         {
496         case CURLE_OK:
497             // We completed successfully. runningHandles should have dropped to zero, so we'll bail out below...
498             break;
499
500         case CURLE_UNSUPPORTED_PROTOCOL:
501             ThrowXML(MalformedURLException, XMLExcepts::URL_UnsupportedProto);
502             break;
503
504         case CURLE_COULDNT_RESOLVE_HOST:
505         case CURLE_COULDNT_RESOLVE_PROXY:
506             ThrowXML1(NetAccessorException,  XMLExcepts::NetAcc_TargetResolution, fURL.c_str());
507             break;
508
509         case CURLE_COULDNT_CONNECT:
510             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
511             break;
512
513         case CURLE_OPERATION_TIMEDOUT:
514             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, fURL.c_str());
515             break;
516
517         case CURLE_RECV_ERROR:
518             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_ReadSocket, fURL.c_str());
519             break;
520
521         default:
522             fLog.error("error while fetching %s: (%d) %s", fURL.c_str(), msg->data.result, fError);
523             ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError, fURL.c_str());
524             break;
525         }
526     }
527
528     // If nothing is running any longer, bail out
529     if(*runningHandles == 0)
530         return false;
531
532     // If there is no further data to read, and we haven't
533     // read any yet on this invocation, call select to wait for data
534     if (curlResult != CURLM_CALL_MULTI_PERFORM && fBytesRead == 0)
535     {
536         fd_set readSet;
537         fd_set writeSet;
538         fd_set exceptSet;
539         int fdcnt=0;
540
541         FD_ZERO(&readSet);
542         FD_ZERO(&writeSet);
543         FD_ZERO(&exceptSet);
544
545         // Ask curl for the file descriptors to wait on
546         curl_multi_fdset(fMulti, &readSet, &writeSet, &exceptSet, &fdcnt);
547
548         // Wait on the file descriptors
549         timeval tv;
550         tv.tv_sec  = 2;
551         tv.tv_usec = 0;
552         select(fdcnt+1, &readSet, &writeSet, &exceptSet, &tv);
553     }
554
555     return curlResult == CURLM_CALL_MULTI_PERFORM;
556 }
557
558 xsecsize_t CurlURLInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
559 {
560     fBytesRead = 0;
561     fBytesToRead = maxToRead;
562     fWritePtr = toFill;
563
564     for (bool tryAgain = true; fBytesToRead > 0 && (tryAgain || fBytesRead == 0); )
565     {
566         // First, any buffered data we have available
567         size_t bufCnt = fBufferHeadPtr - fBufferTailPtr;
568         bufCnt = (bufCnt > fBytesToRead) ? fBytesToRead : bufCnt;
569         if (bufCnt > 0)
570         {
571             memcpy(fWritePtr, fBufferTailPtr, bufCnt);
572             fWritePtr       += bufCnt;
573             fBytesRead      += bufCnt;
574             fTotalBytesRead += bufCnt;
575             fBytesToRead    -= bufCnt;
576
577             fBufferTailPtr  += bufCnt;
578             if (fBufferTailPtr == fBufferHeadPtr)
579                 fBufferHeadPtr = fBufferTailPtr = fBuffer;
580
581             fLog.debug("consuming %d buffered bytes", bufCnt);
582
583             tryAgain = true;
584             continue;
585         }
586
587         // Check for a non-2xx status that means to ignore the curl response.
588         if (fStatusCode >= 300)
589             break;
590
591         // Ask the curl to do some work
592         int runningHandles = 0;
593         tryAgain = readMore(&runningHandles);
594
595         // If nothing is running any longer, bail out
596         if (runningHandles == 0)
597             break;
598     }
599
600     return fBytesRead;
601 }