forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdalopeninfo.cpp
497 lines (449 loc) · 16.8 KB
/
gdalopeninfo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/******************************************************************************
*
* Project: GDAL Core
* Purpose: Implementation of GDALOpenInfo class.
* Author: Frank Warmerdam, [email protected]
*
**********************************************************************
* Copyright (c) 2002, Frank Warmerdam
* Copyright (c) 2008-2012, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "gdal_priv.h" // Must be included first for mingw VSIStatBufL.
#include "cpl_port.h"
#include <cstdlib>
#include <cstring>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <algorithm>
#include <map>
#include <mutex>
#include <vector>
#include "cpl_config.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
#include "gdal.h"
// Keep in sync prototype of those 2 functions between gdalopeninfo.cpp,
// ogrsqlitedatasource.cpp and ogrgeopackagedatasource.cpp
void GDALOpenInfoDeclareFileNotToOpen(const char *pszFilename,
const GByte *pabyHeader,
int nHeaderBytes);
void GDALOpenInfoUnDeclareFileNotToOpen(const char *pszFilename);
/************************************************************************/
/* This whole section helps for SQLite/GPKG, especially with write-ahead
* log enabled. The issue is that sqlite3 relies on POSIX advisory locks to
* properly work and decide when to create/delete the wal related files.
* One issue with POSIX advisory locks is that if within the same process
* you do
* f1 = open('somefile')
* set locks on f1
* f2 = open('somefile')
* close(f2)
* The close(f2) will cancel the locks set on f1. The work on f1 is done by
* libsqlite3 whereas the work on f2 is done by GDALOpenInfo.
* So as soon as sqlite3 has opened a file we should make sure not to re-open
* it (actually close it) ourselves.
*/
namespace
{
struct FileNotToOpen
{
CPLString osFilename{};
int nRefCount{};
GByte *pabyHeader{nullptr};
int nHeaderBytes{0};
};
} // namespace
static std::mutex sFNTOMutex;
static std::map<CPLString, FileNotToOpen> *pMapFNTO = nullptr;
void GDALOpenInfoDeclareFileNotToOpen(const char *pszFilename,
const GByte *pabyHeader, int nHeaderBytes)
{
std::lock_guard<std::mutex> oLock(sFNTOMutex);
if (pMapFNTO == nullptr)
pMapFNTO = new std::map<CPLString, FileNotToOpen>();
auto oIter = pMapFNTO->find(pszFilename);
if (oIter != pMapFNTO->end())
{
oIter->second.nRefCount++;
}
else
{
FileNotToOpen fnto;
fnto.osFilename = pszFilename;
fnto.nRefCount = 1;
fnto.pabyHeader = static_cast<GByte *>(CPLMalloc(nHeaderBytes + 1));
memcpy(fnto.pabyHeader, pabyHeader, nHeaderBytes);
fnto.pabyHeader[nHeaderBytes] = 0;
fnto.nHeaderBytes = nHeaderBytes;
(*pMapFNTO)[pszFilename] = std::move(fnto);
}
}
void GDALOpenInfoUnDeclareFileNotToOpen(const char *pszFilename)
{
std::lock_guard<std::mutex> oLock(sFNTOMutex);
CPLAssert(pMapFNTO);
auto oIter = pMapFNTO->find(pszFilename);
CPLAssert(oIter != pMapFNTO->end());
oIter->second.nRefCount--;
if (oIter->second.nRefCount == 0)
{
CPLFree(oIter->second.pabyHeader);
pMapFNTO->erase(oIter);
}
if (pMapFNTO->empty())
{
delete pMapFNTO;
pMapFNTO = nullptr;
}
}
static GByte *GDALOpenInfoGetFileNotToOpen(const char *pszFilename,
int *pnHeaderBytes)
{
std::lock_guard<std::mutex> oLock(sFNTOMutex);
*pnHeaderBytes = 0;
if (pMapFNTO == nullptr)
{
return nullptr;
}
auto oIter = pMapFNTO->find(pszFilename);
if (oIter == pMapFNTO->end())
{
return nullptr;
}
*pnHeaderBytes = oIter->second.nHeaderBytes;
GByte *pabyHeader = static_cast<GByte *>(CPLMalloc(*pnHeaderBytes + 1));
memcpy(pabyHeader, oIter->second.pabyHeader, *pnHeaderBytes);
pabyHeader[*pnHeaderBytes] = 0;
return pabyHeader;
}
/************************************************************************/
/* ==================================================================== */
/* GDALOpenInfo */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* GDALOpenInfo() */
/************************************************************************/
/** Constructor/
* @param pszFilenameIn filename
* @param nOpenFlagsIn open flags
* @param papszSiblingsIn list of sibling files, or NULL.
*/
GDALOpenInfo::GDALOpenInfo(const char *pszFilenameIn, int nOpenFlagsIn,
const char *const *papszSiblingsIn)
: bHasGotSiblingFiles(false), papszSiblingFiles(nullptr),
nHeaderBytesTried(0), pszFilename(CPLStrdup(pszFilenameIn)),
papszOpenOptions(nullptr),
eAccess(nOpenFlagsIn & GDAL_OF_UPDATE ? GA_Update : GA_ReadOnly),
nOpenFlags(nOpenFlagsIn), bStatOK(FALSE), bIsDirectory(FALSE),
fpL(nullptr), nHeaderBytes(0), pabyHeader(nullptr),
papszAllowedDrivers(nullptr)
{
if (STARTS_WITH(pszFilename, "MVT:/vsi"))
return;
/* -------------------------------------------------------------------- */
/* Ensure that C: is treated as C:\ so we can stat it on */
/* Windows. Similar to what is done in CPLStat(). */
/* -------------------------------------------------------------------- */
#ifdef _WIN32
if (strlen(pszFilenameIn) == 2 && pszFilenameIn[1] == ':')
{
char szAltPath[10];
strcpy(szAltPath, pszFilenameIn);
strcat(szAltPath, "\\");
CPLFree(pszFilename);
pszFilename = CPLStrdup(szAltPath);
}
#endif // WIN32
/* -------------------------------------------------------------------- */
/* Collect information about the file. */
/* -------------------------------------------------------------------- */
#ifdef HAVE_READLINK
bool bHasRetried = false;
retry: // TODO(schwehr): Stop using goto.
#endif // HAVE_READLINK
#if !(defined(_WIN32) || defined(__linux__) || defined(__ANDROID__) || \
(defined(__MACH__) && defined(__APPLE__)))
/* On BSDs, fread() on a directory returns non zero, so we have to */
/* do a stat() before to check the nature of pszFilename. */
bool bPotentialDirectory = (eAccess == GA_ReadOnly);
#else
bool bPotentialDirectory = false;
#endif
/* Check if the filename might be a directory of a special virtual file
* system */
if (STARTS_WITH(pszFilename, "/vsizip/") ||
STARTS_WITH(pszFilename, "/vsitar/") ||
STARTS_WITH(pszFilename, "/vsi7z/") ||
STARTS_WITH(pszFilename, "/vsirar/"))
{
const char *pszExt = CPLGetExtension(pszFilename);
if (EQUAL(pszExt, "zip") || EQUAL(pszExt, "tar") ||
EQUAL(pszExt, "gz") || EQUAL(pszExt, "7z") ||
EQUAL(pszExt, "rar") ||
pszFilename[strlen(pszFilename) - 1] == '}'
#ifdef DEBUG
// For AFL, so that .cur_input is detected as the archive filename.
|| EQUAL(CPLGetFilename(pszFilename), ".cur_input")
#endif // DEBUG
)
{
bPotentialDirectory = true;
}
}
else if (STARTS_WITH(pszFilename, "/vsicurl/"))
{
bPotentialDirectory = true;
}
if (bPotentialDirectory)
{
int nStatFlags = VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG;
if (nOpenFlagsIn & GDAL_OF_VERBOSE_ERROR)
nStatFlags |= VSI_STAT_SET_ERROR_FLAG;
// For those special files, opening them with VSIFOpenL() might result
// in content, even if they should be considered as directories, so
// use stat.
VSIStatBufL sStat;
if (VSIStatExL(pszFilename, &sStat, nStatFlags) == 0)
{
bStatOK = TRUE;
if (VSI_ISDIR(sStat.st_mode))
bIsDirectory = TRUE;
}
}
pabyHeader = GDALOpenInfoGetFileNotToOpen(pszFilename, &nHeaderBytes);
if (!bIsDirectory && pabyHeader == nullptr)
{
fpL = VSIFOpenExL(pszFilename, (eAccess == GA_Update) ? "r+b" : "rb",
(nOpenFlagsIn & GDAL_OF_VERBOSE_ERROR) > 0);
}
if (pabyHeader)
{
bStatOK = TRUE;
nHeaderBytesTried = nHeaderBytes;
}
else if (fpL != nullptr)
{
bStatOK = TRUE;
int nBufSize =
atoi(CPLGetConfigOption("GDAL_INGESTED_BYTES_AT_OPEN", "1024"));
if (nBufSize < 1024)
nBufSize = 1024;
else if (nBufSize > 10 * 1024 * 1024)
nBufSize = 10 * 1024 * 1024;
pabyHeader = static_cast<GByte *>(CPLCalloc(nBufSize + 1, 1));
nHeaderBytesTried = nBufSize;
nHeaderBytes =
static_cast<int>(VSIFReadL(pabyHeader, 1, nHeaderBytesTried, fpL));
VSIRewindL(fpL);
/* If we cannot read anything, check if it is not a directory instead */
VSIStatBufL sStat;
if (nHeaderBytes == 0 &&
VSIStatExL(pszFilename, &sStat,
VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
VSI_ISDIR(sStat.st_mode))
{
CPL_IGNORE_RET_VAL(VSIFCloseL(fpL));
fpL = nullptr;
CPLFree(pabyHeader);
pabyHeader = nullptr;
bIsDirectory = TRUE;
}
}
else if (!bStatOK)
{
VSIStatBufL sStat;
if (!bPotentialDirectory &&
VSIStatExL(pszFilename, &sStat,
VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0)
{
bStatOK = TRUE;
if (VSI_ISDIR(sStat.st_mode))
bIsDirectory = TRUE;
}
#ifdef HAVE_READLINK
else if (!bHasRetried && !STARTS_WITH(pszFilename, "/vsi"))
{
// If someone creates a file with "ln -sf
// /vsicurl/http://download.osgeo.org/gdal/data/gtiff/utm.tif
// my_remote_utm.tif" we will be able to open it by passing
// my_remote_utm.tif. This helps a lot for GDAL based readers that
// only provide file explorers to open datasets.
const int nBufSize = 2048;
std::vector<char> oFilename(nBufSize);
char *szPointerFilename = &oFilename[0];
int nBytes = static_cast<int>(
readlink(pszFilename, szPointerFilename, nBufSize));
if (nBytes != -1)
{
szPointerFilename[std::min(nBytes, nBufSize - 1)] = 0;
CPLFree(pszFilename);
pszFilename = CPLStrdup(szPointerFilename);
papszSiblingsIn = nullptr;
bHasRetried = true;
goto retry;
}
}
#endif // HAVE_READLINK
}
/* -------------------------------------------------------------------- */
/* Capture sibling list either from passed in values, or by */
/* scanning for them only if requested through GetSiblingFiles(). */
/* -------------------------------------------------------------------- */
if (papszSiblingsIn != nullptr)
{
papszSiblingFiles = CSLDuplicate(papszSiblingsIn);
bHasGotSiblingFiles = true;
}
else if (bStatOK && !bIsDirectory)
{
papszSiblingFiles = VSISiblingFiles(pszFilename);
if (papszSiblingFiles != nullptr)
{
bHasGotSiblingFiles = true;
}
else
{
const char *pszOptionVal = VSIGetPathSpecificOption(
pszFilename, "GDAL_DISABLE_READDIR_ON_OPEN", "NO");
if (EQUAL(pszOptionVal, "EMPTY_DIR"))
{
papszSiblingFiles =
CSLAddString(nullptr, CPLGetFilename(pszFilename));
bHasGotSiblingFiles = true;
}
else if (CPLTestBool(pszOptionVal))
{
/* skip reading the directory */
papszSiblingFiles = nullptr;
bHasGotSiblingFiles = true;
}
else
{
/* will be lazy loaded */
papszSiblingFiles = nullptr;
bHasGotSiblingFiles = false;
}
}
}
else
{
papszSiblingFiles = nullptr;
bHasGotSiblingFiles = true;
}
}
/************************************************************************/
/* ~GDALOpenInfo() */
/************************************************************************/
GDALOpenInfo::~GDALOpenInfo()
{
VSIFree(pabyHeader);
CPLFree(pszFilename);
if (fpL != nullptr)
CPL_IGNORE_RET_VAL(VSIFCloseL(fpL));
CSLDestroy(papszSiblingFiles);
}
/************************************************************************/
/* GetSiblingFiles() */
/************************************************************************/
/** Return sibling files.
*
* If the list of sibling files has not already been established, it will be,
* unless the GDAL_DISABLE_READDIR_ON_OPEN configuration option has been set to
* YES or EMPTY_DIR when this instance was constructed.
*
* @return sibling files. Ownership belongs to "this".
*/
char **GDALOpenInfo::GetSiblingFiles()
{
if (bHasGotSiblingFiles)
return papszSiblingFiles;
bHasGotSiblingFiles = true;
papszSiblingFiles = VSISiblingFiles(pszFilename);
if (papszSiblingFiles != nullptr)
{
return papszSiblingFiles;
}
CPLString osDir = CPLGetDirname(pszFilename);
const int nMaxFiles = atoi(VSIGetPathSpecificOption(
pszFilename, "GDAL_READDIR_LIMIT_ON_OPEN", "1000"));
papszSiblingFiles = VSIReadDirEx(osDir, nMaxFiles);
if (nMaxFiles > 0 && CSLCount(papszSiblingFiles) > nMaxFiles)
{
CPLDebug("GDAL", "GDAL_READDIR_LIMIT_ON_OPEN reached on %s",
osDir.c_str());
CSLDestroy(papszSiblingFiles);
papszSiblingFiles = nullptr;
}
return papszSiblingFiles;
}
/************************************************************************/
/* StealSiblingFiles() */
/* */
/* Same as GetSiblingFiles() except that the list is stealed */
/* (ie ownership transferred to the caller) and the associated */
/* member variable is set to NULL. */
/************************************************************************/
/** Return sibling files and steal reference
* @return sibling files. Ownership below to the caller (must be freed with
* CSLDestroy)
*/
char **GDALOpenInfo::StealSiblingFiles()
{
char **papszRet = GetSiblingFiles();
papszSiblingFiles = nullptr;
return papszRet;
}
/************************************************************************/
/* AreSiblingFilesLoaded() */
/************************************************************************/
/** Return whether sibling files have been loaded.
* @return true or false.
*/
bool GDALOpenInfo::AreSiblingFilesLoaded() const
{
return bHasGotSiblingFiles;
}
/************************************************************************/
/* TryToIngest() */
/************************************************************************/
/** Ingest bytes from the file.
* @param nBytes number of bytes to ingest.
* @return TRUE if successful
*/
int GDALOpenInfo::TryToIngest(int nBytes)
{
if (fpL == nullptr)
return FALSE;
if (nHeaderBytes < nHeaderBytesTried)
return TRUE;
pabyHeader = static_cast<GByte *>(CPLRealloc(pabyHeader, nBytes + 1));
memset(pabyHeader, 0, nBytes + 1);
VSIRewindL(fpL);
nHeaderBytesTried = nBytes;
nHeaderBytes = static_cast<int>(VSIFReadL(pabyHeader, 1, nBytes, fpL));
VSIRewindL(fpL);
return TRUE;
}
/************************************************************************/
/* IsSingleAllowedDriver() */
/************************************************************************/
/** Returns true if the driver name is the single in the list of allowed
* drivers.
*
* @param pszDriverName Driver name to test.
* @return true if the driver name is the single in the list of allowed
* drivers.
* @since GDAL 3.10
*/
bool GDALOpenInfo::IsSingleAllowedDriver(const char *pszDriverName) const
{
return papszAllowedDrivers && papszAllowedDrivers[0] &&
!papszAllowedDrivers[1] &&
EQUAL(papszAllowedDrivers[0], pszDriverName);
}