Coverage Report

Created: 2025-08-28 06:57

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