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