Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL Core
4 : * Purpose: Implementation of GDALDriver class (and C wrappers)
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 1998, 2000, Frank Warmerdam
9 : * Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "cpl_port.h"
15 : #include "gdal.h"
16 : #include "gdal_priv.h"
17 : #include "gdal_rat.h"
18 : #include "gdalalgorithm.h"
19 : #include "gdal_known_connection_prefixes.h"
20 :
21 : #include <algorithm>
22 : #include <cerrno>
23 : #include <cstdlib>
24 : #include <cstring>
25 : #include <set>
26 : #include <sys/stat.h>
27 :
28 : #include "cpl_conv.h"
29 : #include "cpl_error.h"
30 : #include "cpl_minixml.h"
31 : #include "cpl_multiproc.h"
32 : #include "cpl_progress.h"
33 : #include "cpl_string.h"
34 : #include "cpl_vsi.h"
35 : #include "ograpispy.h"
36 : #include "ogr_core.h"
37 : #include "ogrsf_frmts.h"
38 :
39 : /************************************************************************/
40 : /* GDALDriver() */
41 : /************************************************************************/
42 :
43 : GDALDriver::GDALDriver() = default;
44 :
45 : /************************************************************************/
46 : /* ~GDALDriver() */
47 : /************************************************************************/
48 :
49 504146 : GDALDriver::~GDALDriver()
50 :
51 : {
52 284002 : if (pfnUnloadDriver != nullptr)
53 8703 : pfnUnloadDriver(this);
54 504146 : }
55 :
56 : /************************************************************************/
57 : /* GDALCreateDriver() */
58 : /************************************************************************/
59 :
60 : /**
61 : * \brief Create a GDALDriver.
62 : *
63 : * Creates a driver in the GDAL heap.
64 : */
65 :
66 234 : GDALDriverH CPL_STDCALL GDALCreateDriver()
67 : {
68 234 : return new GDALDriver();
69 : }
70 :
71 : /************************************************************************/
72 : /* GDALDestroyDriver() */
73 : /************************************************************************/
74 :
75 : /**
76 : * \brief Destroy a GDALDriver.
77 : *
78 : * This is roughly equivalent to deleting the driver, but is guaranteed
79 : * to take place in the GDAL heap. It is important this that function
80 : * not be called on a driver that is registered with the GDALDriverManager.
81 : *
82 : * @param hDriver the driver to destroy.
83 : */
84 :
85 0 : void CPL_STDCALL GDALDestroyDriver(GDALDriverH hDriver)
86 :
87 : {
88 0 : if (hDriver != nullptr)
89 0 : delete GDALDriver::FromHandle(hDriver);
90 0 : }
91 :
92 : /************************************************************************/
93 : /* Open() */
94 : /************************************************************************/
95 :
96 : //! @cond Doxygen_Suppress
97 :
98 580253 : GDALDataset *GDALDriver::Open(GDALOpenInfo *poOpenInfo, bool bSetOpenOptions)
99 : {
100 :
101 580253 : GDALDataset *poDS = nullptr;
102 580253 : pfnOpen = GetOpenCallback();
103 580253 : if (pfnOpen != nullptr)
104 : {
105 580249 : poDS = pfnOpen(poOpenInfo);
106 : }
107 4 : else if (pfnOpenWithDriverArg != nullptr)
108 : {
109 4 : poDS = pfnOpenWithDriverArg(this, poOpenInfo);
110 : }
111 :
112 580253 : if (poDS)
113 : {
114 : // Only set GDAL_OF_THREAD_SAFE if the driver itself has set it in
115 : // poDS->nOpenFlags
116 62643 : int nOpenFlags = poOpenInfo->nOpenFlags &
117 : ~(GDAL_OF_FROM_GDALOPEN | GDAL_OF_THREAD_SAFE);
118 62643 : if (poDS->nOpenFlags & GDAL_OF_THREAD_SAFE)
119 915 : nOpenFlags |= GDAL_OF_THREAD_SAFE;
120 62643 : poDS->nOpenFlags = nOpenFlags;
121 :
122 62643 : if (strlen(poDS->GetDescription()) == 0)
123 14363 : poDS->SetDescription(poOpenInfo->pszFilename);
124 :
125 62643 : if (poDS->poDriver == nullptr)
126 58750 : poDS->poDriver = this;
127 :
128 62643 : if (poDS->papszOpenOptions == nullptr && bSetOpenOptions)
129 : {
130 29 : poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
131 : }
132 :
133 62643 : if (!(poOpenInfo->nOpenFlags & GDAL_OF_INTERNAL))
134 : {
135 50067 : if (CPLGetPID() != GDALGetResponsiblePIDForCurrentThread())
136 6 : CPLDebug(
137 : "GDAL",
138 : "GDALOpen(%s, this=%p) succeeds as "
139 : "%s (pid=%d, responsiblePID=%d).",
140 6 : poOpenInfo->pszFilename, poDS, GetDescription(),
141 6 : static_cast<int>(CPLGetPID()),
142 6 : static_cast<int>(GDALGetResponsiblePIDForCurrentThread()));
143 : else
144 50061 : CPLDebug("GDAL", "GDALOpen(%s, this=%p) succeeds as %s.",
145 50061 : poOpenInfo->pszFilename, poDS, GetDescription());
146 :
147 50067 : poDS->AddToDatasetOpenList();
148 : }
149 : }
150 :
151 580253 : return poDS;
152 : }
153 :
154 : //! @endcond
155 :
156 : /************************************************************************/
157 : /* Create() */
158 : /************************************************************************/
159 :
160 : /**
161 : * \brief Create a new dataset with this driver.
162 : *
163 : * What argument values are legal for particular drivers is driver specific,
164 : * and there is no way to query in advance to establish legal values.
165 : *
166 : * That function will try to validate the creation option list passed to the
167 : * driver with the GDALValidateCreationOptions() method. This check can be
168 : * disabled by defining the configuration option
169 : * GDAL_VALIDATE_CREATION_OPTIONS=NO.
170 : *
171 : * After you have finished working with the returned dataset, it is
172 : * <b>required</b> to close it with GDALClose(). This does not only close the
173 : * file handle, but also ensures that all the data and metadata has been written
174 : * to the dataset (GDALFlushCache() is not sufficient for that purpose).
175 : *
176 : * The arguments nXSize, nYSize and nBands can be passed to 0 when
177 : * creating a vector-only dataset for a compatible driver.
178 : *
179 : * Equivalent of the C function GDALCreate().
180 : *
181 : * @param pszFilename the name of the dataset to create. UTF-8 encoded.
182 : * @param nXSize width of created raster in pixels.
183 : * @param nYSize height of created raster in pixels.
184 : * @param nBands number of bands.
185 : * @param eType type of raster.
186 : * @param papszOptions list of driver specific control parameters.
187 : * The APPEND_SUBDATASET=YES option can be
188 : * specified to avoid prior destruction of existing dataset.
189 : *
190 : * @return NULL on failure, or a new GDALDataset.
191 : */
192 :
193 26174 : GDALDataset *GDALDriver::Create(const char *pszFilename, int nXSize, int nYSize,
194 : int nBands, GDALDataType eType,
195 : CSLConstList papszOptions)
196 :
197 : {
198 : /* -------------------------------------------------------------------- */
199 : /* Does this format support creation. */
200 : /* -------------------------------------------------------------------- */
201 26174 : pfnCreate = GetCreateCallback();
202 26174 : if (CPL_UNLIKELY(pfnCreate == nullptr && pfnCreateEx == nullptr &&
203 : pfnCreateVectorOnly == nullptr))
204 : {
205 1 : CPLError(CE_Failure, CPLE_NotSupported,
206 : "GDALDriver::Create() ... no create method implemented"
207 : " for this format.");
208 :
209 1 : return nullptr;
210 : }
211 : /* -------------------------------------------------------------------- */
212 : /* Do some rudimentary argument checking. */
213 : /* -------------------------------------------------------------------- */
214 26173 : if (CPL_UNLIKELY(nBands < 0))
215 : {
216 1 : CPLError(CE_Failure, CPLE_AppDefined,
217 : "Attempt to create dataset with %d bands is illegal, "
218 : "Must be >= 0.",
219 : nBands);
220 1 : return nullptr;
221 : }
222 :
223 26172 : if (CPL_UNLIKELY(GetMetadataItem(GDAL_DCAP_RASTER) != nullptr &&
224 : GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr &&
225 26172 : (nXSize < 1 || nYSize < 1)))
226 : {
227 2 : CPLError(CE_Failure, CPLE_AppDefined,
228 : "Attempt to create %dx%d dataset is illegal, "
229 : "sizes must be larger than zero.",
230 : nXSize, nYSize);
231 2 : return nullptr;
232 : }
233 :
234 26170 : if (CPL_UNLIKELY(nBands != 0 &&
235 : (eType == GDT_Unknown || eType == GDT_TypeCount)))
236 : {
237 1 : CPLError(CE_Failure, CPLE_IllegalArg,
238 : "Illegal GDT_Unknown/GDT_TypeCount argument");
239 1 : return nullptr;
240 : }
241 :
242 : /* -------------------------------------------------------------------- */
243 : /* Make sure we cleanup if there is an existing dataset of this */
244 : /* name. But even if that seems to fail we will continue since */
245 : /* it might just be a corrupt file or something. */
246 : /* -------------------------------------------------------------------- */
247 26169 : if (!CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false))
248 : {
249 : // Someone issuing Create("foo.tif") on a
250 : // memory driver doesn't expect files with those names to be deleted
251 : // on a file system...
252 : // This is somewhat messy. Ideally there should be a way for the
253 : // driver to overload the default behavior
254 26148 : if (!EQUAL(GetDescription(), "MEM") &&
255 40093 : !EQUAL(GetDescription(), "Memory") &&
256 : // ogr2ogr -f PostgreSQL might reach the Delete method of the
257 : // PostgisRaster driver which is undesirable
258 13945 : !EQUAL(GetDescription(), "PostgreSQL"))
259 : {
260 13943 : QuietDelete(pszFilename);
261 : }
262 : }
263 :
264 : /* -------------------------------------------------------------------- */
265 : /* Validate creation options. */
266 : /* -------------------------------------------------------------------- */
267 26169 : if (CPLTestBool(
268 : CPLGetConfigOption("GDAL_VALIDATE_CREATION_OPTIONS", "YES")))
269 26169 : GDALValidateCreationOptions(this, papszOptions);
270 :
271 : /* -------------------------------------------------------------------- */
272 : /* Proceed with creation. */
273 : /* -------------------------------------------------------------------- */
274 52338 : CPLDebug("GDAL", "GDALDriver::Create(%s,%s,%d,%d,%d,%s,%p)",
275 26169 : GetDescription(), pszFilename, nXSize, nYSize, nBands,
276 : GDALGetDataTypeName(eType), papszOptions);
277 :
278 26169 : GDALDataset *poDS = nullptr;
279 26169 : if (pfnCreateEx != nullptr)
280 : {
281 0 : poDS = pfnCreateEx(this, pszFilename, nXSize, nYSize, nBands, eType,
282 : const_cast<char **>(papszOptions));
283 : }
284 26169 : else if (pfnCreate != nullptr)
285 : {
286 26169 : poDS = pfnCreate(pszFilename, nXSize, nYSize, nBands, eType,
287 : const_cast<char **>(papszOptions));
288 : }
289 0 : else if (nBands < 1)
290 : {
291 0 : poDS = pfnCreateVectorOnly(this, pszFilename,
292 : const_cast<char **>(papszOptions));
293 : }
294 :
295 26169 : if (poDS != nullptr)
296 : {
297 49414 : if (poDS->GetDescription() == nullptr ||
298 24707 : strlen(poDS->GetDescription()) == 0)
299 22040 : poDS->SetDescription(pszFilename);
300 :
301 24707 : if (poDS->poDriver == nullptr)
302 24210 : poDS->poDriver = this;
303 :
304 24707 : poDS->AddToDatasetOpenList();
305 : }
306 :
307 26169 : return poDS;
308 : }
309 :
310 : /************************************************************************/
311 : /* GDALCreate() */
312 : /************************************************************************/
313 :
314 : /**
315 : * \brief Create a new dataset with this driver.
316 : *
317 : * @see GDALDriver::Create()
318 : */
319 :
320 21455 : GDALDatasetH CPL_DLL CPL_STDCALL GDALCreate(GDALDriverH hDriver,
321 : const char *pszFilename, int nXSize,
322 : int nYSize, int nBands,
323 : GDALDataType eBandType,
324 : CSLConstList papszOptions)
325 :
326 : {
327 21455 : VALIDATE_POINTER1(hDriver, "GDALCreate", nullptr);
328 :
329 21455 : GDALDatasetH hDS = GDALDriver::FromHandle(hDriver)->Create(
330 : pszFilename, nXSize, nYSize, nBands, eBandType, papszOptions);
331 :
332 : #ifdef OGRAPISPY_ENABLED
333 21455 : if (nBands < 1)
334 : {
335 4108 : OGRAPISpyCreateDataSource(hDriver, pszFilename,
336 : const_cast<char **>(papszOptions), hDS);
337 : }
338 : #endif
339 :
340 21455 : return hDS;
341 : }
342 :
343 : /************************************************************************/
344 : /* CreateMultiDimensional() */
345 : /************************************************************************/
346 :
347 : /**
348 : * \brief Create a new multidimensional dataset with this driver.
349 : *
350 : * Only drivers that advertise the GDAL_DCAP_MULTIDIM_RASTER capability and
351 : * implement the pfnCreateMultiDimensional method might return a non nullptr
352 : * GDALDataset.
353 : *
354 : * This is the same as the C function GDALCreateMultiDimensional().
355 : *
356 : * @param pszFilename the name of the dataset to create. UTF-8 encoded.
357 : * @param papszRootGroupOptions driver specific options regarding the creation
358 : * of the root group. Might be nullptr.
359 : * @param papszOptions driver specific options regarding the creation
360 : * of the dataset. Might be nullptr.
361 : * @return a new dataset, or nullptr in case of failure.
362 : *
363 : * @since GDAL 3.1
364 : */
365 :
366 : GDALDataset *
367 628 : GDALDriver::CreateMultiDimensional(const char *pszFilename,
368 : CSLConstList papszRootGroupOptions,
369 : CSLConstList papszOptions)
370 :
371 : {
372 : /* -------------------------------------------------------------------- */
373 : /* Does this format support creation. */
374 : /* -------------------------------------------------------------------- */
375 628 : pfnCreateMultiDimensional = GetCreateMultiDimensionalCallback();
376 628 : if (pfnCreateMultiDimensional == nullptr)
377 : {
378 0 : CPLError(CE_Failure, CPLE_NotSupported,
379 : "GDALDriver::CreateMultiDimensional() ... "
380 : "no CreateMultiDimensional method implemented "
381 : "for this format.");
382 :
383 0 : return nullptr;
384 : }
385 :
386 : /* -------------------------------------------------------------------- */
387 : /* Validate creation options. */
388 : /* -------------------------------------------------------------------- */
389 628 : if (CPLTestBool(
390 : CPLGetConfigOption("GDAL_VALIDATE_CREATION_OPTIONS", "YES")))
391 : {
392 : const char *pszOptionList =
393 628 : GetMetadataItem(GDAL_DMD_MULTIDIM_DATASET_CREATIONOPTIONLIST);
394 1256 : CPLString osDriver;
395 628 : osDriver.Printf("driver %s", GetDescription());
396 628 : GDALValidateOptions(GDALDriver::ToHandle(this), pszOptionList,
397 : papszOptions, "creation option", osDriver);
398 : }
399 :
400 628 : auto poDstDS = pfnCreateMultiDimensional(pszFilename, papszRootGroupOptions,
401 : papszOptions);
402 :
403 628 : if (poDstDS != nullptr)
404 : {
405 1252 : if (poDstDS->GetDescription() == nullptr ||
406 626 : strlen(poDstDS->GetDescription()) == 0)
407 200 : poDstDS->SetDescription(pszFilename);
408 :
409 626 : if (poDstDS->poDriver == nullptr)
410 624 : poDstDS->poDriver = this;
411 : }
412 :
413 628 : return poDstDS;
414 : }
415 :
416 : /************************************************************************/
417 : /* GDALCreateMultiDimensional() */
418 : /************************************************************************/
419 :
420 : /** \brief Create a new multidimensional dataset with this driver.
421 : *
422 : * This is the same as the C++ method GDALDriver::CreateMultiDimensional().
423 : */
424 565 : GDALDatasetH GDALCreateMultiDimensional(GDALDriverH hDriver,
425 : const char *pszName,
426 : CSLConstList papszRootGroupOptions,
427 : CSLConstList papszOptions)
428 : {
429 565 : VALIDATE_POINTER1(hDriver, __func__, nullptr);
430 565 : VALIDATE_POINTER1(pszName, __func__, nullptr);
431 565 : return GDALDataset::ToHandle(
432 : GDALDriver::FromHandle(hDriver)->CreateMultiDimensional(
433 565 : pszName, papszRootGroupOptions, papszOptions));
434 : }
435 :
436 : /************************************************************************/
437 : /* DefaultCreateCopyMultiDimensional() */
438 : /************************************************************************/
439 :
440 : //! @cond Doxygen_Suppress
441 :
442 31 : CPLErr GDALDriver::DefaultCreateCopyMultiDimensional(
443 : GDALDataset *poSrcDS, GDALDataset *poDstDS, bool bStrict,
444 : CSLConstList papszOptions, GDALProgressFunc pfnProgress,
445 : void *pProgressData)
446 : {
447 31 : if (pfnProgress == nullptr)
448 4 : pfnProgress = GDALDummyProgress;
449 :
450 62 : auto poSrcRG = poSrcDS->GetRootGroup();
451 31 : if (!poSrcRG)
452 0 : return CE_Failure;
453 62 : auto poDstRG = poDstDS->GetRootGroup();
454 31 : if (!poDstRG)
455 0 : return CE_Failure;
456 31 : GUInt64 nCurCost = 0;
457 62 : return poDstRG->CopyFrom(poDstRG, poSrcDS, poSrcRG, bStrict, nCurCost,
458 : poSrcRG->GetTotalCopyCost(), pfnProgress,
459 31 : pProgressData, papszOptions)
460 31 : ? CE_None
461 31 : : CE_Failure;
462 : }
463 :
464 : //! @endcond
465 :
466 : /************************************************************************/
467 : /* DefaultCopyMasks() */
468 : /************************************************************************/
469 :
470 : //! @cond Doxygen_Suppress
471 6356 : CPLErr GDALDriver::DefaultCopyMasks(GDALDataset *poSrcDS, GDALDataset *poDstDS,
472 : int bStrict)
473 :
474 : {
475 6356 : return DefaultCopyMasks(poSrcDS, poDstDS, bStrict, nullptr, nullptr,
476 6356 : nullptr);
477 : }
478 :
479 8467 : CPLErr GDALDriver::DefaultCopyMasks(GDALDataset *poSrcDS, GDALDataset *poDstDS,
480 : int bStrict, CSLConstList /*papszOptions*/,
481 : GDALProgressFunc pfnProgress,
482 : void *pProgressData)
483 :
484 : {
485 8467 : if (pfnProgress == nullptr)
486 6356 : pfnProgress = GDALDummyProgress;
487 :
488 8467 : int nBands = poSrcDS->GetRasterCount();
489 8467 : if (nBands == 0)
490 0 : return CE_None;
491 :
492 : /* -------------------------------------------------------------------- */
493 : /* Try to copy mask if it seems appropriate. */
494 : /* -------------------------------------------------------------------- */
495 8467 : const char *papszOptions[2] = {"COMPRESSED=YES", nullptr};
496 8467 : CPLErr eErr = CE_None;
497 :
498 8467 : int nTotalBandsWithMask = 0;
499 29241 : for (int iBand = 0; iBand < nBands; ++iBand)
500 : {
501 20774 : GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
502 :
503 20774 : int nMaskFlags = poSrcBand->GetMaskFlags();
504 20774 : if (!(nMaskFlags &
505 : (GMF_ALL_VALID | GMF_PER_DATASET | GMF_ALPHA | GMF_NODATA)))
506 : {
507 8 : nTotalBandsWithMask++;
508 : }
509 : }
510 :
511 8467 : int iBandWithMask = 0;
512 29241 : for (int iBand = 0; eErr == CE_None && iBand < nBands; ++iBand)
513 : {
514 20774 : GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
515 :
516 20774 : int nMaskFlags = poSrcBand->GetMaskFlags();
517 20774 : if (eErr == CE_None && !(nMaskFlags & (GMF_ALL_VALID | GMF_PER_DATASET |
518 : GMF_ALPHA | GMF_NODATA)))
519 : {
520 8 : GDALRasterBand *poDstBand = poDstDS->GetRasterBand(iBand + 1);
521 8 : if (poDstBand != nullptr)
522 : {
523 8 : eErr = poDstBand->CreateMaskBand(nMaskFlags);
524 8 : if (eErr == CE_None)
525 : {
526 24 : void *pScaledData = GDALCreateScaledProgress(
527 8 : double(iBandWithMask) /
528 8 : std::max(1, nTotalBandsWithMask),
529 8 : double(iBandWithMask + 1) /
530 8 : std::max(1, nTotalBandsWithMask),
531 : pfnProgress, pProgressData);
532 16 : eErr = GDALRasterBandCopyWholeRaster(
533 8 : poSrcBand->GetMaskBand(), poDstBand->GetMaskBand(),
534 : papszOptions, GDALScaledProgress, pScaledData);
535 8 : GDALDestroyScaledProgress(pScaledData);
536 : }
537 0 : else if (!bStrict)
538 : {
539 0 : eErr = CE_None;
540 : }
541 : }
542 : }
543 : }
544 :
545 : /* -------------------------------------------------------------------- */
546 : /* Try to copy a per-dataset mask if we have one. */
547 : /* -------------------------------------------------------------------- */
548 8467 : const int nMaskFlags = poSrcDS->GetRasterBand(1)->GetMaskFlags();
549 8467 : if (eErr == CE_None &&
550 8467 : !(nMaskFlags & (GMF_ALL_VALID | GMF_ALPHA | GMF_NODATA)) &&
551 13 : (nMaskFlags & GMF_PER_DATASET))
552 : {
553 8 : eErr = poDstDS->CreateMaskBand(nMaskFlags);
554 8 : if (eErr == CE_None)
555 : {
556 8 : eErr = GDALRasterBandCopyWholeRaster(
557 8 : poSrcDS->GetRasterBand(1)->GetMaskBand(),
558 8 : poDstDS->GetRasterBand(1)->GetMaskBand(), papszOptions,
559 : pfnProgress, pProgressData);
560 : }
561 0 : else if (!bStrict)
562 : {
563 0 : eErr = CE_None;
564 : }
565 : }
566 :
567 8467 : return eErr;
568 : }
569 :
570 : /************************************************************************/
571 : /* DefaultCreateCopy() */
572 : /************************************************************************/
573 :
574 1521 : GDALDataset *GDALDriver::DefaultCreateCopy(const char *pszFilename,
575 : GDALDataset *poSrcDS, int bStrict,
576 : CSLConstList papszOptions,
577 : GDALProgressFunc pfnProgress,
578 : void *pProgressData)
579 :
580 : {
581 1521 : if (pfnProgress == nullptr)
582 0 : pfnProgress = GDALDummyProgress;
583 :
584 1521 : CPLErrorReset();
585 :
586 : /* -------------------------------------------------------------------- */
587 : /* Use multidimensional raster API if available. */
588 : /* -------------------------------------------------------------------- */
589 3042 : auto poSrcGroup = poSrcDS->GetRootGroup();
590 1521 : if (poSrcGroup != nullptr && GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
591 : {
592 54 : CPLStringList aosDatasetCO;
593 34 : for (const char *pszOption : cpl::Iterate(papszOptions))
594 : {
595 7 : if (!STARTS_WITH_CI(pszOption, "ARRAY:"))
596 0 : aosDatasetCO.AddString(pszOption);
597 : }
598 : auto poDstDS = std::unique_ptr<GDALDataset>(
599 54 : CreateMultiDimensional(pszFilename, nullptr, aosDatasetCO.List()));
600 27 : if (!poDstDS)
601 0 : return nullptr;
602 54 : auto poDstGroup = poDstDS->GetRootGroup();
603 27 : if (!poDstGroup)
604 0 : return nullptr;
605 27 : if (DefaultCreateCopyMultiDimensional(
606 27 : poSrcDS, poDstDS.get(), CPL_TO_BOOL(bStrict), papszOptions,
607 27 : pfnProgress, pProgressData) != CE_None)
608 0 : return nullptr;
609 27 : return poDstDS.release();
610 : }
611 :
612 : /* -------------------------------------------------------------------- */
613 : /* Validate that we can create the output as requested. */
614 : /* -------------------------------------------------------------------- */
615 1494 : const int nXSize = poSrcDS->GetRasterXSize();
616 1494 : const int nYSize = poSrcDS->GetRasterYSize();
617 1494 : const int nBands = poSrcDS->GetRasterCount();
618 :
619 1494 : CPLDebug("GDAL", "Using default GDALDriver::CreateCopy implementation.");
620 :
621 1494 : const int nLayerCount = poSrcDS->GetLayerCount();
622 1518 : if (nBands == 0 && nLayerCount == 0 &&
623 24 : GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
624 : {
625 17 : CPLError(CE_Failure, CPLE_NotSupported,
626 : "GDALDriver::DefaultCreateCopy does not support zero band");
627 17 : return nullptr;
628 : }
629 1477 : if (poSrcDS->GetDriver() != nullptr &&
630 1447 : poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_RASTER) != nullptr &&
631 1440 : poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr &&
632 2927 : GetMetadataItem(GDAL_DCAP_RASTER) == nullptr &&
633 3 : GetMetadataItem(GDAL_DCAP_VECTOR) != nullptr)
634 : {
635 3 : CPLError(CE_Failure, CPLE_NotSupported,
636 : "Source driver is raster-only whereas output driver is "
637 : "vector-only");
638 3 : return nullptr;
639 : }
640 1474 : else if (poSrcDS->GetDriver() != nullptr &&
641 1444 : poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_RASTER) ==
642 7 : nullptr &&
643 7 : poSrcDS->GetDriver()->GetMetadataItem(GDAL_DCAP_VECTOR) !=
644 7 : nullptr &&
645 2918 : GetMetadataItem(GDAL_DCAP_RASTER) != nullptr &&
646 0 : GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
647 : {
648 0 : CPLError(CE_Failure, CPLE_NotSupported,
649 : "Source driver is vector-only whereas output driver is "
650 : "raster-only");
651 0 : return nullptr;
652 : }
653 :
654 1474 : if (!pfnProgress(0.0, nullptr, pProgressData))
655 : {
656 2 : CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
657 2 : return nullptr;
658 : }
659 :
660 : /* -------------------------------------------------------------------- */
661 : /* Propagate some specific structural metadata as options if it */
662 : /* appears to be supported by the target driver and the caller */
663 : /* didn't provide values. */
664 : /* -------------------------------------------------------------------- */
665 1472 : char **papszCreateOptions = CSLDuplicate(papszOptions);
666 1472 : const char *const apszOptItems[] = {GDALMD_NBITS, GDAL_MDD_IMAGE_STRUCTURE,
667 : "PIXELTYPE", GDAL_MDD_IMAGE_STRUCTURE,
668 : nullptr};
669 :
670 4384 : for (int iOptItem = 0; nBands > 0 && apszOptItems[iOptItem] != nullptr;
671 2912 : iOptItem += 2)
672 : {
673 : // does the source have this metadata item on the first band?
674 2912 : auto poBand = poSrcDS->GetRasterBand(1);
675 2912 : poBand->EnablePixelTypeSignedByteWarning(false);
676 5824 : const char *pszValue = poBand->GetMetadataItem(
677 2912 : apszOptItems[iOptItem], apszOptItems[iOptItem + 1]);
678 2912 : poBand->EnablePixelTypeSignedByteWarning(true);
679 :
680 2912 : if (pszValue == nullptr)
681 2910 : continue;
682 :
683 : // Do not override provided value.
684 2 : if (CSLFetchNameValue(papszCreateOptions, pszValue) != nullptr)
685 0 : continue;
686 :
687 : // Does this appear to be a supported creation option on this driver?
688 : const char *pszOptionList =
689 2 : GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST);
690 :
691 2 : if (pszOptionList == nullptr ||
692 2 : strstr(pszOptionList, apszOptItems[iOptItem]) == nullptr)
693 0 : continue;
694 :
695 2 : papszCreateOptions = CSLSetNameValue(papszCreateOptions,
696 2 : apszOptItems[iOptItem], pszValue);
697 : }
698 :
699 : /* -------------------------------------------------------------------- */
700 : /* Create destination dataset. */
701 : /* -------------------------------------------------------------------- */
702 1472 : GDALDataType eType = GDT_Unknown;
703 :
704 1472 : if (nBands > 0)
705 1456 : eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();
706 : GDALDataset *poDstDS =
707 1472 : Create(pszFilename, nXSize, nYSize, nBands, eType, papszCreateOptions);
708 :
709 1472 : CSLDestroy(papszCreateOptions);
710 :
711 1472 : if (poDstDS == nullptr)
712 305 : return nullptr;
713 :
714 1167 : int nDstBands = poDstDS->GetRasterCount();
715 1167 : CPLErr eErr = CE_None;
716 1167 : if (nDstBands != nBands)
717 : {
718 0 : if (GetMetadataItem(GDAL_DCAP_RASTER) != nullptr)
719 : {
720 : // Should not happen for a well-behaved driver.
721 0 : CPLError(
722 : CE_Failure, CPLE_AppDefined,
723 : "Output driver created only %d bands whereas %d were expected",
724 : nDstBands, nBands);
725 0 : eErr = CE_Failure;
726 : }
727 0 : nDstBands = 0;
728 : }
729 :
730 : /* -------------------------------------------------------------------- */
731 : /* Try setting the projection and geotransform if it seems */
732 : /* suitable. */
733 : /* -------------------------------------------------------------------- */
734 1167 : if (nDstBands == 0 && !bStrict)
735 4 : CPLTurnFailureIntoWarning(true);
736 :
737 1167 : GDALGeoTransform gt;
738 2181 : if (eErr == CE_None && poSrcDS->GetGeoTransform(gt) == CE_None &&
739 2181 : gt != GDALGeoTransform())
740 : {
741 1012 : eErr = poDstDS->SetGeoTransform(gt);
742 1012 : if (!bStrict)
743 651 : eErr = CE_None;
744 : }
745 :
746 1167 : if (eErr == CE_None)
747 : {
748 1158 : const auto poSrcSRS = poSrcDS->GetSpatialRefRasterOnly();
749 1158 : if (poSrcSRS && !poSrcSRS->IsEmpty())
750 : {
751 936 : eErr = poDstDS->SetSpatialRef(poSrcSRS);
752 936 : if (!bStrict)
753 608 : eErr = CE_None;
754 : }
755 : }
756 :
757 : /* -------------------------------------------------------------------- */
758 : /* Copy GCPs. */
759 : /* -------------------------------------------------------------------- */
760 1167 : if (poSrcDS->GetGCPCount() > 0 && eErr == CE_None)
761 : {
762 2 : eErr = poDstDS->SetGCPs(poSrcDS->GetGCPCount(), poSrcDS->GetGCPs(),
763 : poSrcDS->GetGCPProjection());
764 2 : if (!bStrict)
765 1 : eErr = CE_None;
766 : }
767 :
768 1167 : if (nDstBands == 0 && !bStrict)
769 4 : CPLTurnFailureIntoWarning(false);
770 :
771 : /* -------------------------------------------------------------------- */
772 : /* Copy metadata. */
773 : /* -------------------------------------------------------------------- */
774 1167 : DefaultCopyMetadata(poSrcDS, poDstDS, papszOptions, nullptr);
775 :
776 : /* -------------------------------------------------------------------- */
777 : /* Loop copying bands. */
778 : /* -------------------------------------------------------------------- */
779 3058 : for (int iBand = 0; eErr == CE_None && iBand < nDstBands; ++iBand)
780 : {
781 1891 : GDALRasterBand *const poSrcBand = poSrcDS->GetRasterBand(iBand + 1);
782 1891 : GDALRasterBand *const poDstBand = poDstDS->GetRasterBand(iBand + 1);
783 :
784 : /* --------------------------------------------------------------------
785 : */
786 : /* Do we need to copy a colortable. */
787 : /* --------------------------------------------------------------------
788 : */
789 1891 : GDALColorTable *const poCT = poSrcBand->GetColorTable();
790 1891 : if (poCT != nullptr)
791 41 : poDstBand->SetColorTable(poCT);
792 :
793 : /* --------------------------------------------------------------------
794 : */
795 : /* Do we need to copy other metadata? Most of this is */
796 : /* non-critical, so lets not bother folks if it fails are we */
797 : /* are not in strict mode. */
798 : /* --------------------------------------------------------------------
799 : */
800 1891 : if (!bStrict)
801 1250 : CPLTurnFailureIntoWarning(true);
802 :
803 1891 : if (strlen(poSrcBand->GetDescription()) > 0)
804 53 : poDstBand->SetDescription(poSrcBand->GetDescription());
805 :
806 1891 : if (CSLCount(poSrcBand->GetMetadata()) > 0)
807 120 : poDstBand->SetMetadata(poSrcBand->GetMetadata());
808 :
809 1891 : int bSuccess = FALSE;
810 1891 : double dfValue = poSrcBand->GetOffset(&bSuccess);
811 1891 : if (bSuccess && dfValue != 0.0)
812 25 : poDstBand->SetOffset(dfValue);
813 :
814 1891 : dfValue = poSrcBand->GetScale(&bSuccess);
815 1891 : if (bSuccess && dfValue != 1.0)
816 62 : poDstBand->SetScale(dfValue);
817 :
818 1891 : if (poSrcBand->GetUnitType()[0] != '\0')
819 35 : poDstBand->SetUnitType(poSrcBand->GetUnitType());
820 :
821 1891 : GDALCopyNoDataValue(poDstBand, poSrcBand);
822 :
823 3080 : if (poSrcBand->GetColorInterpretation() != GCI_Undefined &&
824 1189 : poSrcBand->GetColorInterpretation() !=
825 1189 : poDstBand->GetColorInterpretation())
826 957 : poDstBand->SetColorInterpretation(
827 957 : poSrcBand->GetColorInterpretation());
828 :
829 1891 : char **papszCatNames = poSrcBand->GetCategoryNames();
830 1891 : if (nullptr != papszCatNames)
831 1 : poDstBand->SetCategoryNames(papszCatNames);
832 :
833 : // Only copy RAT if it is of reasonable size to fit in memory
834 1891 : GDALRasterAttributeTable *poRAT = poSrcBand->GetDefaultRAT();
835 1893 : if (poRAT != nullptr && static_cast<GIntBig>(poRAT->GetColumnCount()) *
836 2 : poRAT->GetRowCount() <
837 : 1024 * 1024)
838 : {
839 2 : poDstBand->SetDefaultRAT(poRAT);
840 : }
841 :
842 1891 : if (!bStrict)
843 : {
844 1250 : CPLTurnFailureIntoWarning(false);
845 : }
846 : else
847 : {
848 641 : eErr = CPLGetLastErrorType();
849 : }
850 : }
851 :
852 : /* -------------------------------------------------------------------- */
853 : /* Copy image data. */
854 : /* -------------------------------------------------------------------- */
855 1167 : if (eErr == CE_None && nDstBands > 0)
856 : {
857 1123 : const char *const apszCopyRasterOptionsSkipHoles[] = {"SKIP_HOLES=YES",
858 : nullptr};
859 1123 : const bool bSkipHoles = CPLTestBool(
860 : CSLFetchNameValueDef(papszOptions, "SKIP_HOLES", "FALSE"));
861 1123 : eErr = GDALDatasetCopyWholeRaster(
862 : poSrcDS, poDstDS,
863 : bSkipHoles ? apszCopyRasterOptionsSkipHoles : nullptr, pfnProgress,
864 : pProgressData);
865 : }
866 :
867 : /* -------------------------------------------------------------------- */
868 : /* Should we copy some masks over? */
869 : /* -------------------------------------------------------------------- */
870 1167 : if (eErr == CE_None && nDstBands > 0)
871 1106 : eErr = DefaultCopyMasks(poSrcDS, poDstDS, eErr);
872 :
873 : /* -------------------------------------------------------------------- */
874 : /* Copy vector layers */
875 : /* -------------------------------------------------------------------- */
876 1167 : if (eErr == CE_None)
877 : {
878 1119 : if (nLayerCount > 0 && poDstDS->TestCapability(ODsCCreateLayer))
879 : {
880 20 : for (int iLayer = 0; iLayer < nLayerCount; ++iLayer)
881 : {
882 10 : OGRLayer *poLayer = poSrcDS->GetLayer(iLayer);
883 :
884 10 : if (poLayer == nullptr)
885 0 : continue;
886 :
887 10 : poDstDS->CopyLayer(poLayer, poLayer->GetName(), nullptr);
888 : }
889 : }
890 : }
891 :
892 : /* -------------------------------------------------------------------- */
893 : /* Try to cleanup the output dataset if the translation failed. */
894 : /* -------------------------------------------------------------------- */
895 1167 : if (eErr != CE_None)
896 : {
897 48 : delete poDstDS;
898 48 : if (!CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false))
899 : {
900 : // Only delete if creating a new file
901 48 : Delete(pszFilename);
902 : }
903 48 : return nullptr;
904 : }
905 : else
906 : {
907 1119 : CPLErrorReset();
908 : }
909 :
910 1119 : return poDstDS;
911 : }
912 :
913 : /************************************************************************/
914 : /* DefaultCopyMetadata() */
915 : /************************************************************************/
916 :
917 5559 : void GDALDriver::DefaultCopyMetadata(GDALDataset *poSrcDS, GDALDataset *poDstDS,
918 : CSLConstList papszOptions,
919 : CSLConstList papszExcludedDomains)
920 : {
921 : const char *pszCopySrcMDD =
922 5559 : CSLFetchNameValueDef(papszOptions, "COPY_SRC_MDD", "AUTO");
923 5559 : char **papszSrcMDD = CSLFetchNameValueMultiple(papszOptions, "SRC_MDD");
924 5559 : if (EQUAL(pszCopySrcMDD, "AUTO") || CPLTestBool(pszCopySrcMDD) ||
925 : papszSrcMDD)
926 : {
927 4 : if ((!papszSrcMDD || CSLFindString(papszSrcMDD, "") >= 0 ||
928 2 : CSLFindString(papszSrcMDD, "_DEFAULT_") >= 0) &&
929 10965 : CSLFindString(papszExcludedDomains, "") < 0 &&
930 5404 : CSLFindString(papszExcludedDomains, "_DEFAULT_") < 0)
931 : {
932 5404 : if (poSrcDS->GetMetadata() != nullptr)
933 886 : poDstDS->SetMetadata(poSrcDS->GetMetadata());
934 : }
935 :
936 : /* -------------------------------------------------------------------- */
937 : /* Copy transportable special domain metadata. */
938 : /* It would be nice to copy geolocation, but it is pretty fragile. */
939 : /* -------------------------------------------------------------------- */
940 5557 : constexpr const char *apszDefaultDomains[] = {
941 : GDAL_MDD_RPC, "xml:XMP", "json:ISIS3", "json:VICAR"};
942 27785 : for (const char *pszDomain : apszDefaultDomains)
943 : {
944 44440 : if ((!papszSrcMDD || CSLFindString(papszSrcMDD, pszDomain) >= 0) &&
945 22212 : CSLFindString(papszExcludedDomains, pszDomain) < 0)
946 : {
947 22212 : CSLConstList papszMD = poSrcDS->GetMetadata(pszDomain);
948 22212 : if (papszMD)
949 5 : poDstDS->SetMetadata(papszMD, pszDomain);
950 : }
951 : }
952 :
953 5557 : if ((!EQUAL(pszCopySrcMDD, "AUTO") && CPLTestBool(pszCopySrcMDD)) ||
954 : papszSrcMDD)
955 : {
956 24 : for (const char *pszDomain :
957 30 : CPLStringList(poSrcDS->GetMetadataDomainList()))
958 : {
959 36 : if (pszDomain[0] != 0 &&
960 12 : (!papszSrcMDD ||
961 12 : CSLFindString(papszSrcMDD, pszDomain) >= 0))
962 : {
963 10 : bool bCanCopy = true;
964 10 : if (CSLFindString(papszExcludedDomains, pszDomain) >= 0)
965 : {
966 0 : bCanCopy = false;
967 : }
968 : else
969 : {
970 50 : for (const char *pszOtherDomain : apszDefaultDomains)
971 : {
972 40 : if (EQUAL(pszDomain, pszOtherDomain))
973 : {
974 0 : bCanCopy = false;
975 0 : break;
976 : }
977 : }
978 10 : if (!papszSrcMDD)
979 : {
980 6 : constexpr const char *const apszReservedDomains[] =
981 : {GDAL_MDD_IMAGE_STRUCTURE,
982 : "DERIVED_SUBDATASETS"};
983 6 : for (const char *pszOtherDomain :
984 12 : apszReservedDomains)
985 : {
986 10 : if (EQUAL(pszDomain, pszOtherDomain))
987 : {
988 4 : bCanCopy = false;
989 4 : break;
990 : }
991 : }
992 : }
993 : }
994 10 : if (bCanCopy)
995 : {
996 6 : poDstDS->SetMetadata(poSrcDS->GetMetadata(pszDomain),
997 6 : pszDomain);
998 : }
999 : }
1000 : }
1001 : }
1002 : }
1003 5559 : CSLDestroy(papszSrcMDD);
1004 5559 : }
1005 :
1006 : /************************************************************************/
1007 : /* QuietDeleteForCreateCopy() */
1008 : /************************************************************************/
1009 :
1010 12360 : CPLErr GDALDriver::QuietDeleteForCreateCopy(const char *pszFilename,
1011 : GDALDataset *poSrcDS)
1012 : {
1013 : // Someone issuing CreateCopy("foo.tif") on a
1014 : // memory driver doesn't expect files with those names to be deleted
1015 : // on a file system...
1016 : // This is somewhat messy. Ideally there should be a way for the
1017 : // driver to overload the default behavior
1018 24037 : if (!EQUAL(GetDescription(), "MEM") && !EQUAL(GetDescription(), "Memory") &&
1019 : // VRT with empty name is a un-materialized dataset
1020 11677 : !(EQUAL(GetDescription(), "VRT") && pszFilename[0] == 0) &&
1021 : // Also exclude database formats for which there's no file list
1022 : // and whose opening might be slow (GeoRaster in particular)
1023 34959 : !EQUAL(GetDescription(), "GeoRaster") &&
1024 10922 : !EQUAL(GetDescription(), "PostGISRaster"))
1025 : {
1026 : /* --------------------------------------------------------------------
1027 : */
1028 : /* Establish list of files of output dataset if it already
1029 : * exists. */
1030 : /* --------------------------------------------------------------------
1031 : */
1032 21810 : std::set<std::string> oSetExistingDestFiles;
1033 : {
1034 21810 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1035 10905 : const char *const apszAllowedDrivers[] = {GetDescription(),
1036 10905 : nullptr};
1037 : auto poExistingOutputDS =
1038 : std::unique_ptr<GDALDataset>(GDALDataset::Open(
1039 21810 : pszFilename, GDAL_OF_RASTER, apszAllowedDrivers));
1040 10905 : if (poExistingOutputDS)
1041 : {
1042 586 : for (const char *pszFileInList :
1043 551 : CPLStringList(poExistingOutputDS->GetFileList()))
1044 : {
1045 : oSetExistingDestFiles.insert(
1046 293 : CPLString(pszFileInList).replaceAll('\\', '/'));
1047 : }
1048 : }
1049 : }
1050 :
1051 : /* --------------------------------------------------------------------
1052 : */
1053 : /* Check if the source dataset shares some files with the dest
1054 : * one.*/
1055 : /* --------------------------------------------------------------------
1056 : */
1057 21810 : std::set<std::string> oSetExistingDestFilesFoundInSource;
1058 10905 : if (!oSetExistingDestFiles.empty())
1059 : {
1060 516 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1061 : // We need to reopen in a temporary dataset for the particular
1062 : // case of overwritten a .tif.ovr file from a .tif
1063 : // If we probe the file list of the .tif, it will then open the
1064 : // .tif.ovr !
1065 258 : const char *const apszAllowedDrivers[] = {
1066 258 : poSrcDS->GetDriver() ? poSrcDS->GetDriver()->GetDescription()
1067 : : nullptr,
1068 258 : nullptr};
1069 : auto poSrcDSTmp = std::unique_ptr<GDALDataset>(GDALDataset::Open(
1070 258 : poSrcDS->GetDescription(), GDAL_OF_RASTER, apszAllowedDrivers,
1071 516 : poSrcDS->papszOpenOptions));
1072 258 : if (poSrcDSTmp)
1073 : {
1074 163 : for (const char *pszFileInList :
1075 314 : CPLStringList(poSrcDSTmp->GetFileList()))
1076 : {
1077 326 : CPLString osFilename(pszFileInList);
1078 163 : osFilename.replaceAll('\\', '/');
1079 163 : if (cpl::contains(oSetExistingDestFiles, osFilename))
1080 : {
1081 : oSetExistingDestFilesFoundInSource.insert(
1082 16 : std::move(osFilename));
1083 : }
1084 : }
1085 : }
1086 : }
1087 :
1088 : // If the source file(s) and the dest one share some files in
1089 : // common, only remove the files that are *not* in common
1090 10905 : if (!oSetExistingDestFilesFoundInSource.empty())
1091 : {
1092 36 : for (const std::string &osFilename : oSetExistingDestFiles)
1093 : {
1094 21 : if (!cpl::contains(oSetExistingDestFilesFoundInSource,
1095 : osFilename))
1096 : {
1097 5 : VSIUnlink(osFilename.c_str());
1098 : }
1099 : }
1100 : }
1101 :
1102 10905 : QuietDelete(pszFilename);
1103 : }
1104 :
1105 12360 : return CE_None;
1106 : }
1107 :
1108 : //! @endcond
1109 :
1110 : /************************************************************************/
1111 : /* CreateCopy() */
1112 : /************************************************************************/
1113 :
1114 : /**
1115 : * \brief Create a copy of a dataset.
1116 : *
1117 : * This method will attempt to create a copy of a raster dataset with the
1118 : * indicated filename, and in this drivers format. Band number, size,
1119 : * type, projection, geotransform and so forth are all to be copied from
1120 : * the provided template dataset.
1121 : *
1122 : * Note that many sequential write once formats (such as JPEG and PNG) don't
1123 : * implement the Create() method but do implement this CreateCopy() method.
1124 : * If the driver doesn't implement CreateCopy(), but does implement Create()
1125 : * then the default CreateCopy() mechanism built on calling Create() will
1126 : * be used.
1127 : * So to test if CreateCopy() is available, you can test if GDAL_DCAP_CREATECOPY
1128 : * or GDAL_DCAP_CREATE is set in the GDAL metadata.
1129 : *
1130 : * It is intended that CreateCopy() will often be used with a source dataset
1131 : * which is a virtual dataset allowing configuration of band types, and other
1132 : * information without actually duplicating raster data (see the VRT driver).
1133 : * This is what is done by the gdal_translate utility for example.
1134 : *
1135 : * That function will try to validate the creation option list passed to the
1136 : * driver with the GDALValidateCreationOptions() method. This check can be
1137 : * disabled by defining the configuration option
1138 : * GDAL_VALIDATE_CREATION_OPTIONS=NO.
1139 : *
1140 : * This function copy all metadata from the default domain ("")
1141 : *
1142 : * Even is bStrict is TRUE, only the <b>value</b> of the data is equivalent,
1143 : * but the data layout (INTERLEAVE as PIXEL/LINE/BAND) of the dst dataset is
1144 : * controlled by the papszOptions creation options, and may differ from the
1145 : * poSrcDS src dataset.
1146 : * Starting from GDAL 3.5, if no INTERLEAVE and COMPRESS creation option has
1147 : * been specified in papszOptions, and if the driver supports equivalent
1148 : * interleaving as the src dataset, the CreateCopy() will internally add the
1149 : * proper creation option to get the same data interleaving.
1150 : *
1151 : * After you have finished working with the returned dataset, it is
1152 : * <b>required</b> to close it with GDALClose(). This does not only close the
1153 : * file handle, but also ensures that all the data and metadata has been written
1154 : * to the dataset (GDALFlushCache() is not sufficient for that purpose).
1155 : *
1156 : * For multidimensional datasets, papszOptions can contain array creation
1157 : * options, if they are prefixed with "ARRAY:". \see GDALGroup::CopyFrom()
1158 : * documentation for further details regarding such options.
1159 : *
1160 : * @param pszFilename the name for the new dataset. UTF-8 encoded.
1161 : * @param poSrcDS the dataset being duplicated.
1162 : * @param bStrict TRUE if the copy must be strictly equivalent, or more
1163 : * normally FALSE indicating that the copy may adapt as needed for the
1164 : * output format.
1165 : * @param papszOptions additional format dependent options controlling
1166 : * creation of the output file.
1167 : * The APPEND_SUBDATASET=YES option can be specified to avoid prior destruction
1168 : * of existing dataset.
1169 : * Starting with GDAL 3.8.0, the following options are recognized by the
1170 : * GTiff, COG, VRT, PNG au JPEG drivers:
1171 : * <ul>
1172 : * <li>COPY_SRC_MDD=AUTO/YES/NO: whether metadata domains of the source dataset
1173 : * should be copied to the destination dataset. In the default AUTO mode, only
1174 : * "safe" domains will be copied, which include the default metadata domain
1175 : * (some drivers may include other domains such as IMD, RPC, GEOLOCATION). When
1176 : * setting YES, all domains will be copied (but a few reserved ones like
1177 : * IMAGE_STRUCTURE or DERIVED_SUBDATASETS). When setting NO, no source metadata
1178 : * will be copied.
1179 : * </li>
1180 : *<li>SRC_MDD=domain_name: which source metadata domain should be copied.
1181 : * This option restricts the list of source metadata domains to be copied
1182 : * (it implies COPY_SRC_MDD=YES if it is not set). This option may be specified
1183 : * as many times as they are source domains. The default metadata domain is the
1184 : * empty string "" ("_DEFAULT_") may also be used when empty string is not practical)
1185 : * </li>
1186 : * </ul>
1187 : * @param pfnProgress a function to be used to report progress of the copy.
1188 : * @param pProgressData application data passed into progress function.
1189 : *
1190 : * @return a pointer to the newly created dataset (may be read-only access).
1191 : */
1192 :
1193 11735 : GDALDataset *GDALDriver::CreateCopy(const char *pszFilename,
1194 : GDALDataset *poSrcDS, int bStrict,
1195 : CSLConstList papszOptions,
1196 : GDALProgressFunc pfnProgress,
1197 : void *pProgressData)
1198 :
1199 : {
1200 11735 : if (pfnProgress == nullptr)
1201 8892 : pfnProgress = GDALDummyProgress;
1202 :
1203 11735 : const int nBandCount = poSrcDS->GetRasterCount();
1204 :
1205 : /* -------------------------------------------------------------------- */
1206 : /* If no INTERLEAVE creation option is given, we will try to add */
1207 : /* one that matches the current srcDS interleaving */
1208 : /* -------------------------------------------------------------------- */
1209 11735 : char **papszOptionsToDelete = nullptr;
1210 : const char *srcInterleave =
1211 11735 : poSrcDS->GetMetadataItem(GDALMD_INTERLEAVE, GDAL_MDD_IMAGE_STRUCTURE);
1212 7027 : if (nBandCount > 1 && srcInterleave != nullptr &&
1213 25392 : CSLFetchNameValue(papszOptions, GDALMD_INTERLEAVE) == nullptr &&
1214 6630 : EQUAL(CSLFetchNameValueDef(papszOptions, "COMPRESS", "NONE"), "NONE"))
1215 : {
1216 :
1217 : // look for INTERLEAVE values of the driver
1218 6445 : char **interleavesCSL = nullptr;
1219 : const char *pszOptionList =
1220 6445 : this->GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST);
1221 : CPLXMLNode *xmlNode =
1222 6445 : !pszOptionList ? nullptr : CPLParseXMLString(pszOptionList);
1223 6445 : for (CPLXMLNode *child = !xmlNode ? nullptr : xmlNode->psChild;
1224 134600 : child != nullptr; child = child->psNext)
1225 : {
1226 128155 : if ((child->eType == CXT_Element) &&
1227 128155 : EQUAL(child->pszValue, "Option"))
1228 : {
1229 : const char *nameAttribute =
1230 128155 : CPLGetXMLValue(child, "name", nullptr);
1231 128155 : const bool isInterleaveAttribute =
1232 128155 : nameAttribute && EQUAL(nameAttribute, GDALMD_INTERLEAVE);
1233 128155 : if (isInterleaveAttribute)
1234 : {
1235 1206 : for (CPLXMLNode *optionChild = child->psChild;
1236 7305 : optionChild != nullptr;
1237 6099 : optionChild = optionChild->psNext)
1238 : {
1239 6099 : if ((optionChild->eType == CXT_Element) &&
1240 2466 : EQUAL(optionChild->pszValue, "Value"))
1241 : {
1242 2466 : CPLXMLNode *optionChildValue = optionChild->psChild;
1243 2466 : if (optionChildValue &&
1244 2466 : (optionChildValue->eType == CXT_Text))
1245 : {
1246 2466 : interleavesCSL = CSLAddString(
1247 2466 : interleavesCSL, optionChildValue->pszValue);
1248 : }
1249 : }
1250 : }
1251 : }
1252 : }
1253 : }
1254 6445 : CPLDestroyXMLNode(xmlNode);
1255 :
1256 : const char *dstInterleaveBand =
1257 11708 : (CSLFindString(interleavesCSL, "BAND") >= 0) ? "BAND"
1258 5263 : : (CSLFindString(interleavesCSL, "BSQ") >= 0) ? "BSQ"
1259 6445 : : nullptr;
1260 : const char *dstInterleaveLine =
1261 12890 : (CSLFindString(interleavesCSL, "LINE") >= 0) ? "LINE"
1262 6445 : : (CSLFindString(interleavesCSL, "BIL") >= 0) ? "BIL"
1263 6445 : : nullptr;
1264 : const char *dstInterleavePixel =
1265 11708 : (CSLFindString(interleavesCSL, "PIXEL") >= 0) ? "PIXEL"
1266 5263 : : (CSLFindString(interleavesCSL, "BIP") >= 0) ? "BIP"
1267 6445 : : nullptr;
1268 6445 : const char *dstInterleave =
1269 6760 : EQUAL(srcInterleave, "BAND") ? dstInterleaveBand
1270 628 : : EQUAL(srcInterleave, "LINE") ? dstInterleaveLine
1271 313 : : EQUAL(srcInterleave, "PIXEL") ? dstInterleavePixel
1272 : : nullptr;
1273 6445 : CSLDestroy(interleavesCSL);
1274 :
1275 6445 : if (dstInterleave != nullptr)
1276 : {
1277 1206 : papszOptionsToDelete = CSLDuplicate(papszOptions);
1278 1206 : papszOptionsToDelete = CSLSetNameValue(
1279 : papszOptionsToDelete, GDALMD_INTERLEAVE, dstInterleave);
1280 1206 : papszOptionsToDelete = CSLSetNameValue(
1281 : papszOptionsToDelete, "@INTERLEAVE_ADDED_AUTOMATICALLY", "YES");
1282 1206 : papszOptions = papszOptionsToDelete;
1283 : }
1284 : }
1285 :
1286 : /* -------------------------------------------------------------------- */
1287 : /* Make sure we cleanup if there is an existing dataset of this */
1288 : /* name. But even if that seems to fail we will continue since */
1289 : /* it might just be a corrupt file or something. */
1290 : /* -------------------------------------------------------------------- */
1291 : const bool bAppendSubdataset =
1292 11735 : CPLFetchBool(papszOptions, "APPEND_SUBDATASET", false);
1293 : // Note: @QUIET_DELETE_ON_CREATE_COPY is set to NO by the KMLSuperOverlay
1294 : // driver when writing a .kmz file. Also by GDALTranslate() if it has
1295 : // already done a similar job.
1296 23445 : if (!bAppendSubdataset &&
1297 11710 : CPLFetchBool(papszOptions, "@QUIET_DELETE_ON_CREATE_COPY", true))
1298 : {
1299 8978 : QuietDeleteForCreateCopy(pszFilename, poSrcDS);
1300 : }
1301 :
1302 : int iIdxQuietDeleteOnCreateCopy =
1303 11735 : CSLPartialFindString(papszOptions, "@QUIET_DELETE_ON_CREATE_COPY=");
1304 11735 : if (iIdxQuietDeleteOnCreateCopy >= 0)
1305 : {
1306 2732 : if (papszOptionsToDelete == nullptr)
1307 1661 : papszOptionsToDelete = CSLDuplicate(papszOptions);
1308 2732 : papszOptionsToDelete = CSLRemoveStrings(
1309 : papszOptionsToDelete, iIdxQuietDeleteOnCreateCopy, 1, nullptr);
1310 2732 : papszOptions = papszOptionsToDelete;
1311 : }
1312 :
1313 : /* -------------------------------------------------------------------- */
1314 : /* If _INTERNAL_DATASET=YES, the returned dataset will not be */
1315 : /* registered in the global list of open datasets. */
1316 : /* -------------------------------------------------------------------- */
1317 : const int iIdxInternalDataset =
1318 11735 : CSLPartialFindString(papszOptions, "_INTERNAL_DATASET=");
1319 11735 : bool bInternalDataset = false;
1320 11735 : if (iIdxInternalDataset >= 0)
1321 : {
1322 : bInternalDataset =
1323 4221 : CPLFetchBool(papszOptions, "_INTERNAL_DATASET", false);
1324 4221 : if (papszOptionsToDelete == nullptr)
1325 4221 : papszOptionsToDelete = CSLDuplicate(papszOptions);
1326 4221 : papszOptionsToDelete = CSLRemoveStrings(
1327 : papszOptionsToDelete, iIdxInternalDataset, 1, nullptr);
1328 4221 : papszOptions = papszOptionsToDelete;
1329 : }
1330 :
1331 : /* -------------------------------------------------------------------- */
1332 : /* Validate creation options. */
1333 : /* -------------------------------------------------------------------- */
1334 11735 : if (CPLTestBool(
1335 : CPLGetConfigOption("GDAL_VALIDATE_CREATION_OPTIONS", "YES")))
1336 : {
1337 23470 : auto poSrcGroup = poSrcDS->GetRootGroup();
1338 11735 : if (poSrcGroup != nullptr && GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
1339 : {
1340 238 : CPLStringList aosDatasetCO;
1341 127 : for (const char *pszOption : cpl::Iterate(papszOptions))
1342 : {
1343 8 : if (!STARTS_WITH_CI(pszOption, "ARRAY:"))
1344 1 : aosDatasetCO.AddString(pszOption);
1345 : }
1346 :
1347 : const char *pszOptionList =
1348 119 : GetMetadataItem(GDAL_DMD_MULTIDIM_DATASET_CREATIONOPTIONLIST);
1349 238 : CPLString osDriver;
1350 119 : osDriver.Printf("driver %s", GetDescription());
1351 238 : GDALValidateOptions(GDALDriver::ToHandle(this), pszOptionList,
1352 119 : aosDatasetCO.List(),
1353 : "mulitdim dataset creation option", osDriver);
1354 : }
1355 : else
1356 : {
1357 11616 : GDALValidateCreationOptions(this, papszOptions);
1358 : }
1359 : }
1360 :
1361 : /* -------------------------------------------------------------------- */
1362 : /* Advise the source raster that we are going to read it completely */
1363 : /* -------------------------------------------------------------------- */
1364 :
1365 11735 : const int nXSize = poSrcDS->GetRasterXSize();
1366 11735 : const int nYSize = poSrcDS->GetRasterYSize();
1367 11735 : GDALDataType eDT = GDT_Unknown;
1368 11735 : if (nBandCount > 0)
1369 : {
1370 11492 : GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(1);
1371 11492 : if (poSrcBand)
1372 11492 : eDT = poSrcBand->GetRasterDataType();
1373 : }
1374 11735 : poSrcDS->AdviseRead(0, 0, nXSize, nYSize, nXSize, nYSize, eDT, nBandCount,
1375 11735 : nullptr, nullptr);
1376 :
1377 : /* -------------------------------------------------------------------- */
1378 : /* If the format provides a CreateCopy() method use that, */
1379 : /* otherwise fallback to the internal implementation using the */
1380 : /* Create() method. */
1381 : /* -------------------------------------------------------------------- */
1382 11735 : GDALDataset *poDstDS = nullptr;
1383 11735 : auto l_pfnCreateCopy = GetCreateCopyCallback();
1384 22267 : if (l_pfnCreateCopy != nullptr &&
1385 10532 : !CPLTestBool(CPLGetConfigOption("GDAL_DEFAULT_CREATE_COPY", "NO")))
1386 : {
1387 10532 : poDstDS = l_pfnCreateCopy(pszFilename, poSrcDS, bStrict,
1388 : const_cast<char **>(papszOptions),
1389 : pfnProgress, pProgressData);
1390 10532 : if (poDstDS != nullptr)
1391 : {
1392 18624 : if (poDstDS->GetDescription() == nullptr ||
1393 9312 : strlen(poDstDS->GetDescription()) == 0)
1394 457 : poDstDS->SetDescription(pszFilename);
1395 :
1396 9312 : if (poDstDS->poDriver == nullptr)
1397 8473 : poDstDS->poDriver = this;
1398 :
1399 9312 : if (!bInternalDataset)
1400 5091 : poDstDS->AddToDatasetOpenList();
1401 : }
1402 : }
1403 : else
1404 : {
1405 1203 : poDstDS = DefaultCreateCopy(pszFilename, poSrcDS, bStrict, papszOptions,
1406 : pfnProgress, pProgressData);
1407 : }
1408 :
1409 11735 : CSLDestroy(papszOptionsToDelete);
1410 11735 : return poDstDS;
1411 : }
1412 :
1413 : /************************************************************************/
1414 : /* GDALCreateCopy() */
1415 : /************************************************************************/
1416 :
1417 : /**
1418 : * \brief Create a copy of a dataset.
1419 : *
1420 : * @see GDALDriver::CreateCopy()
1421 : */
1422 :
1423 6790 : GDALDatasetH CPL_STDCALL GDALCreateCopy(GDALDriverH hDriver,
1424 : const char *pszFilename,
1425 : GDALDatasetH hSrcDS, int bStrict,
1426 : CSLConstList papszOptions,
1427 : GDALProgressFunc pfnProgress,
1428 : void *pProgressData)
1429 :
1430 : {
1431 6790 : VALIDATE_POINTER1(hDriver, "GDALCreateCopy", nullptr);
1432 6790 : VALIDATE_POINTER1(hSrcDS, "GDALCreateCopy", nullptr);
1433 :
1434 6790 : return GDALDriver::FromHandle(hDriver)->CreateCopy(
1435 : pszFilename, GDALDataset::FromHandle(hSrcDS), bStrict, papszOptions,
1436 6790 : pfnProgress, pProgressData);
1437 : }
1438 :
1439 : /************************************************************************/
1440 : /* CanVectorTranslateFrom() */
1441 : /************************************************************************/
1442 :
1443 : /** Returns whether the driver can translate from a vector dataset,
1444 : * using the arguments passed to GDALVectorTranslate() stored in
1445 : * papszVectorTranslateArguments.
1446 : *
1447 : * This is used to determine if the driver supports the VectorTranslateFrom()
1448 : * operation.
1449 : *
1450 : * @param pszDestName Target dataset name
1451 : * @param poSourceDS Source dataset
1452 : * @param papszVectorTranslateArguments Non-positional arguments passed to
1453 : * GDALVectorTranslate() (may be nullptr)
1454 : * @param[out] ppapszFailureReasons nullptr, or a pointer to an null-terminated
1455 : * array of strings to record the reason(s) for the impossibility.
1456 : * @return true if VectorTranslateFrom() can be called with the same arguments.
1457 : * @since GDAL 3.8
1458 : */
1459 1058 : bool GDALDriver::CanVectorTranslateFrom(
1460 : const char *pszDestName, GDALDataset *poSourceDS,
1461 : CSLConstList papszVectorTranslateArguments, char ***ppapszFailureReasons)
1462 :
1463 : {
1464 1058 : if (ppapszFailureReasons)
1465 : {
1466 0 : *ppapszFailureReasons = nullptr;
1467 : }
1468 :
1469 1058 : if (!pfnCanVectorTranslateFrom)
1470 : {
1471 1052 : if (ppapszFailureReasons)
1472 : {
1473 0 : *ppapszFailureReasons = CSLAddString(
1474 : nullptr,
1475 : "CanVectorTranslateFrom() not implemented for this driver");
1476 : }
1477 1052 : return false;
1478 : }
1479 :
1480 6 : char **papszFailureReasons = nullptr;
1481 6 : bool bRet = pfnCanVectorTranslateFrom(
1482 : pszDestName, poSourceDS, papszVectorTranslateArguments,
1483 : ppapszFailureReasons ? ppapszFailureReasons : &papszFailureReasons);
1484 6 : if (!ppapszFailureReasons)
1485 : {
1486 2 : for (const char *pszReason :
1487 10 : cpl::Iterate(static_cast<CSLConstList>(papszFailureReasons)))
1488 : {
1489 2 : CPLDebug("GDAL", "%s", pszReason);
1490 : }
1491 6 : CSLDestroy(papszFailureReasons);
1492 : }
1493 6 : return bRet;
1494 : }
1495 :
1496 : /************************************************************************/
1497 : /* HasOpenOption() */
1498 : /************************************************************************/
1499 :
1500 193 : bool GDALDriver::HasOpenOption(const char *pszOpenOptionName) const
1501 : {
1502 193 : if (pszOpenOptionName == nullptr)
1503 0 : return false;
1504 :
1505 : // Const cast is safe here since we are only reading the metadata
1506 386 : auto pszOOMd{const_cast<GDALDriver *>(this)->GetMetadataItem(
1507 193 : GDAL_DMD_OPENOPTIONLIST)};
1508 193 : if (pszOOMd == nullptr)
1509 74 : return false;
1510 :
1511 238 : const CPLXMLTreeCloser oXml{CPLParseXMLString(pszOOMd)};
1512 1259 : for (CPLXMLNode *option = oXml->psChild; option != nullptr;
1513 1140 : option = option->psNext)
1514 : {
1515 1141 : if (EQUAL(CPLGetXMLValue(CPLGetXMLNode(option, "name"), nullptr, ""),
1516 : pszOpenOptionName))
1517 1 : return true;
1518 : }
1519 118 : return false;
1520 : }
1521 :
1522 : /************************************************************************/
1523 : /* HasLayerCreationOption() */
1524 : /************************************************************************/
1525 :
1526 7 : bool GDALDriver::HasLayerCreationOption(const char *pszOptionName) const
1527 : {
1528 7 : if (pszOptionName == nullptr)
1529 0 : return false;
1530 :
1531 : // Const cast is safe here since we are only reading the metadata
1532 14 : auto pszXML{const_cast<GDALDriver *>(this)->GetMetadataItem(
1533 7 : GDAL_DS_LAYER_CREATIONOPTIONLIST)};
1534 7 : if (pszXML == nullptr)
1535 0 : return false;
1536 :
1537 14 : const CPLXMLTreeCloser oXml{CPLParseXMLString(pszXML)};
1538 49 : for (CPLXMLNode *option = oXml->psChild; option != nullptr;
1539 42 : option = option->psNext)
1540 : {
1541 49 : if (EQUAL(CPLGetXMLValue(CPLGetXMLNode(option, "name"), nullptr, ""),
1542 : pszOptionName))
1543 7 : return true;
1544 : }
1545 0 : return false;
1546 : }
1547 :
1548 : /************************************************************************/
1549 : /* VectorTranslateFrom() */
1550 : /************************************************************************/
1551 :
1552 : /** Create a copy of a vector dataset, using the arguments passed to
1553 : * GDALVectorTranslate() stored in papszVectorTranslateArguments.
1554 : *
1555 : * This may be implemented by some drivers that can convert from an existing
1556 : * dataset in an optimized way.
1557 : *
1558 : * This is for example used by the PMTiles to convert from MBTiles.
1559 : *
1560 : * @param pszDestName Target dataset name
1561 : * @param poSourceDS Source dataset
1562 : * @param papszVectorTranslateArguments Non-positional arguments passed to
1563 : * GDALVectorTranslate() (may be nullptr)
1564 : * @param pfnProgress a function to be used to report progress of the copy.
1565 : * @param pProgressData application data passed into progress function.
1566 : * @return a new dataset in case of success, or nullptr in case of error.
1567 : * @since GDAL 3.8
1568 : */
1569 4 : GDALDataset *GDALDriver::VectorTranslateFrom(
1570 : const char *pszDestName, GDALDataset *poSourceDS,
1571 : CSLConstList papszVectorTranslateArguments, GDALProgressFunc pfnProgress,
1572 : void *pProgressData)
1573 :
1574 : {
1575 4 : if (!pfnVectorTranslateFrom)
1576 : {
1577 0 : CPLError(CE_Failure, CPLE_AppDefined,
1578 : "VectorTranslateFrom() not implemented for this driver");
1579 0 : return nullptr;
1580 : }
1581 :
1582 4 : return pfnVectorTranslateFrom(pszDestName, poSourceDS,
1583 : papszVectorTranslateArguments, pfnProgress,
1584 4 : pProgressData);
1585 : }
1586 :
1587 : /************************************************************************/
1588 : /* QuietDelete() */
1589 : /************************************************************************/
1590 :
1591 : /**
1592 : * \brief Delete dataset if found.
1593 : *
1594 : * This is a helper method primarily used by Create() and
1595 : * CreateCopy() to predelete any dataset of the name soon to be
1596 : * created. It will attempt to delete the named dataset if
1597 : * one is found, otherwise it does nothing. An error is only
1598 : * returned if the dataset is found but the delete fails.
1599 : *
1600 : * This is a static method and it doesn't matter what driver instance
1601 : * it is invoked on. It will attempt to discover the correct driver
1602 : * using Identify().
1603 : *
1604 : * @param pszName the dataset name to try and delete.
1605 : * @param papszAllowedDrivers NULL to consider all candidate drivers, or a NULL
1606 : * terminated list of strings with the driver short names that must be
1607 : * considered. (Note: implemented only starting with GDAL 3.4.1)
1608 : * @return CE_None if the dataset does not exist, or is deleted without issues.
1609 : */
1610 :
1611 24848 : CPLErr GDALDriver::QuietDelete(const char *pszName,
1612 : CSLConstList papszAllowedDrivers)
1613 :
1614 : {
1615 : VSIStatBufL sStat;
1616 : const bool bExists =
1617 24848 : VSIStatExL(pszName, &sStat,
1618 24848 : VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0;
1619 :
1620 : #ifdef S_ISFIFO
1621 24848 : if (bExists && S_ISFIFO(sStat.st_mode))
1622 0 : return CE_None;
1623 : #endif
1624 :
1625 24848 : GDALDriver *poDriver = nullptr;
1626 24848 : if (papszAllowedDrivers)
1627 : {
1628 0 : GDALOpenInfo oOpenInfo(pszName, GDAL_OF_ALL);
1629 0 : for (const char *pszDriverName : cpl::Iterate(papszAllowedDrivers))
1630 : {
1631 : GDALDriver *poTmpDriver =
1632 0 : GDALDriver::FromHandle(GDALGetDriverByName(pszDriverName));
1633 0 : if (poTmpDriver)
1634 : {
1635 : const bool bIdentifyRes =
1636 0 : poTmpDriver->pfnIdentifyEx
1637 0 : ? poTmpDriver->pfnIdentifyEx(poTmpDriver, &oOpenInfo) >
1638 : 0
1639 0 : : poTmpDriver->pfnIdentify &&
1640 0 : poTmpDriver->pfnIdentify(&oOpenInfo) > 0;
1641 0 : if (bIdentifyRes)
1642 : {
1643 0 : poDriver = poTmpDriver;
1644 0 : break;
1645 : }
1646 : }
1647 : }
1648 : }
1649 : else
1650 : {
1651 49696 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1652 24848 : poDriver = GDALDriver::FromHandle(GDALIdentifyDriver(pszName, nullptr));
1653 : }
1654 :
1655 24848 : if (poDriver == nullptr)
1656 24027 : return CE_None;
1657 :
1658 855 : if (bExists && VSI_ISDIR(sStat.st_mode) &&
1659 34 : (EQUAL(poDriver->GetDescription(), "MapInfo File") ||
1660 34 : EQUAL(poDriver->GetDescription(), "ESRI Shapefile")))
1661 : {
1662 : // Those drivers are a bit special and handle directories as container
1663 : // of layers, but it is quite common to found other files too, and
1664 : // removing the directory might be non-desirable.
1665 33 : return CE_None;
1666 : }
1667 :
1668 788 : CPLDebug("GDAL", "QuietDelete(%s) invoking Delete()", pszName);
1669 :
1670 788 : poDriver->pfnDelete = poDriver->GetDeleteCallback();
1671 826 : const bool bQuiet = !bExists && poDriver->pfnDelete == nullptr &&
1672 38 : poDriver->pfnDeleteDataSource == nullptr;
1673 788 : if (bQuiet)
1674 : {
1675 76 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1676 38 : return poDriver->Delete(pszName);
1677 : }
1678 : else
1679 : {
1680 750 : return poDriver->Delete(pszName);
1681 : }
1682 : }
1683 :
1684 : /************************************************************************/
1685 : /* Delete() */
1686 : /************************************************************************/
1687 :
1688 : /**
1689 : * \brief Delete named dataset.
1690 : *
1691 : * The driver will attempt to delete the named dataset in a driver specific
1692 : * fashion. Full featured drivers will delete all associated files,
1693 : * database objects, or whatever is appropriate. The default behavior when
1694 : * no driver specific behavior is provided is to attempt to delete all the
1695 : * files that are returned by GDALGetFileList() on the dataset handle.
1696 : *
1697 : * It is unwise to have open dataset handles on this dataset when it is
1698 : * deleted.
1699 : *
1700 : * Equivalent of the C function GDALDeleteDataset().
1701 : *
1702 : * @param pszFilename name of dataset to delete.
1703 : *
1704 : * @return CE_None on success, or CE_Failure if the operation fails.
1705 : */
1706 :
1707 4119 : CPLErr GDALDriver::Delete(const char *pszFilename)
1708 :
1709 : {
1710 4119 : pfnDelete = GetDeleteCallback();
1711 4119 : if (pfnDelete != nullptr)
1712 984 : return pfnDelete(pszFilename);
1713 3135 : else if (pfnDeleteDataSource != nullptr)
1714 0 : return pfnDeleteDataSource(this, pszFilename);
1715 :
1716 : /* -------------------------------------------------------------------- */
1717 : /* Collect file list. */
1718 : /* -------------------------------------------------------------------- */
1719 3135 : GDALDatasetH hDS = GDALOpenEx(pszFilename, GDAL_OF_VERBOSE_ERROR, nullptr,
1720 : nullptr, nullptr);
1721 :
1722 3135 : if (hDS == nullptr)
1723 : {
1724 236 : if (CPLGetLastErrorNo() == 0)
1725 0 : CPLError(CE_Failure, CPLE_OpenFailed,
1726 : "Unable to open %s to obtain file list.", pszFilename);
1727 :
1728 236 : return CE_Failure;
1729 : }
1730 :
1731 5798 : const CPLStringList aosFileList(GDALGetFileList(hDS));
1732 :
1733 2899 : GDALClose(hDS);
1734 2899 : hDS = nullptr;
1735 :
1736 2899 : if (aosFileList.empty())
1737 : {
1738 0 : CPLError(CE_Failure, CPLE_NotSupported,
1739 : "Unable to determine files associated with %s, "
1740 : "delete fails.",
1741 : pszFilename);
1742 0 : return CE_Failure;
1743 : }
1744 :
1745 2899 : return Delete(nullptr, aosFileList.List());
1746 : }
1747 :
1748 : /************************************************************************/
1749 : /* Delete() */
1750 : /************************************************************************/
1751 :
1752 : /**
1753 : * \brief Delete a currently opened dataset
1754 : *
1755 : * The driver will attempt to delete the passed dataset in a driver specific
1756 : * fashion. Full featured drivers will delete all associated files,
1757 : * database objects, or whatever is appropriate. The default behavior when
1758 : * no driver specific behavior is provided is to attempt to delete all the
1759 : * files that are returned by GDALGetFileList() on the dataset handle.
1760 : *
1761 : * Note that this will generally not work on Windows systems that don't accept
1762 : * deleting opened files.
1763 : *
1764 : * At least one of poDS or papszFileList must not be NULL
1765 : *
1766 : * @param poDS dataset to delete, or NULL
1767 : * @param papszFileList File list to delete, typically obtained with
1768 : * poDS->GetFileList(), or NULL
1769 : *
1770 : * @return CE_None on success, or CE_Failure if the operation fails.
1771 : *
1772 : * @since 3.12
1773 : */
1774 :
1775 2911 : CPLErr GDALDriver::Delete(GDALDataset *poDS, CSLConstList papszFileList)
1776 :
1777 : {
1778 2911 : if (poDS)
1779 : {
1780 11 : pfnDelete = GetDeleteCallback();
1781 11 : if (pfnDelete != nullptr)
1782 7 : return pfnDelete(poDS->GetDescription());
1783 4 : else if (pfnDeleteDataSource != nullptr)
1784 0 : return pfnDeleteDataSource(this, poDS->GetDescription());
1785 : }
1786 :
1787 : /* -------------------------------------------------------------------- */
1788 : /* Delete all files. */
1789 : /* -------------------------------------------------------------------- */
1790 2904 : CPLErr eErr = CE_None;
1791 6432 : for (int i = 0; papszFileList && papszFileList[i]; ++i)
1792 : {
1793 3528 : if (VSIUnlink(papszFileList[i]) != 0)
1794 : {
1795 4 : CPLError(CE_Failure, CPLE_AppDefined, "Deleting %s failed:\n%s",
1796 2 : papszFileList[i], VSIStrerror(errno));
1797 2 : eErr = CE_Failure;
1798 : }
1799 : }
1800 :
1801 2904 : return eErr;
1802 : }
1803 :
1804 : /************************************************************************/
1805 : /* GDALDeleteDataset() */
1806 : /************************************************************************/
1807 :
1808 : /**
1809 : * \brief Delete named dataset.
1810 : *
1811 : * @see GDALDriver::Delete()
1812 : */
1813 :
1814 2166 : CPLErr CPL_STDCALL GDALDeleteDataset(GDALDriverH hDriver,
1815 : const char *pszFilename)
1816 :
1817 : {
1818 2166 : if (hDriver == nullptr)
1819 10 : hDriver = GDALIdentifyDriver(pszFilename, nullptr);
1820 :
1821 2166 : if (hDriver == nullptr)
1822 : {
1823 1 : CPLError(CE_Failure, CPLE_AppDefined, "No identifiable driver for %s.",
1824 : pszFilename);
1825 1 : return CE_Failure;
1826 : }
1827 :
1828 : #ifdef OGRAPISPY_ENABLED
1829 2165 : if (GDALGetMetadataItem(hDriver, GDAL_DCAP_VECTOR, nullptr))
1830 : {
1831 439 : OGRAPISpyDeleteDataSource(hDriver, pszFilename);
1832 : }
1833 : #endif
1834 :
1835 2165 : return GDALDriver::FromHandle(hDriver)->Delete(pszFilename);
1836 : }
1837 :
1838 : /************************************************************************/
1839 : /* DefaultRename() */
1840 : /* */
1841 : /* The generic implementation based on the file list used when */
1842 : /* there is no format specific implementation. */
1843 : /************************************************************************/
1844 :
1845 : //! @cond Doxygen_Suppress
1846 175 : CPLErr GDALDriver::DefaultRename(const char *pszNewName, const char *pszOldName)
1847 :
1848 : {
1849 : /* -------------------------------------------------------------------- */
1850 : /* Collect file list. */
1851 : /* -------------------------------------------------------------------- */
1852 : auto poDS = std::unique_ptr<GDALDataset>(
1853 : GDALDataset::Open(pszOldName, GDAL_OF_ALL | GDAL_OF_VERBOSE_ERROR,
1854 350 : nullptr, nullptr, nullptr));
1855 :
1856 175 : if (!poDS)
1857 : {
1858 0 : if (CPLGetLastErrorNo() == 0)
1859 0 : CPLError(CE_Failure, CPLE_OpenFailed,
1860 : "Unable to open %s to obtain file list.", pszOldName);
1861 :
1862 0 : return CE_Failure;
1863 : }
1864 :
1865 350 : const CPLStringList aosFileList(poDS->GetFileList());
1866 :
1867 175 : poDS.reset();
1868 :
1869 175 : if (aosFileList.empty())
1870 : {
1871 0 : CPLError(CE_Failure, CPLE_NotSupported,
1872 : "Unable to determine files associated with %s,\n"
1873 : "rename fails.",
1874 : pszOldName);
1875 :
1876 0 : return CE_Failure;
1877 : }
1878 :
1879 : /* -------------------------------------------------------------------- */
1880 : /* Produce a list of new filenames that correspond to the old */
1881 : /* names. */
1882 : /* -------------------------------------------------------------------- */
1883 175 : CPLErr eErr = CE_None;
1884 : const CPLStringList aosNewFileList(
1885 350 : CPLCorrespondingPaths(pszOldName, pszNewName, aosFileList.List()));
1886 :
1887 175 : if (aosNewFileList.empty())
1888 0 : return CE_Failure;
1889 :
1890 : // Guaranteed by CPLCorrespondingPaths()
1891 175 : CPLAssert(aosNewFileList.size() == aosFileList.size());
1892 :
1893 : VSIStatBufL sStatBuf;
1894 177 : if (VSIStatL(pszOldName, &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode) &&
1895 2 : VSIStatL(pszNewName, &sStatBuf) != 0)
1896 : {
1897 2 : if (VSIMkdirRecursive(pszNewName, 0755) != 0)
1898 : {
1899 1 : CPLError(CE_Failure, CPLE_AppDefined,
1900 : "Cannot create directory '%s'", pszNewName);
1901 1 : return CE_Failure;
1902 : }
1903 : }
1904 :
1905 358 : for (int i = 0; i < aosFileList.size(); ++i)
1906 : {
1907 184 : if (CPLMoveFile(aosNewFileList[i], aosFileList[i]) != 0)
1908 : {
1909 : // Above method will have emitted an error in case of failure.
1910 0 : eErr = CE_Failure;
1911 : // Try to put the ones we moved back.
1912 0 : for (--i; i >= 0; i--)
1913 : {
1914 : // Nothing we can do if the moving back doesn't work...
1915 0 : CPL_IGNORE_RET_VAL(
1916 0 : CPLMoveFile(aosFileList[i], aosNewFileList[i]));
1917 : }
1918 0 : break;
1919 : }
1920 : }
1921 :
1922 174 : return eErr;
1923 : }
1924 :
1925 : //! @endcond
1926 :
1927 : /************************************************************************/
1928 : /* Rename() */
1929 : /************************************************************************/
1930 :
1931 : /**
1932 : * \brief Rename a dataset.
1933 : *
1934 : * Rename a dataset. This may including moving the dataset to a new directory
1935 : * or even a new filesystem.
1936 : *
1937 : * It is unwise to have open dataset handles on this dataset when it is
1938 : * being renamed.
1939 : *
1940 : * Equivalent of the C function GDALRenameDataset().
1941 : *
1942 : * @param pszNewName new name for the dataset.
1943 : * @param pszOldName old name for the dataset.
1944 : *
1945 : * @return CE_None on success, or CE_Failure if the operation fails.
1946 : */
1947 :
1948 177 : CPLErr GDALDriver::Rename(const char *pszNewName, const char *pszOldName)
1949 :
1950 : {
1951 177 : pfnRename = GetRenameCallback();
1952 177 : if (pfnRename != nullptr)
1953 3 : return pfnRename(pszNewName, pszOldName);
1954 :
1955 174 : return DefaultRename(pszNewName, pszOldName);
1956 : }
1957 :
1958 : /************************************************************************/
1959 : /* GDALRenameDataset() */
1960 : /************************************************************************/
1961 :
1962 : /**
1963 : * \brief Rename a dataset.
1964 : *
1965 : * @see GDALDriver::Rename()
1966 : */
1967 :
1968 178 : CPLErr CPL_STDCALL GDALRenameDataset(GDALDriverH hDriver,
1969 : const char *pszNewName,
1970 : const char *pszOldName)
1971 :
1972 : {
1973 178 : if (hDriver == nullptr)
1974 5 : hDriver = GDALIdentifyDriver(pszOldName, nullptr);
1975 :
1976 178 : if (hDriver == nullptr)
1977 : {
1978 1 : CPLError(CE_Failure, CPLE_AppDefined, "No identifiable driver for %s.",
1979 : pszOldName);
1980 1 : return CE_Failure;
1981 : }
1982 :
1983 177 : return GDALDriver::FromHandle(hDriver)->Rename(pszNewName, pszOldName);
1984 : }
1985 :
1986 : /************************************************************************/
1987 : /* DefaultCopyFiles() */
1988 : /* */
1989 : /* The default implementation based on file lists used when */
1990 : /* there is no format specific implementation. */
1991 : /************************************************************************/
1992 :
1993 : //! @cond Doxygen_Suppress
1994 12 : CPLErr GDALDriver::DefaultCopyFiles(const char *pszNewName,
1995 : const char *pszOldName)
1996 :
1997 : {
1998 : /* -------------------------------------------------------------------- */
1999 : /* Collect file list. */
2000 : /* -------------------------------------------------------------------- */
2001 : auto poDS = std::unique_ptr<GDALDataset>(
2002 : GDALDataset::Open(pszOldName, GDAL_OF_ALL | GDAL_OF_VERBOSE_ERROR,
2003 24 : nullptr, nullptr, nullptr));
2004 :
2005 12 : if (!poDS)
2006 : {
2007 0 : if (CPLGetLastErrorNo() == 0)
2008 0 : CPLError(CE_Failure, CPLE_OpenFailed,
2009 : "Unable to open %s to obtain file list.", pszOldName);
2010 :
2011 0 : return CE_Failure;
2012 : }
2013 :
2014 24 : const CPLStringList aosFileList(poDS->GetFileList());
2015 :
2016 12 : poDS.reset();
2017 :
2018 12 : if (aosFileList.empty())
2019 : {
2020 0 : CPLError(CE_Failure, CPLE_NotSupported,
2021 : "Unable to determine files associated with %s,\n"
2022 : "copy fails.",
2023 : pszOldName);
2024 :
2025 0 : return CE_Failure;
2026 : }
2027 :
2028 : /* -------------------------------------------------------------------- */
2029 : /* Produce a list of new filenames that correspond to the old */
2030 : /* names. */
2031 : /* -------------------------------------------------------------------- */
2032 12 : CPLErr eErr = CE_None;
2033 : const CPLStringList aosNewFileList(
2034 24 : CPLCorrespondingPaths(pszOldName, pszNewName, aosFileList.List()));
2035 :
2036 12 : if (aosNewFileList.empty())
2037 0 : return CE_Failure;
2038 :
2039 : // Guaranteed by CPLCorrespondingPaths()
2040 12 : CPLAssert(aosNewFileList.size() == aosFileList.size());
2041 :
2042 : VSIStatBufL sStatBuf;
2043 14 : if (VSIStatL(pszOldName, &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode) &&
2044 2 : VSIStatL(pszNewName, &sStatBuf) != 0)
2045 : {
2046 2 : if (VSIMkdirRecursive(pszNewName, 0755) != 0)
2047 : {
2048 1 : CPLError(CE_Failure, CPLE_AppDefined,
2049 : "Cannot create directory '%s'", pszNewName);
2050 1 : return CE_Failure;
2051 : }
2052 : }
2053 :
2054 33 : for (int i = 0; i < aosFileList.size(); ++i)
2055 : {
2056 22 : if (CPLCopyFile(aosNewFileList[i], aosFileList[i]) != 0)
2057 : {
2058 : // Above method will have emitted an error in case of failure.
2059 0 : eErr = CE_Failure;
2060 : // Try to put the ones we moved back.
2061 0 : for (--i; i >= 0; --i)
2062 : {
2063 0 : if (VSIUnlink(aosNewFileList[i]) != 0)
2064 : {
2065 0 : CPLError(CE_Warning, CPLE_AppDefined, "Cannot delete '%s'",
2066 : aosNewFileList[i]);
2067 : }
2068 : }
2069 0 : break;
2070 : }
2071 : }
2072 :
2073 11 : return eErr;
2074 : }
2075 :
2076 : //! @endcond
2077 :
2078 : /************************************************************************/
2079 : /* CopyFiles() */
2080 : /************************************************************************/
2081 :
2082 : /**
2083 : * \brief Copy the files of a dataset.
2084 : *
2085 : * Copy all the files associated with a dataset.
2086 : *
2087 : * Equivalent of the C function GDALCopyDatasetFiles().
2088 : *
2089 : * @param pszNewName new name for the dataset.
2090 : * @param pszOldName old name for the dataset.
2091 : *
2092 : * @return CE_None on success, or CE_Failure if the operation fails.
2093 : */
2094 :
2095 14 : CPLErr GDALDriver::CopyFiles(const char *pszNewName, const char *pszOldName)
2096 :
2097 : {
2098 14 : pfnCopyFiles = GetCopyFilesCallback();
2099 14 : if (pfnCopyFiles != nullptr)
2100 3 : return pfnCopyFiles(pszNewName, pszOldName);
2101 :
2102 11 : return DefaultCopyFiles(pszNewName, pszOldName);
2103 : }
2104 :
2105 : /************************************************************************/
2106 : /* GDALCopyDatasetFiles() */
2107 : /************************************************************************/
2108 :
2109 : /**
2110 : * \brief Copy the files of a dataset.
2111 : *
2112 : * @see GDALDriver::CopyFiles()
2113 : */
2114 :
2115 15 : CPLErr CPL_STDCALL GDALCopyDatasetFiles(GDALDriverH hDriver,
2116 : const char *pszNewName,
2117 : const char *pszOldName)
2118 :
2119 : {
2120 15 : if (hDriver == nullptr)
2121 10 : hDriver = GDALIdentifyDriver(pszOldName, nullptr);
2122 :
2123 15 : if (hDriver == nullptr)
2124 : {
2125 1 : CPLError(CE_Failure, CPLE_AppDefined, "No identifiable driver for %s.",
2126 : pszOldName);
2127 1 : return CE_Failure;
2128 : }
2129 :
2130 14 : return GDALDriver::FromHandle(hDriver)->CopyFiles(pszNewName, pszOldName);
2131 : }
2132 :
2133 : /************************************************************************/
2134 : /* GDALDriverHasOpenOption() */
2135 : /************************************************************************/
2136 :
2137 : /**
2138 : * \brief Returns TRUE if the given open option is supported by the driver.
2139 : * @param hDriver the handle of the driver
2140 : * @param pszOpenOptionName name of the open option to be checked
2141 : * @return TRUE if the driver supports the open option
2142 : * @since GDAL 3.11
2143 : */
2144 2 : bool GDALDriverHasOpenOption(GDALDriverH hDriver, const char *pszOpenOptionName)
2145 : {
2146 2 : VALIDATE_POINTER1(hDriver, "GDALDriverHasOpenOption", false);
2147 2 : return GDALDriver::FromHandle(hDriver)->HasOpenOption(pszOpenOptionName);
2148 : }
2149 :
2150 : /************************************************************************/
2151 : /* GDALGetDriverShortName() */
2152 : /************************************************************************/
2153 :
2154 : /**
2155 : * \brief Return the short name of a driver
2156 : *
2157 : * This is the string that can be
2158 : * passed to the GDALGetDriverByName() function.
2159 : *
2160 : * For the GeoTIFF driver, this is "GTiff"
2161 : *
2162 : * @param hDriver the handle of the driver
2163 : * @return the short name of the driver. The
2164 : * returned string should not be freed and is owned by the driver.
2165 : */
2166 :
2167 8907490 : const char *CPL_STDCALL GDALGetDriverShortName(GDALDriverH hDriver)
2168 :
2169 : {
2170 8907490 : VALIDATE_POINTER1(hDriver, "GDALGetDriverShortName", nullptr);
2171 :
2172 8907490 : return GDALDriver::FromHandle(hDriver)->GetDescription();
2173 : }
2174 :
2175 : /************************************************************************/
2176 : /* GDALGetDriverLongName() */
2177 : /************************************************************************/
2178 :
2179 : /**
2180 : * \brief Return the long name of a driver
2181 : *
2182 : * For the GeoTIFF driver, this is "GeoTIFF"
2183 : *
2184 : * @param hDriver the handle of the driver
2185 : * @return the long name of the driver or empty string. The
2186 : * returned string should not be freed and is owned by the driver.
2187 : */
2188 :
2189 514 : const char *CPL_STDCALL GDALGetDriverLongName(GDALDriverH hDriver)
2190 :
2191 : {
2192 514 : VALIDATE_POINTER1(hDriver, "GDALGetDriverLongName", nullptr);
2193 :
2194 : const char *pszLongName =
2195 514 : GDALDriver::FromHandle(hDriver)->GetMetadataItem(GDAL_DMD_LONGNAME);
2196 :
2197 514 : if (pszLongName == nullptr)
2198 0 : return "";
2199 :
2200 514 : return pszLongName;
2201 : }
2202 :
2203 : /************************************************************************/
2204 : /* GDALGetDriverHelpTopic() */
2205 : /************************************************************************/
2206 :
2207 : /**
2208 : * \brief Return the URL to the help that describes the driver
2209 : *
2210 : * That URL is relative to the GDAL documentation directory.
2211 : *
2212 : * For the GeoTIFF driver, this is "frmt_gtiff.html"
2213 : *
2214 : * @param hDriver the handle of the driver
2215 : * @return the URL to the help that describes the driver or NULL. The
2216 : * returned string should not be freed and is owned by the driver.
2217 : */
2218 :
2219 0 : const char *CPL_STDCALL GDALGetDriverHelpTopic(GDALDriverH hDriver)
2220 :
2221 : {
2222 0 : VALIDATE_POINTER1(hDriver, "GDALGetDriverHelpTopic", nullptr);
2223 :
2224 0 : return GDALDriver::FromHandle(hDriver)->GetMetadataItem(GDAL_DMD_HELPTOPIC);
2225 : }
2226 :
2227 : /************************************************************************/
2228 : /* GDALGetDriverCreationOptionList() */
2229 : /************************************************************************/
2230 :
2231 : /**
2232 : * \brief Return the list of creation options of the driver
2233 : *
2234 : * Return the list of creation options of the driver used by Create() and
2235 : * CreateCopy() as an XML string
2236 : *
2237 : * @param hDriver the handle of the driver
2238 : * @return an XML string that describes the list of creation options or
2239 : * empty string. The returned string should not be freed and is
2240 : * owned by the driver.
2241 : */
2242 :
2243 0 : const char *CPL_STDCALL GDALGetDriverCreationOptionList(GDALDriverH hDriver)
2244 :
2245 : {
2246 0 : VALIDATE_POINTER1(hDriver, "GDALGetDriverCreationOptionList", nullptr);
2247 :
2248 : const char *pszOptionList =
2249 0 : GDALDriver::FromHandle(hDriver)->GetMetadataItem(
2250 0 : GDAL_DMD_CREATIONOPTIONLIST);
2251 :
2252 0 : if (pszOptionList == nullptr)
2253 0 : return "";
2254 :
2255 0 : return pszOptionList;
2256 : }
2257 :
2258 : /************************************************************************/
2259 : /* GDALValidateCreationOptions() */
2260 : /************************************************************************/
2261 :
2262 : /**
2263 : * \brief Validate the list of creation options that are handled by a driver
2264 : *
2265 : * This is a helper method primarily used by Create() and
2266 : * CreateCopy() to validate that the passed in list of creation options
2267 : * is compatible with the GDAL_DMD_CREATIONOPTIONLIST metadata item defined
2268 : * by some drivers. @see GDALGetDriverCreationOptionList()
2269 : *
2270 : * If the GDAL_DMD_CREATIONOPTIONLIST metadata item is not defined, this
2271 : * function will return TRUE. Otherwise it will check that the keys and values
2272 : * in the list of creation options are compatible with the capabilities declared
2273 : * by the GDAL_DMD_CREATIONOPTIONLIST metadata item. In case of incompatibility
2274 : * a (non fatal) warning will be emitted and FALSE will be returned.
2275 : *
2276 : * @param hDriver the handle of the driver with whom the lists of creation
2277 : * option must be validated
2278 : * @param papszCreationOptions the list of creation options. An array of
2279 : * strings, whose last element is a NULL pointer
2280 : * @return TRUE if the list of creation options is compatible with the Create()
2281 : * and CreateCopy() method of the driver, FALSE otherwise.
2282 : */
2283 :
2284 37947 : int CPL_STDCALL GDALValidateCreationOptions(GDALDriverH hDriver,
2285 : CSLConstList papszCreationOptions)
2286 : {
2287 37947 : VALIDATE_POINTER1(hDriver, "GDALValidateCreationOptions", FALSE);
2288 : const char *pszOptionList =
2289 37947 : GDALDriver::FromHandle(hDriver)->GetMetadataItem(
2290 37947 : GDAL_DMD_CREATIONOPTIONLIST);
2291 37947 : CPLString osDriver;
2292 : osDriver.Printf("driver %s",
2293 37947 : GDALDriver::FromHandle(hDriver)->GetDescription());
2294 37947 : bool bFoundOptionToRemove = false;
2295 37947 : constexpr const char *const apszExcludedOptions[] = {
2296 : "APPEND_SUBDATASET", "COPY_SRC_MDD", "SRC_MDD", "SKIP_HOLES"};
2297 55774 : for (const char *pszCO : cpl::Iterate(papszCreationOptions))
2298 : {
2299 89796 : for (const char *pszExcludedOptions : apszExcludedOptions)
2300 : {
2301 71969 : if (STARTS_WITH_CI(pszCO, pszExcludedOptions) &&
2302 211 : pszCO[strlen(pszExcludedOptions)] == '=')
2303 : {
2304 211 : bFoundOptionToRemove = true;
2305 211 : break;
2306 : }
2307 : }
2308 18038 : if (bFoundOptionToRemove)
2309 211 : break;
2310 : }
2311 37947 : CSLConstList papszOptionsToValidate = papszCreationOptions;
2312 37947 : char **papszOptionsToFree = nullptr;
2313 37947 : if (bFoundOptionToRemove)
2314 : {
2315 647 : for (const char *pszCO : cpl::Iterate(papszCreationOptions))
2316 : {
2317 436 : bool bMatch = false;
2318 1766 : for (const char *pszExcludedOptions : apszExcludedOptions)
2319 : {
2320 1554 : if (STARTS_WITH_CI(pszCO, pszExcludedOptions) &&
2321 224 : pszCO[strlen(pszExcludedOptions)] == '=')
2322 : {
2323 224 : bMatch = true;
2324 224 : break;
2325 : }
2326 : }
2327 436 : if (!bMatch)
2328 212 : papszOptionsToFree = CSLAddString(papszOptionsToFree, pszCO);
2329 : }
2330 211 : papszOptionsToValidate = papszOptionsToFree;
2331 : }
2332 :
2333 37947 : const bool bRet = CPL_TO_BOOL(
2334 : GDALValidateOptions(hDriver, pszOptionList, papszOptionsToValidate,
2335 : "creation option", osDriver));
2336 37947 : CSLDestroy(papszOptionsToFree);
2337 37947 : return bRet;
2338 : }
2339 :
2340 : /************************************************************************/
2341 : /* GDALValidateOpenOptions() */
2342 : /************************************************************************/
2343 :
2344 63860 : int GDALValidateOpenOptions(GDALDriverH hDriver,
2345 : const char *const *papszOpenOptions)
2346 : {
2347 63860 : VALIDATE_POINTER1(hDriver, "GDALValidateOpenOptions", FALSE);
2348 : const char *pszOptionList =
2349 63860 : GDALDriver::FromHandle(hDriver)->GetMetadataItem(
2350 63860 : GDAL_DMD_OPENOPTIONLIST);
2351 127720 : CPLString osDriver;
2352 : osDriver.Printf("driver %s",
2353 63860 : GDALDriver::FromHandle(hDriver)->GetDescription());
2354 63860 : return GDALValidateOptions(hDriver, pszOptionList, papszOpenOptions,
2355 63860 : "open option", osDriver);
2356 : }
2357 :
2358 : /************************************************************************/
2359 : /* GDALValidateOptions() */
2360 : /************************************************************************/
2361 :
2362 117047 : int GDALValidateOptions(GDALDriverH hDriver, const char *pszOptionList,
2363 : const char *const *papszOptionsToValidate,
2364 : const char *pszErrorMessageOptionType,
2365 : const char *pszErrorMessageContainerName)
2366 : {
2367 117047 : if (papszOptionsToValidate == nullptr || *papszOptionsToValidate == nullptr)
2368 98497 : return TRUE;
2369 18550 : if (pszOptionList == nullptr)
2370 182 : return TRUE;
2371 :
2372 18368 : CPLXMLNode *psNode = CPLParseXMLString(pszOptionList);
2373 18368 : if (psNode == nullptr)
2374 : {
2375 0 : CPLError(CE_Warning, CPLE_AppDefined,
2376 : "Could not parse %s list of %s. Assuming options are valid.",
2377 : pszErrorMessageOptionType, pszErrorMessageContainerName);
2378 0 : return TRUE;
2379 : }
2380 :
2381 18368 : bool bRet = true;
2382 49884 : while (*papszOptionsToValidate)
2383 : {
2384 31516 : char *pszKey = nullptr;
2385 : const char *pszValue =
2386 31516 : CPLParseNameValue(*papszOptionsToValidate, &pszKey);
2387 31516 : if (pszKey == nullptr)
2388 : {
2389 2 : CPLError(CE_Warning, CPLE_NotSupported,
2390 : "%s '%s' is not formatted with the key=value format",
2391 : pszErrorMessageOptionType, *papszOptionsToValidate);
2392 2 : bRet = false;
2393 :
2394 2 : ++papszOptionsToValidate;
2395 2434 : continue;
2396 : }
2397 :
2398 31514 : if (EQUAL(pszKey, "VALIDATE_OPEN_OPTIONS"))
2399 : {
2400 0 : ++papszOptionsToValidate;
2401 0 : CPLFree(pszKey);
2402 0 : continue;
2403 : }
2404 :
2405 : // Must we be forgiving in case of missing option ?
2406 31514 : bool bWarnIfMissingKey = true;
2407 31514 : if (pszKey[0] == '@')
2408 : {
2409 2415 : bWarnIfMissingKey = false;
2410 2415 : memmove(pszKey, pszKey + 1, strlen(pszKey + 1) + 1);
2411 : }
2412 :
2413 31514 : CPLXMLNode *psChildNode = psNode->psChild;
2414 316922 : while (psChildNode)
2415 : {
2416 314490 : if (EQUAL(psChildNode->pszValue, "OPTION"))
2417 : {
2418 : const char *pszOptionName =
2419 314490 : CPLGetXMLValue(psChildNode, "name", "");
2420 : /* For option names terminated by wildcard (NITF BLOCKA option
2421 : * names for example) */
2422 314490 : if (strlen(pszOptionName) > 0 &&
2423 314490 : pszOptionName[strlen(pszOptionName) - 1] == '*' &&
2424 1288 : EQUALN(pszOptionName, pszKey, strlen(pszOptionName) - 1))
2425 : {
2426 216 : break;
2427 : }
2428 :
2429 : /* For option names beginning by a wildcard */
2430 314274 : if (pszOptionName[0] == '*' &&
2431 57 : strlen(pszKey) > strlen(pszOptionName) &&
2432 9 : EQUAL(pszKey + strlen(pszKey) - strlen(pszOptionName + 1),
2433 : pszOptionName + 1))
2434 : {
2435 2 : break;
2436 : }
2437 :
2438 : // For options names with * in the middle
2439 314272 : const char *pszStarInOptionName = strchr(pszOptionName, '*');
2440 314272 : if (pszStarInOptionName &&
2441 1093 : pszStarInOptionName != pszOptionName &&
2442 : pszStarInOptionName !=
2443 1093 : pszOptionName + strlen(pszOptionName) - 1 &&
2444 21 : strlen(pszKey) > static_cast<size_t>(pszStarInOptionName -
2445 12 : pszOptionName) &&
2446 12 : EQUALN(pszKey, pszOptionName,
2447 : static_cast<size_t>(pszStarInOptionName -
2448 12 : pszOptionName)) &&
2449 12 : EQUAL(pszKey +
2450 : static_cast<size_t>(pszStarInOptionName -
2451 : pszOptionName) +
2452 : 1,
2453 : pszStarInOptionName + 1))
2454 : {
2455 6 : break;
2456 : }
2457 :
2458 314266 : if (EQUAL(pszOptionName, pszKey))
2459 : {
2460 28746 : break;
2461 : }
2462 : const char *pszAlias =
2463 285520 : CPLGetXMLValue(psChildNode, "alias", nullptr);
2464 : const char *pszDeprecatedAlias =
2465 285520 : pszAlias ? nullptr
2466 284577 : : CPLGetXMLValue(psChildNode, "deprecated_alias",
2467 285520 : nullptr);
2468 285520 : if (!pszAlias && pszDeprecatedAlias)
2469 168 : pszAlias = pszDeprecatedAlias;
2470 285520 : if (pszAlias && EQUAL(pszAlias, pszKey))
2471 : {
2472 112 : if (pszDeprecatedAlias)
2473 : {
2474 0 : CPLDebug(
2475 : "GDAL",
2476 : "Using deprecated alias '%s'. New name is '%s'",
2477 : pszAlias, pszOptionName);
2478 : }
2479 112 : break;
2480 : }
2481 : }
2482 285408 : psChildNode = psChildNode->psNext;
2483 : }
2484 31514 : if (psChildNode == nullptr)
2485 : {
2486 2456 : if (bWarnIfMissingKey &&
2487 24 : (!EQUAL(pszErrorMessageOptionType, "open option") ||
2488 2 : CPLFetchBool(papszOptionsToValidate, "VALIDATE_OPEN_OPTIONS",
2489 : true)))
2490 : {
2491 24 : const char *pszAdditionalMsg = "";
2492 24 : if (hDriver &&
2493 19 : EQUAL(pszErrorMessageOptionType, "creation option"))
2494 : {
2495 : const char *pszLCOList =
2496 15 : GDALDriver::FromHandle(hDriver)->GetMetadataItem(
2497 15 : GDAL_DS_LAYER_CREATIONOPTIONLIST);
2498 20 : if (pszLCOList &&
2499 20 : (CPLString(pszLCOList)
2500 5 : .ifind(CPLSPrintf("\"%s\"", pszKey)) !=
2501 10 : std::string::npos ||
2502 20 : CPLString(pszLCOList)
2503 5 : .ifind(CPLSPrintf("'%s'", pszKey)) !=
2504 : std::string::npos))
2505 : {
2506 1 : pszAdditionalMsg = ", but a layer creation option of "
2507 : "that name exists.";
2508 15 : }
2509 : }
2510 9 : else if (hDriver && EQUAL(pszErrorMessageOptionType,
2511 : "layer creation option"))
2512 : {
2513 : const char *pszLCOList =
2514 2 : GDALDriver::FromHandle(hDriver)->GetMetadataItem(
2515 2 : GDAL_DMD_CREATIONOPTIONLIST);
2516 4 : if (pszLCOList &&
2517 4 : (CPLString(pszLCOList)
2518 2 : .ifind(CPLSPrintf("\"%s\"", pszKey)) !=
2519 4 : std::string::npos ||
2520 4 : CPLString(pszLCOList)
2521 2 : .ifind(CPLSPrintf("'%s'", pszKey)) !=
2522 : std::string::npos))
2523 : {
2524 1 : pszAdditionalMsg = ", but a creation option of "
2525 : "that name exists.";
2526 : }
2527 : }
2528 :
2529 24 : CPLError(CE_Warning, CPLE_NotSupported,
2530 : "%s does not support %s %s%s",
2531 : pszErrorMessageContainerName,
2532 : pszErrorMessageOptionType, pszKey, pszAdditionalMsg);
2533 24 : bRet = false;
2534 : }
2535 :
2536 2432 : CPLFree(pszKey);
2537 2432 : ++papszOptionsToValidate;
2538 2432 : continue;
2539 : }
2540 :
2541 : #ifdef DEBUG
2542 29082 : CPLXMLNode *psChildSubNode = psChildNode->psChild;
2543 172226 : while (psChildSubNode)
2544 : {
2545 143144 : if (psChildSubNode->eType == CXT_Attribute)
2546 : {
2547 100838 : if (!(EQUAL(psChildSubNode->pszValue, "name") ||
2548 71756 : EQUAL(psChildSubNode->pszValue, "alias") ||
2549 71561 : EQUAL(psChildSubNode->pszValue, "deprecated_alias") ||
2550 71467 : EQUAL(psChildSubNode->pszValue, "alt_config_option") ||
2551 71447 : EQUAL(psChildSubNode->pszValue, "description") ||
2552 46968 : EQUAL(psChildSubNode->pszValue, "type") ||
2553 17886 : EQUAL(psChildSubNode->pszValue, "min") ||
2554 17568 : EQUAL(psChildSubNode->pszValue, "max") ||
2555 17181 : EQUAL(psChildSubNode->pszValue, "default") ||
2556 1102 : EQUAL(psChildSubNode->pszValue, "maxsize") ||
2557 1072 : EQUAL(psChildSubNode->pszValue, "required") ||
2558 1017 : EQUAL(psChildSubNode->pszValue, "scope")))
2559 : {
2560 : /* Driver error */
2561 0 : CPLError(CE_Warning, CPLE_NotSupported,
2562 : "%s : unhandled attribute '%s' for %s %s.",
2563 : pszErrorMessageContainerName,
2564 : psChildSubNode->pszValue, pszKey,
2565 : pszErrorMessageOptionType);
2566 : }
2567 : }
2568 143144 : psChildSubNode = psChildSubNode->psNext;
2569 : }
2570 : #endif
2571 :
2572 29082 : const char *pszType = CPLGetXMLValue(psChildNode, "type", nullptr);
2573 29082 : const char *pszMin = CPLGetXMLValue(psChildNode, "min", nullptr);
2574 29082 : const char *pszMax = CPLGetXMLValue(psChildNode, "max", nullptr);
2575 29082 : if (pszType != nullptr)
2576 : {
2577 29082 : if (EQUAL(pszType, "INT") || EQUAL(pszType, "INTEGER"))
2578 : {
2579 8872 : const char *pszValueIter = pszValue;
2580 22755 : while (*pszValueIter)
2581 : {
2582 13934 : if (!((*pszValueIter >= '0' && *pszValueIter <= '9') ||
2583 70 : *pszValueIter == '+' || *pszValueIter == '-'))
2584 : {
2585 51 : CPLError(CE_Warning, CPLE_NotSupported,
2586 : "'%s' is an unexpected value for %s %s of "
2587 : "type int.",
2588 : pszValue, pszKey, pszErrorMessageOptionType);
2589 51 : bRet = false;
2590 51 : break;
2591 : }
2592 13883 : ++pszValueIter;
2593 : }
2594 8872 : if (*pszValueIter == '\0')
2595 : {
2596 8821 : if (pszMin && atoi(pszValue) < atoi(pszMin))
2597 : {
2598 10 : CPLError(CE_Warning, CPLE_NotSupported,
2599 : "'%s' is an unexpected value for %s %s that "
2600 : "should be >= %s.",
2601 : pszValue, pszKey, pszErrorMessageOptionType,
2602 : pszMin);
2603 10 : bRet = false;
2604 : }
2605 8821 : if (pszMax && atoi(pszValue) > atoi(pszMax))
2606 : {
2607 12 : CPLError(CE_Warning, CPLE_NotSupported,
2608 : "'%s' is an unexpected value for %s %s that "
2609 : "should be <= %s.",
2610 : pszValue, pszKey, pszErrorMessageOptionType,
2611 : pszMax);
2612 12 : bRet = false;
2613 : }
2614 8872 : }
2615 : }
2616 20210 : else if (EQUAL(pszType, "UNSIGNED INT"))
2617 : {
2618 3 : const char *pszValueIter = pszValue;
2619 10 : while (*pszValueIter)
2620 : {
2621 7 : if (!((*pszValueIter >= '0' && *pszValueIter <= '9') ||
2622 0 : *pszValueIter == '+'))
2623 : {
2624 0 : CPLError(CE_Warning, CPLE_NotSupported,
2625 : "'%s' is an unexpected value for %s %s of "
2626 : "type unsigned int.",
2627 : pszValue, pszKey, pszErrorMessageOptionType);
2628 0 : bRet = false;
2629 0 : break;
2630 : }
2631 7 : ++pszValueIter;
2632 : }
2633 3 : if (*pszValueIter == '\0')
2634 : {
2635 3 : if (pszMin && atoi(pszValue) < atoi(pszMin))
2636 : {
2637 0 : CPLError(CE_Warning, CPLE_NotSupported,
2638 : "'%s' is an unexpected value for %s %s that "
2639 : "should be >= %s.",
2640 : pszValue, pszKey, pszErrorMessageOptionType,
2641 : pszMin);
2642 0 : bRet = false;
2643 : }
2644 3 : if (pszMax && atoi(pszValue) > atoi(pszMax))
2645 : {
2646 0 : CPLError(CE_Warning, CPLE_NotSupported,
2647 : "'%s' is an unexpected value for %s %s that "
2648 : "should be <= %s.",
2649 : pszValue, pszKey, pszErrorMessageOptionType,
2650 : pszMax);
2651 0 : bRet = false;
2652 : }
2653 : }
2654 : }
2655 20207 : else if (EQUAL(pszType, "FLOAT"))
2656 : {
2657 774 : char *endPtr = nullptr;
2658 774 : double dfVal = CPLStrtod(pszValue, &endPtr);
2659 774 : if (!(endPtr == nullptr || *endPtr == '\0'))
2660 : {
2661 2 : CPLError(
2662 : CE_Warning, CPLE_NotSupported,
2663 : "'%s' is an unexpected value for %s %s of type float.",
2664 : pszValue, pszKey, pszErrorMessageOptionType);
2665 2 : bRet = false;
2666 : }
2667 : else
2668 : {
2669 772 : if (pszMin && dfVal < CPLAtof(pszMin))
2670 : {
2671 3 : CPLError(CE_Warning, CPLE_NotSupported,
2672 : "'%s' is an unexpected value for %s %s that "
2673 : "should be >= %s.",
2674 : pszValue, pszKey, pszErrorMessageOptionType,
2675 : pszMin);
2676 3 : bRet = false;
2677 : }
2678 772 : if (pszMax && dfVal > CPLAtof(pszMax))
2679 : {
2680 0 : CPLError(CE_Warning, CPLE_NotSupported,
2681 : "'%s' is an unexpected value for %s %s that "
2682 : "should be <= %s.",
2683 : pszValue, pszKey, pszErrorMessageOptionType,
2684 : pszMax);
2685 0 : bRet = false;
2686 : }
2687 : }
2688 : }
2689 19433 : else if (EQUAL(pszType, "BOOLEAN"))
2690 : {
2691 4658 : if (!(EQUAL(pszValue, "ON") || EQUAL(pszValue, "TRUE") ||
2692 4588 : EQUAL(pszValue, "YES") || EQUAL(pszValue, "OFF") ||
2693 836 : EQUAL(pszValue, "FALSE") || EQUAL(pszValue, "NO")))
2694 : {
2695 1 : CPLError(CE_Warning, CPLE_NotSupported,
2696 : "'%s' is an unexpected value for %s %s of type "
2697 : "boolean.",
2698 : pszValue, pszKey, pszErrorMessageOptionType);
2699 1 : bRet = false;
2700 : }
2701 : }
2702 14775 : else if (EQUAL(pszType, "STRING-SELECT"))
2703 : {
2704 7591 : bool bMatchFound = false;
2705 7591 : bool bOtherValuesElementFound = false;
2706 7591 : CPLXMLNode *psStringSelect = psChildNode->psChild;
2707 46582 : while (psStringSelect)
2708 : {
2709 46541 : if (psStringSelect->eType == CXT_Element &&
2710 22385 : EQUAL(psStringSelect->pszValue, "Value"))
2711 : {
2712 22385 : CPLXMLNode *psOptionNode = psStringSelect->psChild;
2713 37847 : while (psOptionNode)
2714 : {
2715 23012 : if (psOptionNode->eType == CXT_Text &&
2716 22266 : EQUAL(psOptionNode->pszValue, pszValue))
2717 : {
2718 7431 : bMatchFound = true;
2719 7431 : break;
2720 : }
2721 15581 : if (psOptionNode->eType == CXT_Attribute &&
2722 746 : (EQUAL(psOptionNode->pszValue, "alias") ||
2723 15 : EQUAL(psOptionNode->pszValue,
2724 731 : "deprecated_alias")) &&
2725 731 : EQUAL(psOptionNode->psChild->pszValue,
2726 : pszValue))
2727 : {
2728 119 : bMatchFound = true;
2729 119 : break;
2730 : }
2731 15462 : psOptionNode = psOptionNode->psNext;
2732 : }
2733 22385 : if (bMatchFound)
2734 22385 : break;
2735 : }
2736 24156 : else if (psStringSelect->eType == CXT_Element &&
2737 0 : EQUAL(psStringSelect->pszValue, "OtherValues"))
2738 : {
2739 0 : bOtherValuesElementFound = true;
2740 : }
2741 38991 : psStringSelect = psStringSelect->psNext;
2742 : }
2743 7591 : if (!bMatchFound && !bOtherValuesElementFound)
2744 : {
2745 41 : CPLError(CE_Warning, CPLE_NotSupported,
2746 : "'%s' is an unexpected value for %s %s of type "
2747 : "string-select.",
2748 : pszValue, pszKey, pszErrorMessageOptionType);
2749 41 : bRet = false;
2750 : }
2751 : }
2752 7184 : else if (EQUAL(pszType, "STRING"))
2753 : {
2754 : const char *pszMaxSize =
2755 7184 : CPLGetXMLValue(psChildNode, "maxsize", nullptr);
2756 7184 : if (pszMaxSize != nullptr)
2757 : {
2758 30 : if (static_cast<int>(strlen(pszValue)) > atoi(pszMaxSize))
2759 : {
2760 1 : CPLError(CE_Warning, CPLE_NotSupported,
2761 : "'%s' is of size %d, whereas maximum size for "
2762 : "%s %s is %d.",
2763 1 : pszValue, static_cast<int>(strlen(pszValue)),
2764 : pszKey, pszErrorMessageOptionType,
2765 : atoi(pszMaxSize));
2766 1 : bRet = false;
2767 : }
2768 : }
2769 : }
2770 : else
2771 : {
2772 : /* Driver error */
2773 0 : CPLError(CE_Warning, CPLE_NotSupported,
2774 : "%s : type '%s' for %s %s is not recognized.",
2775 : pszErrorMessageContainerName, pszType, pszKey,
2776 : pszErrorMessageOptionType);
2777 : }
2778 : }
2779 : else
2780 : {
2781 : /* Driver error */
2782 0 : CPLError(CE_Warning, CPLE_NotSupported, "%s : no type for %s %s.",
2783 : pszErrorMessageContainerName, pszKey,
2784 : pszErrorMessageOptionType);
2785 : }
2786 29082 : CPLFree(pszKey);
2787 29082 : ++papszOptionsToValidate;
2788 : }
2789 :
2790 18368 : CPLDestroyXMLNode(psNode);
2791 18368 : return bRet ? TRUE : FALSE;
2792 : }
2793 :
2794 : /************************************************************************/
2795 : /* GDALIdentifyDriver() */
2796 : /************************************************************************/
2797 :
2798 : /**
2799 : * \brief Identify the driver that can open a dataset.
2800 : *
2801 : * This function will try to identify the driver that can open the passed file
2802 : * name by invoking the Identify method of each registered GDALDriver in turn.
2803 : * The first driver that successfully identifies the file name will be returned.
2804 : * If all drivers fail then NULL is returned.
2805 : *
2806 : * In order to reduce the need for such searches to touch the operating system
2807 : * file system machinery, it is possible to give an optional list of files.
2808 : * This is the list of all files at the same level in the file system as the
2809 : * target file, including the target file. The filenames will not include any
2810 : * path components, and are essentially just the output of VSIReadDir() on the
2811 : * parent directory. If the target object does not have filesystem semantics
2812 : * then the file list should be NULL.
2813 : *
2814 : * @param pszFilename the name of the file to access. In the case of
2815 : * exotic drivers this may not refer to a physical file, but instead contain
2816 : * information for the driver on how to access a dataset.
2817 : *
2818 : * @param papszFileList an array of strings, whose last element is the NULL
2819 : * pointer. These strings are filenames that are auxiliary to the main
2820 : * filename. The passed value may be NULL.
2821 : *
2822 : * @return A GDALDriverH handle or NULL on failure. For C++ applications
2823 : * this handle can be cast to a GDALDriver *.
2824 : */
2825 :
2826 26850 : GDALDriverH CPL_STDCALL GDALIdentifyDriver(const char *pszFilename,
2827 : CSLConstList papszFileList)
2828 :
2829 : {
2830 26850 : return GDALIdentifyDriverEx(pszFilename, 0, nullptr, papszFileList);
2831 : }
2832 :
2833 : /************************************************************************/
2834 : /* GDALIdentifyDriverEx() */
2835 : /************************************************************************/
2836 :
2837 : /**
2838 : * \brief Identify the driver that can open a dataset.
2839 : *
2840 : * This function will try to identify the driver that can open the passed file
2841 : * name by invoking the Identify method of each registered GDALDriver in turn.
2842 : * The first driver that successfully identifies the file name will be returned.
2843 : * If all drivers fail then NULL is returned.
2844 : *
2845 : * In order to reduce the need for such searches to touch the operating system
2846 : * file system machinery, it is possible to give an optional list of files.
2847 : * This is the list of all files at the same level in the file system as the
2848 : * target file, including the target file. The filenames will not include any
2849 : * path components, and are essentially just the output of VSIReadDir() on the
2850 : * parent directory. If the target object does not have filesystem semantics
2851 : * then the file list should be NULL.
2852 : *
2853 : * @param pszFilename the name of the file to access. In the case of
2854 : * exotic drivers this may not refer to a physical file, but instead contain
2855 : * information for the driver on how to access a dataset.
2856 : *
2857 : * @param nIdentifyFlags a combination of GDAL_OF_RASTER for raster drivers
2858 : * or GDAL_OF_VECTOR for vector drivers. If none of the value is specified,
2859 : * both kinds are implied.
2860 : *
2861 : * @param papszAllowedDrivers NULL to consider all candidate drivers, or a NULL
2862 : * terminated list of strings with the driver short names that must be
2863 : * considered.
2864 : *
2865 : * @param papszFileList an array of strings, whose last element is the NULL
2866 : * pointer. These strings are filenames that are auxiliary to the main
2867 : * filename. The passed value may be NULL.
2868 : *
2869 : * @return A GDALDriverH handle or NULL on failure. For C++ applications
2870 : * this handle can be cast to a GDALDriver *.
2871 : */
2872 :
2873 26940 : GDALDriverH CPL_STDCALL GDALIdentifyDriverEx(
2874 : const char *pszFilename, unsigned int nIdentifyFlags,
2875 : const char *const *papszAllowedDrivers, const char *const *papszFileList)
2876 : {
2877 26940 : GDALDriverManager *poDM = GetGDALDriverManager();
2878 26940 : CPLAssert(nullptr != poDM);
2879 :
2880 : // If no driver kind is specified, assume all are to be probed.
2881 26940 : if ((nIdentifyFlags & GDAL_OF_KIND_MASK) == 0)
2882 26897 : nIdentifyFlags |= GDAL_OF_KIND_MASK & ~GDAL_OF_MULTIDIM_RASTER;
2883 :
2884 53880 : GDALOpenInfo oOpenInfo(pszFilename, nIdentifyFlags, papszFileList);
2885 26940 : oOpenInfo.papszAllowedDrivers = papszAllowedDrivers;
2886 :
2887 53880 : CPLErrorStateBackuper oBackuper;
2888 26940 : CPLErrorSetState(CE_None, CPLE_AppDefined, "");
2889 :
2890 26940 : const int nDriverCount = poDM->GetDriverCount();
2891 :
2892 : // First pass: only use drivers that have a pfnIdentify implementation.
2893 53880 : std::vector<GDALDriver *> apoSecondPassDrivers;
2894 6049720 : for (int iDriver = 0; iDriver < nDriverCount; ++iDriver)
2895 : {
2896 6024040 : GDALDriver *poDriver = poDM->GetDriver(iDriver);
2897 6031560 : if (papszAllowedDrivers != nullptr &&
2898 7527 : CSLFindString(papszAllowedDrivers,
2899 : GDALGetDriverShortName(poDriver)) == -1)
2900 : {
2901 1155150 : continue;
2902 : }
2903 :
2904 6017810 : VALIDATE_POINTER1(poDriver, "GDALIdentifyDriver", nullptr);
2905 :
2906 6016560 : if (poDriver->pfnIdentify == nullptr &&
2907 1143750 : poDriver->pfnIdentifyEx == nullptr)
2908 : {
2909 1143750 : continue;
2910 : }
2911 :
2912 4872850 : if (papszAllowedDrivers != nullptr &&
2913 44 : CSLFindString(papszAllowedDrivers,
2914 : GDALGetDriverShortName(poDriver)) == -1)
2915 0 : continue;
2916 14613600 : if ((nIdentifyFlags & GDAL_OF_RASTER) != 0 &&
2917 4873320 : (nIdentifyFlags & GDAL_OF_VECTOR) == 0 &&
2918 519 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER) == nullptr)
2919 145 : continue;
2920 14621400 : if ((nIdentifyFlags & GDAL_OF_VECTOR) != 0 &&
2921 4877670 : (nIdentifyFlags & GDAL_OF_RASTER) == 0 &&
2922 5012 : poDriver->GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
2923 3772 : continue;
2924 :
2925 4868890 : if (poDriver->pfnIdentifyEx)
2926 : {
2927 0 : if (poDriver->pfnIdentifyEx(poDriver, &oOpenInfo) > 0)
2928 0 : return poDriver;
2929 : }
2930 : else
2931 : {
2932 4868890 : const int nIdentifyRes = poDriver->pfnIdentify(&oOpenInfo);
2933 4868890 : if (nIdentifyRes > 0)
2934 1257 : return poDriver;
2935 4894470 : if (nIdentifyRes < 0 &&
2936 26840 : poDriver->GetMetadataItem("IS_NON_LOADED_PLUGIN"))
2937 : {
2938 : // Not loaded plugin
2939 34 : apoSecondPassDrivers.push_back(poDriver);
2940 : }
2941 : }
2942 : }
2943 :
2944 : // second pass: try loading plugin drivers
2945 25714 : for (auto poDriver : apoSecondPassDrivers)
2946 : {
2947 : // Force plugin driver loading
2948 32 : poDriver->GetMetadata();
2949 32 : if (poDriver->pfnIdentify(&oOpenInfo) > 0)
2950 1 : return poDriver;
2951 : }
2952 :
2953 : // third pass: slow method.
2954 5917750 : for (int iDriver = 0; iDriver < nDriverCount; ++iDriver)
2955 : {
2956 5892290 : GDALDriver *poDriver = poDM->GetDriver(iDriver);
2957 5896220 : if (papszAllowedDrivers != nullptr &&
2958 3926 : CSLFindString(papszAllowedDrivers,
2959 : GDALGetDriverShortName(poDriver)) == -1)
2960 : {
2961 3909 : continue;
2962 : }
2963 :
2964 5888380 : VALIDATE_POINTER1(poDriver, "GDALIdentifyDriver", nullptr);
2965 :
2966 17663700 : if ((nIdentifyFlags & GDAL_OF_RASTER) != 0 &&
2967 5888840 : (nIdentifyFlags & GDAL_OF_VECTOR) == 0 &&
2968 460 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER) == nullptr)
2969 143 : continue;
2970 17665400 : if ((nIdentifyFlags & GDAL_OF_VECTOR) != 0 &&
2971 5889850 : (nIdentifyFlags & GDAL_OF_RASTER) == 0 &&
2972 1612 : poDriver->GetMetadataItem(GDAL_DCAP_VECTOR) == nullptr)
2973 974 : continue;
2974 :
2975 5887260 : if (poDriver->pfnIdentifyEx != nullptr)
2976 : {
2977 0 : if (poDriver->pfnIdentifyEx(poDriver, &oOpenInfo) == 0)
2978 0 : continue;
2979 : }
2980 5887260 : else if (poDriver->pfnIdentify != nullptr)
2981 : {
2982 4767440 : if (poDriver->pfnIdentify(&oOpenInfo) == 0)
2983 4741180 : continue;
2984 : }
2985 :
2986 : GDALDataset *poDS;
2987 1146080 : if (poDriver->pfnOpen != nullptr)
2988 : {
2989 1094970 : poDS = poDriver->pfnOpen(&oOpenInfo);
2990 1094970 : if (poDS != nullptr)
2991 : {
2992 87 : delete poDS;
2993 87 : return GDALDriver::ToHandle(poDriver);
2994 : }
2995 :
2996 1094880 : if (CPLGetLastErrorType() != CE_None)
2997 136 : return nullptr;
2998 : }
2999 51109 : else if (poDriver->pfnOpenWithDriverArg != nullptr)
3000 : {
3001 0 : poDS = poDriver->pfnOpenWithDriverArg(poDriver, &oOpenInfo);
3002 0 : if (poDS != nullptr)
3003 : {
3004 0 : delete poDS;
3005 0 : return GDALDriver::ToHandle(poDriver);
3006 : }
3007 :
3008 0 : if (CPLGetLastErrorType() != CE_None)
3009 0 : return nullptr;
3010 : }
3011 : }
3012 :
3013 25459 : return nullptr;
3014 : }
3015 :
3016 : /************************************************************************/
3017 : /* GetMetadataItem() */
3018 : /************************************************************************/
3019 :
3020 11849900 : const char *GDALDriver::GetMetadataItem(const char *pszName,
3021 : const char *pszDomain)
3022 : {
3023 11849900 : if (pszDomain == nullptr || pszDomain[0] == '\0')
3024 : {
3025 11849700 : if (EQUAL(pszName, GDAL_DMD_OVERVIEW_CREATIONOPTIONLIST))
3026 : {
3027 2224 : const char *pszVal = GDALMajorObject::GetMetadataItem(pszName, "");
3028 2224 : if (pszVal)
3029 1996 : return pszVal;
3030 228 : if (GetMetadataItem(GDAL_DCAP_RASTER))
3031 : {
3032 156 : auto poDM = GetGDALDriverManager();
3033 156 : auto poGTiffDrv = poDM->GetDriverByName("GTiff");
3034 156 : if (poGTiffDrv)
3035 : {
3036 : const char *pszXML =
3037 156 : poGTiffDrv->GetMetadataItem(pszName, "");
3038 156 : if (pszXML)
3039 : {
3040 312 : CPLString osXML(pszXML);
3041 156 : osXML.replaceAll("<Value>INTERNAL</Value>", "");
3042 156 : return CPLSPrintf("%s", osXML.c_str());
3043 : }
3044 : }
3045 : }
3046 : }
3047 : }
3048 11847700 : return GDALMajorObject::GetMetadataItem(pszName, pszDomain);
3049 : }
3050 :
3051 : /************************************************************************/
3052 : /* SetMetadataItem() */
3053 : /************************************************************************/
3054 :
3055 4642270 : CPLErr GDALDriver::SetMetadataItem(const char *pszName, const char *pszValue,
3056 : const char *pszDomain)
3057 :
3058 : {
3059 4642270 : if (pszDomain == nullptr || pszDomain[0] == '\0')
3060 : {
3061 : /* Automatically sets GDAL_DMD_EXTENSIONS from GDAL_DMD_EXTENSION */
3062 4838930 : if (EQUAL(pszName, GDAL_DMD_EXTENSION) &&
3063 202081 : GDALMajorObject::GetMetadataItem(GDAL_DMD_EXTENSIONS) == nullptr)
3064 : {
3065 202081 : GDALMajorObject::SetMetadataItem(GDAL_DMD_EXTENSIONS, pszValue);
3066 : }
3067 : /* and vice-versa if there is a single extension in GDAL_DMD_EXTENSIONS */
3068 8952430 : else if (EQUAL(pszName, GDAL_DMD_EXTENSIONS) &&
3069 4443780 : strchr(pszValue, ' ') == nullptr &&
3070 9011 : GDALMajorObject::GetMetadataItem(GDAL_DMD_EXTENSION) ==
3071 : nullptr)
3072 : {
3073 9011 : GDALMajorObject::SetMetadataItem(GDAL_DMD_EXTENSION, pszValue);
3074 : }
3075 : }
3076 4642270 : return GDALMajorObject::SetMetadataItem(pszName, pszValue, pszDomain);
3077 : }
3078 :
3079 : /************************************************************************/
3080 : /* InstantiateAlgorithm() */
3081 : /************************************************************************/
3082 :
3083 : //! @cond Doxygen_Suppress
3084 :
3085 : GDALAlgorithm *
3086 1694 : GDALDriver::InstantiateAlgorithm(const std::vector<std::string> &aosPath)
3087 : {
3088 1694 : pfnInstantiateAlgorithm = GetInstantiateAlgorithmCallback();
3089 1694 : if (pfnInstantiateAlgorithm)
3090 1694 : return pfnInstantiateAlgorithm(aosPath);
3091 0 : return nullptr;
3092 : }
3093 :
3094 : /************************************************************************/
3095 : /* DeclareAlgorithm() */
3096 : /************************************************************************/
3097 :
3098 19923 : void GDALDriver::DeclareAlgorithm(const std::vector<std::string> &aosPath)
3099 : {
3100 39846 : const std::string osDriverName = GetDescription();
3101 19923 : auto &singleton = GDALGlobalAlgorithmRegistry::GetSingleton();
3102 :
3103 39846 : if (!singleton.HasDeclaredSubAlgorithm({"driver"}))
3104 : {
3105 3200 : singleton.DeclareAlgorithm(
3106 : {"driver"},
3107 171 : []() -> std::unique_ptr<GDALAlgorithm>
3108 : {
3109 342 : return std::make_unique<GDALContainerAlgorithm>(
3110 171 : "driver", "Command for driver specific operations.");
3111 1600 : });
3112 : }
3113 :
3114 : std::vector<std::string> path = {"driver",
3115 119538 : CPLString(osDriverName).tolower()};
3116 19923 : if (!singleton.HasDeclaredSubAlgorithm(path))
3117 : {
3118 2024 : auto lambda = [osDriverName]() -> std::unique_ptr<GDALAlgorithm>
3119 : {
3120 : auto poDriver =
3121 2024 : GetGDALDriverManager()->GetDriverByName(osDriverName.c_str());
3122 2024 : if (poDriver)
3123 : {
3124 : const char *pszHelpTopic =
3125 2024 : poDriver->GetMetadataItem(GDAL_DMD_HELPTOPIC);
3126 4048 : return std::make_unique<GDALContainerAlgorithm>(
3127 4048 : CPLString(osDriverName).tolower(),
3128 4048 : std::string("Command for ")
3129 2024 : .append(osDriverName)
3130 : .append(" driver specific operations."),
3131 4048 : pszHelpTopic ? std::string("/").append(pszHelpTopic)
3132 2024 : : std::string());
3133 : }
3134 0 : return nullptr;
3135 14400 : };
3136 14400 : singleton.DeclareAlgorithm(path, std::move(lambda));
3137 : }
3138 :
3139 19923 : path.insert(path.end(), aosPath.begin(), aosPath.end());
3140 :
3141 1694 : auto lambda = [osDriverName, aosPath]() -> std::unique_ptr<GDALAlgorithm>
3142 : {
3143 : auto poDriver =
3144 1694 : GetGDALDriverManager()->GetDriverByName(osDriverName.c_str());
3145 1694 : if (poDriver)
3146 : return std::unique_ptr<GDALAlgorithm>(
3147 1694 : poDriver->InstantiateAlgorithm(aosPath));
3148 0 : return nullptr;
3149 39846 : };
3150 :
3151 19923 : singleton.DeclareAlgorithm(path, std::move(lambda));
3152 :
3153 19923 : CPL_IGNORE_RET_VAL(osDriverName);
3154 19923 : }
3155 :
3156 : //! @endcond
3157 :
3158 : /************************************************************************/
3159 : /* DoesDriverHandleExtension() */
3160 : /************************************************************************/
3161 :
3162 207800 : static bool DoesDriverHandleExtension(GDALDriverH hDriver, const char *pszExt)
3163 : {
3164 207800 : bool bRet = false;
3165 : const char *pszDriverExtensions =
3166 207800 : GDALGetMetadataItem(hDriver, GDAL_DMD_EXTENSIONS, nullptr);
3167 207800 : if (pszDriverExtensions)
3168 : {
3169 347962 : const CPLStringList aosTokens(CSLTokenizeString(pszDriverExtensions));
3170 173981 : const int nTokens = aosTokens.size();
3171 393103 : for (int j = 0; j < nTokens; ++j)
3172 : {
3173 224011 : if (EQUAL(pszExt, aosTokens[j]))
3174 : {
3175 4889 : bRet = true;
3176 4889 : break;
3177 : }
3178 : }
3179 : }
3180 207800 : return bRet;
3181 : }
3182 :
3183 : /************************************************************************/
3184 : /* IsOnlyExpectedGDBDrivers() */
3185 : /************************************************************************/
3186 :
3187 1 : static bool IsOnlyExpectedGDBDrivers(const CPLStringList &aosDriverNames)
3188 : {
3189 3 : for (const char *pszDrvName : aosDriverNames)
3190 : {
3191 2 : if (!EQUAL(pszDrvName, "OpenFileGDB") &&
3192 1 : !EQUAL(pszDrvName, "FileGDB") && !EQUAL(pszDrvName, "GPSBabel"))
3193 : {
3194 0 : return false;
3195 : }
3196 : }
3197 1 : return true;
3198 : }
3199 :
3200 : /************************************************************************/
3201 : /* GDALGetOutputDriversForDatasetName() */
3202 : /************************************************************************/
3203 :
3204 : /** Return a list of driver short names that are likely candidates for the
3205 : * provided output file name.
3206 : *
3207 : * @param pszDestDataset Output dataset name (might not exist).
3208 : * @param nDatasetTypeFlag GDAL_OF_RASTER, GDAL_OF_VECTOR, GDAL_OF_MULTIDIM_RASTER
3209 : * or a binary-or'ed combination of them
3210 : * @param bSingleMatch Whether a single match is desired, that is to say the
3211 : * returned list will contain at most one item, which will
3212 : * be the first driver in the order they are registered to
3213 : * match the output dataset name. Note that in this mode, if
3214 : * nDatasetTypeFlag==GDAL_OF_RASTER and pszDestDataset has
3215 : * no extension, GTiff will be selected.
3216 : * @param bEmitWarning Whether a warning should be emitted when bSingleMatch is
3217 : * true and there are more than 2 candidates.
3218 : * @return NULL terminated list of driver short names.
3219 : * To be freed with CSLDestroy()
3220 : * @since 3.9
3221 : */
3222 2904 : char **GDALGetOutputDriversForDatasetName(const char *pszDestDataset,
3223 : int nDatasetTypeFlag,
3224 : bool bSingleMatch, bool bEmitWarning)
3225 : {
3226 5808 : CPLStringList aosDriverNames;
3227 5808 : CPLStringList aosMissingDriverNames;
3228 :
3229 5808 : std::string osExt = CPLGetExtensionSafe(pszDestDataset);
3230 2904 : if (EQUAL(osExt.c_str(), "zip"))
3231 : {
3232 4 : const CPLString osLower(CPLString(pszDestDataset).tolower());
3233 2 : if (osLower.endsWith(".shp.zip"))
3234 : {
3235 2 : osExt = "shp.zip";
3236 : }
3237 0 : else if (osLower.endsWith(".gpkg.zip"))
3238 : {
3239 0 : osExt = "gpkg.zip";
3240 : }
3241 : }
3242 2902 : else if (EQUAL(osExt.c_str(), "json"))
3243 : {
3244 1 : const CPLString osLower(CPLString(pszDestDataset).tolower());
3245 1 : if (osLower.endsWith(".gdalg.json"))
3246 0 : return nullptr;
3247 : }
3248 :
3249 2904 : auto poDM = GetGDALDriverManager();
3250 2904 : const int nDriverCount = poDM->GetDriverCount(true);
3251 2904 : GDALDriver *poMissingPluginDriver = nullptr;
3252 5808 : std::string osMatchingPrefix;
3253 673319 : for (int i = 0; i < nDriverCount; i++)
3254 : {
3255 670415 : GDALDriver *poDriver = poDM->GetDriver(i, true);
3256 670415 : bool bOk = false;
3257 670415 : if ((poDriver->GetMetadataItem(GDAL_DCAP_CREATE) != nullptr ||
3258 414866 : poDriver->GetMetadataItem(GDAL_DCAP_CREATECOPY) != nullptr ||
3259 1340830 : poDriver->GetMetadataItem(GDAL_DCAP_UPDATE) != nullptr) &&
3260 342669 : (((nDatasetTypeFlag & GDAL_OF_RASTER) &&
3261 268685 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER) != nullptr) ||
3262 167341 : ((nDatasetTypeFlag & GDAL_OF_VECTOR) &&
3263 73394 : poDriver->GetMetadataItem(GDAL_DCAP_VECTOR) != nullptr) ||
3264 132511 : ((nDatasetTypeFlag & GDAL_OF_MULTIDIM_RASTER) &&
3265 590 : poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER) != nullptr)))
3266 : {
3267 210208 : bOk = true;
3268 : }
3269 462494 : else if (poDriver->GetMetadataItem(GDAL_DCAP_VECTOR_TRANSLATE_FROM) &&
3270 2287 : (nDatasetTypeFlag & GDAL_OF_VECTOR) != 0)
3271 : {
3272 0 : bOk = true;
3273 : }
3274 670415 : if (bOk)
3275 : {
3276 418008 : if (!osExt.empty() &&
3277 207800 : DoesDriverHandleExtension(GDALDriver::ToHandle(poDriver),
3278 : osExt.c_str()))
3279 : {
3280 4889 : if (poDriver->GetMetadataItem("MISSING_PLUGIN_FILENAME"))
3281 : {
3282 0 : poMissingPluginDriver = poDriver;
3283 0 : aosMissingDriverNames.AddString(poDriver->GetDescription());
3284 : }
3285 : else
3286 4889 : aosDriverNames.AddString(poDriver->GetDescription());
3287 : }
3288 : else
3289 : {
3290 : const char *pszPrefix =
3291 205319 : poDriver->GetMetadataItem(GDAL_DMD_CONNECTION_PREFIX);
3292 205319 : if (pszPrefix && STARTS_WITH_CI(pszDestDataset, pszPrefix))
3293 : {
3294 9 : if (poDriver->GetMetadataItem("MISSING_PLUGIN_FILENAME"))
3295 : {
3296 0 : osMatchingPrefix = pszPrefix;
3297 0 : poMissingPluginDriver = poDriver;
3298 : aosMissingDriverNames.AddString(
3299 0 : poDriver->GetDescription());
3300 : }
3301 : else
3302 9 : aosDriverNames.AddString(poDriver->GetDescription());
3303 : }
3304 : }
3305 : }
3306 : }
3307 :
3308 : // GMT is registered before netCDF for opening reasons, but we want
3309 : // netCDF to be used by default for output.
3310 2917 : if (EQUAL(osExt.c_str(), "nc") && aosDriverNames.size() == 2 &&
3311 2917 : EQUAL(aosDriverNames[0], "GMT") && EQUAL(aosDriverNames[1], "netCDF"))
3312 : {
3313 0 : aosDriverNames.Clear();
3314 0 : aosDriverNames.AddString("netCDF");
3315 0 : aosDriverNames.AddString("GMT");
3316 : }
3317 :
3318 2904 : if (bSingleMatch)
3319 : {
3320 2832 : if (nDatasetTypeFlag == GDAL_OF_RASTER)
3321 : {
3322 2277 : if (aosDriverNames.empty())
3323 : {
3324 13 : if (osExt.empty())
3325 : {
3326 8 : aosDriverNames.AddString("GTiff");
3327 : }
3328 : }
3329 2264 : else if (aosDriverNames.size() >= 2)
3330 : {
3331 4063 : if (bEmitWarning && !(EQUAL(aosDriverNames[0], "GTiff") &&
3332 2030 : EQUAL(aosDriverNames[1], "COG")))
3333 : {
3334 3 : CPLError(CE_Warning, CPLE_AppDefined,
3335 : "Several drivers matching %s extension. Using %s",
3336 : osExt.c_str(), aosDriverNames[0]);
3337 : }
3338 4066 : const std::string osDrvName = aosDriverNames[0];
3339 2033 : aosDriverNames.Clear();
3340 2033 : aosDriverNames.AddString(osDrvName.c_str());
3341 : }
3342 : }
3343 556 : else if (EQUAL(osExt.c_str(), "gdb") &&
3344 1 : IsOnlyExpectedGDBDrivers(aosDriverNames))
3345 : {
3346 : // Do not warn about that case given that FileGDB write support
3347 : // forwards to OpenFileGDB one. And also consider GPSBabel as too
3348 : // marginal to deserve the warning.
3349 1 : aosDriverNames.Clear();
3350 1 : aosDriverNames.AddString("OpenFileGDB");
3351 : }
3352 554 : else if (aosDriverNames.size() >= 2)
3353 : {
3354 0 : if (bEmitWarning)
3355 : {
3356 0 : CPLError(CE_Warning, CPLE_AppDefined,
3357 : "Several drivers matching %s %s. Using %s",
3358 0 : osMatchingPrefix.empty() ? osExt.c_str()
3359 0 : : osMatchingPrefix.c_str(),
3360 0 : osMatchingPrefix.empty() ? "extension" : "prefix",
3361 : aosDriverNames[0]);
3362 : }
3363 0 : const std::string osDrvName = aosDriverNames[0];
3364 0 : aosDriverNames.Clear();
3365 0 : aosDriverNames.AddString(osDrvName.c_str());
3366 : }
3367 : }
3368 :
3369 2937 : if (aosDriverNames.empty() && bEmitWarning &&
3370 2937 : aosMissingDriverNames.size() == 1 && poMissingPluginDriver)
3371 : {
3372 0 : CPLError(CE_Failure, CPLE_AppDefined,
3373 : "No installed driver matching %s %s, but %s driver is "
3374 : "known. However plugin %s",
3375 0 : osMatchingPrefix.empty() ? osExt.c_str()
3376 0 : : osMatchingPrefix.c_str(),
3377 0 : osMatchingPrefix.empty() ? "extension" : "prefix",
3378 0 : poMissingPluginDriver->GetDescription(),
3379 0 : GDALGetMessageAboutMissingPluginDriver(poMissingPluginDriver)
3380 : .c_str());
3381 : }
3382 2936 : else if (aosDriverNames.empty() && bEmitWarning &&
3383 32 : aosMissingDriverNames.empty())
3384 : {
3385 915 : for (const auto &sConnectionPrefix : asKnownConnectionPrefixes)
3386 : {
3387 884 : if (STARTS_WITH_CI(pszDestDataset, sConnectionPrefix.pszPrefix))
3388 : {
3389 1 : CPLError(CE_Failure, CPLE_AppDefined,
3390 : "Filename %s starts with the connection prefix of "
3391 : "driver %s, which is not enabled in this GDAL build. "
3392 : "If that filename is really intended, explicitly "
3393 : "specify its output format.",
3394 1 : pszDestDataset, sConnectionPrefix.pszDriverName);
3395 1 : break;
3396 : }
3397 : }
3398 : }
3399 :
3400 2904 : return aosDriverNames.StealList();
3401 : }
3402 :
3403 : /************************************************************************/
3404 : /* GDALGetMessageAboutMissingPluginDriver() */
3405 : /************************************************************************/
3406 :
3407 : std::string
3408 0 : GDALGetMessageAboutMissingPluginDriver(GDALDriver *poMissingPluginDriver)
3409 : {
3410 : std::string osMsg =
3411 0 : poMissingPluginDriver->GetMetadataItem("MISSING_PLUGIN_FILENAME");
3412 : osMsg += " is not available in your "
3413 0 : "installation.";
3414 0 : if (const char *pszInstallationMsg = poMissingPluginDriver->GetMetadataItem(
3415 0 : GDAL_DMD_PLUGIN_INSTALLATION_MESSAGE))
3416 : {
3417 0 : osMsg += " ";
3418 0 : osMsg += pszInstallationMsg;
3419 : }
3420 :
3421 : VSIStatBuf sStat;
3422 0 : if (const char *pszGDALDriverPath =
3423 0 : CPLGetConfigOption("GDAL_DRIVER_PATH", nullptr))
3424 : {
3425 0 : if (VSIStat(pszGDALDriverPath, &sStat) != 0)
3426 : {
3427 0 : if (osMsg.back() != '.')
3428 0 : osMsg += ".";
3429 0 : osMsg += " Directory '";
3430 0 : osMsg += pszGDALDriverPath;
3431 0 : osMsg += "' pointed by GDAL_DRIVER_PATH does not exist.";
3432 : }
3433 : }
3434 : else
3435 : {
3436 0 : if (osMsg.back() != '.')
3437 0 : osMsg += ".";
3438 : #ifdef INSTALL_PLUGIN_FULL_DIR
3439 : if (VSIStat(INSTALL_PLUGIN_FULL_DIR, &sStat) != 0)
3440 : {
3441 : osMsg += " Directory '";
3442 : osMsg += INSTALL_PLUGIN_FULL_DIR;
3443 : osMsg += "' hardcoded in the GDAL library does not "
3444 : "exist and the GDAL_DRIVER_PATH "
3445 : "configuration option is not set.";
3446 : }
3447 : else
3448 : #endif
3449 : {
3450 : osMsg += " The GDAL_DRIVER_PATH configuration "
3451 0 : "option is not set.";
3452 : }
3453 : }
3454 0 : return osMsg;
3455 : }
3456 :
3457 : /************************************************************************/
3458 : /* GDALClearMemoryCaches() */
3459 : /************************************************************************/
3460 :
3461 : /**
3462 : * \brief Clear all GDAL-controlled in-memory caches.
3463 : *
3464 : * Iterates registered drivers and calls their pfnClearCaches callback if set,
3465 : * then calls VSICurlClearCache() to clear /vsicurl/ and related caches.
3466 : *
3467 : * Note that neither the global raster block cache or caches specific to open
3468 : * dataset objects are not cleared by this function (in its current implementation).
3469 : *
3470 : * Useful when remote datasets may have changed during the lifetime of a
3471 : * process.
3472 : *
3473 : * @since GDAL 3.13
3474 : */
3475 1006 : void GDALClearMemoryCaches()
3476 : {
3477 1006 : auto *poDM = GetGDALDriverManager();
3478 1006 : if (poDM)
3479 : {
3480 233392 : for (int i = 0; i < poDM->GetDriverCount(); i++)
3481 : {
3482 232386 : auto *poDriver = poDM->GetDriver(i);
3483 232386 : if (poDriver && poDriver->pfnClearCaches)
3484 2012 : poDriver->pfnClearCaches(poDriver);
3485 : }
3486 : }
3487 1006 : VSICurlClearCache();
3488 1006 : }
|