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