LCOV - code coverage report
Current view: top level - port - cpl_vsil_curl.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 2505 3260 76.8 %
Date: 2026-08-19 02:25:49 Functions: 157 170 92.4 %

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

Generated by: LCOV version 1.14