LCOV - code coverage report
Current view: top level - port - cpl_vsil_curl.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 2239 2977 75.2 %
Date: 2025-08-19 18:03:11 Functions: 138 150 92.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  CPL - Common Portability Library
       4             :  * Purpose:  Implement VSI large file api for HTTP/FTP files
       5             :  * Author:   Even Rouault, even.rouault at spatialys.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2010-2018, Even Rouault <even.rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "cpl_port.h"
      14             : #include "cpl_vsil_curl_priv.h"
      15             : #include "cpl_vsil_curl_class.h"
      16             : 
      17             : #include <algorithm>
      18             : #include <array>
      19             : #include <limits>
      20             : #include <map>
      21             : #include <memory>
      22             : #include <set>
      23             : 
      24             : #include "cpl_aws.h"
      25             : #include "cpl_json.h"
      26             : #include "cpl_json_header.h"
      27             : #include "cpl_minixml.h"
      28             : #include "cpl_multiproc.h"
      29             : #include "cpl_string.h"
      30             : #include "cpl_time.h"
      31             : #include "cpl_vsi.h"
      32             : #include "cpl_vsi_virtual.h"
      33             : #include "cpl_http.h"
      34             : #include "cpl_mem_cache.h"
      35             : 
      36             : #ifndef S_IRUSR
      37             : #define S_IRUSR 00400
      38             : #define S_IWUSR 00200
      39             : #define S_IXUSR 00100
      40             : #define S_IRGRP 00040
      41             : #define S_IWGRP 00020
      42             : #define S_IXGRP 00010
      43             : #define S_IROTH 00004
      44             : #define S_IWOTH 00002
      45             : #define S_IXOTH 00001
      46             : #endif
      47             : 
      48             : #ifndef HAVE_CURL
      49             : 
      50             : void VSIInstallCurlFileHandler(void)
      51             : {
      52             :     // Not supported.
      53             : }
      54             : 
      55             : void VSICurlClearCache(void)
      56             : {
      57             :     // Not supported.
      58             : }
      59             : 
      60             : void VSICurlPartialClearCache(const char *)
      61             : {
      62             :     // Not supported.
      63             : }
      64             : 
      65             : void VSICurlAuthParametersChanged()
      66             : {
      67             :     // Not supported.
      68             : }
      69             : 
      70             : void VSINetworkStatsReset(void)
      71             : {
      72             :     // Not supported
      73             : }
      74             : 
      75             : char *VSINetworkStatsGetAsSerializedJSON(char ** /* papszOptions */)
      76             : {
      77             :     // Not supported
      78             :     return nullptr;
      79             : }
      80             : 
      81             : /************************************************************************/
      82             : /*                      VSICurlInstallReadCbk()                         */
      83             : /************************************************************************/
      84             : 
      85             : int VSICurlInstallReadCbk(VSILFILE * /* fp */,
      86             :                           VSICurlReadCbkFunc /* pfnReadCbk */,
      87             :                           void * /* pfnUserData */,
      88             :                           int /* bStopOnInterruptUntilUninstall */)
      89             : {
      90             :     return FALSE;
      91             : }
      92             : 
      93             : /************************************************************************/
      94             : /*                    VSICurlUninstallReadCbk()                         */
      95             : /************************************************************************/
      96             : 
      97             : int VSICurlUninstallReadCbk(VSILFILE * /* fp */)
      98             : {
      99             :     return FALSE;
     100             : }
     101             : 
     102             : #else
     103             : 
     104             : //! @cond Doxygen_Suppress
     105             : #ifndef DOXYGEN_SKIP
     106             : 
     107             : #define ENABLE_DEBUG 1
     108             : #define ENABLE_DEBUG_VERBOSE 0
     109             : 
     110             : #define unchecked_curl_easy_setopt(handle, opt, param)                         \
     111             :     CPL_IGNORE_RET_VAL(curl_easy_setopt(handle, opt, param))
     112             : 
     113             : /***********************************************************รน************/
     114             : /*                    VSICurlAuthParametersChanged()                    */
     115             : /************************************************************************/
     116             : 
     117             : static unsigned int gnGenerationAuthParameters = 0;
     118             : 
     119        3067 : void VSICurlAuthParametersChanged()
     120             : {
     121        3067 :     gnGenerationAuthParameters++;
     122        3067 : }
     123             : 
     124             : // Do not access those variables directly !
     125             : // Use VSICURLGetDownloadChunkSize() and GetMaxRegions()
     126             : static int N_MAX_REGIONS_DO_NOT_USE_DIRECTLY = 0;
     127             : static int DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY = 0;
     128             : 
     129             : /************************************************************************/
     130             : /*                    VSICURLReadGlobalEnvVariables()                   */
     131             : /************************************************************************/
     132             : 
     133      147032 : static void VSICURLReadGlobalEnvVariables()
     134             : {
     135             :     struct Initializer
     136             :     {
     137         926 :         Initializer()
     138             :         {
     139         926 :             constexpr int DOWNLOAD_CHUNK_SIZE_DEFAULT = 16384;
     140             :             const char *pszChunkSize =
     141         926 :                 CPLGetConfigOption("CPL_VSIL_CURL_CHUNK_SIZE", nullptr);
     142         926 :             GIntBig nChunkSize = DOWNLOAD_CHUNK_SIZE_DEFAULT;
     143             : 
     144         926 :             if (pszChunkSize)
     145             :             {
     146           0 :                 if (CPLParseMemorySize(pszChunkSize, &nChunkSize, nullptr) !=
     147             :                     CE_None)
     148             :                 {
     149           0 :                     CPLError(
     150             :                         CE_Warning, CPLE_AppDefined,
     151             :                         "Could not parse value for CPL_VSIL_CURL_CHUNK_SIZE. "
     152             :                         "Using default value of %d instead.",
     153             :                         DOWNLOAD_CHUNK_SIZE_DEFAULT);
     154             :                 }
     155             :             }
     156             : 
     157         926 :             constexpr int MIN_CHUNK_SIZE = 1024;
     158         926 :             constexpr int MAX_CHUNK_SIZE = 10 * 1024 * 1024;
     159         926 :             if (nChunkSize < MIN_CHUNK_SIZE || nChunkSize > MAX_CHUNK_SIZE)
     160             :             {
     161           0 :                 nChunkSize = DOWNLOAD_CHUNK_SIZE_DEFAULT;
     162           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     163             :                          "Invalid value for CPL_VSIL_CURL_CHUNK_SIZE. "
     164             :                          "Allowed range is [%d, %d]. "
     165             :                          "Using CPL_VSIL_CURL_CHUNK_SIZE=%d instead",
     166             :                          MIN_CHUNK_SIZE, MAX_CHUNK_SIZE,
     167             :                          DOWNLOAD_CHUNK_SIZE_DEFAULT);
     168             :             }
     169         926 :             DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY =
     170             :                 static_cast<int>(nChunkSize);
     171             : 
     172         926 :             constexpr int N_MAX_REGIONS_DEFAULT = 1000;
     173         926 :             constexpr int CACHE_SIZE_DEFAULT =
     174             :                 N_MAX_REGIONS_DEFAULT * DOWNLOAD_CHUNK_SIZE_DEFAULT;
     175             : 
     176             :             const char *pszCacheSize =
     177         926 :                 CPLGetConfigOption("CPL_VSIL_CURL_CACHE_SIZE", nullptr);
     178         926 :             GIntBig nCacheSize = CACHE_SIZE_DEFAULT;
     179             : 
     180         926 :             if (pszCacheSize)
     181             :             {
     182           0 :                 if (CPLParseMemorySize(pszCacheSize, &nCacheSize, nullptr) !=
     183             :                     CE_None)
     184             :                 {
     185           0 :                     CPLError(
     186             :                         CE_Warning, CPLE_AppDefined,
     187             :                         "Could not parse value for CPL_VSIL_CURL_CACHE_SIZE. "
     188             :                         "Using default value of " CPL_FRMT_GIB " instead.",
     189             :                         nCacheSize);
     190             :                 }
     191             :             }
     192             : 
     193         926 :             const auto nMaxRAM = CPLGetUsablePhysicalRAM();
     194         926 :             const auto nMinVal = DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY;
     195         926 :             auto nMaxVal = static_cast<GIntBig>(INT_MAX) *
     196         926 :                            DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY;
     197         926 :             if (nMaxRAM > 0 && nMaxVal > nMaxRAM)
     198         926 :                 nMaxVal = nMaxRAM;
     199         926 :             if (nCacheSize < nMinVal || nCacheSize > nMaxVal)
     200             :             {
     201           0 :                 nCacheSize = nCacheSize < nMinVal ? nMinVal : nMaxVal;
     202           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     203             :                          "Invalid value for CPL_VSIL_CURL_CACHE_SIZE. "
     204             :                          "Allowed range is [%d, " CPL_FRMT_GIB "]. "
     205             :                          "Using CPL_VSIL_CURL_CACHE_SIZE=" CPL_FRMT_GIB
     206             :                          " instead",
     207             :                          nMinVal, nMaxVal, nCacheSize);
     208             :             }
     209         926 :             N_MAX_REGIONS_DO_NOT_USE_DIRECTLY = std::max(
     210        1852 :                 1, static_cast<int>(nCacheSize /
     211         926 :                                     DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY));
     212         926 :         }
     213             :     };
     214             : 
     215      147032 :     static Initializer initializer;
     216      147032 : }
     217             : 
     218             : /************************************************************************/
     219             : /*                     VSICURLGetDownloadChunkSize()                    */
     220             : /************************************************************************/
     221             : 
     222       92720 : int VSICURLGetDownloadChunkSize()
     223             : {
     224       92720 :     VSICURLReadGlobalEnvVariables();
     225       92720 :     return DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY;
     226             : }
     227             : 
     228             : /************************************************************************/
     229             : /*                            GetMaxRegions()                           */
     230             : /************************************************************************/
     231             : 
     232       54312 : static int GetMaxRegions()
     233             : {
     234       54312 :     VSICURLReadGlobalEnvVariables();
     235       54312 :     return N_MAX_REGIONS_DO_NOT_USE_DIRECTLY;
     236             : }
     237             : 
     238             : /************************************************************************/
     239             : /*          VSICurlFindStringSensitiveExceptEscapeSequences()           */
     240             : /************************************************************************/
     241             : 
     242             : static int
     243         143 : VSICurlFindStringSensitiveExceptEscapeSequences(char **papszList,
     244             :                                                 const char *pszTarget)
     245             : 
     246             : {
     247         143 :     if (papszList == nullptr)
     248         103 :         return -1;
     249             : 
     250         109 :     for (int i = 0; papszList[i] != nullptr; i++)
     251             :     {
     252          92 :         const char *pszIter1 = papszList[i];
     253          92 :         const char *pszIter2 = pszTarget;
     254          92 :         char ch1 = '\0';
     255          92 :         char ch2 = '\0';
     256             :         /* The comparison is case-sensitive, escape for escaped */
     257             :         /* sequences where letters of the hexadecimal sequence */
     258             :         /* can be uppercase or lowercase depending on the quoting algorithm */
     259             :         while (true)
     260             :         {
     261         779 :             ch1 = *pszIter1;
     262         779 :             ch2 = *pszIter2;
     263         779 :             if (ch1 == '\0' || ch2 == '\0')
     264             :                 break;
     265         750 :             if (ch1 == '%' && ch2 == '%' && pszIter1[1] != '\0' &&
     266           0 :                 pszIter1[2] != '\0' && pszIter2[1] != '\0' &&
     267           0 :                 pszIter2[2] != '\0')
     268             :             {
     269           0 :                 if (!EQUALN(pszIter1 + 1, pszIter2 + 1, 2))
     270           0 :                     break;
     271           0 :                 pszIter1 += 2;
     272           0 :                 pszIter2 += 2;
     273             :             }
     274         750 :             if (ch1 != ch2)
     275          63 :                 break;
     276         687 :             pszIter1++;
     277         687 :             pszIter2++;
     278             :         }
     279          92 :         if (ch1 == ch2 && ch1 == '\0')
     280          23 :             return i;
     281             :     }
     282             : 
     283          17 :     return -1;
     284             : }
     285             : 
     286             : /************************************************************************/
     287             : /*                      VSICurlIsFileInList()                           */
     288             : /************************************************************************/
     289             : 
     290         135 : static int VSICurlIsFileInList(char **papszList, const char *pszTarget)
     291             : {
     292             :     int nRet =
     293         135 :         VSICurlFindStringSensitiveExceptEscapeSequences(papszList, pszTarget);
     294         135 :     if (nRet >= 0)
     295          23 :         return nRet;
     296             : 
     297             :     // If we didn't find anything, try to URL-escape the target filename.
     298         112 :     char *pszEscaped = CPLEscapeString(pszTarget, -1, CPLES_URL);
     299         112 :     if (strcmp(pszTarget, pszEscaped) != 0)
     300             :     {
     301           8 :         nRet = VSICurlFindStringSensitiveExceptEscapeSequences(papszList,
     302             :                                                                pszEscaped);
     303             :     }
     304         112 :     CPLFree(pszEscaped);
     305         112 :     return nRet;
     306             : }
     307             : 
     308             : /************************************************************************/
     309             : /*                      VSICurlGetURLFromFilename()                     */
     310             : /************************************************************************/
     311             : 
     312        1916 : static std::string VSICurlGetURLFromFilename(
     313             :     const char *pszFilename, CPLHTTPRetryParameters *poRetryParameters,
     314             :     bool *pbUseHead, bool *pbUseRedirectURLIfNoQueryStringParams,
     315             :     bool *pbListDir, bool *pbEmptyDir, CPLStringList *paosHTTPOptions,
     316             :     bool *pbPlanetaryComputerURLSigning, char **ppszPlanetaryComputerCollection)
     317             : {
     318        1916 :     if (ppszPlanetaryComputerCollection)
     319         691 :         *ppszPlanetaryComputerCollection = nullptr;
     320             : 
     321        1916 :     if (!STARTS_WITH(pszFilename, "/vsicurl/") &&
     322         447 :         !STARTS_WITH(pszFilename, "/vsicurl?"))
     323         359 :         return pszFilename;
     324             : 
     325        1557 :     if (pbPlanetaryComputerURLSigning)
     326             :     {
     327             :         // It may be more convenient sometimes to store Planetary Computer URL
     328             :         // signing as a per-path specific option rather than capturing it in
     329             :         // the filename with the &pc_url_signing=yes option.
     330         691 :         if (CPLTestBool(VSIGetPathSpecificOption(
     331             :                 pszFilename, "VSICURL_PC_URL_SIGNING", "FALSE")))
     332             :         {
     333           1 :             *pbPlanetaryComputerURLSigning = true;
     334             :         }
     335             :     }
     336             : 
     337        1557 :     pszFilename += strlen("/vsicurl/");
     338        1557 :     if (!STARTS_WITH(pszFilename, "http://") &&
     339        1179 :         !STARTS_WITH(pszFilename, "https://") &&
     340          88 :         !STARTS_WITH(pszFilename, "ftp://") &&
     341          88 :         !STARTS_WITH(pszFilename, "file://"))
     342             :     {
     343          88 :         if (*pszFilename == '?')
     344           0 :             pszFilename++;
     345          88 :         char **papszTokens = CSLTokenizeString2(pszFilename, "&", 0);
     346         330 :         for (int i = 0; papszTokens[i] != nullptr; i++)
     347             :         {
     348             :             char *pszUnescaped =
     349         242 :                 CPLUnescapeString(papszTokens[i], nullptr, CPLES_URL);
     350         242 :             CPLFree(papszTokens[i]);
     351         242 :             papszTokens[i] = pszUnescaped;
     352             :         }
     353             : 
     354         176 :         std::string osURL;
     355         176 :         std::string osHeaders;
     356         330 :         for (int i = 0; papszTokens[i]; i++)
     357             :         {
     358         242 :             char *pszKey = nullptr;
     359         242 :             const char *pszValue = CPLParseNameValue(papszTokens[i], &pszKey);
     360         242 :             if (pszKey && pszValue)
     361             :             {
     362         242 :                 if (EQUAL(pszKey, "max_retry"))
     363             :                 {
     364          36 :                     if (poRetryParameters)
     365          13 :                         poRetryParameters->nMaxRetry = atoi(pszValue);
     366             :                 }
     367         206 :                 else if (EQUAL(pszKey, "retry_delay"))
     368             :                 {
     369          16 :                     if (poRetryParameters)
     370           4 :                         poRetryParameters->dfInitialDelay = CPLAtof(pszValue);
     371             :                 }
     372         190 :                 else if (EQUAL(pszKey, "retry_codes"))
     373             :                 {
     374           4 :                     if (poRetryParameters)
     375           1 :                         poRetryParameters->osRetryCodes = pszValue;
     376             :                 }
     377         186 :                 else if (EQUAL(pszKey, "use_head"))
     378             :                 {
     379          24 :                     if (pbUseHead)
     380          11 :                         *pbUseHead = CPLTestBool(pszValue);
     381             :                 }
     382         162 :                 else if (EQUAL(pszKey,
     383             :                                "use_redirect_url_if_no_query_string_params"))
     384             :                 {
     385             :                     /* Undocumented. Used by PLScenes driver */
     386          20 :                     if (pbUseRedirectURLIfNoQueryStringParams)
     387           9 :                         *pbUseRedirectURLIfNoQueryStringParams =
     388           9 :                             CPLTestBool(pszValue);
     389             :                 }
     390         142 :                 else if (EQUAL(pszKey, "list_dir"))
     391             :                 {
     392           0 :                     if (pbListDir)
     393           0 :                         *pbListDir = CPLTestBool(pszValue);
     394             :                 }
     395         142 :                 else if (EQUAL(pszKey, "empty_dir"))
     396             :                 {
     397          20 :                     if (pbEmptyDir)
     398          10 :                         *pbEmptyDir = CPLTestBool(pszValue);
     399             :                 }
     400         122 :                 else if (EQUAL(pszKey, "useragent") ||
     401         122 :                          EQUAL(pszKey, "referer") || EQUAL(pszKey, "cookie") ||
     402         122 :                          EQUAL(pszKey, "header_file") ||
     403         122 :                          EQUAL(pszKey, "unsafessl") ||
     404             : #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
     405         122 :                          EQUAL(pszKey, "timeout") ||
     406         122 :                          EQUAL(pszKey, "connecttimeout") ||
     407             : #endif
     408         122 :                          EQUAL(pszKey, "low_speed_time") ||
     409         122 :                          EQUAL(pszKey, "low_speed_limit") ||
     410         122 :                          EQUAL(pszKey, "proxy") || EQUAL(pszKey, "proxyauth") ||
     411         122 :                          EQUAL(pszKey, "proxyuserpwd"))
     412             :                 {
     413             :                     // Above names are the ones supported by
     414             :                     // CPLHTTPSetOptions()
     415           0 :                     if (paosHTTPOptions)
     416             :                     {
     417           0 :                         paosHTTPOptions->SetNameValue(pszKey, pszValue);
     418             :                     }
     419             :                 }
     420         122 :                 else if (EQUAL(pszKey, "url"))
     421             :                 {
     422          88 :                     osURL = pszValue;
     423             :                 }
     424          34 :                 else if (EQUAL(pszKey, "pc_url_signing"))
     425             :                 {
     426          20 :                     if (pbPlanetaryComputerURLSigning)
     427          10 :                         *pbPlanetaryComputerURLSigning = CPLTestBool(pszValue);
     428             :                 }
     429          14 :                 else if (EQUAL(pszKey, "pc_collection"))
     430             :                 {
     431          10 :                     if (ppszPlanetaryComputerCollection)
     432             :                     {
     433           5 :                         CPLFree(*ppszPlanetaryComputerCollection);
     434           5 :                         *ppszPlanetaryComputerCollection = CPLStrdup(pszValue);
     435             :                     }
     436             :                 }
     437           4 :                 else if (STARTS_WITH(pszKey, "header."))
     438             :                 {
     439           4 :                     osHeaders += (pszKey + strlen("header."));
     440           4 :                     osHeaders += ':';
     441           4 :                     osHeaders += pszValue;
     442           4 :                     osHeaders += "\r\n";
     443             :                 }
     444             :                 else
     445             :                 {
     446           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
     447             :                              "Unsupported option: %s", pszKey);
     448             :                 }
     449             :             }
     450         242 :             CPLFree(pszKey);
     451             :         }
     452             : 
     453          88 :         if (paosHTTPOptions && !osHeaders.empty())
     454           1 :             paosHTTPOptions->SetNameValue("HEADERS", osHeaders.c_str());
     455             : 
     456          88 :         CSLDestroy(papszTokens);
     457          88 :         if (osURL.empty())
     458             :         {
     459           0 :             CPLError(CE_Failure, CPLE_IllegalArg, "Missing url parameter");
     460           0 :             return pszFilename;
     461             :         }
     462             : 
     463          88 :         return osURL;
     464             :     }
     465             : 
     466        1469 :     return pszFilename;
     467             : }
     468             : 
     469             : namespace cpl
     470             : {
     471             : 
     472             : /************************************************************************/
     473             : /*                           VSICurlHandle()                            */
     474             : /************************************************************************/
     475             : 
     476        1029 : VSICurlHandle::VSICurlHandle(VSICurlFilesystemHandlerBase *poFSIn,
     477        1029 :                              const char *pszFilename, const char *pszURLIn)
     478             :     : poFS(poFSIn), m_osFilename(pszFilename),
     479             :       m_aosHTTPOptions(CPLHTTPGetOptionsFromEnv(pszFilename)),
     480        1029 :       m_oRetryParameters(m_aosHTTPOptions),
     481             :       m_bUseHead(
     482        1029 :           CPLTestBool(CPLGetConfigOption("CPL_VSIL_CURL_USE_HEAD", "YES")))
     483             : {
     484        1029 :     if (pszURLIn)
     485             :     {
     486         338 :         m_pszURL = CPLStrdup(pszURLIn);
     487             :     }
     488             :     else
     489             :     {
     490         691 :         char *pszPCCollection = nullptr;
     491         691 :         m_pszURL =
     492         691 :             CPLStrdup(VSICurlGetURLFromFilename(
     493             :                           pszFilename, &m_oRetryParameters, &m_bUseHead,
     494             :                           &m_bUseRedirectURLIfNoQueryStringParams, nullptr,
     495             :                           nullptr, &m_aosHTTPOptions,
     496             :                           &m_bPlanetaryComputerURLSigning, &pszPCCollection)
     497             :                           .c_str());
     498         691 :         if (pszPCCollection)
     499           5 :             m_osPlanetaryComputerCollection = pszPCCollection;
     500         691 :         CPLFree(pszPCCollection);
     501             :     }
     502             : 
     503        1029 :     m_bCached = poFSIn->AllowCachedDataFor(pszFilename);
     504        1029 :     poFS->GetCachedFileProp(m_pszURL, oFileProp);
     505        1029 : }
     506             : 
     507             : /************************************************************************/
     508             : /*                          ~VSICurlHandle()                            */
     509             : /************************************************************************/
     510             : 
     511        1720 : VSICurlHandle::~VSICurlHandle()
     512             : {
     513        1029 :     if (m_oThreadAdviseRead.joinable())
     514             :     {
     515           5 :         m_oThreadAdviseRead.join();
     516             :     }
     517        1029 :     if (m_hCurlMultiHandleForAdviseRead)
     518             :     {
     519           5 :         curl_multi_cleanup(m_hCurlMultiHandleForAdviseRead);
     520             :     }
     521             : 
     522        1029 :     if (!m_bCached)
     523             :     {
     524          58 :         poFS->InvalidateCachedData(m_pszURL);
     525          58 :         poFS->InvalidateDirContent(CPLGetDirnameSafe(m_osFilename.c_str()));
     526             :     }
     527        1029 :     CPLFree(m_pszURL);
     528        1720 : }
     529             : 
     530             : /************************************************************************/
     531             : /*                            SetURL()                                  */
     532             : /************************************************************************/
     533             : 
     534          10 : void VSICurlHandle::SetURL(const char *pszURLIn)
     535             : {
     536          10 :     CPLFree(m_pszURL);
     537          10 :     m_pszURL = CPLStrdup(pszURLIn);
     538          10 : }
     539             : 
     540             : /************************************************************************/
     541             : /*                          InstallReadCbk()                            */
     542             : /************************************************************************/
     543             : 
     544           3 : int VSICurlHandle::InstallReadCbk(VSICurlReadCbkFunc pfnReadCbkIn,
     545             :                                   void *pfnUserDataIn,
     546             :                                   int bStopOnInterruptUntilUninstallIn)
     547             : {
     548           3 :     if (pfnReadCbk != nullptr)
     549           0 :         return FALSE;
     550             : 
     551           3 :     pfnReadCbk = pfnReadCbkIn;
     552           3 :     pReadCbkUserData = pfnUserDataIn;
     553           3 :     bStopOnInterruptUntilUninstall =
     554           3 :         CPL_TO_BOOL(bStopOnInterruptUntilUninstallIn);
     555           3 :     bInterrupted = false;
     556           3 :     return TRUE;
     557             : }
     558             : 
     559             : /************************************************************************/
     560             : /*                         UninstallReadCbk()                           */
     561             : /************************************************************************/
     562             : 
     563           3 : int VSICurlHandle::UninstallReadCbk()
     564             : {
     565           3 :     if (pfnReadCbk == nullptr)
     566           0 :         return FALSE;
     567             : 
     568           3 :     pfnReadCbk = nullptr;
     569           3 :     pReadCbkUserData = nullptr;
     570           3 :     bStopOnInterruptUntilUninstall = false;
     571           3 :     bInterrupted = false;
     572           3 :     return TRUE;
     573             : }
     574             : 
     575             : /************************************************************************/
     576             : /*                                Seek()                                */
     577             : /************************************************************************/
     578             : 
     579        8613 : int VSICurlHandle::Seek(vsi_l_offset nOffset, int nWhence)
     580             : {
     581        8613 :     if (nWhence == SEEK_SET)
     582             :     {
     583        6732 :         curOffset = nOffset;
     584             :     }
     585        1881 :     else if (nWhence == SEEK_CUR)
     586             :     {
     587        1604 :         curOffset = curOffset + nOffset;
     588             :     }
     589             :     else
     590             :     {
     591         277 :         curOffset = GetFileSize(false) + nOffset;
     592             :     }
     593        8613 :     bEOF = false;
     594        8613 :     return 0;
     595             : }
     596             : 
     597             : }  // namespace cpl
     598             : 
     599             : /************************************************************************/
     600             : /*                 VSICurlGetTimeStampFromRFC822DateTime()              */
     601             : /************************************************************************/
     602             : 
     603         946 : static GIntBig VSICurlGetTimeStampFromRFC822DateTime(const char *pszDT)
     604             : {
     605             :     // Sun, 03 Apr 2016 12:07:27 GMT
     606         946 :     if (strlen(pszDT) >= 5 && pszDT[3] == ',' && pszDT[4] == ' ')
     607         946 :         pszDT += 5;
     608         946 :     int nDay = 0;
     609         946 :     int nYear = 0;
     610         946 :     int nHour = 0;
     611         946 :     int nMinute = 0;
     612         946 :     int nSecond = 0;
     613         946 :     char szMonth[4] = {};
     614         946 :     szMonth[3] = 0;
     615         946 :     if (sscanf(pszDT, "%02d %03s %04d %02d:%02d:%02d GMT", &nDay, szMonth,
     616         946 :                &nYear, &nHour, &nMinute, &nSecond) == 6)
     617             :     {
     618             :         static const char *const aszMonthStr[] = {"Jan", "Feb", "Mar", "Apr",
     619             :                                                   "May", "Jun", "Jul", "Aug",
     620             :                                                   "Sep", "Oct", "Nov", "Dec"};
     621             : 
     622         946 :         int nMonthIdx0 = -1;
     623        7540 :         for (int i = 0; i < 12; i++)
     624             :         {
     625        7540 :             if (EQUAL(szMonth, aszMonthStr[i]))
     626             :             {
     627         946 :                 nMonthIdx0 = i;
     628         946 :                 break;
     629             :             }
     630             :         }
     631         946 :         if (nMonthIdx0 >= 0)
     632             :         {
     633             :             struct tm brokendowntime;
     634         946 :             brokendowntime.tm_year = nYear - 1900;
     635         946 :             brokendowntime.tm_mon = nMonthIdx0;
     636         946 :             brokendowntime.tm_mday = nDay;
     637         946 :             brokendowntime.tm_hour = nHour;
     638         946 :             brokendowntime.tm_min = nMinute;
     639         946 :             brokendowntime.tm_sec = nSecond;
     640         946 :             return CPLYMDHMSToUnixTime(&brokendowntime);
     641             :         }
     642             :     }
     643           0 :     return 0;
     644             : }
     645             : 
     646             : /************************************************************************/
     647             : /*                    VSICURLInitWriteFuncStruct()                      */
     648             : /************************************************************************/
     649             : 
     650        2530 : void VSICURLInitWriteFuncStruct(cpl::WriteFuncStruct *psStruct, VSILFILE *fp,
     651             :                                 VSICurlReadCbkFunc pfnReadCbk,
     652             :                                 void *pReadCbkUserData)
     653             : {
     654        2530 :     psStruct->pBuffer = nullptr;
     655        2530 :     psStruct->nSize = 0;
     656        2530 :     psStruct->bIsHTTP = false;
     657        2530 :     psStruct->bMultiRange = false;
     658        2530 :     psStruct->nStartOffset = 0;
     659        2530 :     psStruct->nEndOffset = 0;
     660        2530 :     psStruct->nHTTPCode = 0;
     661        2530 :     psStruct->nFirstHTTPCode = 0;
     662        2530 :     psStruct->nContentLength = 0;
     663        2530 :     psStruct->bFoundContentRange = false;
     664        2530 :     psStruct->bError = false;
     665        2530 :     psStruct->bDetectRangeDownloadingError = true;
     666        2530 :     psStruct->nTimestampDate = 0;
     667             : 
     668        2530 :     psStruct->fp = fp;
     669        2530 :     psStruct->pfnReadCbk = pfnReadCbk;
     670        2530 :     psStruct->pReadCbkUserData = pReadCbkUserData;
     671        2530 :     psStruct->bInterrupted = false;
     672        2530 : }
     673             : 
     674             : /************************************************************************/
     675             : /*                       VSICurlHandleWriteFunc()                       */
     676             : /************************************************************************/
     677             : 
     678       17555 : size_t VSICurlHandleWriteFunc(void *buffer, size_t count, size_t nmemb,
     679             :                               void *req)
     680             : {
     681       17555 :     cpl::WriteFuncStruct *psStruct = static_cast<cpl::WriteFuncStruct *>(req);
     682       17555 :     const size_t nSize = count * nmemb;
     683             : 
     684       17555 :     if (psStruct->bInterrupted)
     685             :     {
     686           8 :         return 0;
     687             :     }
     688             : 
     689             :     char *pNewBuffer = static_cast<char *>(
     690       17547 :         VSIRealloc(psStruct->pBuffer, psStruct->nSize + nSize + 1));
     691       17548 :     if (pNewBuffer)
     692             :     {
     693       17548 :         psStruct->pBuffer = pNewBuffer;
     694       17548 :         memcpy(psStruct->pBuffer + psStruct->nSize, buffer, nSize);
     695       17548 :         psStruct->pBuffer[psStruct->nSize + nSize] = '\0';
     696       17548 :         if (psStruct->bIsHTTP)
     697             :         {
     698       10397 :             char *pszLine = psStruct->pBuffer + psStruct->nSize;
     699       10397 :             if (STARTS_WITH_CI(pszLine, "HTTP/"))
     700             :             {
     701         947 :                 char *pszSpace = strchr(pszLine, ' ');
     702         947 :                 if (pszSpace)
     703             :                 {
     704         947 :                     const int nHTTPCode = atoi(pszSpace + 1);
     705         947 :                     if (psStruct->nFirstHTTPCode == 0)
     706         833 :                         psStruct->nFirstHTTPCode = nHTTPCode;
     707         947 :                     psStruct->nHTTPCode = nHTTPCode;
     708             :                 }
     709             :             }
     710        9450 :             else if (STARTS_WITH_CI(pszLine, "Content-Length: "))
     711             :             {
     712         869 :                 psStruct->nContentLength = CPLScanUIntBig(
     713         869 :                     pszLine + 16, static_cast<int>(strlen(pszLine + 16)));
     714             :             }
     715        8581 :             else if (STARTS_WITH_CI(pszLine, "Content-Range: "))
     716             :             {
     717         280 :                 psStruct->bFoundContentRange = true;
     718             :             }
     719        8301 :             else if (STARTS_WITH_CI(pszLine, "Date: "))
     720             :             {
     721         946 :                 CPLString osDate = pszLine + strlen("Date: ");
     722         946 :                 size_t nSizeLine = osDate.size();
     723        4730 :                 while (nSizeLine && (osDate[nSizeLine - 1] == '\r' ||
     724        1892 :                                      osDate[nSizeLine - 1] == '\n'))
     725             :                 {
     726        1892 :                     osDate.resize(nSizeLine - 1);
     727        1892 :                     nSizeLine--;
     728             :                 }
     729         946 :                 osDate.Trim();
     730             : 
     731             :                 GIntBig nTimestampDate =
     732         946 :                     VSICurlGetTimeStampFromRFC822DateTime(osDate.c_str());
     733             : #if DEBUG_VERBOSE
     734             :                 CPLDebug("VSICURL", "Timestamp = " CPL_FRMT_GIB,
     735             :                          nTimestampDate);
     736             : #endif
     737         946 :                 psStruct->nTimestampDate = nTimestampDate;
     738             :             }
     739             :             /*if( nSize > 2 && pszLine[nSize - 2] == '\r' &&
     740             :                   pszLine[nSize - 1] == '\n' )
     741             :             {
     742             :                 pszLine[nSize - 2] = 0;
     743             :                 CPLDebug("VSICURL", "%s", pszLine);
     744             :                 pszLine[nSize - 2] = '\r';
     745             :             }*/
     746             : 
     747       10397 :             if (pszLine[0] == '\r' && pszLine[1] == '\n')
     748             :             {
     749             :                 // Detect servers that don't support range downloading.
     750         947 :                 if (psStruct->nHTTPCode == 200 &&
     751         342 :                     psStruct->bDetectRangeDownloadingError &&
     752         131 :                     !psStruct->bMultiRange && !psStruct->bFoundContentRange &&
     753         121 :                     (psStruct->nStartOffset != 0 ||
     754         121 :                      psStruct->nContentLength >
     755         121 :                          10 * (psStruct->nEndOffset - psStruct->nStartOffset +
     756             :                                1)))
     757             :                 {
     758           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
     759             :                              "Range downloading not supported by this "
     760             :                              "server!");
     761           0 :                     psStruct->bError = true;
     762           0 :                     return 0;
     763             :                 }
     764             :             }
     765             :         }
     766             :         else
     767             :         {
     768        7151 :             if (psStruct->pfnReadCbk)
     769             :             {
     770           1 :                 if (!psStruct->pfnReadCbk(psStruct->fp, buffer, nSize,
     771             :                                           psStruct->pReadCbkUserData))
     772             :                 {
     773           0 :                     psStruct->bInterrupted = true;
     774           0 :                     return 0;
     775             :                 }
     776             :             }
     777             :         }
     778       17548 :         psStruct->nSize += nSize;
     779       17548 :         return nmemb;
     780             :     }
     781             :     else
     782             :     {
     783           0 :         return 0;
     784             :     }
     785             : }
     786             : 
     787             : /************************************************************************/
     788             : /*                    VSICurlIsS3LikeSignedURL()                        */
     789             : /************************************************************************/
     790             : 
     791         427 : static bool VSICurlIsS3LikeSignedURL(const char *pszURL)
     792             : {
     793         850 :     return ((strstr(pszURL, ".s3.amazonaws.com/") != nullptr ||
     794         423 :              strstr(pszURL, ".s3.amazonaws.com:") != nullptr ||
     795         423 :              strstr(pszURL, ".storage.googleapis.com/") != nullptr ||
     796         423 :              strstr(pszURL, ".storage.googleapis.com:") != nullptr ||
     797         423 :              strstr(pszURL, ".cloudfront.net/") != nullptr ||
     798         423 :              strstr(pszURL, ".cloudfront.net:") != nullptr) &&
     799           4 :             (strstr(pszURL, "&Signature=") != nullptr ||
     800           4 :              strstr(pszURL, "?Signature=") != nullptr)) ||
     801        1279 :            strstr(pszURL, "&X-Amz-Signature=") != nullptr ||
     802         852 :            strstr(pszURL, "?X-Amz-Signature=") != nullptr;
     803             : }
     804             : 
     805             : /************************************************************************/
     806             : /*                  VSICurlGetExpiresFromS3LikeSignedURL()              */
     807             : /************************************************************************/
     808             : 
     809           4 : static GIntBig VSICurlGetExpiresFromS3LikeSignedURL(const char *pszURL)
     810             : {
     811          18 :     const auto GetParamValue = [pszURL](const char *pszKey) -> const char *
     812             :     {
     813          12 :         for (const char *pszPrefix : {"&", "?"})
     814             :         {
     815          10 :             std::string osNeedle(pszPrefix);
     816          10 :             osNeedle += pszKey;
     817          10 :             osNeedle += '=';
     818          10 :             const char *pszStr = strstr(pszURL, osNeedle.c_str());
     819          10 :             if (pszStr)
     820           6 :                 return pszStr + osNeedle.size();
     821             :         }
     822           2 :         return nullptr;
     823           4 :     };
     824             : 
     825             :     {
     826             :         // Expires= is a Unix timestamp
     827           4 :         const char *pszExpires = GetParamValue("Expires");
     828           4 :         if (pszExpires != nullptr)
     829           2 :             return CPLAtoGIntBig(pszExpires);
     830             :     }
     831             : 
     832             :     // X-Amz-Expires= is a delay, to be combined with X-Amz-Date=
     833           2 :     const char *pszAmzExpires = GetParamValue("X-Amz-Expires");
     834           2 :     if (pszAmzExpires == nullptr)
     835           0 :         return 0;
     836           2 :     const int nDelay = atoi(pszAmzExpires);
     837             : 
     838           2 :     const char *pszAmzDate = GetParamValue("X-Amz-Date");
     839           2 :     if (pszAmzDate == nullptr)
     840           0 :         return 0;
     841             :     // pszAmzDate should be YYYYMMDDTHHMMSSZ
     842           2 :     if (strlen(pszAmzDate) < strlen("YYYYMMDDTHHMMSSZ"))
     843           0 :         return 0;
     844           2 :     if (pszAmzDate[strlen("YYYYMMDDTHHMMSSZ") - 1] != 'Z')
     845           0 :         return 0;
     846             :     struct tm brokendowntime;
     847           2 :     brokendowntime.tm_year =
     848           2 :         atoi(std::string(pszAmzDate).substr(0, 4).c_str()) - 1900;
     849           2 :     brokendowntime.tm_mon =
     850           2 :         atoi(std::string(pszAmzDate).substr(4, 2).c_str()) - 1;
     851           2 :     brokendowntime.tm_mday = atoi(std::string(pszAmzDate).substr(6, 2).c_str());
     852           2 :     brokendowntime.tm_hour = atoi(std::string(pszAmzDate).substr(9, 2).c_str());
     853           2 :     brokendowntime.tm_min = atoi(std::string(pszAmzDate).substr(11, 2).c_str());
     854           2 :     brokendowntime.tm_sec = atoi(std::string(pszAmzDate).substr(13, 2).c_str());
     855           2 :     return CPLYMDHMSToUnixTime(&brokendowntime) + nDelay;
     856             : }
     857             : 
     858             : /************************************************************************/
     859             : /*                       VSICURLMultiPerform()                          */
     860             : /************************************************************************/
     861             : 
     862        1288 : void VSICURLMultiPerform(CURLM *hCurlMultiHandle, CURL *hEasyHandle,
     863             :                          std::atomic<bool> *pbInterrupt)
     864             : {
     865        1288 :     int repeats = 0;
     866             : 
     867        1288 :     if (hEasyHandle)
     868        1286 :         curl_multi_add_handle(hCurlMultiHandle, hEasyHandle);
     869             : 
     870        1288 :     void *old_handler = CPLHTTPIgnoreSigPipe();
     871             :     while (true)
     872             :     {
     873             :         int still_running;
     874        4611 :         while (curl_multi_perform(hCurlMultiHandle, &still_running) ==
     875             :                CURLM_CALL_MULTI_PERFORM)
     876             :         {
     877             :             // loop
     878             :         }
     879        4611 :         if (!still_running)
     880             :         {
     881        1288 :             break;
     882             :         }
     883             : 
     884             : #ifdef undef
     885             :         CURLMsg *msg;
     886             :         do
     887             :         {
     888             :             int msgq = 0;
     889             :             msg = curl_multi_info_read(hCurlMultiHandle, &msgq);
     890             :             if (msg && (msg->msg == CURLMSG_DONE))
     891             :             {
     892             :                 CURL *e = msg->easy_handle;
     893             :             }
     894             :         } while (msg);
     895             : #endif
     896             : 
     897        3323 :         CPLMultiPerformWait(hCurlMultiHandle, repeats);
     898             : 
     899        3324 :         if (pbInterrupt && *pbInterrupt)
     900           0 :             break;
     901        3323 :     }
     902        1288 :     CPLHTTPRestoreSigPipeHandler(old_handler);
     903             : 
     904        1288 :     if (hEasyHandle)
     905        1286 :         curl_multi_remove_handle(hCurlMultiHandle, hEasyHandle);
     906        1288 : }
     907             : 
     908             : /************************************************************************/
     909             : /*                       VSICurlDummyWriteFunc()                        */
     910             : /************************************************************************/
     911             : 
     912           0 : static size_t VSICurlDummyWriteFunc(void *, size_t, size_t, void *)
     913             : {
     914           0 :     return 0;
     915             : }
     916             : 
     917             : /************************************************************************/
     918             : /*                  VSICURLResetHeaderAndWriterFunctions()              */
     919             : /************************************************************************/
     920             : 
     921        1247 : void VSICURLResetHeaderAndWriterFunctions(CURL *hCurlHandle)
     922             : {
     923        1247 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
     924             :                                VSICurlDummyWriteFunc);
     925        1247 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
     926             :                                VSICurlDummyWriteFunc);
     927        1247 : }
     928             : 
     929             : /************************************************************************/
     930             : /*                        Iso8601ToUnixTime()                           */
     931             : /************************************************************************/
     932             : 
     933           6 : static bool Iso8601ToUnixTime(const char *pszDT, GIntBig *pnUnixTime)
     934             : {
     935             :     int nYear;
     936             :     int nMonth;
     937             :     int nDay;
     938             :     int nHour;
     939             :     int nMinute;
     940             :     int nSecond;
     941           6 :     if (sscanf(pszDT, "%04d-%02d-%02dT%02d:%02d:%02d", &nYear, &nMonth, &nDay,
     942           6 :                &nHour, &nMinute, &nSecond) == 6)
     943             :     {
     944             :         struct tm brokendowntime;
     945           6 :         brokendowntime.tm_year = nYear - 1900;
     946           6 :         brokendowntime.tm_mon = nMonth - 1;
     947           6 :         brokendowntime.tm_mday = nDay;
     948           6 :         brokendowntime.tm_hour = nHour;
     949           6 :         brokendowntime.tm_min = nMinute;
     950           6 :         brokendowntime.tm_sec = nSecond;
     951           6 :         *pnUnixTime = CPLYMDHMSToUnixTime(&brokendowntime);
     952           6 :         return true;
     953             :     }
     954           0 :     return false;
     955             : }
     956             : 
     957             : namespace cpl
     958             : {
     959             : 
     960             : /************************************************************************/
     961             : /*                   ManagePlanetaryComputerSigning()                   */
     962             : /************************************************************************/
     963             : 
     964          11 : void VSICurlHandle::ManagePlanetaryComputerSigning() const
     965             : {
     966             :     // Take global lock
     967             :     static std::mutex goMutex;
     968          22 :     std::lock_guard<std::mutex> oLock(goMutex);
     969             : 
     970             :     struct PCSigningInfo
     971             :     {
     972             :         std::string osQueryString{};
     973             :         GIntBig nExpireTimestamp = 0;
     974             :     };
     975             : 
     976          22 :     PCSigningInfo sSigningInfo;
     977          11 :     constexpr int knExpirationDelayMargin = 60;
     978             : 
     979          11 :     if (!m_osPlanetaryComputerCollection.empty())
     980             :     {
     981             :         // key is the name of a collection
     982           5 :         static lru11::Cache<std::string, PCSigningInfo> goCacheCollection{1024};
     983             : 
     984           5 :         if (goCacheCollection.tryGet(m_osPlanetaryComputerCollection,
     985           8 :                                      sSigningInfo) &&
     986           3 :             time(nullptr) + knExpirationDelayMargin <=
     987           3 :                 sSigningInfo.nExpireTimestamp)
     988             :         {
     989           2 :             m_osQueryString = sSigningInfo.osQueryString;
     990             :         }
     991             :         else
     992             :         {
     993             :             const auto psResult =
     994           9 :                 CPLHTTPFetch((std::string(CPLGetConfigOption(
     995             :                                   "VSICURL_PC_SAS_TOKEN_URL",
     996             :                                   "https://planetarycomputer.microsoft.com/api/"
     997           6 :                                   "sas/v1/token/")) +
     998           3 :                               m_osPlanetaryComputerCollection)
     999             :                                  .c_str(),
    1000             :                              nullptr);
    1001           3 :             if (psResult)
    1002             :             {
    1003             :                 const auto aosKeyVals = CPLParseKeyValueJson(
    1004           6 :                     reinterpret_cast<const char *>(psResult->pabyData));
    1005           3 :                 const char *pszToken = aosKeyVals.FetchNameValue("token");
    1006           3 :                 if (pszToken)
    1007             :                 {
    1008           3 :                     m_osQueryString = '?';
    1009           3 :                     m_osQueryString += pszToken;
    1010             : 
    1011           3 :                     sSigningInfo.osQueryString = m_osQueryString;
    1012           3 :                     sSigningInfo.nExpireTimestamp = 0;
    1013             :                     const char *pszExpiry =
    1014           3 :                         aosKeyVals.FetchNameValue("msft:expiry");
    1015           3 :                     if (pszExpiry)
    1016             :                     {
    1017           3 :                         Iso8601ToUnixTime(pszExpiry,
    1018             :                                           &sSigningInfo.nExpireTimestamp);
    1019             :                     }
    1020           3 :                     goCacheCollection.insert(m_osPlanetaryComputerCollection,
    1021             :                                              sSigningInfo);
    1022             : 
    1023           3 :                     CPLDebug("VSICURL", "Got token from Planetary Computer: %s",
    1024             :                              m_osQueryString.c_str());
    1025             :                 }
    1026           3 :                 CPLHTTPDestroyResult(psResult);
    1027             :             }
    1028             :         }
    1029             :     }
    1030             :     else
    1031             :     {
    1032             :         // key is a URL
    1033           6 :         static lru11::Cache<std::string, PCSigningInfo> goCacheURL{1024};
    1034             : 
    1035          10 :         if (goCacheURL.tryGet(m_pszURL, sSigningInfo) &&
    1036           4 :             time(nullptr) + knExpirationDelayMargin <=
    1037           4 :                 sSigningInfo.nExpireTimestamp)
    1038             :         {
    1039           3 :             m_osQueryString = sSigningInfo.osQueryString;
    1040             :         }
    1041             :         else
    1042             :         {
    1043             :             const auto psResult =
    1044           9 :                 CPLHTTPFetch((std::string(CPLGetConfigOption(
    1045             :                                   "VSICURL_PC_SAS_SIGN_HREF_URL",
    1046             :                                   "https://planetarycomputer.microsoft.com/api/"
    1047           6 :                                   "sas/v1/sign?href=")) +
    1048           3 :                               m_pszURL)
    1049             :                                  .c_str(),
    1050             :                              nullptr);
    1051           3 :             if (psResult)
    1052             :             {
    1053             :                 const auto aosKeyVals = CPLParseKeyValueJson(
    1054           6 :                     reinterpret_cast<const char *>(psResult->pabyData));
    1055           3 :                 const char *pszHref = aosKeyVals.FetchNameValue("href");
    1056           3 :                 if (pszHref && STARTS_WITH(pszHref, m_pszURL))
    1057             :                 {
    1058           3 :                     m_osQueryString = pszHref + strlen(m_pszURL);
    1059             : 
    1060           3 :                     sSigningInfo.osQueryString = m_osQueryString;
    1061           3 :                     sSigningInfo.nExpireTimestamp = 0;
    1062             :                     const char *pszExpiry =
    1063           3 :                         aosKeyVals.FetchNameValue("msft:expiry");
    1064           3 :                     if (pszExpiry)
    1065             :                     {
    1066           3 :                         Iso8601ToUnixTime(pszExpiry,
    1067             :                                           &sSigningInfo.nExpireTimestamp);
    1068             :                     }
    1069           3 :                     goCacheURL.insert(m_pszURL, sSigningInfo);
    1070             : 
    1071           3 :                     CPLDebug("VSICURL",
    1072             :                              "Got signature from Planetary Computer: %s",
    1073             :                              m_osQueryString.c_str());
    1074             :                 }
    1075           3 :                 CPLHTTPDestroyResult(psResult);
    1076             :             }
    1077             :         }
    1078             :     }
    1079          11 : }
    1080             : 
    1081             : /************************************************************************/
    1082             : /*                        UpdateQueryString()                           */
    1083             : /************************************************************************/
    1084             : 
    1085         816 : void VSICurlHandle::UpdateQueryString() const
    1086             : {
    1087         816 :     if (m_bPlanetaryComputerURLSigning)
    1088             :     {
    1089          11 :         ManagePlanetaryComputerSigning();
    1090             :     }
    1091             :     else
    1092             :     {
    1093         805 :         const char *pszQueryString = VSIGetPathSpecificOption(
    1094             :             m_osFilename.c_str(), "VSICURL_QUERY_STRING", nullptr);
    1095         805 :         if (pszQueryString)
    1096             :         {
    1097           4 :             if (m_osFilename.back() == '?')
    1098             :             {
    1099           2 :                 if (pszQueryString[0] == '?')
    1100           1 :                     m_osQueryString = pszQueryString + 1;
    1101             :                 else
    1102           1 :                     m_osQueryString = pszQueryString;
    1103             :             }
    1104             :             else
    1105             :             {
    1106           2 :                 if (pszQueryString[0] == '?')
    1107           1 :                     m_osQueryString = pszQueryString;
    1108             :                 else
    1109             :                 {
    1110           1 :                     m_osQueryString = "?";
    1111           1 :                     m_osQueryString.append(pszQueryString);
    1112             :                 }
    1113             :             }
    1114             :         }
    1115             :     }
    1116         816 : }
    1117             : 
    1118             : /************************************************************************/
    1119             : /*                     GetFileSizeOrHeaders()                           */
    1120             : /************************************************************************/
    1121             : 
    1122         956 : vsi_l_offset VSICurlHandle::GetFileSizeOrHeaders(bool bSetError,
    1123             :                                                  bool bGetHeaders)
    1124             : {
    1125         956 :     if (oFileProp.bHasComputedFileSize && !bGetHeaders)
    1126         534 :         return oFileProp.fileSize;
    1127             : 
    1128         844 :     NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
    1129         844 :     NetworkStatisticsFile oContextFile(m_osFilename.c_str());
    1130         844 :     NetworkStatisticsAction oContextAction("GetFileSize");
    1131             : 
    1132         422 :     oFileProp.bHasComputedFileSize = true;
    1133             : 
    1134         422 :     CURLM *hCurlMultiHandle = poFS->GetCurlMultiHandleFor(m_pszURL);
    1135             : 
    1136         422 :     UpdateQueryString();
    1137             : 
    1138         844 :     std::string osURL(m_pszURL + m_osQueryString);
    1139         422 :     bool bRetryWithGet = false;
    1140         422 :     bool bS3LikeRedirect = false;
    1141         844 :     CPLHTTPRetryContext oRetryContext(m_oRetryParameters);
    1142             : 
    1143         429 : retry:
    1144         429 :     CURL *hCurlHandle = curl_easy_init();
    1145             : 
    1146             :     struct curl_slist *headers =
    1147         429 :         VSICurlSetOptions(hCurlHandle, osURL.c_str(), m_aosHTTPOptions.List());
    1148             : 
    1149         429 :     WriteFuncStruct sWriteFuncHeaderData;
    1150         429 :     VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
    1151             :                                nullptr);
    1152         429 :     sWriteFuncHeaderData.bDetectRangeDownloadingError = false;
    1153         429 :     sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(osURL.c_str(), "http");
    1154             : 
    1155         429 :     WriteFuncStruct sWriteFuncData;
    1156         429 :     VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
    1157             : 
    1158         429 :     std::string osVerb;
    1159         429 :     std::string osRange;  // leave in this scope !
    1160         429 :     int nRoundedBufSize = 0;
    1161         429 :     const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
    1162         429 :     if (UseLimitRangeGetInsteadOfHead())
    1163             :     {
    1164         128 :         osVerb = "GET";
    1165             :         const int nBufSize = std::max(
    1166         384 :             1024, std::min(10 * 1024 * 1024,
    1167         128 :                            atoi(CPLGetConfigOption(
    1168         128 :                                "GDAL_INGESTED_BYTES_AT_OPEN", "1024"))));
    1169         128 :         nRoundedBufSize = cpl::div_round_up(nBufSize, knDOWNLOAD_CHUNK_SIZE) *
    1170             :                           knDOWNLOAD_CHUNK_SIZE;
    1171             : 
    1172             :         // so it gets included in Azure signature
    1173         128 :         osRange = CPLSPrintf("Range: bytes=0-%d", nRoundedBufSize - 1);
    1174         128 :         headers = curl_slist_append(headers, osRange.c_str());
    1175             :     }
    1176             :     // HACK for mbtiles driver: http://a.tiles.mapbox.com/v3/ doesn't accept
    1177             :     // HEAD, as it is a redirect to AWS S3 signed URL, but those are only valid
    1178             :     // for a given type of HTTP request, and thus GET. This is valid for any
    1179             :     // signed URL for AWS S3.
    1180         595 :     else if (bRetryWithGet ||
    1181         587 :              strstr(osURL.c_str(), ".tiles.mapbox.com/") != nullptr ||
    1182         888 :              VSICurlIsS3LikeSignedURL(osURL.c_str()) || !m_bUseHead)
    1183             :     {
    1184          13 :         sWriteFuncData.bInterrupted = true;
    1185          13 :         osVerb = "GET";
    1186             :     }
    1187             :     else
    1188             :     {
    1189         288 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_NOBODY, 1);
    1190         288 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPGET, 0);
    1191         288 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADER, 1);
    1192         288 :         osVerb = "HEAD";
    1193             :     }
    1194             : 
    1195         429 :     if (!AllowAutomaticRedirection())
    1196          81 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FOLLOWLOCATION, 0);
    1197             : 
    1198         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    1199             :                                &sWriteFuncHeaderData);
    1200         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    1201             :                                VSICurlHandleWriteFunc);
    1202             : 
    1203             :     // Bug with older curl versions (<=7.16.4) and FTP.
    1204             :     // See http://curl.haxx.se/mail/lib-2007-08/0312.html
    1205         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
    1206         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    1207             :                                VSICurlHandleWriteFunc);
    1208             : 
    1209         429 :     char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
    1210         429 :     szCurlErrBuf[0] = '\0';
    1211         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
    1212             : 
    1213         429 :     headers = GetCurlHeaders(osVerb, headers);
    1214         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    1215             : 
    1216         429 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FILETIME, 1);
    1217             : 
    1218         429 :     VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle, &m_bInterrupt);
    1219             : 
    1220         429 :     VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
    1221             : 
    1222         429 :     curl_slist_free_all(headers);
    1223             : 
    1224         429 :     oFileProp.eExists = EXIST_UNKNOWN;
    1225             : 
    1226         429 :     long mtime = 0;
    1227         429 :     curl_easy_getinfo(hCurlHandle, CURLINFO_FILETIME, &mtime);
    1228             : 
    1229         429 :     if (osVerb == "GET")
    1230         141 :         NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
    1231             :     else
    1232         288 :         NetworkStatisticsLogger::LogHEAD();
    1233             : 
    1234         429 :     if (STARTS_WITH(osURL.c_str(), "ftp"))
    1235             :     {
    1236           0 :         if (sWriteFuncData.pBuffer != nullptr)
    1237             :         {
    1238             :             const char *pszContentLength =
    1239           0 :                 strstr(const_cast<const char *>(sWriteFuncData.pBuffer),
    1240             :                        "Content-Length: ");
    1241           0 :             if (pszContentLength)
    1242             :             {
    1243           0 :                 pszContentLength += strlen("Content-Length: ");
    1244           0 :                 oFileProp.eExists = EXIST_YES;
    1245           0 :                 oFileProp.fileSize =
    1246           0 :                     CPLScanUIntBig(pszContentLength,
    1247           0 :                                    static_cast<int>(strlen(pszContentLength)));
    1248             :                 if (ENABLE_DEBUG)
    1249           0 :                     CPLDebug(poFS->GetDebugKey(),
    1250             :                              "GetFileSize(%s)=" CPL_FRMT_GUIB, osURL.c_str(),
    1251             :                              oFileProp.fileSize);
    1252             :             }
    1253             :         }
    1254             :     }
    1255             : 
    1256         429 :     double dfSize = 0;
    1257         429 :     if (oFileProp.eExists != EXIST_YES)
    1258             :     {
    1259         429 :         long response_code = 0;
    1260         429 :         curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
    1261             : 
    1262         429 :         bool bAlreadyLogged = false;
    1263         429 :         if (response_code >= 400 && szCurlErrBuf[0] == '\0')
    1264             :         {
    1265             :             const bool bLogResponse =
    1266         192 :                 CPLTestBool(CPLGetConfigOption("CPL_CURL_VERBOSE", "NO"));
    1267         192 :             if (bLogResponse && sWriteFuncData.pBuffer)
    1268             :             {
    1269           0 :                 const char *pszErrorMsg =
    1270             :                     static_cast<const char *>(sWriteFuncData.pBuffer);
    1271           0 :                 bAlreadyLogged = true;
    1272           0 :                 CPLDebug(
    1273           0 :                     poFS->GetDebugKey(),
    1274             :                     "GetFileSize(%s): response_code=%d, server error msg=%s",
    1275             :                     osURL.c_str(), static_cast<int>(response_code),
    1276           0 :                     pszErrorMsg[0] ? pszErrorMsg : "(no message provided)");
    1277         192 :             }
    1278             :         }
    1279         237 :         else if (szCurlErrBuf[0] != '\0')
    1280             :         {
    1281          14 :             bAlreadyLogged = true;
    1282          14 :             CPLDebug(poFS->GetDebugKey(),
    1283             :                      "GetFileSize(%s): response_code=%d, curl error msg=%s",
    1284             :                      osURL.c_str(), static_cast<int>(response_code),
    1285             :                      szCurlErrBuf);
    1286             :         }
    1287             : 
    1288         429 :         std::string osEffectiveURL;
    1289             :         {
    1290         429 :             char *pszEffectiveURL = nullptr;
    1291         429 :             curl_easy_getinfo(hCurlHandle, CURLINFO_EFFECTIVE_URL,
    1292             :                               &pszEffectiveURL);
    1293         429 :             if (pszEffectiveURL)
    1294         429 :                 osEffectiveURL = pszEffectiveURL;
    1295             :         }
    1296             : 
    1297         858 :         if (!osEffectiveURL.empty() &&
    1298         429 :             strstr(osEffectiveURL.c_str(), osURL.c_str()) == nullptr)
    1299             :         {
    1300             :             // Moved permanently ?
    1301          53 :             if (sWriteFuncHeaderData.nFirstHTTPCode == 301 ||
    1302          22 :                 (m_bUseRedirectURLIfNoQueryStringParams &&
    1303           2 :                  osEffectiveURL.find('?') == std::string::npos))
    1304             :             {
    1305          15 :                 CPLDebug(poFS->GetDebugKey(),
    1306             :                          "Using effective URL %s permanently",
    1307             :                          osEffectiveURL.c_str());
    1308          15 :                 oFileProp.osRedirectURL = osEffectiveURL;
    1309          15 :                 poFS->SetCachedFileProp(m_pszURL, oFileProp);
    1310             :             }
    1311             :             else
    1312             :             {
    1313          18 :                 CPLDebug(poFS->GetDebugKey(),
    1314             :                          "Using effective URL %s temporarily",
    1315             :                          osEffectiveURL.c_str());
    1316             :             }
    1317             : 
    1318             :             // Is this is a redirect to a S3 URL?
    1319          35 :             if (VSICurlIsS3LikeSignedURL(osEffectiveURL.c_str()) &&
    1320           2 :                 !VSICurlIsS3LikeSignedURL(osURL.c_str()))
    1321             :             {
    1322             :                 // Note that this is a redirect as we won't notice after the
    1323             :                 // retry.
    1324           2 :                 bS3LikeRedirect = true;
    1325             : 
    1326           2 :                 if (!bRetryWithGet && osVerb == "HEAD" && response_code == 403)
    1327             :                 {
    1328           2 :                     CPLDebug(poFS->GetDebugKey(),
    1329             :                              "Redirected to a AWS S3 signed URL. Retrying "
    1330             :                              "with GET request instead of HEAD since the URL "
    1331             :                              "might be valid only for GET");
    1332           2 :                     bRetryWithGet = true;
    1333           2 :                     osURL = std::move(osEffectiveURL);
    1334           2 :                     CPLFree(sWriteFuncData.pBuffer);
    1335           2 :                     CPLFree(sWriteFuncHeaderData.pBuffer);
    1336           2 :                     curl_easy_cleanup(hCurlHandle);
    1337           2 :                     goto retry;
    1338             :                 }
    1339             :             }
    1340             :         }
    1341             : 
    1342           2 :         if (bS3LikeRedirect && response_code >= 200 && response_code < 300 &&
    1343           2 :             sWriteFuncHeaderData.nTimestampDate > 0 &&
    1344         431 :             !osEffectiveURL.empty() &&
    1345           2 :             CPLTestBool(
    1346             :                 CPLGetConfigOption("CPL_VSIL_CURL_USE_S3_REDIRECT", "TRUE")))
    1347             :         {
    1348             :             const GIntBig nExpireTimestamp =
    1349           2 :                 VSICurlGetExpiresFromS3LikeSignedURL(osEffectiveURL.c_str());
    1350           2 :             if (nExpireTimestamp > sWriteFuncHeaderData.nTimestampDate + 10)
    1351             :             {
    1352           2 :                 const int nValidity = static_cast<int>(
    1353           2 :                     nExpireTimestamp - sWriteFuncHeaderData.nTimestampDate);
    1354           2 :                 CPLDebug(poFS->GetDebugKey(),
    1355             :                          "Will use redirect URL for the next %d seconds",
    1356             :                          nValidity);
    1357             :                 // As our local clock might not be in sync with server clock,
    1358             :                 // figure out the expiration timestamp in local time
    1359           2 :                 oFileProp.bS3LikeRedirect = true;
    1360           2 :                 oFileProp.nExpireTimestampLocal = time(nullptr) + nValidity;
    1361           2 :                 oFileProp.osRedirectURL = osEffectiveURL;
    1362           2 :                 poFS->SetCachedFileProp(m_pszURL, oFileProp);
    1363             :             }
    1364             :         }
    1365             : 
    1366         427 :         curl_off_t nSizeTmp = 0;
    1367         427 :         const CURLcode code = curl_easy_getinfo(
    1368             :             hCurlHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &nSizeTmp);
    1369         427 :         CPL_IGNORE_RET_VAL(dfSize);
    1370         427 :         dfSize = static_cast<double>(nSizeTmp);
    1371         427 :         if (code == 0)
    1372             :         {
    1373         427 :             oFileProp.eExists = EXIST_YES;
    1374         427 :             if (dfSize < 0)
    1375             :             {
    1376          66 :                 if (osVerb == "HEAD" && !bRetryWithGet && response_code == 200)
    1377             :                 {
    1378           4 :                     CPLDebug(
    1379           4 :                         poFS->GetDebugKey(),
    1380             :                         "HEAD did not provide file size. Retrying with GET");
    1381           4 :                     bRetryWithGet = true;
    1382           4 :                     CPLFree(sWriteFuncData.pBuffer);
    1383           4 :                     CPLFree(sWriteFuncHeaderData.pBuffer);
    1384           4 :                     curl_easy_cleanup(hCurlHandle);
    1385           4 :                     goto retry;
    1386             :                 }
    1387          62 :                 oFileProp.fileSize = 0;
    1388             :             }
    1389             :             else
    1390         361 :                 oFileProp.fileSize = static_cast<GUIntBig>(dfSize);
    1391             :         }
    1392             : 
    1393         423 :         if (sWriteFuncHeaderData.pBuffer != nullptr &&
    1394         418 :             (response_code == 200 || response_code == 206))
    1395             :         {
    1396             :             {
    1397             :                 char **papszHeaders =
    1398         227 :                     CSLTokenizeString2(sWriteFuncHeaderData.pBuffer, "\r\n", 0);
    1399        2194 :                 for (int i = 0; papszHeaders[i]; ++i)
    1400             :                 {
    1401        1967 :                     char *pszKey = nullptr;
    1402             :                     const char *pszValue =
    1403        1967 :                         CPLParseNameValue(papszHeaders[i], &pszKey);
    1404        1967 :                     if (pszKey && pszValue)
    1405             :                     {
    1406        1712 :                         if (bGetHeaders)
    1407             :                         {
    1408          17 :                             m_aosHeaders.SetNameValue(pszKey, pszValue);
    1409             :                         }
    1410        3467 :                         if (EQUAL(pszKey, "Cache-Control") &&
    1411        1730 :                             EQUAL(pszValue, "no-cache") &&
    1412          18 :                             CPLTestBool(CPLGetConfigOption(
    1413             :                                 "CPL_VSIL_CURL_HONOR_CACHE_CONTROL", "YES")))
    1414             :                         {
    1415          18 :                             m_bCached = false;
    1416             :                         }
    1417             : 
    1418        1694 :                         else if (EQUAL(pszKey, "ETag"))
    1419             :                         {
    1420         104 :                             std::string osValue(pszValue);
    1421          99 :                             if (osValue.size() >= 2 && osValue.front() == '"' &&
    1422          47 :                                 osValue.back() == '"')
    1423          47 :                                 osValue = osValue.substr(1, osValue.size() - 2);
    1424          52 :                             oFileProp.ETag = std::move(osValue);
    1425             :                         }
    1426             : 
    1427             :                         // Azure Data Lake Storage
    1428        1642 :                         else if (EQUAL(pszKey, "x-ms-resource-type"))
    1429             :                         {
    1430          11 :                             if (EQUAL(pszValue, "file"))
    1431             :                             {
    1432           9 :                                 oFileProp.nMode |= S_IFREG;
    1433             :                             }
    1434           2 :                             else if (EQUAL(pszValue, "directory"))
    1435             :                             {
    1436           2 :                                 oFileProp.bIsDirectory = true;
    1437           2 :                                 oFileProp.nMode |= S_IFDIR;
    1438             :                             }
    1439             :                         }
    1440        1631 :                         else if (EQUAL(pszKey, "x-ms-permissions"))
    1441             :                         {
    1442          11 :                             oFileProp.nMode |=
    1443          11 :                                 VSICurlParseUnixPermissions(pszValue);
    1444             :                         }
    1445             : 
    1446             :                         // https://overturemapswestus2.blob.core.windows.net/release/2024-11-13.0/theme%3Ddivisions/type%3Ddivision_area
    1447             :                         // returns a x-ms-meta-hdi_isfolder: true header
    1448        1620 :                         else if (EQUAL(pszKey, "x-ms-meta-hdi_isfolder") &&
    1449           1 :                                  EQUAL(pszValue, "true"))
    1450             :                         {
    1451           1 :                             oFileProp.bIsAzureFolder = true;
    1452           1 :                             oFileProp.bIsDirectory = true;
    1453           1 :                             oFileProp.nMode |= S_IFDIR;
    1454             :                         }
    1455             :                     }
    1456        1967 :                     CPLFree(pszKey);
    1457             :                 }
    1458         227 :                 CSLDestroy(papszHeaders);
    1459             :             }
    1460             :         }
    1461             : 
    1462         423 :         if (UseLimitRangeGetInsteadOfHead() && response_code == 206)
    1463             :         {
    1464          20 :             oFileProp.eExists = EXIST_NO;
    1465          20 :             oFileProp.fileSize = 0;
    1466          20 :             if (sWriteFuncHeaderData.pBuffer != nullptr)
    1467             :             {
    1468          20 :                 const char *pszContentRange = strstr(
    1469             :                     sWriteFuncHeaderData.pBuffer, "Content-Range: bytes ");
    1470          20 :                 if (pszContentRange == nullptr)
    1471           0 :                     pszContentRange = strstr(sWriteFuncHeaderData.pBuffer,
    1472             :                                              "content-range: bytes ");
    1473          20 :                 if (pszContentRange)
    1474          20 :                     pszContentRange = strchr(pszContentRange, '/');
    1475          20 :                 if (pszContentRange)
    1476             :                 {
    1477          20 :                     oFileProp.eExists = EXIST_YES;
    1478          20 :                     oFileProp.fileSize = static_cast<GUIntBig>(
    1479          20 :                         CPLAtoGIntBig(pszContentRange + 1));
    1480             :                 }
    1481             : 
    1482             :                 // Add first bytes to cache
    1483          20 :                 if (sWriteFuncData.pBuffer != nullptr)
    1484             :                 {
    1485          20 :                     size_t nOffset = 0;
    1486          40 :                     while (nOffset < sWriteFuncData.nSize)
    1487             :                     {
    1488             :                         const size_t nToCache =
    1489          40 :                             std::min<size_t>(sWriteFuncData.nSize - nOffset,
    1490          20 :                                              knDOWNLOAD_CHUNK_SIZE);
    1491          20 :                         poFS->AddRegion(m_pszURL, nOffset, nToCache,
    1492          20 :                                         sWriteFuncData.pBuffer + nOffset);
    1493          20 :                         nOffset += nToCache;
    1494             :                     }
    1495             :                 }
    1496             :             }
    1497             :         }
    1498         403 :         else if (IsDirectoryFromExists(osVerb.c_str(),
    1499         403 :                                        static_cast<int>(response_code)))
    1500             :         {
    1501          10 :             oFileProp.eExists = EXIST_YES;
    1502          10 :             oFileProp.fileSize = 0;
    1503          10 :             oFileProp.bIsDirectory = true;
    1504             :         }
    1505             :         // 405 = Method not allowed
    1506         393 :         else if (response_code == 405 && !bRetryWithGet && osVerb == "HEAD")
    1507             :         {
    1508           1 :             CPLDebug(poFS->GetDebugKey(),
    1509             :                      "HEAD not allowed. Retrying with GET");
    1510           1 :             bRetryWithGet = true;
    1511           1 :             CPLFree(sWriteFuncData.pBuffer);
    1512           1 :             CPLFree(sWriteFuncHeaderData.pBuffer);
    1513           1 :             curl_easy_cleanup(hCurlHandle);
    1514           1 :             goto retry;
    1515             :         }
    1516         392 :         else if (response_code == 416)
    1517             :         {
    1518           0 :             oFileProp.eExists = EXIST_YES;
    1519           0 :             oFileProp.fileSize = 0;
    1520             :         }
    1521         392 :         else if (response_code != 200)
    1522             :         {
    1523             :             // Look if we should attempt a retry
    1524         185 :             if (oRetryContext.CanRetry(static_cast<int>(response_code),
    1525         185 :                                        sWriteFuncHeaderData.pBuffer,
    1526             :                                        szCurlErrBuf))
    1527             :             {
    1528           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1529             :                          "HTTP error code: %d - %s. "
    1530             :                          "Retrying again in %.1f secs",
    1531             :                          static_cast<int>(response_code), m_pszURL,
    1532             :                          oRetryContext.GetCurrentDelay());
    1533           0 :                 CPLSleep(oRetryContext.GetCurrentDelay());
    1534           0 :                 CPLFree(sWriteFuncData.pBuffer);
    1535           0 :                 CPLFree(sWriteFuncHeaderData.pBuffer);
    1536           0 :                 curl_easy_cleanup(hCurlHandle);
    1537           0 :                 goto retry;
    1538             :             }
    1539             : 
    1540         185 :             if (sWriteFuncData.pBuffer != nullptr)
    1541             :             {
    1542         155 :                 if (UseLimitRangeGetInsteadOfHead() &&
    1543           7 :                     CanRestartOnError(sWriteFuncData.pBuffer,
    1544           7 :                                       sWriteFuncHeaderData.pBuffer, bSetError))
    1545             :                 {
    1546           1 :                     oFileProp.bHasComputedFileSize = false;
    1547           1 :                     CPLFree(sWriteFuncData.pBuffer);
    1548           1 :                     CPLFree(sWriteFuncHeaderData.pBuffer);
    1549           1 :                     curl_easy_cleanup(hCurlHandle);
    1550           1 :                     return GetFileSizeOrHeaders(bSetError, bGetHeaders);
    1551             :                 }
    1552             :                 else
    1553             :                 {
    1554         147 :                     CPL_IGNORE_RET_VAL(CanRestartOnError(
    1555         147 :                         sWriteFuncData.pBuffer, sWriteFuncHeaderData.pBuffer,
    1556         147 :                         bSetError));
    1557             :                 }
    1558             :             }
    1559             : 
    1560             :             // If there was no VSI error thrown in the process,
    1561             :             // fail by reporting the HTTP response code.
    1562         184 :             if (bSetError && VSIGetLastErrorNo() == 0)
    1563             :             {
    1564          10 :                 if (strlen(szCurlErrBuf) > 0)
    1565             :                 {
    1566           1 :                     if (response_code == 0)
    1567             :                     {
    1568           1 :                         VSIError(VSIE_HttpError, "CURL error: %s",
    1569             :                                  szCurlErrBuf);
    1570             :                     }
    1571             :                     else
    1572             :                     {
    1573           0 :                         VSIError(VSIE_HttpError, "HTTP response code: %d - %s",
    1574             :                                  static_cast<int>(response_code), szCurlErrBuf);
    1575             :                     }
    1576             :                 }
    1577             :                 else
    1578             :                 {
    1579           9 :                     VSIError(VSIE_HttpError, "HTTP response code: %d",
    1580             :                              static_cast<int>(response_code));
    1581             :                 }
    1582             :             }
    1583             :             else
    1584             :             {
    1585         174 :                 if (response_code != 400 && response_code != 404)
    1586             :                 {
    1587          24 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1588             :                              "HTTP response code on %s: %d", osURL.c_str(),
    1589             :                              static_cast<int>(response_code));
    1590             :                 }
    1591             :                 // else a CPLDebug() is emitted below
    1592             :             }
    1593             : 
    1594         184 :             oFileProp.eExists = EXIST_NO;
    1595         184 :             oFileProp.nHTTPCode = static_cast<int>(response_code);
    1596         184 :             oFileProp.fileSize = 0;
    1597             :         }
    1598         207 :         else if (sWriteFuncData.pBuffer != nullptr)
    1599             :         {
    1600         183 :             ProcessGetFileSizeResult(
    1601         183 :                 reinterpret_cast<const char *>(sWriteFuncData.pBuffer));
    1602             :         }
    1603             : 
    1604             :         // Try to guess if this is a directory. Generally if this is a
    1605             :         // directory, curl will retry with an URL with slash added.
    1606         421 :         if (!osEffectiveURL.empty() &&
    1607         811 :             strncmp(osURL.c_str(), osEffectiveURL.c_str(), osURL.size()) == 0 &&
    1608         390 :             osEffectiveURL[osURL.size()] == '/')
    1609             :         {
    1610           0 :             oFileProp.eExists = EXIST_YES;
    1611           0 :             oFileProp.fileSize = 0;
    1612           0 :             oFileProp.bIsDirectory = true;
    1613             :         }
    1614         421 :         else if (osURL.back() == '/')
    1615             :         {
    1616          37 :             oFileProp.bIsDirectory = true;
    1617             :         }
    1618             : 
    1619         421 :         if (!bAlreadyLogged)
    1620             :         {
    1621         407 :             CPLDebug(poFS->GetDebugKey(),
    1622             :                      "GetFileSize(%s)=" CPL_FRMT_GUIB "  response_code=%d",
    1623             :                      osURL.c_str(), oFileProp.fileSize,
    1624             :                      static_cast<int>(response_code));
    1625             :         }
    1626             :     }
    1627             : 
    1628         421 :     CPLFree(sWriteFuncData.pBuffer);
    1629         421 :     CPLFree(sWriteFuncHeaderData.pBuffer);
    1630         421 :     curl_easy_cleanup(hCurlHandle);
    1631             : 
    1632         421 :     oFileProp.bHasComputedFileSize = true;
    1633         421 :     if (mtime > 0)
    1634          39 :         oFileProp.mTime = mtime;
    1635         421 :     poFS->SetCachedFileProp(m_pszURL, oFileProp);
    1636             : 
    1637         421 :     return oFileProp.fileSize;
    1638             : }
    1639             : 
    1640             : /************************************************************************/
    1641             : /*                                 Exists()                             */
    1642             : /************************************************************************/
    1643             : 
    1644         726 : bool VSICurlHandle::Exists(bool bSetError)
    1645             : {
    1646         726 :     if (oFileProp.eExists == EXIST_UNKNOWN)
    1647             :     {
    1648         231 :         GetFileSize(bSetError);
    1649             :     }
    1650         495 :     else if (oFileProp.eExists == EXIST_NO)
    1651             :     {
    1652             :         // If there was no VSI error thrown in the process,
    1653             :         // and we know the HTTP error code of the first request where the
    1654             :         // file could not be retrieved, fail by reporting the HTTP code.
    1655         158 :         if (bSetError && VSIGetLastErrorNo() == 0 && oFileProp.nHTTPCode)
    1656             :         {
    1657           1 :             VSIError(VSIE_HttpError, "HTTP response code: %d",
    1658             :                      oFileProp.nHTTPCode);
    1659             :         }
    1660             :     }
    1661             : 
    1662         726 :     return oFileProp.eExists == EXIST_YES;
    1663             : }
    1664             : 
    1665             : /************************************************************************/
    1666             : /*                                  Tell()                              */
    1667             : /************************************************************************/
    1668             : 
    1669        1995 : vsi_l_offset VSICurlHandle::Tell()
    1670             : {
    1671        1995 :     return curOffset;
    1672             : }
    1673             : 
    1674             : /************************************************************************/
    1675             : /*                       GetRedirectURLIfValid()                        */
    1676             : /************************************************************************/
    1677             : 
    1678             : std::string
    1679         394 : VSICurlHandle::GetRedirectURLIfValid(bool &bHasExpired,
    1680             :                                      CPLStringList &aosHTTPOptions) const
    1681             : {
    1682         394 :     bHasExpired = false;
    1683         394 :     poFS->GetCachedFileProp(m_pszURL, oFileProp);
    1684             : 
    1685         394 :     std::string osURL(m_pszURL + m_osQueryString);
    1686         394 :     if (oFileProp.bS3LikeRedirect)
    1687             :     {
    1688           4 :         if (time(nullptr) + 1 < oFileProp.nExpireTimestampLocal)
    1689             :         {
    1690           4 :             CPLDebug(poFS->GetDebugKey(),
    1691             :                      "Using redirect URL as it looks to be still valid "
    1692             :                      "(%d seconds left)",
    1693           4 :                      static_cast<int>(oFileProp.nExpireTimestampLocal -
    1694           4 :                                       time(nullptr)));
    1695           4 :             osURL = oFileProp.osRedirectURL;
    1696             :         }
    1697             :         else
    1698             :         {
    1699           0 :             CPLDebug(poFS->GetDebugKey(),
    1700             :                      "Redirect URL has expired. Using original URL");
    1701           0 :             oFileProp.bS3LikeRedirect = false;
    1702           0 :             poFS->SetCachedFileProp(m_pszURL, oFileProp);
    1703           0 :             bHasExpired = true;
    1704             :         }
    1705             :     }
    1706         390 :     else if (!oFileProp.osRedirectURL.empty())
    1707             :     {
    1708          14 :         osURL = oFileProp.osRedirectURL;
    1709          14 :         bHasExpired = false;
    1710             :     }
    1711             : 
    1712         394 :     if (m_pszURL != osURL)
    1713             :     {
    1714          19 :         const char *pszAuthorizationHeaderAllowed = CPLGetConfigOption(
    1715             :             "CPL_VSIL_CURL_AUTHORIZATION_HEADER_ALLOWED_IF_REDIRECT",
    1716             :             "IF_SAME_HOST");
    1717          19 :         if (EQUAL(pszAuthorizationHeaderAllowed, "IF_SAME_HOST"))
    1718             :         {
    1719          26 :             const auto ExtractServer = [](const std::string &s)
    1720             :             {
    1721          26 :                 size_t afterHTTPPos = 0;
    1722          26 :                 if (STARTS_WITH(s.c_str(), "http://"))
    1723          26 :                     afterHTTPPos = strlen("http://");
    1724           0 :                 else if (STARTS_WITH(s.c_str(), "https://"))
    1725           0 :                     afterHTTPPos = strlen("https://");
    1726          26 :                 const auto posSlash = s.find('/', afterHTTPPos);
    1727          26 :                 if (posSlash != std::string::npos)
    1728          26 :                     return s.substr(afterHTTPPos, posSlash - afterHTTPPos);
    1729             :                 else
    1730           0 :                     return s.substr(afterHTTPPos);
    1731             :             };
    1732             : 
    1733          13 :             if (ExtractServer(osURL) != ExtractServer(m_pszURL))
    1734             :             {
    1735             :                 aosHTTPOptions.SetNameValue("AUTHORIZATION_HEADER_ALLOWED",
    1736           6 :                                             "NO");
    1737             :             }
    1738             :         }
    1739           6 :         else if (!CPLTestBool(pszAuthorizationHeaderAllowed))
    1740             :         {
    1741           3 :             aosHTTPOptions.SetNameValue("AUTHORIZATION_HEADER_ALLOWED", "NO");
    1742             :         }
    1743             :     }
    1744             : 
    1745         394 :     return osURL;
    1746             : }
    1747             : 
    1748             : /************************************************************************/
    1749             : /*                          CurrentDownload                             */
    1750             : /************************************************************************/
    1751             : 
    1752             : namespace
    1753             : {
    1754             : struct CurrentDownload
    1755             : {
    1756             :     VSICurlFilesystemHandlerBase *m_poFS = nullptr;
    1757             :     std::string m_osURL{};
    1758             :     vsi_l_offset m_nStartOffset = 0;
    1759             :     int m_nBlocks = 0;
    1760             :     std::string m_osAlreadyDownloadedData{};
    1761             :     bool m_bHasAlreadyDownloadedData = false;
    1762             : 
    1763         316 :     CurrentDownload(VSICurlFilesystemHandlerBase *poFS, const char *pszURL,
    1764             :                     vsi_l_offset startOffset, int nBlocks)
    1765         316 :         : m_poFS(poFS), m_osURL(pszURL), m_nStartOffset(startOffset),
    1766         316 :           m_nBlocks(nBlocks)
    1767             :     {
    1768         316 :         auto res = m_poFS->NotifyStartDownloadRegion(m_osURL, m_nStartOffset,
    1769         632 :                                                      m_nBlocks);
    1770         316 :         m_bHasAlreadyDownloadedData = res.first;
    1771         316 :         m_osAlreadyDownloadedData = std::move(res.second);
    1772         316 :     }
    1773             : 
    1774         316 :     bool HasAlreadyDownloadedData() const
    1775             :     {
    1776         316 :         return m_bHasAlreadyDownloadedData;
    1777             :     }
    1778             : 
    1779           2 :     const std::string &GetAlreadyDownloadedData() const
    1780             :     {
    1781           2 :         return m_osAlreadyDownloadedData;
    1782             :     }
    1783             : 
    1784         309 :     void SetData(const std::string &osData)
    1785             :     {
    1786         309 :         CPLAssert(!m_bHasAlreadyDownloadedData);
    1787         309 :         m_bHasAlreadyDownloadedData = true;
    1788         309 :         m_poFS->NotifyStopDownloadRegion(m_osURL, m_nStartOffset, m_nBlocks,
    1789             :                                          osData);
    1790         309 :     }
    1791             : 
    1792         316 :     ~CurrentDownload()
    1793         316 :     {
    1794         316 :         if (!m_bHasAlreadyDownloadedData)
    1795           5 :             m_poFS->NotifyStopDownloadRegion(m_osURL, m_nStartOffset, m_nBlocks,
    1796          10 :                                              std::string());
    1797         316 :     }
    1798             : 
    1799             :     CurrentDownload(const CurrentDownload &) = delete;
    1800             :     CurrentDownload &operator=(const CurrentDownload &) = delete;
    1801             : };
    1802             : }  // namespace
    1803             : 
    1804             : /************************************************************************/
    1805             : /*                      NotifyStartDownloadRegion()                     */
    1806             : /************************************************************************/
    1807             : 
    1808             : /** Indicate intent at downloading a new region.
    1809             :  *
    1810             :  * If the region is already in download in another thread, then wait for its
    1811             :  * completion.
    1812             :  *
    1813             :  * Returns:
    1814             :  * - (false, empty string) if a new download is needed
    1815             :  * - (true, region_content) if we have been waiting for a download of the same
    1816             :  *   region to be completed and got its result. Note that region_content will be
    1817             :  *   empty if the download of that region failed.
    1818             :  */
    1819             : std::pair<bool, std::string>
    1820         316 : VSICurlFilesystemHandlerBase::NotifyStartDownloadRegion(
    1821             :     const std::string &osURL, vsi_l_offset startOffset, int nBlocks)
    1822             : {
    1823         632 :     std::string osId(osURL);
    1824         316 :     osId += '_';
    1825         316 :     osId += std::to_string(startOffset);
    1826         316 :     osId += '_';
    1827         316 :     osId += std::to_string(nBlocks);
    1828             : 
    1829         316 :     m_oMutex.lock();
    1830         316 :     auto oIter = m_oMapRegionInDownload.find(osId);
    1831         316 :     if (oIter != m_oMapRegionInDownload.end())
    1832             :     {
    1833           2 :         auto &region = *(oIter->second);
    1834           4 :         std::unique_lock<std::mutex> oRegionLock(region.oMutex);
    1835           2 :         m_oMutex.unlock();
    1836           2 :         region.nWaiters++;
    1837           4 :         while (region.bDownloadInProgress)
    1838             :         {
    1839           2 :             region.oCond.wait(oRegionLock);
    1840             :         }
    1841           2 :         std::string osRet = region.osData;
    1842           2 :         region.nWaiters--;
    1843           2 :         region.oCond.notify_one();
    1844           2 :         return std::pair<bool, std::string>(true, osRet);
    1845             :     }
    1846             :     else
    1847             :     {
    1848         314 :         auto poRegionInDownload = std::make_unique<RegionInDownload>();
    1849         314 :         poRegionInDownload->bDownloadInProgress = true;
    1850         314 :         m_oMapRegionInDownload[osId] = std::move(poRegionInDownload);
    1851         314 :         m_oMutex.unlock();
    1852         314 :         return std::pair<bool, std::string>(false, std::string());
    1853             :     }
    1854             : }
    1855             : 
    1856             : /************************************************************************/
    1857             : /*                      NotifyStopDownloadRegion()                      */
    1858             : /************************************************************************/
    1859             : 
    1860         314 : void VSICurlFilesystemHandlerBase::NotifyStopDownloadRegion(
    1861             :     const std::string &osURL, vsi_l_offset startOffset, int nBlocks,
    1862             :     const std::string &osData)
    1863             : {
    1864         628 :     std::string osId(osURL);
    1865         314 :     osId += '_';
    1866         314 :     osId += std::to_string(startOffset);
    1867         314 :     osId += '_';
    1868         314 :     osId += std::to_string(nBlocks);
    1869             : 
    1870         314 :     m_oMutex.lock();
    1871         314 :     auto oIter = m_oMapRegionInDownload.find(osId);
    1872         314 :     CPLAssert(oIter != m_oMapRegionInDownload.end());
    1873         314 :     auto &region = *(oIter->second);
    1874             :     {
    1875         628 :         std::unique_lock<std::mutex> oRegionLock(region.oMutex);
    1876         314 :         if (region.nWaiters)
    1877             :         {
    1878           2 :             region.osData = osData;
    1879           2 :             region.bDownloadInProgress = false;
    1880           2 :             region.oCond.notify_all();
    1881             : 
    1882           4 :             while (region.nWaiters)
    1883             :             {
    1884           2 :                 region.oCond.wait(oRegionLock);
    1885             :             }
    1886             :         }
    1887             :     }
    1888         314 :     m_oMapRegionInDownload.erase(oIter);
    1889         314 :     m_oMutex.unlock();
    1890         314 : }
    1891             : 
    1892             : /************************************************************************/
    1893             : /*                          DownloadRegion()                            */
    1894             : /************************************************************************/
    1895             : 
    1896         316 : std::string VSICurlHandle::DownloadRegion(const vsi_l_offset startOffset,
    1897             :                                           const int nBlocks)
    1898             : {
    1899         316 :     if (bInterrupted && bStopOnInterruptUntilUninstall)
    1900           0 :         return std::string();
    1901             : 
    1902         316 :     if (oFileProp.eExists == EXIST_NO)
    1903           0 :         return std::string();
    1904             : 
    1905             :     // Check if there is not a download of the same region in progress in
    1906             :     // another thread, and if so wait for it to be completed
    1907         632 :     CurrentDownload currentDownload(poFS, m_pszURL, startOffset, nBlocks);
    1908         316 :     if (currentDownload.HasAlreadyDownloadedData())
    1909             :     {
    1910           2 :         return currentDownload.GetAlreadyDownloadedData();
    1911             :     }
    1912             : 
    1913         314 : begin:
    1914         323 :     CURLM *hCurlMultiHandle = poFS->GetCurlMultiHandleFor(m_pszURL);
    1915             : 
    1916         323 :     UpdateQueryString();
    1917             : 
    1918         323 :     bool bHasExpired = false;
    1919             : 
    1920         323 :     CPLStringList aosHTTPOptions(m_aosHTTPOptions);
    1921         323 :     std::string osURL(GetRedirectURLIfValid(bHasExpired, aosHTTPOptions));
    1922         323 :     bool bUsedRedirect = osURL != m_pszURL;
    1923             : 
    1924         323 :     WriteFuncStruct sWriteFuncData;
    1925         323 :     WriteFuncStruct sWriteFuncHeaderData;
    1926         323 :     CPLHTTPRetryContext oRetryContext(m_oRetryParameters);
    1927             : 
    1928         333 : retry:
    1929         333 :     CURL *hCurlHandle = curl_easy_init();
    1930             :     struct curl_slist *headers =
    1931         333 :         VSICurlSetOptions(hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
    1932             : 
    1933         333 :     if (!AllowAutomaticRedirection())
    1934          60 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FOLLOWLOCATION, 0);
    1935             : 
    1936         333 :     VSICURLInitWriteFuncStruct(&sWriteFuncData, this, pfnReadCbk,
    1937             :                                pReadCbkUserData);
    1938         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
    1939         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    1940             :                                VSICurlHandleWriteFunc);
    1941             : 
    1942         333 :     VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
    1943             :                                nullptr);
    1944         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    1945             :                                &sWriteFuncHeaderData);
    1946         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    1947             :                                VSICurlHandleWriteFunc);
    1948         333 :     sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(m_pszURL, "http");
    1949         333 :     sWriteFuncHeaderData.nStartOffset = startOffset;
    1950         333 :     sWriteFuncHeaderData.nEndOffset =
    1951         333 :         startOffset +
    1952         333 :         static_cast<vsi_l_offset>(nBlocks) * VSICURLGetDownloadChunkSize() - 1;
    1953             :     // Some servers don't like we try to read after end-of-file (#5786).
    1954         333 :     if (oFileProp.bHasComputedFileSize &&
    1955         244 :         sWriteFuncHeaderData.nEndOffset >= oFileProp.fileSize)
    1956             :     {
    1957         118 :         sWriteFuncHeaderData.nEndOffset = oFileProp.fileSize - 1;
    1958             :     }
    1959             : 
    1960         333 :     char rangeStr[512] = {};
    1961         333 :     snprintf(rangeStr, sizeof(rangeStr), CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    1962             :              startOffset, sWriteFuncHeaderData.nEndOffset);
    1963             : 
    1964             :     if (ENABLE_DEBUG)
    1965         333 :         CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...", rangeStr,
    1966             :                  osURL.c_str());
    1967             : 
    1968         333 :     std::string osHeaderRange;  // leave in this scope
    1969         333 :     if (sWriteFuncHeaderData.bIsHTTP)
    1970             :     {
    1971         333 :         osHeaderRange = CPLSPrintf("Range: bytes=%s", rangeStr);
    1972             :         // So it gets included in Azure signature
    1973         333 :         headers = curl_slist_append(headers, osHeaderRange.c_str());
    1974         333 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
    1975             :     }
    1976             :     else
    1977           0 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, rangeStr);
    1978             : 
    1979         333 :     char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
    1980         333 :     szCurlErrBuf[0] = '\0';
    1981         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
    1982             : 
    1983         333 :     headers = GetCurlHeaders("GET", headers);
    1984         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    1985             : 
    1986         333 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FILETIME, 1);
    1987             : 
    1988         333 :     VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle, &m_bInterrupt);
    1989             : 
    1990         333 :     VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
    1991             : 
    1992         333 :     curl_slist_free_all(headers);
    1993             : 
    1994         333 :     NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
    1995             : 
    1996         333 :     if (sWriteFuncData.bInterrupted || m_bInterrupt)
    1997             :     {
    1998           0 :         bInterrupted = true;
    1999             : 
    2000             :         // Notify that the download of the current region is finished
    2001           0 :         currentDownload.SetData(std::string());
    2002             : 
    2003           0 :         CPLFree(sWriteFuncData.pBuffer);
    2004           0 :         CPLFree(sWriteFuncHeaderData.pBuffer);
    2005           0 :         curl_easy_cleanup(hCurlHandle);
    2006             : 
    2007           0 :         return std::string();
    2008             :     }
    2009             : 
    2010         333 :     long response_code = 0;
    2011         333 :     curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
    2012             : 
    2013         333 :     if (ENABLE_DEBUG && szCurlErrBuf[0] != '\0')
    2014             :     {
    2015           3 :         CPLDebug(poFS->GetDebugKey(),
    2016             :                  "DownloadRegion(%s): response_code=%d, msg=%s", osURL.c_str(),
    2017             :                  static_cast<int>(response_code), szCurlErrBuf);
    2018             :     }
    2019             : 
    2020         333 :     long mtime = 0;
    2021         333 :     curl_easy_getinfo(hCurlHandle, CURLINFO_FILETIME, &mtime);
    2022         333 :     if (mtime > 0)
    2023             :     {
    2024          53 :         oFileProp.mTime = mtime;
    2025          53 :         poFS->SetCachedFileProp(m_pszURL, oFileProp);
    2026             :     }
    2027             : 
    2028             :     if (ENABLE_DEBUG)
    2029         333 :         CPLDebug(poFS->GetDebugKey(), "Got response_code=%ld", response_code);
    2030             : 
    2031         352 :     if (bUsedRedirect &&
    2032          19 :         (response_code == 403 ||
    2033             :          // Below case is in particular for
    2034             :          // gdalinfo
    2035             :          // /vsicurl/https://lpdaac.earthdata.nasa.gov/lp-prod-protected/HLSS30.015/HLS.S30.T10TEK.2020273T190109.v1.5.B8A.tif
    2036             :          // --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR --config
    2037             :          // GDAL_HTTP_COOKIEFILE /tmp/cookie.txt --config GDAL_HTTP_COOKIEJAR
    2038             :          // /tmp/cookie.txt We got the redirect URL from a HEAD request, but it
    2039             :          // is not valid for a GET. So retry with GET on original URL to get a
    2040             :          // redirect URL valid for it.
    2041          17 :          (response_code == 400 &&
    2042           0 :           osURL.find(".cloudfront.net") != std::string::npos)))
    2043             :     {
    2044           2 :         CPLDebug(poFS->GetDebugKey(),
    2045             :                  "Got an error with redirect URL. Retrying with original one");
    2046           2 :         oFileProp.bS3LikeRedirect = false;
    2047           2 :         poFS->SetCachedFileProp(m_pszURL, oFileProp);
    2048           2 :         bUsedRedirect = false;
    2049           2 :         osURL = m_pszURL;
    2050           2 :         CPLFree(sWriteFuncData.pBuffer);
    2051           2 :         CPLFree(sWriteFuncHeaderData.pBuffer);
    2052           2 :         curl_easy_cleanup(hCurlHandle);
    2053           2 :         goto retry;
    2054             :     }
    2055             : 
    2056         331 :     if (response_code == 401 && oRetryContext.CanRetry())
    2057             :     {
    2058           0 :         CPLDebug(poFS->GetDebugKey(), "Unauthorized, trying to authenticate");
    2059           0 :         CPLFree(sWriteFuncData.pBuffer);
    2060           0 :         CPLFree(sWriteFuncHeaderData.pBuffer);
    2061           0 :         curl_easy_cleanup(hCurlHandle);
    2062           0 :         if (Authenticate(m_osFilename.c_str()))
    2063           0 :             goto retry;
    2064           0 :         return std::string();
    2065             :     }
    2066             : 
    2067         331 :     UpdateRedirectInfo(hCurlHandle, sWriteFuncHeaderData);
    2068             : 
    2069         331 :     if ((response_code != 200 && response_code != 206 && response_code != 225 &&
    2070          22 :          response_code != 226 && response_code != 426) ||
    2071         309 :         sWriteFuncHeaderData.bError)
    2072             :     {
    2073          31 :         if (sWriteFuncData.pBuffer != nullptr &&
    2074           9 :             CanRestartOnError(
    2075           9 :                 reinterpret_cast<const char *>(sWriteFuncData.pBuffer),
    2076           9 :                 reinterpret_cast<const char *>(sWriteFuncHeaderData.pBuffer),
    2077           9 :                 true))
    2078             :         {
    2079           9 :             CPLFree(sWriteFuncData.pBuffer);
    2080           9 :             CPLFree(sWriteFuncHeaderData.pBuffer);
    2081           9 :             curl_easy_cleanup(hCurlHandle);
    2082           9 :             goto begin;
    2083             :         }
    2084             : 
    2085             :         // Look if we should attempt a retry
    2086          13 :         if (oRetryContext.CanRetry(static_cast<int>(response_code),
    2087          13 :                                    sWriteFuncHeaderData.pBuffer, szCurlErrBuf))
    2088             :         {
    2089           8 :             CPLError(CE_Warning, CPLE_AppDefined,
    2090             :                      "HTTP error code: %d - %s. "
    2091             :                      "Retrying again in %.1f secs",
    2092             :                      static_cast<int>(response_code), m_pszURL,
    2093             :                      oRetryContext.GetCurrentDelay());
    2094           8 :             CPLSleep(oRetryContext.GetCurrentDelay());
    2095           8 :             CPLFree(sWriteFuncData.pBuffer);
    2096           8 :             CPLFree(sWriteFuncHeaderData.pBuffer);
    2097           8 :             curl_easy_cleanup(hCurlHandle);
    2098           8 :             goto retry;
    2099             :         }
    2100             : 
    2101           5 :         if (response_code >= 400 && szCurlErrBuf[0] != '\0')
    2102             :         {
    2103           0 :             if (strcmp(szCurlErrBuf, "Couldn't use REST") == 0)
    2104           0 :                 CPLError(
    2105             :                     CE_Failure, CPLE_AppDefined,
    2106             :                     "%d: %s, Range downloading not supported by this server!",
    2107             :                     static_cast<int>(response_code), szCurlErrBuf);
    2108             :             else
    2109           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "%d: %s",
    2110             :                          static_cast<int>(response_code), szCurlErrBuf);
    2111             :         }
    2112           5 :         else if (response_code == 416) /* Range Not Satisfiable */
    2113             :         {
    2114           0 :             if (sWriteFuncData.pBuffer)
    2115             :             {
    2116           0 :                 CPLError(
    2117             :                     CE_Failure, CPLE_AppDefined,
    2118             :                     "%d: Range downloading not supported by this server: %s",
    2119             :                     static_cast<int>(response_code), sWriteFuncData.pBuffer);
    2120             :             }
    2121             :             else
    2122             :             {
    2123           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2124             :                          "%d: Range downloading not supported by this server",
    2125             :                          static_cast<int>(response_code));
    2126             :             }
    2127             :         }
    2128           5 :         if (!oFileProp.bHasComputedFileSize && startOffset == 0)
    2129             :         {
    2130           1 :             oFileProp.bHasComputedFileSize = true;
    2131           1 :             oFileProp.fileSize = 0;
    2132           1 :             oFileProp.eExists = EXIST_NO;
    2133           1 :             poFS->SetCachedFileProp(m_pszURL, oFileProp);
    2134             :         }
    2135           5 :         CPLFree(sWriteFuncData.pBuffer);
    2136           5 :         CPLFree(sWriteFuncHeaderData.pBuffer);
    2137           5 :         curl_easy_cleanup(hCurlHandle);
    2138           5 :         return std::string();
    2139             :     }
    2140             : 
    2141         309 :     if (!oFileProp.bHasComputedFileSize && sWriteFuncHeaderData.pBuffer)
    2142             :     {
    2143             :         // Try to retrieve the filesize from the HTTP headers
    2144             :         // if in the form: "Content-Range: bytes x-y/filesize".
    2145             :         char *pszContentRange =
    2146          79 :             strstr(sWriteFuncHeaderData.pBuffer, "Content-Range: bytes ");
    2147          79 :         if (pszContentRange == nullptr)
    2148             :             pszContentRange =
    2149          75 :                 strstr(sWriteFuncHeaderData.pBuffer, "content-range: bytes ");
    2150          79 :         if (pszContentRange)
    2151             :         {
    2152           5 :             char *pszEOL = strchr(pszContentRange, '\n');
    2153           5 :             if (pszEOL)
    2154             :             {
    2155           5 :                 *pszEOL = 0;
    2156           5 :                 pszEOL = strchr(pszContentRange, '\r');
    2157           5 :                 if (pszEOL)
    2158           5 :                     *pszEOL = 0;
    2159           5 :                 char *pszSlash = strchr(pszContentRange, '/');
    2160           5 :                 if (pszSlash)
    2161             :                 {
    2162           5 :                     pszSlash++;
    2163           5 :                     oFileProp.fileSize = CPLScanUIntBig(
    2164           5 :                         pszSlash, static_cast<int>(strlen(pszSlash)));
    2165             :                 }
    2166             :             }
    2167             :         }
    2168          74 :         else if (STARTS_WITH(m_pszURL, "ftp"))
    2169             :         {
    2170             :             // Parse 213 answer for FTP protocol.
    2171           0 :             char *pszSize = strstr(sWriteFuncHeaderData.pBuffer, "213 ");
    2172           0 :             if (pszSize)
    2173             :             {
    2174           0 :                 pszSize += 4;
    2175           0 :                 char *pszEOL = strchr(pszSize, '\n');
    2176           0 :                 if (pszEOL)
    2177             :                 {
    2178           0 :                     *pszEOL = 0;
    2179           0 :                     pszEOL = strchr(pszSize, '\r');
    2180           0 :                     if (pszEOL)
    2181           0 :                         *pszEOL = 0;
    2182             : 
    2183           0 :                     oFileProp.fileSize = CPLScanUIntBig(
    2184           0 :                         pszSize, static_cast<int>(strlen(pszSize)));
    2185             :                 }
    2186             :             }
    2187             :         }
    2188             : 
    2189          79 :         if (oFileProp.fileSize != 0)
    2190             :         {
    2191           5 :             oFileProp.eExists = EXIST_YES;
    2192             : 
    2193             :             if (ENABLE_DEBUG)
    2194           5 :                 CPLDebug(poFS->GetDebugKey(),
    2195             :                          "GetFileSize(%s)=" CPL_FRMT_GUIB "  response_code=%d",
    2196             :                          m_pszURL, oFileProp.fileSize,
    2197             :                          static_cast<int>(response_code));
    2198             : 
    2199           5 :             oFileProp.bHasComputedFileSize = true;
    2200           5 :             poFS->SetCachedFileProp(m_pszURL, oFileProp);
    2201             :         }
    2202             :     }
    2203             : 
    2204         309 :     DownloadRegionPostProcess(startOffset, nBlocks, sWriteFuncData.pBuffer,
    2205             :                               sWriteFuncData.nSize);
    2206             : 
    2207         618 :     std::string osRet;
    2208         309 :     osRet.assign(sWriteFuncData.pBuffer, sWriteFuncData.nSize);
    2209             : 
    2210             :     // Notify that the download of the current region is finished
    2211         309 :     currentDownload.SetData(osRet);
    2212             : 
    2213         309 :     CPLFree(sWriteFuncData.pBuffer);
    2214         309 :     CPLFree(sWriteFuncHeaderData.pBuffer);
    2215         309 :     curl_easy_cleanup(hCurlHandle);
    2216             : 
    2217         309 :     return osRet;
    2218             : }
    2219             : 
    2220             : /************************************************************************/
    2221             : /*                      UpdateRedirectInfo()                            */
    2222             : /************************************************************************/
    2223             : 
    2224         395 : void VSICurlHandle::UpdateRedirectInfo(
    2225             :     CURL *hCurlHandle, const WriteFuncStruct &sWriteFuncHeaderData)
    2226             : {
    2227         790 :     std::string osEffectiveURL;
    2228             :     {
    2229         395 :         char *pszEffectiveURL = nullptr;
    2230         395 :         curl_easy_getinfo(hCurlHandle, CURLINFO_EFFECTIVE_URL,
    2231             :                           &pszEffectiveURL);
    2232         395 :         if (pszEffectiveURL)
    2233         395 :             osEffectiveURL = pszEffectiveURL;
    2234             :     }
    2235             : 
    2236         788 :     if (!oFileProp.bS3LikeRedirect && !osEffectiveURL.empty() &&
    2237         393 :         strstr(osEffectiveURL.c_str(), m_pszURL) == nullptr)
    2238             :     {
    2239          97 :         CPLDebug(poFS->GetDebugKey(), "Effective URL: %s",
    2240             :                  osEffectiveURL.c_str());
    2241             : 
    2242          97 :         long response_code = 0;
    2243          97 :         curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
    2244          97 :         if (response_code >= 200 && response_code < 300 &&
    2245         194 :             sWriteFuncHeaderData.nTimestampDate > 0 &&
    2246          97 :             VSICurlIsS3LikeSignedURL(osEffectiveURL.c_str()) &&
    2247         196 :             !VSICurlIsS3LikeSignedURL(m_pszURL) &&
    2248           2 :             CPLTestBool(
    2249             :                 CPLGetConfigOption("CPL_VSIL_CURL_USE_S3_REDIRECT", "TRUE")))
    2250             :         {
    2251             :             GIntBig nExpireTimestamp =
    2252           2 :                 VSICurlGetExpiresFromS3LikeSignedURL(osEffectiveURL.c_str());
    2253           2 :             if (nExpireTimestamp > sWriteFuncHeaderData.nTimestampDate + 10)
    2254             :             {
    2255           2 :                 const int nValidity = static_cast<int>(
    2256           2 :                     nExpireTimestamp - sWriteFuncHeaderData.nTimestampDate);
    2257           2 :                 CPLDebug(poFS->GetDebugKey(),
    2258             :                          "Will use redirect URL for the next %d seconds",
    2259             :                          nValidity);
    2260             :                 // As our local clock might not be in sync with server clock,
    2261             :                 // figure out the expiration timestamp in local time.
    2262           2 :                 oFileProp.bS3LikeRedirect = true;
    2263           2 :                 oFileProp.nExpireTimestampLocal = time(nullptr) + nValidity;
    2264           2 :                 oFileProp.osRedirectURL = std::move(osEffectiveURL);
    2265           2 :                 poFS->SetCachedFileProp(m_pszURL, oFileProp);
    2266             :             }
    2267             :         }
    2268             :     }
    2269         395 : }
    2270             : 
    2271             : /************************************************************************/
    2272             : /*                      DownloadRegionPostProcess()                     */
    2273             : /************************************************************************/
    2274             : 
    2275         311 : void VSICurlHandle::DownloadRegionPostProcess(const vsi_l_offset startOffset,
    2276             :                                               const int nBlocks,
    2277             :                                               const char *pBuffer, size_t nSize)
    2278             : {
    2279         311 :     const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
    2280         311 :     lastDownloadedOffset = startOffset + static_cast<vsi_l_offset>(nBlocks) *
    2281         311 :                                              knDOWNLOAD_CHUNK_SIZE;
    2282             : 
    2283         311 :     if (nSize > static_cast<size_t>(nBlocks) * knDOWNLOAD_CHUNK_SIZE)
    2284             :     {
    2285             :         if (ENABLE_DEBUG)
    2286           1 :             CPLDebug(
    2287           1 :                 poFS->GetDebugKey(),
    2288             :                 "Got more data than expected : %u instead of %u",
    2289             :                 static_cast<unsigned int>(nSize),
    2290           1 :                 static_cast<unsigned int>(nBlocks * knDOWNLOAD_CHUNK_SIZE));
    2291             :     }
    2292             : 
    2293         311 :     vsi_l_offset l_startOffset = startOffset;
    2294         895 :     while (nSize > 0)
    2295             :     {
    2296             : #if DEBUG_VERBOSE
    2297             :         if (ENABLE_DEBUG)
    2298             :             CPLDebug(poFS->GetDebugKey(), "Add region %u - %u",
    2299             :                      static_cast<unsigned int>(startOffset),
    2300             :                      static_cast<unsigned int>(std::min(
    2301             :                          static_cast<size_t>(knDOWNLOAD_CHUNK_SIZE), nSize)));
    2302             : #endif
    2303             :         const size_t nChunkSize =
    2304         584 :             std::min(static_cast<size_t>(knDOWNLOAD_CHUNK_SIZE), nSize);
    2305         584 :         poFS->AddRegion(m_pszURL, l_startOffset, nChunkSize, pBuffer);
    2306         584 :         l_startOffset += nChunkSize;
    2307         584 :         pBuffer += nChunkSize;
    2308         584 :         nSize -= nChunkSize;
    2309             :     }
    2310         311 : }
    2311             : 
    2312             : /************************************************************************/
    2313             : /*                                Read()                                */
    2314             : /************************************************************************/
    2315             : 
    2316       45319 : size_t VSICurlHandle::Read(void *const pBufferIn, size_t const nSize,
    2317             :                            size_t const nMemb)
    2318             : {
    2319       90638 :     NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
    2320       90638 :     NetworkStatisticsFile oContextFile(m_osFilename.c_str());
    2321       90638 :     NetworkStatisticsAction oContextAction("Read");
    2322             : 
    2323       45319 :     size_t nBufferRequestSize = nSize * nMemb;
    2324       45319 :     if (nBufferRequestSize == 0)
    2325           1 :         return 0;
    2326             : 
    2327       45318 :     void *pBuffer = pBufferIn;
    2328             : 
    2329             : #if DEBUG_VERBOSE
    2330             :     CPLDebug(poFS->GetDebugKey(), "offset=%d, size=%d",
    2331             :              static_cast<int>(curOffset), static_cast<int>(nBufferRequestSize));
    2332             : #endif
    2333             : 
    2334       45318 :     vsi_l_offset iterOffset = curOffset;
    2335       45318 :     const int knMAX_REGIONS = GetMaxRegions();
    2336       45318 :     const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
    2337       91194 :     while (nBufferRequestSize)
    2338             :     {
    2339             :         // Don't try to read after end of file.
    2340       46000 :         poFS->GetCachedFileProp(m_pszURL, oFileProp);
    2341       46000 :         if (oFileProp.bHasComputedFileSize && iterOffset >= oFileProp.fileSize)
    2342             :         {
    2343           2 :             if (iterOffset == curOffset)
    2344             :             {
    2345           2 :                 CPLDebug(poFS->GetDebugKey(),
    2346             :                          "Request at offset " CPL_FRMT_GUIB
    2347             :                          ", after end of file",
    2348             :                          iterOffset);
    2349             :             }
    2350         118 :             break;
    2351             :         }
    2352             : 
    2353       45998 :         const vsi_l_offset nOffsetToDownload =
    2354       45998 :             (iterOffset / knDOWNLOAD_CHUNK_SIZE) * knDOWNLOAD_CHUNK_SIZE;
    2355       45998 :         std::string osRegion;
    2356             :         std::shared_ptr<std::string> psRegion =
    2357       45998 :             poFS->GetRegion(m_pszURL, nOffsetToDownload);
    2358       45998 :         if (psRegion != nullptr)
    2359             :         {
    2360       45679 :             osRegion = *psRegion;
    2361             :         }
    2362             :         else
    2363             :         {
    2364         319 :             if (nOffsetToDownload == lastDownloadedOffset)
    2365             :             {
    2366             :                 // In case of consecutive reads (of small size), we use a
    2367             :                 // heuristic that we will read the file sequentially, so
    2368             :                 // we double the requested size to decrease the number of
    2369             :                 // client/server roundtrips.
    2370          17 :                 constexpr int MAX_CHUNK_SIZE_INCREASE_FACTOR = 128;
    2371          17 :                 if (nBlocksToDownload < MAX_CHUNK_SIZE_INCREASE_FACTOR)
    2372          17 :                     nBlocksToDownload *= 2;
    2373             :             }
    2374             :             else
    2375             :             {
    2376             :                 // Random reads. Cancel the above heuristics.
    2377         302 :                 nBlocksToDownload = 1;
    2378             :             }
    2379             : 
    2380             :             // Ensure that we will request at least the number of blocks
    2381             :             // to satisfy the remaining buffer size to read.
    2382         319 :             const vsi_l_offset nEndOffsetToDownload =
    2383         319 :                 ((iterOffset + nBufferRequestSize + knDOWNLOAD_CHUNK_SIZE - 1) /
    2384         319 :                  knDOWNLOAD_CHUNK_SIZE) *
    2385         319 :                 knDOWNLOAD_CHUNK_SIZE;
    2386         319 :             const int nMinBlocksToDownload =
    2387         319 :                 static_cast<int>((nEndOffsetToDownload - nOffsetToDownload) /
    2388         319 :                                  knDOWNLOAD_CHUNK_SIZE);
    2389         319 :             if (nBlocksToDownload < nMinBlocksToDownload)
    2390          72 :                 nBlocksToDownload = nMinBlocksToDownload;
    2391             : 
    2392             :             // Avoid reading already cached data.
    2393             :             // Note: this might get evicted if concurrent reads are done, but
    2394             :             // this should not cause bugs. Just missed optimization.
    2395         602 :             for (int i = 1; i < nBlocksToDownload; i++)
    2396             :             {
    2397         328 :                 if (poFS->GetRegion(m_pszURL, nOffsetToDownload +
    2398         328 :                                                   static_cast<vsi_l_offset>(i) *
    2399         328 :                                                       knDOWNLOAD_CHUNK_SIZE) !=
    2400             :                     nullptr)
    2401             :                 {
    2402          45 :                     nBlocksToDownload = i;
    2403          45 :                     break;
    2404             :                 }
    2405             :             }
    2406             : 
    2407             :             // We can't download more than knMAX_REGIONS chunks at a time,
    2408             :             // otherwise the cache will not be big enough to store them and
    2409             :             // copy their content to the target buffer.
    2410         319 :             if (nBlocksToDownload > knMAX_REGIONS)
    2411           0 :                 nBlocksToDownload = knMAX_REGIONS;
    2412             : 
    2413         319 :             osRegion = DownloadRegion(nOffsetToDownload, nBlocksToDownload);
    2414         319 :             if (osRegion.empty())
    2415             :             {
    2416           6 :                 if (!bInterrupted)
    2417           6 :                     bError = true;
    2418           6 :                 return 0;
    2419             :             }
    2420             :         }
    2421             : 
    2422       45992 :         const vsi_l_offset nRegionOffset = iterOffset - nOffsetToDownload;
    2423       45992 :         if (osRegion.size() < nRegionOffset)
    2424             :         {
    2425           0 :             if (iterOffset == curOffset)
    2426             :             {
    2427           0 :                 CPLDebug(poFS->GetDebugKey(),
    2428             :                          "Request at offset " CPL_FRMT_GUIB
    2429             :                          ", after end of file",
    2430             :                          iterOffset);
    2431             :             }
    2432           0 :             break;
    2433             :         }
    2434             : 
    2435             :         const int nToCopy = static_cast<int>(
    2436       91984 :             std::min(static_cast<vsi_l_offset>(nBufferRequestSize),
    2437       45992 :                      osRegion.size() - nRegionOffset));
    2438       45992 :         memcpy(pBuffer, osRegion.data() + nRegionOffset, nToCopy);
    2439       45992 :         pBuffer = static_cast<char *>(pBuffer) + nToCopy;
    2440       45992 :         iterOffset += nToCopy;
    2441       45992 :         nBufferRequestSize -= nToCopy;
    2442       45992 :         if (osRegion.size() < static_cast<size_t>(knDOWNLOAD_CHUNK_SIZE) &&
    2443             :             nBufferRequestSize != 0)
    2444             :         {
    2445         116 :             break;
    2446             :         }
    2447             :     }
    2448             : 
    2449       45312 :     const size_t ret = static_cast<size_t>((iterOffset - curOffset) / nSize);
    2450       45312 :     if (ret != nMemb)
    2451         118 :         bEOF = true;
    2452             : 
    2453       45312 :     curOffset = iterOffset;
    2454             : 
    2455       45312 :     return ret;
    2456             : }
    2457             : 
    2458             : /************************************************************************/
    2459             : /*                           ReadMultiRange()                           */
    2460             : /************************************************************************/
    2461             : 
    2462          10 : int VSICurlHandle::ReadMultiRange(int const nRanges, void **const ppData,
    2463             :                                   const vsi_l_offset *const panOffsets,
    2464             :                                   const size_t *const panSizes)
    2465             : {
    2466          10 :     if (bInterrupted && bStopOnInterruptUntilUninstall)
    2467           0 :         return FALSE;
    2468             : 
    2469          10 :     poFS->GetCachedFileProp(m_pszURL, oFileProp);
    2470          10 :     if (oFileProp.eExists == EXIST_NO)
    2471           0 :         return -1;
    2472             : 
    2473          20 :     NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
    2474          20 :     NetworkStatisticsFile oContextFile(m_osFilename.c_str());
    2475          20 :     NetworkStatisticsAction oContextAction("ReadMultiRange");
    2476             : 
    2477             :     const char *pszMultiRangeStrategy =
    2478          10 :         CPLGetConfigOption("GDAL_HTTP_MULTIRANGE", "");
    2479          10 :     if (EQUAL(pszMultiRangeStrategy, "SINGLE_GET"))
    2480             :     {
    2481             :         // Just in case someone needs it, but the interest of this mode is
    2482             :         // rather dubious now. We could probably remove it
    2483           0 :         return ReadMultiRangeSingleGet(nRanges, ppData, panOffsets, panSizes);
    2484             :     }
    2485          10 :     else if (nRanges == 1 || EQUAL(pszMultiRangeStrategy, "SERIAL"))
    2486             :     {
    2487           9 :         return VSIVirtualHandle::ReadMultiRange(nRanges, ppData, panOffsets,
    2488           9 :                                                 panSizes);
    2489             :     }
    2490             : 
    2491           1 :     UpdateQueryString();
    2492             : 
    2493           1 :     bool bHasExpired = false;
    2494             : 
    2495           2 :     CPLStringList aosHTTPOptions(m_aosHTTPOptions);
    2496           2 :     std::string osURL(GetRedirectURLIfValid(bHasExpired, aosHTTPOptions));
    2497           1 :     if (bHasExpired)
    2498             :     {
    2499           0 :         return VSIVirtualHandle::ReadMultiRange(nRanges, ppData, panOffsets,
    2500           0 :                                                 panSizes);
    2501             :     }
    2502             : 
    2503           1 :     CURLM *hMultiHandle = poFS->GetCurlMultiHandleFor(osURL);
    2504             : #ifdef CURLPIPE_MULTIPLEX
    2505             :     // Enable HTTP/2 multiplexing (ignored if an older version of HTTP is
    2506             :     // used)
    2507             :     // Not that this does not enable HTTP/1.1 pipeling, which is not
    2508             :     // recommended for example by Google Cloud Storage.
    2509             :     // For HTTP/1.1, parallel connections work better since you can get
    2510             :     // results out of order.
    2511           1 :     if (CPLTestBool(CPLGetConfigOption("GDAL_HTTP_MULTIPLEX", "YES")))
    2512             :     {
    2513           1 :         curl_multi_setopt(hMultiHandle, CURLMOPT_PIPELINING,
    2514             :                           CURLPIPE_MULTIPLEX);
    2515             :     }
    2516             : #endif
    2517             : 
    2518           2 :     std::vector<CURL *> aHandles;
    2519           2 :     std::vector<WriteFuncStruct> asWriteFuncData(nRanges);
    2520           2 :     std::vector<WriteFuncStruct> asWriteFuncHeaderData(nRanges);
    2521           2 :     std::vector<char *> apszRanges;
    2522           2 :     std::vector<struct curl_slist *> aHeaders;
    2523             : 
    2524             :     struct CurlErrBuffer
    2525             :     {
    2526             :         std::array<char, CURL_ERROR_SIZE + 1> szCurlErrBuf;
    2527             :     };
    2528             : 
    2529           1 :     std::vector<CurlErrBuffer> asCurlErrors(nRanges);
    2530             : 
    2531           1 :     const bool bMergeConsecutiveRanges = CPLTestBool(
    2532             :         CPLGetConfigOption("GDAL_HTTP_MERGE_CONSECUTIVE_RANGES", "TRUE"));
    2533             : 
    2534           5 :     for (int i = 0, iRequest = 0; i < nRanges;)
    2535             :     {
    2536           4 :         size_t nSize = 0;
    2537           4 :         int iNext = i;
    2538             :         // Identify consecutive ranges
    2539           4 :         while (bMergeConsecutiveRanges && iNext + 1 < nRanges &&
    2540           3 :                panOffsets[iNext] + panSizes[iNext] == panOffsets[iNext + 1])
    2541             :         {
    2542           0 :             nSize += panSizes[iNext];
    2543           0 :             iNext++;
    2544             :         }
    2545           4 :         nSize += panSizes[iNext];
    2546             : 
    2547           4 :         if (nSize == 0)
    2548             :         {
    2549           0 :             i = iNext + 1;
    2550           0 :             continue;
    2551             :         }
    2552             : 
    2553           4 :         CURL *hCurlHandle = curl_easy_init();
    2554           4 :         aHandles.push_back(hCurlHandle);
    2555             : 
    2556             :         // As the multi-range request is likely not the first one, we don't
    2557             :         // need to wait as we already know if pipelining is possible
    2558             :         // unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_PIPEWAIT, 1);
    2559             : 
    2560           4 :         struct curl_slist *headers = VSICurlSetOptions(
    2561           4 :             hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
    2562             : 
    2563           4 :         VSICURLInitWriteFuncStruct(&asWriteFuncData[iRequest], this, pfnReadCbk,
    2564             :                                    pReadCbkUserData);
    2565           4 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
    2566             :                                    &asWriteFuncData[iRequest]);
    2567           4 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    2568             :                                    VSICurlHandleWriteFunc);
    2569             : 
    2570           4 :         VSICURLInitWriteFuncStruct(&asWriteFuncHeaderData[iRequest], nullptr,
    2571             :                                    nullptr, nullptr);
    2572           4 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    2573             :                                    &asWriteFuncHeaderData[iRequest]);
    2574           4 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    2575             :                                    VSICurlHandleWriteFunc);
    2576           4 :         asWriteFuncHeaderData[iRequest].bIsHTTP = STARTS_WITH(m_pszURL, "http");
    2577           4 :         asWriteFuncHeaderData[iRequest].nStartOffset = panOffsets[i];
    2578             : 
    2579           4 :         asWriteFuncHeaderData[iRequest].nEndOffset = panOffsets[i] + nSize - 1;
    2580             : 
    2581           4 :         char rangeStr[512] = {};
    2582           8 :         snprintf(rangeStr, sizeof(rangeStr), CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    2583           4 :                  asWriteFuncHeaderData[iRequest].nStartOffset,
    2584           4 :                  asWriteFuncHeaderData[iRequest].nEndOffset);
    2585             : 
    2586             :         if (ENABLE_DEBUG)
    2587           4 :             CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...", rangeStr,
    2588             :                      osURL.c_str());
    2589             : 
    2590           4 :         if (asWriteFuncHeaderData[iRequest].bIsHTTP)
    2591             :         {
    2592             :             // So it gets included in Azure signature
    2593           4 :             char *pszRange = CPLStrdup(CPLSPrintf("Range: bytes=%s", rangeStr));
    2594           4 :             apszRanges.push_back(pszRange);
    2595           4 :             headers = curl_slist_append(headers, pszRange);
    2596           4 :             unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
    2597             :         }
    2598             :         else
    2599             :         {
    2600           0 :             apszRanges.push_back(nullptr);
    2601           0 :             unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, rangeStr);
    2602             :         }
    2603             : 
    2604           4 :         asCurlErrors[iRequest].szCurlErrBuf[0] = '\0';
    2605           4 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
    2606             :                                    &asCurlErrors[iRequest].szCurlErrBuf[0]);
    2607             : 
    2608           4 :         headers = GetCurlHeaders("GET", headers);
    2609           4 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    2610           4 :         aHeaders.push_back(headers);
    2611           4 :         curl_multi_add_handle(hMultiHandle, hCurlHandle);
    2612             : 
    2613           4 :         i = iNext + 1;
    2614           4 :         iRequest++;
    2615             :     }
    2616             : 
    2617           1 :     if (!aHandles.empty())
    2618             :     {
    2619           1 :         VSICURLMultiPerform(hMultiHandle);
    2620             :     }
    2621             : 
    2622           1 :     int nRet = 0;
    2623           1 :     size_t iReq = 0;
    2624           1 :     int iRange = 0;
    2625           1 :     size_t nTotalDownloaded = 0;
    2626           5 :     for (; iReq < aHandles.size(); iReq++, iRange++)
    2627             :     {
    2628           4 :         while (iRange < nRanges && panSizes[iRange] == 0)
    2629             :         {
    2630           0 :             iRange++;
    2631             :         }
    2632           4 :         if (iRange == nRanges)
    2633           0 :             break;
    2634             : 
    2635           4 :         long response_code = 0;
    2636           4 :         curl_easy_getinfo(aHandles[iReq], CURLINFO_HTTP_CODE, &response_code);
    2637             : 
    2638           4 :         if (ENABLE_DEBUG && asCurlErrors[iRange].szCurlErrBuf[0] != '\0')
    2639             :         {
    2640           0 :             char rangeStr[512] = {};
    2641           0 :             snprintf(rangeStr, sizeof(rangeStr),
    2642             :                      CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    2643           0 :                      asWriteFuncHeaderData[iReq].nStartOffset,
    2644           0 :                      asWriteFuncHeaderData[iReq].nEndOffset);
    2645             : 
    2646           0 :             const char *pszErrorMsg = &asCurlErrors[iRange].szCurlErrBuf[0];
    2647           0 :             CPLDebug(poFS->GetDebugKey(),
    2648             :                      "ReadMultiRange(%s), %s: response_code=%d, msg=%s",
    2649             :                      osURL.c_str(), rangeStr, static_cast<int>(response_code),
    2650             :                      pszErrorMsg);
    2651             :         }
    2652             : 
    2653           8 :         if ((response_code != 206 && response_code != 225) ||
    2654           4 :             asWriteFuncHeaderData[iReq].nEndOffset + 1 !=
    2655           4 :                 asWriteFuncHeaderData[iReq].nStartOffset +
    2656           4 :                     asWriteFuncData[iReq].nSize)
    2657             :         {
    2658           0 :             char rangeStr[512] = {};
    2659           0 :             snprintf(rangeStr, sizeof(rangeStr),
    2660             :                      CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    2661           0 :                      asWriteFuncHeaderData[iReq].nStartOffset,
    2662           0 :                      asWriteFuncHeaderData[iReq].nEndOffset);
    2663             : 
    2664           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2665             :                      "Request for %s failed with response_code=%ld", rangeStr,
    2666             :                      response_code);
    2667           0 :             nRet = -1;
    2668             :         }
    2669           4 :         else if (nRet == 0)
    2670             :         {
    2671           4 :             size_t nOffset = 0;
    2672           4 :             size_t nRemainingSize = asWriteFuncData[iReq].nSize;
    2673           4 :             nTotalDownloaded += nRemainingSize;
    2674           4 :             CPLAssert(iRange < nRanges);
    2675             :             while (true)
    2676             :             {
    2677           4 :                 if (nRemainingSize < panSizes[iRange])
    2678             :                 {
    2679           0 :                     nRet = -1;
    2680           0 :                     break;
    2681             :                 }
    2682             : 
    2683           4 :                 if (panSizes[iRange] > 0)
    2684             :                 {
    2685           8 :                     memcpy(ppData[iRange],
    2686           4 :                            asWriteFuncData[iReq].pBuffer + nOffset,
    2687           4 :                            panSizes[iRange]);
    2688             :                 }
    2689             : 
    2690           4 :                 if (bMergeConsecutiveRanges && iRange + 1 < nRanges &&
    2691           3 :                     panOffsets[iRange] + panSizes[iRange] ==
    2692           3 :                         panOffsets[iRange + 1])
    2693             :                 {
    2694           0 :                     nOffset += panSizes[iRange];
    2695           0 :                     nRemainingSize -= panSizes[iRange];
    2696           0 :                     iRange++;
    2697             :                 }
    2698             :                 else
    2699             :                 {
    2700             :                     break;
    2701             :                 }
    2702             :             }
    2703             :         }
    2704             : 
    2705           4 :         curl_multi_remove_handle(hMultiHandle, aHandles[iReq]);
    2706           4 :         VSICURLResetHeaderAndWriterFunctions(aHandles[iReq]);
    2707           4 :         curl_easy_cleanup(aHandles[iReq]);
    2708           4 :         CPLFree(apszRanges[iReq]);
    2709           4 :         CPLFree(asWriteFuncData[iReq].pBuffer);
    2710           4 :         CPLFree(asWriteFuncHeaderData[iReq].pBuffer);
    2711           4 :         curl_slist_free_all(aHeaders[iReq]);
    2712             :     }
    2713             : 
    2714           1 :     NetworkStatisticsLogger::LogGET(nTotalDownloaded);
    2715             : 
    2716             :     if (ENABLE_DEBUG)
    2717           1 :         CPLDebug(poFS->GetDebugKey(), "Download completed");
    2718             : 
    2719           1 :     return nRet;
    2720             : }
    2721             : 
    2722             : /************************************************************************/
    2723             : /*                       ReadMultiRangeSingleGet()                      */
    2724             : /************************************************************************/
    2725             : 
    2726             : // TODO: the interest of this mode is rather dubious now. We could probably
    2727             : // remove it
    2728           0 : int VSICurlHandle::ReadMultiRangeSingleGet(int const nRanges,
    2729             :                                            void **const ppData,
    2730             :                                            const vsi_l_offset *const panOffsets,
    2731             :                                            const size_t *const panSizes)
    2732             : {
    2733           0 :     std::string osRanges;
    2734           0 :     std::string osFirstRange;
    2735           0 :     std::string osLastRange;
    2736           0 :     int nMergedRanges = 0;
    2737           0 :     vsi_l_offset nTotalReqSize = 0;
    2738           0 :     for (int i = 0; i < nRanges; i++)
    2739             :     {
    2740           0 :         std::string osCurRange;
    2741           0 :         if (i != 0)
    2742           0 :             osRanges.append(",");
    2743           0 :         osCurRange = CPLSPrintf(CPL_FRMT_GUIB "-", panOffsets[i]);
    2744           0 :         while (i + 1 < nRanges &&
    2745           0 :                panOffsets[i] + panSizes[i] == panOffsets[i + 1])
    2746             :         {
    2747           0 :             nTotalReqSize += panSizes[i];
    2748           0 :             i++;
    2749             :         }
    2750           0 :         nTotalReqSize += panSizes[i];
    2751             :         osCurRange.append(
    2752           0 :             CPLSPrintf(CPL_FRMT_GUIB, panOffsets[i] + panSizes[i] - 1));
    2753           0 :         nMergedRanges++;
    2754             : 
    2755           0 :         osRanges += osCurRange;
    2756             : 
    2757           0 :         if (nMergedRanges == 1)
    2758           0 :             osFirstRange = osCurRange;
    2759           0 :         osLastRange = std::move(osCurRange);
    2760             :     }
    2761             : 
    2762             :     const char *pszMaxRanges =
    2763           0 :         CPLGetConfigOption("CPL_VSIL_CURL_MAX_RANGES", "250");
    2764           0 :     int nMaxRanges = atoi(pszMaxRanges);
    2765           0 :     if (nMaxRanges <= 0)
    2766           0 :         nMaxRanges = 250;
    2767           0 :     if (nMergedRanges > nMaxRanges)
    2768             :     {
    2769           0 :         const int nHalf = nRanges / 2;
    2770           0 :         const int nRet = ReadMultiRange(nHalf, ppData, panOffsets, panSizes);
    2771           0 :         if (nRet != 0)
    2772           0 :             return nRet;
    2773           0 :         return ReadMultiRange(nRanges - nHalf, ppData + nHalf,
    2774           0 :                               panOffsets + nHalf, panSizes + nHalf);
    2775             :     }
    2776             : 
    2777           0 :     CURLM *hCurlMultiHandle = poFS->GetCurlMultiHandleFor(m_pszURL);
    2778           0 :     CURL *hCurlHandle = curl_easy_init();
    2779             : 
    2780             :     struct curl_slist *headers =
    2781           0 :         VSICurlSetOptions(hCurlHandle, m_pszURL, m_aosHTTPOptions.List());
    2782             : 
    2783           0 :     WriteFuncStruct sWriteFuncData;
    2784           0 :     WriteFuncStruct sWriteFuncHeaderData;
    2785             : 
    2786           0 :     VSICURLInitWriteFuncStruct(&sWriteFuncData, this, pfnReadCbk,
    2787             :                                pReadCbkUserData);
    2788           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
    2789           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    2790             :                                VSICurlHandleWriteFunc);
    2791             : 
    2792           0 :     VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
    2793             :                                nullptr);
    2794           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    2795             :                                &sWriteFuncHeaderData);
    2796           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    2797             :                                VSICurlHandleWriteFunc);
    2798           0 :     sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(m_pszURL, "http");
    2799           0 :     sWriteFuncHeaderData.bMultiRange = nMergedRanges > 1;
    2800           0 :     if (nMergedRanges == 1)
    2801             :     {
    2802           0 :         sWriteFuncHeaderData.nStartOffset = panOffsets[0];
    2803           0 :         sWriteFuncHeaderData.nEndOffset = panOffsets[0] + nTotalReqSize - 1;
    2804             :     }
    2805             : 
    2806             :     if (ENABLE_DEBUG)
    2807             :     {
    2808           0 :         if (nMergedRanges == 1)
    2809           0 :             CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...",
    2810             :                      osRanges.c_str(), m_pszURL);
    2811             :         else
    2812           0 :             CPLDebug(poFS->GetDebugKey(),
    2813             :                      "Downloading %s, ..., %s (" CPL_FRMT_GUIB " bytes, %s)...",
    2814             :                      osFirstRange.c_str(), osLastRange.c_str(),
    2815             :                      static_cast<GUIntBig>(nTotalReqSize), m_pszURL);
    2816             :     }
    2817             : 
    2818           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, osRanges.c_str());
    2819             : 
    2820           0 :     char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
    2821           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
    2822             : 
    2823           0 :     headers = GetCurlHeaders("GET", headers);
    2824           0 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    2825             : 
    2826           0 :     VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle);
    2827             : 
    2828           0 :     VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
    2829             : 
    2830           0 :     curl_slist_free_all(headers);
    2831             : 
    2832           0 :     NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
    2833             : 
    2834           0 :     if (sWriteFuncData.bInterrupted)
    2835             :     {
    2836           0 :         bInterrupted = true;
    2837             : 
    2838           0 :         CPLFree(sWriteFuncData.pBuffer);
    2839           0 :         CPLFree(sWriteFuncHeaderData.pBuffer);
    2840           0 :         curl_easy_cleanup(hCurlHandle);
    2841             : 
    2842           0 :         return -1;
    2843             :     }
    2844             : 
    2845           0 :     long response_code = 0;
    2846           0 :     curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
    2847             : 
    2848           0 :     if ((response_code != 200 && response_code != 206 && response_code != 225 &&
    2849           0 :          response_code != 226 && response_code != 426) ||
    2850           0 :         sWriteFuncHeaderData.bError)
    2851             :     {
    2852           0 :         if (response_code >= 400 && szCurlErrBuf[0] != '\0')
    2853             :         {
    2854           0 :             if (strcmp(szCurlErrBuf, "Couldn't use REST") == 0)
    2855           0 :                 CPLError(
    2856             :                     CE_Failure, CPLE_AppDefined,
    2857             :                     "%d: %s, Range downloading not supported by this server!",
    2858             :                     static_cast<int>(response_code), szCurlErrBuf);
    2859             :             else
    2860           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "%d: %s",
    2861             :                          static_cast<int>(response_code), szCurlErrBuf);
    2862             :         }
    2863             :         /*
    2864             :         if( !bHasComputedFileSize && startOffset == 0 )
    2865             :         {
    2866             :             cachedFileProp->bHasComputedFileSize = bHasComputedFileSize = true;
    2867             :             cachedFileProp->fileSize = fileSize = 0;
    2868             :             cachedFileProp->eExists = eExists = EXIST_NO;
    2869             :         }
    2870             :         */
    2871           0 :         CPLFree(sWriteFuncData.pBuffer);
    2872           0 :         CPLFree(sWriteFuncHeaderData.pBuffer);
    2873           0 :         curl_easy_cleanup(hCurlHandle);
    2874           0 :         return -1;
    2875             :     }
    2876             : 
    2877           0 :     char *pBuffer = sWriteFuncData.pBuffer;
    2878           0 :     size_t nSize = sWriteFuncData.nSize;
    2879             : 
    2880             :     // TODO(schwehr): Localize after removing gotos.
    2881           0 :     int nRet = -1;
    2882             :     char *pszBoundary;
    2883           0 :     std::string osBoundary;
    2884           0 :     char *pszNext = nullptr;
    2885           0 :     int iRange = 0;
    2886           0 :     int iPart = 0;
    2887           0 :     char *pszEOL = nullptr;
    2888             : 
    2889             :     /* -------------------------------------------------------------------- */
    2890             :     /*      No multipart if a single range has been requested               */
    2891             :     /* -------------------------------------------------------------------- */
    2892             : 
    2893           0 :     if (nMergedRanges == 1)
    2894             :     {
    2895           0 :         size_t nAccSize = 0;
    2896           0 :         if (static_cast<vsi_l_offset>(nSize) < nTotalReqSize)
    2897           0 :             goto end;
    2898             : 
    2899           0 :         for (int i = 0; i < nRanges; i++)
    2900             :         {
    2901           0 :             memcpy(ppData[i], pBuffer + nAccSize, panSizes[i]);
    2902           0 :             nAccSize += panSizes[i];
    2903             :         }
    2904             : 
    2905           0 :         nRet = 0;
    2906           0 :         goto end;
    2907             :     }
    2908             : 
    2909             :     /* -------------------------------------------------------------------- */
    2910             :     /*      Extract boundary name                                           */
    2911             :     /* -------------------------------------------------------------------- */
    2912             : 
    2913           0 :     pszBoundary = strstr(sWriteFuncHeaderData.pBuffer,
    2914             :                          "Content-Type: multipart/byteranges; boundary=");
    2915           0 :     if (pszBoundary == nullptr)
    2916             :     {
    2917           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Could not find '%s'",
    2918             :                  "Content-Type: multipart/byteranges; boundary=");
    2919           0 :         goto end;
    2920             :     }
    2921             : 
    2922           0 :     pszBoundary += strlen("Content-Type: multipart/byteranges; boundary=");
    2923             : 
    2924           0 :     pszEOL = strchr(pszBoundary, '\r');
    2925           0 :     if (pszEOL)
    2926           0 :         *pszEOL = 0;
    2927           0 :     pszEOL = strchr(pszBoundary, '\n');
    2928           0 :     if (pszEOL)
    2929           0 :         *pszEOL = 0;
    2930             : 
    2931             :     /* Remove optional double-quote character around boundary name */
    2932           0 :     if (pszBoundary[0] == '"')
    2933             :     {
    2934           0 :         pszBoundary++;
    2935           0 :         char *pszLastDoubleQuote = strrchr(pszBoundary, '"');
    2936           0 :         if (pszLastDoubleQuote)
    2937           0 :             *pszLastDoubleQuote = 0;
    2938             :     }
    2939             : 
    2940           0 :     osBoundary = "--";
    2941           0 :     osBoundary += pszBoundary;
    2942             : 
    2943             :     /* -------------------------------------------------------------------- */
    2944             :     /*      Find the start of the first chunk.                              */
    2945             :     /* -------------------------------------------------------------------- */
    2946           0 :     pszNext = strstr(pBuffer, osBoundary.c_str());
    2947           0 :     if (pszNext == nullptr)
    2948             :     {
    2949           0 :         CPLError(CE_Failure, CPLE_AppDefined, "No parts found.");
    2950           0 :         goto end;
    2951             :     }
    2952             : 
    2953           0 :     pszNext += osBoundary.size();
    2954           0 :     while (*pszNext != '\n' && *pszNext != '\r' && *pszNext != '\0')
    2955           0 :         pszNext++;
    2956           0 :     if (*pszNext == '\r')
    2957           0 :         pszNext++;
    2958           0 :     if (*pszNext == '\n')
    2959           0 :         pszNext++;
    2960             : 
    2961             :     /* -------------------------------------------------------------------- */
    2962             :     /*      Loop over parts...                                              */
    2963             :     /* -------------------------------------------------------------------- */
    2964           0 :     while (iPart < nRanges)
    2965             :     {
    2966             :         /* --------------------------------------------------------------------
    2967             :          */
    2968             :         /*      Collect headers. */
    2969             :         /* --------------------------------------------------------------------
    2970             :          */
    2971           0 :         bool bExpectedRange = false;
    2972             : 
    2973           0 :         while (*pszNext != '\n' && *pszNext != '\r' && *pszNext != '\0')
    2974             :         {
    2975           0 :             pszEOL = strstr(pszNext, "\n");
    2976             : 
    2977           0 :             if (pszEOL == nullptr)
    2978             :             {
    2979           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2980             :                          "Error while parsing multipart content (at line %d)",
    2981             :                          __LINE__);
    2982           0 :                 goto end;
    2983             :             }
    2984             : 
    2985           0 :             *pszEOL = '\0';
    2986           0 :             bool bRestoreAntislashR = false;
    2987           0 :             if (pszEOL - pszNext > 1 && pszEOL[-1] == '\r')
    2988             :             {
    2989           0 :                 bRestoreAntislashR = true;
    2990           0 :                 pszEOL[-1] = '\0';
    2991             :             }
    2992             : 
    2993           0 :             if (STARTS_WITH_CI(pszNext, "Content-Range: bytes "))
    2994             :             {
    2995           0 :                 bExpectedRange = true; /* FIXME */
    2996             :             }
    2997             : 
    2998           0 :             if (bRestoreAntislashR)
    2999           0 :                 pszEOL[-1] = '\r';
    3000           0 :             *pszEOL = '\n';
    3001             : 
    3002           0 :             pszNext = pszEOL + 1;
    3003             :         }
    3004             : 
    3005           0 :         if (!bExpectedRange)
    3006             :         {
    3007           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3008             :                      "Error while parsing multipart content (at line %d)",
    3009             :                      __LINE__);
    3010           0 :             goto end;
    3011             :         }
    3012             : 
    3013           0 :         if (*pszNext == '\r')
    3014           0 :             pszNext++;
    3015           0 :         if (*pszNext == '\n')
    3016           0 :             pszNext++;
    3017             : 
    3018             :         /* --------------------------------------------------------------------
    3019             :          */
    3020             :         /*      Work out the data block size. */
    3021             :         /* --------------------------------------------------------------------
    3022             :          */
    3023           0 :         size_t nBytesAvail = nSize - (pszNext - pBuffer);
    3024             : 
    3025             :         while (true)
    3026             :         {
    3027           0 :             if (nBytesAvail < panSizes[iRange])
    3028             :             {
    3029           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3030             :                          "Error while parsing multipart content (at line %d)",
    3031             :                          __LINE__);
    3032           0 :                 goto end;
    3033             :             }
    3034             : 
    3035           0 :             memcpy(ppData[iRange], pszNext, panSizes[iRange]);
    3036           0 :             pszNext += panSizes[iRange];
    3037           0 :             nBytesAvail -= panSizes[iRange];
    3038           0 :             if (iRange + 1 < nRanges &&
    3039           0 :                 panOffsets[iRange] + panSizes[iRange] == panOffsets[iRange + 1])
    3040             :             {
    3041           0 :                 iRange++;
    3042             :             }
    3043             :             else
    3044             :             {
    3045             :                 break;
    3046             :             }
    3047             :         }
    3048             : 
    3049           0 :         iPart++;
    3050           0 :         iRange++;
    3051             : 
    3052           0 :         while (nBytesAvail > 0 &&
    3053           0 :                (*pszNext != '-' ||
    3054           0 :                 strncmp(pszNext, osBoundary.c_str(), osBoundary.size()) != 0))
    3055             :         {
    3056           0 :             pszNext++;
    3057           0 :             nBytesAvail--;
    3058             :         }
    3059             : 
    3060           0 :         if (nBytesAvail == 0)
    3061             :         {
    3062           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3063             :                      "Error while parsing multipart content (at line %d)",
    3064             :                      __LINE__);
    3065           0 :             goto end;
    3066             :         }
    3067             : 
    3068           0 :         pszNext += osBoundary.size();
    3069           0 :         if (STARTS_WITH(pszNext, "--"))
    3070             :         {
    3071             :             // End of multipart.
    3072           0 :             break;
    3073             :         }
    3074             : 
    3075           0 :         if (*pszNext == '\r')
    3076           0 :             pszNext++;
    3077           0 :         if (*pszNext == '\n')
    3078           0 :             pszNext++;
    3079             :         else
    3080             :         {
    3081           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3082             :                      "Error while parsing multipart content (at line %d)",
    3083             :                      __LINE__);
    3084           0 :             goto end;
    3085             :         }
    3086             :     }
    3087             : 
    3088           0 :     if (iPart == nMergedRanges)
    3089           0 :         nRet = 0;
    3090             :     else
    3091           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3092             :                  "Got only %d parts, where %d were expected", iPart,
    3093             :                  nMergedRanges);
    3094             : 
    3095           0 : end:
    3096           0 :     CPLFree(sWriteFuncData.pBuffer);
    3097           0 :     CPLFree(sWriteFuncHeaderData.pBuffer);
    3098           0 :     curl_easy_cleanup(hCurlHandle);
    3099             : 
    3100           0 :     return nRet;
    3101             : }
    3102             : 
    3103             : /************************************************************************/
    3104             : /*                              PRead()                                 */
    3105             : /************************************************************************/
    3106             : 
    3107         208 : size_t VSICurlHandle::PRead(void *pBuffer, size_t nSize,
    3108             :                             vsi_l_offset nOffset) const
    3109             : {
    3110             :     // Try to use AdviseRead ranges fetched asynchronously
    3111         208 :     if (!m_aoAdviseReadRanges.empty())
    3112             :     {
    3113         144 :         for (auto &poRange : m_aoAdviseReadRanges)
    3114             :         {
    3115         288 :             if (nOffset >= poRange->nStartOffset &&
    3116         144 :                 nOffset + nSize <= poRange->nStartOffset + poRange->nSize)
    3117             :             {
    3118             :                 {
    3119         288 :                     std::unique_lock<std::mutex> oLock(poRange->oMutex);
    3120             :                     // coverity[missing_lock:FALSE]
    3121         288 :                     while (!poRange->bDone)
    3122             :                     {
    3123         144 :                         poRange->oCV.wait(oLock);
    3124             :                     }
    3125             :                 }
    3126         144 :                 if (poRange->abyData.empty())
    3127         144 :                     return 0;
    3128             : 
    3129             :                 auto nEndOffset =
    3130         144 :                     poRange->nStartOffset + poRange->abyData.size();
    3131         144 :                 if (nOffset >= nEndOffset)
    3132           0 :                     return 0;
    3133             :                 const size_t nToCopy = static_cast<size_t>(
    3134         144 :                     std::min<vsi_l_offset>(nSize, nEndOffset - nOffset));
    3135         144 :                 memcpy(pBuffer,
    3136         144 :                        poRange->abyData.data() +
    3137         144 :                            static_cast<size_t>(nOffset - poRange->nStartOffset),
    3138             :                        nToCopy);
    3139         144 :                 return nToCopy;
    3140             :             }
    3141             :         }
    3142             :     }
    3143             : 
    3144             :     // poFS has a global mutex
    3145          64 :     poFS->GetCachedFileProp(m_pszURL, oFileProp);
    3146          64 :     if (oFileProp.eExists == EXIST_NO)
    3147           0 :         return static_cast<size_t>(-1);
    3148             : 
    3149         128 :     NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
    3150         128 :     NetworkStatisticsFile oContextFile(m_osFilename.c_str());
    3151         128 :     NetworkStatisticsAction oContextAction("PRead");
    3152             : 
    3153         128 :     CPLStringList aosHTTPOptions(m_aosHTTPOptions);
    3154         128 :     std::string osURL;
    3155             :     {
    3156          64 :         std::lock_guard<std::mutex> oLock(m_oMutex);
    3157          64 :         UpdateQueryString();
    3158             :         bool bHasExpired;
    3159          64 :         osURL = GetRedirectURLIfValid(bHasExpired, aosHTTPOptions);
    3160             :     }
    3161             : 
    3162          64 :     CURL *hCurlHandle = curl_easy_init();
    3163             : 
    3164             :     struct curl_slist *headers =
    3165          64 :         VSICurlSetOptions(hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
    3166             : 
    3167          64 :     WriteFuncStruct sWriteFuncData;
    3168          64 :     VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
    3169          64 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
    3170          64 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    3171             :                                VSICurlHandleWriteFunc);
    3172             : 
    3173          64 :     WriteFuncStruct sWriteFuncHeaderData;
    3174          64 :     VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
    3175             :                                nullptr);
    3176          64 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    3177             :                                &sWriteFuncHeaderData);
    3178          64 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    3179             :                                VSICurlHandleWriteFunc);
    3180          64 :     sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(m_pszURL, "http");
    3181          64 :     sWriteFuncHeaderData.nStartOffset = nOffset;
    3182             : 
    3183          64 :     sWriteFuncHeaderData.nEndOffset = nOffset + nSize - 1;
    3184             : 
    3185          64 :     char rangeStr[512] = {};
    3186          64 :     snprintf(rangeStr, sizeof(rangeStr), CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    3187             :              sWriteFuncHeaderData.nStartOffset,
    3188             :              sWriteFuncHeaderData.nEndOffset);
    3189             : 
    3190             : #if 0
    3191             :     if( ENABLE_DEBUG )
    3192             :         CPLDebug(poFS->GetDebugKey(),
    3193             :                  "Downloading %s (%s)...", rangeStr, osURL.c_str());
    3194             : #endif
    3195             : 
    3196          64 :     std::string osHeaderRange;
    3197          64 :     if (sWriteFuncHeaderData.bIsHTTP)
    3198             :     {
    3199          64 :         osHeaderRange = CPLSPrintf("Range: bytes=%s", rangeStr);
    3200             :         // So it gets included in Azure signature
    3201          64 :         headers = curl_slist_append(headers, osHeaderRange.data());
    3202          64 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
    3203             :     }
    3204             :     else
    3205             :     {
    3206           0 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, rangeStr);
    3207             :     }
    3208             : 
    3209             :     std::array<char, CURL_ERROR_SIZE + 1> szCurlErrBuf;
    3210          64 :     szCurlErrBuf[0] = '\0';
    3211          64 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
    3212             :                                &szCurlErrBuf[0]);
    3213             : 
    3214             :     {
    3215          64 :         std::lock_guard<std::mutex> oLock(m_oMutex);
    3216             :         headers =
    3217          64 :             const_cast<VSICurlHandle *>(this)->GetCurlHeaders("GET", headers);
    3218             :     }
    3219          64 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    3220             : 
    3221          64 :     CURLM *hMultiHandle = poFS->GetCurlMultiHandleFor(osURL);
    3222          64 :     VSICURLMultiPerform(hMultiHandle, hCurlHandle, &m_bInterrupt);
    3223             : 
    3224             :     {
    3225         128 :         std::lock_guard<std::mutex> oLock(m_oMutex);
    3226          64 :         const_cast<VSICurlHandle *>(this)->UpdateRedirectInfo(
    3227             :             hCurlHandle, sWriteFuncHeaderData);
    3228             :     }
    3229             : 
    3230          64 :     long response_code = 0;
    3231          64 :     curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
    3232             : 
    3233          64 :     if (ENABLE_DEBUG && szCurlErrBuf[0] != '\0')
    3234             :     {
    3235           0 :         const char *pszErrorMsg = &szCurlErrBuf[0];
    3236           0 :         CPLDebug(poFS->GetDebugKey(), "PRead(%s), %s: response_code=%d, msg=%s",
    3237             :                  osURL.c_str(), rangeStr, static_cast<int>(response_code),
    3238             :                  pszErrorMsg);
    3239             :     }
    3240             : 
    3241             :     size_t nRet;
    3242          64 :     if ((response_code != 206 && response_code != 225) ||
    3243          64 :         sWriteFuncData.nSize == 0)
    3244             :     {
    3245           0 :         if (!m_bInterrupt)
    3246             :         {
    3247           0 :             CPLDebug(poFS->GetDebugKey(),
    3248             :                      "Request for %s failed with response_code=%ld", rangeStr,
    3249             :                      response_code);
    3250             :         }
    3251           0 :         nRet = static_cast<size_t>(-1);
    3252             :     }
    3253             :     else
    3254             :     {
    3255          64 :         nRet = std::min(sWriteFuncData.nSize, nSize);
    3256          64 :         if (nRet > 0)
    3257          64 :             memcpy(pBuffer, sWriteFuncData.pBuffer, nRet);
    3258             :     }
    3259             : 
    3260          64 :     VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
    3261          64 :     curl_easy_cleanup(hCurlHandle);
    3262          64 :     CPLFree(sWriteFuncData.pBuffer);
    3263          64 :     CPLFree(sWriteFuncHeaderData.pBuffer);
    3264          64 :     curl_slist_free_all(headers);
    3265             : 
    3266          64 :     NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
    3267             : 
    3268             : #if 0
    3269             :     if( ENABLE_DEBUG )
    3270             :         CPLDebug(poFS->GetDebugKey(), "Download completed");
    3271             : #endif
    3272             : 
    3273          64 :     return nRet;
    3274             : }
    3275             : 
    3276             : /************************************************************************/
    3277             : /*                  GetAdviseReadTotalBytesLimit()                      */
    3278             : /************************************************************************/
    3279             : 
    3280          16 : size_t VSICurlHandle::GetAdviseReadTotalBytesLimit() const
    3281             : {
    3282             :     return static_cast<size_t>(std::min<unsigned long long>(
    3283          48 :         std::numeric_limits<size_t>::max(),
    3284             :         // 100 MB
    3285          16 :         std::strtoull(
    3286             :             CPLGetConfigOption("CPL_VSIL_CURL_ADVISE_READ_TOTAL_BYTES_LIMIT",
    3287             :                                "104857600"),
    3288          16 :             nullptr, 10)));
    3289             : }
    3290             : 
    3291             : /************************************************************************/
    3292             : /*                       VSICURLMultiInit()                             */
    3293             : /************************************************************************/
    3294             : 
    3295         284 : static CURLM *VSICURLMultiInit()
    3296             : {
    3297         284 :     CURLM *hCurlMultiHandle = curl_multi_init();
    3298             : 
    3299         284 :     if (const char *pszMAXCONNECTS =
    3300         284 :             CPLGetConfigOption("GDAL_HTTP_MAX_CACHED_CONNECTIONS", nullptr))
    3301             :     {
    3302           1 :         curl_multi_setopt(hCurlMultiHandle, CURLMOPT_MAXCONNECTS,
    3303             :                           atoi(pszMAXCONNECTS));
    3304             :     }
    3305             : 
    3306         284 :     if (const char *pszMAX_TOTAL_CONNECTIONS =
    3307         284 :             CPLGetConfigOption("GDAL_HTTP_MAX_TOTAL_CONNECTIONS", nullptr))
    3308             :     {
    3309           1 :         curl_multi_setopt(hCurlMultiHandle, CURLMOPT_MAX_TOTAL_CONNECTIONS,
    3310             :                           atoi(pszMAX_TOTAL_CONNECTIONS));
    3311             :     }
    3312             : 
    3313         284 :     return hCurlMultiHandle;
    3314             : }
    3315             : 
    3316             : /************************************************************************/
    3317             : /*                         AdviseRead()                                 */
    3318             : /************************************************************************/
    3319             : 
    3320           8 : void VSICurlHandle::AdviseRead(int nRanges, const vsi_l_offset *panOffsets,
    3321             :                                const size_t *panSizes)
    3322             : {
    3323           8 :     if (!CPLTestBool(
    3324             :             CPLGetConfigOption("GDAL_HTTP_ENABLE_ADVISE_READ", "TRUE")))
    3325           2 :         return;
    3326             : 
    3327           6 :     if (m_oThreadAdviseRead.joinable())
    3328             :     {
    3329           1 :         m_oThreadAdviseRead.join();
    3330             :     }
    3331             : 
    3332             :     // Give up if we need to allocate too much memory
    3333           6 :     vsi_l_offset nMaxSize = 0;
    3334           6 :     const size_t nLimit = GetAdviseReadTotalBytesLimit();
    3335         150 :     for (int i = 0; i < nRanges; ++i)
    3336             :     {
    3337         144 :         if (panSizes[i] > nLimit - nMaxSize)
    3338             :         {
    3339           0 :             CPLDebug(poFS->GetDebugKey(),
    3340             :                      "Trying to request too many bytes in AdviseRead()");
    3341           0 :             return;
    3342             :         }
    3343         144 :         nMaxSize += panSizes[i];
    3344             :     }
    3345             : 
    3346           6 :     UpdateQueryString();
    3347             : 
    3348           6 :     bool bHasExpired = false;
    3349           6 :     CPLStringList aosHTTPOptions(m_aosHTTPOptions);
    3350             :     const std::string l_osURL(
    3351           6 :         GetRedirectURLIfValid(bHasExpired, aosHTTPOptions));
    3352           6 :     if (bHasExpired)
    3353             :     {
    3354           0 :         return;
    3355             :     }
    3356             : 
    3357           6 :     const bool bMergeConsecutiveRanges = CPLTestBool(
    3358             :         CPLGetConfigOption("GDAL_HTTP_MERGE_CONSECUTIVE_RANGES", "TRUE"));
    3359             : 
    3360             :     try
    3361             :     {
    3362           6 :         m_aoAdviseReadRanges.clear();
    3363           6 :         m_aoAdviseReadRanges.reserve(nRanges);
    3364          12 :         for (int i = 0; i < nRanges;)
    3365             :         {
    3366           6 :             int iNext = i;
    3367             :             // Identify consecutive ranges
    3368           6 :             constexpr size_t SIZE_COG_MARKERS = 2 * sizeof(uint32_t);
    3369           6 :             auto nEndOffset = panOffsets[iNext] + panSizes[iNext];
    3370         144 :             while (bMergeConsecutiveRanges && iNext + 1 < nRanges &&
    3371         138 :                    panOffsets[iNext + 1] > panOffsets[iNext] &&
    3372         138 :                    panOffsets[iNext] + panSizes[iNext] + SIZE_COG_MARKERS >=
    3373         282 :                        panOffsets[iNext + 1] &&
    3374         138 :                    panOffsets[iNext + 1] + panSizes[iNext + 1] > nEndOffset)
    3375             :             {
    3376         138 :                 iNext++;
    3377         138 :                 nEndOffset = panOffsets[iNext] + panSizes[iNext];
    3378             :             }
    3379           6 :             CPLAssert(panOffsets[i] <= nEndOffset);
    3380           6 :             const size_t nSize =
    3381           6 :                 static_cast<size_t>(nEndOffset - panOffsets[i]);
    3382             : 
    3383           6 :             if (nSize == 0)
    3384             :             {
    3385           0 :                 i = iNext + 1;
    3386           0 :                 continue;
    3387             :             }
    3388             : 
    3389             :             auto newAdviseReadRange =
    3390           6 :                 std::make_unique<AdviseReadRange>(m_oRetryParameters);
    3391           6 :             newAdviseReadRange->nStartOffset = panOffsets[i];
    3392           6 :             newAdviseReadRange->nSize = nSize;
    3393           6 :             newAdviseReadRange->abyData.resize(nSize);
    3394           6 :             m_aoAdviseReadRanges.push_back(std::move(newAdviseReadRange));
    3395             : 
    3396           6 :             i = iNext + 1;
    3397             :         }
    3398             :     }
    3399           0 :     catch (const std::exception &)
    3400             :     {
    3401           0 :         CPLError(CE_Failure, CPLE_OutOfMemory,
    3402             :                  "Out of memory in VSICurlHandle::AdviseRead()");
    3403           0 :         m_aoAdviseReadRanges.clear();
    3404             :     }
    3405             : 
    3406           6 :     if (m_aoAdviseReadRanges.empty())
    3407           0 :         return;
    3408             : 
    3409             : #ifdef DEBUG
    3410           6 :     CPLDebug(poFS->GetDebugKey(), "AdviseRead(): fetching %u ranges",
    3411           6 :              static_cast<unsigned>(m_aoAdviseReadRanges.size()));
    3412             : #endif
    3413             : 
    3414          12 :     const auto task = [this, aosHTTPOptions = std::move(aosHTTPOptions)](
    3415         477 :                           const std::string &osURL)
    3416             :     {
    3417           6 :         if (!m_hCurlMultiHandleForAdviseRead)
    3418           5 :             m_hCurlMultiHandleForAdviseRead = VSICURLMultiInit();
    3419             : 
    3420          12 :         NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
    3421          12 :         NetworkStatisticsFile oContextFile(m_osFilename.c_str());
    3422          12 :         NetworkStatisticsAction oContextAction("AdviseRead");
    3423             : 
    3424             : #ifdef CURLPIPE_MULTIPLEX
    3425             :         // Enable HTTP/2 multiplexing (ignored if an older version of HTTP is
    3426             :         // used)
    3427             :         // Not that this does not enable HTTP/1.1 pipeling, which is not
    3428             :         // recommended for example by Google Cloud Storage.
    3429             :         // For HTTP/1.1, parallel connections work better since you can get
    3430             :         // results out of order.
    3431           6 :         if (CPLTestBool(CPLGetConfigOption("GDAL_HTTP_MULTIPLEX", "YES")))
    3432             :         {
    3433           6 :             curl_multi_setopt(m_hCurlMultiHandleForAdviseRead,
    3434             :                               CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
    3435             :         }
    3436             : #endif
    3437             : 
    3438           6 :         size_t nTotalDownloaded = 0;
    3439             : 
    3440             :         while (true)
    3441             :         {
    3442             : 
    3443           8 :             std::vector<CURL *> aHandles;
    3444             :             std::vector<WriteFuncStruct> asWriteFuncData(
    3445           8 :                 m_aoAdviseReadRanges.size());
    3446             :             std::vector<WriteFuncStruct> asWriteFuncHeaderData(
    3447           8 :                 m_aoAdviseReadRanges.size());
    3448           8 :             std::vector<char *> apszRanges;
    3449           8 :             std::vector<struct curl_slist *> aHeaders;
    3450             : 
    3451             :             struct CurlErrBuffer
    3452             :             {
    3453             :                 std::array<char, CURL_ERROR_SIZE + 1> szCurlErrBuf;
    3454             :             };
    3455             :             std::vector<CurlErrBuffer> asCurlErrors(
    3456           8 :                 m_aoAdviseReadRanges.size());
    3457             : 
    3458           8 :             std::map<CURL *, size_t> oMapHandleToIdx;
    3459          16 :             for (size_t i = 0; i < m_aoAdviseReadRanges.size(); ++i)
    3460             :             {
    3461           8 :                 if (!m_aoAdviseReadRanges[i]->bToRetry)
    3462             :                 {
    3463           0 :                     aHandles.push_back(nullptr);
    3464           0 :                     apszRanges.push_back(nullptr);
    3465           0 :                     aHeaders.push_back(nullptr);
    3466           0 :                     continue;
    3467             :                 }
    3468           8 :                 m_aoAdviseReadRanges[i]->bToRetry = false;
    3469             : 
    3470           8 :                 CURL *hCurlHandle = curl_easy_init();
    3471           8 :                 oMapHandleToIdx[hCurlHandle] = i;
    3472           8 :                 aHandles.push_back(hCurlHandle);
    3473             : 
    3474             :                 // As the multi-range request is likely not the first one, we don't
    3475             :                 // need to wait as we already know if pipelining is possible
    3476             :                 // unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_PIPEWAIT, 1);
    3477             : 
    3478           8 :                 struct curl_slist *headers = VSICurlSetOptions(
    3479           8 :                     hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
    3480             : 
    3481           8 :                 VSICURLInitWriteFuncStruct(&asWriteFuncData[i], this,
    3482             :                                            pfnReadCbk, pReadCbkUserData);
    3483           8 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
    3484             :                                            &asWriteFuncData[i]);
    3485           8 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    3486             :                                            VSICurlHandleWriteFunc);
    3487             : 
    3488           8 :                 VSICURLInitWriteFuncStruct(&asWriteFuncHeaderData[i], nullptr,
    3489             :                                            nullptr, nullptr);
    3490           8 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    3491             :                                            &asWriteFuncHeaderData[i]);
    3492           8 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    3493             :                                            VSICurlHandleWriteFunc);
    3494          16 :                 asWriteFuncHeaderData[i].bIsHTTP =
    3495           8 :                     STARTS_WITH(m_pszURL, "http");
    3496          16 :                 asWriteFuncHeaderData[i].nStartOffset =
    3497           8 :                     m_aoAdviseReadRanges[i]->nStartOffset;
    3498             : 
    3499          16 :                 asWriteFuncHeaderData[i].nEndOffset =
    3500           8 :                     m_aoAdviseReadRanges[i]->nStartOffset +
    3501           8 :                     m_aoAdviseReadRanges[i]->nSize - 1;
    3502             : 
    3503           8 :                 char rangeStr[512] = {};
    3504          16 :                 snprintf(rangeStr, sizeof(rangeStr),
    3505             :                          CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    3506           8 :                          asWriteFuncHeaderData[i].nStartOffset,
    3507           8 :                          asWriteFuncHeaderData[i].nEndOffset);
    3508             : 
    3509             :                 if (ENABLE_DEBUG)
    3510           8 :                     CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...",
    3511             :                              rangeStr, osURL.c_str());
    3512             : 
    3513           8 :                 if (asWriteFuncHeaderData[i].bIsHTTP)
    3514             :                 {
    3515             :                     std::string osHeaderRange(
    3516           8 :                         CPLSPrintf("Range: bytes=%s", rangeStr));
    3517             :                     // So it gets included in Azure signature
    3518           8 :                     char *pszRange = CPLStrdup(osHeaderRange.c_str());
    3519           8 :                     apszRanges.push_back(pszRange);
    3520           8 :                     headers = curl_slist_append(headers, pszRange);
    3521           8 :                     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE,
    3522             :                                                nullptr);
    3523             :                 }
    3524             :                 else
    3525             :                 {
    3526           0 :                     apszRanges.push_back(nullptr);
    3527           0 :                     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE,
    3528             :                                                rangeStr);
    3529             :                 }
    3530             : 
    3531           8 :                 asCurlErrors[i].szCurlErrBuf[0] = '\0';
    3532           8 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
    3533             :                                            &asCurlErrors[i].szCurlErrBuf[0]);
    3534             : 
    3535           8 :                 headers = GetCurlHeaders("GET", headers);
    3536           8 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER,
    3537             :                                            headers);
    3538           8 :                 aHeaders.push_back(headers);
    3539           8 :                 curl_multi_add_handle(m_hCurlMultiHandleForAdviseRead,
    3540             :                                       hCurlHandle);
    3541             :             }
    3542             : 
    3543           8 :             const auto DealWithRequest = [this, &osURL, &nTotalDownloaded,
    3544             :                                           &oMapHandleToIdx, &asCurlErrors,
    3545             :                                           &asWriteFuncHeaderData,
    3546         116 :                                           &asWriteFuncData](CURL *hCurlHandle)
    3547             :             {
    3548           8 :                 auto oIter = oMapHandleToIdx.find(hCurlHandle);
    3549           8 :                 CPLAssert(oIter != oMapHandleToIdx.end());
    3550           8 :                 const auto iReq = oIter->second;
    3551             : 
    3552           8 :                 long response_code = 0;
    3553           8 :                 curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE,
    3554             :                                   &response_code);
    3555             : 
    3556           8 :                 if (ENABLE_DEBUG && asCurlErrors[iReq].szCurlErrBuf[0] != '\0')
    3557             :                 {
    3558           0 :                     char rangeStr[512] = {};
    3559           0 :                     snprintf(rangeStr, sizeof(rangeStr),
    3560             :                              CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    3561           0 :                              asWriteFuncHeaderData[iReq].nStartOffset,
    3562           0 :                              asWriteFuncHeaderData[iReq].nEndOffset);
    3563             : 
    3564             :                     const char *pszErrorMsg =
    3565           0 :                         &asCurlErrors[iReq].szCurlErrBuf[0];
    3566           0 :                     CPLDebug(poFS->GetDebugKey(),
    3567             :                              "ReadMultiRange(%s), %s: response_code=%d, msg=%s",
    3568             :                              osURL.c_str(), rangeStr,
    3569             :                              static_cast<int>(response_code), pszErrorMsg);
    3570             :                 }
    3571             : 
    3572           8 :                 bool bToRetry = false;
    3573          14 :                 if ((response_code != 206 && response_code != 225) ||
    3574           6 :                     asWriteFuncHeaderData[iReq].nEndOffset + 1 !=
    3575           6 :                         asWriteFuncHeaderData[iReq].nStartOffset +
    3576           6 :                             asWriteFuncData[iReq].nSize)
    3577             :                 {
    3578           2 :                     char rangeStr[512] = {};
    3579           4 :                     snprintf(rangeStr, sizeof(rangeStr),
    3580             :                              CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
    3581           2 :                              asWriteFuncHeaderData[iReq].nStartOffset,
    3582           2 :                              asWriteFuncHeaderData[iReq].nEndOffset);
    3583             : 
    3584             :                     // Look if we should attempt a retry
    3585           4 :                     if (m_aoAdviseReadRanges[iReq]->retryContext.CanRetry(
    3586             :                             static_cast<int>(response_code),
    3587           2 :                             asWriteFuncData[iReq].pBuffer,
    3588           2 :                             &asCurlErrors[iReq].szCurlErrBuf[0]))
    3589             :                     {
    3590           2 :                         CPLError(CE_Warning, CPLE_AppDefined,
    3591             :                                  "HTTP error code for %s range %s: %d. "
    3592             :                                  "Retrying again in %.1f secs",
    3593             :                                  osURL.c_str(), rangeStr,
    3594             :                                  static_cast<int>(response_code),
    3595           2 :                                  m_aoAdviseReadRanges[iReq]
    3596           2 :                                      ->retryContext.GetCurrentDelay());
    3597           2 :                         m_aoAdviseReadRanges[iReq]->dfSleepDelay =
    3598           2 :                             m_aoAdviseReadRanges[iReq]
    3599           2 :                                 ->retryContext.GetCurrentDelay();
    3600           2 :                         bToRetry = true;
    3601             :                     }
    3602             :                     else
    3603             :                     {
    3604           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    3605             :                                  "Request for %s range %s failed with "
    3606             :                                  "response_code=%ld",
    3607             :                                  osURL.c_str(), rangeStr, response_code);
    3608             :                     }
    3609             :                 }
    3610             :                 else
    3611             :                 {
    3612           6 :                     const size_t nSize = asWriteFuncData[iReq].nSize;
    3613           6 :                     memcpy(&m_aoAdviseReadRanges[iReq]->abyData[0],
    3614           6 :                            asWriteFuncData[iReq].pBuffer, nSize);
    3615           6 :                     m_aoAdviseReadRanges[iReq]->abyData.resize(nSize);
    3616             : 
    3617           6 :                     nTotalDownloaded += nSize;
    3618             :                 }
    3619             : 
    3620           8 :                 m_aoAdviseReadRanges[iReq]->bToRetry = bToRetry;
    3621             : 
    3622           8 :                 if (!bToRetry)
    3623             :                 {
    3624             :                     std::lock_guard<std::mutex> oLock(
    3625          12 :                         m_aoAdviseReadRanges[iReq]->oMutex);
    3626           6 :                     m_aoAdviseReadRanges[iReq]->bDone = true;
    3627           6 :                     m_aoAdviseReadRanges[iReq]->oCV.notify_all();
    3628             :                 }
    3629           8 :             };
    3630             : 
    3631           8 :             int repeats = 0;
    3632             : 
    3633           8 :             void *old_handler = CPLHTTPIgnoreSigPipe();
    3634             :             while (true)
    3635             :             {
    3636             :                 int still_running;
    3637          90 :                 while (curl_multi_perform(m_hCurlMultiHandleForAdviseRead,
    3638          90 :                                           &still_running) ==
    3639             :                        CURLM_CALL_MULTI_PERFORM)
    3640             :                 {
    3641             :                     // loop
    3642             :                 }
    3643          90 :                 if (!still_running)
    3644             :                 {
    3645           8 :                     break;
    3646             :                 }
    3647             : 
    3648             :                 CURLMsg *msg;
    3649           0 :                 do
    3650             :                 {
    3651          82 :                     int msgq = 0;
    3652          82 :                     msg = curl_multi_info_read(m_hCurlMultiHandleForAdviseRead,
    3653             :                                                &msgq);
    3654          82 :                     if (msg && (msg->msg == CURLMSG_DONE))
    3655             :                     {
    3656           0 :                         DealWithRequest(msg->easy_handle);
    3657             :                     }
    3658          82 :                 } while (msg);
    3659             : 
    3660          82 :                 CPLMultiPerformWait(m_hCurlMultiHandleForAdviseRead, repeats);
    3661          82 :             }
    3662           8 :             CPLHTTPRestoreSigPipeHandler(old_handler);
    3663             : 
    3664           8 :             bool bRetry = false;
    3665           8 :             double dfDelay = 0.0;
    3666          16 :             for (size_t i = 0; i < m_aoAdviseReadRanges.size(); ++i)
    3667             :             {
    3668             :                 bool bReqDone;
    3669             :                 {
    3670             :                     // To please Coverity Scan
    3671             :                     std::lock_guard<std::mutex> oLock(
    3672           8 :                         m_aoAdviseReadRanges[i]->oMutex);
    3673           8 :                     bReqDone = m_aoAdviseReadRanges[i]->bDone;
    3674             :                 }
    3675           8 :                 if (!bReqDone && !m_aoAdviseReadRanges[i]->bToRetry)
    3676             :                 {
    3677           8 :                     DealWithRequest(aHandles[i]);
    3678             :                 }
    3679           8 :                 if (m_aoAdviseReadRanges[i]->bToRetry)
    3680           2 :                     dfDelay = std::max(dfDelay,
    3681           2 :                                        m_aoAdviseReadRanges[i]->dfSleepDelay);
    3682           8 :                 bRetry = bRetry || m_aoAdviseReadRanges[i]->bToRetry;
    3683           8 :                 if (aHandles[i])
    3684             :                 {
    3685           8 :                     curl_multi_remove_handle(m_hCurlMultiHandleForAdviseRead,
    3686           8 :                                              aHandles[i]);
    3687           8 :                     VSICURLResetHeaderAndWriterFunctions(aHandles[i]);
    3688           8 :                     curl_easy_cleanup(aHandles[i]);
    3689             :                 }
    3690           8 :                 CPLFree(apszRanges[i]);
    3691           8 :                 CPLFree(asWriteFuncData[i].pBuffer);
    3692           8 :                 CPLFree(asWriteFuncHeaderData[i].pBuffer);
    3693           8 :                 if (aHeaders[i])
    3694           8 :                     curl_slist_free_all(aHeaders[i]);
    3695             :             }
    3696           8 :             if (!bRetry)
    3697           6 :                 break;
    3698           2 :             CPLSleep(dfDelay);
    3699           2 :         }
    3700             : 
    3701           6 :         NetworkStatisticsLogger::LogGET(nTotalDownloaded);
    3702          12 :     };
    3703             : 
    3704           6 :     m_oThreadAdviseRead = std::thread(task, l_osURL);
    3705             : }
    3706             : 
    3707             : /************************************************************************/
    3708             : /*                               Write()                                */
    3709             : /************************************************************************/
    3710             : 
    3711           0 : size_t VSICurlHandle::Write(const void * /* pBuffer */, size_t /* nSize */,
    3712             :                             size_t /* nMemb */)
    3713             : {
    3714           0 :     return 0;
    3715             : }
    3716             : 
    3717             : /************************************************************************/
    3718             : /*                             ClearErr()                               */
    3719             : /************************************************************************/
    3720             : 
    3721           1 : void VSICurlHandle::ClearErr()
    3722             : 
    3723             : {
    3724           1 :     bEOF = false;
    3725           1 :     bError = false;
    3726           1 : }
    3727             : 
    3728             : /************************************************************************/
    3729             : /*                              Error()                                 */
    3730             : /************************************************************************/
    3731             : 
    3732           8 : int VSICurlHandle::Error()
    3733             : 
    3734             : {
    3735           8 :     return bError ? TRUE : FALSE;
    3736             : }
    3737             : 
    3738             : /************************************************************************/
    3739             : /*                                Eof()                                 */
    3740             : /************************************************************************/
    3741             : 
    3742          10 : int VSICurlHandle::Eof()
    3743             : 
    3744             : {
    3745          10 :     return bEOF ? TRUE : FALSE;
    3746             : }
    3747             : 
    3748             : /************************************************************************/
    3749             : /*                                 Flush()                              */
    3750             : /************************************************************************/
    3751             : 
    3752           0 : int VSICurlHandle::Flush()
    3753             : {
    3754           0 :     return 0;
    3755             : }
    3756             : 
    3757             : /************************************************************************/
    3758             : /*                                  Close()                             */
    3759             : /************************************************************************/
    3760             : 
    3761         432 : int VSICurlHandle::Close()
    3762             : {
    3763         432 :     return 0;
    3764             : }
    3765             : 
    3766             : /************************************************************************/
    3767             : /*                   VSICurlFilesystemHandlerBase()                         */
    3768             : /************************************************************************/
    3769             : 
    3770       13552 : VSICurlFilesystemHandlerBase::VSICurlFilesystemHandlerBase()
    3771       13552 :     : oCacheFileProp{100 * 1024}, oCacheDirList{1024, 0}
    3772             : {
    3773       13552 : }
    3774             : 
    3775             : /************************************************************************/
    3776             : /*                           CachedConnection                           */
    3777             : /************************************************************************/
    3778             : 
    3779             : namespace
    3780             : {
    3781             : struct CachedConnection
    3782             : {
    3783             :     CURLM *hCurlMultiHandle = nullptr;
    3784             :     void clear();
    3785             : 
    3786        9003 :     ~CachedConnection()
    3787        9003 :     {
    3788        9003 :         clear();
    3789        9003 :     }
    3790             : };
    3791             : }  // namespace
    3792             : 
    3793             : #ifdef _WIN32
    3794             : // Currently thread_local and C++ objects don't work well with DLL on Windows
    3795             : static void FreeCachedConnection(void *pData)
    3796             : {
    3797             :     delete static_cast<
    3798             :         std::map<VSICurlFilesystemHandlerBase *, CachedConnection> *>(pData);
    3799             : }
    3800             : 
    3801             : // Per-thread and per-filesystem Curl connection cache.
    3802             : static std::map<VSICurlFilesystemHandlerBase *, CachedConnection> &
    3803             : GetConnectionCache()
    3804             : {
    3805             :     static std::map<VSICurlFilesystemHandlerBase *, CachedConnection>
    3806             :         dummyCache;
    3807             :     int bMemoryErrorOccurred = false;
    3808             :     void *pData =
    3809             :         CPLGetTLSEx(CTLS_VSICURL_CACHEDCONNECTION, &bMemoryErrorOccurred);
    3810             :     if (bMemoryErrorOccurred)
    3811             :     {
    3812             :         return dummyCache;
    3813             :     }
    3814             :     if (pData == nullptr)
    3815             :     {
    3816             :         auto cachedConnection =
    3817             :             new std::map<VSICurlFilesystemHandlerBase *, CachedConnection>();
    3818             :         CPLSetTLSWithFreeFuncEx(CTLS_VSICURL_CACHEDCONNECTION, cachedConnection,
    3819             :                                 FreeCachedConnection, &bMemoryErrorOccurred);
    3820             :         if (bMemoryErrorOccurred)
    3821             :         {
    3822             :             delete cachedConnection;
    3823             :             return dummyCache;
    3824             :         }
    3825             :         return *cachedConnection;
    3826             :     }
    3827             :     return *static_cast<
    3828             :         std::map<VSICurlFilesystemHandlerBase *, CachedConnection> *>(pData);
    3829             : }
    3830             : #else
    3831             : static thread_local std::map<VSICurlFilesystemHandlerBase *, CachedConnection>
    3832             :     g_tls_connectionCache;
    3833             : 
    3834             : static std::map<VSICurlFilesystemHandlerBase *, CachedConnection> &
    3835       26389 : GetConnectionCache()
    3836             : {
    3837       26389 :     return g_tls_connectionCache;
    3838             : }
    3839             : #endif
    3840             : 
    3841             : /************************************************************************/
    3842             : /*                              clear()                                 */
    3843             : /************************************************************************/
    3844             : 
    3845       25147 : void CachedConnection::clear()
    3846             : {
    3847       25147 :     if (hCurlMultiHandle)
    3848             :     {
    3849         251 :         VSICURLMultiCleanup(hCurlMultiHandle);
    3850         251 :         hCurlMultiHandle = nullptr;
    3851             :     }
    3852       25147 : }
    3853             : 
    3854             : /************************************************************************/
    3855             : /*                  ~VSICurlFilesystemHandlerBase()                         */
    3856             : /************************************************************************/
    3857             : 
    3858        8976 : VSICurlFilesystemHandlerBase::~VSICurlFilesystemHandlerBase()
    3859             : {
    3860        8976 :     VSICurlFilesystemHandlerBase::ClearCache();
    3861        8976 :     GetConnectionCache().erase(this);
    3862             : 
    3863        8976 :     if (hMutex != nullptr)
    3864        8976 :         CPLDestroyMutex(hMutex);
    3865        8976 :     hMutex = nullptr;
    3866        8976 : }
    3867             : 
    3868             : /************************************************************************/
    3869             : /*                      AllowCachedDataFor()                            */
    3870             : /************************************************************************/
    3871             : 
    3872        2046 : bool VSICurlFilesystemHandlerBase::AllowCachedDataFor(const char *pszFilename)
    3873             : {
    3874        2046 :     bool bCachedAllowed = true;
    3875        2046 :     char **papszTokens = CSLTokenizeString2(
    3876             :         CPLGetConfigOption("CPL_VSIL_CURL_NON_CACHED", ""), ":", 0);
    3877        2086 :     for (int i = 0; papszTokens && papszTokens[i]; i++)
    3878             :     {
    3879         120 :         if (STARTS_WITH(pszFilename, papszTokens[i]))
    3880             :         {
    3881          80 :             bCachedAllowed = false;
    3882          80 :             break;
    3883             :         }
    3884             :     }
    3885        2046 :     CSLDestroy(papszTokens);
    3886        2046 :     return bCachedAllowed;
    3887             : }
    3888             : 
    3889             : /************************************************************************/
    3890             : /*                     GetCurlMultiHandleFor()                          */
    3891             : /************************************************************************/
    3892             : 
    3893        1269 : CURLM *VSICurlFilesystemHandlerBase::GetCurlMultiHandleFor(
    3894             :     const std::string & /*osURL*/)
    3895             : {
    3896        1269 :     auto &conn = GetConnectionCache()[this];
    3897        1269 :     if (conn.hCurlMultiHandle == nullptr)
    3898             :     {
    3899         279 :         conn.hCurlMultiHandle = VSICURLMultiInit();
    3900             :     }
    3901        1269 :     return conn.hCurlMultiHandle;
    3902             : }
    3903             : 
    3904             : /************************************************************************/
    3905             : /*                          GetRegionCache()                            */
    3906             : /************************************************************************/
    3907             : 
    3908             : VSICurlFilesystemHandlerBase::RegionCacheType *
    3909       63276 : VSICurlFilesystemHandlerBase::GetRegionCache()
    3910             : {
    3911             :     // should be called under hMutex taken
    3912       63276 :     if (m_poRegionCacheDoNotUseDirectly == nullptr)
    3913             :     {
    3914        8994 :         m_poRegionCacheDoNotUseDirectly.reset(
    3915        8994 :             new RegionCacheType(static_cast<size_t>(GetMaxRegions())));
    3916             :     }
    3917       63276 :     return m_poRegionCacheDoNotUseDirectly.get();
    3918             : }
    3919             : 
    3920             : /************************************************************************/
    3921             : /*                          GetRegion()                                 */
    3922             : /************************************************************************/
    3923             : 
    3924             : std::shared_ptr<std::string>
    3925       46326 : VSICurlFilesystemHandlerBase::GetRegion(const char *pszURL,
    3926             :                                         vsi_l_offset nFileOffsetStart)
    3927             : {
    3928       92652 :     CPLMutexHolder oHolder(&hMutex);
    3929             : 
    3930       46326 :     const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
    3931       46326 :     nFileOffsetStart =
    3932       46326 :         (nFileOffsetStart / knDOWNLOAD_CHUNK_SIZE) * knDOWNLOAD_CHUNK_SIZE;
    3933             : 
    3934       46326 :     std::shared_ptr<std::string> out;
    3935       92652 :     if (GetRegionCache()->tryGet(
    3936       92652 :             FilenameOffsetPair(std::string(pszURL), nFileOffsetStart), out))
    3937             :     {
    3938       45724 :         return out;
    3939             :     }
    3940             : 
    3941         602 :     return nullptr;
    3942             : }
    3943             : 
    3944             : /************************************************************************/
    3945             : /*                          AddRegion()                                 */
    3946             : /************************************************************************/
    3947             : 
    3948         604 : void VSICurlFilesystemHandlerBase::AddRegion(const char *pszURL,
    3949             :                                              vsi_l_offset nFileOffsetStart,
    3950             :                                              size_t nSize, const char *pData)
    3951             : {
    3952        1208 :     CPLMutexHolder oHolder(&hMutex);
    3953             : 
    3954         604 :     std::shared_ptr<std::string> value(new std::string());
    3955         604 :     value->assign(pData, nSize);
    3956        1208 :     GetRegionCache()->insert(
    3957        1208 :         FilenameOffsetPair(std::string(pszURL), nFileOffsetStart), value);
    3958         604 : }
    3959             : 
    3960             : /************************************************************************/
    3961             : /*                         GetCachedFileProp()                          */
    3962             : /************************************************************************/
    3963             : 
    3964       48298 : bool VSICurlFilesystemHandlerBase::GetCachedFileProp(const char *pszURL,
    3965             :                                                      FileProp &oFileProp)
    3966             : {
    3967       96596 :     CPLMutexHolder oHolder(&hMutex);
    3968             :     bool inCache;
    3969       48298 :     if (oCacheFileProp.tryGet(std::string(pszURL), inCache))
    3970             :     {
    3971       46568 :         if (VSICURLGetCachedFileProp(pszURL, oFileProp))
    3972             :         {
    3973       46568 :             return true;
    3974             :         }
    3975           0 :         oCacheFileProp.remove(std::string(pszURL));
    3976             :     }
    3977        1730 :     return false;
    3978             : }
    3979             : 
    3980             : /************************************************************************/
    3981             : /*                         SetCachedFileProp()                          */
    3982             : /************************************************************************/
    3983             : 
    3984        1087 : void VSICurlFilesystemHandlerBase::SetCachedFileProp(const char *pszURL,
    3985             :                                                      FileProp &oFileProp)
    3986             : {
    3987        2174 :     CPLMutexHolder oHolder(&hMutex);
    3988        1087 :     oCacheFileProp.insert(std::string(pszURL), true);
    3989        1087 :     VSICURLSetCachedFileProp(pszURL, oFileProp);
    3990        1087 : }
    3991             : 
    3992             : /************************************************************************/
    3993             : /*                         GetCachedDirList()                           */
    3994             : /************************************************************************/
    3995             : 
    3996         568 : bool VSICurlFilesystemHandlerBase::GetCachedDirList(
    3997             :     const char *pszURL, CachedDirList &oCachedDirList)
    3998             : {
    3999         568 :     CPLMutexHolder oHolder(&hMutex);
    4000             : 
    4001        1291 :     return oCacheDirList.tryGet(std::string(pszURL), oCachedDirList) &&
    4002             :            // Let a chance to use new auth parameters
    4003         155 :            gnGenerationAuthParameters ==
    4004        1291 :                oCachedDirList.nGenerationAuthParameters;
    4005             : }
    4006             : 
    4007             : /************************************************************************/
    4008             : /*                         SetCachedDirList()                           */
    4009             : /************************************************************************/
    4010             : 
    4011         166 : void VSICurlFilesystemHandlerBase::SetCachedDirList(
    4012             :     const char *pszURL, CachedDirList &oCachedDirList)
    4013             : {
    4014         332 :     CPLMutexHolder oHolder(&hMutex);
    4015             : 
    4016         332 :     std::string key(pszURL);
    4017         332 :     CachedDirList oldValue;
    4018         166 :     if (oCacheDirList.tryGet(key, oldValue))
    4019             :     {
    4020          10 :         nCachedFilesInDirList -= oldValue.oFileList.size();
    4021          10 :         oCacheDirList.remove(key);
    4022             :     }
    4023             : 
    4024         166 :     while ((!oCacheDirList.empty() &&
    4025          60 :             nCachedFilesInDirList + oCachedDirList.oFileList.size() >
    4026         332 :                 1024 * 1024) ||
    4027         166 :            oCacheDirList.size() == oCacheDirList.getMaxAllowedSize())
    4028             :     {
    4029           0 :         std::string oldestKey;
    4030           0 :         oCacheDirList.getOldestEntry(oldestKey, oldValue);
    4031           0 :         nCachedFilesInDirList -= oldValue.oFileList.size();
    4032           0 :         oCacheDirList.remove(oldestKey);
    4033             :     }
    4034         166 :     oCachedDirList.nGenerationAuthParameters = gnGenerationAuthParameters;
    4035             : 
    4036         166 :     nCachedFilesInDirList += oCachedDirList.oFileList.size();
    4037         166 :     oCacheDirList.insert(key, oCachedDirList);
    4038         166 : }
    4039             : 
    4040             : /************************************************************************/
    4041             : /*                        ExistsInCacheDirList()                        */
    4042             : /************************************************************************/
    4043             : 
    4044          13 : bool VSICurlFilesystemHandlerBase::ExistsInCacheDirList(
    4045             :     const std::string &osDirname, bool *pbIsDir)
    4046             : {
    4047          26 :     CachedDirList cachedDirList;
    4048          13 :     if (GetCachedDirList(osDirname.c_str(), cachedDirList))
    4049             :     {
    4050           0 :         if (pbIsDir)
    4051           0 :             *pbIsDir = !cachedDirList.oFileList.empty();
    4052           0 :         return false;
    4053             :     }
    4054             :     else
    4055             :     {
    4056          13 :         if (pbIsDir)
    4057          13 :             *pbIsDir = false;
    4058          13 :         return false;
    4059             :     }
    4060             : }
    4061             : 
    4062             : /************************************************************************/
    4063             : /*                        InvalidateCachedData()                        */
    4064             : /************************************************************************/
    4065             : 
    4066         197 : void VSICurlFilesystemHandlerBase::InvalidateCachedData(const char *pszURL)
    4067             : {
    4068         394 :     CPLMutexHolder oHolder(&hMutex);
    4069             : 
    4070         197 :     oCacheFileProp.remove(std::string(pszURL));
    4071             : 
    4072             :     // Invalidate all cached regions for this URL
    4073         394 :     std::list<FilenameOffsetPair> keysToRemove;
    4074         394 :     std::string osURL(pszURL);
    4075             :     auto lambda =
    4076        1119 :         [&keysToRemove,
    4077             :          &osURL](const lru11::KeyValuePair<FilenameOffsetPair,
    4078        1262 :                                            std::shared_ptr<std::string>> &kv)
    4079             :     {
    4080        1119 :         if (kv.key.filename_ == osURL)
    4081         143 :             keysToRemove.push_back(kv.key);
    4082        1316 :     };
    4083         197 :     auto *poRegionCache = GetRegionCache();
    4084         197 :     poRegionCache->cwalk(lambda);
    4085         340 :     for (const auto &key : keysToRemove)
    4086         143 :         poRegionCache->remove(key);
    4087         197 : }
    4088             : 
    4089             : /************************************************************************/
    4090             : /*                            ClearCache()                              */
    4091             : /************************************************************************/
    4092             : 
    4093       16144 : void VSICurlFilesystemHandlerBase::ClearCache()
    4094             : {
    4095       16144 :     CPLMutexHolder oHolder(&hMutex);
    4096             : 
    4097       16144 :     GetRegionCache()->clear();
    4098             : 
    4099             :     {
    4100         633 :         const auto lambda = [](const lru11::KeyValuePair<std::string, bool> &kv)
    4101         633 :         { VSICURLInvalidateCachedFileProp(kv.key.c_str()); };
    4102       16144 :         oCacheFileProp.cwalk(lambda);
    4103       16144 :         oCacheFileProp.clear();
    4104             :     }
    4105             : 
    4106       16144 :     oCacheDirList.clear();
    4107       16144 :     nCachedFilesInDirList = 0;
    4108             : 
    4109       16144 :     GetConnectionCache()[this].clear();
    4110       16144 : }
    4111             : 
    4112             : /************************************************************************/
    4113             : /*                          PartialClearCache()                         */
    4114             : /************************************************************************/
    4115             : 
    4116           5 : void VSICurlFilesystemHandlerBase::PartialClearCache(
    4117             :     const char *pszFilenamePrefix)
    4118             : {
    4119          10 :     CPLMutexHolder oHolder(&hMutex);
    4120             : 
    4121          15 :     std::string osURL = GetURLFromFilename(pszFilenamePrefix);
    4122             :     {
    4123          10 :         std::list<FilenameOffsetPair> keysToRemove;
    4124             :         auto lambda =
    4125           1 :             [&keysToRemove, &osURL](
    4126             :                 const lru11::KeyValuePair<FilenameOffsetPair,
    4127           2 :                                           std::shared_ptr<std::string>> &kv)
    4128             :         {
    4129           1 :             if (strncmp(kv.key.filename_.c_str(), osURL.c_str(),
    4130           1 :                         osURL.size()) == 0)
    4131           0 :                 keysToRemove.push_back(kv.key);
    4132           6 :         };
    4133           5 :         auto *poRegionCache = GetRegionCache();
    4134           5 :         poRegionCache->cwalk(lambda);
    4135           5 :         for (const auto &key : keysToRemove)
    4136           0 :             poRegionCache->remove(key);
    4137             :     }
    4138             : 
    4139             :     {
    4140          10 :         std::list<std::string> keysToRemove;
    4141           8 :         auto lambda = [&keysToRemove,
    4142          19 :                        &osURL](const lru11::KeyValuePair<std::string, bool> &kv)
    4143             :         {
    4144           8 :             if (strncmp(kv.key.c_str(), osURL.c_str(), osURL.size()) == 0)
    4145           3 :                 keysToRemove.push_back(kv.key);
    4146          13 :         };
    4147           5 :         oCacheFileProp.cwalk(lambda);
    4148           8 :         for (const auto &key : keysToRemove)
    4149           3 :             oCacheFileProp.remove(key);
    4150             :     }
    4151           5 :     VSICURLInvalidateCachedFilePropPrefix(osURL.c_str());
    4152             : 
    4153             :     {
    4154           5 :         const size_t nLen = strlen(pszFilenamePrefix);
    4155          10 :         std::list<std::string> keysToRemove;
    4156             :         auto lambda =
    4157           2 :             [this, &keysToRemove, pszFilenamePrefix,
    4158           4 :              nLen](const lru11::KeyValuePair<std::string, CachedDirList> &kv)
    4159             :         {
    4160           2 :             if (strncmp(kv.key.c_str(), pszFilenamePrefix, nLen) == 0)
    4161             :             {
    4162           1 :                 keysToRemove.push_back(kv.key);
    4163           1 :                 nCachedFilesInDirList -= kv.value.oFileList.size();
    4164             :             }
    4165           7 :         };
    4166           5 :         oCacheDirList.cwalk(lambda);
    4167           6 :         for (const auto &key : keysToRemove)
    4168           1 :             oCacheDirList.remove(key);
    4169             :     }
    4170           5 : }
    4171             : 
    4172             : /************************************************************************/
    4173             : /*                          CreateFileHandle()                          */
    4174             : /************************************************************************/
    4175             : 
    4176             : VSICurlHandle *
    4177         691 : VSICurlFilesystemHandlerBase::CreateFileHandle(const char *pszFilename)
    4178             : {
    4179         691 :     return new VSICurlHandle(this, pszFilename);
    4180             : }
    4181             : 
    4182             : /************************************************************************/
    4183             : /*                          GetActualURL()                              */
    4184             : /************************************************************************/
    4185             : 
    4186           5 : const char *VSICurlFilesystemHandlerBase::GetActualURL(const char *pszFilename)
    4187             : {
    4188           5 :     VSICurlHandle *poHandle = CreateFileHandle(pszFilename);
    4189           5 :     if (poHandle == nullptr)
    4190           0 :         return pszFilename;
    4191          10 :     std::string osURL(poHandle->GetURL());
    4192           5 :     delete poHandle;
    4193           5 :     return CPLSPrintf("%s", osURL.c_str());
    4194             : }
    4195             : 
    4196             : /************************************************************************/
    4197             : /*                           GetOptions()                               */
    4198             : /************************************************************************/
    4199             : 
    4200             : #define VSICURL_OPTIONS                                                        \
    4201             :     "  <Option name='GDAL_HTTP_MAX_RETRY' type='int' "                         \
    4202             :     "description='Maximum number of retries' default='0'/>"                    \
    4203             :     "  <Option name='GDAL_HTTP_RETRY_DELAY' type='double' "                    \
    4204             :     "description='Retry delay in seconds' default='30'/>"                      \
    4205             :     "  <Option name='GDAL_HTTP_HEADER_FILE' type='string' "                    \
    4206             :     "description='Filename of a file that contains HTTP headers to "           \
    4207             :     "forward to the server'/>"                                                 \
    4208             :     "  <Option name='CPL_VSIL_CURL_USE_HEAD' type='boolean' "                  \
    4209             :     "description='Whether to use HTTP HEAD verb to retrieve "                  \
    4210             :     "file information' default='YES'/>"                                        \
    4211             :     "  <Option name='GDAL_HTTP_MULTIRANGE' type='string-select' "              \
    4212             :     "description='Strategy to apply to run multi-range requests' "             \
    4213             :     "default='PARALLEL'>"                                                      \
    4214             :     "       <Value>PARALLEL</Value>"                                           \
    4215             :     "       <Value>SERIAL</Value>"                                             \
    4216             :     "  </Option>"                                                              \
    4217             :     "  <Option name='GDAL_HTTP_MULTIPLEX' type='boolean' "                     \
    4218             :     "description='Whether to enable HTTP/2 multiplexing' default='YES'/>"      \
    4219             :     "  <Option name='GDAL_HTTP_MERGE_CONSECUTIVE_RANGES' type='boolean' "      \
    4220             :     "description='Whether to merge consecutive ranges in multirange "          \
    4221             :     "requests' default='YES'/>"                                                \
    4222             :     "  <Option name='CPL_VSIL_CURL_NON_CACHED' type='string' "                 \
    4223             :     "description='Colon-separated list of filenames whose content"             \
    4224             :     "must not be cached across open attempts'/>"                               \
    4225             :     "  <Option name='CPL_VSIL_CURL_ALLOWED_FILENAME' type='string' "           \
    4226             :     "description='Single filename that is allowed to be opened'/>"             \
    4227             :     "  <Option name='CPL_VSIL_CURL_ALLOWED_EXTENSIONS' type='string' "         \
    4228             :     "description='Comma or space separated list of allowed file "              \
    4229             :     "extensions'/>"                                                            \
    4230             :     "  <Option name='GDAL_DISABLE_READDIR_ON_OPEN' type='string-select' "      \
    4231             :     "description='Whether to disable establishing the list of files in "       \
    4232             :     "the directory of the current filename' default='NO'>"                     \
    4233             :     "       <Value>NO</Value>"                                                 \
    4234             :     "       <Value>YES</Value>"                                                \
    4235             :     "       <Value>EMPTY_DIR</Value>"                                          \
    4236             :     "  </Option>"                                                              \
    4237             :     "  <Option name='VSI_CACHE' type='boolean' "                               \
    4238             :     "description='Whether to cache in memory the contents of the opened "      \
    4239             :     "file as soon as they are read' default='NO'/>"                            \
    4240             :     "  <Option name='CPL_VSIL_CURL_CHUNK_SIZE' type='integer' "                \
    4241             :     "description='Size in bytes of the minimum amount of data read in a "      \
    4242             :     "file' default='16384' min='1024' max='10485760'/>"                        \
    4243             :     "  <Option name='CPL_VSIL_CURL_CACHE_SIZE' type='integer' "                \
    4244             :     "description='Size in bytes of the global /vsicurl/ cache' "               \
    4245             :     "default='16384000'/>"                                                     \
    4246             :     "  <Option name='CPL_VSIL_CURL_IGNORE_GLACIER_STORAGE' type='boolean' "    \
    4247             :     "description='Whether to skip files with Glacier storage class in "        \
    4248             :     "directory listing.' default='YES'/>"                                      \
    4249             :     "  <Option name='CPL_VSIL_CURL_ADVISE_READ_TOTAL_BYTES_LIMIT' "            \
    4250             :     "type='integer' description='Maximum number of bytes AdviseRead() is "     \
    4251             :     "allowed to fetch at once' default='104857600'/>"                          \
    4252             :     "  <Option name='GDAL_HTTP_MAX_CACHED_CONNECTIONS' type='integer' "        \
    4253             :     "description='Maximum amount of connections that libcurl may keep alive "  \
    4254             :     "in its connection cache after use'/>"                                     \
    4255             :     "  <Option name='GDAL_HTTP_MAX_TOTAL_CONNECTIONS' type='integer' "         \
    4256             :     "description='Maximum number of simultaneously open connections in "       \
    4257             :     "total'/>"
    4258             : 
    4259           8 : const char *VSICurlFilesystemHandlerBase::GetOptionsStatic()
    4260             : {
    4261           8 :     return VSICURL_OPTIONS;
    4262             : }
    4263             : 
    4264           2 : const char *VSICurlFilesystemHandlerBase::GetOptions()
    4265             : {
    4266           2 :     static std::string osOptions(std::string("<Options>") + GetOptionsStatic() +
    4267           3 :                                  "</Options>");
    4268           2 :     return osOptions.c_str();
    4269             : }
    4270             : 
    4271             : /************************************************************************/
    4272             : /*                        IsAllowedFilename()                           */
    4273             : /************************************************************************/
    4274             : 
    4275        1251 : bool VSICurlFilesystemHandlerBase::IsAllowedFilename(const char *pszFilename)
    4276             : {
    4277             :     const char *pszAllowedFilename =
    4278        1251 :         CPLGetConfigOption("CPL_VSIL_CURL_ALLOWED_FILENAME", nullptr);
    4279        1251 :     if (pszAllowedFilename != nullptr)
    4280             :     {
    4281           0 :         return strcmp(pszFilename, pszAllowedFilename) == 0;
    4282             :     }
    4283             : 
    4284             :     // Consider that only the files whose extension ends up with one that is
    4285             :     // listed in CPL_VSIL_CURL_ALLOWED_EXTENSIONS exist on the server.  This can
    4286             :     // speeds up dramatically open experience, in case the server cannot return
    4287             :     // a file list.  {noext} can be used as a special token to mean file with no
    4288             :     // extension.
    4289             :     // For example:
    4290             :     // gdalinfo --config CPL_VSIL_CURL_ALLOWED_EXTENSIONS ".tif"
    4291             :     // /vsicurl/http://igskmncngs506.cr.usgs.gov/gmted/Global_tiles_GMTED/075darcsec/bln/W030/30N030W_20101117_gmted_bln075.tif
    4292             :     const char *pszAllowedExtensions =
    4293        1251 :         CPLGetConfigOption("CPL_VSIL_CURL_ALLOWED_EXTENSIONS", nullptr);
    4294        1251 :     if (pszAllowedExtensions)
    4295             :     {
    4296             :         char **papszExtensions =
    4297          20 :             CSLTokenizeString2(pszAllowedExtensions, ", ", 0);
    4298          20 :         const char *queryStart = strchr(pszFilename, '?');
    4299          20 :         char *pszFilenameWithoutQuery = nullptr;
    4300          20 :         if (queryStart != nullptr)
    4301             :         {
    4302           0 :             pszFilenameWithoutQuery = CPLStrdup(pszFilename);
    4303           0 :             pszFilenameWithoutQuery[queryStart - pszFilename] = '\0';
    4304           0 :             pszFilename = pszFilenameWithoutQuery;
    4305             :         }
    4306          20 :         const size_t nURLLen = strlen(pszFilename);
    4307          20 :         bool bFound = false;
    4308          20 :         for (int i = 0; papszExtensions[i] != nullptr; i++)
    4309             :         {
    4310          20 :             const size_t nExtensionLen = strlen(papszExtensions[i]);
    4311          20 :             if (EQUAL(papszExtensions[i], "{noext}"))
    4312             :             {
    4313           0 :                 const char *pszLastSlash = strrchr(pszFilename, '/');
    4314           0 :                 if (pszLastSlash != nullptr &&
    4315           0 :                     strchr(pszLastSlash, '.') == nullptr)
    4316             :                 {
    4317           0 :                     bFound = true;
    4318           0 :                     break;
    4319             :                 }
    4320             :             }
    4321          20 :             else if (nURLLen > nExtensionLen &&
    4322          20 :                      EQUAL(pszFilename + nURLLen - nExtensionLen,
    4323             :                            papszExtensions[i]))
    4324             :             {
    4325          20 :                 bFound = true;
    4326          20 :                 break;
    4327             :             }
    4328             :         }
    4329             : 
    4330          20 :         CSLDestroy(papszExtensions);
    4331          20 :         if (pszFilenameWithoutQuery)
    4332             :         {
    4333           0 :             CPLFree(pszFilenameWithoutQuery);
    4334             :         }
    4335             : 
    4336          20 :         return bFound;
    4337             :     }
    4338        1231 :     return TRUE;
    4339             : }
    4340             : 
    4341             : /************************************************************************/
    4342             : /*                                Open()                                */
    4343             : /************************************************************************/
    4344             : 
    4345         468 : VSIVirtualHandle *VSICurlFilesystemHandlerBase::Open(const char *pszFilename,
    4346             :                                                      const char *pszAccess,
    4347             :                                                      bool bSetError,
    4348             :                                                      CSLConstList papszOptions)
    4349             : {
    4350         485 :     if (!STARTS_WITH_CI(pszFilename, GetFSPrefix().c_str()) &&
    4351          17 :         !STARTS_WITH_CI(pszFilename, "/vsicurl?"))
    4352           1 :         return nullptr;
    4353             : 
    4354         467 :     if (strchr(pszAccess, 'w') != nullptr || strchr(pszAccess, '+') != nullptr)
    4355             :     {
    4356           1 :         if (bSetError)
    4357             :         {
    4358           0 :             VSIError(VSIE_FileError,
    4359             :                      "Only read-only mode is supported for /vsicurl");
    4360             :         }
    4361           1 :         return nullptr;
    4362             :     }
    4363         467 :     if (!papszOptions ||
    4364           1 :         !CPLTestBool(CSLFetchNameValueDef(
    4365             :             papszOptions, "IGNORE_FILENAME_RESTRICTIONS", "NO")))
    4366             :     {
    4367         466 :         if (!IsAllowedFilename(pszFilename))
    4368           0 :             return nullptr;
    4369             :     }
    4370             : 
    4371         466 :     bool bListDir = true;
    4372         466 :     bool bEmptyDir = false;
    4373         466 :     CPL_IGNORE_RET_VAL(VSICurlGetURLFromFilename(pszFilename, nullptr, nullptr,
    4374             :                                                  nullptr, &bListDir, &bEmptyDir,
    4375             :                                                  nullptr, nullptr, nullptr));
    4376             : 
    4377         466 :     const char *pszOptionVal = CSLFetchNameValueDef(
    4378             :         papszOptions, "DISABLE_READDIR_ON_OPEN",
    4379             :         VSIGetPathSpecificOption(pszFilename, "GDAL_DISABLE_READDIR_ON_OPEN",
    4380             :                                  "NO"));
    4381             :     const bool bSkipReadDir =
    4382         466 :         !bListDir || bEmptyDir || EQUAL(pszOptionVal, "EMPTY_DIR") ||
    4383         932 :         CPLTestBool(pszOptionVal) || !AllowCachedDataFor(pszFilename);
    4384             : 
    4385         932 :     std::string osFilename(pszFilename);
    4386         466 :     bool bGotFileList = !bSkipReadDir;
    4387         466 :     bool bForceExistsCheck = false;
    4388         932 :     FileProp cachedFileProp;
    4389        1398 :     if (!(GetCachedFileProp(osFilename.c_str() + strlen(GetFSPrefix().c_str()),
    4390             :                             cachedFileProp) &&
    4391         220 :           cachedFileProp.eExists == EXIST_YES) &&
    4392         268 :         strchr(CPLGetFilename(osFilename.c_str()), '.') != nullptr &&
    4393        2025 :         !STARTS_WITH(CPLGetExtensionSafe(osFilename.c_str()).c_str(), "zip") &&
    4394         161 :         !bSkipReadDir)
    4395             :     {
    4396         135 :         char **papszFileList = ReadDirInternal(
    4397         270 :             (CPLGetDirnameSafe(osFilename.c_str()) + '/').c_str(), 0,
    4398             :             &bGotFileList);
    4399             :         const bool bFound =
    4400         135 :             VSICurlIsFileInList(papszFileList,
    4401         135 :                                 CPLGetFilename(osFilename.c_str())) != -1;
    4402         135 :         if (bGotFileList && !bFound)
    4403             :         {
    4404             :             // Some file servers are case insensitive, so in case there is a
    4405             :             // match with case difference, do a full check just in case.
    4406             :             // e.g.
    4407             :             // http://pds-geosciences.wustl.edu/mgs/mgs-m-mola-5-megdr-l3-v1/mgsl_300x/meg004/MEGA90N000CB.IMG
    4408             :             // that is queried by
    4409             :             // gdalinfo
    4410             :             // /vsicurl/http://pds-geosciences.wustl.edu/mgs/mgs-m-mola-5-megdr-l3-v1/mgsl_300x/meg004/mega90n000cb.lbl
    4411          17 :             if (CSLFindString(papszFileList,
    4412          17 :                               CPLGetFilename(osFilename.c_str())) != -1)
    4413             :             {
    4414           0 :                 bForceExistsCheck = true;
    4415             :             }
    4416             :             else
    4417             :             {
    4418          17 :                 CSLDestroy(papszFileList);
    4419          17 :                 return nullptr;
    4420             :             }
    4421             :         }
    4422         118 :         CSLDestroy(papszFileList);
    4423             :     }
    4424             : 
    4425         449 :     VSICurlHandle *poHandle = CreateFileHandle(osFilename.c_str());
    4426         449 :     if (poHandle == nullptr)
    4427          17 :         return nullptr;
    4428         432 :     if (!bGotFileList || bForceExistsCheck)
    4429             :     {
    4430             :         // If we didn't get a filelist, check that the file really exists.
    4431         138 :         if (!poHandle->Exists(bSetError))
    4432             :         {
    4433          58 :             delete poHandle;
    4434          58 :             return nullptr;
    4435             :         }
    4436             :     }
    4437             : 
    4438         374 :     if (CPLTestBool(CPLGetConfigOption("VSI_CACHE", "FALSE")))
    4439           0 :         return VSICreateCachedFile(poHandle);
    4440             :     else
    4441         374 :         return poHandle;
    4442             : }
    4443             : 
    4444             : /************************************************************************/
    4445             : /*                        VSICurlParserFindEOL()                        */
    4446             : /*                                                                      */
    4447             : /*      Small helper function for VSICurlPaseHTMLFileList() to find     */
    4448             : /*      the end of a line in the directory listing.  Either a <br>      */
    4449             : /*      or newline.                                                     */
    4450             : /************************************************************************/
    4451             : 
    4452      202785 : static char *VSICurlParserFindEOL(char *pszData)
    4453             : 
    4454             : {
    4455      202785 :     while (*pszData != '\0' && *pszData != '\n' &&
    4456      200548 :            !STARTS_WITH_CI(pszData, "<br>"))
    4457      200548 :         pszData++;
    4458             : 
    4459        2237 :     if (*pszData == '\0')
    4460          13 :         return nullptr;
    4461             : 
    4462        2224 :     return pszData;
    4463             : }
    4464             : 
    4465             : /************************************************************************/
    4466             : /*                   VSICurlParseHTMLDateTimeFileSize()                 */
    4467             : /************************************************************************/
    4468             : 
    4469             : static const char *const apszMonths[] = {
    4470             :     "January", "February", "March",     "April",   "May",      "June",
    4471             :     "July",    "August",   "September", "October", "November", "December"};
    4472             : 
    4473          30 : static bool VSICurlParseHTMLDateTimeFileSize(const char *pszStr,
    4474             :                                              struct tm &brokendowntime,
    4475             :                                              GUIntBig &nFileSize,
    4476             :                                              GIntBig &mTime)
    4477             : {
    4478         340 :     for (int iMonth = 0; iMonth < 12; iMonth++)
    4479             :     {
    4480         315 :         char szMonth[32] = {};
    4481         315 :         szMonth[0] = '-';
    4482         315 :         memcpy(szMonth + 1, apszMonths[iMonth], 3);
    4483         315 :         szMonth[4] = '-';
    4484         315 :         szMonth[5] = '\0';
    4485         315 :         const char *pszMonthFound = strstr(pszStr, szMonth);
    4486         315 :         if (pszMonthFound)
    4487             :         {
    4488             :             // Format of Apache, like in
    4489             :             // http://download.osgeo.org/gdal/data/gtiff/
    4490             :             // "17-May-2010 12:26"
    4491           5 :             if (pszMonthFound - pszStr > 2 && strlen(pszMonthFound) > 15 &&
    4492           5 :                 pszMonthFound[-2 + 11] == ' ' && pszMonthFound[-2 + 14] == ':')
    4493             :             {
    4494           2 :                 pszMonthFound -= 2;
    4495           2 :                 int nDay = atoi(pszMonthFound);
    4496           2 :                 int nYear = atoi(pszMonthFound + 7);
    4497           2 :                 int nHour = atoi(pszMonthFound + 12);
    4498           2 :                 int nMin = atoi(pszMonthFound + 15);
    4499           2 :                 if (nDay >= 1 && nDay <= 31 && nYear >= 1900 && nHour >= 0 &&
    4500           2 :                     nHour <= 24 && nMin >= 0 && nMin < 60)
    4501             :                 {
    4502           2 :                     brokendowntime.tm_year = nYear - 1900;
    4503           2 :                     brokendowntime.tm_mon = iMonth;
    4504           2 :                     brokendowntime.tm_mday = nDay;
    4505           2 :                     brokendowntime.tm_hour = nHour;
    4506           2 :                     brokendowntime.tm_min = nMin;
    4507           2 :                     mTime = CPLYMDHMSToUnixTime(&brokendowntime);
    4508             : 
    4509           5 :                     return true;
    4510             :                 }
    4511             :             }
    4512           3 :             return false;
    4513             :         }
    4514             : 
    4515             :         /* Microsoft IIS */
    4516         310 :         snprintf(szMonth, sizeof(szMonth), " %s ", apszMonths[iMonth]);
    4517         310 :         pszMonthFound = strstr(pszStr, szMonth);
    4518         310 :         if (pszMonthFound)
    4519             :         {
    4520           0 :             int nLenMonth = static_cast<int>(strlen(apszMonths[iMonth]));
    4521           0 :             if (pszMonthFound - pszStr > 2 && pszMonthFound[-1] != ',' &&
    4522           0 :                 pszMonthFound[-2] != ' ' &&
    4523           0 :                 static_cast<int>(strlen(pszMonthFound - 2)) >
    4524           0 :                     2 + 1 + nLenMonth + 1 + 4 + 1 + 5 + 1 + 4)
    4525             :             {
    4526             :                 /* Format of http://ortho.linz.govt.nz/tifs/1994_95/ */
    4527             :                 /* "        Friday, 21 April 2006 12:05 p.m.     48062343
    4528             :                  * m35a_fy_94_95.tif" */
    4529           0 :                 pszMonthFound -= 2;
    4530           0 :                 int nDay = atoi(pszMonthFound);
    4531           0 :                 int nCurOffset = 2 + 1 + nLenMonth + 1;
    4532           0 :                 int nYear = atoi(pszMonthFound + nCurOffset);
    4533           0 :                 nCurOffset += 4 + 1;
    4534           0 :                 int nHour = atoi(pszMonthFound + nCurOffset);
    4535           0 :                 if (nHour < 10)
    4536           0 :                     nCurOffset += 1 + 1;
    4537             :                 else
    4538           0 :                     nCurOffset += 2 + 1;
    4539           0 :                 const int nMin = atoi(pszMonthFound + nCurOffset);
    4540           0 :                 nCurOffset += 2 + 1;
    4541           0 :                 if (STARTS_WITH(pszMonthFound + nCurOffset, "p.m."))
    4542           0 :                     nHour += 12;
    4543           0 :                 else if (!STARTS_WITH(pszMonthFound + nCurOffset, "a.m."))
    4544           0 :                     nHour = -1;
    4545           0 :                 nCurOffset += 4;
    4546             : 
    4547           0 :                 const char *pszFilesize = pszMonthFound + nCurOffset;
    4548           0 :                 while (*pszFilesize == ' ')
    4549           0 :                     pszFilesize++;
    4550           0 :                 if (*pszFilesize >= '1' && *pszFilesize <= '9')
    4551           0 :                     nFileSize = CPLScanUIntBig(
    4552           0 :                         pszFilesize, static_cast<int>(strlen(pszFilesize)));
    4553             : 
    4554           0 :                 if (nDay >= 1 && nDay <= 31 && nYear >= 1900 && nHour >= 0 &&
    4555           0 :                     nHour <= 24 && nMin >= 0 && nMin < 60)
    4556             :                 {
    4557           0 :                     brokendowntime.tm_year = nYear - 1900;
    4558           0 :                     brokendowntime.tm_mon = iMonth;
    4559           0 :                     brokendowntime.tm_mday = nDay;
    4560           0 :                     brokendowntime.tm_hour = nHour;
    4561           0 :                     brokendowntime.tm_min = nMin;
    4562           0 :                     mTime = CPLYMDHMSToUnixTime(&brokendowntime);
    4563             : 
    4564           0 :                     return true;
    4565             :                 }
    4566           0 :                 nFileSize = 0;
    4567             :             }
    4568           0 :             else if (pszMonthFound - pszStr > 1 && pszMonthFound[-1] == ',' &&
    4569           0 :                      static_cast<int>(strlen(pszMonthFound)) >
    4570           0 :                          1 + nLenMonth + 1 + 2 + 1 + 1 + 4 + 1 + 5 + 1 + 2)
    4571             :             {
    4572             :                 // Format of
    4573             :                 // http://publicfiles.dep.state.fl.us/dear/BWR_GIS/2007NWFLULC/
    4574             :                 // "        Sunday, June 20, 2010  6:46 PM    233170905
    4575             :                 // NWF2007LULCForSDE.zip"
    4576           0 :                 pszMonthFound += 1;
    4577           0 :                 int nCurOffset = nLenMonth + 1;
    4578           0 :                 int nDay = atoi(pszMonthFound + nCurOffset);
    4579           0 :                 nCurOffset += 2 + 1 + 1;
    4580           0 :                 int nYear = atoi(pszMonthFound + nCurOffset);
    4581           0 :                 nCurOffset += 4 + 1;
    4582           0 :                 int nHour = atoi(pszMonthFound + nCurOffset);
    4583           0 :                 nCurOffset += 2 + 1;
    4584           0 :                 const int nMin = atoi(pszMonthFound + nCurOffset);
    4585           0 :                 nCurOffset += 2 + 1;
    4586           0 :                 if (STARTS_WITH(pszMonthFound + nCurOffset, "PM"))
    4587           0 :                     nHour += 12;
    4588           0 :                 else if (!STARTS_WITH(pszMonthFound + nCurOffset, "AM"))
    4589           0 :                     nHour = -1;
    4590           0 :                 nCurOffset += 2;
    4591             : 
    4592           0 :                 const char *pszFilesize = pszMonthFound + nCurOffset;
    4593           0 :                 while (*pszFilesize == ' ')
    4594           0 :                     pszFilesize++;
    4595           0 :                 if (*pszFilesize >= '1' && *pszFilesize <= '9')
    4596           0 :                     nFileSize = CPLScanUIntBig(
    4597           0 :                         pszFilesize, static_cast<int>(strlen(pszFilesize)));
    4598             : 
    4599           0 :                 if (nDay >= 1 && nDay <= 31 && nYear >= 1900 && nHour >= 0 &&
    4600           0 :                     nHour <= 24 && nMin >= 0 && nMin < 60)
    4601             :                 {
    4602           0 :                     brokendowntime.tm_year = nYear - 1900;
    4603           0 :                     brokendowntime.tm_mon = iMonth;
    4604           0 :                     brokendowntime.tm_mday = nDay;
    4605           0 :                     brokendowntime.tm_hour = nHour;
    4606           0 :                     brokendowntime.tm_min = nMin;
    4607           0 :                     mTime = CPLYMDHMSToUnixTime(&brokendowntime);
    4608             : 
    4609           0 :                     return true;
    4610             :                 }
    4611           0 :                 nFileSize = 0;
    4612             :             }
    4613           0 :             return false;
    4614             :         }
    4615             :     }
    4616             : 
    4617          25 :     return false;
    4618             : }
    4619             : 
    4620             : /************************************************************************/
    4621             : /*                          ParseHTMLFileList()                         */
    4622             : /*                                                                      */
    4623             : /*      Parse a file list document and return all the components.       */
    4624             : /************************************************************************/
    4625             : 
    4626          13 : char **VSICurlFilesystemHandlerBase::ParseHTMLFileList(const char *pszFilename,
    4627             :                                                        int nMaxFiles,
    4628             :                                                        char *pszData,
    4629             :                                                        bool *pbGotFileList)
    4630             : {
    4631          13 :     *pbGotFileList = false;
    4632             : 
    4633             :     std::string osURL(VSICurlGetURLFromFilename(pszFilename, nullptr, nullptr,
    4634             :                                                 nullptr, nullptr, nullptr,
    4635          26 :                                                 nullptr, nullptr, nullptr));
    4636          13 :     const char *pszDir = nullptr;
    4637          13 :     if (STARTS_WITH_CI(osURL.c_str(), "http://"))
    4638           4 :         pszDir = strchr(osURL.c_str() + strlen("http://"), '/');
    4639           9 :     else if (STARTS_WITH_CI(osURL.c_str(), "https://"))
    4640           9 :         pszDir = strchr(osURL.c_str() + strlen("https://"), '/');
    4641           0 :     else if (STARTS_WITH_CI(osURL.c_str(), "ftp://"))
    4642           0 :         pszDir = strchr(osURL.c_str() + strlen("ftp://"), '/');
    4643          13 :     if (pszDir == nullptr)
    4644           1 :         pszDir = "";
    4645             : 
    4646             :     /* Apache */
    4647          26 :     std::string osExpectedString = "<title>Index of ";
    4648          13 :     osExpectedString += pszDir;
    4649          13 :     osExpectedString += "</title>";
    4650             :     /* shttpd */
    4651          26 :     std::string osExpectedString2 = "<title>Index of ";
    4652          13 :     osExpectedString2 += pszDir;
    4653          13 :     osExpectedString2 += "/</title>";
    4654             :     /* FTP */
    4655          26 :     std::string osExpectedString3 = "FTP Listing of ";
    4656          13 :     osExpectedString3 += pszDir;
    4657          13 :     osExpectedString3 += "/";
    4658             :     /* Apache 1.3.33 */
    4659          26 :     std::string osExpectedString4 = "<TITLE>Index of ";
    4660          13 :     osExpectedString4 += pszDir;
    4661          13 :     osExpectedString4 += "</TITLE>";
    4662             : 
    4663             :     // The listing of
    4664             :     // http://dds.cr.usgs.gov/srtm/SRTM_image_sample/picture%20examples/
    4665             :     // has
    4666             :     // "<title>Index of /srtm/SRTM_image_sample/picture examples</title>"
    4667             :     // so we must try unescaped %20 also.
    4668             :     // Similar with
    4669             :     // http://datalib.usask.ca/gis/Data/Central_America_goodbutdoweown%3f/
    4670          26 :     std::string osExpectedString_unescaped;
    4671          13 :     if (strchr(pszDir, '%'))
    4672             :     {
    4673           0 :         char *pszUnescapedDir = CPLUnescapeString(pszDir, nullptr, CPLES_URL);
    4674           0 :         osExpectedString_unescaped = "<title>Index of ";
    4675           0 :         osExpectedString_unescaped += pszUnescapedDir;
    4676           0 :         osExpectedString_unescaped += "</title>";
    4677           0 :         CPLFree(pszUnescapedDir);
    4678             :     }
    4679             : 
    4680          13 :     char *c = nullptr;
    4681          13 :     int nCount = 0;
    4682          13 :     int nCountTable = 0;
    4683          26 :     CPLStringList oFileList;
    4684          13 :     char *pszLine = pszData;
    4685          13 :     bool bIsHTMLDirList = false;
    4686             : 
    4687        2237 :     while ((c = VSICurlParserFindEOL(pszLine)) != nullptr)
    4688             :     {
    4689        2224 :         *c = '\0';
    4690             : 
    4691             :         // To avoid false positive on pages such as
    4692             :         // http://www.ngs.noaa.gov/PC_PROD/USGG2009BETA
    4693             :         // This is a heuristics, but normal HTML listing of files have not more
    4694             :         // than one table.
    4695        2224 :         if (strstr(pszLine, "<table"))
    4696             :         {
    4697           5 :             nCountTable++;
    4698           5 :             if (nCountTable == 2)
    4699             :             {
    4700           0 :                 *pbGotFileList = false;
    4701           0 :                 return nullptr;
    4702             :             }
    4703             :         }
    4704             : 
    4705        4376 :         if (!bIsHTMLDirList &&
    4706        2152 :             (strstr(pszLine, osExpectedString.c_str()) ||
    4707        2148 :              strstr(pszLine, osExpectedString2.c_str()) ||
    4708        2147 :              strstr(pszLine, osExpectedString3.c_str()) ||
    4709        2147 :              strstr(pszLine, osExpectedString4.c_str()) ||
    4710        2147 :              (!osExpectedString_unescaped.empty() &&
    4711           0 :               strstr(pszLine, osExpectedString_unescaped.c_str()))))
    4712             :         {
    4713           5 :             bIsHTMLDirList = true;
    4714           5 :             *pbGotFileList = true;
    4715             :         }
    4716             :         // Subversion HTTP listing
    4717             :         // or Microsoft-IIS/6.0 listing
    4718             :         // (e.g. http://ortho.linz.govt.nz/tifs/2005_06/) */
    4719        2219 :         else if (!bIsHTMLDirList && strstr(pszLine, "<title>"))
    4720             :         {
    4721             :             // Detect something like:
    4722             :             // <html><head><title>gdal - Revision 20739:
    4723             :             // /trunk/autotest/gcore/data</title></head> */ The annoying thing
    4724             :             // is that what is after ': ' is a subpart of what is after
    4725             :             // http://server/
    4726           3 :             char *pszSubDir = strstr(pszLine, ": ");
    4727           3 :             if (pszSubDir == nullptr)
    4728             :                 // or <title>ortho.linz.govt.nz - /tifs/2005_06/</title>
    4729           3 :                 pszSubDir = strstr(pszLine, "- ");
    4730           3 :             if (pszSubDir)
    4731             :             {
    4732           0 :                 pszSubDir += 2;
    4733           0 :                 char *pszTmp = strstr(pszSubDir, "</title>");
    4734           0 :                 if (pszTmp)
    4735             :                 {
    4736           0 :                     if (pszTmp[-1] == '/')
    4737           0 :                         pszTmp[-1] = 0;
    4738             :                     else
    4739           0 :                         *pszTmp = 0;
    4740           0 :                     if (strstr(pszDir, pszSubDir))
    4741             :                     {
    4742           0 :                         bIsHTMLDirList = true;
    4743           0 :                         *pbGotFileList = true;
    4744             :                     }
    4745             :                 }
    4746           3 :             }
    4747             :         }
    4748        2216 :         else if (bIsHTMLDirList &&
    4749          72 :                  (strstr(pszLine, "<a href=\"") != nullptr ||
    4750          33 :                   strstr(pszLine, "<A HREF=\"") != nullptr) &&
    4751             :                  // Exclude absolute links, like to subversion home.
    4752          39 :                  strstr(pszLine, "<a href=\"http://") == nullptr &&
    4753             :                  // exclude parent directory.
    4754          39 :                  strstr(pszLine, "Parent Directory") == nullptr)
    4755             :         {
    4756          35 :             char *beginFilename = strstr(pszLine, "<a href=\"");
    4757          35 :             if (beginFilename == nullptr)
    4758           0 :                 beginFilename = strstr(pszLine, "<A HREF=\"");
    4759          35 :             beginFilename += strlen("<a href=\"");
    4760          35 :             char *endQuote = strchr(beginFilename, '"');
    4761          35 :             if (endQuote && !STARTS_WITH(beginFilename, "?C=") &&
    4762          30 :                 !STARTS_WITH(beginFilename, "?N="))
    4763             :             {
    4764             :                 struct tm brokendowntime;
    4765          30 :                 memset(&brokendowntime, 0, sizeof(brokendowntime));
    4766          30 :                 GUIntBig nFileSize = 0;
    4767          30 :                 GIntBig mTime = 0;
    4768             : 
    4769          30 :                 VSICurlParseHTMLDateTimeFileSize(pszLine, brokendowntime,
    4770             :                                                  nFileSize, mTime);
    4771             : 
    4772          30 :                 *endQuote = '\0';
    4773             : 
    4774             :                 // Remove trailing slash, that are returned for directories by
    4775             :                 // Apache.
    4776          30 :                 bool bIsDirectory = false;
    4777          30 :                 if (endQuote[-1] == '/')
    4778             :                 {
    4779           3 :                     bIsDirectory = true;
    4780           3 :                     endQuote[-1] = 0;
    4781             :                 }
    4782             : 
    4783             :                 // shttpd links include slashes from the root directory.
    4784             :                 // Skip them.
    4785          30 :                 while (strchr(beginFilename, '/'))
    4786           0 :                     beginFilename = strchr(beginFilename, '/') + 1;
    4787             : 
    4788          30 :                 if (strcmp(beginFilename, ".") != 0 &&
    4789          30 :                     strcmp(beginFilename, "..") != 0)
    4790             :                 {
    4791             :                     std::string osCachedFilename =
    4792          29 :                         CPLSPrintf("%s/%s", osURL.c_str(), beginFilename);
    4793             : 
    4794          29 :                     FileProp cachedFileProp;
    4795          29 :                     GetCachedFileProp(osCachedFilename.c_str(), cachedFileProp);
    4796          29 :                     cachedFileProp.eExists = EXIST_YES;
    4797          29 :                     cachedFileProp.bIsDirectory = bIsDirectory;
    4798          29 :                     cachedFileProp.mTime = static_cast<time_t>(mTime);
    4799          29 :                     cachedFileProp.bHasComputedFileSize = nFileSize > 0;
    4800          29 :                     cachedFileProp.fileSize = nFileSize;
    4801          29 :                     SetCachedFileProp(osCachedFilename.c_str(), cachedFileProp);
    4802             : 
    4803          29 :                     oFileList.AddString(beginFilename);
    4804             :                     if (ENABLE_DEBUG_VERBOSE)
    4805             :                     {
    4806             :                         CPLDebug(
    4807             :                             GetDebugKey(),
    4808             :                             "File[%d] = %s, is_dir = %d, size = " CPL_FRMT_GUIB
    4809             :                             ", time = %04d/%02d/%02d %02d:%02d:%02d",
    4810             :                             nCount, osCachedFilename.c_str(),
    4811             :                             bIsDirectory ? 1 : 0, nFileSize,
    4812             :                             brokendowntime.tm_year + 1900,
    4813             :                             brokendowntime.tm_mon + 1, brokendowntime.tm_mday,
    4814             :                             brokendowntime.tm_hour, brokendowntime.tm_min,
    4815             :                             brokendowntime.tm_sec);
    4816             :                     }
    4817          29 :                     nCount++;
    4818             : 
    4819          29 :                     if (nMaxFiles > 0 && oFileList.Count() > nMaxFiles)
    4820           0 :                         break;
    4821             :                 }
    4822             :             }
    4823             :         }
    4824        2224 :         pszLine = c + 1;
    4825             :     }
    4826             : 
    4827          13 :     return oFileList.StealList();
    4828             : }
    4829             : 
    4830             : /************************************************************************/
    4831             : /*                      GetStreamingFilename()                          */
    4832             : /************************************************************************/
    4833             : 
    4834           1 : std::string VSICurlFilesystemHandler::GetStreamingFilename(
    4835             :     const std::string &osFilename) const
    4836             : {
    4837           1 :     if (STARTS_WITH(osFilename.c_str(), GetFSPrefix().c_str()))
    4838           2 :         return "/vsicurl_streaming/" + osFilename.substr(GetFSPrefix().size());
    4839           0 :     return osFilename;
    4840             : }
    4841             : 
    4842             : /************************************************************************/
    4843             : /*                         VSICurlGetToken()                            */
    4844             : /************************************************************************/
    4845             : 
    4846           0 : static char *VSICurlGetToken(char *pszCurPtr, char **ppszNextToken)
    4847             : {
    4848           0 :     if (pszCurPtr == nullptr)
    4849           0 :         return nullptr;
    4850             : 
    4851           0 :     while ((*pszCurPtr) == ' ')
    4852           0 :         pszCurPtr++;
    4853           0 :     if (*pszCurPtr == '\0')
    4854           0 :         return nullptr;
    4855             : 
    4856           0 :     char *pszToken = pszCurPtr;
    4857           0 :     while ((*pszCurPtr) != ' ' && (*pszCurPtr) != '\0')
    4858           0 :         pszCurPtr++;
    4859           0 :     if (*pszCurPtr == '\0')
    4860             :     {
    4861           0 :         *ppszNextToken = nullptr;
    4862             :     }
    4863             :     else
    4864             :     {
    4865           0 :         *pszCurPtr = '\0';
    4866           0 :         pszCurPtr++;
    4867           0 :         while ((*pszCurPtr) == ' ')
    4868           0 :             pszCurPtr++;
    4869           0 :         *ppszNextToken = pszCurPtr;
    4870             :     }
    4871             : 
    4872           0 :     return pszToken;
    4873             : }
    4874             : 
    4875             : /************************************************************************/
    4876             : /*                    VSICurlParseFullFTPLine()                         */
    4877             : /************************************************************************/
    4878             : 
    4879             : /* Parse lines like the following ones :
    4880             : -rw-r--r--    1 10003    100           430 Jul 04  2008 COPYING
    4881             : lrwxrwxrwx    1 ftp      ftp            28 Jun 14 14:13 MPlayer ->
    4882             : mirrors/mplayerhq.hu/MPlayer -rw-r--r--    1 ftp      ftp      725614592 May 13
    4883             : 20:13 Fedora-15-x86_64-Live-KDE.iso drwxr-xr-x  280 1003  1003  6656 Aug 26
    4884             : 04:17 gnu
    4885             : */
    4886             : 
    4887           0 : static bool VSICurlParseFullFTPLine(char *pszLine, char *&pszFilename,
    4888             :                                     bool &bSizeValid, GUIntBig &nSize,
    4889             :                                     bool &bIsDirectory, GIntBig &nUnixTime)
    4890             : {
    4891           0 :     char *pszNextToken = pszLine;
    4892           0 :     char *pszPermissions = VSICurlGetToken(pszNextToken, &pszNextToken);
    4893           0 :     if (pszPermissions == nullptr || strlen(pszPermissions) != 10)
    4894           0 :         return false;
    4895           0 :     bIsDirectory = pszPermissions[0] == 'd';
    4896             : 
    4897           0 :     for (int i = 0; i < 3; i++)
    4898             :     {
    4899           0 :         if (VSICurlGetToken(pszNextToken, &pszNextToken) == nullptr)
    4900           0 :             return false;
    4901             :     }
    4902             : 
    4903           0 :     char *pszSize = VSICurlGetToken(pszNextToken, &pszNextToken);
    4904           0 :     if (pszSize == nullptr)
    4905           0 :         return false;
    4906             : 
    4907           0 :     if (pszPermissions[0] == '-')
    4908             :     {
    4909             :         // Regular file.
    4910           0 :         bSizeValid = true;
    4911           0 :         nSize = CPLScanUIntBig(pszSize, static_cast<int>(strlen(pszSize)));
    4912             :     }
    4913             : 
    4914             :     struct tm brokendowntime;
    4915           0 :     memset(&brokendowntime, 0, sizeof(brokendowntime));
    4916           0 :     bool bBrokenDownTimeValid = true;
    4917             : 
    4918           0 :     char *pszMonth = VSICurlGetToken(pszNextToken, &pszNextToken);
    4919           0 :     if (pszMonth == nullptr || strlen(pszMonth) != 3)
    4920           0 :         return false;
    4921             : 
    4922           0 :     int i = 0;  // Used after for.
    4923           0 :     for (; i < 12; i++)
    4924             :     {
    4925           0 :         if (EQUALN(pszMonth, apszMonths[i], 3))
    4926           0 :             break;
    4927             :     }
    4928           0 :     if (i < 12)
    4929           0 :         brokendowntime.tm_mon = i;
    4930             :     else
    4931           0 :         bBrokenDownTimeValid = false;
    4932             : 
    4933           0 :     char *pszDay = VSICurlGetToken(pszNextToken, &pszNextToken);
    4934           0 :     if (pszDay == nullptr || (strlen(pszDay) != 1 && strlen(pszDay) != 2))
    4935           0 :         return false;
    4936           0 :     int nDay = atoi(pszDay);
    4937           0 :     if (nDay >= 1 && nDay <= 31)
    4938           0 :         brokendowntime.tm_mday = nDay;
    4939             :     else
    4940           0 :         bBrokenDownTimeValid = false;
    4941             : 
    4942           0 :     char *pszHourOrYear = VSICurlGetToken(pszNextToken, &pszNextToken);
    4943           0 :     if (pszHourOrYear == nullptr ||
    4944           0 :         (strlen(pszHourOrYear) != 4 && strlen(pszHourOrYear) != 5))
    4945           0 :         return false;
    4946           0 :     if (strlen(pszHourOrYear) == 4)
    4947             :     {
    4948           0 :         brokendowntime.tm_year = atoi(pszHourOrYear) - 1900;
    4949             :     }
    4950             :     else
    4951             :     {
    4952             :         time_t sTime;
    4953           0 :         time(&sTime);
    4954             :         struct tm currentBrokendowntime;
    4955           0 :         CPLUnixTimeToYMDHMS(static_cast<GIntBig>(sTime),
    4956             :                             &currentBrokendowntime);
    4957           0 :         brokendowntime.tm_year = currentBrokendowntime.tm_year;
    4958           0 :         brokendowntime.tm_hour = atoi(pszHourOrYear);
    4959           0 :         brokendowntime.tm_min = atoi(pszHourOrYear + 3);
    4960             :     }
    4961             : 
    4962           0 :     if (bBrokenDownTimeValid)
    4963           0 :         nUnixTime = CPLYMDHMSToUnixTime(&brokendowntime);
    4964             :     else
    4965           0 :         nUnixTime = 0;
    4966             : 
    4967           0 :     if (pszNextToken == nullptr)
    4968           0 :         return false;
    4969             : 
    4970           0 :     pszFilename = pszNextToken;
    4971             : 
    4972           0 :     char *pszCurPtr = pszFilename;
    4973           0 :     while (*pszCurPtr != '\0')
    4974             :     {
    4975             :         // In case of a link, stop before the pointed part of the link.
    4976           0 :         if (pszPermissions[0] == 'l' && STARTS_WITH(pszCurPtr, " -> "))
    4977             :         {
    4978           0 :             break;
    4979             :         }
    4980           0 :         pszCurPtr++;
    4981             :     }
    4982           0 :     *pszCurPtr = '\0';
    4983             : 
    4984           0 :     return true;
    4985             : }
    4986             : 
    4987             : /************************************************************************/
    4988             : /*                          GetURLFromFilename()                         */
    4989             : /************************************************************************/
    4990             : 
    4991         105 : std::string VSICurlFilesystemHandlerBase::GetURLFromFilename(
    4992             :     const std::string &osFilename) const
    4993             : {
    4994             :     return VSICurlGetURLFromFilename(osFilename.c_str(), nullptr, nullptr,
    4995             :                                      nullptr, nullptr, nullptr, nullptr,
    4996         105 :                                      nullptr, nullptr);
    4997             : }
    4998             : 
    4999             : /************************************************************************/
    5000             : /*                         RegisterEmptyDir()                           */
    5001             : /************************************************************************/
    5002             : 
    5003          14 : void VSICurlFilesystemHandlerBase::RegisterEmptyDir(
    5004             :     const std::string &osDirname)
    5005             : {
    5006          28 :     CachedDirList cachedDirList;
    5007          14 :     cachedDirList.bGotFileList = true;
    5008          14 :     cachedDirList.oFileList.AddString(".");
    5009          14 :     SetCachedDirList(osDirname.c_str(), cachedDirList);
    5010          14 : }
    5011             : 
    5012             : /************************************************************************/
    5013             : /*                          GetFileList()                               */
    5014             : /************************************************************************/
    5015             : 
    5016          42 : char **VSICurlFilesystemHandlerBase::GetFileList(const char *pszDirname,
    5017             :                                                  int nMaxFiles,
    5018             :                                                  bool *pbGotFileList)
    5019             : {
    5020             :     if (ENABLE_DEBUG)
    5021          42 :         CPLDebug(GetDebugKey(), "GetFileList(%s)", pszDirname);
    5022             : 
    5023          42 :     *pbGotFileList = false;
    5024             : 
    5025          42 :     bool bListDir = true;
    5026          42 :     bool bEmptyDir = false;
    5027             :     std::string osURL(VSICurlGetURLFromFilename(pszDirname, nullptr, nullptr,
    5028             :                                                 nullptr, &bListDir, &bEmptyDir,
    5029          84 :                                                 nullptr, nullptr, nullptr));
    5030          42 :     if (bEmptyDir)
    5031             :     {
    5032           1 :         *pbGotFileList = true;
    5033           1 :         return CSLAddString(nullptr, ".");
    5034             :     }
    5035          41 :     if (!bListDir)
    5036           0 :         return nullptr;
    5037             : 
    5038             :     // Deal with publicly visible Azure directories.
    5039          41 :     if (STARTS_WITH(osURL.c_str(), "https://"))
    5040             :     {
    5041             :         const char *pszBlobCore =
    5042          10 :             strstr(osURL.c_str(), ".blob.core.windows.net/");
    5043          10 :         if (pszBlobCore)
    5044             :         {
    5045           2 :             FileProp cachedFileProp;
    5046           2 :             GetCachedFileProp(osURL.c_str(), cachedFileProp);
    5047           2 :             if (cachedFileProp.bIsAzureFolder)
    5048             :             {
    5049             :                 const char *pszURLWithoutHTTPS =
    5050           1 :                     osURL.c_str() + strlen("https://");
    5051             :                 const std::string osStorageAccount(
    5052           1 :                     pszURLWithoutHTTPS, pszBlobCore - pszURLWithoutHTTPS);
    5053             :                 CPLConfigOptionSetter oSetter1("AZURE_NO_SIGN_REQUEST", "YES",
    5054           1 :                                                false);
    5055             :                 CPLConfigOptionSetter oSetter2("AZURE_STORAGE_ACCOUNT",
    5056           1 :                                                osStorageAccount.c_str(), false);
    5057           2 :                 const std::string osVSIAZ(std::string("/vsiaz/").append(
    5058           1 :                     pszBlobCore + strlen(".blob.core.windows.net/")));
    5059           1 :                 char **papszFileList = VSIReadDirEx(osVSIAZ.c_str(), nMaxFiles);
    5060           1 :                 if (papszFileList)
    5061             :                 {
    5062           1 :                     *pbGotFileList = true;
    5063           1 :                     return papszFileList;
    5064             :                 }
    5065             :             }
    5066             :         }
    5067             :     }
    5068             : 
    5069             :     // HACK (optimization in fact) for MBTiles driver.
    5070          40 :     if (strstr(pszDirname, ".tiles.mapbox.com") != nullptr)
    5071           1 :         return nullptr;
    5072             : 
    5073          39 :     if (STARTS_WITH(osURL.c_str(), "ftp://"))
    5074             :     {
    5075           0 :         WriteFuncStruct sWriteFuncData;
    5076           0 :         sWriteFuncData.pBuffer = nullptr;
    5077             : 
    5078           0 :         std::string osDirname(osURL);
    5079           0 :         osDirname += '/';
    5080             : 
    5081           0 :         char **papszFileList = nullptr;
    5082             : 
    5083           0 :         CURLM *hCurlMultiHandle = GetCurlMultiHandleFor(osDirname);
    5084           0 :         CURL *hCurlHandle = curl_easy_init();
    5085             : 
    5086           0 :         for (int iTry = 0; iTry < 2; iTry++)
    5087             :         {
    5088             :             struct curl_slist *headers =
    5089           0 :                 VSICurlSetOptions(hCurlHandle, osDirname.c_str(), nullptr);
    5090             : 
    5091             :             // On the first pass, we want to try fetching all the possible
    5092             :             // information (filename, file/directory, size). If that does not
    5093             :             // work, then try again with CURLOPT_DIRLISTONLY set.
    5094           0 :             if (iTry == 1)
    5095             :             {
    5096           0 :                 unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_DIRLISTONLY, 1);
    5097             :             }
    5098             : 
    5099           0 :             VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr,
    5100             :                                        nullptr);
    5101           0 :             unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
    5102             :                                        &sWriteFuncData);
    5103           0 :             unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    5104             :                                        VSICurlHandleWriteFunc);
    5105             : 
    5106           0 :             char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
    5107           0 :             unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
    5108             :                                        szCurlErrBuf);
    5109             : 
    5110           0 :             unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER,
    5111             :                                        headers);
    5112             : 
    5113           0 :             VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle);
    5114             : 
    5115           0 :             curl_slist_free_all(headers);
    5116             : 
    5117           0 :             if (sWriteFuncData.pBuffer == nullptr)
    5118             :             {
    5119           0 :                 curl_easy_cleanup(hCurlHandle);
    5120           0 :                 return nullptr;
    5121             :             }
    5122             : 
    5123           0 :             char *pszLine = sWriteFuncData.pBuffer;
    5124           0 :             char *c = nullptr;
    5125           0 :             int nCount = 0;
    5126             : 
    5127           0 :             if (STARTS_WITH_CI(pszLine, "<!DOCTYPE HTML") ||
    5128           0 :                 STARTS_WITH_CI(pszLine, "<HTML>"))
    5129             :             {
    5130             :                 papszFileList =
    5131           0 :                     ParseHTMLFileList(pszDirname, nMaxFiles,
    5132             :                                       sWriteFuncData.pBuffer, pbGotFileList);
    5133           0 :                 break;
    5134             :             }
    5135           0 :             else if (iTry == 0)
    5136             :             {
    5137           0 :                 CPLStringList oFileList;
    5138           0 :                 *pbGotFileList = true;
    5139             : 
    5140           0 :                 while ((c = strchr(pszLine, '\n')) != nullptr)
    5141             :                 {
    5142           0 :                     *c = 0;
    5143           0 :                     if (c - pszLine > 0 && c[-1] == '\r')
    5144           0 :                         c[-1] = 0;
    5145             : 
    5146           0 :                     char *pszFilename = nullptr;
    5147           0 :                     bool bSizeValid = false;
    5148           0 :                     GUIntBig nFileSize = 0;
    5149           0 :                     bool bIsDirectory = false;
    5150           0 :                     GIntBig mUnixTime = 0;
    5151           0 :                     if (!VSICurlParseFullFTPLine(pszLine, pszFilename,
    5152             :                                                  bSizeValid, nFileSize,
    5153             :                                                  bIsDirectory, mUnixTime))
    5154           0 :                         break;
    5155             : 
    5156           0 :                     if (strcmp(pszFilename, ".") != 0 &&
    5157           0 :                         strcmp(pszFilename, "..") != 0)
    5158             :                     {
    5159             :                         std::string osCachedFilename =
    5160           0 :                             CPLSPrintf("%s/%s", osURL.c_str(), pszFilename);
    5161             : 
    5162           0 :                         FileProp cachedFileProp;
    5163           0 :                         GetCachedFileProp(osCachedFilename.c_str(),
    5164             :                                           cachedFileProp);
    5165           0 :                         cachedFileProp.eExists = EXIST_YES;
    5166           0 :                         cachedFileProp.bIsDirectory = bIsDirectory;
    5167           0 :                         cachedFileProp.mTime = static_cast<time_t>(mUnixTime);
    5168           0 :                         cachedFileProp.bHasComputedFileSize = bSizeValid;
    5169           0 :                         cachedFileProp.fileSize = nFileSize;
    5170           0 :                         SetCachedFileProp(osCachedFilename.c_str(),
    5171             :                                           cachedFileProp);
    5172             : 
    5173           0 :                         oFileList.AddString(pszFilename);
    5174             :                         if (ENABLE_DEBUG_VERBOSE)
    5175             :                         {
    5176             :                             struct tm brokendowntime;
    5177             :                             CPLUnixTimeToYMDHMS(mUnixTime, &brokendowntime);
    5178             :                             CPLDebug(
    5179             :                                 GetDebugKey(),
    5180             :                                 "File[%d] = %s, is_dir = %d, size "
    5181             :                                 "= " CPL_FRMT_GUIB
    5182             :                                 ", time = %04d/%02d/%02d %02d:%02d:%02d",
    5183             :                                 nCount, pszFilename, bIsDirectory ? 1 : 0,
    5184             :                                 nFileSize, brokendowntime.tm_year + 1900,
    5185             :                                 brokendowntime.tm_mon + 1,
    5186             :                                 brokendowntime.tm_mday, brokendowntime.tm_hour,
    5187             :                                 brokendowntime.tm_min, brokendowntime.tm_sec);
    5188             :                         }
    5189             : 
    5190           0 :                         nCount++;
    5191             : 
    5192           0 :                         if (nMaxFiles > 0 && oFileList.Count() > nMaxFiles)
    5193           0 :                             break;
    5194             :                     }
    5195             : 
    5196           0 :                     pszLine = c + 1;
    5197             :                 }
    5198             : 
    5199           0 :                 if (c == nullptr)
    5200             :                 {
    5201           0 :                     papszFileList = oFileList.StealList();
    5202           0 :                     break;
    5203             :                 }
    5204             :             }
    5205             :             else
    5206             :             {
    5207           0 :                 CPLStringList oFileList;
    5208           0 :                 *pbGotFileList = true;
    5209             : 
    5210           0 :                 while ((c = strchr(pszLine, '\n')) != nullptr)
    5211             :                 {
    5212           0 :                     *c = 0;
    5213           0 :                     if (c - pszLine > 0 && c[-1] == '\r')
    5214           0 :                         c[-1] = 0;
    5215             : 
    5216           0 :                     if (strcmp(pszLine, ".") != 0 && strcmp(pszLine, "..") != 0)
    5217             :                     {
    5218           0 :                         oFileList.AddString(pszLine);
    5219             :                         if (ENABLE_DEBUG_VERBOSE)
    5220             :                         {
    5221             :                             CPLDebug(GetDebugKey(), "File[%d] = %s", nCount,
    5222             :                                      pszLine);
    5223             :                         }
    5224           0 :                         nCount++;
    5225             :                     }
    5226             : 
    5227           0 :                     pszLine = c + 1;
    5228             :                 }
    5229             : 
    5230           0 :                 papszFileList = oFileList.StealList();
    5231             :             }
    5232             : 
    5233           0 :             CPLFree(sWriteFuncData.pBuffer);
    5234           0 :             sWriteFuncData.pBuffer = nullptr;
    5235             :         }
    5236             : 
    5237           0 :         CPLFree(sWriteFuncData.pBuffer);
    5238           0 :         curl_easy_cleanup(hCurlHandle);
    5239             : 
    5240           0 :         return papszFileList;
    5241             :     }
    5242             : 
    5243             :     // Try to recognize HTML pages that list the content of a directory.
    5244             :     // Currently this supports what Apache and shttpd can return.
    5245          48 :     else if (STARTS_WITH(osURL.c_str(), "http://") ||
    5246           9 :              STARTS_WITH(osURL.c_str(), "https://"))
    5247             :     {
    5248          78 :         std::string osDirname(std::move(osURL));
    5249          39 :         osDirname += '/';
    5250             : 
    5251          39 :         CURLM *hCurlMultiHandle = GetCurlMultiHandleFor(osDirname);
    5252          39 :         CURL *hCurlHandle = curl_easy_init();
    5253             : 
    5254             :         struct curl_slist *headers =
    5255          39 :             VSICurlSetOptions(hCurlHandle, osDirname.c_str(), nullptr);
    5256             : 
    5257          39 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
    5258             : 
    5259          39 :         WriteFuncStruct sWriteFuncData;
    5260          39 :         VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
    5261          39 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
    5262             :                                    &sWriteFuncData);
    5263          39 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    5264             :                                    VSICurlHandleWriteFunc);
    5265             : 
    5266          39 :         char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
    5267          39 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
    5268             :                                    szCurlErrBuf);
    5269             : 
    5270          39 :         unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    5271             : 
    5272          39 :         VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle);
    5273             : 
    5274          39 :         curl_slist_free_all(headers);
    5275             : 
    5276          39 :         NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
    5277             : 
    5278          39 :         if (sWriteFuncData.pBuffer == nullptr)
    5279             :         {
    5280          26 :             curl_easy_cleanup(hCurlHandle);
    5281          26 :             return nullptr;
    5282             :         }
    5283             : 
    5284          13 :         char **papszFileList = nullptr;
    5285          13 :         if (STARTS_WITH_CI(sWriteFuncData.pBuffer, "<?xml") &&
    5286           1 :             strstr(sWriteFuncData.pBuffer, "<ListBucketResult") != nullptr)
    5287             :         {
    5288           0 :             CPLStringList osFileList;
    5289           0 :             std::string osBaseURL(pszDirname);
    5290           0 :             osBaseURL += "/";
    5291           0 :             bool bIsTruncated = true;
    5292           0 :             bool ret = AnalyseS3FileList(
    5293           0 :                 osBaseURL, sWriteFuncData.pBuffer, osFileList, nMaxFiles,
    5294           0 :                 GetS3IgnoredStorageClasses(), bIsTruncated);
    5295             :             // If the list is truncated, then don't report it.
    5296           0 :             if (ret && !bIsTruncated)
    5297             :             {
    5298           0 :                 if (osFileList.empty())
    5299             :                 {
    5300             :                     // To avoid an error to be reported
    5301           0 :                     osFileList.AddString(".");
    5302             :                 }
    5303           0 :                 papszFileList = osFileList.StealList();
    5304           0 :                 *pbGotFileList = true;
    5305           0 :             }
    5306             :         }
    5307             :         else
    5308             :         {
    5309          13 :             papszFileList = ParseHTMLFileList(
    5310             :                 pszDirname, nMaxFiles, sWriteFuncData.pBuffer, pbGotFileList);
    5311             :         }
    5312             : 
    5313          13 :         CPLFree(sWriteFuncData.pBuffer);
    5314          13 :         curl_easy_cleanup(hCurlHandle);
    5315          13 :         return papszFileList;
    5316             :     }
    5317             : 
    5318           0 :     return nullptr;
    5319             : }
    5320             : 
    5321             : /************************************************************************/
    5322             : /*                       GetS3IgnoredStorageClasses()                   */
    5323             : /************************************************************************/
    5324             : 
    5325          61 : std::set<std::string> VSICurlFilesystemHandlerBase::GetS3IgnoredStorageClasses()
    5326             : {
    5327          61 :     std::set<std::string> oSetIgnoredStorageClasses;
    5328             :     const char *pszIgnoredStorageClasses =
    5329          61 :         CPLGetConfigOption("CPL_VSIL_CURL_IGNORE_STORAGE_CLASSES", nullptr);
    5330             :     const char *pszIgnoreGlacierStorage =
    5331          61 :         CPLGetConfigOption("CPL_VSIL_CURL_IGNORE_GLACIER_STORAGE", nullptr);
    5332             :     CPLStringList aosIgnoredStorageClasses(
    5333             :         CSLTokenizeString2(pszIgnoredStorageClasses ? pszIgnoredStorageClasses
    5334             :                                                     : "GLACIER,DEEP_ARCHIVE",
    5335         122 :                            ",", 0));
    5336         181 :     for (int i = 0; i < aosIgnoredStorageClasses.size(); ++i)
    5337         120 :         oSetIgnoredStorageClasses.insert(aosIgnoredStorageClasses[i]);
    5338          60 :     if (pszIgnoredStorageClasses == nullptr &&
    5339         121 :         pszIgnoreGlacierStorage != nullptr &&
    5340           1 :         !CPLTestBool(pszIgnoreGlacierStorage))
    5341             :     {
    5342           1 :         oSetIgnoredStorageClasses.clear();
    5343             :     }
    5344         122 :     return oSetIgnoredStorageClasses;
    5345             : }
    5346             : 
    5347             : /************************************************************************/
    5348             : /*                                Stat()                                */
    5349             : /************************************************************************/
    5350             : 
    5351         609 : int VSICurlFilesystemHandlerBase::Stat(const char *pszFilename,
    5352             :                                        VSIStatBufL *pStatBuf, int nFlags)
    5353             : {
    5354         628 :     if (!STARTS_WITH_CI(pszFilename, GetFSPrefix().c_str()) &&
    5355          19 :         !STARTS_WITH_CI(pszFilename, "/vsicurl?"))
    5356           1 :         return -1;
    5357             : 
    5358         608 :     memset(pStatBuf, 0, sizeof(VSIStatBufL));
    5359             : 
    5360         608 :     if ((nFlags & VSI_STAT_CACHE_ONLY) != 0)
    5361             :     {
    5362          18 :         cpl::FileProp oFileProp;
    5363          27 :         if (!GetCachedFileProp(GetURLFromFilename(pszFilename).c_str(),
    5364          32 :                                oFileProp) ||
    5365           5 :             oFileProp.eExists != EXIST_YES)
    5366             :         {
    5367           4 :             return -1;
    5368             :         }
    5369           5 :         pStatBuf->st_mode = static_cast<unsigned short>(oFileProp.nMode);
    5370           5 :         pStatBuf->st_mtime = oFileProp.mTime;
    5371           5 :         pStatBuf->st_size = oFileProp.fileSize;
    5372           5 :         return 0;
    5373             :     }
    5374             : 
    5375        1198 :     NetworkStatisticsFileSystem oContextFS(GetFSPrefix().c_str());
    5376        1198 :     NetworkStatisticsAction oContextAction("Stat");
    5377             : 
    5378        1198 :     const std::string osFilename(pszFilename);
    5379             : 
    5380         599 :     if (!IsAllowedFilename(pszFilename))
    5381           0 :         return -1;
    5382             : 
    5383         599 :     bool bListDir = true;
    5384         599 :     bool bEmptyDir = false;
    5385             :     std::string osURL(VSICurlGetURLFromFilename(pszFilename, nullptr, nullptr,
    5386             :                                                 nullptr, &bListDir, &bEmptyDir,
    5387        1198 :                                                 nullptr, nullptr, nullptr));
    5388             : 
    5389         599 :     const char *pszOptionVal = VSIGetPathSpecificOption(
    5390             :         pszFilename, "GDAL_DISABLE_READDIR_ON_OPEN", "NO");
    5391             :     const bool bSkipReadDir =
    5392         599 :         !bListDir || bEmptyDir || EQUAL(pszOptionVal, "EMPTY_DIR") ||
    5393        1198 :         CPLTestBool(pszOptionVal) || !AllowCachedDataFor(pszFilename);
    5394             : 
    5395             :     // Does it look like a FTP directory?
    5396         599 :     if (STARTS_WITH(osURL.c_str(), "ftp://") && osFilename.back() == '/' &&
    5397           0 :         !bSkipReadDir)
    5398             :     {
    5399           0 :         char **papszFileList = ReadDirEx(osFilename.c_str(), 0);
    5400           0 :         if (papszFileList)
    5401             :         {
    5402           0 :             pStatBuf->st_mode = S_IFDIR;
    5403           0 :             pStatBuf->st_size = 0;
    5404             : 
    5405           0 :             CSLDestroy(papszFileList);
    5406             : 
    5407           0 :             return 0;
    5408             :         }
    5409           0 :         return -1;
    5410             :     }
    5411         599 :     else if (strchr(CPLGetFilename(osFilename.c_str()), '.') != nullptr &&
    5412        1097 :              !STARTS_WITH_CI(CPLGetExtensionSafe(osFilename.c_str()).c_str(),
    5413         362 :                              "zip") &&
    5414         362 :              strstr(osFilename.c_str(), ".zip.") != nullptr &&
    5415        1696 :              strstr(osFilename.c_str(), ".ZIP.") != nullptr && !bSkipReadDir)
    5416             :     {
    5417           0 :         bool bGotFileList = false;
    5418           0 :         char **papszFileList = ReadDirInternal(
    5419           0 :             CPLGetDirnameSafe(osFilename.c_str()).c_str(), 0, &bGotFileList);
    5420             :         const bool bFound =
    5421           0 :             VSICurlIsFileInList(papszFileList,
    5422           0 :                                 CPLGetFilename(osFilename.c_str())) != -1;
    5423           0 :         CSLDestroy(papszFileList);
    5424           0 :         if (bGotFileList && !bFound)
    5425             :         {
    5426           0 :             return -1;
    5427             :         }
    5428             :     }
    5429             : 
    5430         599 :     VSICurlHandle *poHandle = CreateFileHandle(osFilename.c_str());
    5431         599 :     if (poHandle == nullptr)
    5432          11 :         return -1;
    5433             : 
    5434         896 :     if (poHandle->IsKnownFileSize() ||
    5435         308 :         ((nFlags & VSI_STAT_SIZE_FLAG) && !poHandle->IsDirectory() &&
    5436         167 :          CPLTestBool(CPLGetConfigOption("CPL_VSIL_CURL_SLOW_GET_SIZE", "YES"))))
    5437             :     {
    5438         447 :         pStatBuf->st_size = poHandle->GetFileSize(true);
    5439             :     }
    5440             : 
    5441             :     const int nRet =
    5442         588 :         poHandle->Exists((nFlags & VSI_STAT_SET_ERROR_FLAG) > 0) ? 0 : -1;
    5443         588 :     pStatBuf->st_mtime = poHandle->GetMTime();
    5444         588 :     pStatBuf->st_mode = static_cast<unsigned short>(poHandle->GetMode());
    5445         588 :     if (pStatBuf->st_mode == 0)
    5446         550 :         pStatBuf->st_mode = poHandle->IsDirectory() ? S_IFDIR : S_IFREG;
    5447         588 :     delete poHandle;
    5448         588 :     return nRet;
    5449             : }
    5450             : 
    5451             : /************************************************************************/
    5452             : /*                             ReadDirInternal()                        */
    5453             : /************************************************************************/
    5454             : 
    5455         271 : char **VSICurlFilesystemHandlerBase::ReadDirInternal(const char *pszDirname,
    5456             :                                                      int nMaxFiles,
    5457             :                                                      bool *pbGotFileList)
    5458             : {
    5459         542 :     std::string osDirname(pszDirname);
    5460             : 
    5461             :     // Replace a/b/../c by a/c
    5462         271 :     const auto posSlashDotDot = osDirname.find("/..");
    5463         271 :     if (posSlashDotDot != std::string::npos && posSlashDotDot >= 1)
    5464             :     {
    5465             :         const auto posPrecedingSlash =
    5466           0 :             osDirname.find_last_of('/', posSlashDotDot - 1);
    5467           0 :         if (posPrecedingSlash != std::string::npos && posPrecedingSlash >= 1)
    5468             :         {
    5469           0 :             osDirname.erase(osDirname.begin() + posPrecedingSlash,
    5470           0 :                             osDirname.begin() + posSlashDotDot + strlen("/.."));
    5471             :         }
    5472             :     }
    5473             : 
    5474         542 :     std::string osDirnameOri(osDirname);
    5475         271 :     if (osDirname + "/" == GetFSPrefix())
    5476             :     {
    5477           0 :         osDirname += "/";
    5478             :     }
    5479         271 :     else if (osDirname != GetFSPrefix())
    5480             :     {
    5481         418 :         while (!osDirname.empty() && osDirname.back() == '/')
    5482         164 :             osDirname.erase(osDirname.size() - 1);
    5483             :     }
    5484             : 
    5485         271 :     if (osDirname.size() < GetFSPrefix().size())
    5486             :     {
    5487           0 :         if (pbGotFileList)
    5488           0 :             *pbGotFileList = true;
    5489           0 :         return nullptr;
    5490             :     }
    5491             : 
    5492         542 :     NetworkStatisticsFileSystem oContextFS(GetFSPrefix().c_str());
    5493         542 :     NetworkStatisticsAction oContextAction("ReadDir");
    5494             : 
    5495         542 :     CPLMutexHolder oHolder(&hMutex);
    5496             : 
    5497             :     // If we know the file exists and is not a directory,
    5498             :     // then don't try to list its content.
    5499         542 :     FileProp cachedFileProp;
    5500         813 :     if (GetCachedFileProp(GetURLFromFilename(osDirname.c_str()).c_str(),
    5501          47 :                           cachedFileProp) &&
    5502         813 :         cachedFileProp.eExists == EXIST_YES && !cachedFileProp.bIsDirectory)
    5503             :     {
    5504           8 :         if (osDirnameOri != osDirname)
    5505             :         {
    5506           3 :             if (GetCachedFileProp((GetURLFromFilename(osDirname) + "/").c_str(),
    5507           1 :                                   cachedFileProp) &&
    5508           4 :                 cachedFileProp.eExists == EXIST_YES &&
    5509           1 :                 !cachedFileProp.bIsDirectory)
    5510             :             {
    5511           0 :                 if (pbGotFileList)
    5512           0 :                     *pbGotFileList = true;
    5513           0 :                 return nullptr;
    5514             :             }
    5515             :         }
    5516             :         else
    5517             :         {
    5518           7 :             if (pbGotFileList)
    5519           0 :                 *pbGotFileList = true;
    5520           7 :             return nullptr;
    5521             :         }
    5522             :     }
    5523             : 
    5524         528 :     CachedDirList cachedDirList;
    5525         264 :     if (!GetCachedDirList(osDirname.c_str(), cachedDirList))
    5526             :     {
    5527             :         cachedDirList.oFileList.Assign(GetFileList(osDirname.c_str(), nMaxFiles,
    5528         157 :                                                    &cachedDirList.bGotFileList),
    5529         157 :                                        true);
    5530         157 :         if (cachedDirList.bGotFileList && cachedDirList.oFileList.empty())
    5531             :         {
    5532             :             // To avoid an error to be reported
    5533          18 :             cachedDirList.oFileList.AddString(".");
    5534             :         }
    5535         157 :         if (nMaxFiles <= 0 || cachedDirList.oFileList.size() < nMaxFiles)
    5536             :         {
    5537             :             // Only cache content if we didn't hit the limitation
    5538         152 :             SetCachedDirList(osDirname.c_str(), cachedDirList);
    5539             :         }
    5540             :     }
    5541             : 
    5542         264 :     if (pbGotFileList)
    5543         135 :         *pbGotFileList = cachedDirList.bGotFileList;
    5544             : 
    5545         264 :     return CSLDuplicate(cachedDirList.oFileList.List());
    5546             : }
    5547             : 
    5548             : /************************************************************************/
    5549             : /*                        InvalidateDirContent()                        */
    5550             : /************************************************************************/
    5551             : 
    5552         195 : void VSICurlFilesystemHandlerBase::InvalidateDirContent(
    5553             :     const std::string &osDirname)
    5554             : {
    5555         390 :     CPLMutexHolder oHolder(&hMutex);
    5556             : 
    5557         390 :     CachedDirList oCachedDirList;
    5558         195 :     if (oCacheDirList.tryGet(osDirname, oCachedDirList))
    5559             :     {
    5560          18 :         nCachedFilesInDirList -= oCachedDirList.oFileList.size();
    5561          18 :         oCacheDirList.remove(osDirname);
    5562             :     }
    5563         195 : }
    5564             : 
    5565             : /************************************************************************/
    5566             : /*                             ReadDirEx()                              */
    5567             : /************************************************************************/
    5568             : 
    5569          90 : char **VSICurlFilesystemHandlerBase::ReadDirEx(const char *pszDirname,
    5570             :                                                int nMaxFiles)
    5571             : {
    5572          90 :     return ReadDirInternal(pszDirname, nMaxFiles, nullptr);
    5573             : }
    5574             : 
    5575             : /************************************************************************/
    5576             : /*                             SiblingFiles()                           */
    5577             : /************************************************************************/
    5578             : 
    5579          52 : char **VSICurlFilesystemHandlerBase::SiblingFiles(const char *pszFilename)
    5580             : {
    5581             :     /* Small optimization to avoid unnecessary stat'ing from PAux or ENVI */
    5582             :     /* drivers. The MBTiles driver needs no companion file. */
    5583          52 :     if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "mbtiles"))
    5584             :     {
    5585           6 :         return static_cast<char **>(CPLCalloc(1, sizeof(char *)));
    5586             :     }
    5587          46 :     return nullptr;
    5588             : }
    5589             : 
    5590             : /************************************************************************/
    5591             : /*                          GetFileMetadata()                           */
    5592             : /************************************************************************/
    5593             : 
    5594           7 : char **VSICurlFilesystemHandlerBase::GetFileMetadata(const char *pszFilename,
    5595             :                                                      const char *pszDomain,
    5596             :                                                      CSLConstList)
    5597             : {
    5598           7 :     if (pszDomain == nullptr || !EQUAL(pszDomain, "HEADERS"))
    5599           3 :         return nullptr;
    5600           8 :     std::unique_ptr<VSICurlHandle> poHandle(CreateFileHandle(pszFilename));
    5601           4 :     if (poHandle == nullptr)
    5602           0 :         return nullptr;
    5603             : 
    5604           8 :     NetworkStatisticsFileSystem oContextFS(GetFSPrefix().c_str());
    5605           8 :     NetworkStatisticsAction oContextAction("GetFileMetadata");
    5606             : 
    5607           4 :     poHandle->GetFileSizeOrHeaders(true, true);
    5608           4 :     return CSLDuplicate(poHandle->GetHeaders().List());
    5609             : }
    5610             : 
    5611             : /************************************************************************/
    5612             : /*                       VSIAppendWriteHandle()                         */
    5613             : /************************************************************************/
    5614             : 
    5615          17 : VSIAppendWriteHandle::VSIAppendWriteHandle(VSICurlFilesystemHandlerBase *poFS,
    5616             :                                            const char *pszFSPrefix,
    5617             :                                            const char *pszFilename,
    5618          17 :                                            int nChunkSize)
    5619             :     : m_poFS(poFS), m_osFSPrefix(pszFSPrefix), m_osFilename(pszFilename),
    5620          34 :       m_oRetryParameters(CPLStringList(CPLHTTPGetOptionsFromEnv(pszFilename))),
    5621          34 :       m_nBufferSize(nChunkSize)
    5622             : {
    5623          17 :     m_pabyBuffer = static_cast<GByte *>(VSIMalloc(m_nBufferSize));
    5624          17 :     if (m_pabyBuffer == nullptr)
    5625             :     {
    5626           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5627             :                  "Cannot allocate working buffer for %s writing",
    5628             :                  m_osFSPrefix.c_str());
    5629             :     }
    5630          17 : }
    5631             : 
    5632             : /************************************************************************/
    5633             : /*                      ~VSIAppendWriteHandle()                         */
    5634             : /************************************************************************/
    5635             : 
    5636          17 : VSIAppendWriteHandle::~VSIAppendWriteHandle()
    5637             : {
    5638             :     /* WARNING: implementation should call Close() themselves */
    5639             :     /* cannot be done safely from here, since Send() can be called. */
    5640          17 :     CPLFree(m_pabyBuffer);
    5641          17 : }
    5642             : 
    5643             : /************************************************************************/
    5644             : /*                               Seek()                                 */
    5645             : /************************************************************************/
    5646             : 
    5647           0 : int VSIAppendWriteHandle::Seek(vsi_l_offset nOffset, int nWhence)
    5648             : {
    5649           0 :     if (!((nWhence == SEEK_SET && nOffset == m_nCurOffset) ||
    5650           0 :           (nWhence == SEEK_CUR && nOffset == 0) ||
    5651           0 :           (nWhence == SEEK_END && nOffset == 0)))
    5652             :     {
    5653           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    5654             :                  "Seek not supported on writable %s files",
    5655             :                  m_osFSPrefix.c_str());
    5656           0 :         m_bError = true;
    5657           0 :         return -1;
    5658             :     }
    5659           0 :     return 0;
    5660             : }
    5661             : 
    5662             : /************************************************************************/
    5663             : /*                               Tell()                                 */
    5664             : /************************************************************************/
    5665             : 
    5666           0 : vsi_l_offset VSIAppendWriteHandle::Tell()
    5667             : {
    5668           0 :     return m_nCurOffset;
    5669             : }
    5670             : 
    5671             : /************************************************************************/
    5672             : /*                               Read()                                 */
    5673             : /************************************************************************/
    5674             : 
    5675           0 : size_t VSIAppendWriteHandle::Read(void * /* pBuffer */, size_t /* nSize */,
    5676             :                                   size_t /* nMemb */)
    5677             : {
    5678           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    5679             :              "Read not supported on writable %s files", m_osFSPrefix.c_str());
    5680           0 :     m_bError = true;
    5681           0 :     return 0;
    5682             : }
    5683             : 
    5684             : /************************************************************************/
    5685             : /*                         ReadCallBackBuffer()                         */
    5686             : /************************************************************************/
    5687             : 
    5688           1 : size_t VSIAppendWriteHandle::ReadCallBackBuffer(char *buffer, size_t size,
    5689             :                                                 size_t nitems, void *instream)
    5690             : {
    5691           1 :     VSIAppendWriteHandle *poThis =
    5692             :         static_cast<VSIAppendWriteHandle *>(instream);
    5693           1 :     const int nSizeMax = static_cast<int>(size * nitems);
    5694             :     const int nSizeToWrite = std::min(
    5695           1 :         nSizeMax, poThis->m_nBufferOff - poThis->m_nBufferOffReadCallback);
    5696           1 :     memcpy(buffer, poThis->m_pabyBuffer + poThis->m_nBufferOffReadCallback,
    5697             :            nSizeToWrite);
    5698           1 :     poThis->m_nBufferOffReadCallback += nSizeToWrite;
    5699           1 :     return nSizeToWrite;
    5700             : }
    5701             : 
    5702             : /************************************************************************/
    5703             : /*                               Write()                                */
    5704             : /************************************************************************/
    5705             : 
    5706           9 : size_t VSIAppendWriteHandle::Write(const void *pBuffer, size_t nSize,
    5707             :                                    size_t nMemb)
    5708             : {
    5709           9 :     if (m_bError)
    5710           0 :         return 0;
    5711             : 
    5712           9 :     size_t nBytesToWrite = nSize * nMemb;
    5713           9 :     if (nBytesToWrite == 0)
    5714           0 :         return 0;
    5715             : 
    5716           9 :     const GByte *pabySrcBuffer = reinterpret_cast<const GByte *>(pBuffer);
    5717          21 :     while (nBytesToWrite > 0)
    5718             :     {
    5719          12 :         if (m_nBufferOff == m_nBufferSize)
    5720             :         {
    5721           3 :             if (!Send(false))
    5722             :             {
    5723           0 :                 m_bError = true;
    5724           0 :                 return 0;
    5725             :             }
    5726           3 :             m_nBufferOff = 0;
    5727             :         }
    5728             : 
    5729          12 :         const int nToWriteInBuffer = static_cast<int>(std::min(
    5730          12 :             static_cast<size_t>(m_nBufferSize - m_nBufferOff), nBytesToWrite));
    5731          12 :         memcpy(m_pabyBuffer + m_nBufferOff, pabySrcBuffer, nToWriteInBuffer);
    5732          12 :         pabySrcBuffer += nToWriteInBuffer;
    5733          12 :         m_nBufferOff += nToWriteInBuffer;
    5734          12 :         m_nCurOffset += nToWriteInBuffer;
    5735          12 :         nBytesToWrite -= nToWriteInBuffer;
    5736             :     }
    5737           9 :     return nMemb;
    5738             : }
    5739             : 
    5740             : /************************************************************************/
    5741             : /*                                 Close()                              */
    5742             : /************************************************************************/
    5743             : 
    5744          30 : int VSIAppendWriteHandle::Close()
    5745             : {
    5746          30 :     int nRet = 0;
    5747          30 :     if (!m_bClosed)
    5748             :     {
    5749          17 :         m_bClosed = true;
    5750          17 :         if (!m_bError && !Send(true))
    5751           4 :             nRet = -1;
    5752             :     }
    5753          30 :     return nRet;
    5754             : }
    5755             : 
    5756             : /************************************************************************/
    5757             : /*                         CurlRequestHelper()                          */
    5758             : /************************************************************************/
    5759             : 
    5760         376 : CurlRequestHelper::CurlRequestHelper()
    5761             : {
    5762         376 :     VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
    5763         376 :     VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
    5764             :                                nullptr);
    5765         376 : }
    5766             : 
    5767             : /************************************************************************/
    5768             : /*                        ~CurlRequestHelper()                          */
    5769             : /************************************************************************/
    5770             : 
    5771         752 : CurlRequestHelper::~CurlRequestHelper()
    5772             : {
    5773         376 :     CPLFree(sWriteFuncData.pBuffer);
    5774         376 :     CPLFree(sWriteFuncHeaderData.pBuffer);
    5775         376 : }
    5776             : 
    5777             : /************************************************************************/
    5778             : /*                             perform()                                */
    5779             : /************************************************************************/
    5780             : 
    5781         376 : long CurlRequestHelper::perform(CURL *hCurlHandle, struct curl_slist *headers,
    5782             :                                 VSICurlFilesystemHandlerBase *poFS,
    5783             :                                 IVSIS3LikeHandleHelper *poS3HandleHelper)
    5784             : {
    5785         376 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
    5786             : 
    5787         376 :     poS3HandleHelper->ResetQueryParameters();
    5788             : 
    5789         376 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
    5790         376 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
    5791             :                                VSICurlHandleWriteFunc);
    5792             : 
    5793         376 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
    5794             :                                &sWriteFuncHeaderData);
    5795         376 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
    5796             :                                VSICurlHandleWriteFunc);
    5797             : 
    5798         376 :     szCurlErrBuf[0] = '\0';
    5799         376 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
    5800             : 
    5801         376 :     VSICURLMultiPerform(poFS->GetCurlMultiHandleFor(poS3HandleHelper->GetURL()),
    5802             :                         hCurlHandle);
    5803             : 
    5804         376 :     VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
    5805             : 
    5806         376 :     curl_slist_free_all(headers);
    5807             : 
    5808         376 :     long response_code = 0;
    5809         376 :     curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
    5810         376 :     return response_code;
    5811             : }
    5812             : 
    5813             : /************************************************************************/
    5814             : /*                       NetworkStatisticsLogger                        */
    5815             : /************************************************************************/
    5816             : 
    5817             : // Global variable
    5818             : NetworkStatisticsLogger NetworkStatisticsLogger::gInstance{};
    5819             : int NetworkStatisticsLogger::gnEnabled = -1;  // unknown state
    5820             : 
    5821           0 : static void ShowNetworkStats()
    5822             : {
    5823           0 :     printf("Network statistics:\n%s\n",  // ok
    5824           0 :            NetworkStatisticsLogger::GetReportAsSerializedJSON().c_str());
    5825           0 : }
    5826             : 
    5827           8 : void NetworkStatisticsLogger::ReadEnabled()
    5828             : {
    5829             :     const bool bShowNetworkStats =
    5830           8 :         CPLTestBool(CPLGetConfigOption("CPL_VSIL_SHOW_NETWORK_STATS", "NO"));
    5831           8 :     gnEnabled =
    5832           8 :         (bShowNetworkStats || CPLTestBool(CPLGetConfigOption(
    5833             :                                   "CPL_VSIL_NETWORK_STATS_ENABLED", "NO")))
    5834          16 :             ? TRUE
    5835             :             : FALSE;
    5836           8 :     if (bShowNetworkStats)
    5837             :     {
    5838             :         static bool bRegistered = false;
    5839           0 :         if (!bRegistered)
    5840             :         {
    5841           0 :             bRegistered = true;
    5842           0 :             atexit(ShowNetworkStats);
    5843             :         }
    5844             :     }
    5845           8 : }
    5846             : 
    5847       47495 : void NetworkStatisticsLogger::EnterFileSystem(const char *pszName)
    5848             : {
    5849       47495 :     if (!IsEnabled())
    5850       47494 :         return;
    5851           1 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5852           2 :     gInstance.m_mapThreadIdToContextPath[CPLGetPID()].push_back(
    5853           2 :         ContextPathItem(ContextPathType::FILESYSTEM, pszName));
    5854             : }
    5855             : 
    5856       47495 : void NetworkStatisticsLogger::LeaveFileSystem()
    5857             : {
    5858       47495 :     if (!IsEnabled())
    5859       47494 :         return;
    5860           1 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5861           1 :     gInstance.m_mapThreadIdToContextPath[CPLGetPID()].pop_back();
    5862             : }
    5863             : 
    5864       45943 : void NetworkStatisticsLogger::EnterFile(const char *pszName)
    5865             : {
    5866       45943 :     if (!IsEnabled())
    5867       45942 :         return;
    5868           1 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5869           2 :     gInstance.m_mapThreadIdToContextPath[CPLGetPID()].push_back(
    5870           2 :         ContextPathItem(ContextPathType::FILE, pszName));
    5871             : }
    5872             : 
    5873       45943 : void NetworkStatisticsLogger::LeaveFile()
    5874             : {
    5875       45943 :     if (!IsEnabled())
    5876       45942 :         return;
    5877           1 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5878           1 :     gInstance.m_mapThreadIdToContextPath[CPLGetPID()].pop_back();
    5879             : }
    5880             : 
    5881       47495 : void NetworkStatisticsLogger::EnterAction(const char *pszName)
    5882             : {
    5883       47495 :     if (!IsEnabled())
    5884       47494 :         return;
    5885           1 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5886           2 :     gInstance.m_mapThreadIdToContextPath[CPLGetPID()].push_back(
    5887           2 :         ContextPathItem(ContextPathType::ACTION, pszName));
    5888             : }
    5889             : 
    5890       47495 : void NetworkStatisticsLogger::LeaveAction()
    5891             : {
    5892       47495 :     if (!IsEnabled())
    5893       47494 :         return;
    5894           1 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5895           1 :     gInstance.m_mapThreadIdToContextPath[CPLGetPID()].pop_back();
    5896             : }
    5897             : 
    5898             : std::vector<NetworkStatisticsLogger::Counters *>
    5899           1 : NetworkStatisticsLogger::GetCountersForContext()
    5900             : {
    5901           1 :     std::vector<Counters *> v;
    5902           1 :     const auto &contextPath = gInstance.m_mapThreadIdToContextPath[CPLGetPID()];
    5903             : 
    5904           1 :     Stats *curStats = &m_stats;
    5905           1 :     v.push_back(&(curStats->counters));
    5906             : 
    5907           1 :     bool inFileSystem = false;
    5908           1 :     bool inFile = false;
    5909           1 :     bool inAction = false;
    5910           4 :     for (const auto &item : contextPath)
    5911             :     {
    5912           3 :         if (item.eType == ContextPathType::FILESYSTEM)
    5913             :         {
    5914           1 :             if (inFileSystem)
    5915           0 :                 continue;
    5916           1 :             inFileSystem = true;
    5917             :         }
    5918           2 :         else if (item.eType == ContextPathType::FILE)
    5919             :         {
    5920           1 :             if (inFile)
    5921           0 :                 continue;
    5922           1 :             inFile = true;
    5923             :         }
    5924           1 :         else if (item.eType == ContextPathType::ACTION)
    5925             :         {
    5926           1 :             if (inAction)
    5927           0 :                 continue;
    5928           1 :             inAction = true;
    5929             :         }
    5930             : 
    5931           3 :         curStats = &(curStats->children[item]);
    5932           3 :         v.push_back(&(curStats->counters));
    5933             :     }
    5934             : 
    5935           1 :     return v;
    5936             : }
    5937             : 
    5938         771 : void NetworkStatisticsLogger::LogGET(size_t nDownloadedBytes)
    5939             : {
    5940         771 :     if (!IsEnabled())
    5941         771 :         return;
    5942           0 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5943           0 :     for (auto counters : gInstance.GetCountersForContext())
    5944             :     {
    5945           0 :         counters->nGET++;
    5946           0 :         counters->nGETDownloadedBytes += nDownloadedBytes;
    5947             :     }
    5948             : }
    5949             : 
    5950         132 : void NetworkStatisticsLogger::LogPUT(size_t nUploadedBytes)
    5951             : {
    5952         132 :     if (!IsEnabled())
    5953         131 :         return;
    5954           2 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5955           5 :     for (auto counters : gInstance.GetCountersForContext())
    5956             :     {
    5957           4 :         counters->nPUT++;
    5958           4 :         counters->nPUTUploadedBytes += nUploadedBytes;
    5959             :     }
    5960             : }
    5961             : 
    5962         294 : void NetworkStatisticsLogger::LogHEAD()
    5963             : {
    5964         294 :     if (!IsEnabled())
    5965         294 :         return;
    5966           0 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5967           0 :     for (auto counters : gInstance.GetCountersForContext())
    5968             :     {
    5969           0 :         counters->nHEAD++;
    5970             :     }
    5971             : }
    5972             : 
    5973          37 : void NetworkStatisticsLogger::LogPOST(size_t nUploadedBytes,
    5974             :                                       size_t nDownloadedBytes)
    5975             : {
    5976          37 :     if (!IsEnabled())
    5977          37 :         return;
    5978           0 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5979           0 :     for (auto counters : gInstance.GetCountersForContext())
    5980             :     {
    5981           0 :         counters->nPOST++;
    5982           0 :         counters->nPOSTUploadedBytes += nUploadedBytes;
    5983           0 :         counters->nPOSTDownloadedBytes += nDownloadedBytes;
    5984             :     }
    5985             : }
    5986             : 
    5987          44 : void NetworkStatisticsLogger::LogDELETE()
    5988             : {
    5989          44 :     if (!IsEnabled())
    5990          44 :         return;
    5991           0 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    5992           0 :     for (auto counters : gInstance.GetCountersForContext())
    5993             :     {
    5994           0 :         counters->nDELETE++;
    5995             :     }
    5996             : }
    5997             : 
    5998           2 : void NetworkStatisticsLogger::Reset()
    5999             : {
    6000           2 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    6001           2 :     gInstance.m_stats = Stats();
    6002           2 :     gnEnabled = -1;
    6003           2 : }
    6004             : 
    6005           4 : void NetworkStatisticsLogger::Stats::AsJSON(CPLJSONObject &oJSON) const
    6006             : {
    6007           8 :     CPLJSONObject oMethods;
    6008           4 :     if (counters.nHEAD)
    6009           0 :         oMethods.Add("HEAD/count", counters.nHEAD);
    6010           4 :     if (counters.nGET)
    6011           0 :         oMethods.Add("GET/count", counters.nGET);
    6012           4 :     if (counters.nGETDownloadedBytes)
    6013           0 :         oMethods.Add("GET/downloaded_bytes", counters.nGETDownloadedBytes);
    6014           4 :     if (counters.nPUT)
    6015           4 :         oMethods.Add("PUT/count", counters.nPUT);
    6016           4 :     if (counters.nPUTUploadedBytes)
    6017           4 :         oMethods.Add("PUT/uploaded_bytes", counters.nPUTUploadedBytes);
    6018           4 :     if (counters.nPOST)
    6019           0 :         oMethods.Add("POST/count", counters.nPOST);
    6020           4 :     if (counters.nPOSTUploadedBytes)
    6021           0 :         oMethods.Add("POST/uploaded_bytes", counters.nPOSTUploadedBytes);
    6022           4 :     if (counters.nPOSTDownloadedBytes)
    6023           0 :         oMethods.Add("POST/downloaded_bytes", counters.nPOSTDownloadedBytes);
    6024           4 :     if (counters.nDELETE)
    6025           0 :         oMethods.Add("DELETE/count", counters.nDELETE);
    6026           4 :     oJSON.Add("methods", oMethods);
    6027           8 :     CPLJSONObject oFiles;
    6028           4 :     bool bFilesAdded = false;
    6029           7 :     for (const auto &kv : children)
    6030             :     {
    6031           6 :         CPLJSONObject childJSON;
    6032           3 :         kv.second.AsJSON(childJSON);
    6033           3 :         if (kv.first.eType == ContextPathType::FILESYSTEM)
    6034             :         {
    6035           1 :             std::string osName(kv.first.osName);
    6036           1 :             if (!osName.empty() && osName[0] == '/')
    6037           1 :                 osName = osName.substr(1);
    6038           1 :             if (!osName.empty() && osName.back() == '/')
    6039           1 :                 osName.pop_back();
    6040           1 :             oJSON.Add(("handlers/" + osName).c_str(), childJSON);
    6041             :         }
    6042           2 :         else if (kv.first.eType == ContextPathType::FILE)
    6043             :         {
    6044           1 :             if (!bFilesAdded)
    6045             :             {
    6046           1 :                 bFilesAdded = true;
    6047           1 :                 oJSON.Add("files", oFiles);
    6048             :             }
    6049           1 :             oFiles.AddNoSplitName(kv.first.osName.c_str(), childJSON);
    6050             :         }
    6051           1 :         else if (kv.first.eType == ContextPathType::ACTION)
    6052             :         {
    6053           1 :             oJSON.Add(("actions/" + kv.first.osName).c_str(), childJSON);
    6054             :         }
    6055             :     }
    6056           4 : }
    6057             : 
    6058           1 : std::string NetworkStatisticsLogger::GetReportAsSerializedJSON()
    6059             : {
    6060           2 :     std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
    6061             : 
    6062           2 :     CPLJSONObject oJSON;
    6063           1 :     gInstance.m_stats.AsJSON(oJSON);
    6064           2 :     return oJSON.Format(CPLJSONObject::PrettyFormat::Pretty);
    6065             : }
    6066             : 
    6067             : } /* end of namespace cpl */
    6068             : 
    6069             : /************************************************************************/
    6070             : /*                     VSICurlParseUnixPermissions()                    */
    6071             : /************************************************************************/
    6072             : 
    6073          23 : int VSICurlParseUnixPermissions(const char *pszPermissions)
    6074             : {
    6075          23 :     if (strlen(pszPermissions) != 9)
    6076          12 :         return 0;
    6077          11 :     int nMode = 0;
    6078          11 :     if (pszPermissions[0] == 'r')
    6079          11 :         nMode |= S_IRUSR;
    6080          11 :     if (pszPermissions[1] == 'w')
    6081          11 :         nMode |= S_IWUSR;
    6082          11 :     if (pszPermissions[2] == 'x')
    6083          11 :         nMode |= S_IXUSR;
    6084          11 :     if (pszPermissions[3] == 'r')
    6085          11 :         nMode |= S_IRGRP;
    6086          11 :     if (pszPermissions[4] == 'w')
    6087          11 :         nMode |= S_IWGRP;
    6088          11 :     if (pszPermissions[5] == 'x')
    6089          11 :         nMode |= S_IXGRP;
    6090          11 :     if (pszPermissions[6] == 'r')
    6091          11 :         nMode |= S_IROTH;
    6092          11 :     if (pszPermissions[7] == 'w')
    6093          11 :         nMode |= S_IWOTH;
    6094          11 :     if (pszPermissions[8] == 'x')
    6095          11 :         nMode |= S_IXOTH;
    6096          11 :     return nMode;
    6097             : }
    6098             : 
    6099             : /************************************************************************/
    6100             : /*                  Cache of file properties.                           */
    6101             : /************************************************************************/
    6102             : 
    6103             : static std::mutex oCacheFilePropMutex;
    6104             : static lru11::Cache<std::string, cpl::FileProp> *poCacheFileProp = nullptr;
    6105             : 
    6106             : /************************************************************************/
    6107             : /*                   VSICURLGetCachedFileProp()                         */
    6108             : /************************************************************************/
    6109             : 
    6110       46916 : bool VSICURLGetCachedFileProp(const char *pszURL, cpl::FileProp &oFileProp)
    6111             : {
    6112       46916 :     std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
    6113      140748 :     return poCacheFileProp != nullptr &&
    6114      140748 :            poCacheFileProp->tryGet(std::string(pszURL), oFileProp) &&
    6115             :            // Let a chance to use new auth parameters
    6116       46916 :            !(oFileProp.eExists == cpl::EXIST_NO &&
    6117       94055 :              gnGenerationAuthParameters != oFileProp.nGenerationAuthParameters);
    6118             : }
    6119             : 
    6120             : /************************************************************************/
    6121             : /*                   VSICURLSetCachedFileProp()                         */
    6122             : /************************************************************************/
    6123             : 
    6124        1497 : void VSICURLSetCachedFileProp(const char *pszURL, cpl::FileProp &oFileProp)
    6125             : {
    6126        1497 :     std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
    6127        1497 :     if (poCacheFileProp == nullptr)
    6128           4 :         poCacheFileProp =
    6129           4 :             new lru11::Cache<std::string, cpl::FileProp>(100 * 1024);
    6130        1497 :     oFileProp.nGenerationAuthParameters = gnGenerationAuthParameters;
    6131        1497 :     poCacheFileProp->insert(std::string(pszURL), oFileProp);
    6132        1497 : }
    6133             : 
    6134             : /************************************************************************/
    6135             : /*                   VSICURLInvalidateCachedFileProp()                  */
    6136             : /************************************************************************/
    6137             : 
    6138         693 : void VSICURLInvalidateCachedFileProp(const char *pszURL)
    6139             : {
    6140        1386 :     std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
    6141         693 :     if (poCacheFileProp != nullptr)
    6142         693 :         poCacheFileProp->remove(std::string(pszURL));
    6143         693 : }
    6144             : 
    6145             : /************************************************************************/
    6146             : /*               VSICURLInvalidateCachedFilePropPrefix()                */
    6147             : /************************************************************************/
    6148             : 
    6149           5 : void VSICURLInvalidateCachedFilePropPrefix(const char *pszURL)
    6150             : {
    6151          10 :     std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
    6152           5 :     if (poCacheFileProp != nullptr)
    6153             :     {
    6154          10 :         std::list<std::string> keysToRemove;
    6155           5 :         const size_t nURLSize = strlen(pszURL);
    6156             :         auto lambda =
    6157          73 :             [&keysToRemove, &pszURL, nURLSize](
    6158          77 :                 const lru11::KeyValuePair<std::string, cpl::FileProp> &kv)
    6159             :         {
    6160          73 :             if (strncmp(kv.key.c_str(), pszURL, nURLSize) == 0)
    6161           4 :                 keysToRemove.push_back(kv.key);
    6162          78 :         };
    6163           5 :         poCacheFileProp->cwalk(lambda);
    6164           9 :         for (const auto &key : keysToRemove)
    6165           4 :             poCacheFileProp->remove(key);
    6166             :     }
    6167           5 : }
    6168             : 
    6169             : /************************************************************************/
    6170             : /*                   VSICURLDestroyCacheFileProp()                      */
    6171             : /************************************************************************/
    6172             : 
    6173        1122 : void VSICURLDestroyCacheFileProp()
    6174             : {
    6175        1122 :     std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
    6176        1122 :     delete poCacheFileProp;
    6177        1122 :     poCacheFileProp = nullptr;
    6178        1122 : }
    6179             : 
    6180             : /************************************************************************/
    6181             : /*                       VSICURLMultiCleanup()                          */
    6182             : /************************************************************************/
    6183             : 
    6184         252 : void VSICURLMultiCleanup(CURLM *hCurlMultiHandle)
    6185             : {
    6186         252 :     void *old_handler = CPLHTTPIgnoreSigPipe();
    6187         252 :     curl_multi_cleanup(hCurlMultiHandle);
    6188         252 :     CPLHTTPRestoreSigPipeHandler(old_handler);
    6189         252 : }
    6190             : 
    6191             : /************************************************************************/
    6192             : /*                      VSICurlInstallReadCbk()                         */
    6193             : /************************************************************************/
    6194             : 
    6195           3 : int VSICurlInstallReadCbk(VSILFILE *fp, VSICurlReadCbkFunc pfnReadCbk,
    6196             :                           void *pfnUserData, int bStopOnInterruptUntilUninstall)
    6197             : {
    6198           3 :     return reinterpret_cast<cpl::VSICurlHandle *>(fp)->InstallReadCbk(
    6199           3 :         pfnReadCbk, pfnUserData, bStopOnInterruptUntilUninstall);
    6200             : }
    6201             : 
    6202             : /************************************************************************/
    6203             : /*                    VSICurlUninstallReadCbk()                         */
    6204             : /************************************************************************/
    6205             : 
    6206           3 : int VSICurlUninstallReadCbk(VSILFILE *fp)
    6207             : {
    6208           3 :     return reinterpret_cast<cpl::VSICurlHandle *>(fp)->UninstallReadCbk();
    6209             : }
    6210             : 
    6211             : /************************************************************************/
    6212             : /*                       VSICurlSetOptions()                            */
    6213             : /************************************************************************/
    6214             : 
    6215        1157 : struct curl_slist *VSICurlSetOptions(CURL *hCurlHandle, const char *pszURL,
    6216             :                                      const char *const *papszOptions)
    6217             : {
    6218             :     struct curl_slist *headers = static_cast<struct curl_slist *>(
    6219        1157 :         CPLHTTPSetOptions(hCurlHandle, pszURL, papszOptions));
    6220             : 
    6221        1157 :     long option = CURLFTPMETHOD_SINGLECWD;
    6222        1157 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FTP_FILEMETHOD, option);
    6223             : 
    6224             :     // ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif/
    6225             :     // doesn't like EPSV command,
    6226        1157 :     unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FTP_USE_EPSV, 0);
    6227             : 
    6228        1157 :     return headers;
    6229             : }
    6230             : 
    6231             : /************************************************************************/
    6232             : /*                    VSICurlSetContentTypeFromExt()                    */
    6233             : /************************************************************************/
    6234             : 
    6235          96 : struct curl_slist *VSICurlSetContentTypeFromExt(struct curl_slist *poList,
    6236             :                                                 const char *pszPath)
    6237             : {
    6238          96 :     struct curl_slist *iter = poList;
    6239         134 :     while (iter != nullptr)
    6240             :     {
    6241          38 :         if (STARTS_WITH_CI(iter->data, "Content-Type"))
    6242             :         {
    6243           0 :             return poList;
    6244             :         }
    6245          38 :         iter = iter->next;
    6246             :     }
    6247             : 
    6248             :     static const struct
    6249             :     {
    6250             :         const char *ext;
    6251             :         const char *mime;
    6252             :     } aosExtMimePairs[] = {
    6253             :         {"txt", "text/plain"}, {"json", "application/json"},
    6254             :         {"tif", "image/tiff"}, {"tiff", "image/tiff"},
    6255             :         {"jpg", "image/jpeg"}, {"jpeg", "image/jpeg"},
    6256             :         {"jp2", "image/jp2"},  {"jpx", "image/jp2"},
    6257             :         {"j2k", "image/jp2"},  {"jpc", "image/jp2"},
    6258             :         {"png", "image/png"},
    6259             :     };
    6260             : 
    6261          96 :     const std::string osExt = CPLGetExtensionSafe(pszPath);
    6262          96 :     if (!osExt.empty())
    6263             :     {
    6264         658 :         for (const auto &pair : aosExtMimePairs)
    6265             :         {
    6266         605 :             if (EQUAL(osExt.c_str(), pair.ext))
    6267             :             {
    6268             : 
    6269             :                 const std::string osContentType(
    6270          32 :                     CPLSPrintf("Content-Type: %s", pair.mime));
    6271          16 :                 poList = curl_slist_append(poList, osContentType.c_str());
    6272             : #ifdef DEBUG_VERBOSE
    6273             :                 CPLDebug("HTTP", "Setting %s, based on lookup table.",
    6274             :                          osContentType.c_str());
    6275             : #endif
    6276          16 :                 break;
    6277             :             }
    6278             :         }
    6279             :     }
    6280             : 
    6281          96 :     return poList;
    6282             : }
    6283             : 
    6284             : /************************************************************************/
    6285             : /*                VSICurlSetCreationHeadersFromOptions()                */
    6286             : /************************************************************************/
    6287             : 
    6288          83 : struct curl_slist *VSICurlSetCreationHeadersFromOptions(
    6289             :     struct curl_slist *headers, CSLConstList papszOptions, const char *pszPath)
    6290             : {
    6291          83 :     bool bContentTypeFound = false;
    6292          93 :     for (CSLConstList papszIter = papszOptions; papszIter && *papszIter;
    6293             :          ++papszIter)
    6294             :     {
    6295          10 :         char *pszKey = nullptr;
    6296          10 :         const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
    6297          10 :         if (pszKey && pszValue)
    6298             :         {
    6299          10 :             if (EQUAL(pszKey, "Content-Type"))
    6300             :             {
    6301           2 :                 bContentTypeFound = true;
    6302             :             }
    6303          10 :             headers = curl_slist_append(headers,
    6304             :                                         CPLSPrintf("%s: %s", pszKey, pszValue));
    6305             :         }
    6306          10 :         CPLFree(pszKey);
    6307             :     }
    6308             : 
    6309             :     // If Content-type not found in papszOptions, try to set it from the
    6310             :     // filename exstension.
    6311          83 :     if (!bContentTypeFound)
    6312             :     {
    6313          81 :         headers = VSICurlSetContentTypeFromExt(headers, pszPath);
    6314             :     }
    6315             : 
    6316          83 :     return headers;
    6317             : }
    6318             : 
    6319             : #endif  // DOXYGEN_SKIP
    6320             : //! @endcond
    6321             : 
    6322             : /************************************************************************/
    6323             : /*                   VSIInstallCurlFileHandler()                        */
    6324             : /************************************************************************/
    6325             : 
    6326             : /*!
    6327             :  \brief Install /vsicurl/ HTTP/FTP file system handler (requires libcurl)
    6328             : 
    6329             :  \verbatim embed:rst
    6330             :  See :ref:`/vsicurl/ documentation <vsicurl>`
    6331             :  \endverbatim
    6332             : 
    6333             :  @since GDAL 1.8.0
    6334             :  */
    6335        1694 : void VSIInstallCurlFileHandler(void)
    6336             : {
    6337        1694 :     VSIFilesystemHandler *poHandler = new cpl::VSICurlFilesystemHandler;
    6338        1694 :     VSIFileManager::InstallHandler("/vsicurl/", poHandler);
    6339        1694 :     VSIFileManager::InstallHandler("/vsicurl?", poHandler);
    6340        1694 : }
    6341             : 
    6342             : /************************************************************************/
    6343             : /*                         VSICurlClearCache()                          */
    6344             : /************************************************************************/
    6345             : 
    6346             : /**
    6347             :  * \brief Clean local cache associated with /vsicurl/ (and related file systems)
    6348             :  *
    6349             :  * /vsicurl (and related file systems like /vsis3/, /vsigs/, /vsiaz/, /vsioss/,
    6350             :  * /vsiswift/) cache a number of
    6351             :  * metadata and data for faster execution in read-only scenarios. But when the
    6352             :  * content on the server-side may change during the same process, those
    6353             :  * mechanisms can prevent opening new files, or give an outdated version of
    6354             :  * them.
    6355             :  *
    6356             :  * @since GDAL 2.2.1
    6357             :  */
    6358             : 
    6359         335 : void VSICurlClearCache(void)
    6360             : {
    6361             :     // FIXME ? Currently we have different filesystem instances for
    6362             :     // vsicurl/, /vsis3/, /vsigs/ . So each one has its own cache of regions.
    6363             :     // File properties cache are now shared
    6364         335 :     char **papszPrefix = VSIFileManager::GetPrefixes();
    6365       10385 :     for (size_t i = 0; papszPrefix && papszPrefix[i]; ++i)
    6366             :     {
    6367           0 :         auto poFSHandler = dynamic_cast<cpl::VSICurlFilesystemHandlerBase *>(
    6368       10050 :             VSIFileManager::GetHandler(papszPrefix[i]));
    6369             : 
    6370       10050 :         if (poFSHandler)
    6371        2680 :             poFSHandler->ClearCache();
    6372             :     }
    6373         335 :     CSLDestroy(papszPrefix);
    6374             : 
    6375         335 :     VSICurlStreamingClearCache();
    6376         335 : }
    6377             : 
    6378             : /************************************************************************/
    6379             : /*                      VSICurlPartialClearCache()                      */
    6380             : /************************************************************************/
    6381             : 
    6382             : /**
    6383             :  * \brief Clean local cache associated with /vsicurl/ (and related file systems)
    6384             :  * for a given filename (and its subfiles and subdirectories if it is a
    6385             :  * directory)
    6386             :  *
    6387             :  * /vsicurl (and related file systems like /vsis3/, /vsigs/, /vsiaz/, /vsioss/,
    6388             :  * /vsiswift/) cache a number of
    6389             :  * metadata and data for faster execution in read-only scenarios. But when the
    6390             :  * content on the server-side may change during the same process, those
    6391             :  * mechanisms can prevent opening new files, or give an outdated version of
    6392             :  * them.
    6393             :  *
    6394             :  * The filename prefix must start with the name of a known virtual file system
    6395             :  * (such as "/vsicurl/", "/vsis3/")
    6396             :  *
    6397             :  * VSICurlPartialClearCache("/vsis3/b") will clear all cached state for any file
    6398             :  * or directory starting with that prefix, so potentially "/vsis3/bucket",
    6399             :  * "/vsis3/basket/" or "/vsis3/basket/object".
    6400             :  *
    6401             :  * @param pszFilenamePrefix Filename prefix
    6402             :  * @since GDAL 2.4.0
    6403             :  */
    6404             : 
    6405           2 : void VSICurlPartialClearCache(const char *pszFilenamePrefix)
    6406             : {
    6407           0 :     auto poFSHandler = dynamic_cast<cpl::VSICurlFilesystemHandlerBase *>(
    6408           2 :         VSIFileManager::GetHandler(pszFilenamePrefix));
    6409             : 
    6410           2 :     if (poFSHandler)
    6411           2 :         poFSHandler->PartialClearCache(pszFilenamePrefix);
    6412           2 : }
    6413             : 
    6414             : /************************************************************************/
    6415             : /*                        VSINetworkStatsReset()                        */
    6416             : /************************************************************************/
    6417             : 
    6418             : /**
    6419             :  * \brief Clear network related statistics.
    6420             :  *
    6421             :  * The effect of the CPL_VSIL_NETWORK_STATS_ENABLED configuration option
    6422             :  * will also be reset. That is, that the next network access will check its
    6423             :  * value again.
    6424             :  *
    6425             :  * @since GDAL 3.2.0
    6426             :  */
    6427             : 
    6428           2 : void VSINetworkStatsReset(void)
    6429             : {
    6430           2 :     cpl::NetworkStatisticsLogger::Reset();
    6431           2 : }
    6432             : 
    6433             : /************************************************************************/
    6434             : /*                 VSINetworkStatsGetAsSerializedJSON()                 */
    6435             : /************************************************************************/
    6436             : 
    6437             : /**
    6438             :  * \brief Return network related statistics, as a JSON serialized object.
    6439             :  *
    6440             :  * Statistics collecting should be enabled with the
    6441             :  CPL_VSIL_NETWORK_STATS_ENABLED
    6442             :  * configuration option set to YES before any network activity starts
    6443             :  * (for efficiency, reading it is cached on first access, until
    6444             :  VSINetworkStatsReset() is called)
    6445             :  *
    6446             :  * Statistics can also be emitted on standard output at process termination if
    6447             :  * the CPL_VSIL_SHOW_NETWORK_STATS configuration option is set to YES.
    6448             :  *
    6449             :  * Example of output:
    6450             :  * \code{.js}
    6451             :  * {
    6452             :  *   "methods":{
    6453             :  *     "GET":{
    6454             :  *       "count":6,
    6455             :  *       "downloaded_bytes":40825
    6456             :  *     },
    6457             :  *     "PUT":{
    6458             :  *       "count":1,
    6459             :  *       "uploaded_bytes":35472
    6460             :  *     }
    6461             :  *   },
    6462             :  *   "handlers":{
    6463             :  *     "vsigs":{
    6464             :  *       "methods":{
    6465             :  *         "GET":{
    6466             :  *           "count":2,
    6467             :  *           "downloaded_bytes":446
    6468             :  *         },
    6469             :  *         "PUT":{
    6470             :  *           "count":1,
    6471             :  *           "uploaded_bytes":35472
    6472             :  *         }
    6473             :  *       },
    6474             :  *       "files":{
    6475             :  *         "\/vsigs\/spatialys\/byte.tif":{
    6476             :  *           "methods":{
    6477             :  *             "PUT":{
    6478             :  *               "count":1,
    6479             :  *               "uploaded_bytes":35472
    6480             :  *             }
    6481             :  *           },
    6482             :  *           "actions":{
    6483             :  *             "Write":{
    6484             :  *               "methods":{
    6485             :  *                 "PUT":{
    6486             :  *                   "count":1,
    6487             :  *                   "uploaded_bytes":35472
    6488             :  *                 }
    6489             :  *               }
    6490             :  *             }
    6491             :  *           }
    6492             :  *         }
    6493             :  *       },
    6494             :  *       "actions":{
    6495             :  *         "Stat":{
    6496             :  *           "methods":{
    6497             :  *             "GET":{
    6498             :  *               "count":2,
    6499             :  *               "downloaded_bytes":446
    6500             :  *             }
    6501             :  *           },
    6502             :  *           "files":{
    6503             :  *             "\/vsigs\/spatialys\/byte.tif\/":{
    6504             :  *               "methods":{
    6505             :  *                 "GET":{
    6506             :  *                   "count":1,
    6507             :  *                   "downloaded_bytes":181
    6508             :  *                 }
    6509             :  *               }
    6510             :  *             }
    6511             :  *           }
    6512             :  *         }
    6513             :  *       }
    6514             :  *     },
    6515             :  *     "vsis3":{
    6516             :  *          [...]
    6517             :  *     }
    6518             :  *   }
    6519             :  * }
    6520             :  * \endcode
    6521             :  *
    6522             :  * @param papszOptions Unused.
    6523             :  * @return a JSON serialized string to free with VSIFree(), or nullptr
    6524             :  * @since GDAL 3.2.0
    6525             :  */
    6526             : 
    6527           1 : char *VSINetworkStatsGetAsSerializedJSON(CPL_UNUSED char **papszOptions)
    6528             : {
    6529           1 :     return CPLStrdup(
    6530           2 :         cpl::NetworkStatisticsLogger::GetReportAsSerializedJSON().c_str());
    6531             : }
    6532             : 
    6533             : #endif /* HAVE_CURL */
    6534             : 
    6535             : #undef ENABLE_DEBUG

Generated by: LCOV version 1.14