diff --git a/alg/gdal_rpc.cpp b/alg/gdal_rpc.cpp index 27737ff345df..cbff487fc53c 100644 --- a/alg/gdal_rpc.cpp +++ b/alg/gdal_rpc.cpp @@ -1149,7 +1149,9 @@ static bool RPCInverseTransformPoint(GDALRPCTransformInfo *psTransform, if (psTransform->pszRPCInverseLog) { fpLog = VSIFOpenL( - CPLResetExtension(psTransform->pszRPCInverseLog, "csvt"), "wb"); + CPLResetExtensionSafe(psTransform->pszRPCInverseLog, "csvt") + .c_str(), + "wb"); if (fpLog != nullptr) { VSIFPrintfL(fpLog, "Integer,Real,Real,Real,String,Real,Real\n"); diff --git a/alg/gdalgeoloc.cpp b/alg/gdalgeoloc.cpp index 74ba0a74fadb..32f28648cc1f 100644 --- a/alg/gdalgeoloc.cpp +++ b/alg/gdalgeoloc.cpp @@ -1817,9 +1817,11 @@ void *GDALCreateGeoLocTransformerEx(GDALDatasetH hBaseDS, papszGeolocationInfo, "X_DATASET_RELATIVE_TO_SOURCE", "NO")) && (hBaseDS != nullptr || pszSourceDataset)) { - CPLString osFilename = CPLProjectRelativeFilename( - CPLGetDirname(pszSourceDataset ? pszSourceDataset - : GDALGetDescription(hBaseDS)), + const CPLString osFilename = CPLProjectRelativeFilenameSafe( + CPLGetDirnameSafe(pszSourceDataset + ? pszSourceDataset + : GDALGetDescription(hBaseDS)) + .c_str(), pszDSName); psTransform->hDS_X = GDALOpenShared(osFilename.c_str(), GA_ReadOnly); @@ -1849,9 +1851,11 @@ void *GDALCreateGeoLocTransformerEx(GDALDatasetH hBaseDS, papszGeolocationInfo, "Y_DATASET_RELATIVE_TO_SOURCE", "NO")) && (hBaseDS != nullptr || pszSourceDataset)) { - CPLString osFilename = CPLProjectRelativeFilename( - CPLGetDirname(pszSourceDataset ? pszSourceDataset - : GDALGetDescription(hBaseDS)), + const CPLString osFilename = CPLProjectRelativeFilenameSafe( + CPLGetDirnameSafe(pszSourceDataset + ? pszSourceDataset + : GDALGetDescription(hBaseDS)) + .c_str(), pszDSName); psTransform->hDS_Y = GDALOpenShared(osFilename.c_str(), GA_ReadOnly); diff --git a/alg/gdalgeoloc_dataset_accessor.h b/alg/gdalgeoloc_dataset_accessor.h index 56113574c766..c84e72674979 100644 --- a/alg/gdalgeoloc_dataset_accessor.h +++ b/alg/gdalgeoloc_dataset_accessor.h @@ -104,8 +104,8 @@ bool GDALGeoLocDatasetAccessors::AllocateBackMap() // CPLResetExtension / CPLGenerateTempFilename generate short-lived strings, // so store them in a long-lived std::string - const std::string osBackmapTmpFilename = - CPLResetExtension(CPLGenerateTempFilename(nullptr), "tif"); + const std::string osBackmapTmpFilename = CPLResetExtensionSafe( + CPLGenerateTempFilenameSafe(nullptr).c_str(), "tif"); m_poBackmapTmpDataset = poDriver->Create( osBackmapTmpFilename.c_str(), m_psTransform->nBackMapWidth, m_psTransform->nBackMapHeight, 2, GDT_Float32, @@ -124,8 +124,8 @@ bool GDALGeoLocDatasetAccessors::AllocateBackMap() // CPLResetExtension / CPLGenerateTempFilename generate short-lived strings, // so store them in a long-lived std::string - const std::string osBackmapWeightsTmpFilename = - CPLResetExtension(CPLGenerateTempFilename(nullptr), "tif"); + const std::string osBackmapWeightsTmpFilename = CPLResetExtensionSafe( + CPLGenerateTempFilenameSafe(nullptr).c_str(), "tif"); m_poBackmapWeightsTmpDataset = poDriver->Create( osBackmapWeightsTmpFilename.c_str(), m_psTransform->nBackMapWidth, m_psTransform->nBackMapHeight, 1, GDT_Float32, @@ -209,8 +209,8 @@ bool GDALGeoLocDatasetAccessors::LoadGeoloc(bool bIsRegularGrid) // CPLResetExtension / CPLGenerateTempFilename generate short-lived // strings, so store them in a long-lived std::string - const std::string osGeolocTmpFilename = - CPLResetExtension(CPLGenerateTempFilename(nullptr), "tif"); + const std::string osGeolocTmpFilename = CPLResetExtensionSafe( + CPLGenerateTempFilenameSafe(nullptr).c_str(), "tif"); m_poGeolocTmpDataset = poDriver->Create(osGeolocTmpFilename.c_str(), nXSize, nYSize, 2, GDT_Float64, m_aosGTiffCreationOptions.List()); diff --git a/alg/gdalproximity.cpp b/alg/gdalproximity.cpp index aaa9bda10ef8..34bf2387d2c1 100644 --- a/alg/gdalproximity.cpp +++ b/alg/gdalproximity.cpp @@ -263,7 +263,7 @@ CPLErr CPL_STDCALL GDALComputeProximity(GDALRasterBandH hSrcBand, eErr = CE_Failure; goto end; } - CPLString osTmpFile = CPLGenerateTempFilename("proximity"); + CPLString osTmpFile = CPLGenerateTempFilenameSafe("proximity"); hWorkProximityDS = GDALCreate(hDriver, osTmpFile, nXSize, nYSize, 1, GDT_Float32, nullptr); if (hWorkProximityDS == nullptr) diff --git a/alg/rasterfill.cpp b/alg/rasterfill.cpp index 3be8db9d3f8d..3ff51c4ab75f 100644 --- a/alg/rasterfill.cpp +++ b/alg/rasterfill.cpp @@ -462,7 +462,7 @@ CPLErr CPL_STDCALL GDALFillNodata(GDALRasterBandH hTargetBand, aosWorkFileOptions.SetNameValue("BIGTIFF", "IF_SAFER"); } - const CPLString osTmpFile = CPLGenerateTempFilename(""); + const CPLString osTmpFile = CPLGenerateTempFilenameSafe(""); std::unique_ptr poTmpMaskDS; if (hMaskBand == nullptr) diff --git a/apps/dumpoverviews.cpp b/apps/dumpoverviews.cpp index 76f81c20a521..71194aa13ccb 100644 --- a/apps/dumpoverviews.cpp +++ b/apps/dumpoverviews.cpp @@ -134,7 +134,8 @@ int main(int argc, char **argv) /* -------------------------------------------------------------------- */ CPLString osFilename; - osFilename.Printf("%s_%d_%d.tif", CPLGetBasename(pszSrcFilename), + osFilename.Printf("%s_%d_%d.tif", + CPLGetBasenameSafe(pszSrcFilename).c_str(), iBand + 1, iOverview); if (!DumpBand(hSrcDS, hSrcOver, osFilename)) bRet = false; @@ -142,9 +143,10 @@ int main(int argc, char **argv) if (bMasks) { CPLString osMaskFilename; - osMaskFilename.Printf("%s_%d_%d_mask.tif", - CPLGetBasename(pszSrcFilename), iBand + 1, - iOverview); + osMaskFilename.Printf( + "%s_%d_%d_mask.tif", + CPLGetBasenameSafe(pszSrcFilename).c_str(), iBand + 1, + iOverview); if (!DumpBand(hSrcDS, GDALGetMaskBand(hSrcOver), osMaskFilename)) bRet = false; @@ -159,7 +161,8 @@ int main(int argc, char **argv) if (bMasks) { CPLString osFilename; - osFilename.Printf("%s_%d_mask.tif", CPLGetBasename(pszSrcFilename), + osFilename.Printf("%s_%d_mask.tif", + CPLGetBasenameSafe(pszSrcFilename).c_str(), iBand + 1); if (!DumpBand(hSrcDS, GDALGetMaskBand(hBaseBand), osFilename)) bRet = false; diff --git a/apps/gdal_contour.cpp b/apps/gdal_contour.cpp index 406284777525..76a73539b4c6 100644 --- a/apps/gdal_contour.cpp +++ b/apps/gdal_contour.cpp @@ -388,7 +388,8 @@ MAIN_START(argc, argv) { CPLError(CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", - CPLGetExtension(sOptions.aosDestFilename.c_str()), + CPLGetExtensionSafe(sOptions.aosDestFilename.c_str()) + .c_str(), aoDrivers[0].c_str()); } osFormat = aoDrivers[0]; diff --git a/apps/gdal_footprint_lib.cpp b/apps/gdal_footprint_lib.cpp index a647517bf3a7..30ebaa79b300 100644 --- a/apps/gdal_footprint_lib.cpp +++ b/apps/gdal_footprint_lib.cpp @@ -568,7 +568,8 @@ GetOutputLayerAndUpdateDstDS(const char *pszDest, GDALDatasetH &hDstDS, { CPLError(CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", - CPLGetExtension(pszDest), aoDrivers[0].c_str()); + CPLGetExtensionSafe(pszDest).c_str(), + aoDrivers[0].c_str()); } osFormat = aoDrivers[0]; } @@ -633,7 +634,7 @@ GetOutputLayerAndUpdateDstDS(const char *pszDest, GDALDatasetH &hDstDS, if (poDstDS->GetDriver() && EQUAL(poDstDS->GetDriver()->GetDescription(), "ESRI Shapefile")) { - osDestLayerName = CPLGetBasename(pszDest); + osDestLayerName = CPLGetBasenameSafe(pszDest); } else { @@ -1187,8 +1188,8 @@ static bool GDALFootprintProcess(GDALDataset *poSrcDS, OGRLayer *poDstLayer, char *pszCurDir = CPLGetCurrentDir(); if (pszCurDir) { - osFilename = CPLProjectRelativeFilename(pszCurDir, - osFilename.c_str()); + osFilename = CPLProjectRelativeFilenameSafe( + pszCurDir, osFilename.c_str()); CPLFree(pszCurDir); } } diff --git a/apps/gdal_translate_bin.cpp b/apps/gdal_translate_bin.cpp index e51e108b1e48..eeedde984501 100644 --- a/apps/gdal_translate_bin.cpp +++ b/apps/gdal_translate_bin.cpp @@ -198,11 +198,12 @@ MAIN_START(argc, argv) char *pszSubDest = static_cast( CPLMalloc(strlen(sOptionsForBinary.osDest.c_str()) + 32)); - CPLString osPath = CPLGetPath(sOptionsForBinary.osDest.c_str()); - CPLString osBasename = - CPLGetBasename(sOptionsForBinary.osDest.c_str()); - CPLString osExtension = - CPLGetExtension(sOptionsForBinary.osDest.c_str()); + const CPLString osPath = + CPLGetPathSafe(sOptionsForBinary.osDest.c_str()); + const CPLString osBasename = + CPLGetBasenameSafe(sOptionsForBinary.osDest.c_str()); + const CPLString osExtension = + CPLGetExtensionSafe(sOptionsForBinary.osDest.c_str()); CPLString osTemp; const char *pszFormat = nullptr; @@ -226,7 +227,7 @@ MAIN_START(argc, argv) char *pszSource = CPLStrdup(strstr(papszSubdatasets[i], "=") + 1); osTemp = CPLSPrintf(pszFormat, osBasename.c_str(), i / 2 + 1); - osTemp = CPLFormFilename(osPath, osTemp, osExtension); + osTemp = CPLFormFilenameSafe(osPath, osTemp, osExtension); strcpy(pszSubDest, osTemp.c_str()); hDataset = GDALOpenEx(pszSource, GDAL_OF_RASTER, nullptr, sOptionsForBinary.aosOpenOptions.List(), diff --git a/apps/gdalbuildvrt_bin.cpp b/apps/gdalbuildvrt_bin.cpp index d517fbe943cc..a91b2c9643d4 100644 --- a/apps/gdalbuildvrt_bin.cpp +++ b/apps/gdalbuildvrt_bin.cpp @@ -78,9 +78,10 @@ MAIN_START(argc, argv) if (hDriver && !(EQUAL(GDALGetDriverShortName(hDriver), "VRT") || (EQUAL(GDALGetDriverShortName(hDriver), "API_PROXY") && - EQUAL( - CPLGetExtension(sOptionsForBinary.osDstFilename.c_str()), - "VRT")))) + EQUAL(CPLGetExtensionSafe( + sOptionsForBinary.osDstFilename.c_str()) + .c_str(), + "VRT")))) { fprintf( stderr, diff --git a/apps/gdalbuildvrt_lib.cpp b/apps/gdalbuildvrt_lib.cpp index 309da017eb6e..febb54b74096 100644 --- a/apps/gdalbuildvrt_lib.cpp +++ b/apps/gdalbuildvrt_lib.cpp @@ -1684,7 +1684,7 @@ static bool add_file_to_list(const char *filename, const char *tile_index, CPLStringList &aosList) { - if (EQUAL(CPLGetExtension(filename), "SHP")) + if (EQUAL(CPLGetExtensionSafe(filename).c_str(), "SHP")) { /* Handle gdaltindex Shapefile as a special case */ auto poDS = std::unique_ptr(GDALDataset::Open(filename)); diff --git a/apps/gdaldem_lib.cpp b/apps/gdaldem_lib.cpp index 7136f84b58af..6fec3cb4e356 100644 --- a/apps/gdaldem_lib.cpp +++ b/apps/gdaldem_lib.cpp @@ -2321,7 +2321,7 @@ static CPLErr GDALGenerateVRTColorRelief(const char *pszDstFilename, GDALGetBlockSize(hSrcBand, &nBlockXSize, &nBlockYSize); int bRelativeToVRT = FALSE; - CPLString osPath = CPLGetPath(pszDstFilename); + const CPLString osPath = CPLGetPathSafe(pszDstFilename); char *pszSourceFilename = CPLStrdup(CPLExtractRelativePath( osPath.c_str(), GDALGetDescription(hSrcDataset), &bRelativeToVRT)); diff --git a/apps/gdalmanage.cpp b/apps/gdalmanage.cpp index 80710813bc09..29a94f3dfc21 100644 --- a/apps/gdalmanage.cpp +++ b/apps/gdalmanage.cpp @@ -66,8 +66,8 @@ static void ProcessIdentifyTarget(const char *pszTarget, if (EQUAL(papszSiblingList[i], "..") || EQUAL(papszSiblingList[i], ".")) continue; - CPLString osSubTarget = - CPLFormFilename(pszTarget, papszSiblingList[i], nullptr); + const CPLString osSubTarget = + CPLFormFilenameSafe(pszTarget, papszSiblingList[i], nullptr); ProcessIdentifyTarget(osSubTarget, papszSiblingList, bRecursive, bReportFailures, bForceRecurse); diff --git a/apps/gdalmdimtranslate_lib.cpp b/apps/gdalmdimtranslate_lib.cpp index 02d189c277eb..0162c7973b07 100644 --- a/apps/gdalmdimtranslate_lib.cpp +++ b/apps/gdalmdimtranslate_lib.cpp @@ -1794,7 +1794,7 @@ GDALMultiDimTranslate(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount, { if (osFormat.empty()) { - if (EQUAL(CPLGetExtension(pszDest), "nc")) + if (EQUAL(CPLGetExtensionSafe(pszDest).c_str(), "nc")) osFormat = "netCDF"; else osFormat = GetOutputDriverForRaster(pszDest); diff --git a/apps/gdaltindex_lib.cpp b/apps/gdaltindex_lib.cpp index b49445bb3b5f..f07a4d17b52f 100644 --- a/apps/gdaltindex_lib.cpp +++ b/apps/gdaltindex_lib.cpp @@ -458,8 +458,8 @@ struct GDALTileIndexTileIterator continue; } - const std::string osFilename = - CPLFormFilename(osCurDir.c_str(), psEntry->pszName, nullptr); + const std::string osFilename = CPLFormFilenameSafe( + osCurDir.c_str(), psEntry->pszName, nullptr); if (VSI_ISDIR(psEntry->nMode)) { auto poSrcDS = std::unique_ptr( @@ -607,7 +607,8 @@ GDALDatasetH GDALTileIndex(const char *pszDest, int nSrcCount, { CPLError(CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", - CPLGetExtension(pszDest), aoDrivers[0].c_str()); + CPLGetExtensionSafe(pszDest).c_str(), + aoDrivers[0].c_str()); } osFormat = aoDrivers[0]; } @@ -647,7 +648,7 @@ GDALDatasetH GDALTileIndex(const char *pszDest, int nSrcCount, if (EQUAL(osFormat.c_str(), "ESRI Shapefile") || VSIStat(pszDest, &sStat) == 0) { - osLayerName = CPLGetBasename(pszDest); + osLayerName = CPLGetBasenameSafe(pszDest); } else { @@ -999,7 +1000,7 @@ GDALDatasetH GDALTileIndex(const char *pszDest, int nSrcCount, CPLIsFilenameRelative(osSrcFilename.c_str()) && VSIStat(osSrcFilename.c_str(), &sStatBuf) == 0) { - osFileNameToWrite = CPLProjectRelativeFilename( + osFileNameToWrite = CPLProjectRelativeFilenameSafe( osCurrentPath.c_str(), osSrcFilename.c_str()); } else diff --git a/apps/gdaltorture.cpp b/apps/gdaltorture.cpp index fa7fbb6aee2e..38738174e073 100644 --- a/apps/gdaltorture.cpp +++ b/apps/gdaltorture.cpp @@ -204,7 +204,7 @@ static void ProcessTortureTarget(const char *pszTarget, char **papszSiblingList, continue; const CPLString osSubTarget = - CPLFormFilename(pszTarget, papszSiblingList[i], nullptr); + CPLFormFilenameSafe(pszTarget, papszSiblingList[i], nullptr); ProcessTortureTarget(osSubTarget, papszSiblingList, bRecursive, bReportFailures, bReadWriteOperations); diff --git a/apps/gdalwarp_lib.cpp b/apps/gdalwarp_lib.cpp index 802281bc8e67..e0dd6c9b7e19 100644 --- a/apps/gdalwarp_lib.cpp +++ b/apps/gdalwarp_lib.cpp @@ -1476,7 +1476,7 @@ static bool CheckOptions(const char *pszDest, GDALDatasetH hDstDS, } if ((psOptions->osFormat.empty() && - EQUAL(CPLGetExtension(pszDest), "VRT")) || + EQUAL(CPLGetExtensionSafe(pszDest).c_str(), "VRT")) || (EQUAL(psOptions->osFormat.c_str(), "VRT"))) { if (hDstDS != nullptr) diff --git a/apps/gnmmanage.cpp b/apps/gnmmanage.cpp index ef21df7f9c01..bbfabe36f283 100644 --- a/apps/gnmmanage.cpp +++ b/apps/gnmmanage.cpp @@ -507,25 +507,27 @@ MAIN_START(nArgc, papszArgv) } else if (stOper == op_create) { - const char *pszPath; - const char *pszNetworkName = CSLFetchNameValue(papszDSCO, GNM_MD_NAME); + std::string osPath; + std::string osNetworkName = + CSLFetchNameValueDef(papszDSCO, GNM_MD_NAME, ""); if (pszDataSource == nullptr) Usage(true, "No network dataset provided"); // the DSCO have priority on input keys - if (nullptr == pszNetworkName) + if (osNetworkName.empty()) { - pszPath = CPLGetPath(pszDataSource); - pszNetworkName = CPLGetBasename(pszDataSource); - papszDSCO = CSLAddNameValue(papszDSCO, GNM_MD_NAME, pszNetworkName); + osPath = CPLGetPathSafe(pszDataSource); + osNetworkName = CPLGetBasenameSafe(pszDataSource); + papszDSCO = + CSLAddNameValue(papszDSCO, GNM_MD_NAME, osNetworkName.c_str()); } else { - pszPath = pszDataSource; + osPath = pszDataSource; } - if (pszNetworkName == nullptr) + if (osNetworkName.empty()) Usage(true, "No dataset name provided"); const char *pszFinalSRS = CSLFetchNameValue(papszDSCO, GNM_MD_SRS); @@ -553,8 +555,8 @@ MAIN_START(nArgc, papszArgv) if (!CPLFetchBool(papszMD, GDAL_DCAP_GNM, false)) Usage(true, "not a GNM driver"); - poDS = cpl::down_cast( - poDriver->Create(pszPath, 0, 0, 0, GDT_Unknown, papszDSCO)); + poDS = cpl::down_cast(poDriver->Create( + osPath.c_str(), 0, 0, 0, GDT_Unknown, papszDSCO)); if (nullptr == poDS) { @@ -562,7 +564,9 @@ MAIN_START(nArgc, papszArgv) stderr, "\nFAILURE: Failed to create network in a new dataset at " "%s and with driver %s\n", - CPLFormFilename(pszPath, pszNetworkName, nullptr), + CPLFormFilenameSafe(osPath.c_str(), osNetworkName.c_str(), + nullptr) + .c_str(), pszFormat); nRet = 1; } @@ -571,7 +575,9 @@ MAIN_START(nArgc, papszArgv) if (bQuiet == FALSE) printf("\nNetwork created successfully in a " "new dataset at %s\n", - CPLFormFilename(pszPath, pszNetworkName, nullptr)); + CPLFormFilenameSafe(osPath.c_str(), + osNetworkName.c_str(), nullptr) + .c_str()); } } } diff --git a/apps/nearblack_lib_floodfill.cpp b/apps/nearblack_lib_floodfill.cpp index 541a3ddd7b4e..75d492f92111 100644 --- a/apps/nearblack_lib_floodfill.cpp +++ b/apps/nearblack_lib_floodfill.cpp @@ -509,7 +509,8 @@ bool GDALNearblackFloodFillAlg::Process() } else { - osVisitedDataset = CPLGenerateTempFilename(osVisitedDataset.c_str()); + osVisitedDataset = + CPLGenerateTempFilenameSafe(osVisitedDataset.c_str()); } CPLStringList aosOptions; if (strcmp(pszTmpDriver, "GTiff") == 0) diff --git a/apps/ogr2ogr_lib.cpp b/apps/ogr2ogr_lib.cpp index 8937c3976421..f72c19593fbf 100644 --- a/apps/ogr2ogr_lib.cpp +++ b/apps/ogr2ogr_lib.cpp @@ -2219,7 +2219,7 @@ GDALVectorTranslateCreateCopy(GDALDriver *poDriver, const char *pszDest, EQUAL(GDALGetDescription(hIdentifyingDriver), "GML")) { VSIUnlink(pszDest); - VSIUnlink(CPLResetExtension(pszDest, "gfs")); + VSIUnlink(CPLResetExtensionSafe(pszDest, "gfs").c_str()); } } @@ -2737,7 +2737,7 @@ GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS, { if (aoDrivers.empty()) { - if (EQUAL(CPLGetExtension(pszDest), "")) + if (CPLGetExtensionSafe(pszDest).empty()) { psOptions->osFormat = "ESRI Shapefile"; } @@ -2754,7 +2754,8 @@ GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS, { CPLError(CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", - CPLGetExtension(pszDest), aoDrivers[0].c_str()); + CPLGetExtensionSafe(pszDest).c_str(), + aoDrivers[0].c_str()); } psOptions->osFormat = aoDrivers[0]; } @@ -2840,7 +2841,7 @@ GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS, (psOptions->aosLayers.size() > 1 || (psOptions->aosLayers.empty() && poDS->GetLayerCount() > 1)) && psOptions->osNewLayerName.empty() && - EQUAL(CPLGetExtension(osDestFilename), "SHP") && + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "SHP") && VSIStatL(osDestFilename, &sStat) != 0) { if (VSIMkdir(osDestFilename, 0755) != 0) @@ -3198,11 +3199,11 @@ GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS, psOptions->osNewLayerName.empty() && VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode) && - (EQUAL(CPLGetExtension(osDestFilename), "shp") || - EQUAL(CPLGetExtension(osDestFilename), "shz") || - EQUAL(CPLGetExtension(osDestFilename), "dbf"))) + (EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shp") || + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shz") || + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "dbf"))) { - psOptions->osNewLayerName = CPLGetBasename(osDestFilename); + psOptions->osNewLayerName = CPLGetBasenameSafe(osDestFilename); } auto psInfo = oSetup.Setup(poPassedLayer, @@ -3278,11 +3279,11 @@ GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS, (psOptions->aosLayers.size() == 1 || nSrcLayerCount == 1) && psOptions->osNewLayerName.empty() && VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode) && - (EQUAL(CPLGetExtension(osDestFilename), "shp") || - EQUAL(CPLGetExtension(osDestFilename), "shz") || - EQUAL(CPLGetExtension(osDestFilename), "dbf"))) + (EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shp") || + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shz") || + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "dbf"))) { - psOptions->osNewLayerName = CPLGetBasename(osDestFilename); + psOptions->osNewLayerName = CPLGetBasenameSafe(osDestFilename); } GDALProgressFunc pfnProgress = nullptr; @@ -3557,11 +3558,11 @@ GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS, if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") && nLayerCount == 1 && psOptions->osNewLayerName.empty() && VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode) && - (EQUAL(CPLGetExtension(osDestFilename), "shp") || - EQUAL(CPLGetExtension(osDestFilename), "shz") || - EQUAL(CPLGetExtension(osDestFilename), "dbf"))) + (EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shp") || + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shz") || + EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "dbf"))) { - psOptions->osNewLayerName = CPLGetBasename(osDestFilename); + psOptions->osNewLayerName = CPLGetBasenameSafe(osDestFilename); } std::vector anLayerCountFeatures; diff --git a/apps/ogrlineref.cpp b/apps/ogrlineref.cpp index 91a1274ab477..facf87c08b89 100644 --- a/apps/ogrlineref.cpp +++ b/apps/ogrlineref.cpp @@ -66,8 +66,9 @@ static OGRLayer *SetupTargetLayer(OGRLayer *poSrcLayer, GDALDataset *poDstDS, const char *pszOutputSepFieldName = nullptr) { const CPLString szLayerName = - pszNewLayerName == nullptr ? CPLGetBasename(poDstDS->GetDescription()) - : pszNewLayerName; + pszNewLayerName == nullptr + ? CPLGetBasenameSafe(poDstDS->GetDescription()) + : pszNewLayerName; /* -------------------------------------------------------------------- */ /* Get other info. */ @@ -218,7 +219,8 @@ static OGRLayer *SetupTargetLayer(OGRLayer *poSrcLayer, GDALDataset *poDstDS, static void CheckDestDataSourceNameConsistency(const char *pszDestFilename, const char *pszDriverName) { - char *pszDestExtension = CPLStrdup(CPLGetExtension(pszDestFilename)); + char *pszDestExtension = + CPLStrdup(CPLGetExtensionSafe(pszDestFilename).c_str()); // TODO: Would be good to have driver metadata like for GDAL drivers. static const char *apszExtensions[][2] = {{"shp", "ESRI Shapefile"}, diff --git a/apps/ogrtindex.cpp b/apps/ogrtindex.cpp index 960fef541a68..1bc71417532e 100644 --- a/apps/ogrtindex.cpp +++ b/apps/ogrtindex.cpp @@ -264,7 +264,7 @@ MAIN_START(nArgc, papszArgv) { CPLError(CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", - CPLGetExtension(osOutputName.c_str()), + CPLGetExtensionSafe(osOutputName.c_str()).c_str(), aoDrivers[0].c_str()); } osFormat = aoDrivers[0]; @@ -493,8 +493,9 @@ MAIN_START(nArgc, papszArgv) if (bWriteAbsolutePath && CPLIsFilenameRelative(srcDataSet.c_str()) && VSIStat(srcDataSet.c_str(), &sStatBuf) == 0) { - fileNameToWrite = CPLStrdup( - CPLProjectRelativeFilename(pszCurrentPath, srcDataSet.c_str())); + fileNameToWrite = CPLStrdup(CPLProjectRelativeFilenameSafe( + pszCurrentPath, srcDataSet.c_str()) + .c_str()); } else { diff --git a/apps/sozip.cpp b/apps/sozip.cpp index 79bf539972bd..aad2b2d7d02b 100644 --- a/apps/sozip.cpp +++ b/apps/sozip.cpp @@ -455,7 +455,7 @@ MAIN_START(nArgc, papszArgv) } const char *pszZipFilename = osZipFilename.c_str(); - if (!EQUAL(CPLGetExtension(pszZipFilename), "zip")) + if (!EQUAL(CPLGetExtensionSafe(pszZipFilename).c_str(), "zip")) { std::cerr << _("Extension of zip filename should be .zip") << std::endl << std::endl; diff --git a/apps/test_ogrsf.cpp b/apps/test_ogrsf.cpp index adbb5b717d52..777964088bfd 100644 --- a/apps/test_ogrsf.cpp +++ b/apps/test_ogrsf.cpp @@ -611,8 +611,8 @@ static int TestCreateLayer(GDALDriver *poDriver, OGRwkbGeometryType eGeomType) const char *pszExt = poDriver->GetMetadataItem(GDAL_DMD_EXTENSION); static int nCounter = 0; - CPLString osFilename = - CPLFormFilename("/vsimem", CPLSPrintf("test%d", ++nCounter), pszExt); + CPLString osFilename = CPLFormFilenameSafe( + "/vsimem", CPLSPrintf("test%d", ++nCounter), pszExt); GDALDataset *poDS = LOG_ACTION( poDriver->Create(osFilename, 0, 0, 0, GDT_Unknown, papszDSCO)); if (poDS == nullptr) @@ -1019,8 +1019,8 @@ static int TestCreateLayer(GDALDriver *poDriver, OGRwkbGeometryType eGeomType) if (poLayer != nullptr) { /* Test creating empty layer */ - osFilename = CPLFormFilename("/vsimem", - CPLSPrintf("test%d", ++nCounter), pszExt); + osFilename = CPLFormFilenameSafe( + "/vsimem", CPLSPrintf("test%d", ++nCounter), pszExt); poDS = LOG_ACTION( poDriver->Create(osFilename, 0, 0, 0, GDT_Unknown, nullptr)); if (poDS != nullptr) @@ -1062,7 +1062,7 @@ static int TestCreate(GDALDriver *poDriver, int bFromAllDrivers) poDriver->GetDescription()))); const char *pszExt = poDriver->GetMetadataItem(GDAL_DMD_EXTENSION); - CPLString osFilename = CPLFormFilename("/foo", "test", pszExt); + CPLString osFilename = CPLFormFilenameSafe("/foo", "test", pszExt); CPLPushErrorHandler(CPLQuietErrorHandler); GDALDataset *poDS = LOG_ACTION(poDriver->Create(osFilename, 0, 0, 0, GDT_Unknown, nullptr)); @@ -4725,8 +4725,8 @@ static int TestVirtualIO(GDALDataset *poDS) for (const char *pszFilename : aosFileList) { if (pszFilename == aosFileList[0]) - osPath = CPLGetPath(pszFilename); - else if (strcmp(osPath, CPLGetPath(pszFilename)) != 0) + osPath = CPLGetPathSafe(pszFilename); + else if (osPath != CPLGetPathSafe(pszFilename)) { bAllPathIdentical = FALSE; break; @@ -4736,7 +4736,7 @@ static int TestVirtualIO(GDALDataset *poDS) if (bAllPathIdentical && aosFileList.size() > 1) { osVirtPath = - CPLFormFilename("/vsimem", CPLGetFilename(osPath), nullptr); + CPLFormFilenameSafe("/vsimem", CPLGetFilename(osPath), nullptr); VSIMkdir(osVirtPath, 0666); } else @@ -4744,22 +4744,22 @@ static int TestVirtualIO(GDALDataset *poDS) for (const char *pszFilename : aosFileList) { - const char *pszDestFile = - CPLFormFilename(osVirtPath, CPLGetFilename(pszFilename), nullptr); - /* CPLDebug("test_ogrsf", "Copying %s to %s", pszFilename, pszDestFile); + const std::string osDestFile = CPLFormFilenameSafe( + osVirtPath, CPLGetFilename(pszFilename), nullptr); + /* CPLDebug("test_ogrsf", "Copying %s to %s", pszFilename, osDestFile.c_str()); */ - CPLCopyFile(pszDestFile, pszFilename); + CPLCopyFile(osDestFile.c_str(), pszFilename); } - const char *pszVirtFile; + std::string osVirtFile; if (VSI_ISREG(sStat.st_mode)) - pszVirtFile = CPLFormFilename( + osVirtFile = CPLFormFilenameSafe( osVirtPath, CPLGetFilename(poDS->GetDescription()), nullptr); else - pszVirtFile = osVirtPath; - CPLDebug("test_ogrsf", "Trying to open %s", pszVirtFile); - GDALDataset *poDS2 = LOG_ACTION(static_cast( - GDALOpenEx(pszVirtFile, GDAL_OF_VECTOR, nullptr, nullptr, nullptr))); + osVirtFile = osVirtPath; + CPLDebug("test_ogrsf", "Trying to open %s", osVirtFile.c_str()); + GDALDataset *poDS2 = LOG_ACTION(static_cast(GDALOpenEx( + osVirtFile.c_str(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr))); if (poDS2 != nullptr) { if (poDS->GetDriver()->GetMetadataItem(GDAL_DCAP_VIRTUALIO) == nullptr) @@ -4794,8 +4794,9 @@ static int TestVirtualIO(GDALDataset *poDS) for (const char *pszFilename : aosFileList) { - VSIUnlink( - CPLFormFilename(osVirtPath, CPLGetFilename(pszFilename), nullptr)); + VSIUnlink(CPLFormFilenameSafe(osVirtPath, CPLGetFilename(pszFilename), + nullptr) + .c_str()); } return bRet; diff --git a/autotest/cpp/CMakeLists.txt b/autotest/cpp/CMakeLists.txt index 7129a5cf1f56..67a8feea8cc5 100644 --- a/autotest/cpp/CMakeLists.txt +++ b/autotest/cpp/CMakeLists.txt @@ -115,6 +115,7 @@ endif() gdal_standard_includes(gdal_unit_test) target_compile_options(gdal_unit_test PRIVATE ${GDAL_CXX_WARNING_FLAGS}) target_compile_definitions(gdal_unit_test PRIVATE -DGDAL_TEST_ROOT_DIR="${GDAL_ROOT_TEST_DIR}") +target_compile_definitions(gdal_unit_test PRIVATE ALLOW_DEPRECATED_CPL_PATH_FUNCTIONS) target_include_directories( gdal_unit_test PRIVATE $ $ $) if (GDAL_USE_SQLITE3) diff --git a/autotest/cpp/testvirtualmem.cpp b/autotest/cpp/testvirtualmem.cpp index e073fb45e1d1..d96685debe44 100644 --- a/autotest/cpp/testvirtualmem.cpp +++ b/autotest/cpp/testvirtualmem.cpp @@ -141,8 +141,8 @@ static void test_raw_auto(const char *pszFormat, int bFileMapping) CPLString osTmpFile; if (bFileMapping) - osTmpFile = - CPLResetExtension(CPLGenerateTempFilename(pszFormat), "img"); + osTmpFile = CPLResetExtensionSafe( + CPLGenerateTempFilenameSafe(pszFormat).c_str(), "img"); else osTmpFile = "/vsimem/tmp.img"; GDALDatasetH hDS = diff --git a/ci/travis/conda/upload.sh b/ci/travis/conda/upload.sh index a02dd00c646e..ccebfd8c5527 100755 --- a/ci/travis/conda/upload.sh +++ b/ci/travis/conda/upload.sh @@ -20,5 +20,5 @@ fi echo "Anaconda token is available, attempting to upload" conda install -c conda-forge python=3.12 anaconda-client -y -find . -name "*gdal*.bz2" -exec anaconda -t "$ANACONDA_TOKEN" upload --force --no-progress --user gdal-master {} \; +find . -name "*gdal*.conda" -exec anaconda -t "$ANACONDA_TOKEN" upload --force --no-progress --user gdal-master {} \; diff --git a/frmts/aaigrid/aaigriddataset.cpp b/frmts/aaigrid/aaigriddataset.cpp index 2e2ef751f31c..a7a81c13c421 100644 --- a/frmts/aaigrid/aaigriddataset.cpp +++ b/frmts/aaigrid/aaigriddataset.cpp @@ -1218,11 +1218,12 @@ GDALDataset *AAIGDataset::CommonOpen(GDALOpenInfo *poOpenInfo, } // Try to read projection file. - char *const pszDirname = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); + char *const pszDirname = + CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); char *const pszBasename = - CPLStrdup(CPLGetBasename(poOpenInfo->pszFilename)); + CPLStrdup(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str()); - poDS->osPrjFilename = CPLFormFilename(pszDirname, pszBasename, "prj"); + poDS->osPrjFilename = CPLFormFilenameSafe(pszDirname, pszBasename, "prj"); int nRet = 0; { VSIStatBufL sStatBuf; @@ -1230,7 +1231,8 @@ GDALDataset *AAIGDataset::CommonOpen(GDALOpenInfo *poOpenInfo, } if (nRet != 0 && VSIIsCaseSensitiveFS(poDS->osPrjFilename)) { - poDS->osPrjFilename = CPLFormFilename(pszDirname, pszBasename, "PRJ"); + poDS->osPrjFilename = + CPLFormFilenameSafe(pszDirname, pszBasename, "PRJ"); VSIStatBufL sStatBuf; nRet = VSIStatL(poDS->osPrjFilename, &sStatBuf); @@ -1557,10 +1559,10 @@ GDALDataset *AAIGDataset::CreateCopy(const char *pszFilename, const char *pszOriginalProjection = poSrcDS->GetProjectionRef(); if (!EQUAL(pszOriginalProjection, "")) { - char *pszDirname = CPLStrdup(CPLGetPath(pszFilename)); - char *pszBasename = CPLStrdup(CPLGetBasename(pszFilename)); - char *pszPrjFilename = - CPLStrdup(CPLFormFilename(pszDirname, pszBasename, "prj")); + char *pszDirname = CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); + char *pszBasename = CPLStrdup(CPLGetBasenameSafe(pszFilename).c_str()); + char *pszPrjFilename = CPLStrdup( + CPLFormFilenameSafe(pszDirname, pszBasename, "prj").c_str()); VSILFILE *fp = VSIFOpenL(pszPrjFilename, "wt"); if (fp != nullptr) { diff --git a/frmts/adrg/adrgdataset.cpp b/frmts/adrg/adrgdataset.cpp index ee460adf0653..dde59c560a9d 100644 --- a/frmts/adrg/adrgdataset.cpp +++ b/frmts/adrg/adrgdataset.cpp @@ -1332,11 +1332,12 @@ char **ADRGDataset::GetGENListFromTHF(const char *pszFileName) char *c = (char *)strchr(osSubFileName.c_str(), ' '); if (c) *c = 0; - if (EQUAL(CPLGetExtension(osSubFileName.c_str()), "GEN")) + if (EQUAL(CPLGetExtensionSafe(osSubFileName.c_str()).c_str(), + "GEN")) { CPLDebug("ADRG", "Found GEN file in THF : %s", osSubFileName.c_str()); - CPLString osGENFileName(CPLGetDirname(pszFileName)); + CPLString osGENFileName(CPLGetDirnameSafe(pszFileName)); char **tokens = CSLTokenizeString2(osSubFileName.c_str(), "/\"", 0); char **ptr = tokens; @@ -1353,9 +1354,9 @@ char **ADRGDataset::GetGENListFromTHF(const char *pszFileName) { if (EQUAL(*ptrDir, *ptr)) { - osGENFileName = - CPLFormFilename(osGENFileName.c_str(), - *ptrDir, nullptr); + osGENFileName = CPLFormFilenameSafe( + osGENFileName.c_str(), *ptrDir, + nullptr); CPLDebug("ADRG", "Building GEN full file name : %s", osGENFileName.c_str()); @@ -1471,10 +1472,10 @@ char **ADRGDataset::GetIMGListFromGEN(const char *pszFileName, CPLDebug("ADRG", "BAD=%s", osBAD.c_str()); /* Build full IMG file name from BAD value */ - CPLString osGENDir(CPLGetDirname(pszFileName)); + CPLString osGENDir(CPLGetDirnameSafe(pszFileName)); const CPLString osFileName = - CPLFormFilename(osGENDir.c_str(), osBAD.c_str(), nullptr); + CPLFormFilenameSafe(osGENDir.c_str(), osBAD.c_str(), nullptr); VSIStatBufL sStatBuf; if (VSIStatL(osFileName, &sStatBuf) == 0) { @@ -1497,8 +1498,8 @@ char **ADRGDataset::GetIMGListFromGEN(const char *pszFileName, { if (EQUAL(*ptrDir, osBAD.c_str())) { - osBAD = - CPLFormFilename(osGENDir.c_str(), *ptrDir, nullptr); + osBAD = CPLFormFilenameSafe(osGENDir.c_str(), *ptrDir, + nullptr); CPLDebug("ADRG", "Building IMG full file name : %s", osBAD.c_str()); break; @@ -1551,7 +1552,7 @@ GDALDataset *ADRGDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; CPLString osFileName(poOpenInfo->pszFilename); - if (EQUAL(CPLGetExtension(osFileName.c_str()), "THF")) + if (EQUAL(CPLGetExtensionSafe(osFileName.c_str()).c_str(), "THF")) { char **papszFileNames = GetGENListFromTHF(osFileName.c_str()); if (papszFileNames == nullptr) @@ -1583,7 +1584,7 @@ GDALDataset *ADRGDataset::Open(GDALOpenInfo *poOpenInfo) } } - if (EQUAL(CPLGetExtension(osFileName.c_str()), "GEN")) + if (EQUAL(CPLGetExtensionSafe(osFileName.c_str()).c_str(), "GEN")) { osGENFileName = osFileName; @@ -1696,14 +1697,14 @@ GDALDataset *ADRGDataset::Create(const char *pszFilename, int nXSize, nYSize); } - if (!EQUAL(CPLGetExtension(pszFilename), "gen")) + if (!EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "gen")) { CPLError(CE_Failure, CPLE_NotSupported, "Invalid filename. Must be ABCDEF01.GEN"); return nullptr; } - CPLString osBaseFileName(CPLGetBasename(pszFilename)); + CPLString osBaseFileName(CPLGetBasenameSafe(pszFilename)); if (osBaseFileName.size() != 8 || osBaseFileName[6] != DIGIT_ZERO || osBaseFileName[7] != '1') { @@ -1732,9 +1733,9 @@ GDALDataset *ADRGDataset::Create(const char *pszFilename, int nXSize, return nullptr; } - CPLString osDirname(CPLGetDirname(pszFilename)); + CPLString osDirname(CPLGetDirnameSafe(pszFilename)); CPLString osTransh01THF( - CPLFormFilename(osDirname.c_str(), "TRANSH01.THF", nullptr)); + CPLFormFilenameSafe(osDirname.c_str(), "TRANSH01.THF", nullptr)); VSILFILE *fdTHF = VSIFOpenL(osTransh01THF.c_str(), "wb"); if (fdTHF == nullptr) { @@ -1744,7 +1745,7 @@ GDALDataset *ADRGDataset::Create(const char *pszFilename, int nXSize, return nullptr; } - CPLString osImgFilename = CPLResetExtension(pszFilename, "IMG"); + CPLString osImgFilename = CPLResetExtensionSafe(pszFilename, "IMG"); VSILFILE *fdIMG = VSIFOpenL(osImgFilename.c_str(), "w+b"); if (fdIMG == nullptr) { diff --git a/frmts/adrg/srpdataset.cpp b/frmts/adrg/srpdataset.cpp index c35346a7ce67..d0d4ad1300ba 100644 --- a/frmts/adrg/srpdataset.cpp +++ b/frmts/adrg/srpdataset.cpp @@ -579,8 +579,9 @@ bool SRPDataset::GetFromRecord(const char *pszFileName, DDFRecord *record) /* Open the .IMG file. Try to recover gracefully if the case */ /* of the filename is wrong. */ /* -------------------------------------------------------------------- */ - const CPLString osDirname = CPLGetDirname(pszFileName); - const CPLString osImgName = CPLFormCIFilename(osDirname, osBAD, nullptr); + const CPLString osDirname = CPLGetDirnameSafe(pszFileName); + const CPLString osImgName = + CPLFormCIFilenameSafe(osDirname, osBAD, nullptr); fdIMG = VSIFOpenL(osImgName, "rb"); if (fdIMG == nullptr) @@ -670,8 +671,8 @@ bool SRPDataset::GetFromRecord(const char *pszFileName, DDFRecord *record) /* -------------------------------------------------------------------- */ /* Try to collect a color map from the .QAL file. */ /* -------------------------------------------------------------------- */ - const CPLString osBasename = CPLGetBasename(pszFileName); - osQALFileName = CPLFormCIFilename(osDirname, osBasename, "QAL"); + const CPLString osBasename = CPLGetBasenameSafe(pszFileName); + osQALFileName = CPLFormCIFilenameSafe(osDirname, osBasename, "QAL"); DDFModule oQALModule; @@ -1058,7 +1059,7 @@ char **SRPDataset::GetGENListFromTHF(const char *pszFileName) if (!module.Open(pszFileName, TRUE)) return papszFileNames; - CPLString osDirName(CPLGetDirname(pszFileName)); + CPLString osDirName(CPLGetDirnameSafe(pszFileName)); while (true) { @@ -1119,7 +1120,7 @@ char **SRPDataset::GetGENListFromTHF(const char *pszFileName) * characters */ CPLString osDirDataset = pszNAM; osDirDataset.resize(6); - CPLString osDatasetDir = CPLFormFilename( + CPLString osDatasetDir = CPLFormFilenameSafe( osDirName.c_str(), osDirDataset.c_str(), nullptr); CPLString osGENFileName = ""; @@ -1134,10 +1135,11 @@ char **SRPDataset::GetGENListFromTHF(const char *pszFileName) { while (*ptrDir) { - if (EQUAL(CPLGetExtension(*ptrDir), "GEN")) + if (EQUAL(CPLGetExtensionSafe(*ptrDir).c_str(), + "GEN")) { bFound = 1; - osGENFileName = CPLFormFilename( + osGENFileName = CPLFormFilenameSafe( osDatasetDir.c_str(), *ptrDir, nullptr); CPLDebug("SRP", "Building GEN full file name : %s", @@ -1160,11 +1162,13 @@ char **SRPDataset::GetGENListFromTHF(const char *pszFileName) { while (*ptrDir) { - if (EQUAL(CPLGetExtension(*ptrDir), "GEN") && - EQUALN(CPLGetBasename(*ptrDir), osName, 6)) + if (EQUAL(CPLGetExtensionSafe(*ptrDir).c_str(), + "GEN") && + EQUALN(CPLGetBasenameSafe(*ptrDir).c_str(), + osName, 6)) { bFound = 1; - osGENFileName = CPLFormFilename( + osGENFileName = CPLFormFilenameSafe( osDirName.c_str(), *ptrDir, nullptr); CPLDebug("SRP", "Building GEN full file name : %s", @@ -1399,10 +1403,10 @@ char **SRPDataset::GetIMGListFromGEN(const char *pszFileName, CPLDebug("SRP", "BAD=%s", osBAD.c_str()); /* Build full IMG file name from BAD value */ - const CPLString osGENDir(CPLGetDirname(pszFileName)); + const CPLString osGENDir(CPLGetDirnameSafe(pszFileName)); const CPLString osFileName = - CPLFormFilename(osGENDir.c_str(), osBAD.c_str(), nullptr); + CPLFormFilenameSafe(osGENDir.c_str(), osBAD.c_str(), nullptr); VSIStatBufL sStatBuf; if (VSIStatL(osFileName, &sStatBuf) == 0) { @@ -1425,8 +1429,8 @@ char **SRPDataset::GetIMGListFromGEN(const char *pszFileName, { if (EQUAL(*ptrDir, osBAD.c_str())) { - osBAD = - CPLFormFilename(osGENDir.c_str(), *ptrDir, nullptr); + osBAD = CPLFormFilenameSafe(osGENDir.c_str(), *ptrDir, + nullptr); CPLDebug("SRP", "Building IMG full file name : %s", osBAD.c_str()); break; @@ -1480,7 +1484,7 @@ GDALDataset *SRPDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; CPLString osFileName(poOpenInfo->pszFilename); - if (EQUAL(CPLGetExtension(osFileName.c_str()), "THF")) + if (EQUAL(CPLGetExtensionSafe(osFileName.c_str()).c_str(), "THF")) { CPLDebug("SRP", "Read THF"); @@ -1521,7 +1525,7 @@ GDALDataset *SRPDataset::Open(GDALOpenInfo *poOpenInfo) if (bTHFWithSingleGEN #ifdef OPEN_GEN - || EQUAL(CPLGetExtension(osFileName.c_str()), "GEN") + || EQUAL(CPLGetExtensionSafe(osFileName.c_str()).c_str(), "GEN") #endif ) { @@ -1550,7 +1554,7 @@ GDALDataset *SRPDataset::Open(GDALOpenInfo *poOpenInfo) } } - if (EQUAL(CPLGetExtension(osFileName.c_str()), "IMG")) + if (EQUAL(CPLGetExtensionSafe(osFileName.c_str()).c_str(), "IMG")) { osIMGFileName = osFileName; @@ -1581,7 +1585,7 @@ GDALDataset *SRPDataset::Open(GDALOpenInfo *poOpenInfo) // -------------------------------------------------------------------- VSIStatBufL sStatBuf; - CPLString basename = CPLGetBasename(osFileName); + CPLString basename = CPLGetBasenameSafe(osFileName); if (basename.size() != 8) { CPLDebug("SRP", "Invalid basename file"); @@ -1590,14 +1594,14 @@ GDALDataset *SRPDataset::Open(GDALOpenInfo *poOpenInfo) nRecordIndex = static_cast(CPLScanLong(basename + 6, 2)); - CPLString path = CPLGetDirname(osFileName); + CPLString path = CPLGetDirnameSafe(osFileName); CPLString basename01 = ResetTo01(basename); - osFileName = CPLFormFilename(path, basename01, ".IMG"); + osFileName = CPLFormFilenameSafe(path, basename01, ".IMG"); - osFileName = CPLResetExtension(osFileName, "GEN"); + osFileName = CPLResetExtensionSafe(osFileName, "GEN"); if (VSIStatL(osFileName, &sStatBuf) != 0) { - osFileName = CPLResetExtension(osFileName, "gen"); + osFileName = CPLResetExtensionSafe(osFileName, "gen"); if (VSIStatL(osFileName, &sStatBuf) != 0) return nullptr; } diff --git a/frmts/aigrid/aigdataset.cpp b/frmts/aigrid/aigdataset.cpp index fc363c34d766..b5f5faae53c5 100644 --- a/frmts/aigrid/aigdataset.cpp +++ b/frmts/aigrid/aigdataset.cpp @@ -337,7 +337,8 @@ char **AIGDataset::GetFileList() papszFileList = CSLAddString( papszFileList, - CPLFormFilename(GetDescription(), papszCoverFiles[i], nullptr)); + CPLFormFilenameSafe(GetDescription(), papszCoverFiles[i], nullptr) + .c_str()); } CSLDestroy(papszCoverFiles); @@ -533,7 +534,7 @@ GDALDataset *AIGDataset::Open(GDALOpenInfo *poOpenInfo) if (osCoverName.size() > 4 && EQUAL(osCoverName.c_str() + osCoverName.size() - 4, ".adf")) { - osCoverName = CPLGetDirname(poOpenInfo->pszFilename); + osCoverName = CPLGetDirnameSafe(poOpenInfo->pszFilename); if (osCoverName == "") osCoverName = "."; } @@ -653,18 +654,18 @@ GDALDataset *AIGDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ char **papszFiles = VSIReadDir(psInfo->pszCoverName); CPLString osClrFilename; - CPLString osCleanPath = CPLCleanTrailingSlash(psInfo->pszCoverName); + CPLString osCleanPath = CPLCleanTrailingSlashSafe(psInfo->pszCoverName); // first check for any .clr in coverage dir. for (int iFile = 0; papszFiles != nullptr && papszFiles[iFile] != nullptr; iFile++) { - if (!EQUAL(CPLGetExtension(papszFiles[iFile]), "clr") && - !EQUAL(CPLGetExtension(papszFiles[iFile]), "CLR")) + const std::string osExt = CPLGetExtensionSafe(papszFiles[iFile]); + if (!EQUAL(osExt.c_str(), "clr") && !EQUAL(osExt.c_str(), "CLR")) continue; - osClrFilename = - CPLFormFilename(psInfo->pszCoverName, papszFiles[iFile], nullptr); + osClrFilename = CPLFormFilenameSafe(psInfo->pszCoverName, + papszFiles[iFile], nullptr); break; } @@ -707,14 +708,14 @@ GDALDataset *AIGDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Try to read projection file. */ /* -------------------------------------------------------------------- */ - const char *pszPrjFilename = - CPLFormCIFilename(psInfo->pszCoverName, "prj", "adf"); - if (VSIStatL(pszPrjFilename, &sStatBuf) == 0) + const std::string osPrjFilename = + CPLFormCIFilenameSafe(psInfo->pszCoverName, "prj", "adf"); + if (VSIStatL(osPrjFilename.c_str(), &sStatBuf) == 0) { OGRSpatialReference oSRS; oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); - poDS->papszPrj = CSLLoad(pszPrjFilename); + poDS->papszPrj = CSLLoad(osPrjFilename.c_str()); if (oSRS.importFromESRI(poDS->papszPrj) == OGRERR_NONE) { @@ -874,13 +875,13 @@ static CPLErr AIGRename(const char *pszNewName, const char *pszOldName) /* -------------------------------------------------------------------- */ CPLString osOldPath, osNewPath; - if (strlen(CPLGetExtension(pszNewName)) > 0) - osNewPath = CPLGetPath(pszNewName); + if (!CPLGetExtensionSafe(pszNewName).empty()) + osNewPath = CPLGetPathSafe(pszNewName); else osNewPath = pszNewName; - if (strlen(CPLGetExtension(pszOldName)) > 0) - osOldPath = CPLGetPath(pszOldName); + if (!CPLGetExtensionSafe(pszOldName).empty()) + osOldPath = CPLGetPathSafe(pszOldName); else osOldPath = pszOldName; diff --git a/frmts/basisu_ktx2/common.cpp b/frmts/basisu_ktx2/common.cpp index 91f7b22e39c1..0eac8e892248 100644 --- a/frmts/basisu_ktx2/common.cpp +++ b/frmts/basisu_ktx2/common.cpp @@ -127,7 +127,7 @@ bool GDAL_KTX2_BASISU_CreateCopy(const char *pszFilename, GDALDataset *poSrcDS, #endif if (bUseTempFilename) { - osTempFilename = CPLGenerateTempFilename(nullptr); + osTempFilename = CPLGenerateTempFilenameSafe(nullptr); CPLDebug("KTX2", "Using temporary file %s", osTempFilename.c_str()); params.m_out_filename = osTempFilename; } diff --git a/frmts/bsb/bsbdataset.cpp b/frmts/bsb/bsbdataset.cpp index e2bdb34154ba..a0afd3291be6 100644 --- a/frmts/bsb/bsbdataset.cpp +++ b/frmts/bsb/bsbdataset.cpp @@ -568,24 +568,24 @@ void BSBDataset::ScanForGCPs(bool isNos, const char *pszFilename) void BSBDataset::ScanForGCPsNos(const char *pszFilename) { - const char *extension = CPLGetExtension(pszFilename); + const std::string extension = CPLGetExtensionSafe(pszFilename); // pseudointelligently try and guess whether we want a .geo or a .GEO - const char *geofile = nullptr; - if (extension[1] == 'O') + std::string geofile; + if (extension.size() >= 2 && extension[1] == 'O') { - geofile = CPLResetExtension(pszFilename, "GEO"); + geofile = CPLResetExtensionSafe(pszFilename, "GEO"); } else { - geofile = CPLResetExtension(pszFilename, "geo"); + geofile = CPLResetExtensionSafe(pszFilename, "geo"); } - FILE *gfp = VSIFOpen(geofile, "r"); // Text files + FILE *gfp = VSIFOpen(geofile.c_str(), "r"); // Text files if (gfp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Couldn't find a matching .GEO file: %s", geofile); + "Couldn't find a matching .GEO file: %s", geofile.c_str()); return; } diff --git a/frmts/ceos2/sar_ceosdataset.cpp b/frmts/ceos2/sar_ceosdataset.cpp index eb5347088eaf..dda64ac26480 100644 --- a/frmts/ceos2/sar_ceosdataset.cpp +++ b/frmts/ceos2/sar_ceosdataset.cpp @@ -1822,9 +1822,11 @@ GDALDataset *SAR_CEOSDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Try the various filenames. */ /* -------------------------------------------------------------------- */ - char *pszPath = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); - char *pszBasename = CPLStrdup(CPLGetBasename(poOpenInfo->pszFilename)); - char *pszExtension = CPLStrdup(CPLGetExtension(poOpenInfo->pszFilename)); + char *pszPath = CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); + char *pszBasename = + CPLStrdup(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str()); + char *pszExtension = + CPLStrdup(CPLGetExtensionSafe(poOpenInfo->pszFilename).c_str()); int nBand; if (strlen(pszBasename) > 4) @@ -1841,7 +1843,7 @@ GDALDataset *SAR_CEOSDataset::Open(GDALOpenInfo *poOpenInfo) int e = 0; while (CeosExtension[e][iFile] != nullptr) { - char *pszFilename = nullptr; + std::string osFilename; /* build filename */ if (EQUAL(CeosExtension[e][5], "base")) @@ -1850,18 +1852,18 @@ GDALDataset *SAR_CEOSDataset::Open(GDALOpenInfo *poOpenInfo) snprintf(szMadeBasename, sizeof(szMadeBasename), CeosExtension[e][iFile], nBand); - pszFilename = CPLStrdup( - CPLFormFilename(pszPath, szMadeBasename, pszExtension)); + osFilename = + CPLFormFilenameSafe(pszPath, szMadeBasename, pszExtension); } else if (EQUAL(CeosExtension[e][5], "ext")) { - pszFilename = CPLStrdup(CPLFormFilename( - pszPath, pszBasename, CeosExtension[e][iFile])); + osFilename = CPLFormFilenameSafe(pszPath, pszBasename, + CeosExtension[e][iFile]); } else if (EQUAL(CeosExtension[e][5], "whole")) { - pszFilename = CPLStrdup( - CPLFormFilename(pszPath, CeosExtension[e][iFile], "")); + osFilename = + CPLFormFilenameSafe(pszPath, CeosExtension[e][iFile], ""); } // This is for SAR SLC as per the SAR Toolbox (from ASF). @@ -1876,37 +1878,33 @@ GDALDataset *SAR_CEOSDataset::Open(GDALOpenInfo *poOpenInfo) snprintf(szThisExtension, sizeof(szThisExtension), "%s", CeosExtension[e][iFile]); - pszFilename = CPLStrdup( - CPLFormFilename(pszPath, pszBasename, szThisExtension)); + osFilename = + CPLFormFilenameSafe(pszPath, pszBasename, szThisExtension); } - CPLAssert(pszFilename != nullptr); - if (pszFilename == nullptr) - return nullptr; - /* try to open */ - VSILFILE *process_fp = VSIFOpenL(pszFilename, "rb"); + VSILFILE *process_fp = VSIFOpenL(osFilename.c_str(), "rb"); /* try upper case */ if (process_fp == nullptr) { - for (int i = static_cast(strlen(pszFilename)) - 1; - i >= 0 && pszFilename[i] != '/' && pszFilename[i] != '\\'; + for (int i = static_cast(osFilename.size()) - 1; + i >= 0 && osFilename[i] != '/' && osFilename[i] != '\\'; i--) { - if (pszFilename[i] >= 'a' && pszFilename[i] <= 'z') - pszFilename[i] = pszFilename[i] - 'a' + 'A'; + if (osFilename[i] >= 'a' && osFilename[i] <= 'z') + osFilename[i] = osFilename[i] - 'a' + 'A'; } - process_fp = VSIFOpenL(pszFilename, "rb"); + process_fp = VSIFOpenL(osFilename.c_str(), "rb"); } if (process_fp != nullptr) { - CPLDebug("CEOS", "Opened %s.\n", pszFilename); + CPLDebug("CEOS", "Opened %s.\n", osFilename.c_str()); poDS->papszExtraFiles = - CSLAddString(poDS->papszExtraFiles, pszFilename); + CSLAddString(poDS->papszExtraFiles, osFilename.c_str()); CPL_IGNORE_RET_VAL(VSIFSeekL(process_fp, 0, SEEK_END)); if (ProcessData(process_fp, iFile, psVolume, -1, @@ -1929,15 +1927,12 @@ GDALDataset *SAR_CEOSDataset::Open(GDALOpenInfo *poOpenInfo) } CPL_IGNORE_RET_VAL(VSIFCloseL(process_fp)); - CPLFree(pszFilename); break; /* Exit the while loop, we have this data type*/ } CPL_IGNORE_RET_VAL(VSIFCloseL(process_fp)); } - CPLFree(pszFilename); - e++; } } diff --git a/frmts/coasp/coasp_dataset.cpp b/frmts/coasp/coasp_dataset.cpp index 3db8b729a0cf..65e916510a63 100644 --- a/frmts/coasp/coasp_dataset.cpp +++ b/frmts/coasp/coasp_dataset.cpp @@ -393,8 +393,9 @@ GDALDataset *COASPDataset::Open(GDALOpenInfo *poOpenInfo) poDS->pszFileName = VSIStrdup(poOpenInfo->pszFilename); /* determine the file name prefix */ - char *pszBaseName = VSIStrdup(CPLGetBasename(poDS->pszFileName)); - char *pszDir = VSIStrdup(CPLGetPath(poDS->pszFileName)); + char *pszBaseName = + VSIStrdup(CPLGetBasenameSafe(poDS->pszFileName).c_str()); + char *pszDir = VSIStrdup(CPLGetPathSafe(poDS->pszFileName).c_str()); const char *pszExt = "rc"; int nNull = static_cast(strlen(pszBaseName)) - 1; if (nNull <= 0) @@ -476,9 +477,9 @@ GDALDataset *COASPDataset::Open(GDALOpenInfo *poOpenInfo) /* Horizontal transmit, horizontal receive */ psChan[0] = 'h'; psChan[1] = 'h'; - const char *pszFilename = CPLFormFilename(pszDir, pszBase, pszExt); + std::string osFilename = CPLFormFilenameSafe(pszDir, pszBase, pszExt); - poDS->fpBinHH = VSIFOpenL(pszFilename, "r"); + poDS->fpBinHH = VSIFOpenL(osFilename.c_str(), "r"); if (poDS->fpBinHH != nullptr) { @@ -490,9 +491,9 @@ GDALDataset *COASPDataset::Open(GDALOpenInfo *poOpenInfo) /* Horizontal transmit, vertical receive */ psChan[0] = 'h'; psChan[1] = 'v'; - pszFilename = CPLFormFilename(pszDir, pszBase, pszExt); + osFilename = CPLFormFilenameSafe(pszDir, pszBase, pszExt); - poDS->fpBinHV = VSIFOpenL(pszFilename, "r"); + poDS->fpBinHV = VSIFOpenL(osFilename.c_str(), "r"); if (poDS->fpBinHV != nullptr) { @@ -503,9 +504,9 @@ GDALDataset *COASPDataset::Open(GDALOpenInfo *poOpenInfo) /* Vertical transmit, horizontal receive */ psChan[0] = 'v'; psChan[1] = 'h'; - pszFilename = CPLFormFilename(pszDir, pszBase, pszExt); + osFilename = CPLFormFilenameSafe(pszDir, pszBase, pszExt); - poDS->fpBinVH = VSIFOpenL(pszFilename, "r"); + poDS->fpBinVH = VSIFOpenL(osFilename.c_str(), "r"); if (poDS->fpBinVH != nullptr) { @@ -516,9 +517,9 @@ GDALDataset *COASPDataset::Open(GDALOpenInfo *poOpenInfo) /* Vertical transmit, vertical receive */ psChan[0] = 'v'; psChan[1] = 'v'; - pszFilename = CPLFormFilename(pszDir, pszBase, pszExt); + osFilename = CPLFormFilenameSafe(pszDir, pszBase, pszExt); - poDS->fpBinVV = VSIFOpenL(pszFilename, "r"); + poDS->fpBinVV = VSIFOpenL(osFilename.c_str(), "r"); if (poDS->fpBinVV != nullptr) { diff --git a/frmts/derived/deriveddataset.cpp b/frmts/derived/deriveddataset.cpp index bccbf31501db..920140f2a848 100644 --- a/frmts/derived/deriveddataset.cpp +++ b/frmts/derived/deriveddataset.cpp @@ -172,10 +172,10 @@ GDALDataset *DerivedDataset::Open(GDALOpenInfo *poOpenInfo) VSIStatBufL sStat; if (VSIStatL(odFilename, &sStat) == 0) { - CPLString path = CPLGetPath(odFilename); + CPLString path = CPLGetPathSafe(odFilename); CPLString ovrFileName = "DERIVED_DATASET_" + odDerivedName + "_" + CPLGetFilename(odFilename); - CPLString ovrFilePath = CPLFormFilename(path, ovrFileName, nullptr); + CPLString ovrFilePath = CPLFormFilenameSafe(path, ovrFileName, nullptr); poDS->oOvManager.Initialize(poDS, ovrFilePath); } diff --git a/frmts/dimap/dimapdataset.cpp b/frmts/dimap/dimapdataset.cpp index 04bd3adb3c57..30ce22e5350e 100644 --- a/frmts/dimap/dimapdataset.cpp +++ b/frmts/dimap/dimapdataset.cpp @@ -457,8 +457,8 @@ int DIMAPDataset::Identify(GDALOpenInfo *poOpenInfo) else if (poOpenInfo->bIsDirectory) { // DIMAP file. - CPLString osMDFilename = - CPLFormCIFilename(poOpenInfo->pszFilename, "METADATA.DIM", nullptr); + CPLString osMDFilename = CPLFormCIFilenameSafe(poOpenInfo->pszFilename, + "METADATA.DIM", nullptr); VSIStatBufL sStat; if (VSIStatL(osMDFilename, &sStat) == 0) @@ -477,15 +477,15 @@ int DIMAPDataset::Identify(GDALOpenInfo *poOpenInfo) else { // DIMAP 2 file. - osMDFilename = CPLFormCIFilename(poOpenInfo->pszFilename, - "VOL_PHR.XML", nullptr); + osMDFilename = CPLFormCIFilenameSafe(poOpenInfo->pszFilename, + "VOL_PHR.XML", nullptr); if (VSIStatL(osMDFilename, &sStat) == 0) return TRUE; // DIMAP VHR2020 file. - osMDFilename = CPLFormCIFilename(poOpenInfo->pszFilename, - "VOL_PNEO.XML", nullptr); + osMDFilename = CPLFormCIFilenameSafe(poOpenInfo->pszFilename, + "VOL_PNEO.XML", nullptr); if (VSIStatL(osMDFilename, &sStat) == 0) return TRUE; @@ -542,18 +542,19 @@ GDALDataset *DIMAPDataset::Open(GDALOpenInfo *poOpenInfo) std::string osMDFilename(osFilename); if (VSIStatL(osFilename.c_str(), &sStat) == 0 && VSI_ISDIR(sStat.st_mode)) { - osMDFilename = CPLFormCIFilename(osFilename, "METADATA.DIM", nullptr); + osMDFilename = + CPLFormCIFilenameSafe(osFilename, "METADATA.DIM", nullptr); /* DIMAP2 */ if (VSIStatL(osMDFilename.c_str(), &sStat) != 0) { osMDFilename = - CPLFormCIFilename(osFilename, "VOL_PHR.XML", nullptr); + CPLFormCIFilenameSafe(osFilename, "VOL_PHR.XML", nullptr); if (VSIStatL(osMDFilename.c_str(), &sStat) != 0) { // DIMAP VHR2020 file. osMDFilename = - CPLFormCIFilename(osFilename, "VOL_PNEO.XML", nullptr); + CPLFormCIFilenameSafe(osFilename, "VOL_PNEO.XML", nullptr); } } } @@ -642,14 +643,15 @@ GDALDataset *DIMAPDataset::Open(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->bIsDirectory) { - osDIMAPFilename = CPLFormCIFilename( + osDIMAPFilename = CPLFormCIFilenameSafe( poOpenInfo->pszFilename, pszHref, nullptr); } else { - CPLString osPath = CPLGetPath(osMDFilename.c_str()); + CPLString osPath = + CPLGetPathSafe(osMDFilename.c_str()); osDIMAPFilename = - CPLFormFilename(osPath, pszHref, nullptr); + CPLFormFilenameSafe(osPath, pszHref, nullptr); } // Data file might be specified there. @@ -659,8 +661,9 @@ GDALDataset *DIMAPDataset::Open(GDALOpenInfo *poOpenInfo) if (strlen(pszDataFileHref) > 0) { - CPLString osPath = CPLGetPath(osMDFilename.c_str()); - osImageDSFilename = CPLFormFilename( + CPLString osPath = + CPLGetPathSafe(osMDFilename.c_str()); + osImageDSFilename = CPLFormFilenameSafe( osPath, pszDataFileHref, nullptr); } } @@ -709,9 +712,10 @@ GDALDataset *DIMAPDataset::Open(GDALOpenInfo *poOpenInfo) if (strlen(pszHref) > 0) // STRIP product found. { - CPLString osPath = CPLGetPath(osDIMAPFilename.c_str()); + CPLString osPath = + CPLGetPathSafe(osDIMAPFilename.c_str()); osSTRIPFilename = - CPLFormCIFilename(osPath, pszHref, nullptr); + CPLFormCIFilenameSafe(osPath, pszHref, nullptr); if (VSIStatL(osSTRIPFilename, &sStat) == 0) { psProductStrip = CPLParseXMLFile(osSTRIPFilename); @@ -740,9 +744,10 @@ GDALDataset *DIMAPDataset::Open(GDALOpenInfo *poOpenInfo) if (strlen(pszHref) > 0) // RPC product found. { - CPLString osPath = CPLGetPath(osDIMAPFilename.c_str()); + CPLString osPath = + CPLGetPathSafe(osDIMAPFilename.c_str()); osRPCFilename = - CPLFormCIFilename(osPath, pszHref, nullptr); + CPLFormCIFilenameSafe(osPath, pszHref, nullptr); break; } @@ -803,8 +808,8 @@ int DIMAPDataset::ReadImageInformation() const char *pszHref = CPLGetXMLValue(psDoc, "Data_Access.Data_File.DATA_FILE_PATH.href", ""); - CPLString osPath = CPLGetPath(osMDFilename); - CPLString osImageFilename = CPLFormFilename(osPath, pszHref, nullptr); + CPLString osPath = CPLGetPathSafe(osMDFilename); + CPLString osImageFilename = CPLFormFilenameSafe(osPath, pszHref, nullptr); /* -------------------------------------------------------------------- */ /* Try and open the file. */ @@ -1154,7 +1159,7 @@ int DIMAPDataset::ReadImageInformation2() int nImageDSRow = 1, nImageDSCol = 1; if (psDataFiles) { - const CPLString osPath = CPLGetPath(osDIMAPFilename); + const CPLString osPath = CPLGetPathSafe(osDIMAPFilename); for (int nPart = 0; psDataFiles != nullptr; psDataFiles = psDataFiles->psNext, nPart++) { @@ -1179,7 +1184,7 @@ int DIMAPDataset::ReadImageInformation2() return false; } const CPLString osTileFilename( - CPLFormCIFilename(osPath, pszHref, nullptr)); + CPLFormCIFilenameSafe(osPath, pszHref, nullptr)); if ((nRow == 1 && nCol == 1 && nPart == 0) || osImageDSFilename.empty()) { diff --git a/frmts/dted/dteddataset.cpp b/frmts/dted/dteddataset.cpp index 47cac394e5e9..eb9139146edc 100644 --- a/frmts/dted/dteddataset.cpp +++ b/frmts/dted/dteddataset.cpp @@ -470,9 +470,9 @@ GDALDataset *DTEDDataset::Open(GDALOpenInfo *poOpenInfo) int bTryAux = TRUE; if (poOpenInfo->GetSiblingFiles() != nullptr && CSLFindString(poOpenInfo->GetSiblingFiles(), - CPLResetExtension( - CPLGetFilename(poOpenInfo->pszFilename), "aux")) < - 0 && + CPLResetExtensionSafe( + CPLGetFilename(poOpenInfo->pszFilename), "aux") + .c_str()) < 0 && CSLFindString( poOpenInfo->GetSiblingFiles(), CPLSPrintf("%s.aux", CPLGetFilename(poOpenInfo->pszFilename))) < diff --git a/frmts/ecw/ecwcreatecopy.cpp b/frmts/ecw/ecwcreatecopy.cpp index 525bb65d9ad6..04930bf9b576 100644 --- a/frmts/ecw/ecwcreatecopy.cpp +++ b/frmts/ecw/ecwcreatecopy.cpp @@ -827,7 +827,8 @@ CPLErr GDALECWCompressor::Initialize( SetParameter(CNCSJP2FileView::JP2_COMPRESS_PROFILE_NITF_BIIF_EPJE); pszOption = CSLFetchNameValue(papszOptions, "CODESTREAM_ONLY"); - if (pszOption == nullptr && EQUAL(CPLGetExtension(pszFilename), "j2k")) + if (pszOption == nullptr && + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "j2k")) pszOption = "YES"; if (pszOption != nullptr) SetParameter(CNCSJP2FileView::JP2_COMPRESS_CODESTREAM_ONLY, @@ -1510,7 +1511,7 @@ GDALDataset *ECWCreateCopyECW(const char *pszFilename, GDALDataset *poSrcDS, return nullptr; } - if (!EQUAL(CPLGetExtension(pszFilename), "ecw")) + if (!EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "ecw")) { CPLError(CE_Failure, CPLE_AppDefined, "ECW driver does not support creating ECW files\n" @@ -1605,7 +1606,7 @@ GDALDataset *ECWCreateCopyJPEG2000(const char *pszFilename, return nullptr; } - if (EQUAL(CPLGetExtension(pszFilename), "ecw")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "ecw")) { CPLError(CE_Failure, CPLE_AppDefined, "JP2ECW driver does not support creating JPEG2000 files\n" diff --git a/frmts/ecw/ecwdataset.cpp b/frmts/ecw/ecwdataset.cpp index 933c07eb4149..2509b485249d 100644 --- a/frmts/ecw/ecwdataset.cpp +++ b/frmts/ecw/ecwdataset.cpp @@ -2762,7 +2762,7 @@ GDALDataset *ECWDataset::Open(GDALOpenInfo *poOpenInfo, int bIsJPEG2000) { #if ECWSDK_VERSION < 50 /* Detect what is apparently the ECW v3 file format signature */ - if (EQUAL(CPLGetExtension(osFilename), "ECW") && + if (EQUAL(CPLGetExtensionSafe(osFilename).c_str(), "ECW") && poOpenInfo->nHeaderBytes > 0x30 && STARTS_WITH_CI((const char *)(poOpenInfo->pabyHeader + 0x20), "ecw ECW3")) diff --git a/frmts/ecw/ecwdrivercore.cpp b/frmts/ecw/ecwdrivercore.cpp index ec48d73a8113..ef23df51434a 100644 --- a/frmts/ecw/ecwdrivercore.cpp +++ b/frmts/ecw/ecwdrivercore.cpp @@ -40,7 +40,7 @@ int ECWDatasetIdentifyECW(GDALOpenInfo *poOpenInfo) /* This has to either be a file on disk ending in .ecw or a */ /* ecwp: protocol url. */ /* -------------------------------------------------------------------- */ - if ((!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "ecw") || + if ((!poOpenInfo->IsExtensionEqualToCI("ecw") || poOpenInfo->nHeaderBytes == 0) && !STARTS_WITH_CI(poOpenInfo->pszFilename, "ecwp:") && !STARTS_WITH_CI(poOpenInfo->pszFilename, "ecwps:")) diff --git a/frmts/ecw/gdal_ecw.h b/frmts/ecw/gdal_ecw.h index 70ec8ec3464d..555e32617f9f 100644 --- a/frmts/ecw/gdal_ecw.h +++ b/frmts/ecw/gdal_ecw.h @@ -214,16 +214,17 @@ class VSIIOStream final : public CNCSJPCIOStream CPLString osFilenameUsed = pszFilename; #if ECWSDK_VERSION < 55 - CPLString osPath = CPLGetPath(pszFilename); + CPLString osPath = CPLGetPathSafe(pszFilename); struct stat sStatBuf; if (!osPath.empty() && stat(osPath, &sStatBuf) != 0) { - osFilenameUsed = CPLGenerateTempFilename(nullptr); + osFilenameUsed = CPLGenerateTempFilenameSafe(nullptr); // try to preserve the extension. - if (strlen(CPLGetExtension(pszFilename)) > 0) + const auto osExt = CPLGetExtensionSafe(pszFilename); + if (!osExt.empty()) { osFilenameUsed += "."; - osFilenameUsed += CPLGetExtension(pszFilename); + osFilenameUsed += osExt; } CPLDebug("ECW", "Using filename '%s' for temporary directory " diff --git a/frmts/ers/ersdataset.cpp b/frmts/ers/ersdataset.cpp index 4bb321ca3c46..522623009b4c 100644 --- a/frmts/ers/ersdataset.cpp +++ b/frmts/ers/ersdataset.cpp @@ -988,7 +988,7 @@ GDALDataset *ERSDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Figure out the name of the target file. */ /* -------------------------------------------------------------------- */ - CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); + CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); CPLString osDataFile = poHeader->Find("DataFile", ""); if (osDataFile.length() == 0) // just strip off extension. @@ -997,7 +997,7 @@ GDALDataset *ERSDataset::Open(GDALOpenInfo *poOpenInfo) osDataFile = osDataFile.substr(0, osDataFile.find_last_of('.')); } - CPLString osDataFilePath = CPLFormFilename(osPath, osDataFile, nullptr); + CPLString osDataFilePath = CPLFormFilenameSafe(osPath, osDataFile, nullptr); /* -------------------------------------------------------------------- */ /* DataSetType = Translated files are links to things like ecw */ @@ -1350,7 +1350,7 @@ GDALDataset *ERSDataset::Create(const char *pszFilename, int nXSize, int nYSize, /* -------------------------------------------------------------------- */ CPLString osBinFile, osErsFile; - if (EQUAL(CPLGetExtension(pszFilename), "ers")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "ers")) { osErsFile = pszFilename; osBinFile = osErsFile.substr(0, osErsFile.length() - 4); diff --git a/frmts/esric/esric_dataset.cpp b/frmts/esric/esric_dataset.cpp index b3b162577c61..d6e662e101b0 100644 --- a/frmts/esric/esric_dataset.cpp +++ b/frmts/esric/esric_dataset.cpp @@ -633,8 +633,7 @@ GDALDataset *ECDataset::Open(GDALOpenInfo *poOpenInfo, return nullptr; } auto ds = new ECDataset(); - ds->dname.Printf("%s/_alllayers", - CPLGetDirname(poOpenInfo->pszFilename)); + ds->dname = CPLGetDirnameSafe(poOpenInfo->pszFilename) + "/_alllayers"; CPLErr error = ds->Initialize(CacheInfo); CPLDestroyXMLNode(config); if (CE_None != error) @@ -684,7 +683,8 @@ GDALDataset *ECDataset::Open(GDALOpenInfo *poOpenInfo, tileBundlesPath.erase(0, 2); } - ds->dname.Printf("%s/%s", CPLGetDirname(poOpenInfo->pszFilename), + ds->dname.Printf("%s/%s", + CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str(), tileBundlesPath.c_str()); CPLErr error = ds->InitializeFromJSON(oRoot); if (CE_None != error) diff --git a/frmts/fits/fitsdataset.cpp b/frmts/fits/fitsdataset.cpp index 67209ae32d2e..b62a824ab454 100644 --- a/frmts/fits/fitsdataset.cpp +++ b/frmts/fits/fitsdataset.cpp @@ -2543,7 +2543,7 @@ GDALDataset *FITSDataset::Open(GDALOpenInfo *poOpenInfo) osPath.resize(1024); if (CPLGetExecPath(&osPath[0], static_cast(osPath.size()))) { - osPath = CPLGetBasename(osPath.c_str()); + osPath = CPLGetBasenameSafe(osPath.c_str()); } if (osPath == "gdalinfo") { @@ -2578,7 +2578,7 @@ GDALDataset *FITSDataset::Open(GDALOpenInfo *poOpenInfo) osPath.resize(1024); if (CPLGetExecPath(&osPath[0], static_cast(osPath.size()))) { - osPath = CPLGetBasename(osPath.c_str()); + osPath = CPLGetBasenameSafe(osPath.c_str()); } if (osPath == "ogrinfo") { diff --git a/frmts/gif/biggifdataset.cpp b/frmts/gif/biggifdataset.cpp index 557c1d2deb41..20f2e936cf56 100644 --- a/frmts/gif/biggifdataset.cpp +++ b/frmts/gif/biggifdataset.cpp @@ -220,7 +220,7 @@ CPLErr BIGGIFDataset::ReOpen() /* while closing and then destroying this temporary dataset */ const char *apszOptions[] = {"COMPRESS=LZW", "SPARSE_OK=YES", nullptr}; - CPLString osTempFilename = CPLGenerateTempFilename("biggif"); + CPLString osTempFilename = CPLGenerateTempFilenameSafe("biggif"); osTempFilename += ".tif"; diff --git a/frmts/grib/degrib/degrib/metaname.cpp b/frmts/grib/degrib/degrib/metaname.cpp index d0192d7fd93c..99da1a04f6ad 100644 --- a/frmts/grib/degrib/degrib/metaname.cpp +++ b/frmts/grib/degrib/degrib/metaname.cpp @@ -51,7 +51,7 @@ void MetanameCleanup(void) #endif } -static const char* GetGRIB2_CSVFilename(const char* pszFilename) +static std::string GetGRIB2_CSVFilename(const char* pszFilename) { #ifdef EMBED_RESOURCE_FILES std::lock_guard oGuard(goMutex); @@ -59,16 +59,16 @@ static const char* GetGRIB2_CSVFilename(const char* pszFilename) pgoMapResourceFiles = new std::map(); const auto oIter = pgoMapResourceFiles->find(pszFilename); if( oIter != pgoMapResourceFiles->end() ) - return oIter->second.c_str(); + return oIter->second; #endif const char* pszGribTableDirectory = CPLGetConfigOption("GRIB_RESOURCE_DIR", nullptr); if( pszGribTableDirectory ) { - const char* pszFullFilename = CPLFormFilename(pszGribTableDirectory, pszFilename, nullptr); + const std::string osFullFilename = CPLFormFilenameSafe(pszGribTableDirectory, pszFilename, nullptr); VSIStatBufL sStat; - if( VSIStatL(pszFullFilename, &sStat) == 0 ) - return pszFullFilename; - return nullptr; + if( VSIStatL(osFullFilename.c_str(), &sStat) == 0 ) + return osFullFilename; + return std::string(); } const char* pszRet = nullptr; CPL_IGNORE_RET_VAL(pszRet); @@ -96,21 +96,21 @@ static const char* GetGRIB2_CSVFilename(const char* pszFilename) else #endif { - return nullptr; + return std::string(); } } - return pszRet; + return std::string(pszRet ? pszRet : ""); } const char *centerLookup (unsigned short int center) { - const char* pszFilename = GetGRIB2_CSVFilename("grib2_center.csv"); - if( pszFilename == nullptr ) + const std::string osFilename = GetGRIB2_CSVFilename("grib2_center.csv"); + if( osFilename.empty() ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find grib2_center.csv"); return nullptr; } - const char* pszName = CSVGetField( pszFilename, "code", CPLSPrintf("%d", center), + const char* pszName = CSVGetField( osFilename.c_str(), "code", CPLSPrintf("%d", center), CC_Integer, "name" ); if( pszName && pszName[0] == 0 ) pszName = nullptr; @@ -120,22 +120,22 @@ const char *centerLookup (unsigned short int center) const char *subCenterLookup(unsigned short int center, unsigned short int subcenter) { - const char* pszFilename = GetGRIB2_CSVFilename("grib2_subcenter.csv"); - if( pszFilename == nullptr ) + const std::string osFilename = GetGRIB2_CSVFilename("grib2_subcenter.csv"); + if( osFilename.empty() ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find grib2_subcenter.csv"); return nullptr; } - int iCenter = CSVGetFileFieldId(pszFilename,"center_code"); - int iSubCenter = CSVGetFileFieldId(pszFilename,"subcenter_code"); - int iName = CSVGetFileFieldId(pszFilename,"name"); + int iCenter = CSVGetFileFieldId(osFilename.c_str(),"center_code"); + int iSubCenter = CSVGetFileFieldId(osFilename.c_str(),"subcenter_code"); + int iName = CSVGetFileFieldId(osFilename.c_str(),"name"); if( iCenter < 0 || iSubCenter < 0 || iName < 0 ) { - CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", pszFilename); + CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", osFilename.c_str()); return nullptr; } - CSVRewind(pszFilename); - while( char** papszFields = CSVGetNextLine(pszFilename) ) + CSVRewind(osFilename.c_str()); + while( char** papszFields = CSVGetNextLine(osFilename.c_str()) ) { if( atoi(papszFields[iCenter]) == static_cast(center) && atoi(papszFields[iSubCenter]) == static_cast(subcenter) ) @@ -149,22 +149,22 @@ const char *subCenterLookup(unsigned short int center, #ifdef unused_by_GDAL const char *processLookup (unsigned short int center, unsigned char process) { - const char* pszFilename = GetGRIB2_CSVFilename("grib2_process.csv"); - if( pszFilename == nullptr ) + const std::string Filename = GetGRIB2_CSVFilename("grib2_process.csv"); + if( osFilename.empty() ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find grib2_process.csv"); return nullptr; } - int iCenter = CSVGetFileFieldId(pszFilename,"center_code"); - int iProcess = CSVGetFileFieldId(pszFilename,"process_code"); - int iName = CSVGetFileFieldId(pszFilename,"name"); + int iCenter = CSVGetFileFieldId(osFilename.c_str(),"center_code"); + int iProcess = CSVGetFileFieldId(osFilename.c_str(),"process_code"); + int iName = CSVGetFileFieldId(osFilename.c_str(),"name"); if( iCenter < 0 || iProcess < 0 || iName < 0 ) { - CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", pszFilename); + CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", osFilename.c_str()); return nullptr; } - CSVRewind(pszFilename); - while( char** papszFields = CSVGetNextLine(pszFilename) ) + CSVRewind(osFilename.c_str()); + while( char** papszFields = CSVGetNextLine(osFilename.c_str()) ) { if( atoi(papszFields[iCenter]) == static_cast(center) && atoi(papszFields[iProcess]) == static_cast(process) ) @@ -240,23 +240,23 @@ static int GetGrib2Table4_2_Record (int prodType, int cat, int subcat, { const char* pszBaseFilename = CPLSPrintf("grib2_table_4_2_%d_%d.csv", prodType, cat); - const char* pszFilename = GetGRIB2_CSVFilename(pszBaseFilename); - if( pszFilename == nullptr ) + const std::string osFilename = GetGRIB2_CSVFilename(pszBaseFilename); + if( osFilename.empty() ) { return FALSE; } - int iSubcat = CSVGetFileFieldId(pszFilename,"subcat"); - int iShortName = CSVGetFileFieldId(pszFilename,"short_name"); - int iName = CSVGetFileFieldId(pszFilename,"name"); - int iUnit = CSVGetFileFieldId(pszFilename,"unit"); - int iUnitConv = CSVGetFileFieldId(pszFilename,"unit_conv"); + int iSubcat = CSVGetFileFieldId(osFilename.c_str(),"subcat"); + int iShortName = CSVGetFileFieldId(osFilename.c_str(),"short_name"); + int iName = CSVGetFileFieldId(osFilename.c_str(),"name"); + int iUnit = CSVGetFileFieldId(osFilename.c_str(),"unit"); + int iUnitConv = CSVGetFileFieldId(osFilename.c_str(),"unit_conv"); if( iSubcat < 0 || iShortName < 0 || iName < 0 || iUnit < 0 || iUnitConv < 0 ) { - CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", pszFilename); + CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", osFilename.c_str()); return FALSE; } - CSVRewind(pszFilename); - while( char** papszFields = CSVGetNextLine(pszFilename) ) + CSVRewind(osFilename.c_str()); + while( char** papszFields = CSVGetNextLine(osFilename.c_str()) ) { if( atoi(papszFields[iSubcat]) == subcat ) { @@ -312,24 +312,24 @@ int IsData_MOS (unsigned short int center, unsigned short int subcenter) return ((center == 7) && (subcenter == 14)); } -static const char* GetGrib2LocalTable4_2FileName(int center, +static std::string GetGrib2LocalTable4_2FileName(int center, int subcenter) { - const char* pszFilename = GetGRIB2_CSVFilename("grib2_table_4_2_local_index.csv"); - if( pszFilename == nullptr ) + const std::string osFilename = GetGRIB2_CSVFilename("grib2_table_4_2_local_index.csv"); + if( osFilename.empty() ) { - return nullptr; + return osFilename; } - int iCenter = CSVGetFileFieldId(pszFilename,"center_code"); - int iSubCenter = CSVGetFileFieldId(pszFilename,"subcenter_code"); - int iFilename = CSVGetFileFieldId(pszFilename,"filename"); + int iCenter = CSVGetFileFieldId(osFilename.c_str(),"center_code"); + int iSubCenter = CSVGetFileFieldId(osFilename.c_str(),"subcenter_code"); + int iFilename = CSVGetFileFieldId(osFilename.c_str(),"filename"); if( iCenter < 0 || iSubCenter < 0 || iFilename < 0 ) { - CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", pszFilename); - return nullptr; + CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", osFilename.c_str()); + return std::string(); } - CSVRewind(pszFilename); - while( char** papszFields = CSVGetNextLine(pszFilename) ) + CSVRewind(osFilename.c_str()); + while( char** papszFields = CSVGetNextLine(osFilename.c_str()) ) { if( atoi(papszFields[iCenter]) == center ) { @@ -340,7 +340,7 @@ static const char* GetGrib2LocalTable4_2FileName(int center, } } } - return nullptr; + return std::string(); } /***************************************************************************** @@ -379,26 +379,26 @@ static int GetGrib2LocalTable4_2_Record (int center, const char** unit, unit_convert* convert) { - const char* pszFilename = GetGrib2LocalTable4_2FileName(center, subcenter); - if( pszFilename == nullptr ) + const std::string osFilename = GetGrib2LocalTable4_2FileName(center, subcenter); + if( osFilename.empty() ) { return FALSE; } - int iProd = CSVGetFileFieldId(pszFilename,"prod"); - int iCat = CSVGetFileFieldId(pszFilename,"cat"); - int iSubcat = CSVGetFileFieldId(pszFilename,"subcat"); - int iShortName = CSVGetFileFieldId(pszFilename,"short_name"); - int iName = CSVGetFileFieldId(pszFilename,"name"); - int iUnit = CSVGetFileFieldId(pszFilename,"unit"); - int iUnitConv = CSVGetFileFieldId(pszFilename,"unit_conv"); + int iProd = CSVGetFileFieldId(osFilename.c_str(),"prod"); + int iCat = CSVGetFileFieldId(osFilename.c_str(),"cat"); + int iSubcat = CSVGetFileFieldId(osFilename.c_str(),"subcat"); + int iShortName = CSVGetFileFieldId(osFilename.c_str(),"short_name"); + int iName = CSVGetFileFieldId(osFilename.c_str(),"name"); + int iUnit = CSVGetFileFieldId(osFilename.c_str(),"unit"); + int iUnitConv = CSVGetFileFieldId(osFilename.c_str(),"unit_conv"); if( iProd < 0 || iCat < 0 || iSubcat < 0 || iShortName < 0 || iName < 0 || iUnit < 0 || iUnitConv < 0 ) { - CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", pszFilename); + CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", osFilename.c_str()); return FALSE; } - CSVRewind(pszFilename); - while( char** papszFields = CSVGetNextLine(pszFilename) ) + CSVRewind(osFilename.c_str()); + while( char** papszFields = CSVGetNextLine(osFilename.c_str()) ) { if( atoi(papszFields[iProd]) == prodType && atoi(papszFields[iCat]) == cat && @@ -1786,23 +1786,23 @@ int Table45Lookup (int code, return TRUE; } - const char* pszFilename = GetGRIB2_CSVFilename("grib2_table_4_5.csv"); - if( pszFilename == nullptr ) + const std::string osFilename = GetGRIB2_CSVFilename("grib2_table_4_5.csv"); + if( osFilename.empty() ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find grib2_table_4_5.csv"); return FALSE; } - int iCode = CSVGetFileFieldId(pszFilename,"code"); - int iShortName = CSVGetFileFieldId(pszFilename,"short_name"); - int iName = CSVGetFileFieldId(pszFilename,"name"); - int iUnit = CSVGetFileFieldId(pszFilename,"unit"); + int iCode = CSVGetFileFieldId(osFilename.c_str(),"code"); + int iShortName = CSVGetFileFieldId(osFilename.c_str(),"short_name"); + int iName = CSVGetFileFieldId(osFilename.c_str(),"name"); + int iUnit = CSVGetFileFieldId(osFilename.c_str(),"unit"); if( iCode < 0 || iShortName < 0 || iName < 0 || iUnit < 0 ) { - CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", pszFilename); + CPLError(CE_Failure, CPLE_AppDefined, "Bad structure for %s", osFilename.c_str()); return FALSE; } - CSVRewind(pszFilename); - while( char** papszFields = CSVGetNextLine(pszFilename) ) + CSVRewind(osFilename.c_str()); + while( char** papszFields = CSVGetNextLine(osFilename.c_str()) ) { if( atoi(papszFields[iCode]) == code ) { diff --git a/frmts/grib/gribdataset.cpp b/frmts/grib/gribdataset.cpp index f4f3e26c5b66..f99407267ae7 100644 --- a/frmts/grib/gribdataset.cpp +++ b/frmts/grib/gribdataset.cpp @@ -901,7 +901,7 @@ static bool IsGdalinfoInteractive() osPath.resize(1024); if (CPLGetExecPath(&osPath[0], static_cast(osPath.size()))) { - osPath = CPLGetBasename(osPath.c_str()); + osPath = CPLGetBasenameSafe(osPath.c_str()); } return osPath == "gdalinfo"; } diff --git a/frmts/gti/gdaltileindexdataset.cpp b/frmts/gti/gdaltileindexdataset.cpp index 2f4581c9ee55..79a9ca3ce978 100644 --- a/frmts/gti/gdaltileindexdataset.cpp +++ b/frmts/gti/gdaltileindexdataset.cpp @@ -591,15 +591,17 @@ static std::string GetAbsoluteFileName(const char *pszTileName, const std::string osRet = CPLIsFilenameRelative(osPath.c_str()) ? oSubDSInfo->ModifyPathComponent( - CPLProjectRelativeFilename(CPLGetPath(pszVRTName), - osPath.c_str())) + CPLProjectRelativeFilenameSafe( + CPLGetPathSafe(pszVRTName).c_str(), + osPath.c_str())) : std::string(pszTileName); GDALDestroySubdatasetInfo(oSubDSInfo); return osRet; } const std::string osRelativeMadeAbsolute = - CPLProjectRelativeFilename(CPLGetPath(pszVRTName), pszTileName); + CPLProjectRelativeFilenameSafe(CPLGetPathSafe(pszVRTName).c_str(), + pszTileName); VSIStatBufL sStat; if (VSIStatL(osRelativeMadeAbsolute.c_str(), &sStat) == 0) return osRelativeMadeAbsolute; @@ -2455,7 +2457,7 @@ static int GDALTileIndexDatasetIdentify(GDALOpenInfo *poOpenInfo) return GDAL_IDENTIFY_UNKNOWN; } else if (poOpenInfo->IsSingleAllowedDriver("GTI") && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "gpkg")) + poOpenInfo->IsExtensionEqualToCI("gpkg")) { return true; } @@ -2472,8 +2474,8 @@ static int GDALTileIndexDatasetIdentify(GDALOpenInfo *poOpenInfo) return true; } else if (poOpenInfo->IsSingleAllowedDriver("GTI") && - (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "fgb") || - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "parquet"))) + (poOpenInfo->IsExtensionEqualToCI("fgb") || + poOpenInfo->IsExtensionEqualToCI("parquet"))) { return true; } diff --git a/frmts/gtiff/cogdriver.cpp b/frmts/gtiff/cogdriver.cpp index 310204a64127..15333b6a7490 100644 --- a/frmts/gtiff/cogdriver.cpp +++ b/frmts/gtiff/cogdriver.cpp @@ -62,7 +62,8 @@ static CPLString GetTmpFilename(const char *pszFilename, const char *pszExt) if (!bSupportsRandomWrite || CPLGetConfigOption("CPL_TMPDIR", nullptr) != nullptr) { - osTmpFilename = CPLGenerateTempFilename(CPLGetBasename(pszFilename)); + osTmpFilename = CPLGenerateTempFilenameSafe( + CPLGetBasenameSafe(pszFilename).c_str()); } else osTmpFilename = pszFilename; diff --git a/frmts/gtiff/gtiffdataset_read.cpp b/frmts/gtiff/gtiffdataset_read.cpp index 1ba913fa4e23..06fe176c9cf3 100644 --- a/frmts/gtiff/gtiffdataset_read.cpp +++ b/frmts/gtiff/gtiffdataset_read.cpp @@ -4236,7 +4236,7 @@ void GTiffDataset::LookForProjectionFromXML() return; const std::string osXMLFilenameLowerCase = - CPLResetExtension(m_pszFilename, "xml"); + CPLResetExtensionSafe(m_pszFilename, "xml"); CPLString osXMLFilename; if (papszSiblingFiles && @@ -4270,7 +4270,7 @@ void GTiffDataset::LookForProjectionFromXML() else if (VSIIsCaseSensitiveFS(osXMLFilenameLowerCase.c_str())) { const std::string osXMLFilenameUpperCase = - CPLResetExtension(m_pszFilename, "XML"); + CPLResetExtensionSafe(m_pszFilename, "XML"); bGotXML = VSIStatExL(osXMLFilenameUpperCase.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0; if (bGotXML) @@ -5770,12 +5770,12 @@ CSLConstList GTiffDataset::GetSiblingFiles() m_bHasGotSiblingFiles = true; const int nMaxFiles = atoi(CPLGetConfigOption("GDAL_READDIR_LIMIT_ON_OPEN", "1000")); - CPLStringList aosSiblingFiles( - VSIReadDirEx(CPLGetDirname(m_pszFilename), nMaxFiles)); + const std::string osDirname = CPLGetDirnameSafe(m_pszFilename); + CPLStringList aosSiblingFiles(VSIReadDirEx(osDirname.c_str(), nMaxFiles)); if (nMaxFiles > 0 && aosSiblingFiles.size() > nMaxFiles) { CPLDebug("GTiff", "GDAL_READDIR_LIMIT_ON_OPEN reached on %s", - CPLGetDirname(m_pszFilename)); + osDirname.c_str()); aosSiblingFiles.clear(); } oOvManager.TransferSiblingFiles(aosSiblingFiles.StealList()); @@ -6586,7 +6586,7 @@ void GTiffDataset::LoadMetadata() return; m_bIMDRPCMetadataLoaded = true; - if (EQUAL(CPLGetExtension(GetDescription()), "ovr")) + if (EQUAL(CPLGetExtensionSafe(GetDescription()).c_str(), "ovr")) { // Do not attempt to retrieve metadata files on .tif.ovr files. // For example the Pleiades metadata reader might wrongly associate a diff --git a/frmts/gtiff/gtiffdataset_write.cpp b/frmts/gtiff/gtiffdataset_write.cpp index aa45e94280fc..91f2d910080b 100644 --- a/frmts/gtiff/gtiffdataset_write.cpp +++ b/frmts/gtiff/gtiffdataset_write.cpp @@ -5515,7 +5515,7 @@ TIFF *GTiffDataset::CreateLL(const char *pszFilename, int nXSize, int nYSize, CPLTestBool(CPLGetConfigOption("CHECK_DISK_FREE_SPACE", "TRUE"))) { GIntBig nFreeDiskSpace = - VSIGetDiskFreeSpace(CPLGetDirname(pszFilename)); + VSIGetDiskFreeSpace(CPLGetDirnameSafe(pszFilename).c_str()); if (nFreeDiskSpace >= 0 && nFreeDiskSpace < dfUncompressedImageSize) { ReportError(pszFilename, CE_Failure, CPLE_FileIO, diff --git a/frmts/hdf4/hdf4imagedataset.cpp b/frmts/hdf4/hdf4imagedataset.cpp index e5a6084feed8..f51cb69949f0 100644 --- a/frmts/hdf4/hdf4imagedataset.cpp +++ b/frmts/hdf4/hdf4imagedataset.cpp @@ -288,7 +288,7 @@ CPLErr HDF4ImageRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, /* to look in to find the external files. Normally this is the */ /* directory holding the hdf file. */ /* -------------------------------------------------------------------- */ - HXsetdir(CPLGetPath(poGDS->pszFilename)); + HXsetdir(CPLGetPathSafe(poGDS->pszFilename).c_str()); /* -------------------------------------------------------------------- */ /* Handle different configurations. */ diff --git a/frmts/hdf4/hdf4multidim.cpp b/frmts/hdf4/hdf4multidim.cpp index c725e660c482..6216020cd043 100644 --- a/frmts/hdf4/hdf4multidim.cpp +++ b/frmts/hdf4/hdf4multidim.cpp @@ -1635,7 +1635,7 @@ static bool ReadPixels(const GUInt64 *arrayStartIdx, const size_t *count, /* to look in to find the external files. Normally this is the */ /* directory holding the hdf file. */ /* -------------------------------------------------------------------- */ - HXsetdir(CPLGetPath(poShared->GetFilename().c_str())); + HXsetdir(CPLGetPathSafe(poShared->GetFilename().c_str()).c_str()); const size_t nDims(dims.size()); std::vector sw_start(nDims); @@ -3042,7 +3042,7 @@ bool HDF4GRArray::IRead(const GUInt64 *arrayStartIdx, const size_t *count, /* to look in to find the external files. Normally this is the */ /* directory holding the hdf file. */ /* -------------------------------------------------------------------- */ - HXsetdir(CPLGetPath(m_poShared->GetFilename().c_str())); + HXsetdir(CPLGetPathSafe(m_poShared->GetFilename().c_str()).c_str()); const size_t nDims(m_dims.size()); std::vector sw_start(nDims); diff --git a/frmts/hdf5/hdf5drivercore.cpp b/frmts/hdf5/hdf5drivercore.cpp index 41d23084cca5..d866323f3332 100644 --- a/frmts/hdf5/hdf5drivercore.cpp +++ b/frmts/hdf5/hdf5drivercore.cpp @@ -34,7 +34,7 @@ int HDF5DatasetIdentify(GDALOpenInfo *poOpenInfo) if (!poOpenInfo->pabyHeader) return FALSE; - const CPLString osExt(CPLGetExtension(poOpenInfo->pszFilename)); + const CPLString osExt(poOpenInfo->osExtension); const auto IsRecognizedByNetCDFDriver = [&osExt, poOpenInfo]() { @@ -345,7 +345,7 @@ int BAGDatasetIdentify(GDALOpenInfo *poOpenInfo) return FALSE; // Does it have the extension .bag? - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "bag")) + if (!poOpenInfo->IsExtensionEqualToCI("bag")) { if (poOpenInfo->IsSingleAllowedDriver("BAG")) { diff --git a/frmts/hdf5/s100.cpp b/frmts/hdf5/s100.cpp index 86762b3a921d..2a6c3fd1e202 100644 --- a/frmts/hdf5/s100.cpp +++ b/frmts/hdf5/s100.cpp @@ -417,8 +417,9 @@ std::string S100ReadMetadata(GDALDataset *poDS, const std::string &osFilename, const char *pszVal = poAttr->ReadAsString(); if (pszVal && pszVal[0]) { - osMetadataFile = CPLFormFilename(CPLGetPath(osFilename.c_str()), - pszVal, nullptr); + osMetadataFile = CPLFormFilenameSafe( + CPLGetPathSafe(osFilename.c_str()).c_str(), pszVal, + nullptr); VSIStatBufL sStat; if (VSIStatL(osMetadataFile.c_str(), &sStat) != 0) { @@ -427,9 +428,9 @@ std::string S100ReadMetadata(GDALDataset *poDS, const std::string &osFilename, // but the actual filename does not start with "MD_"... if (STARTS_WITH(pszVal, "MD_")) { - osMetadataFile = - CPLFormFilename(CPLGetPath(osFilename.c_str()), - pszVal + strlen("MD_"), nullptr); + osMetadataFile = CPLFormFilenameSafe( + CPLGetPathSafe(osFilename.c_str()).c_str(), + pszVal + strlen("MD_"), nullptr); if (VSIStatL(osMetadataFile.c_str(), &sStat) != 0) { osMetadataFile.clear(); diff --git a/frmts/hf2/hf2dataset.cpp b/frmts/hf2/hf2dataset.cpp index 9732af4c1878..94456bba20f7 100644 --- a/frmts/hf2/hf2dataset.cpp +++ b/frmts/hf2/hf2dataset.cpp @@ -381,7 +381,7 @@ int HF2Dataset::Identify(GDALOpenInfo *poOpenInfo) /* GZipped .hf2 files are common, so automagically open them */ /* if the /vsigzip/ has not been explicitly passed */ CPLString osFilename; // keep in that scope - if ((EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "hfz") || + if ((poOpenInfo->IsExtensionEqualToCI("hfz") || (strlen(poOpenInfo->pszFilename) > 6 && EQUAL(poOpenInfo->pszFilename + strlen(poOpenInfo->pszFilename) - 6, "hf2.gz"))) && @@ -425,7 +425,7 @@ GDALDataset *HF2Dataset::Open(GDALOpenInfo *poOpenInfo) /* GZipped .hf2 files are common, so automagically open them */ /* if the /vsigzip/ has not been explicitly passed */ CPLString osFilename(poOpenInfo->pszFilename); - if ((EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "hfz") || + if ((poOpenInfo->IsExtensionEqualToCI("hfz") || (strlen(poOpenInfo->pszFilename) > 6 && EQUAL(poOpenInfo->pszFilename + strlen(poOpenInfo->pszFilename) - 6, "hf2.gz"))) && diff --git a/frmts/hfa/hfa.h b/frmts/hfa/hfa.h index 4f0698024a77..5d39d1d4a139 100644 --- a/frmts/hfa/hfa.h +++ b/frmts/hfa/hfa.h @@ -148,7 +148,6 @@ CPLErr HFARenameReferences(HFAHandle, const char *, const char *); HFAHandle CPL_DLL HFACreateLL(const char *pszFilename); HFAHandle CPL_DLL HFACreate(const char *pszFilename, int nXSize, int nYSize, int nBands, EPTType eDataType, char **papszOptions); -const char CPL_DLL *HFAGetIGEFilename(HFAHandle); CPLErr CPL_DLL HFAFlush(HFAHandle); int CPL_DLL HFACreateOverview(HFAHandle hHFA, int nBand, int nOverviewLevel, const char *pszResampling); @@ -302,4 +301,12 @@ const char CPL_DLL *HFAReadElevationUnit(HFAHandle psInfo, int iBand); CPL_C_END +#ifdef __cplusplus +extern "C++" +{ +#include + std::string HFAGetIGEFilename(HFAHandle); +} +#endif + #endif /* ndef HFAOPEN_H_INCLUDED */ diff --git a/frmts/hfa/hfaband.cpp b/frmts/hfa/hfaband.cpp index c4d17573c80e..a1d9345f2495 100644 --- a/frmts/hfa/hfaband.cpp +++ b/frmts/hfa/hfaband.cpp @@ -174,10 +174,10 @@ CPLErr HFABand::LoadOverviews() if (psHFA == nullptr) { char *pszBasename = - CPLStrdup(CPLGetBasename(psInfo->pszFilename)); + CPLStrdup(CPLGetBasenameSafe(psInfo->pszFilename).c_str()); - pszJustFilename = - CPLStrdup(CPLFormFilename(nullptr, pszBasename, "rrd")); + pszJustFilename = CPLStrdup( + CPLFormFilenameSafe(nullptr, pszBasename, "rrd").c_str()); CPLDebug("HFA", "Failed to find overview file with " "expected name, try %s instead.", @@ -233,12 +233,13 @@ CPLErr HFABand::LoadOverviews() HFAEntry *poBandProxyNode = poNode; HFAInfo_t *psOvHFA = psInfo; - if (nOverviews == 0 && EQUAL(CPLGetExtension(psInfo->pszFilename), "aux")) + if (nOverviews == 0 && + EQUAL(CPLGetExtensionSafe(psInfo->pszFilename).c_str(), "aux")) { const CPLString osRRDFilename = - CPLResetExtension(psInfo->pszFilename, "rrd"); + CPLResetExtensionSafe(psInfo->pszFilename, "rrd"); const CPLString osFullRRD = - CPLFormFilename(psInfo->pszPath, osRRDFilename, nullptr); + CPLFormFilenameSafe(psInfo->pszPath, osRRDFilename, nullptr); VSIStatBufL sStatBuf; if (VSIStatL(osFullRRD, &sStatBuf) == 0) @@ -463,8 +464,8 @@ CPLErr HFABand::LoadExternalBlockInfo() nLayerStackIndex = poDMS->GetIntField("layerStackIndex"); // Open raw data file. - const char *pszFullFilename = HFAGetIGEFilename(psInfo); - if (pszFullFilename == nullptr) + const std::string osFullFilename = HFAGetIGEFilename(psInfo); + if (osFullFilename.empty()) { CPLError(CE_Failure, CPLE_OpenFailed, "Cannot find external data file name"); @@ -472,13 +473,14 @@ CPLErr HFABand::LoadExternalBlockInfo() } if (psInfo->eAccess == HFA_ReadOnly) - fpExternal = VSIFOpenL(pszFullFilename, "rb"); + fpExternal = VSIFOpenL(osFullFilename.c_str(), "rb"); else - fpExternal = VSIFOpenL(pszFullFilename, "r+b"); + fpExternal = VSIFOpenL(osFullFilename.c_str(), "r+b"); if (fpExternal == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Unable to open external data file: %s", pszFullFilename); + "Unable to open external data file: %s", + osFullFilename.c_str()); return CE_Failure; } @@ -489,7 +491,8 @@ CPLErr HFABand::LoadExternalBlockInfo() !STARTS_WITH(szHeader, "ERDAS_IMG_EXTERNAL_RASTER")) { CPLError(CE_Failure, CPLE_AppDefined, - "Raw data file %s appears to be corrupt.", pszFullFilename); + "Raw data file %s appears to be corrupt.", + osFullFilename.c_str()); return CE_Failure; } diff --git a/frmts/hfa/hfadataset.cpp b/frmts/hfa/hfadataset.cpp index e0f12c1b4485..132796775eb0 100644 --- a/frmts/hfa/hfadataset.cpp +++ b/frmts/hfa/hfadataset.cpp @@ -2624,9 +2624,9 @@ CPLErr HFARasterBand::CleanOverviews() // this. if (hHFA->psDependent != hHFA && hHFA->psDependent != nullptr) { - CPLString osFilename = - CPLFormFilename(hHFA->psDependent->pszPath, - hHFA->psDependent->pszFilename, nullptr); + const CPLString osFilename = + CPLFormFilenameSafe(hHFA->psDependent->pszPath, + hHFA->psDependent->pszFilename, nullptr); CPL_IGNORE_RET_VAL(HFAClose(hHFA->psDependent)); hHFA->psDependent = nullptr; @@ -4727,11 +4727,12 @@ const GDAL_GCP *HFADataset::GetGCPs() char **HFADataset::GetFileList() { - char **papszFileList = GDALPamDataset::GetFileList(); + CPLStringList oFileList(GDALPamDataset::GetFileList()); - if (HFAGetIGEFilename(hHFA) != nullptr) + const std::string osIGEFilename = HFAGetIGEFilename(hHFA); + if (!osIGEFilename.empty()) { - papszFileList = CSLAddString(papszFileList, HFAGetIGEFilename(hHFA)); + oFileList.push_back(osIGEFilename); } // Request an overview to force opening of dependent overview files. @@ -4742,16 +4743,15 @@ char **HFADataset::GetFileList() { HFAInfo_t *psDep = hHFA->psDependent; - papszFileList = CSLAddString( - papszFileList, - CPLFormFilename(psDep->pszPath, psDep->pszFilename, nullptr)); + oFileList.push_back( + CPLFormFilenameSafe(psDep->pszPath, psDep->pszFilename, nullptr)); - if (HFAGetIGEFilename(psDep) != nullptr) - papszFileList = - CSLAddString(papszFileList, HFAGetIGEFilename(psDep)); + const std::string osIGEFilenameDep = HFAGetIGEFilename(psDep); + if (!osIGEFilenameDep.empty()) + oFileList.push_back(osIGEFilenameDep); } - return papszFileList; + return oFileList.StealList(); } /************************************************************************/ @@ -4894,8 +4894,8 @@ CPLErr HFADataset::Rename(const char *pszNewName, const char *pszOldName) return eErr; // Now try to go into the .img file and update RRDNames[] lists. - CPLString osOldBasename = CPLGetBasename(pszOldName); - CPLString osNewBasename = CPLGetBasename(pszNewName); + CPLString osOldBasename = CPLGetBasenameSafe(pszOldName); + CPLString osNewBasename = CPLGetBasenameSafe(pszNewName); if (osOldBasename != osNewBasename) { @@ -4936,8 +4936,8 @@ CPLErr HFADataset::CopyFiles(const char *pszNewName, const char *pszOldName) return eErr; // Now try to go into the .img file and update RRDNames[] lists. - CPLString osOldBasename = CPLGetBasename(pszOldName); - CPLString osNewBasename = CPLGetBasename(pszNewName); + CPLString osOldBasename = CPLGetBasenameSafe(pszOldName); + CPLString osNewBasename = CPLGetBasenameSafe(pszNewName); if (osOldBasename != osNewBasename) { diff --git a/frmts/hfa/hfaopen.cpp b/frmts/hfa/hfaopen.cpp index 3e13ddd03001..0d1192683c5d 100644 --- a/frmts/hfa/hfaopen.cpp +++ b/frmts/hfa/hfaopen.cpp @@ -201,7 +201,7 @@ HFAHandle HFAOpen(const char *pszFilename, const char *pszAccess) static_cast(CPLCalloc(sizeof(HFAInfo_t), 1)); psInfo->pszFilename = CPLStrdup(CPLGetFilename(pszFilename)); - psInfo->pszPath = CPLStrdup(CPLGetPath(pszFilename)); + psInfo->pszPath = CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); psInfo->fp = fp; if (EQUAL(pszAccess, "r") || EQUAL(pszAccess, "rb")) psInfo->eAccess = HFA_ReadOnly; @@ -278,9 +278,9 @@ HFAInfo_t *HFACreateDependent(HFAInfo_t *psBase) return psBase->psDependent; // Create desired RRD filename. - const CPLString oBasename = CPLGetBasename(psBase->pszFilename); + const CPLString oBasename = CPLGetBasenameSafe(psBase->pszFilename); const CPLString oRRDFilename = - CPLFormFilename(psBase->pszPath, oBasename, "rrd"); + CPLFormFilenameSafe(psBase->pszPath, oBasename, "rrd"); // Does this file already exist? If so, re-use it. VSILFILE *fp = VSIFOpenL(oRRDFilename, "rb"); @@ -340,8 +340,8 @@ HFAInfo_t *HFAGetDependent(HFAInfo_t *psBase, const char *pszFilename) // Try to open the dependent file. const char *pszMode = psBase->eAccess == HFA_Update ? "r+b" : "rb"; - char *pszDependent = - CPLStrdup(CPLFormFilename(psBase->pszPath, pszFilename, nullptr)); + char *pszDependent = CPLStrdup( + CPLFormFilenameSafe(psBase->pszPath, pszFilename, nullptr).c_str()); VSILFILE *fp = VSIFOpenL(pszDependent, pszMode); if (fp != nullptr) @@ -531,8 +531,9 @@ CPLErr HFADelete(const char *pszFilename) poDMS->GetStringField("fileName.string"); if (pszRawFilename != nullptr) - HFARemove( - CPLFormFilename(psInfo->pszPath, pszRawFilename, nullptr)); + HFARemove(CPLFormFilenameSafe(psInfo->pszPath, pszRawFilename, + nullptr) + .c_str()); } CPL_IGNORE_RET_VAL(HFAClose(psInfo)); @@ -1808,7 +1809,7 @@ HFAHandle HFACreateLL(const char *pszFilename) psInfo->pProParameters = nullptr; psInfo->bTreeDirty = false; psInfo->pszFilename = CPLStrdup(CPLGetFilename(pszFilename)); - psInfo->pszPath = CPLStrdup(CPLGetPath(pszFilename)); + psInfo->pszPath = CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); // Write out the Ehfa_HeaderTag. bool bRet = VSIFWriteL((void *)"EHFA_HEADER_TAG", 1, 16, fp) > 0; @@ -1873,18 +1874,18 @@ HFAHandle HFACreateLL(const char *pszFilename) // If an .ige or .rrd file exists with the same base name, // delete them. (#1784) - CPLString osExtension = CPLGetExtension(pszFilename); + CPLString osExtension = CPLGetExtensionSafe(pszFilename); if (!EQUAL(osExtension, "rrd") && !EQUAL(osExtension, "aux")) { - CPLString osPath = CPLGetPath(pszFilename); - CPLString osBasename = CPLGetBasename(pszFilename); + CPLString osPath = CPLGetPathSafe(pszFilename); + CPLString osBasename = CPLGetBasenameSafe(pszFilename); VSIStatBufL sStatBuf; - CPLString osSupFile = CPLFormCIFilename(osPath, osBasename, "rrd"); + CPLString osSupFile = CPLFormCIFilenameSafe(osPath, osBasename, "rrd"); if (VSIStatL(osSupFile, &sStatBuf) == 0) VSIUnlink(osSupFile); - osSupFile = CPLFormCIFilename(osPath, osBasename, "ige"); + osSupFile = CPLFormCIFilenameSafe(osPath, osBasename, "ige"); if (VSIStatL(osSupFile, &sStatBuf) == 0) VSIUnlink(osSupFile); @@ -2881,7 +2882,7 @@ CPLErr HFASetMetadata(HFAHandle hHFA, int nBand, char **papszMD) /* NOTE: Returns full path, not just the filename portion. */ /************************************************************************/ -const char *HFAGetIGEFilename(HFAHandle hHFA) +std::string HFAGetIGEFilename(HFAHandle hHFA) { if (hHFA->pszIGEFilename == nullptr) @@ -2900,21 +2901,23 @@ const char *HFAGetIGEFilename(HFAHandle hHFA) if (pszRawFilename != nullptr) { VSIStatBufL sStatBuf; - CPLString osFullFilename = - CPLFormFilename(hHFA->pszPath, pszRawFilename, nullptr); + std::string osFullFilename = + CPLFormFilenameSafe(hHFA->pszPath, pszRawFilename, nullptr); - if (VSIStatL(osFullFilename, &sStatBuf) != 0) + if (VSIStatL(osFullFilename.c_str(), &sStatBuf) != 0) { const CPLString osExtension = - CPLGetExtension(pszRawFilename); + CPLGetExtensionSafe(pszRawFilename); const CPLString osBasename = - CPLGetBasename(hHFA->pszFilename); - osFullFilename = - CPLFormFilename(hHFA->pszPath, osBasename, osExtension); - - if (VSIStatL(osFullFilename, &sStatBuf) == 0) - hHFA->pszIGEFilename = CPLStrdup( - CPLFormFilename(nullptr, osBasename, osExtension)); + CPLGetBasenameSafe(hHFA->pszFilename); + osFullFilename = CPLFormFilenameSafe( + hHFA->pszPath, osBasename, osExtension); + + if (VSIStatL(osFullFilename.c_str(), &sStatBuf) == 0) + hHFA->pszIGEFilename = + CPLStrdup(CPLFormFilenameSafe(nullptr, osBasename, + osExtension) + .c_str()); else hHFA->pszIGEFilename = CPLStrdup(pszRawFilename); } @@ -2928,9 +2931,10 @@ const char *HFAGetIGEFilename(HFAHandle hHFA) // Return the full filename. if (hHFA->pszIGEFilename) - return CPLFormFilename(hHFA->pszPath, hHFA->pszIGEFilename, nullptr); + return CPLFormFilenameSafe(hHFA->pszPath, hHFA->pszIGEFilename, + nullptr); - return nullptr; + return std::string(); } /************************************************************************/ @@ -2955,19 +2959,21 @@ bool HFACreateSpillStack(HFAInfo_t *psInfo, int nXSize, int nYSize, int nLayers, if (psInfo->pszIGEFilename == nullptr) { - if (EQUAL(CPLGetExtension(psInfo->pszFilename), "rrd")) - psInfo->pszIGEFilename = - CPLStrdup(CPLResetExtension(psInfo->pszFilename, "rde")); - else if (EQUAL(CPLGetExtension(psInfo->pszFilename), "aux")) - psInfo->pszIGEFilename = - CPLStrdup(CPLResetExtension(psInfo->pszFilename, "axe")); + const auto osExt = CPLGetExtensionSafe(psInfo->pszFilename); + if (EQUAL(osExt.c_str(), "rrd")) + psInfo->pszIGEFilename = CPLStrdup( + CPLResetExtensionSafe(psInfo->pszFilename, "rde").c_str()); + else if (EQUAL(osExt.c_str(), "aux")) + psInfo->pszIGEFilename = CPLStrdup( + CPLResetExtensionSafe(psInfo->pszFilename, "axe").c_str()); else - psInfo->pszIGEFilename = - CPLStrdup(CPLResetExtension(psInfo->pszFilename, "ige")); + psInfo->pszIGEFilename = CPLStrdup( + CPLResetExtensionSafe(psInfo->pszFilename, "ige").c_str()); } char *pszFullFilename = CPLStrdup( - CPLFormFilename(psInfo->pszPath, psInfo->pszIGEFilename, nullptr)); + CPLFormFilenameSafe(psInfo->pszPath, psInfo->pszIGEFilename, nullptr) + .c_str()); // Try and open it. If we fail, create it and write the magic header. static const char *const pszMagick = "ERDAS_IMG_EXTERNAL_RASTER"; diff --git a/frmts/http/httpdriver.cpp b/frmts/http/httpdriver.cpp index 3b15354e9543..333de6686ab0 100644 --- a/frmts/http/httpdriver.cpp +++ b/frmts/http/httpdriver.cpp @@ -174,12 +174,13 @@ static GDALDataset *HTTPOpen(GDALOpenInfo *poOpenInfo) CPLString osTempFilename; #ifdef _WIN32 - const char *pszPath = CPLGetPath(CPLGenerateTempFilename(NULL)); + const std::string osPath = + CPLGetPathSafe(CPLGenerateTempFilenameSafe(NULL).c_str()); #else - const char *pszPath = "/tmp"; + const std::string osPath = "/tmp"; #endif - osTempFilename = - CPLFormFilename(pszPath, CPLGetFilename(osResultFilename), nullptr); + osTempFilename = CPLFormFilenameSafe( + osPath.c_str(), CPLGetFilename(osResultFilename), nullptr); if (CPLCopyFile(osTempFilename, osResultFilename) != 0) { CPLError(CE_Failure, CPLE_OpenFailed, diff --git a/frmts/idrisi/IdrisiDataset.cpp b/frmts/idrisi/IdrisiDataset.cpp index c5e3db0cf50a..0618a8bd5924 100644 --- a/frmts/idrisi/IdrisiDataset.cpp +++ b/frmts/idrisi/IdrisiDataset.cpp @@ -541,28 +541,28 @@ IdrisiDataset::~IdrisiDataset() GDALDataset *IdrisiDataset::Open(GDALOpenInfo *poOpenInfo) { if ((poOpenInfo->fpL == nullptr) || - (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), extRST) == - FALSE)) // modified + (poOpenInfo->IsExtensionEqualToCI(extRST) == FALSE)) // modified return nullptr; // -------------------------------------------------------------------- // Check the documentation file .rdc // -------------------------------------------------------------------- - const char *pszLDocFilename = - CPLResetExtension(poOpenInfo->pszFilename, extRDC); + std::string osLDocFilename = + CPLResetExtensionSafe(poOpenInfo->pszFilename, extRDC); - if (!FileExists(pszLDocFilename)) + if (!FileExists(osLDocFilename.c_str())) { - pszLDocFilename = CPLResetExtension(poOpenInfo->pszFilename, extRDCu); + osLDocFilename = + CPLResetExtensionSafe(poOpenInfo->pszFilename, extRDCu); - if (!FileExists(pszLDocFilename)) + if (!FileExists(osLDocFilename.c_str())) { return nullptr; } } - char **papszLRDC = CSLLoad(pszLDocFilename); + char **papszLRDC = CSLLoad(osLDocFilename.c_str()); myCSLSetNameValueSeparator(papszLRDC, ":"); @@ -598,7 +598,7 @@ GDALDataset *IdrisiDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; } - poDS->pszDocFilename = CPLStrdup(pszLDocFilename); + poDS->pszDocFilename = CPLStrdup(osLDocFilename.c_str()); poDS->papszRDC = CSLDuplicate(papszLRDC); CSLDestroy(papszLRDC); @@ -711,9 +711,9 @@ GDALDataset *IdrisiDataset::Open(GDALOpenInfo *poOpenInfo) if (poDS->nBands != 3) { - const char *pszSMPFilename = - CPLResetExtension(poDS->pszFilename, extSMP); - VSILFILE *fpSMP = VSIFOpenL(pszSMPFilename, "rb"); + const std::string osSMPFilename = + CPLResetExtensionSafe(poDS->pszFilename, extSMP); + VSILFILE *fpSMP = VSIFOpenL(osSMPFilename.c_str(), "rb"); if (fpSMP != nullptr) { int dfMaxValue = @@ -968,10 +968,11 @@ GDALDataset *IdrisiDataset::Create(const char *pszFilename, int nXSize, papszLRDC = CSLAddNameValue(papszLRDC, rdcLINEAGES, ""); papszLRDC = CSLAddNameValue(papszLRDC, rdcCOMMENTS, ""); - const char *pszLDocFilename = CPLResetExtension(pszFilename, extRDC); + const std::string osLDocFilename = + CPLResetExtensionSafe(pszFilename, extRDC); myCSLSetNameValueSeparator(papszLRDC, ": "); - SaveAsCRLF(papszLRDC, pszLDocFilename); + SaveAsCRLF(papszLRDC, osLDocFilename.c_str()); CSLDestroy(papszLRDC); // ---------------------------------------------------------------- @@ -1201,19 +1202,19 @@ char **IdrisiDataset::GetFileList() // Symbol table file // -------------------------------------------------------------------- - const char *pszAssociated = CPLResetExtension(pszFilename, extSMP); + std::string osAssociated = CPLResetExtensionSafe(pszFilename, extSMP); - if (FileExists(pszAssociated)) + if (FileExists(osAssociated.c_str())) { - papszFileList = CSLAddString(papszFileList, pszAssociated); + papszFileList = CSLAddString(papszFileList, osAssociated.c_str()); } else { - pszAssociated = CPLResetExtension(pszFilename, extSMPu); + osAssociated = CPLResetExtensionSafe(pszFilename, extSMPu); - if (FileExists(pszAssociated)) + if (FileExists(osAssociated.c_str())) { - papszFileList = CSLAddString(papszFileList, pszAssociated); + papszFileList = CSLAddString(papszFileList, osAssociated.c_str()); } } @@ -1221,19 +1222,19 @@ char **IdrisiDataset::GetFileList() // Documentation file // -------------------------------------------------------------------- - pszAssociated = CPLResetExtension(pszFilename, extRDC); + osAssociated = CPLResetExtensionSafe(pszFilename, extRDC); - if (FileExists(pszAssociated)) + if (FileExists(osAssociated.c_str())) { - papszFileList = CSLAddString(papszFileList, pszAssociated); + papszFileList = CSLAddString(papszFileList, osAssociated.c_str()); } else { - pszAssociated = CPLResetExtension(pszFilename, extRDCu); + osAssociated = CPLResetExtensionSafe(pszFilename, extRDCu); - if (FileExists(pszAssociated)) + if (FileExists(osAssociated.c_str())) { - papszFileList = CSLAddString(papszFileList, pszAssociated); + papszFileList = CSLAddString(papszFileList, osAssociated.c_str()); } } @@ -1241,19 +1242,19 @@ char **IdrisiDataset::GetFileList() // Reference file // -------------------------------------------------------------------- - pszAssociated = CPLResetExtension(pszFilename, extREF); + osAssociated = CPLResetExtensionSafe(pszFilename, extREF); - if (FileExists(pszAssociated)) + if (FileExists(osAssociated.c_str())) { - papszFileList = CSLAddString(papszFileList, pszAssociated); + papszFileList = CSLAddString(papszFileList, osAssociated.c_str()); } else { - pszAssociated = CPLResetExtension(pszFilename, extREFu); + osAssociated = CPLResetExtensionSafe(pszFilename, extREFu); - if (FileExists(pszAssociated)) + if (FileExists(osAssociated.c_str())) { - papszFileList = CSLAddString(papszFileList, pszAssociated); + papszFileList = CSLAddString(papszFileList, osAssociated.c_str()); } } @@ -1852,8 +1853,9 @@ CPLErr IdrisiRasterBand::SetColorTable(GDALColorTable *poColorTable) poGDS->poColorTable = poColorTable->Clone(); - const char *pszSMPFilename = CPLResetExtension(poGDS->pszFilename, extSMP); - VSILFILE *fpSMP = VSIFOpenL(pszSMPFilename, "w"); + const std::string osSMPFilename = + CPLResetExtensionSafe(poGDS->pszFilename, extSMP); + VSILFILE *fpSMP = VSIFOpenL(osSMPFilename.c_str(), "w"); if (fpSMP != nullptr) { @@ -2394,8 +2396,9 @@ CPLErr IdrisiGeoReference2Wkt(const char *pszFilename, const char *pszRefSystem, // Search for georeference file .ref // ------------------------------------------------------------------ - const char *pszFName = CPLSPrintf("%s%c%s.ref", CPLGetDirname(pszFilename), - PATHDELIM, pszRefSystem); + const char *pszFName = + CPLSPrintf("%s%c%s.ref", CPLGetDirnameSafe(pszFilename).c_str(), + PATHDELIM, pszRefSystem); if (!FileExists(pszFName)) { @@ -3130,10 +3133,10 @@ CPLErr IdrisiDataset::Wkt2GeoReference(const OGRSpatialReference &oSRS, papszRef = CSLAddNameValue(papszRef, refSTANDL_2, CPLSPrintf("%.9g", dfStdP2)); myCSLSetNameValueSeparator(papszRef, ": "); - SaveAsCRLF(papszRef, CPLResetExtension(pszFilename, extREF)); + SaveAsCRLF(papszRef, CPLResetExtensionSafe(pszFilename, extREF).c_str()); CSLDestroy(papszRef); - *pszRefSystem = CPLStrdup(CPLGetBasename(pszFilename)); + *pszRefSystem = CPLStrdup(CPLGetBasenameSafe(pszFilename).c_str()); *pszRefUnit = CPLStrdup(pszLinearUnit); CPLFree(pszGeorefName); diff --git a/frmts/ilwis/ilwiscoordinatesystem.cpp b/frmts/ilwis/ilwiscoordinatesystem.cpp index 56f4aa95bddf..5c2f799ad574 100644 --- a/frmts/ilwis/ilwiscoordinatesystem.cpp +++ b/frmts/ilwis/ilwiscoordinatesystem.cpp @@ -995,9 +995,9 @@ CPLErr ILWISDataset::WriteProjection() { OGRSpatialReference *poGeogSRS = nullptr; - std::string csFileName = CPLResetExtension(osFileName, "csy"); - std::string pszBaseName = std::string(CPLGetBasename(osFileName)); - // std::string pszPath = std::string(CPLGetPath( osFileName )); + std::string csFileName = CPLResetExtensionSafe(osFileName, "csy"); + std::string pszBaseName = std::string(CPLGetBasenameSafe(osFileName)); + // std::string pszPath = std::string(CPLGetPathSafe( osFileName )); const bool bHaveSRS = !m_oSRS.IsEmpty(); const IlwisDatums *piwDatum = iwDatums; @@ -1013,7 +1013,7 @@ CPLErr ILWISDataset::WriteProjection() poGeogSRS = m_oSRS.CloneGeogCS(); } - std::string grFileName = CPLResetExtension(osFileName, "grf"); + std::string grFileName = CPLResetExtensionSafe(osFileName, "grf"); std::string csy; if (poGeogSRS) { diff --git a/frmts/ilwis/ilwisdataset.cpp b/frmts/ilwis/ilwisdataset.cpp index 60ac1a4c1853..4dcdbbf10349 100644 --- a/frmts/ilwis/ilwisdataset.cpp +++ b/frmts/ilwis/ilwisdataset.cpp @@ -481,10 +481,10 @@ ILWISDataset::~ILWISDataset() /* the transform coefficients from the extent and pixelsize */ /************************************************************************/ -void ILWISDataset::CollectTransformCoef(std::string &pszRefName) +void ILWISDataset::CollectTransformCoef(std::string &osRefname) { - pszRefName = ""; + osRefname = ""; std::string georef; if (EQUAL(pszFileType.c_str(), "Map")) georef = ReadElement("Map", "GeoRef", osFileName); @@ -496,28 +496,24 @@ void ILWISDataset::CollectTransformCoef(std::string &pszRefName) if (!georef.empty() && !EQUAL(georef.c_str(), "none")) { // Form the geo-referencing name - std::string osBaseName = std::string(CPLGetBasename(georef.c_str())); - std::string osPath = std::string(CPLGetPath(osFileName)); - pszRefName = std::string( - CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "grf")); + const std::string osBaseName = CPLGetBasenameSafe(georef.c_str()); + const std::string osPath = CPLGetPathSafe(osFileName); + osRefname = + CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), "grf"); // Check the geo-reference type,support for the GeoRefCorners only - std::string georeftype = ReadElement("GeoRef", "Type", pszRefName); + std::string georeftype = ReadElement("GeoRef", "Type", osRefname); if (EQUAL(georeftype.c_str(), "GeoRefCorners")) { // Center or top-left corner of the pixel approach? std::string IsCorner = - ReadElement("GeoRefCorners", "CornersOfCorners", pszRefName); + ReadElement("GeoRefCorners", "CornersOfCorners", osRefname); // Collect the extent of the coordinates - std::string sMinX = - ReadElement("GeoRefCorners", "MinX", pszRefName); - std::string sMinY = - ReadElement("GeoRefCorners", "MinY", pszRefName); - std::string sMaxX = - ReadElement("GeoRefCorners", "MaxX", pszRefName); - std::string sMaxY = - ReadElement("GeoRefCorners", "MaxY", pszRefName); + std::string sMinX = ReadElement("GeoRefCorners", "MinX", osRefname); + std::string sMinY = ReadElement("GeoRefCorners", "MinY", osRefname); + std::string sMaxX = ReadElement("GeoRefCorners", "MaxX", osRefname); + std::string sMaxY = ReadElement("GeoRefCorners", "MaxY", osRefname); // Calculate pixel size in X and Y direction from the extent double deltaX = CPLAtof(sMaxX.c_str()) - CPLAtof(sMinX.c_str()); @@ -569,7 +565,7 @@ void ILWISDataset::WriteGeoReference() double dURLat = (adfGeoTransform[3]); double dURLong = (adfGeoTransform[0] + nXSize * adfGeoTransform[1]); - std::string grFileName = CPLResetExtension(osFileName, "grf"); + std::string grFileName = CPLResetExtensionSafe(osFileName, "grf"); WriteElement("Ilwis", "Type", grFileName, "GeoRef"); WriteElement("GeoRef", "lines", grFileName, nYSize); WriteElement("GeoRef", "columns", grFileName, nXSize); @@ -583,8 +579,8 @@ void ILWISDataset::WriteGeoReference() // Re-write the GeoRef property to raster ODF // Form band file name - std::string sBaseName = std::string(CPLGetBasename(osFileName)); - std::string sPath = std::string(CPLGetPath(osFileName)); + std::string sBaseName = std::string(CPLGetBasenameSafe(osFileName)); + std::string sPath = std::string(CPLGetPathSafe(osFileName)); if (nBands == 1) { WriteElement("Map", "GeoRef", osFileName, sBaseName + ".grf"); @@ -599,9 +595,9 @@ void ILWISDataset::WriteGeoReference() char szName[100]; snprintf(szName, sizeof(szName), "%s_band_%d", sBaseName.c_str(), iBand + 1); - std::string pszODFName = std::string( - CPLFormFilename(sPath.c_str(), szName, "mpr")); - WriteElement("Map", "GeoRef", pszODFName, + const std::string osODFName = + CPLFormFilenameSafe(sPath.c_str(), szName, "mpr"); + WriteElement("Map", "GeoRef", osODFName, sBaseName + ".grf"); } } @@ -684,9 +680,11 @@ GDALDataset *ILWISDataset::Open(GDALOpenInfo *poOpenInfo) if (poOpenInfo->nHeaderBytes < 1) return nullptr; - std::string sExt = CPLGetExtension(poOpenInfo->pszFilename); - if (!EQUAL(sExt.c_str(), "mpr") && !EQUAL(sExt.c_str(), "mpl")) - return nullptr; + { + const std::string &sExt = poOpenInfo->osExtension; + if (!EQUAL(sExt.c_str(), "mpr") && !EQUAL(sExt.c_str(), "mpl")) + return nullptr; + } if (!CheckASCII(poOpenInfo->pabyHeader, poOpenInfo->nHeaderBytes)) return nullptr; @@ -703,8 +701,9 @@ GDALDataset *ILWISDataset::Open(GDALOpenInfo *poOpenInfo) const std::string maptype = ReadElement("BaseMap", "Type", poOpenInfo->pszFilename); // const std::string sBaseName = - // std::string(CPLGetBasename(poOpenInfo->pszFilename) ); - const std::string sPath = std::string(CPLGetPath(poOpenInfo->pszFilename)); + // std::string(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str() ); + const std::string sPath = + std::string(CPLGetPathSafe(poOpenInfo->pszFilename)); // Verify whether it is a map list or a map if (EQUAL(ilwistype.c_str(), "MapList")) @@ -721,14 +720,13 @@ GDALDataset *ILWISDataset::Open(GDALOpenInfo *poOpenInfo) snprintf(cBandName, sizeof(cBandName), "Map%d", iBand); std::string sBandName = ReadElement( "MapList", std::string(cBandName), poOpenInfo->pszFilename); - std::string pszBandBaseName = - std::string(CPLGetBasename(sBandName.c_str())); - std::string pszBandPath = - std::string(CPLGetPath(sBandName.c_str())); - if (pszBandPath.empty()) + const std::string osBandBaseName = + CPLGetBasenameSafe(sBandName.c_str()); + const std::string osBandPath = CPLGetPathSafe(sBandName.c_str()); + if (osBandPath.empty()) { - sBandName = std::string(CPLFormFilename( - sPath.c_str(), pszBandBaseName.c_str(), "mpr")); + sBandName = CPLFormFilenameSafe(sPath.c_str(), + osBandBaseName.c_str(), "mpr"); } // Verify the file extension, it must be an ILWIS raw data file // with extension .mp#, otherwise, unsupported @@ -736,8 +734,8 @@ GDALDataset *ILWISDataset::Open(GDALOpenInfo *poOpenInfo) // of ILWIS raster maps, std::string sMapStoreName = ReadElement("MapStore", "Data", sBandName); - sExt = CPLGetExtension(sMapStoreName.c_str()); - if (!STARTS_WITH_CI(sExt.c_str(), "mp#")) + if (!STARTS_WITH_CI( + CPLGetExtensionSafe(sMapStoreName.c_str()).c_str(), "mp#")) { CPLError(CE_Failure, CPLE_AppDefined, "Unsupported ILWIS data file. \n" @@ -830,11 +828,10 @@ GDALDataset *ILWISDataset::Open(GDALOpenInfo *poOpenInfo) if (!(STARTS_WITH_CI(csy.c_str(), "latlon.csy")) && !(STARTS_WITH_CI(csy.c_str(), "LatlonWGS84.csy"))) { - std::string osBaseName = - std::string(CPLGetBasename(csy.c_str())); - std::string osPath = std::string(CPLGetPath(poDS->osFileName)); - csy = std::string( - CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "csy")); + const std::string osBaseName = CPLGetBasenameSafe(csy.c_str()); + const std::string osPath = CPLGetPathSafe(poDS->osFileName); + csy = CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), + "csy"); pszProj = ReadElement("CoordSystem", "Type", csy); if (pszProj.empty()) // default to projection pszProj = "Projection"; @@ -922,14 +919,14 @@ GDALDataset *ILWISDataset::Create(const char *pszFilename, int nXSize, EQUAL(sStoreType.c_str(), "float")) stepsize = 0; - const std::string osBaseName = std::string(CPLGetBasename(pszFilename)); - const std::string osPath = std::string(CPLGetPath(pszFilename)); + const std::string osBaseName = std::string(CPLGetBasenameSafe(pszFilename)); + const std::string osPath = std::string(CPLGetPathSafe(pszFilename)); /* -------------------------------------------------------------------- */ /* Write out object definition file for each band */ /* -------------------------------------------------------------------- */ - std::string pszODFName; - std::string pszDataBaseName; + std::string osODFName; + std::string osDataBaseName; std::string osFilename; char strsize[45]; @@ -939,14 +936,16 @@ GDALDataset *ILWISDataset::Create(const char *pszFilename, int nXSize, std::unique_ptr globalFile; if (nBandsIn == 1) { - pszODFName = std::string( - CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "mpr")); - pszDataBaseName = osBaseName; - osFilename = CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "mpr"); + osODFName = + CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), "mpr"); + osDataBaseName = osBaseName; + osFilename = + CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), "mpr"); } else { - osFilename = CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "mpl"); + osFilename = + CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), "mpl"); auto iniFile = new IniFile(std::string(osFilename)); iniFile->SetKeyValue("Ilwis", "Type", "MapList"); iniFile->SetKeyValue("MapList", "GeoRef", "none.grf"); @@ -962,13 +961,13 @@ GDALDataset *ILWISDataset::Create(const char *pszFilename, int nXSize, char szBandName[100]; snprintf(szBandName, sizeof(szBandName), "%s_band_%d", osBaseName.c_str(), iBand + 1); - pszODFName = std::string(szBandName) + ".mpr"; - pszDataBaseName = std::string(szBandName); + osODFName = std::string(szBandName) + ".mpr"; + osDataBaseName = std::string(szBandName); snprintf(szBandName, sizeof(szBandName), "Map%d", iBand); globalFile->SetKeyValue("MapList", std::string(szBandName), - pszODFName); - pszODFName = - CPLFormFilename(osPath.c_str(), pszDataBaseName.c_str(), "mpr"); + osODFName); + osODFName = CPLFormFilenameSafe(osPath.c_str(), + osDataBaseName.c_str(), "mpr"); } /* -------------------------------------------------------------------- */ @@ -976,15 +975,15 @@ GDALDataset *ILWISDataset::Create(const char *pszFilename, int nXSize, /* -------------------------------------------------------------------- */ - IniFile ODFFile(pszODFName); + IniFile ODFFile(osODFName); ODFFile.SetKeyValue("Ilwis", "Type", "BaseMap"); ODFFile.SetKeyValue("BaseMap", "Type", "Map"); ODFFile.SetKeyValue("Map", "Type", "MapStore"); ODFFile.SetKeyValue("BaseMap", "Domain", sDomain); - std::string pszDataName = pszDataBaseName + ".mp#"; - ODFFile.SetKeyValue("MapStore", "Data", pszDataName); + std::string osDataName = osDataBaseName + ".mp#"; + ODFFile.SetKeyValue("MapStore", "Data", osDataName.c_str()); ODFFile.SetKeyValue("MapStore", "Structure", "Line"); // sStoreType is used by ILWISRasterBand constructor to determine // eDataType @@ -1008,14 +1007,14 @@ GDALDataset *ILWISDataset::Create(const char *pszFilename, int nXSize, /* Try to create the data file. */ /* -------------------------------------------------------------------- */ - pszDataName = CPLResetExtension(pszODFName.c_str(), "mp#"); + osDataName = CPLResetExtensionSafe(osODFName.c_str(), "mp#"); - VSILFILE *fp = VSIFOpenL(pszDataName.c_str(), "wb"); + VSILFILE *fp = VSIFOpenL(osDataName.c_str(), "wb"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Unable to create file %s.\n", - pszDataName.c_str()); + osDataName.c_str()); return nullptr; } VSIFCloseL(fp); @@ -1092,8 +1091,8 @@ GDALDataset *ILWISDataset::CreateCopy(const char *pszFilename, if (poDS == nullptr) return nullptr; - const std::string osBaseName = std::string(CPLGetBasename(pszFilename)); - const std::string osPath = std::string(CPLGetPath(pszFilename)); + const std::string osBaseName = std::string(CPLGetBasenameSafe(pszFilename)); + const std::string osPath = std::string(CPLGetPathSafe(pszFilename)); /* -------------------------------------------------------------------- */ /* Copy and geo-transform and projection information. */ @@ -1150,22 +1149,21 @@ GDALDataset *ILWISDataset::CreateCopy(const char *pszFilename, stepsize = 0; // Form the image file name, create the object definition file. - std::string pszODFName; - // std::string pszDataBaseName; + std::string osODFName; + // std::string osDataBaseName; if (nBands == 1) { - pszODFName = std::string( - CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "mpr")); - // pszDataBaseName = osBaseName; + osODFName = + CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), "mpr"); + // osDataBaseName = osBaseName; } else { char szName[100]; snprintf(szName, sizeof(szName), "%s_band_%d", osBaseName.c_str(), iBand + 1); - pszODFName = - std::string(CPLFormFilename(osPath.c_str(), szName, "mpr")); - // pszDataBaseName = std::string(szName); + osODFName = CPLFormFilenameSafe(osPath.c_str(), szName, "mpr"); + // osDataBaseName = std::string(szName); } /* -------------------------------------------------------------------- */ @@ -1189,9 +1187,9 @@ GDALDataset *ILWISDataset::CreateCopy(const char *pszFilename, CPLsnprintf(strdouble, sizeof(strdouble), "%.3f:%.3f:%3f:offset=0", adfMinMax[0], adfMinMax[1], stepsize); std::string range = std::string(strdouble); - WriteElement("BaseMap", "Range", pszODFName, range); + WriteElement("BaseMap", "Range", osODFName, range); } - WriteElement("Map", "GeoRef", pszODFName, georef); + WriteElement("Map", "GeoRef", osODFName, georef); /* -------------------------------------------------------------------- */ @@ -1199,7 +1197,7 @@ GDALDataset *ILWISDataset::CreateCopy(const char *pszFilename, /* -------------------------------------------------------------------- */ // For file name for raw data, and create binary files. - // std::string pszDataFileName = CPLResetExtension(pszODFName.c_str(), + // std::string pszDataFileName = CPLResetExtensionSafe(osODFName.c_str(), // "mp#" ); fpData = desBand->fpRaw; @@ -1322,16 +1320,17 @@ ILWISRasterBand::ILWISRasterBand(ILWISDataset *poDSIn, int nBandIn, { sBandName = sBandNameIn; } - std::string sInputPath = std::string(CPLGetPath(poDSIn->osFileName)); - std::string sBandPath = std::string(CPLGetPath(sBandName.c_str())); + std::string sInputPath = + std::string(CPLGetPathSafe(poDSIn->osFileName)); + std::string sBandPath = std::string(CPLGetPathSafe(sBandName.c_str())); std::string sBandBaseName = - std::string(CPLGetBasename(sBandName.c_str())); + std::string(CPLGetBasenameSafe(sBandName.c_str())); if (sBandPath.empty()) - sBandName = std::string(CPLFormFilename( - sInputPath.c_str(), sBandBaseName.c_str(), "mpr")); + sBandName = CPLFormFilenameSafe(sInputPath.c_str(), + sBandBaseName.c_str(), "mpr"); else - sBandName = std::string(CPLFormFilename( - sBandPath.c_str(), sBandBaseName.c_str(), "mpr")); + sBandName = CPLFormFilenameSafe(sBandPath.c_str(), + sBandBaseName.c_str(), "mpr"); } if (poDSIn->bNewDataset) @@ -1394,7 +1393,7 @@ void ILWISRasterBand::ILWISOpen(const std::string &pszFileName) { ILWISDataset *dataset = (ILWISDataset *)poDS; std::string pszDataFile = - std::string(CPLResetExtension(pszFileName.c_str(), "mp#")); + std::string(CPLResetExtensionSafe(pszFileName.c_str(), "mp#")); fpRaw = VSIFOpenL(pszDataFile.c_str(), (dataset->eAccess == GA_Update) ? "rb+" : "rb"); @@ -1480,8 +1479,9 @@ CPLErr ILWISRasterBand::GetILWISInfo(const std::string &pszFileName) const std::string domName = ReadElement("BaseMap", "Domain", pszFileName.c_str()); - const std::string osBaseName = std::string(CPLGetBasename(domName.c_str())); - const std::string osPath = std::string(CPLGetPath(pszFileName.c_str())); + const std::string osBaseName = + std::string(CPLGetBasenameSafe(domName.c_str())); + const std::string osPath = std::string(CPLGetPathSafe(pszFileName.c_str())); // Check against all "system-domains" if (EQUAL(osBaseName.c_str(), @@ -1522,10 +1522,10 @@ CPLErr ILWISRasterBand::GetILWISInfo(const std::string &pszFileName) { // No match found. Assume it is a self-created domain. Read its type and // decide the GDAL type. - std::string pszDomainFileName = std::string( - CPLFormFilename(osPath.c_str(), osBaseName.c_str(), "dom")); + std::string osDomainFileName = + CPLFormFilenameSafe(osPath.c_str(), osBaseName.c_str(), "dom"); std::string domType = - ReadElement("Domain", "Type", pszDomainFileName.c_str()); + ReadElement("Domain", "Type", osDomainFileName.c_str()); if (EQUAL(domType.c_str(), "domainvalue")) // is it a self-created domain of // type=DomainValue? diff --git a/frmts/jaxapalsar/jaxapalsardataset.cpp b/frmts/jaxapalsar/jaxapalsardataset.cpp index a7b7480a137e..d8ef19f4b95e 100644 --- a/frmts/jaxapalsar/jaxapalsardataset.cpp +++ b/frmts/jaxapalsar/jaxapalsardataset.cpp @@ -514,8 +514,9 @@ int PALSARJaxaDataset::Identify(GDALOpenInfo *poOpenInfo) /* First, check that this is a PALSAR image indeed */ if (!STARTS_WITH_CI((char *)(poOpenInfo->pabyHeader + 60), "AL") || - !STARTS_WITH_CI(CPLGetBasename((char *)(poOpenInfo->pszFilename)) + 4, - "ALPSR")) + !STARTS_WITH_CI( + CPLGetBasenameSafe(poOpenInfo->pszFilename).substr(4).c_str(), + "ALPSR")) { return 0; } @@ -578,14 +579,16 @@ GDALDataset *PALSARJaxaDataset::Open(GDALOpenInfo *poOpenInfo) /* Try to read each of the polarizations */ const size_t nImgFileLen = - strlen(CPLGetDirname(poOpenInfo->pszFilename)) + strlen(pszSuffix) + 8; + CPLGetDirnameSafe(poOpenInfo->pszFilename).size() + strlen(pszSuffix) + + 8; char *pszImgFile = (char *)CPLMalloc(nImgFileLen); int nBandNum = 1; /* HH */ snprintf(pszImgFile, nImgFileLen, "%s%sIMG-HH%s", - CPLGetDirname(poOpenInfo->pszFilename), SEP_STRING, pszSuffix); + CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str(), SEP_STRING, + pszSuffix); VSILFILE *fpHH = VSIFOpenL(pszImgFile, "rb"); if (fpHH != nullptr) { @@ -595,7 +598,8 @@ GDALDataset *PALSARJaxaDataset::Open(GDALOpenInfo *poOpenInfo) /* HV */ snprintf(pszImgFile, nImgFileLen, "%s%sIMG-HV%s", - CPLGetDirname(poOpenInfo->pszFilename), SEP_STRING, pszSuffix); + CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str(), SEP_STRING, + pszSuffix); VSILFILE *fpHV = VSIFOpenL(pszImgFile, "rb"); if (fpHV != nullptr) { @@ -605,7 +609,8 @@ GDALDataset *PALSARJaxaDataset::Open(GDALOpenInfo *poOpenInfo) /* VH */ snprintf(pszImgFile, nImgFileLen, "%s%sIMG-VH%s", - CPLGetDirname(poOpenInfo->pszFilename), SEP_STRING, pszSuffix); + CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str(), SEP_STRING, + pszSuffix); VSILFILE *fpVH = VSIFOpenL(pszImgFile, "rb"); if (fpVH != nullptr) { @@ -615,7 +620,8 @@ GDALDataset *PALSARJaxaDataset::Open(GDALOpenInfo *poOpenInfo) /* VV */ snprintf(pszImgFile, nImgFileLen, "%s%sIMG-VV%s", - CPLGetDirname(poOpenInfo->pszFilename), SEP_STRING, pszSuffix); + CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str(), SEP_STRING, + pszSuffix); VSILFILE *fpVV = VSIFOpenL(pszImgFile, "rb"); if (fpVV != nullptr) { @@ -650,10 +656,12 @@ GDALDataset *PALSARJaxaDataset::Open(GDALOpenInfo *poOpenInfo) /* read metadata from Leader file. */ const size_t nLeaderFilenameLen = - strlen(CPLGetDirname(poOpenInfo->pszFilename)) + strlen(pszSuffix) + 5; + strlen(CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str()) + + strlen(pszSuffix) + 5; char *pszLeaderFilename = (char *)CPLMalloc(nLeaderFilenameLen); snprintf(pszLeaderFilename, nLeaderFilenameLen, "%s%sLED%s", - CPLGetDirname(poOpenInfo->pszFilename), SEP_STRING, pszSuffix); + CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str(), SEP_STRING, + pszSuffix); VSILFILE *fpLeader = VSIFOpenL(pszLeaderFilename, "rb"); /* check if the leader is actually present */ diff --git a/frmts/jp2kak/jp2kakdataset.cpp b/frmts/jp2kak/jp2kakdataset.cpp index eabe52ef4099..0301432c7a7c 100644 --- a/frmts/jp2kak/jp2kakdataset.cpp +++ b/frmts/jp2kak/jp2kakdataset.cpp @@ -692,7 +692,7 @@ GDALDataset *JP2KAKDataset::Open(GDALOpenInfo *poOpenInfo) KakaduInitialize(); // Handle setting up datasource for JPIP. - const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExtension = poOpenInfo->osExtension.c_str(); std::vector abySubfileHeader(16); // leave in this scope if (poOpenInfo->nHeaderBytes < 16) { @@ -2373,22 +2373,24 @@ static GDALDataset *JP2KAKCreateCopy(const char *pszFilename, #ifdef KAKADU_JPX jpx_family_tgt jpx_family; jpx_target jpx_out; - const bool bIsJPX = !EQUAL(CPLGetExtension(pszFilename), "jpf") && - !EQUAL(CPLGetExtension(pszFilename), "jpc") && - !EQUAL(CPLGetExtension(pszFilename), "j2k") && - !(pszCodec != NULL && EQUAL(pszCodec, "J2K")); + const bool bIsJPX = + !EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "jpf") && + !EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "jpc") && + !EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "j2k") && + !(pszCodec != NULL && EQUAL(pszCodec, "J2K")); #endif kdu_compressed_target *poOutputFile = nullptr; jp2_target jp2_out; const char *pszCodec = CSLFetchNameValueDef(papszOptions, "CODEC", nullptr); - const bool bIsJP2 = (!EQUAL(CPLGetExtension(pszFilename), "jpc") && - !EQUAL(CPLGetExtension(pszFilename), "j2k") && + const bool bIsJP2 = + (!EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "jpc") && + !EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "j2k") && #ifdef KAKADU_JPX - !bIsJPX && + !bIsJPX && #endif - !(pszCodec != nullptr && EQUAL(pszCodec, "J2K"))) || - (pszCodec != nullptr && EQUAL(pszCodec, "JP2")); + !(pszCodec != nullptr && EQUAL(pszCodec, "J2K"))) || + (pszCodec != nullptr && EQUAL(pszCodec, "JP2")); kdu_codestream oCodeStream; vsil_target oVSILTarget; diff --git a/frmts/jp2kak/jp2kakdrivercore.cpp b/frmts/jp2kak/jp2kakdrivercore.cpp index 62bc7bf40207..d64327e53d4c 100644 --- a/frmts/jp2kak/jp2kakdrivercore.cpp +++ b/frmts/jp2kak/jp2kakdrivercore.cpp @@ -109,7 +109,7 @@ int JP2KAKDatasetIdentify(GDALOpenInfo *poOpenInfo) if ((STARTS_WITH_CI(poOpenInfo->pszFilename, "http://") || STARTS_WITH_CI(poOpenInfo->pszFilename, "https://") || STARTS_WITH_CI(poOpenInfo->pszFilename, "jpip://")) && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "jp2")) + poOpenInfo->IsExtensionEqualToCI("jp2")) { #ifdef USE_JPIP return TRUE; @@ -133,8 +133,7 @@ int JP2KAKDatasetIdentify(GDALOpenInfo *poOpenInfo) else if (memcmp(poOpenInfo->pabyHeader, jpc_header, sizeof(jpc_header)) == 0) { - const char *const pszExtension = - CPLGetExtension(poOpenInfo->pszFilename); + const char *const pszExtension = poOpenInfo->osExtension.c_str(); if (EQUAL(pszExtension, "jpc") || EQUAL(pszExtension, "j2k") || EQUAL(pszExtension, "jp2") || EQUAL(pszExtension, "jpx") || EQUAL(pszExtension, "j2c") || EQUAL(pszExtension, "jhc")) diff --git a/frmts/jpegxl/jpegxl.cpp b/frmts/jpegxl/jpegxl.cpp index 10671a1ccb18..60f997b93047 100644 --- a/frmts/jpegxl/jpegxl.cpp +++ b/frmts/jpegxl/jpegxl.cpp @@ -205,7 +205,7 @@ int JPEGXLDataset::Identify(GDALOpenInfo *poOpenInfo) if (poOpenInfo->fpL == nullptr) return false; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "jxl")) + if (poOpenInfo->IsExtensionEqualToCI("jxl")) return true; // See diff --git a/frmts/jpegxl/jpegxldrivercore.cpp b/frmts/jpegxl/jpegxldrivercore.cpp index b179896d1d50..2a912fe392fc 100644 --- a/frmts/jpegxl/jpegxldrivercore.cpp +++ b/frmts/jpegxl/jpegxldrivercore.cpp @@ -35,7 +35,7 @@ static int JPEGXLDatasetIdentifyPartial(GDALOpenInfo *poOpenInfo) if (poOpenInfo->fpL == nullptr) return false; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "jxl")) + if (poOpenInfo->IsExtensionEqualToCI("jxl")) return true; // See diff --git a/frmts/kea/keadrivercore.cpp b/frmts/kea/keadrivercore.cpp index a466898f2dc0..6a8fb591255e 100644 --- a/frmts/kea/keadrivercore.cpp +++ b/frmts/kea/keadrivercore.cpp @@ -28,7 +28,7 @@ int KEADriverIdentify(GDALOpenInfo *poOpenInfo) return 0; } - return EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "KEA"); + return poOpenInfo->IsExtensionEqualToCI("KEA"); } /************************************************************************/ diff --git a/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp b/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp index e9aa9a05384f..ecc438ae4e22 100644 --- a/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp +++ b/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp @@ -168,15 +168,15 @@ static int GenerateRootKml(const char *filename, const char *kmlfilename, } int minlodpixels = tilesize / 2; - const char *tmpfilename = CPLGetBasename(kmlfilename); - if (pszOverlayName == nullptr) - pszOverlayName = tmpfilename; + const std::string osOverlayName = pszOverlayName + ? std::string(pszOverlayName) + : CPLGetBasenameSafe(kmlfilename); // If we have not written any features yet, output the layer's schema. VSIFPrintfL(fp, "\n"); VSIFPrintfL(fp, "\n"); VSIFPrintfL(fp, "\t\n"); - char *pszEncoded = CPLEscapeString(pszOverlayName, -1, CPLES_XML); + char *pszEncoded = CPLEscapeString(osOverlayName.c_str(), -1, CPLES_XML); VSIFPrintfL(fp, "\t\t%s\n", pszEncoded); CPLFree(pszEncoded); if (pszOverlayDescription == nullptr) @@ -562,14 +562,17 @@ KmlSuperOverlayCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, // correct the file and get the directory char *output_dir = nullptr; + std::string osFilename; if (pszFilename == nullptr) { output_dir = CPLGetCurrentDir(); - pszFilename = CPLFormFilename(output_dir, "doc", "kml"); + osFilename = CPLFormFilenameSafe(output_dir, "doc", "kml"); } else { - const char *extension = CPLGetExtension(pszFilename); + osFilename = pszFilename; + const std::string osExtension = CPLGetExtensionSafe(pszFilename); + const char *extension = osExtension.c_str(); if (!EQUAL(extension, "kml") && !EQUAL(extension, "kmz")) { CPLError(CE_Failure, CPLE_None, @@ -581,13 +584,15 @@ KmlSuperOverlayCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, isKmz = true; } - output_dir = CPLStrdup(CPLGetPath(pszFilename)); + output_dir = CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); if (strcmp(output_dir, "") == 0) { CPLFree(output_dir); output_dir = CPLGetCurrentDir(); } } + pszFilename = osFilename.c_str(); + CPLString outDir = output_dir ? output_dir : ""; CPLFree(output_dir); output_dir = nullptr; @@ -738,7 +743,7 @@ KmlSuperOverlayCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, if (isKmz) { - tmpFileName = CPLFormFilename(outDir, "doc.kml", nullptr); + tmpFileName = CPLFormFilenameSafe(outDir, "doc.kml", nullptr); nRet = GenerateRootKml(tmpFileName.c_str(), pszFilename, north, south, east, west, static_cast(tilexsize), pszOverlayName, pszOverlayDescription); @@ -1315,24 +1320,27 @@ CPLErr KmlSuperOverlayReadDataset::IRasterIO( else { const char *pszBaseFilename = osFilename.c_str(); - if (EQUAL(CPLGetExtension(pszBaseFilename), "kmz") && + if (EQUAL(CPLGetExtensionSafe(pszBaseFilename).c_str(), + "kmz") && !STARTS_WITH(pszBaseFilename, "/vsizip/")) { osSubFilename = "/vsizip/"; - osSubFilename += CPLGetPath(pszBaseFilename); + osSubFilename += CPLGetPathSafe(pszBaseFilename); osSubFilename += "/"; osSubFilename += pszHref; } else { - osSubFilename = CPLFormFilename( - CPLGetPath(pszBaseFilename), pszHref, nullptr); + osSubFilename = CPLFormFilenameSafe( + CPLGetPathSafe(pszBaseFilename).c_str(), + pszHref, nullptr); } osSubFilename = KMLRemoveSlash(osSubFilename); } KmlSuperOverlayReadDataset *poSubImageDS = nullptr; - if (EQUAL(CPLGetExtension(osSubFilename), "kml")) + if (EQUAL(CPLGetExtensionSafe(osSubFilename).c_str(), + "kml")) { KmlSuperOverlayReadDataset *poRoot = poParent ? poParent : this; @@ -1679,7 +1687,7 @@ static int KmlSuperOverlayFindRegionStart(CPLXMLNode *psNode, int KmlSuperOverlayReadDataset::Identify(GDALOpenInfo *poOpenInfo) { - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (EQUAL(pszExt, "kmz")) return -1; if (poOpenInfo->nHeaderBytes == 0) @@ -1744,7 +1752,8 @@ GDALDataset *KmlSuperOverlayReadDataset::Open(GDALOpenInfo *poOpenInfo) static std::unique_ptr KmlSuperOverlayLoadIcon(const char *pszBaseFilename, const char *pszIcon) { - const char *pszExt = CPLGetExtension(pszIcon); + const std::string osExt = CPLGetExtensionSafe(pszIcon); + const char *pszExt = osExt.c_str(); if (!EQUAL(pszExt, "png") && !EQUAL(pszExt, "jpg") && !EQUAL(pszExt, "jpeg")) { @@ -1756,8 +1765,8 @@ KmlSuperOverlayLoadIcon(const char *pszBaseFilename, const char *pszIcon) osSubFilename = CPLSPrintf("/vsicurl_streaming/%s", pszIcon); else { - osSubFilename = - CPLFormFilename(CPLGetPath(pszBaseFilename), pszIcon, nullptr); + osSubFilename = CPLFormFilenameSafe( + CPLGetPathSafe(pszBaseFilename).c_str(), pszIcon, nullptr); osSubFilename = KMLRemoveSlash(osSubFilename); } @@ -1810,8 +1819,7 @@ static bool KmlSuperOverlayComputeDepth(const std::string &osFilename, CPLGetXMLNode(psIter, "Region") != nullptr && (pszHref = CPLGetXMLValue(psIter, "Link.href", nullptr)) != nullptr) { - const char *pszExt = CPLGetExtension(pszHref); - if (EQUAL(pszExt, "kml")) + if (EQUAL(CPLGetExtensionSafe(pszHref).c_str(), "kml")) { CPLString osSubFilename; if (STARTS_WITH(pszHref, "http")) @@ -1819,8 +1827,9 @@ static bool KmlSuperOverlayComputeDepth(const std::string &osFilename, CPLSPrintf("/vsicurl_streaming/%s", pszHref); else { - osSubFilename = CPLFormFilename( - CPLGetPath(osFilename.c_str()), pszHref, nullptr); + osSubFilename = CPLFormFilenameSafe( + CPLGetPathSafe(osFilename.c_str()).c_str(), pszHref, + nullptr); osSubFilename = KMLRemoveSlash(osSubFilename); } @@ -1999,12 +2008,12 @@ static bool KmlSingleDocGetDimensions(const CPLString &osDirname, int nLevel, int nTileSize, int &nXSize, int &nYSize, int &nBands, int &bHasCT) { - const char *pszImageFilename = CPLFormFilename( + std::string osImageFilename = CPLFormFilenameSafe( osDirname, CPLSPrintf("kml_image_L%d_%d_%d", nLevel, oDesc.nMaxJ_j, oDesc.nMaxJ_i), oDesc.szExtJ); auto poImageDS = std::unique_ptr(GDALDataset::Open( - pszImageFilename, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR)); + osImageFilename.c_str(), GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR)); if (!poImageDS) { return false; @@ -2020,13 +2029,13 @@ static bool KmlSingleDocGetDimensions(const CPLString &osDirname, } else { - pszImageFilename = - CPLFormFilename(osDirname, - CPLSPrintf("kml_image_L%d_%d_%d", nLevel, - oDesc.nMaxI_j, oDesc.nMaxI_i), - oDesc.szExtI); + osImageFilename = + CPLFormFilenameSafe(osDirname, + CPLSPrintf("kml_image_L%d_%d_%d", nLevel, + oDesc.nMaxI_j, oDesc.nMaxI_i), + oDesc.szExtI); poImageDS.reset(GDALDataset::Open( - pszImageFilename, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR)); + osImageFilename.c_str(), GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR)); if (!poImageDS) { return false; @@ -2113,18 +2122,18 @@ CPLErr KmlSingleDocRasterRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, { KmlSingleDocRasterDataset *poGDS = cpl::down_cast(poDS); - const char *pszImageFilename = - CPLFormFilename(poGDS->osDirname, - CPLSPrintf("kml_image_L%d_%d_%d", poGDS->nLevel, - nBlockYOff, nBlockXOff), - poGDS->osNominalExt); + const std::string osImageFilename = + CPLFormFilenameSafe(poGDS->osDirname, + CPLSPrintf("kml_image_L%d_%d_%d", poGDS->nLevel, + nBlockYOff, nBlockXOff), + poGDS->osNominalExt); if (poGDS->poCurTileDS == nullptr || strcmp(CPLGetFilename(poGDS->poCurTileDS->GetDescription()), - CPLGetFilename(pszImageFilename)) != 0) + CPLGetFilename(osImageFilename.c_str())) != 0) { CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler); poGDS->poCurTileDS.reset( - GDALDataset::Open(pszImageFilename, GDAL_OF_RASTER)); + GDALDataset::Open(osImageFilename.c_str(), GDAL_OF_RASTER)); } GDALDataset *poImageDS = poGDS->poCurTileDS.get(); if (poImageDS == nullptr) @@ -2145,7 +2154,7 @@ CPLErr KmlSingleDocRasterRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, if (nXSize != nReqXSize || nYSize != nReqYSize) { CPLDebug("KMLSUPEROVERLAY", "Tile %s, dimensions %dx%d, expected %dx%d", - pszImageFilename, nXSize, nYSize, nReqXSize, nReqYSize); + osImageFilename.c_str(), nXSize, nYSize, nReqXSize, nReqYSize); return CE_Failure; } @@ -2289,7 +2298,7 @@ KmlSingleDocCollectTiles(CPLXMLNode *psNode, const char *pszHref = CPLGetXMLValue(psNode, "", ""); if (STARTS_WITH(pszHref, "http")) { - osURLBase = CPLGetPath(pszHref); + osURLBase = CPLGetPathSafe(pszHref); } if (sscanf(CPLGetFilename(pszHref), "kml_image_L%d_%d_%d.%3s", &level, &j, &i, szExt) == 4) @@ -2380,7 +2389,7 @@ GDALDataset *KmlSingleDocRasterDataset::Open(const char *pszFilename, return nullptr; std::vector aosDescs; - CPLString osDirname = CPLGetPath(osFilename); + CPLString osDirname = CPLGetPathSafe(osFilename); KmlSingleDocCollectTiles(psRootFolder, aosDescs, osDirname); if (aosDescs.empty()) return nullptr; @@ -2390,13 +2399,13 @@ GDALDataset *KmlSingleDocRasterDataset::Open(const char *pszFilename, return nullptr; } - const char *pszImageFilename = - CPLFormFilename(osDirname, - CPLSPrintf("kml_image_L%d_%d_%d", - static_cast(aosDescs.size()), 0, 0), - aosDescs.back().szExtI); + const std::string osImageFilename = + CPLFormFilenameSafe(osDirname, + CPLSPrintf("kml_image_L%d_%d_%d", + static_cast(aosDescs.size()), 0, 0), + aosDescs.back().szExtI); auto poImageDS = std::unique_ptr(GDALDataset::Open( - pszImageFilename, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR)); + osImageFilename.c_str(), GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR)); if (poImageDS == nullptr) { return nullptr; @@ -2522,10 +2531,10 @@ GDALDataset *KmlSingleOverlayRasterDataset::Open(const char *pszFilename, std::array adfExtents = {0, 0, 0, 0}; if (!KmlSuperOverlayGetBoundingBox(psGO, adfExtents)) return nullptr; - const char *pszImageFilename = - CPLFormFilename(CPLGetPath(osFilename), pszHref, nullptr); - GDALDataset *poImageDS = - GDALDataset::FromHandle(GDALOpenShared(pszImageFilename, GA_ReadOnly)); + const std::string osImageFilename = CPLFormFilenameSafe( + CPLGetPathSafe(osFilename).c_str(), pszHref, nullptr); + GDALDataset *poImageDS = GDALDataset::FromHandle( + GDALOpenShared(osImageFilename.c_str(), GA_ReadOnly)); if (poImageDS == nullptr) return nullptr; @@ -2578,8 +2587,7 @@ KmlSuperOverlayReadDataset::Open(const char *pszFilename, if (nRec == 2) return nullptr; CPLString osFilename(pszFilename); - const char *pszExt = CPLGetExtension(pszFilename); - if (EQUAL(pszExt, "kmz")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "kmz")) { if (!STARTS_WITH(pszFilename, "/vsizip/")) osFilename = CPLSPrintf("/vsizip/%s", pszFilename); @@ -2589,10 +2597,10 @@ KmlSuperOverlayReadDataset::Open(const char *pszFilename, char **papszIter = papszFiles; for (; *papszIter != nullptr; papszIter++) { - pszExt = CPLGetExtension(*papszIter); - if (EQUAL(pszExt, "kml")) + if (EQUAL(CPLGetExtensionSafe(*papszIter).c_str(), "kml")) { - osFilename = CPLFormFilename(osFilename, *papszIter, nullptr); + osFilename = + CPLFormFilenameSafe(osFilename, *papszIter, nullptr); osFilename = KMLRemoveSlash(osFilename); break; } @@ -2650,7 +2658,8 @@ KmlSuperOverlayReadDataset::Open(const char *pszFilename, if (psLink != nullptr) { const char *pszHref = CPLGetXMLValue(psLink, "href", nullptr); - if (pszHref == nullptr || !EQUAL(CPLGetExtension(pszHref), "kml")) + if (pszHref == nullptr || + !EQUAL(CPLGetExtensionSafe(pszHref).c_str(), "kml")) { CPLDestroyXMLNode(psNode); return nullptr; @@ -2661,8 +2670,8 @@ KmlSuperOverlayReadDataset::Open(const char *pszFilename, osSubFilename = CPLSPrintf("/vsicurl_streaming/%s", pszHref); else { - osSubFilename = - CPLFormFilename(CPLGetPath(osFilename), pszHref, nullptr); + osSubFilename = CPLFormFilenameSafe( + CPLGetPathSafe(osFilename).c_str(), pszHref, nullptr); osSubFilename = KMLRemoveSlash(osSubFilename); } @@ -2673,7 +2682,8 @@ KmlSuperOverlayReadDataset::Open(const char *pszFilename, const char *pszOverlayName = CPLGetXMLValue(psDocument, "name", nullptr); if (pszOverlayName != nullptr && - strcmp(pszOverlayName, CPLGetBasename(pszFilename)) != 0) + strcmp(pszOverlayName, + CPLGetBasenameSafe(pszFilename).c_str()) != 0) { osOverlayName = pszOverlayName; } diff --git a/frmts/l1b/l1bdataset.cpp b/frmts/l1b/l1bdataset.cpp index 76702fb8c2d4..e956f5580e28 100644 --- a/frmts/l1b/l1bdataset.cpp +++ b/frmts/l1b/l1bdataset.cpp @@ -1032,16 +1032,19 @@ void L1BDataset::FetchMetadata() return; } - const char *pszDir = CPLGetConfigOption("L1B_METADATA_DIRECTORY", nullptr); - if (pszDir == nullptr) - { - pszDir = CPLGetPath(GetDescription()); - if (pszDir[0] == '\0') - pszDir = "."; - } - CPLString osMetadataFile(CPLSPrintf("%s/%s_metadata.csv", pszDir, - CPLGetFilename(GetDescription()))); - VSILFILE *fpCSV = VSIFOpenL(osMetadataFile, "wb"); + std::string osDir = CPLGetConfigOption("L1B_METADATA_DIRECTORY", ""); + if (osDir.empty()) + { + osDir = CPLGetPathSafe(GetDescription()); + if (osDir.empty()) + osDir = "."; + } + const std::string osMetadataFile = + std::string(osDir) + .append("/") + .append(CPLGetFilename(GetDescription())) + .append("_metadata.csv"); + VSILFILE *fpCSV = VSIFOpenL(osMetadataFile.c_str(), "wb"); if (fpCSV == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, @@ -1138,16 +1141,19 @@ void L1BDataset::FetchMetadata() void L1BDataset::FetchMetadataNOAA15() { int i, j; - const char *pszDir = CPLGetConfigOption("L1B_METADATA_DIRECTORY", nullptr); - if (pszDir == nullptr) - { - pszDir = CPLGetPath(GetDescription()); - if (pszDir[0] == '\0') - pszDir = "."; - } - CPLString osMetadataFile(CPLSPrintf("%s/%s_metadata.csv", pszDir, - CPLGetFilename(GetDescription()))); - VSILFILE *fpCSV = VSIFOpenL(osMetadataFile, "wb"); + std::string osDir = CPLGetConfigOption("L1B_METADATA_DIRECTORY", ""); + if (osDir.empty()) + { + osDir = CPLGetPathSafe(GetDescription()); + if (osDir.empty()) + osDir = "."; + } + const std::string osMetadataFile = + std::string(osDir) + .append("/") + .append(CPLGetFilename(GetDescription())) + .append("_metadata.csv"); + VSILFILE *fpCSV = VSIFOpenL(osMetadataFile.c_str(), "wb"); if (fpCSV == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, diff --git a/frmts/map/mapdataset.cpp b/frmts/map/mapdataset.cpp index 8b85e91cd34b..472ae7c31566 100644 --- a/frmts/map/mapdataset.cpp +++ b/frmts/map/mapdataset.cpp @@ -150,7 +150,7 @@ int MAPDataset::Identify(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->nHeaderBytes < 200 || - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MAP")) + !poOpenInfo->IsExtensionEqualToCI("MAP")) return FALSE; if (strstr(reinterpret_cast(poOpenInfo->pabyHeader), @@ -229,11 +229,11 @@ GDALDataset *MAPDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ poDS->osImgFilename = papszLines[2]; - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); if (CPLIsFilenameRelative(poDS->osImgFilename)) { poDS->osImgFilename = - CPLFormCIFilename(osPath, poDS->osImgFilename, nullptr); + CPLFormCIFilenameSafe(osPath, poDS->osImgFilename, nullptr); } else { @@ -242,7 +242,7 @@ GDALDataset *MAPDataset::Open(GDALOpenInfo *poOpenInfo) { poDS->osImgFilename = CPLGetFilename(poDS->osImgFilename); poDS->osImgFilename = - CPLFormCIFilename(osPath, poDS->osImgFilename, nullptr); + CPLFormCIFilenameSafe(osPath, poDS->osImgFilename, nullptr); } } diff --git a/frmts/mbtiles/mbtilesdataset.cpp b/frmts/mbtiles/mbtilesdataset.cpp index 1326c3142baf..0dd0d6408a4e 100644 --- a/frmts/mbtiles/mbtilesdataset.cpp +++ b/frmts/mbtiles/mbtilesdataset.cpp @@ -2015,7 +2015,7 @@ int MBTilesDataset::Identify(GDALOpenInfo *poOpenInfo) } #endif - if ((EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MBTILES") || + if ((poOpenInfo->IsExtensionEqualToCI("MBTILES") || // Allow direct Amazon S3 signed URLs that contains .mbtiles in the // middle of the URL strstr(poOpenInfo->pszFilename, ".mbtiles") != nullptr) && @@ -3054,10 +3054,11 @@ bool MBTilesDataset::CreateInternal(const char *pszFilename, int nXSize, return false; } - const char *pszName = - CSLFetchNameValueDef(papszOptions, "NAME", CPLGetBasename(pszFilename)); + const std::string osName = CSLFetchNameValueDef( + papszOptions, "NAME", CPLGetBasenameSafe(pszFilename).c_str()); char *pszSQL = sqlite3_mprintf( - "INSERT INTO metadata (name, value) VALUES ('name', '%q')", pszName); + "INSERT INTO metadata (name, value) VALUES ('name', '%q')", + osName.c_str()); sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr); sqlite3_free(pszSQL); @@ -3067,11 +3068,11 @@ bool MBTilesDataset::CreateInternal(const char *pszFilename, int nXSize, sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr); sqlite3_free(pszSQL); - const char *pszDescription = CSLFetchNameValueDef( - papszOptions, "DESCRIPTION", CPLGetBasename(pszFilename)); + const std::string osDescription = CSLFetchNameValueDef( + papszOptions, "DESCRIPTION", CPLGetBasenameSafe(pszFilename).c_str()); pszSQL = sqlite3_mprintf( "INSERT INTO metadata (name, value) VALUES ('description', '%q')", - pszDescription); + osDescription.c_str()); sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr); sqlite3_free(pszSQL); diff --git a/frmts/mrf/Tif_band.cpp b/frmts/mrf/Tif_band.cpp index 04a22bc15920..7f9746196364 100644 --- a/frmts/mrf/Tif_band.cpp +++ b/frmts/mrf/Tif_band.cpp @@ -57,7 +57,7 @@ static CPLString uniq_memfname(const char *prefix) // Define MRF_LOCAL_TMP to use local files instead of RAM // #define MRF_LOCAL_TMP #if defined(MRF_LOCAL_TMP) - return CPLGenerateTempFilename(prefix); + return CPLGenerateTempFilenameSafe(prefix); #else return VSIMemGenerateHiddenFilename(prefix); #endif diff --git a/frmts/mrf/marfa_dataset.cpp b/frmts/mrf/marfa_dataset.cpp index 0a1596f96505..a9db25b87c57 100644 --- a/frmts/mrf/marfa_dataset.cpp +++ b/frmts/mrf/marfa_dataset.cpp @@ -623,7 +623,7 @@ GDALDataset *MRFDataset::Open(GDALOpenInfo *poOpenInfo) else if (poOpenInfo->eAccess == GA_ReadOnly && fn.size() > 600 && (fn[262] == 0 || fn[262] == 32) && STARTS_WITH(fn.c_str() + 257, "ustar") && - strlen(CPLGetPath(fn.c_str())) == 0 && + strlen(CPLGetPathSafe(fn.c_str()).c_str()) == 0 && STARTS_WITH(fn.c_str() + 512, "")) { // An MRF inside a tar insidefn = string("/vsitar/") + pszFileName + "/" + pszHeader; diff --git a/frmts/mrf/mrfdrivercore.cpp b/frmts/mrf/mrfdrivercore.cpp index dcfdad5ade58..8bf987e9baa3 100644 --- a/frmts/mrf/mrfdrivercore.cpp +++ b/frmts/mrf/mrfdrivercore.cpp @@ -100,7 +100,8 @@ int MRFDriverIdentify(GDALOpenInfo *poOpenInfo) // accept a tar file if the first file has no folder look like an MRF if (poOpenInfo->eAccess == GA_ReadOnly && fn.size() > 600 && (fn[262] == 0 || fn[262] == 32) && STARTS_WITH(fn + 257, "ustar") && - strlen(CPLGetPath(fn)) == 0 && STARTS_WITH(fn + 512, "")) + strlen(CPLGetPathSafe(fn).c_str()) == 0 && + STARTS_WITH(fn + 512, "")) { return TRUE; } diff --git a/frmts/mrsid/mrsiddataset.cpp b/frmts/mrsid/mrsiddataset.cpp index f91b0bd34b67..559b05f2e0a8 100644 --- a/frmts/mrsid/mrsiddataset.cpp +++ b/frmts/mrsid/mrsiddataset.cpp @@ -1307,10 +1307,11 @@ CPLErr MrSIDDataset::OpenZoomLevel(lt_int32 iZoom) /* projection */ /* -------------------------------------------------------------------- */ if (iZoom == 0 && m_oSRS.IsEmpty() && - EQUAL(CPLGetExtension(GetDescription()), "sid")) + EQUAL(CPLGetExtensionSafe(GetDescription()).c_str(), "sid")) { - const char *pszMETFilename = CPLResetExtension(GetDescription(), "met"); - VSILFILE *fp = VSIFOpenL(pszMETFilename, "rb"); + const std::string l_osMETFilename = + CPLResetExtensionSafe(GetDescription(), "met"); + VSILFILE *fp = VSIFOpenL(l_osMETFilename.c_str(), "rb"); if (fp) { const char *pszLine = nullptr; @@ -1338,7 +1339,7 @@ CPLErr MrSIDDataset::OpenZoomLevel(lt_int32 iZoom) /* UTM SRS for consistency */ if (nUTMZone >= 1 && nUTMZone <= 60 && bWGS84 && bUnitsMeter) { - osMETFilename = pszMETFilename; + osMETFilename = l_osMETFilename; m_oSRS.importFromEPSG(32600 + nUTMZone); m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); diff --git a/frmts/mrsid/mrsiddrivercore.cpp b/frmts/mrsid/mrsiddrivercore.cpp index ae34bf7cd4e1..ff620b88a67e 100644 --- a/frmts/mrsid/mrsiddrivercore.cpp +++ b/frmts/mrsid/mrsiddrivercore.cpp @@ -48,7 +48,7 @@ int MrSIDJP2Identify(GDALOpenInfo *poOpenInfo) if (memcmp(poOpenInfo->pabyHeader, jpc_header, sizeof(jpc_header)) == 0) { - const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExtension = poOpenInfo->osExtension.c_str(); if (!EQUAL(pszExtension, "jpc") && !EQUAL(pszExtension, "j2k") && !EQUAL(pszExtension, "jp2") && !EQUAL(pszExtension, "jpx") && diff --git a/frmts/netcdf/netcdf_sentinel3_sral_mwr.cpp b/frmts/netcdf/netcdf_sentinel3_sral_mwr.cpp index 76fe2e80332c..0dc0514ea1f3 100644 --- a/frmts/netcdf/netcdf_sentinel3_sral_mwr.cpp +++ b/frmts/netcdf/netcdf_sentinel3_sral_mwr.cpp @@ -461,7 +461,7 @@ void netCDFDataset::ProcessSentinel3_SRAL_MWR() NCDF_ERR(status); if (status != NC_NOERR) break; - std::string name(CPLGetBasename(GetDescription())); + std::string name(CPLGetBasenameSafe(GetDescription())); name += '_'; name += szDimName; std::shared_ptr poLayer( diff --git a/frmts/netcdf/netcdfdataset.cpp b/frmts/netcdf/netcdfdataset.cpp index dfe3cd2476c8..fa460ac4fd1c 100644 --- a/frmts/netcdf/netcdfdataset.cpp +++ b/frmts/netcdf/netcdfdataset.cpp @@ -6662,8 +6662,8 @@ OGRLayer *netCDFDataset::ICreateLayer(const char *pszName, papszDatasetOptions = CSLSetNameValue( papszDatasetOptions, "WRITE_GDAL_TAGS", CSLFetchNameValue(papszCreationOptions, "WRITE_GDAL_TAGS")); - CPLString osLayerFilename( - CPLFormFilename(osFilename, osNetCDFLayerName, "nc")); + const CPLString osLayerFilename( + CPLFormFilenameSafe(osFilename, osNetCDFLayerName, "nc")); CPLAcquireMutex(hNCMutex, 1000.0); poLayerDataset = CreateLL(osLayerFilename, 0, 0, 0, papszDatasetOptions); @@ -8058,7 +8058,7 @@ GDALDataset *netCDFDataset::Open(GDALOpenInfo *poOpenInfo) if (poDS->osFilename.empty()) { poDS->bFileToDestroyAtClosing = true; - poDS->osFilename = CPLGenerateTempFilename("netcdf_tmp"); + poDS->osFilename = CPLGenerateTempFilenameSafe("netcdf_tmp"); } if (!netCDFDatasetCreateTempFile(eTmpFormat, poDS->osFilename, poOpenInfo->fpL)) @@ -9223,8 +9223,9 @@ netCDFDataset *netCDFDataset::CreateLL(const char *pszFilename, int nXSize, // Works around bug of msys2 netCDF 4.9.0 package where nc_create() // crashes VSIStatBuf sStat; - const char *pszDir = CPLGetDirname(osFilenameForNCCreate.c_str()); - if (VSIStat(pszDir, &sStat) != 0) + const std::string osDirname = + CPLGetDirnameSafe(osFilenameForNCCreate.c_str()); + if (VSIStat(osDirname.c_str(), &sStat) != 0) { CPLError(CE_Failure, CPLE_OpenFailed, "Unable to create netCDF file %s: non existing output " @@ -11800,7 +11801,8 @@ static CPLErr NCDFOpenSubDataset(int nCdfId, const char *pszSubdatasetName, *pnVarId = -1; // Open group. - char *pszGroupFullName = CPLStrdup(CPLGetPath(pszSubdatasetName)); + char *pszGroupFullName = + CPLStrdup(CPLGetPathSafe(pszSubdatasetName).c_str()); // Add a leading slash if needed. if (pszGroupFullName[0] != '/') { @@ -12372,7 +12374,7 @@ CPLErr netCDFDataset::CreateGrpVectorLayers( if (pszGroupName == nullptr || pszGroupName[0] == '\0') { CPLFree(pszGroupName); - pszGroupName = CPLStrdup(CPLGetBasename(osFilename)); + pszGroupName = CPLStrdup(CPLGetBasenameSafe(osFilename).c_str()); } OGRwkbGeometryType eGType = wkbUnknown; CPLString osLayerName = CSLFetchNameValueDef( diff --git a/frmts/netcdf/netcdfdrivercore.cpp b/frmts/netcdf/netcdfdrivercore.cpp index 50581dae3f4c..3c47fb1993db 100644 --- a/frmts/netcdf/netcdfdrivercore.cpp +++ b/frmts/netcdf/netcdfdrivercore.cpp @@ -105,7 +105,7 @@ NetCDFFormatEnum netCDFIdentifyFormat(GDALOpenInfo *poOpenInfo, bool bCheckExt) if (bCheckExt) { // Check by default. - const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExtension = poOpenInfo->osExtension.c_str(); if (!(EQUAL(pszExtension, "nc") || EQUAL(pszExtension, "cdf") || EQUAL(pszExtension, "nc2") || EQUAL(pszExtension, "nc4") || EQUAL(pszExtension, "nc3") || EQUAL(pszExtension, "grd") || @@ -154,7 +154,7 @@ NetCDFFormatEnum netCDFIdentifyFormat(GDALOpenInfo *poOpenInfo, bool bCheckExt) // The HDF5 signature of netCDF 4 files can be at offsets 512, 1024, 2048, // etc. - const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExtension = poOpenInfo->osExtension.c_str(); if (poOpenInfo->fpL != nullptr && (!bCheckExt || EQUAL(pszExtension, "nc") || EQUAL(pszExtension, "cdf") || EQUAL(pszExtension, "nc4") || diff --git a/frmts/netcdf/netcdflayersg.cpp b/frmts/netcdf/netcdflayersg.cpp index e1fda6024423..860dbd545c98 100644 --- a/frmts/netcdf/netcdflayersg.cpp +++ b/frmts/netcdf/netcdflayersg.cpp @@ -393,5 +393,5 @@ OGRFeature *netCDFLayer::buildSGeometryFeature(size_t featureInd) std::string netCDFDataset::generateLogName() { - return std::string(CPLGenerateTempFilename(nullptr)); + return std::string(CPLGenerateTempFilenameSafe(nullptr)); } diff --git a/frmts/netcdf/netcdfmultidim.cpp b/frmts/netcdf/netcdfmultidim.cpp index 9748c4530a37..50de82cb37b0 100644 --- a/frmts/netcdf/netcdfmultidim.cpp +++ b/frmts/netcdf/netcdfmultidim.cpp @@ -4971,7 +4971,7 @@ GDALDataset *netCDFDataset::OpenMultiDim(GDALOpenInfo *poOpenInfo) if (osFilename.empty()) { bFileToDestroyAtClosing = true; - osFilename = CPLGenerateTempFilename("netcdf_tmp"); + osFilename = CPLGenerateTempFilenameSafe("netcdf_tmp"); } if (!netCDFDatasetCreateTempFile(NCDF_FORMAT_NC4, osFilename.c_str(), poOpenInfo->fpL)) diff --git a/frmts/ngsgeoid/ngsgeoiddataset.cpp b/frmts/ngsgeoid/ngsgeoiddataset.cpp index f530eb9b81bc..6d3d424bd742 100644 --- a/frmts/ngsgeoid/ngsgeoiddataset.cpp +++ b/frmts/ngsgeoid/ngsgeoiddataset.cpp @@ -376,7 +376,7 @@ const OGRSpatialReference *NGSGEOIDDataset::GetSpatialRef() const } const CPLString osFilename = - CPLString(CPLGetBasename(GetDescription())).tolower(); + CPLString(CPLGetBasenameSafe(GetDescription())).tolower(); // See https://www.ngs.noaa.gov/GEOID/GEOID12B/faq_2012B.shtml diff --git a/frmts/nitf/ecrgtocdataset.cpp b/frmts/nitf/ecrgtocdataset.cpp index d4d1e19c126a..8e6b04a1f98d 100644 --- a/frmts/nitf/ecrgtocdataset.cpp +++ b/frmts/nitf/ecrgtocdataset.cpp @@ -471,7 +471,7 @@ bool ECRGTOCSource::ValidateOpenedBand(GDALRasterBand *poBand) const /* BuildFullName() */ /************************************************************************/ -static const char *BuildFullName(const char *pszTOCFilename, +static std::string BuildFullName(const char *pszTOCFilename, const char *pszFramePath, const char *pszFrameName) { @@ -486,24 +486,25 @@ static const char *BuildFullName(const char *pszTOCFilename, if (pszPath[i] == '\\') pszPath[i] = '/'; } - const char *pszName = CPLFormFilename(pszPath, pszFrameName, nullptr); + const std::string osName = + CPLFormFilenameSafe(pszPath, pszFrameName, nullptr); CPLFree(pszPath); pszPath = nullptr; - const char *pszTOCPath = CPLGetDirname(pszTOCFilename); - const char *pszFirstSlashInName = strchr(pszName, '/'); - if (pszFirstSlashInName != nullptr) + std::string osTOCPath = CPLGetDirnameSafe(pszTOCFilename); + const auto nPosFirstSlashInName = osName.find('/'); + if (nPosFirstSlashInName != std::string::npos) { - int nFirstDirLen = static_cast(pszFirstSlashInName - pszName); - if (static_cast(strlen(pszTOCPath)) >= nFirstDirLen + 1 && - (pszTOCPath[strlen(pszTOCPath) - (nFirstDirLen + 1)] == '/' || - pszTOCPath[strlen(pszTOCPath) - (nFirstDirLen + 1)] == '\\') && - strncmp(pszTOCPath + strlen(pszTOCPath) - nFirstDirLen, pszName, - nFirstDirLen) == 0) + if (osTOCPath.size() >= nPosFirstSlashInName + 1 && + (osTOCPath[osTOCPath.size() - (nPosFirstSlashInName + 1)] == '/' || + osTOCPath[osTOCPath.size() - (nPosFirstSlashInName + 1)] == + '\\') && + strncmp(osTOCPath.c_str() + osTOCPath.size() - nPosFirstSlashInName, + osName.c_str(), nPosFirstSlashInName) == 0) { - pszTOCPath = CPLGetDirname(pszTOCPath); + osTOCPath = CPLGetDirnameSafe(osTOCPath.c_str()); } } - return CPLProjectRelativeFilename(pszTOCPath, pszName); + return CPLProjectRelativeFilenameSafe(osTOCPath.c_str(), osName.c_str()); } /************************************************************************/ @@ -571,7 +572,7 @@ GDALDataset *ECRGTOCSubDataset::Build( for (int i = 0; i < static_cast(aosFrameDesc.size()); i++) { - const char *pszName = BuildFullName( + const std::string osName = BuildFullName( pszTOCFilename, aosFrameDesc[i].pszPath, aosFrameDesc[i].pszName); double dfMinX = 0.0; @@ -590,7 +591,7 @@ GDALDataset *ECRGTOCSubDataset::Build( static_cast((dfMaxY - dfMinY) / dfPixelYSize + 0.5); poVirtualDS->papszFileList = - CSLAddString(poVirtualDS->papszFileList, pszName); + CSLAddString(poVirtualDS->papszFileList, osName.c_str()); for (int j = 0; j < 3; j++) { @@ -599,7 +600,7 @@ GDALDataset *ECRGTOCSubDataset::Build( poVirtualDS->GetRasterBand(j + 1)); /* Place the raster band at the right position in the VRT */ auto poSource = new ECRGTOCSource( - pszName, j + 1, nFrameXSize, nFrameYSize, + osName.c_str(), j + 1, nFrameXSize, nFrameYSize, static_cast((dfMinX - dfGlobalMinX) / dfGlobalPixelXSize + 0.5), static_cast((dfGlobalMaxY - dfMaxY) / dfGlobalPixelYSize + @@ -849,10 +850,10 @@ GDALDataset *ECRGTOCDataset::Build(const char *pszTOCFilename, nValidFrames++; - const char *pszFullName = BuildFullName( + const std::string osFullName = BuildFullName( pszTOCFilename, pszFramePath, pszFrameName); poDS->papszFileList = - CSLAddString(poDS->papszFileList, pszFullName); + CSLAddString(poDS->papszFileList, osFullName.c_str()); if (!bGlobalExtentValid) { diff --git a/frmts/nitf/nitfdataset.cpp b/frmts/nitf/nitfdataset.cpp index a4a0db109338..5832a41ad9fc 100644 --- a/frmts/nitf/nitfdataset.cpp +++ b/frmts/nitf/nitfdataset.cpp @@ -962,20 +962,20 @@ NITFDataset *NITFDataset::OpenInternal(GDALOpenInfo *poOpenInfo, /* If nfw found, try looking for a header with projection info */ /* in space imaging style format */ - const char *pszHDR = CPLResetExtension(pszFilename, "hdr"); + std::string osHDR = CPLResetExtensionSafe(pszFilename, "hdr"); - VSILFILE *fpHDR = VSIFOpenL(pszHDR, "rt"); + VSILFILE *fpHDR = VSIFOpenL(osHDR.c_str(), "rt"); - if (fpHDR == nullptr && VSIIsCaseSensitiveFS(pszHDR)) + if (fpHDR == nullptr && VSIIsCaseSensitiveFS(osHDR.c_str())) { - pszHDR = CPLResetExtension(pszFilename, "HDR"); - fpHDR = VSIFOpenL(pszHDR, "rt"); + osHDR = CPLResetExtensionSafe(pszFilename, "HDR"); + fpHDR = VSIFOpenL(osHDR.c_str(), "rt"); } if (fpHDR != nullptr) { CPL_IGNORE_RET_VAL(VSIFCloseL(fpHDR)); - char **papszLines = CSLLoad2(pszHDR, 16, 200, nullptr); + char **papszLines = CSLLoad2(osHDR.c_str(), 16, 200, nullptr); if (CSLCount(papszLines) == 16) { @@ -1422,23 +1422,24 @@ NITFDataset *NITFDataset::OpenInternal(GDALOpenInfo *poOpenInfo, /* -------------------------------------------------------------------- */ // get _rpc.txt file - const char *pszDirName = CPLGetDirname(pszFilename); - const char *pszBaseName = CPLGetBasename(pszFilename); - const char *pszRPCTXTFilename = - CPLFormFilename(pszDirName, CPLSPrintf("%s_rpc", pszBaseName), "txt"); - if (CPLCheckForFile((char *)pszRPCTXTFilename, - poOpenInfo->GetSiblingFiles())) + const std::string osDirName = CPLGetDirnameSafe(pszFilename); + const std::string osBaseName = CPLGetBasenameSafe(pszFilename); + std::string osRPCTXTFilename = CPLFormFilenameSafe( + osDirName.c_str(), std::string(osBaseName).append("_rpc").c_str(), + "txt"); + if (CPLCheckForFile(osRPCTXTFilename.data(), poOpenInfo->GetSiblingFiles())) { - poDS->m_osRPCTXTFilename = pszRPCTXTFilename; + poDS->m_osRPCTXTFilename = osRPCTXTFilename; } else { - pszRPCTXTFilename = CPLFormFilename( - pszDirName, CPLSPrintf("%s_RPC", pszBaseName), "TXT"); - if (CPLCheckForFile((char *)pszRPCTXTFilename, + osRPCTXTFilename = CPLFormFilenameSafe( + osDirName.c_str(), std::string(osBaseName).append("_RPC").c_str(), + "TXT"); + if (CPLCheckForFile(osRPCTXTFilename.data(), poOpenInfo->GetSiblingFiles())) { - poDS->m_osRPCTXTFilename = pszRPCTXTFilename; + poDS->m_osRPCTXTFilename = osRPCTXTFilename; } } bool bHasLoadedRPCTXT = false; @@ -3502,7 +3503,7 @@ int NITFDataset::CheckForRSets(const char *pszNITFFilename, char **papszSiblingFiles) { - bool isR0File = EQUAL(CPLGetExtension(pszNITFFilename), "r0"); + bool isR0File = EQUAL(CPLGetExtensionSafe(pszNITFFilename).c_str(), "r0"); /* -------------------------------------------------------------------- */ /* Check to see if we have RSets. */ @@ -4040,7 +4041,7 @@ char **NITFDataset::AddFile(char **papszFileList, const char *EXTENSION, const char *extension) { VSIStatBufL sStatBuf; - CPLString osTarget = CPLResetExtension(osNITFFilename, EXTENSION); + CPLString osTarget = CPLResetExtensionSafe(osNITFFilename, EXTENSION); if (oOvManager.GetSiblingFiles() != nullptr) { if (CSLFindStringCaseSensitive(oOvManager.GetSiblingFiles(), @@ -4048,7 +4049,7 @@ char **NITFDataset::AddFile(char **papszFileList, const char *EXTENSION, papszFileList = CSLAddString(papszFileList, osTarget); else { - osTarget = CPLResetExtension(osNITFFilename, extension); + osTarget = CPLResetExtensionSafe(osNITFFilename, extension); if (CSLFindStringCaseSensitive(oOvManager.GetSiblingFiles(), CPLGetFilename(osTarget)) >= 0) papszFileList = CSLAddString(papszFileList, osTarget); @@ -4060,7 +4061,7 @@ char **NITFDataset::AddFile(char **papszFileList, const char *EXTENSION, papszFileList = CSLAddString(papszFileList, osTarget); else { - osTarget = CPLResetExtension(osNITFFilename, extension); + osTarget = CPLResetExtensionSafe(osNITFFilename, extension); if (VSIStatL(osTarget, &sStatBuf) == 0) papszFileList = CSLAddString(papszFileList, osTarget); } diff --git a/frmts/nitf/rpftocfile.cpp b/frmts/nitf/rpftocfile.cpp index d3ca6b2f0718..c5ec065409fa 100644 --- a/frmts/nitf/rpftocfile.cpp +++ b/frmts/nitf/rpftocfile.cpp @@ -579,8 +579,9 @@ RPFToc *RPFTOCReadFromBuffer(const char *pszFilename, VSILFILE *fp, // some CADRG maps have legend name smaller than 8.3 then the extension // has blanks (0x20) at the end -> check only the first 3 letters of the // extension. - const char *fileExt = CPLGetExtension(frameEntry->filename); - if (EQUALN(fileExt, "ovr", 3) || EQUALN(fileExt, "lgd", 3)) + const std::string fileExt = CPLGetExtensionSafe(frameEntry->filename); + if (EQUALN(fileExt.c_str(), "ovr", 3) || + EQUALN(fileExt.c_str(), "lgd", 3)) { entry->isOverviewOrLegend = TRUE; } @@ -660,9 +661,11 @@ RPFToc *RPFTOCReadFromBuffer(const char *pszFilename, VSILFILE *fp, // Check if it was not intended to be "./X/" instead. VSIStatBufL sStatBuf; if (frameEntry->directory[0] == '/' && - VSIStatL(CPLFormFilename(CPLGetDirname(pszFilename), - frameEntry->directory + 1, nullptr), - &sStatBuf) == 0 && + VSIStatL( + CPLFormFilenameSafe(CPLGetDirnameSafe(pszFilename).c_str(), + frameEntry->directory + 1, nullptr) + .c_str(), + &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode)) { memmove(frameEntry->directory, frameEntry->directory + 1, @@ -671,7 +674,7 @@ RPFToc *RPFTOCReadFromBuffer(const char *pszFilename, VSILFILE *fp, } { - char *baseDir = CPLStrdup(CPLGetDirname(pszFilename)); + char *baseDir = CPLStrdup(CPLGetDirnameSafe(pszFilename).c_str()); VSIStatBufL sStatBuf; char *subdir = nullptr; if (CPLIsFilenameRelative(frameEntry->directory) == FALSE) @@ -681,7 +684,8 @@ RPFToc *RPFTOCReadFromBuffer(const char *pszFilename, VSILFILE *fp, subdir = CPLStrdup(baseDir); else subdir = CPLStrdup( - CPLFormFilename(baseDir, frameEntry->directory, nullptr)); + CPLFormFilenameSafe(baseDir, frameEntry->directory, nullptr) + .c_str()); #if !defined(_WIN32) && !defined(_WIN32_CE) if (VSIStatL(subdir, &sStatBuf) != 0 && strlen(subdir) > strlen(baseDir)) @@ -696,7 +700,8 @@ RPFToc *RPFTOCReadFromBuffer(const char *pszFilename, VSILFILE *fp, } #endif frameEntry->fullFilePath = CPLStrdup( - CPLFormFilename(subdir, frameEntry->filename, nullptr)); + CPLFormFilenameSafe(subdir, frameEntry->filename, nullptr) + .c_str()); if (VSIStatL(frameEntry->fullFilePath, &sStatBuf) != 0) { #if !defined(_WIN32) && !defined(_WIN32_CE) diff --git a/frmts/northwood/grddataset.cpp b/frmts/northwood/grddataset.cpp index 6d0a4d0840ea..1755828600e2 100644 --- a/frmts/northwood/grddataset.cpp +++ b/frmts/northwood/grddataset.cpp @@ -792,7 +792,7 @@ int NWT_GRDDataset::UpdateHeader() int NWT_GRDDataset::WriteTab() { // Create the filename for the .tab file. - const std::string sTabFile(CPLResetExtension(pGrd->szFileName, "tab")); + const std::string sTabFile(CPLResetExtensionSafe(pGrd->szFileName, "tab")); VSILFILE *tabfp = VSIFOpenL(sTabFile.c_str(), "wt"); if (tabfp == nullptr) diff --git a/frmts/ogcapi/gdalogcapidataset.cpp b/frmts/ogcapi/gdalogcapidataset.cpp index 66b141613cff..25e60e0399b8 100644 --- a/frmts/ogcapi/gdalogcapidataset.cpp +++ b/frmts/ogcapi/gdalogcapidataset.cpp @@ -648,7 +648,7 @@ int OGCAPIDataset::Identify(GDALOpenInfo *poOpenInfo) { if (STARTS_WITH_CI(poOpenInfo->pszFilename, "OGCAPI:")) return TRUE; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "moaw")) + if (poOpenInfo->IsExtensionEqualToCI("moaw")) return TRUE; if (poOpenInfo->IsSingleAllowedDriver("OGCAPI")) { diff --git a/frmts/pcidsk/pcidskdataset2.cpp b/frmts/pcidsk/pcidskdataset2.cpp index c278bb909314..1dae85f04568 100644 --- a/frmts/pcidsk/pcidskdataset2.cpp +++ b/frmts/pcidsk/pcidskdataset2.cpp @@ -853,7 +853,7 @@ char **PCIDSK2Dataset::GetFileList() { char **papszFileList = GDALPamDataset::GetFileList(); - CPLString osBaseDir = CPLGetPath(GetDescription()); + CPLString osBaseDir = CPLGetPathSafe(GetDescription()); try { @@ -871,7 +871,8 @@ char **PCIDSK2Dataset::GetFileList() { papszFileList = CSLAddString( papszFileList, - CPLProjectRelativeFilename(osBaseDir, osChanFilename)); + CPLProjectRelativeFilenameSafe(osBaseDir, osChanFilename) + .c_str()); } } diff --git a/frmts/pdf/pdfdataset.cpp b/frmts/pdf/pdfdataset.cpp index cb57e2a96719..9986deb178d7 100644 --- a/frmts/pdf/pdfdataset.cpp +++ b/frmts/pdf/pdfdataset.cpp @@ -2081,7 +2081,7 @@ CPLErr PDFDataset::ReadPixels(int nReqXOff, int nReqYOff, int nReqXSize, osCmd += "\""; } - CPLString osTmpFilenamePrefix = CPLGenerateTempFilename("pdf"); + CPLString osTmpFilenamePrefix = CPLGenerateTempFilenameSafe("pdf"); osTmpFilename = CPLSPrintf("%s-%d.ppm", osTmpFilenamePrefix.c_str(), iPage); osCmd += CPLSPrintf(" \"%s\"", osTmpFilenamePrefix.c_str()); diff --git a/frmts/pds/isis2dataset.cpp b/frmts/pds/isis2dataset.cpp index b7b42beb50a6..6a3ca5c83410 100644 --- a/frmts/pds/isis2dataset.cpp +++ b/frmts/pds/isis2dataset.cpp @@ -232,18 +232,18 @@ GDALDataset *ISIS2Dataset::Open(GDALOpenInfo *poOpenInfo) if (pszQube[0] == '"') { - const CPLString osTPath = CPLGetPath(poOpenInfo->pszFilename); + const CPLString osTPath = CPLGetPathSafe(poOpenInfo->pszFilename); CPLString osFilename = pszQube; poDS->CleanString(osFilename); - osTargetFile = CPLFormCIFilename(osTPath, osFilename, nullptr); + osTargetFile = CPLFormCIFilenameSafe(osTPath, osFilename, nullptr); poDS->osExternalCube = osTargetFile; } else if (pszQube[0] == '(') { - const CPLString osTPath = CPLGetPath(poOpenInfo->pszFilename); + const CPLString osTPath = CPLGetPathSafe(poOpenInfo->pszFilename); CPLString osFilename = poDS->GetKeywordSub("^QUBE", 1, ""); poDS->CleanString(osFilename); - osTargetFile = CPLFormCIFilename(osTPath, osFilename, nullptr); + osTargetFile = CPLFormCIFilenameSafe(osTPath, osFilename, nullptr); poDS->osExternalCube = osTargetFile; nQube = atoi(poDS->GetKeywordSub("^QUBE", 2, "1")); @@ -714,16 +714,16 @@ GDALDataset *ISIS2Dataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Check for a .prj file. For isis2 I would like to keep this in */ /* -------------------------------------------------------------------- */ - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); - const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename); - const char *pszPrjFile = CPLFormCIFilename(osPath, osName, "prj"); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename); + const std::string osPrjFile = CPLFormCIFilenameSafe(osPath, osName, "prj"); - VSILFILE *fp = VSIFOpenL(pszPrjFile, "r"); + VSILFILE *fp = VSIFOpenL(osPrjFile.c_str(), "r"); if (fp != nullptr) { VSIFCloseL(fp); - char **papszLines = CSLLoad(pszPrjFile); + char **papszLines = CSLLoad(osPrjFile.c_str()); poDS->m_oSRS.importFromESRI(papszLines); @@ -913,7 +913,7 @@ GDALDataset *ISIS2Dataset::Create(const char *pszFilename, int nXSize, sExtension = pszExtension; } - if (EQUAL(CPLGetExtension(pszFilename), sExtension)) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), sExtension)) { CPLError(CE_Failure, CPLE_AppDefined, "IMAGE_EXTENSION (%s) cannot match LABEL file extension.", @@ -922,7 +922,7 @@ GDALDataset *ISIS2Dataset::Create(const char *pszFilename, int nXSize, } osLabelFile = pszFilename; - osRasterFile = CPLResetExtension(osLabelFile, sExtension); + osRasterFile = CPLResetExtensionSafe(osLabelFile, sExtension); osOutFile = osLabelFile; } diff --git a/frmts/pds/isis3dataset.cpp b/frmts/pds/isis3dataset.cpp index f22e76d43b7e..75db6c5efcc7 100644 --- a/frmts/pds/isis3dataset.cpp +++ b/frmts/pds/isis3dataset.cpp @@ -1628,9 +1628,9 @@ GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo) if (oFilename.GetType() == CPLJSONObject::Type::String) { VSIStatBufL sStat; - CPLString osFilename( - CPLFormFilename(CPLGetPath(poOpenInfo->pszFilename), - oFilename.ToString().c_str(), nullptr)); + const CPLString osFilename(CPLFormFilenameSafe( + CPLGetPathSafe(poOpenInfo->pszFilename).c_str(), + oFilename.ToString().c_str(), nullptr)); if (VSIStatL(osFilename, &sStat) == 0) { poDS->m_aosAdditionalFiles.AddString(osFilename); @@ -1681,9 +1681,10 @@ GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo) const char *pszCore = poDS->GetKeyword("IsisCube.Core.^Core"); const CPLString osQubeFile( EQUAL(pszCore, "") - ? poOpenInfo->pszFilename - : CPLFormFilename(CPLGetPath(poOpenInfo->pszFilename), pszCore, - nullptr)); + ? CPLString(poOpenInfo->pszFilename) + : CPLFormFilenameSafe( + CPLGetPathSafe(poOpenInfo->pszFilename).c_str(), pszCore, + nullptr)); if (!EQUAL(pszCore, "")) { poDS->m_osExternalFilename = osQubeFile; @@ -2124,7 +2125,7 @@ GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo) // Sanity checks in case the external raw file appears to be a // TIFF file - if (EQUAL(CPLGetExtension(osQubeFile), "tif")) + if (EQUAL(CPLGetExtensionSafe(osQubeFile).c_str(), "tif")) { GDALDataset *poTIF_DS = GDALDataset::FromHandle(GDALOpen(osQubeFile, GA_ReadOnly)); @@ -2446,21 +2447,21 @@ GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Check for a .prj file. For ISIS3 I would like to keep this in */ /* -------------------------------------------------------------------- */ - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); - const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename); - const char *pszPrjFile = CPLFormCIFilename(osPath, osName, "prj"); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename); + const std::string osPrjFile = CPLFormCIFilenameSafe(osPath, osName, "prj"); - VSILFILE *fp = VSIFOpenL(pszPrjFile, "r"); + VSILFILE *fp = VSIFOpenL(osPrjFile.c_str(), "r"); if (fp != nullptr) { VSIFCloseL(fp); - char **papszLines = CSLLoad(pszPrjFile); + char **papszLines = CSLLoad(osPrjFile.c_str()); OGRSpatialReference oSRS2; if (oSRS2.importFromESRI(papszLines) == OGRERR_NONE) { - poDS->m_aosAdditionalFiles.AddString(pszPrjFile); + poDS->m_aosAdditionalFiles.AddString(osPrjFile.c_str()); poDS->m_oSRS = std::move(oSRS2); poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } @@ -2486,7 +2487,7 @@ GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo) if (poDS->m_bGotTransform) { poDS->m_aosAdditionalFiles.AddString( - CPLResetExtension(poOpenInfo->pszFilename, "cbw")); + CPLResetExtensionSafe(poOpenInfo->pszFilename, "cbw").c_str()); } } @@ -2497,7 +2498,7 @@ GDALDataset *ISIS3Dataset::Open(GDALOpenInfo *poOpenInfo) if (poDS->m_bGotTransform) { poDS->m_aosAdditionalFiles.AddString( - CPLResetExtension(poOpenInfo->pszFilename, "wld")); + CPLResetExtensionSafe(poOpenInfo->pszFilename, "wld").c_str()); } } @@ -3039,7 +3040,7 @@ void ISIS3Dataset::BuildLabel() oHistory.Add("Bytes", static_cast(m_osHistory.size())); if (!m_osExternalFilename.empty()) { - CPLString osFilename(CPLGetBasename(GetDescription())); + CPLString osFilename(CPLGetBasenameSafe(GetDescription())); osFilename += ".History.IsisCube"; oHistory.Add("^History", osFilename); } @@ -3116,9 +3117,9 @@ void ISIS3Dataset::BuildLabel() if (oFilenameCap.GetType() == CPLJSONObject::Type::String) { VSIStatBufL sStat; - const CPLString osSrcFilename( - CPLFormFilename(CPLGetPath(osLabelSrcFilename), - oFilenameCap.ToString().c_str(), nullptr)); + const CPLString osSrcFilename(CPLFormFilenameSafe( + CPLGetPathSafe(osLabelSrcFilename).c_str(), + oFilenameCap.ToString().c_str(), nullptr)); if (VSIStatL(osSrcFilename, &sStat) == 0) { oSection.osSrcFilename = osSrcFilename; @@ -3151,7 +3152,7 @@ void ISIS3Dataset::BuildLabel() if (!m_osExternalFilename.empty()) { - CPLString osDstFilename(CPLGetBasename(GetDescription())); + CPLString osDstFilename(CPLGetBasenameSafe(GetDescription())); osDstFilename += "."; osDstFilename += osContainerName; if (!osName.empty()) @@ -3160,8 +3161,9 @@ void ISIS3Dataset::BuildLabel() osDstFilename += osName; } - oSection.osDstFilename = CPLFormFilename( - CPLGetPath(GetDescription()), osDstFilename, nullptr); + oSection.osDstFilename = CPLFormFilenameSafe( + CPLGetPathSafe(GetDescription()).c_str(), osDstFilename, + nullptr); oObj.Set(osKeyFilename, osDstFilename); } @@ -3202,8 +3204,8 @@ void ISIS3Dataset::BuildHistory() CPLJSONObject oHistoryFilename = oHistory["^History"]; if (oHistoryFilename.GetType() == CPLJSONObject::Type::String) { - osHistoryFilename = CPLFormFilename( - CPLGetPath(osSrcFilename), + osHistoryFilename = CPLFormFilenameSafe( + CPLGetPathSafe(osSrcFilename).c_str(), oHistoryFilename.ToString().c_str(), nullptr); } @@ -3275,8 +3277,8 @@ void ISIS3Dataset::BuildHistory() char szFullFilename[2048] = {0}; if (!CPLGetExecPath(szFullFilename, sizeof(szFullFilename) - 1)) strcpy(szFullFilename, "unknown_program"); - const CPLString osProgram(CPLGetBasename(szFullFilename)); - const CPLString osPath(CPLGetPath(szFullFilename)); + const CPLString osProgram(CPLGetBasenameSafe(szFullFilename)); + const CPLString osPath(CPLGetPathSafe(szFullFilename)); CPLJSONObject oObj; oHistoryObj.Add(osProgram, oObj); @@ -3521,10 +3523,10 @@ void ISIS3Dataset::WriteLabel() } else { - CPLString osFilename(CPLGetBasename(GetDescription())); + CPLString osFilename(CPLGetBasenameSafe(GetDescription())); osFilename += ".History.IsisCube"; - osFilename = CPLFormFilename(CPLGetPath(GetDescription()), - osFilename, nullptr); + osFilename = CPLFormFilenameSafe( + CPLGetPathSafe(GetDescription()).c_str(), osFilename, nullptr); VSILFILE *fp = VSIFOpenL(osFilename, "wb"); if (fp) { @@ -3972,7 +3974,7 @@ GDALDataset *ISIS3Dataset::Create(const char *pszFilename, int nXSize, const int nBlockYSize = std::max( 1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256"))); if (!EQUAL(pszDataLocation, "LABEL") && - !EQUAL(CPLGetExtension(pszFilename), "LBL")) + !EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "LBL")) { CPLError(CE_Failure, CPLE_NotSupported, "For DATA_LOCATION=%s, " @@ -3997,9 +3999,9 @@ GDALDataset *ISIS3Dataset::Create(const char *pszFilename, int nXSize, bool bGeoTIFFAsRegularExternal = false; if (EQUAL(pszDataLocation, "EXTERNAL")) { - osExternalFilename = - CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME", - CPLResetExtension(pszFilename, "cub")); + osExternalFilename = CSLFetchNameValueDef( + papszOptions, "EXTERNAL_FILENAME", + CPLResetExtensionSafe(pszFilename, "cub").c_str()); fpImage = VSIFOpenExL(osExternalFilename.c_str(), pszPermission, true); if (fpImage == nullptr) { @@ -4011,9 +4013,9 @@ GDALDataset *ISIS3Dataset::Create(const char *pszFilename, int nXSize, } else if (EQUAL(pszDataLocation, "GEOTIFF")) { - osExternalFilename = - CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME", - CPLResetExtension(pszFilename, "tif")); + osExternalFilename = CSLFetchNameValueDef( + papszOptions, "EXTERNAL_FILENAME", + CPLResetExtensionSafe(pszFilename, "tif").c_str()); GDALDriver *poDrv = static_cast(GDALGetDriverByName("GTiff")); if (poDrv == nullptr) @@ -4196,9 +4198,9 @@ GDALDataset *ISIS3Dataset::CreateCopy(const char *pszFilename, poSrcUnderlyingDS = poSrcDS; if (EQUAL(pszDataLocation, "GEOTIFF") && strcmp(poSrcUnderlyingDS->GetDescription(), - CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME", - CPLResetExtension(pszFilename, "tif"))) == - 0) + CSLFetchNameValueDef( + papszOptions, "EXTERNAL_FILENAME", + CPLResetExtensionSafe(pszFilename, "tif").c_str())) == 0) { CPLError(CE_Failure, CPLE_NotSupported, "Output file has same name as input file"); diff --git a/frmts/pds/pds4dataset.cpp b/frmts/pds/pds4dataset.cpp index 09e0a1fd5198..6aafcb4b3edc 100644 --- a/frmts/pds/pds4dataset.cpp +++ b/frmts/pds/pds4dataset.cpp @@ -1398,26 +1398,28 @@ OGRLayer *PDS4Dataset::GetLayer(int nIndex) /* FixupTableFilename() */ /************************************************************************/ -static CPLString FixupTableFilename(const CPLString &osFilename) +static std::string FixupTableFilename(const std::string &osFilename) { VSIStatBufL sStat; - if (VSIStatL(osFilename, &sStat) == 0) + if (VSIStatL(osFilename.c_str(), &sStat) == 0) { return osFilename; } - CPLString osExt = CPLGetExtension(osFilename); + const std::string osExt = CPLGetExtensionSafe(osFilename.c_str()); if (!osExt.empty()) { - CPLString osTry(osFilename); + std::string osTry(osFilename); if (osExt[0] >= 'a' && osExt[0] <= 'z') { - osTry = CPLResetExtension(osFilename, osExt.toupper()); + osTry = CPLResetExtensionSafe(osFilename.c_str(), + CPLString(osExt).toupper()); } else { - osTry = CPLResetExtension(osFilename, osExt.tolower()); + osTry = CPLResetExtensionSafe(osFilename.c_str(), + CPLString(osExt).tolower()); } - if (VSIStatL(osTry, &sStat) == 0) + if (VSIStatL(osTry.c_str(), &sStat) == 0) { return osTry; } @@ -1432,11 +1434,11 @@ static CPLString FixupTableFilename(const CPLString &osFilename) bool PDS4Dataset::OpenTableCharacter(const char *pszFilename, const CPLXMLNode *psTable) { - CPLString osLayerName(CPLGetBasename(pszFilename)); - CPLString osFullFilename = FixupTableFilename(CPLFormFilename( - CPLGetPath(m_osXMLFilename.c_str()), pszFilename, nullptr)); - std::unique_ptr poLayer( - new PDS4TableCharacter(this, osLayerName, osFullFilename)); + const std::string osLayerName(CPLGetBasenameSafe(pszFilename)); + const std::string osFullFilename = FixupTableFilename(CPLFormFilenameSafe( + CPLGetPathSafe(m_osXMLFilename.c_str()).c_str(), pszFilename, nullptr)); + std::unique_ptr poLayer(new PDS4TableCharacter( + this, osLayerName.c_str(), osFullFilename.c_str())); if (!poLayer->ReadTableDef(psTable)) { return false; @@ -1454,11 +1456,11 @@ bool PDS4Dataset::OpenTableCharacter(const char *pszFilename, bool PDS4Dataset::OpenTableBinary(const char *pszFilename, const CPLXMLNode *psTable) { - CPLString osLayerName(CPLGetBasename(pszFilename)); - CPLString osFullFilename = FixupTableFilename(CPLFormFilename( - CPLGetPath(m_osXMLFilename.c_str()), pszFilename, nullptr)); + const std::string osLayerName(CPLGetBasenameSafe(pszFilename)); + const std::string osFullFilename = FixupTableFilename(CPLFormFilenameSafe( + CPLGetPathSafe(m_osXMLFilename.c_str()).c_str(), pszFilename, nullptr)); std::unique_ptr poLayer( - new PDS4TableBinary(this, osLayerName, osFullFilename)); + new PDS4TableBinary(this, osLayerName.c_str(), osFullFilename.c_str())); if (!poLayer->ReadTableDef(psTable)) { return false; @@ -1476,11 +1478,11 @@ bool PDS4Dataset::OpenTableBinary(const char *pszFilename, bool PDS4Dataset::OpenTableDelimited(const char *pszFilename, const CPLXMLNode *psTable) { - CPLString osLayerName(CPLGetBasename(pszFilename)); - CPLString osFullFilename = FixupTableFilename(CPLFormFilename( - CPLGetPath(m_osXMLFilename.c_str()), pszFilename, nullptr)); - std::unique_ptr poLayer( - new PDS4DelimitedTable(this, osLayerName, osFullFilename)); + const std::string osLayerName(CPLGetBasenameSafe(pszFilename)); + const std::string osFullFilename = FixupTableFilename(CPLFormFilenameSafe( + CPLGetPathSafe(m_osXMLFilename.c_str()).c_str(), pszFilename, nullptr)); + std::unique_ptr poLayer(new PDS4DelimitedTable( + this, osLayerName.c_str(), osFullFilename.c_str())); if (!poLayer->ReadTableDef(psTable)) { return false; @@ -1951,20 +1953,21 @@ PDS4Dataset *PDS4Dataset::OpenInternal(GDALOpenInfo *poOpenInfo) if (poDS->nBands != 0) continue; - const char *pszImageFullFilename = CPLFormFilename( - CPLGetPath(osXMLFilename.c_str()), pszFilename, nullptr); + const std::string osImageFullFilename = CPLFormFilenameSafe( + CPLGetPathSafe(osXMLFilename.c_str()).c_str(), pszFilename, + nullptr); VSILFILE *fp = VSIFOpenExL( - pszImageFullFilename, + osImageFullFilename.c_str(), (poOpenInfo->eAccess == GA_Update) ? "rb+" : "rb", true); if (fp == nullptr) { CPLError(CE_Warning, CPLE_FileIO, "Cannt open %s: %s", - pszImageFullFilename, VSIGetLastErrorMsg()); + osImageFullFilename.c_str(), VSIGetLastErrorMsg()); continue; } poDS->nRasterXSize = nSamples; poDS->nRasterYSize = nLines; - poDS->m_osImageFilename = pszImageFullFilename; + poDS->m_osImageFilename = osImageFullFilename; poDS->m_fpImage = fp; poDS->m_bIsLSB = bLSBOrder; @@ -3498,8 +3501,9 @@ void PDS4Dataset::WriteVectorLayers(CPLXMLNode *psProduct) poLayer->GetName()); } - const CPLString osRelativePath(CPLExtractRelativePath( - CPLGetPath(m_osXMLFilename), poLayer->GetFileName(), nullptr)); + const std::string osRelativePath( + CPLExtractRelativePath(CPLGetPathSafe(m_osXMLFilename).c_str(), + poLayer->GetFileName(), nullptr)); bool bFound = false; for (CPLXMLNode *psIter = psProduct->psChild; psIter != nullptr; @@ -3512,7 +3516,7 @@ void PDS4Dataset::WriteVectorLayers(CPLXMLNode *psProduct) const char *pszFilename = CPLGetXMLValue( psIter, (osPrefix + "File." + osPrefix + "file_name").c_str(), ""); - if (strcmp(pszFilename, osRelativePath) == 0) + if (strcmp(pszFilename, osRelativePath.c_str()) == 0) { poLayer->RefreshFileAreaObservational(psIter); bFound = true; @@ -3527,8 +3531,9 @@ void PDS4Dataset::WriteVectorLayers(CPLXMLNode *psProduct) (osPrefix + "File_Area_Observational").c_str()); CPLXMLNode *psFile = CPLCreateXMLNode(psFAO, CXT_Element, (osPrefix + "File").c_str()); - CPLCreateXMLElementAndValue( - psFile, (osPrefix + "file_name").c_str(), osRelativePath); + CPLCreateXMLElementAndValue(psFile, + (osPrefix + "file_name").c_str(), + osRelativePath.c_str()); poLayer->RefreshFileAreaObservational(psFAO); } } @@ -4168,8 +4173,9 @@ OGRLayer *PDS4Dataset::ICreateLayer(const char *pszName, CPLString osFullFilename; if (bSameDirectory) { - osFullFilename = CPLFormFilename(CPLGetPath(m_osXMLFilename.c_str()), - osBasename.c_str(), pszExt); + osFullFilename = + CPLFormFilenameSafe(CPLGetPathSafe(m_osXMLFilename.c_str()).c_str(), + osBasename.c_str(), pszExt); VSIStatBufL sStat; if (VSIStatL(osFullFilename, &sStat) == 0) { @@ -4182,9 +4188,9 @@ OGRLayer *PDS4Dataset::ICreateLayer(const char *pszName, } else { - CPLString osDirectory = - CPLFormFilename(CPLGetPath(m_osXMLFilename), - CPLGetBasename(m_osXMLFilename), nullptr); + CPLString osDirectory = CPLFormFilenameSafe( + CPLGetPathSafe(m_osXMLFilename).c_str(), + CPLGetBasenameSafe(m_osXMLFilename).c_str(), nullptr); VSIStatBufL sStat; if (VSIStatL(osDirectory, &sStat) != 0 && VSIMkdir(osDirectory, 0755) != 0) @@ -4194,7 +4200,7 @@ OGRLayer *PDS4Dataset::ICreateLayer(const char *pszName, return nullptr; } osFullFilename = - CPLFormFilename(osDirectory, osBasename.c_str(), pszExt); + CPLFormFilenameSafe(osDirectory, osBasename.c_str(), pszExt); } if (EQUAL(pszTableType, "DELIMITED")) @@ -4370,7 +4376,8 @@ PDS4Dataset *PDS4Dataset::CreateInternal(const char *pszFilename, const char *pszImageExtension = aosOptions.FetchNameValueDef( "IMAGE_EXTENSION", EQUAL(pszImageFormat, "RAW") ? "img" : "tif"); CPLString osImageFilename(aosOptions.FetchNameValueDef( - "IMAGE_FILENAME", CPLResetExtension(pszFilename, pszImageExtension))); + "IMAGE_FILENAME", + CPLResetExtensionSafe(pszFilename, pszImageExtension).c_str())); const bool bAppend = aosOptions.FetchBool("APPEND_SUBDATASET", false); if (bAppend) @@ -4667,9 +4674,9 @@ GDALDataset *PDS4Dataset::CreateCopy(const char *pszFilename, poSrcUnderlyingDS = poSrcDS; if (EQUAL(pszImageFormat, "GEOTIFF") && strcmp(poSrcUnderlyingDS->GetDescription(), - CSLFetchNameValueDef(papszOptions, "IMAGE_FILENAME", - CPLResetExtension(pszFilename, "tif"))) == - 0) + CSLFetchNameValueDef( + papszOptions, "IMAGE_FILENAME", + CPLResetExtensionSafe(pszFilename, "tif").c_str())) == 0) { CPLError(CE_Failure, CPLE_NotSupported, "Output file has same name as input file"); diff --git a/frmts/pds/pds4vector.cpp b/frmts/pds/pds4vector.cpp index 4228b391921e..df10c76a570f 100644 --- a/frmts/pds/pds4vector.cpp +++ b/frmts/pds/pds4vector.cpp @@ -1788,7 +1788,7 @@ PDS4DelimitedTable::~PDS4DelimitedTable() void PDS4DelimitedTable::GenerateVRT() { - CPLString osVRTFilename = CPLResetExtension(m_osFilename, "vrt"); + CPLString osVRTFilename = CPLResetExtensionSafe(m_osFilename, "vrt"); if (m_bCreation) { // In creation mode, generate the VRT, unless explicitly disabled by @@ -2466,7 +2466,7 @@ void PDS4DelimitedTable::RefreshFileAreaObservational(CPLXMLNode *psFAO) char **PDS4DelimitedTable::GetFileList() const { auto papszFileList = PDS4TableBaseLayer::GetFileList(); - CPLString osVRTFilename = CPLResetExtension(m_osFilename, "vrt"); + CPLString osVRTFilename = CPLResetExtensionSafe(m_osFilename, "vrt"); VSIStatBufL sStat; if (VSIStatL(osVRTFilename, &sStat) == 0) { diff --git a/frmts/pds/pdsdataset.cpp b/frmts/pds/pdsdataset.cpp index a0d8f65bf3dd..b96f2ee1be52 100644 --- a/frmts/pds/pdsdataset.cpp +++ b/frmts/pds/pdsdataset.cpp @@ -679,16 +679,17 @@ void PDSDataset::ParseSRS() /* Check for a .prj and world file to override the georeferencing. */ /* ==================================================================== */ { - const CPLString osPath = CPLGetPath(pszFilename); - const CPLString osName = CPLGetBasename(pszFilename); - const char *pszPrjFile = CPLFormCIFilename(osPath, osName, "prj"); + const CPLString osPath = CPLGetPathSafe(pszFilename); + const CPLString osName = CPLGetBasenameSafe(pszFilename); + const std::string osPrjFile = + CPLFormCIFilenameSafe(osPath, osName, "prj"); - VSILFILE *fp = VSIFOpenL(pszPrjFile, "r"); + VSILFILE *fp = VSIFOpenL(osPrjFile.c_str(), "r"); if (fp != nullptr) { VSIFCloseL(fp); - char **papszLines = CSLLoad(pszPrjFile); + char **papszLines = CSLLoad(osPrjFile.c_str()); m_oSRS.importFromESRI(papszLines); CSLDestroy(papszLines); @@ -846,8 +847,9 @@ int PDSDataset::ParseImage(const CPLString &osPrefix, } else { - CPLString osTPath = CPLGetPath(GetDescription()); - m_osImageFilename = CPLFormCIFilename(osTPath, osFilename, nullptr); + CPLString osTPath = CPLGetPathSafe(GetDescription()); + m_osImageFilename = + CPLFormCIFilenameSafe(osTPath, osFilename, nullptr); osExternalCube = m_osImageFilename; } } @@ -1330,9 +1332,9 @@ int PDSDataset::ParseCompressedImage() const CPLString osFileName = CleanString(GetKeyword("COMPRESSED_FILE.FILE_NAME", "")); - const CPLString osPath = CPLGetPath(GetDescription()); + const CPLString osPath = CPLGetPathSafe(GetDescription()); const CPLString osFullFileName = - CPLFormFilename(osPath, osFileName, nullptr); + CPLFormFilenameSafe(osPath, osFileName, nullptr); poCompressedDS = GDALDataset::FromHandle(GDALOpen(osFullFileName, GA_ReadOnly)); @@ -1425,11 +1427,11 @@ GDALDataset *PDSDataset::Open(GDALOpenInfo *poOpenInfo) if (EQUAL(osEncodingType, "ZIP") && !osCompressedFilename.empty() && !osUncompressedFilename.empty()) { - const CPLString osPath = CPLGetPath(poDS->GetDescription()); + const CPLString osPath = CPLGetPathSafe(poDS->GetDescription()); osCompressedFilename = - CPLFormFilename(osPath, osCompressedFilename, nullptr); + CPLFormFilenameSafe(osPath, osCompressedFilename, nullptr); osUncompressedFilename = - CPLFormFilename(osPath, osUncompressedFilename, nullptr); + CPLFormFilenameSafe(osPath, osUncompressedFilename, nullptr); if (VSIStatExL(osCompressedFilename, &sStat, VSI_STAT_EXISTS_FLAG) == 0 && VSIStatExL(osUncompressedFilename, &sStat, VSI_STAT_EXISTS_FLAG) != diff --git a/frmts/plmosaic/plmosaicdataset.cpp b/frmts/plmosaic/plmosaicdataset.cpp index 3026e35d986b..fd338d49d95c 100644 --- a/frmts/plmosaic/plmosaicdataset.cpp +++ b/frmts/plmosaic/plmosaicdataset.cpp @@ -328,7 +328,7 @@ PLMosaicDataset::PLMosaicDataset() adfGeoTransform[5] = 1; SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE"); - osCachePathRoot = CPLGetPath(CPLGenerateTempFilename("")); + osCachePathRoot = CPLGetPathSafe(CPLGenerateTempFilenameSafe("").c_str()); } /************************************************************************/ @@ -678,9 +678,9 @@ CPLString PLMosaicDataset::GetMosaicCachePath() if (!osCachePathRoot.empty()) { const CPLString osCachePath( - CPLFormFilename(osCachePathRoot, "plmosaic_cache", nullptr)); + CPLFormFilenameSafe(osCachePathRoot, "plmosaic_cache", nullptr)); const CPLString osMosaicPath( - CPLFormFilename(osCachePath, osMosaic, nullptr)); + CPLFormFilenameSafe(osCachePath, osMosaic, nullptr)); return osMosaicPath; } @@ -696,9 +696,9 @@ void PLMosaicDataset::CreateMosaicCachePathIfNecessary() if (!osCachePathRoot.empty()) { const CPLString osCachePath( - CPLFormFilename(osCachePathRoot, "plmosaic_cache", nullptr)); + CPLFormFilenameSafe(osCachePathRoot, "plmosaic_cache", nullptr)); const CPLString osMosaicPath( - CPLFormFilename(osCachePath, osMosaic, nullptr)); + CPLFormFilenameSafe(osCachePath, osMosaic, nullptr)); VSIStatBufL sStatBuf; if (VSIStatL(osMosaicPath, &sStatBuf) != 0) @@ -1256,10 +1256,10 @@ GDALDataset *PLMosaicDataset::GetMetaTile(int tile_x, int tile_y) const CPLString osMosaicPath(GetMosaicCachePath()); osTmpFilename = - CPLFormFilename(osMosaicPath, - CPLSPrintf("%s_%s.tif", osMosaic.c_str(), - CPLGetFilename(osTilename)), - nullptr); + CPLFormFilenameSafe(osMosaicPath, + CPLSPrintf("%s_%s.tif", osMosaic.c_str(), + CPLGetFilename(osTilename)), + nullptr); VSIStatBufL sStatBuf; CPLString osURL = osQuadsURL; diff --git a/frmts/prf/phprfdataset.cpp b/frmts/prf/phprfdataset.cpp index 05665f297415..1c007ca69467 100644 --- a/frmts/prf/phprfdataset.cpp +++ b/frmts/prf/phprfdataset.cpp @@ -169,11 +169,11 @@ int PhPrfDataset::Identify(GDALOpenInfo *poOpenInfo) return FALSE; } - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), PH_PRF_EXT)) + if (poOpenInfo->IsExtensionEqualToCI(PH_PRF_EXT)) { return TRUE; } - else if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), PH_DEM_EXT)) + else if (poOpenInfo->IsExtensionEqualToCI(PH_DEM_EXT)) { return TRUE; } @@ -355,11 +355,11 @@ GDALDataset *PhPrfDataset::Open(GDALOpenInfo *poOpenInfo) { ph_format eFormat; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), PH_PRF_EXT)) + if (poOpenInfo->IsExtensionEqualToCI(PH_PRF_EXT)) { eFormat = ph_megatiff; } - else if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), PH_DEM_EXT)) + else if (poOpenInfo->IsExtensionEqualToCI(PH_DEM_EXT)) { eFormat = ph_xdem; } @@ -385,9 +385,9 @@ GDALDataset *PhPrfDataset::Open(GDALOpenInfo *poOpenInfo) int nSizeY = 0; int nBandCount = 0; GDALDataType eResultDatatype = GDT_Unknown; - CPLString osPartsBasePath(CPLGetPath(poOpenInfo->pszFilename)); + CPLString osPartsBasePath(CPLGetPathSafe(poOpenInfo->pszFilename)); CPLString osPartsPath(osPartsBasePath + "/" + - CPLGetBasename(poOpenInfo->pszFilename)); + CPLGetBasenameSafe(poOpenInfo->pszFilename)); CPLString osPartsExt; double adfGeoTrans[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; bool bGeoTransOk = false; @@ -608,8 +608,9 @@ GDALDataset *PhPrfDataset::Open(GDALOpenInfo *poOpenInfo) } } - const char *pszPrj = CPLResetExtension(poOpenInfo->pszFilename, "prj"); - VSILFILE *const fp = VSIFOpenL(pszPrj, "rt"); + const std::string osPrj = + CPLResetExtensionSafe(poOpenInfo->pszFilename, "prj"); + VSILFILE *const fp = VSIFOpenL(osPrj.c_str(), "rt"); if (fp != nullptr) { const size_t nBufMax = 100000; diff --git a/frmts/r/rdataset.cpp b/frmts/r/rdataset.cpp index e239a6c8a54c..6879b7cdcf27 100644 --- a/frmts/r/rdataset.cpp +++ b/frmts/r/rdataset.cpp @@ -313,7 +313,7 @@ int RDataset::Identify(GDALOpenInfo *poOpenInfo) // If the extension is .rda and the file type is gzip // compressed we assume it is a gzipped R binary file. if (memcmp(poOpenInfo->pabyHeader, "\037\213\b", 3) == 0 && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "rda")) + poOpenInfo->IsExtensionEqualToCI("rda")) return TRUE; // Is this an ASCII or XDR binary R file? diff --git a/frmts/rasterlite/rasterlitecreatecopy.cpp b/frmts/rasterlite/rasterlitecreatecopy.cpp index 70f424cbc0e9..cb78648b3043 100644 --- a/frmts/rasterlite/rasterlitecreatecopy.cpp +++ b/frmts/rasterlite/rasterlitecreatecopy.cpp @@ -405,7 +405,7 @@ GDALDataset *RasterliteCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, if (nTokens == 0) { osDBName = pszFilenameWithoutPrefix; - osTableName = CPLGetBasename(pszFilenameWithoutPrefix); + osTableName = CPLGetBasenameSafe(pszFilenameWithoutPrefix); } else { @@ -439,7 +439,7 @@ GDALDataset *RasterliteCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, "specified"); return nullptr; } - osTableName = CPLGetBasename(osDBName.c_str()); + osTableName = CPLGetBasenameSafe(osDBName.c_str()); } CPLString osRasterLayer; diff --git a/frmts/rasterlite/rasterlitedrivercore.cpp b/frmts/rasterlite/rasterlitedrivercore.cpp index 89f049bfeda9..f3377f9fdb13 100644 --- a/frmts/rasterlite/rasterlitedrivercore.cpp +++ b/frmts/rasterlite/rasterlitedrivercore.cpp @@ -27,8 +27,8 @@ int RasterliteDriverIdentify(GDALOpenInfo *poOpenInfo) } #endif - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MBTILES") && - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "GPKG") && + if (!poOpenInfo->IsExtensionEqualToCI("MBTILES") && + !poOpenInfo->IsExtensionEqualToCI("GPKG") && poOpenInfo->nHeaderBytes >= 1024 && poOpenInfo->pabyHeader && STARTS_WITH_CI((const char *)poOpenInfo->pabyHeader, "SQLite Format 3") && diff --git a/frmts/raw/ace2dataset.cpp b/frmts/raw/ace2dataset.cpp index 9feabc42f4e3..1acc5a01408b 100644 --- a/frmts/raw/ace2dataset.cpp +++ b/frmts/raw/ace2dataset.cpp @@ -190,7 +190,7 @@ char **ACE2RasterBand::GetCategoryNames() int ACE2Dataset::Identify(GDALOpenInfo *poOpenInfo) { - if (!(EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "ACE2") || + if (!(poOpenInfo->IsExtensionEqualToCI("ACE2") || strstr(poOpenInfo->pszFilename, ".ACE2.gz") || strstr(poOpenInfo->pszFilename, ".ace2.gz"))) return FALSE; @@ -208,7 +208,8 @@ GDALDataset *ACE2Dataset::Open(GDALOpenInfo *poOpenInfo) if (!Identify(poOpenInfo)) return nullptr; - const char *pszBasename = CPLGetBasename(poOpenInfo->pszFilename); + const std::string osBasename = CPLGetBasenameSafe(poOpenInfo->pszFilename); + const char *pszBasename = osBasename.c_str(); if (strlen(pszBasename) < 7) return nullptr; diff --git a/frmts/raw/btdataset.cpp b/frmts/raw/btdataset.cpp index 48d765c15a44..7b7e5dc09ffb 100644 --- a/frmts/raw/btdataset.cpp +++ b/frmts/raw/btdataset.cpp @@ -532,8 +532,9 @@ CPLErr BTDataset::SetSpatialRef(const OGRSpatialReference *poSRS) m_oSRS.exportToWkt(&pszProjection, apszOptions); if (pszProjection) { - const char *pszPrjFile = CPLResetExtension(GetDescription(), "prj"); - VSILFILE *fp = VSIFOpenL(pszPrjFile, "wt"); + const std::string osPrjFile = + CPLResetExtensionSafe(GetDescription(), "prj"); + VSILFILE *fp = VSIFOpenL(osPrjFile.c_str(), "wt"); if (fp != nullptr) { CPL_IGNORE_RET_VAL(VSIFPrintfL(fp, "%s\n", pszProjection)); @@ -639,9 +640,9 @@ GDALDataset *BTDataset::Open(GDALOpenInfo *poOpenInfo) if (poDS->nVersionCode >= 12 && poDS->abyHeader[60] != 0) { - const char *pszPrjFile = - CPLResetExtension(poOpenInfo->pszFilename, "prj"); - VSILFILE *fp = VSIFOpenL(pszPrjFile, "rt"); + const std::string osPrjFile = + CPLResetExtensionSafe(poOpenInfo->pszFilename, "prj"); + VSILFILE *fp = VSIFOpenL(osPrjFile.c_str(), "rt"); if (fp != nullptr) { const int nBufMax = 10000; diff --git a/frmts/raw/byndataset.cpp b/frmts/raw/byndataset.cpp index e36432527bd3..406e2e7eb98c 100644 --- a/frmts/raw/byndataset.cpp +++ b/frmts/raw/byndataset.cpp @@ -175,7 +175,7 @@ int BYNDataset::Identify(GDALOpenInfo *poOpenInfo) /* Check file extension (.byn/.err) */ /* -------------------------------------------------------------------- */ #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - const char *pszFileExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszFileExtension = poOpenInfo->osExtension.c_str(); if (!EQUAL(pszFileExtension, "byn") && !EQUAL(pszFileExtension, "err")) { @@ -720,19 +720,16 @@ GDALDataset *BYNDataset::Create(const char *pszFilename, int nXSize, int nYSize, /* Check file extension (.byn/.err) */ /* -------------------------------------------------------------------- */ - char *pszFileExtension = CPLStrdup(CPLGetExtension(pszFilename)); + const std::string osExt = CPLGetExtensionSafe(pszFilename); - if (!EQUAL(pszFileExtension, "byn") && !EQUAL(pszFileExtension, "err")) + if (!EQUAL(osExt.c_str(), "byn") && !EQUAL(osExt.c_str(), "err")) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create byn file with extension other than byn/err."); - CPLFree(pszFileExtension); return nullptr; } - CPLFree(pszFileExtension); - /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ diff --git a/frmts/raw/cpgdataset.cpp b/frmts/raw/cpgdataset.cpp index ce8425181c99..9e65d4334f3f 100644 --- a/frmts/raw/cpgdataset.cpp +++ b/frmts/raw/cpgdataset.cpp @@ -244,9 +244,10 @@ int CPGDataset::AdjustFilename(char **pszFilename, const char *pszPolarization, // TODO: Eventually we should handle upper/lower case. if (EQUAL(pszPolarization, "stokes")) { - const char *pszNewName = CPLResetExtension(*pszFilename, pszExtension); + const std::string osNewName = + CPLResetExtensionSafe(*pszFilename, pszExtension); CPLFree(*pszFilename); - *pszFilename = CPLStrdup(pszNewName); + *pszFilename = CPLStrdup(osNewName.c_str()); } else if (strlen(pszPolarization) == 2) { @@ -261,15 +262,17 @@ int CPGDataset::AdjustFilename(char **pszFilename, const char *pszPolarization, return FALSE; strncpy(subptr, pszPolarization, 2); - const char *pszNewName = CPLResetExtension(*pszFilename, pszExtension); + const std::string osNewName = + CPLResetExtensionSafe(*pszFilename, pszExtension); CPLFree(*pszFilename); - *pszFilename = CPLStrdup(pszNewName); + *pszFilename = CPLStrdup(osNewName.c_str()); } else { - const char *pszNewName = CPLResetExtension(*pszFilename, pszExtension); + const std::string osNewName = + CPLResetExtensionSafe(*pszFilename, pszExtension); CPLFree(*pszFilename); - *pszFilename = CPLStrdup(pszNewName); + *pszFilename = CPLStrdup(osNewName.c_str()); } VSIStatBufL sStatBuf; return VSIStatL(*pszFilename, &sStatBuf) == 0; diff --git a/frmts/raw/ehdrdataset.cpp b/frmts/raw/ehdrdataset.cpp index 70205eace122..c81e132c1e8a 100644 --- a/frmts/raw/ehdrdataset.cpp +++ b/frmts/raw/ehdrdataset.cpp @@ -476,7 +476,7 @@ void EHdrDataset::ResetKeyValue(const char *pszKey, const char *pszValue) void EHdrDataset::RewriteCLR(GDALRasterBand *poBand) const { - CPLString osCLRFilename = CPLResetExtension(GetDescription(), "clr"); + CPLString osCLRFilename = CPLResetExtensionSafe(GetDescription(), "clr"); GDALColorTable *poTable = poBand->GetColorTable(); GDALRasterAttributeTable *poRAT = poBand->GetDefaultRAT(); if (poTable || poRAT) @@ -568,7 +568,8 @@ CPLErr EHdrDataset::SetSpatialRef(const OGRSpatialReference *poSRS) if (pszESRI_SRS) { // Write to .prj file. - CPLString osPrjFilename = CPLResetExtension(GetDescription(), "prj"); + CPLString osPrjFilename = + CPLResetExtensionSafe(GetDescription(), "prj"); VSILFILE *fp = VSIFOpenL(osPrjFilename.c_str(), "wt"); if (fp != nullptr) { @@ -657,10 +658,10 @@ CPLErr EHdrDataset::SetGeoTransform(double *padfGeoTransform) CPLErr EHdrDataset::RewriteHDR() { - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); const CPLString osHDRFilename = - CPLFormCIFilename(osPath, osName, osHeaderExt); + CPLFormCIFilenameSafe(osPath, osName, osHeaderExt); // Write .hdr file. VSILFILE *fp = VSIFOpenL(osHDRFilename, "wt"); @@ -697,9 +698,10 @@ CPLErr EHdrDataset::RewriteHDR() CPLErr EHdrDataset::RewriteSTX() const { - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); - const CPLString osSTXFilename = CPLFormCIFilename(osPath, osName, "stx"); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); + const CPLString osSTXFilename = + CPLFormCIFilenameSafe(osPath, osName, "stx"); VSILFILE *fp = VSIFOpenL(osSTXFilename, "wt"); if (fp == nullptr) @@ -739,9 +741,10 @@ CPLErr EHdrDataset::RewriteSTX() const CPLErr EHdrDataset::ReadSTX() const { - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); - const CPLString osSTXFilename = CPLFormCIFilename(osPath, osName, "stx"); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); + const CPLString osSTXFilename = + CPLFormCIFilenameSafe(osPath, osName, "stx"); VSILFILE *fp = VSIFOpenL(osSTXFilename, "rt"); if (fp == nullptr) @@ -822,9 +825,10 @@ CPLErr EHdrDataset::ReadSTX() const CPLString EHdrDataset::GetImageRepFilename(const char *pszFilename) { - const CPLString osPath = CPLGetPath(pszFilename); - const CPLString osName = CPLGetBasename(pszFilename); - const CPLString osREPFilename = CPLFormCIFilename(osPath, osName, "rep"); + const CPLString osPath = CPLGetPathSafe(pszFilename); + const CPLString osName = CPLGetBasenameSafe(pszFilename); + const CPLString osREPFilename = + CPLFormCIFilenameSafe(osPath, osName, "rep"); VSIStatBufL sStatBuf; if (VSIStatExL(osREPFilename.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) @@ -833,19 +837,20 @@ CPLString EHdrDataset::GetImageRepFilename(const char *pszFilename) if (EQUAL(CPLGetFilename(pszFilename), "imspatio.bil") || EQUAL(CPLGetFilename(pszFilename), "haspatio.bil")) { - CPLString osImageRepFilename(CPLFormCIFilename(osPath, "image", "rep")); + CPLString osImageRepFilename( + CPLFormCIFilenameSafe(osPath, "image", "rep")); if (VSIStatExL(osImageRepFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) return osImageRepFilename; // Try in the upper directories if not found in the BIL image directory. - CPLString dirName(CPLGetDirname(osPath)); + CPLString dirName(CPLGetDirnameSafe(osPath)); if (CPLIsFilenameRelative(osPath.c_str())) { char *cwd = CPLGetCurrentDir(); if (cwd) { - dirName = CPLFormFilename(cwd, dirName.c_str(), nullptr); + dirName = CPLFormFilenameSafe(cwd, dirName.c_str(), nullptr); CPLFree(cwd); } } @@ -853,7 +858,7 @@ CPLString EHdrDataset::GetImageRepFilename(const char *pszFilename) EQUAL(dirName, "/") == FALSE) { osImageRepFilename = - CPLFormCIFilename(dirName.c_str(), "image", "rep"); + CPLFormCIFilenameSafe(dirName.c_str(), "image", "rep"); if (VSIStatExL(osImageRepFilename.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) return osImageRepFilename; @@ -863,7 +868,7 @@ CPLString EHdrDataset::GetImageRepFilename(const char *pszFilename) { break; } - dirName = CPLString(CPLGetDirname(dirName)); + dirName = CPLString(CPLGetDirnameSafe(dirName)); } } return CPLString(); @@ -876,29 +881,29 @@ CPLString EHdrDataset::GetImageRepFilename(const char *pszFilename) char **EHdrDataset::GetFileList() { - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); // Main data file, etc. char **papszFileList = GDALPamDataset::GetFileList(); // Header file. - CPLString osFilename = CPLFormCIFilename(osPath, osName, osHeaderExt); + CPLString osFilename = CPLFormCIFilenameSafe(osPath, osName, osHeaderExt); papszFileList = CSLAddString(papszFileList, osFilename); // Statistics file - osFilename = CPLFormCIFilename(osPath, osName, "stx"); + osFilename = CPLFormCIFilenameSafe(osPath, osName, "stx"); VSIStatBufL sStatBuf; if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) papszFileList = CSLAddString(papszFileList, osFilename); // color table file. - osFilename = CPLFormCIFilename(osPath, osName, "clr"); + osFilename = CPLFormCIFilenameSafe(osPath, osName, "clr"); if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) papszFileList = CSLAddString(papszFileList, osFilename); // projections file. - osFilename = CPLFormCIFilename(osPath, osName, "prj"); + osFilename = CPLFormCIFilenameSafe(osPath, osName, "prj"); if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) papszFileList = CSLAddString(papszFileList, osFilename); @@ -927,12 +932,11 @@ GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) return nullptr; // Tear apart the filename to form a .HDR filename. - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); - const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename); const char *pszHeaderExt = "hdr"; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "SRC") && - osName.size() == 7 && + if (poOpenInfo->IsExtensionEqualToCI("SRC") && osName.size() == 7 && (osName[0] == 'e' || osName[0] == 'E' || osName[0] == 'w' || osName[0] == 'W') && (osName[4] == 'n' || osName[4] == 'N' || osName[4] == 's' || @@ -948,16 +952,17 @@ GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) if (papszSiblingFiles) { const int iFile = CSLFindString( - papszSiblingFiles, CPLFormFilename(nullptr, osName, pszHeaderExt)); + papszSiblingFiles, + CPLFormFilenameSafe(nullptr, osName, pszHeaderExt).c_str()); if (iFile < 0) // Return if there is no corresponding .hdr file. return nullptr; osHDRFilename = - CPLFormFilename(osPath, papszSiblingFiles[iFile], nullptr); + CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr); } else { - osHDRFilename = CPLFormCIFilename(osPath, osName, pszHeaderExt); + osHDRFilename = CPLFormCIFilenameSafe(osPath, osName, pszHeaderExt); } const bool bSelectedHDR = EQUAL(osHDRFilename, poOpenInfo->pszFilename); @@ -1159,7 +1164,7 @@ GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) // If the extension is FLT it is likely a floating point file. if (chPixelType == 'N') { - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "FLT")) + if (poOpenInfo->IsExtensionEqualToCI("FLT")) chPixelType = 'F'; } @@ -1350,16 +1355,16 @@ GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) poOpenInfo->pszFilename, "wld", poDS->adfGeoTransform)); // Check for a .prj file. - const char *pszPrjFilename = CPLFormCIFilename(osPath, osName, "prj"); + std::string osPrjFilename = CPLFormCIFilenameSafe(osPath, osName, "prj"); - fp = VSIFOpenL(pszPrjFilename, "r"); + fp = VSIFOpenL(osPrjFilename.c_str(), "r"); // .hdr files from http://www.worldclim.org/futdown.htm have the projection // info in the .hdr file itself. if (fp == nullptr && bHasInternalProjection) { - pszPrjFilename = osHDRFilename; - fp = VSIFOpenL(pszPrjFilename, "r"); + osPrjFilename = osHDRFilename; + fp = VSIFOpenL(osPrjFilename.c_str(), "r"); } if (fp != nullptr) @@ -1367,7 +1372,7 @@ GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) CPL_IGNORE_RET_VAL(VSIFCloseL(fp)); fp = nullptr; - char **papszLines = CSLLoad(pszPrjFilename); + char **papszLines = CSLLoad(osPrjFilename.c_str()); if (poDS->m_oSRS.importFromESRI(papszLines) == OGRERR_NONE) { @@ -1527,11 +1532,12 @@ GDALDataset *EHdrDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) } // Check for a color table. - const char *pszCLRFilename = CPLFormCIFilename(osPath, osName, "clr"); + const std::string osCLRFilename = + CPLFormCIFilenameSafe(osPath, osName, "clr"); // Only read the .clr for byte, int16 or uint16 bands. if (nItemSize <= 2) - fp = VSIFOpenL(pszCLRFilename, "r"); + fp = VSIFOpenL(osCLRFilename.c_str(), "r"); else fp = nullptr; @@ -1678,7 +1684,7 @@ GDALDataset *EHdrDataset::Create(const char *pszFilename, int nXSize, // Create the hdr filename. char *const pszHdrFilename = - CPLStrdup(CPLResetExtension(pszFilename, "hdr")); + CPLStrdup(CPLResetExtensionSafe(pszFilename, "hdr").c_str()); // Open the file. fp = VSIFOpenL(pszHdrFilename, "wt"); diff --git a/frmts/raw/eirdataset.cpp b/frmts/raw/eirdataset.cpp index 4184644049a9..4494e2da41cf 100644 --- a/frmts/raw/eirdataset.cpp +++ b/frmts/raw/eirdataset.cpp @@ -280,9 +280,9 @@ GDALDataset *EIRDataset::Open(GDALOpenInfo *poOpenInfo) CPLStringList aosHDR; // default raster file: same name with no extension - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); - const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename); - CPLString osRasterFilename = CPLFormCIFilename(osPath, osName, ""); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename); + CPLString osRasterFilename = CPLFormCIFilenameSafe(osPath, osName, ""); // parse the header file const char *pszLine = nullptr; @@ -327,7 +327,7 @@ GDALDataset *EIRDataset::Open(GDALOpenInfo *poOpenInfo) } else if (EQUAL(aosTokens[0], "PIXEL_FILES")) { - osRasterFilename = CPLFormCIFilename(osPath, aosTokens[1], ""); + osRasterFilename = CPLFormCIFilenameSafe(osPath, aosTokens[1], ""); } else if (EQUAL(aosTokens[0], "FORMAT")) { diff --git a/frmts/raw/envidataset.cpp b/frmts/raw/envidataset.cpp index f2955ab2832f..184682e29b62 100644 --- a/frmts/raw/envidataset.cpp +++ b/frmts/raw/envidataset.cpp @@ -1782,7 +1782,7 @@ static unsigned byteSwapUInt(unsigned swapMe) void ENVIDataset::ProcessStatsFile() { - osStaFilename = CPLResetExtension(pszHDRFilename, "sta"); + osStaFilename = CPLResetExtensionSafe(pszHDRFilename, "sta"); VSILFILE *fpStaFile = VSIFOpenL(osStaFilename, "rb"); if (!fpStaFile) @@ -2008,49 +2008,52 @@ ENVIDataset *ENVIDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) { // First try hdr as an extra extension osHdrFilename = - CPLFormFilename(nullptr, poOpenInfo->pszFilename, "hdr"); + CPLFormFilenameSafe(nullptr, poOpenInfo->pszFilename, "hdr"); fpHeader = VSIFOpenL(osHdrFilename, pszMode); if (fpHeader == nullptr && VSIIsCaseSensitiveFS(osHdrFilename)) { osHdrFilename = - CPLFormFilename(nullptr, poOpenInfo->pszFilename, "HDR"); + CPLFormFilenameSafe(nullptr, poOpenInfo->pszFilename, "HDR"); fpHeader = VSIFOpenL(osHdrFilename, pszMode); } // Otherwise, try .hdr as a replacement extension if (fpHeader == nullptr) { - osHdrFilename = CPLResetExtension(poOpenInfo->pszFilename, "hdr"); + osHdrFilename = + CPLResetExtensionSafe(poOpenInfo->pszFilename, "hdr"); fpHeader = VSIFOpenL(osHdrFilename, pszMode); } if (fpHeader == nullptr && VSIIsCaseSensitiveFS(osHdrFilename)) { - osHdrFilename = CPLResetExtension(poOpenInfo->pszFilename, "HDR"); + osHdrFilename = + CPLResetExtensionSafe(poOpenInfo->pszFilename, "HDR"); fpHeader = VSIFOpenL(osHdrFilename, pszMode); } } else { // Now we need to tear apart the filename to form a .HDR filename. - CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); + CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); CPLString osName = CPLGetFilename(poOpenInfo->pszFilename); // First try hdr as an extra extension - int iFile = CSLFindString(papszSiblingFiles, - CPLFormFilename(nullptr, osName, "hdr")); + int iFile = + CSLFindString(papszSiblingFiles, + CPLFormFilenameSafe(nullptr, osName, "hdr").c_str()); if (iFile < 0) { // Otherwise, try .hdr as a replacement extension iFile = CSLFindString(papszSiblingFiles, - CPLResetExtension(osName, "hdr")); + CPLResetExtensionSafe(osName, "hdr").c_str()); } if (iFile >= 0) { osHdrFilename = - CPLFormFilename(osPath, papszSiblingFiles[iFile], nullptr); + CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr); fpHeader = VSIFOpenL(osHdrFilename, pszMode); } } @@ -2084,7 +2087,7 @@ ENVIDataset *ENVIDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) } // Has the user selected the .hdr file to open? - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "hdr")) + if (poOpenInfo->IsExtensionEqualToCI("hdr")) { CPLError(CE_Failure, CPLE_AppDefined, "The selected file is an ENVI header file, but to " @@ -2097,7 +2100,7 @@ ENVIDataset *ENVIDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) } // Has the user selected the .sta (stats) file to open? - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "sta")) + if (poOpenInfo->IsExtensionEqualToCI("sta")) { CPLError(CE_Failure, CPLE_AppDefined, "The selected file is an ENVI statistics file. " @@ -2119,7 +2122,7 @@ ENVIDataset *ENVIDataset::Open(GDALOpenInfo *poOpenInfo, bool bFileSizeCheck) // In case, there is no interleave keyword, we try to derive it from the // file extension. CPLString osInterleave = poDS->m_aosHeader.FetchNameValueDef( - "interleave", CPLGetExtension(poOpenInfo->pszFilename)); + "interleave", poOpenInfo->osExtension.c_str()); if (!STARTS_WITH_CI(osInterleave, "BSQ") && !STARTS_WITH_CI(osInterleave, "BIP") && @@ -2747,19 +2750,19 @@ GDALDataset *ENVIDataset::Create(const char *pszFilename, int nXSize, } // Create the .hdr filename. - const char *pszHDRFilename = nullptr; + std::string osHDRFilename; const char *pszSuffix = CSLFetchNameValue(papszOptions, "SUFFIX"); if (pszSuffix && STARTS_WITH_CI(pszSuffix, "ADD")) - pszHDRFilename = CPLFormFilename(nullptr, pszFilename, "hdr"); + osHDRFilename = CPLFormFilenameSafe(nullptr, pszFilename, "hdr"); else - pszHDRFilename = CPLResetExtension(pszFilename, "hdr"); + osHDRFilename = CPLResetExtensionSafe(pszFilename, "hdr"); // Open the file. - fp = VSIFOpenL(pszHDRFilename, "wt"); + fp = VSIFOpenL(osHDRFilename.c_str(), "wt"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Attempt to create file `%s' failed.", pszHDRFilename); + "Attempt to create file `%s' failed.", osHDRFilename.c_str()); return nullptr; } diff --git a/frmts/raw/fastdataset.cpp b/frmts/raw/fastdataset.cpp index 619d3f65e7b6..2695a2e3c486 100644 --- a/frmts/raw/fastdataset.cpp +++ b/frmts/raw/fastdataset.cpp @@ -215,9 +215,9 @@ int FASTDataset::OpenChannel(const char *pszFilenameIn, int iBand) VSILFILE *FASTDataset::FOpenChannel(const char *pszBandname, int iBand, int iFASTBand) { - const char *pszChannelFilename = nullptr; - char *pszPrefix = CPLStrdup(CPLGetBasename(pszFilename)); - char *pszSuffix = CPLStrdup(CPLGetExtension(pszFilename)); + std::string osChannelFilename; + const std::string osPrefix = CPLGetBasenameSafe(pszFilename); + const std::string osSuffix = CPLGetExtensionSafe(pszFilename); fpChannels[iBand] = nullptr; @@ -226,78 +226,80 @@ VSILFILE *FASTDataset::FOpenChannel(const char *pszBandname, int iBand, case LANDSAT: if (pszBandname && !EQUAL(pszBandname, "")) { - pszChannelFilename = - CPLFormCIFilename(pszDirname, pszBandname, nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + osChannelFilename = + CPLFormCIFilenameSafe(pszDirname, pszBandname, nullptr); + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( - pszDirname, CPLSPrintf("%s.b%02d", pszPrefix, iFASTBand), + osChannelFilename = CPLFormFilenameSafe( + pszDirname, + CPLSPrintf("%s.b%02d", osPrefix.c_str(), iFASTBand), nullptr); - CPL_IGNORE_RET_VAL(OpenChannel(pszChannelFilename, iBand)); + CPL_IGNORE_RET_VAL( + OpenChannel(osChannelFilename.c_str(), iBand)); } break; case IRS: default: - pszChannelFilename = CPLFormFilename( - pszDirname, CPLSPrintf("%s.%d", pszPrefix, iFASTBand), - pszSuffix); - if (OpenChannel(pszChannelFilename, iBand)) + osChannelFilename = CPLFormFilenameSafe( + pszDirname, CPLSPrintf("%s.%d", osPrefix.c_str(), iFASTBand), + osSuffix.c_str()); + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( - pszDirname, CPLSPrintf("IMAGERY%d", iFASTBand), pszSuffix); - if (OpenChannel(pszChannelFilename, iBand)) + osChannelFilename = CPLFormFilenameSafe( + pszDirname, CPLSPrintf("IMAGERY%d", iFASTBand), + osSuffix.c_str()); + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( - pszDirname, CPLSPrintf("imagery%d", iFASTBand), pszSuffix); - if (OpenChannel(pszChannelFilename, iBand)) + osChannelFilename = CPLFormFilenameSafe( + pszDirname, CPLSPrintf("imagery%d", iFASTBand), + osSuffix.c_str()); + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("IMAGERY%d.DAT", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("imagery%d.dat", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("IMAGERY%d.dat", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("imagery%d.DAT", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( - pszDirname, CPLSPrintf("BAND%d", iFASTBand), pszSuffix); - if (OpenChannel(pszChannelFilename, iBand)) + osChannelFilename = CPLFormFilenameSafe( + pszDirname, CPLSPrintf("BAND%d", iFASTBand), osSuffix.c_str()); + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( - pszDirname, CPLSPrintf("band%d", iFASTBand), pszSuffix); - if (OpenChannel(pszChannelFilename, iBand)) + osChannelFilename = CPLFormFilenameSafe( + pszDirname, CPLSPrintf("band%d", iFASTBand), osSuffix.c_str()); + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("BAND%d.DAT", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("band%d.dat", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("BAND%d.dat", iFASTBand), nullptr); - if (OpenChannel(pszChannelFilename, iBand)) + if (OpenChannel(osChannelFilename.c_str(), iBand)) break; - pszChannelFilename = CPLFormFilename( + osChannelFilename = CPLFormFilenameSafe( pszDirname, CPLSPrintf("band%d.DAT", iFASTBand), nullptr); - CPL_IGNORE_RET_VAL(OpenChannel(pszChannelFilename, iBand)); + CPL_IGNORE_RET_VAL(OpenChannel(osChannelFilename.c_str(), iBand)); break; } CPLDebug("FAST", "Band %d filename=%s", iBand + 1, - pszChannelFilename ? pszChannelFilename : "(null)"); + osChannelFilename.c_str()); - CPLFree(pszPrefix); - CPLFree(pszSuffix); return fpChannels[iBand]; } @@ -573,7 +575,8 @@ GDALDataset *FASTDataset::Open(GDALOpenInfo *poOpenInfo) std::swap(poDS->fpHeader, poOpenInfo->fpL); poDS->pszFilename = poOpenInfo->pszFilename; - poDS->pszDirname = CPLStrdup(CPLGetDirname(poOpenInfo->pszFilename)); + poDS->pszDirname = + CPLStrdup(CPLGetDirnameSafe(poOpenInfo->pszFilename).c_str()); /* -------------------------------------------------------------------- */ /* Read the administrative record. */ @@ -663,12 +666,13 @@ GDALDataset *FASTDataset::Open(GDALOpenInfo *poOpenInfo) { // See appendix F in // http://www.euromap.de/download/p5fast_20050301.pdf - const CPLString osSuffix = CPLGetExtension(poDS->pszFilename); + const CPLString osSuffix = + CPLGetExtensionSafe(poDS->pszFilename); const char *papszBasenames[] = {"BANDF", "bandf", "BANDA", "banda"}; for (int i = 0; i < 4; i++) { - const CPLString osChannelFilename = CPLFormFilename( + const CPLString osChannelFilename = CPLFormFilenameSafe( poDS->pszDirname, papszBasenames[i], osSuffix); if (poDS->OpenChannel(osChannelFilename, 0)) { diff --git a/frmts/raw/genbindataset.cpp b/frmts/raw/genbindataset.cpp index c9fff1fc92f0..326e8133c5b6 100644 --- a/frmts/raw/genbindataset.cpp +++ b/frmts/raw/genbindataset.cpp @@ -266,14 +266,14 @@ CPLErr GenBinDataset::GetGeoTransform(double *padfTransform) char **GenBinDataset::GetFileList() { - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); // Main data file, etc. char **papszFileList = GDALPamDataset::GetFileList(); // Header file. - const CPLString osFilename = CPLFormCIFilename(osPath, osName, "hdr"); + const CPLString osFilename = CPLFormCIFilenameSafe(osPath, osName, "hdr"); papszFileList = CSLAddString(papszFileList, osFilename); return papszFileList; @@ -401,24 +401,25 @@ GDALDataset *GenBinDataset::Open(GDALOpenInfo *poOpenInfo) /* Now we need to tear apart the filename to form a .HDR */ /* filename. */ /* -------------------------------------------------------------------- */ - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); - const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + const CPLString osName = CPLGetBasenameSafe(poOpenInfo->pszFilename); CPLString osHDRFilename; char **papszSiblingFiles = poOpenInfo->GetSiblingFiles(); if (papszSiblingFiles) { - const int iFile = CSLFindString( - papszSiblingFiles, CPLFormFilename(nullptr, osName, "hdr")); + const int iFile = + CSLFindString(papszSiblingFiles, + CPLFormFilenameSafe(nullptr, osName, "hdr").c_str()); if (iFile < 0) // return if there is no corresponding .hdr file return nullptr; osHDRFilename = - CPLFormFilename(osPath, papszSiblingFiles[iFile], nullptr); + CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr); } else { - osHDRFilename = CPLFormCIFilename(osPath, osName, "hdr"); + osHDRFilename = CPLFormCIFilenameSafe(osPath, osName, "hdr"); } const bool bSelectedHDR = EQUAL(osHDRFilename, poOpenInfo->pszFilename); diff --git a/frmts/raw/gtxdataset.cpp b/frmts/raw/gtxdataset.cpp index 3f38ac16561a..a2e3372bd392 100644 --- a/frmts/raw/gtxdataset.cpp +++ b/frmts/raw/gtxdataset.cpp @@ -204,7 +204,7 @@ int GTXDataset::Identify(GDALOpenInfo *poOpenInfo) if (poOpenInfo->nHeaderBytes < 40) return FALSE; - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "gtx")) + if (!poOpenInfo->IsExtensionEqualToCI("gtx")) return FALSE; return TRUE; @@ -396,7 +396,7 @@ GDALDataset *GTXDataset::Create(const char *pszFilename, int nXSize, int nYSize, return nullptr; } - if (!EQUAL(CPLGetExtension(pszFilename), "gtx")) + if (!EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "gtx")) { CPLError(CE_Failure, CPLE_AppDefined, "Attempt to create gtx file with extension other than gtx."); diff --git a/frmts/raw/hkvdataset.cpp b/frmts/raw/hkvdataset.cpp index 7adb93fe4e47..5dc12dfd9357 100644 --- a/frmts/raw/hkvdataset.cpp +++ b/frmts/raw/hkvdataset.cpp @@ -373,9 +373,9 @@ CPLErr HKVDataset::Close() if (bGeorefChanged) { - const char *pszFilename = - CPLFormFilename(pszPath, "georef", nullptr); - CSLSave(papszGeoref, pszFilename); + const std::string osFilename = + CPLFormFilenameSafe(pszPath, "georef", nullptr); + CSLSave(papszGeoref, osFilename.c_str()); } if (bNoDataChanged) @@ -430,13 +430,14 @@ CPLErr SaveHKVAttribFile(const char *pszFilenameIn, int nXSize, int nYSize, double dfNoDataValue) { - const char *pszFilename = CPLFormFilename(pszFilenameIn, "attrib", nullptr); + const std::string osFilename = + CPLFormFilenameSafe(pszFilenameIn, "attrib", nullptr); - FILE *fp = VSIFOpen(pszFilename, "wt"); + FILE *fp = VSIFOpen(osFilename.c_str(), "wt"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Couldn't create %s.", - pszFilename); + osFilename.c_str()); return CE_Failure; } @@ -1254,23 +1255,25 @@ GDALDataset *HKVDataset::Open(GDALOpenInfo *poOpenInfo) if (!poOpenInfo->bIsDirectory) return nullptr; - const char *pszFilename = - CPLFormFilename(poOpenInfo->pszFilename, "image_data", nullptr); + std::string osFilename = + CPLFormFilenameSafe(poOpenInfo->pszFilename, "image_data", nullptr); VSIStatBuf sStat; - if (VSIStat(pszFilename, &sStat) != 0) - pszFilename = CPLFormFilename(poOpenInfo->pszFilename, "blob", nullptr); - if (VSIStat(pszFilename, &sStat) != 0) + if (VSIStat(osFilename.c_str(), &sStat) != 0) + osFilename = + CPLFormFilenameSafe(poOpenInfo->pszFilename, "blob", nullptr); + if (VSIStat(osFilename.c_str(), &sStat) != 0) return nullptr; - pszFilename = CPLFormFilename(poOpenInfo->pszFilename, "attrib", nullptr); - if (VSIStat(pszFilename, &sStat) != 0) + osFilename = + CPLFormFilenameSafe(poOpenInfo->pszFilename, "attrib", nullptr); + if (VSIStat(osFilename.c_str(), &sStat) != 0) return nullptr; /* -------------------------------------------------------------------- */ /* Load the attrib file, and boil white space away from around */ /* the equal sign. */ /* -------------------------------------------------------------------- */ - char **papszAttrib = CSLLoad(pszFilename); + char **papszAttrib = CSLLoad(osFilename.c_str()); if (papszAttrib == nullptr) return nullptr; @@ -1420,26 +1423,28 @@ GDALDataset *HKVDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Open the blob file. */ /* -------------------------------------------------------------------- */ - pszFilename = CPLFormFilename(poDS->pszPath, "image_data", nullptr); - if (VSIStat(pszFilename, &sStat) != 0) - pszFilename = CPLFormFilename(poDS->pszPath, "blob", nullptr); + osFilename = CPLFormFilenameSafe(poDS->pszPath, "image_data", nullptr); + if (VSIStat(osFilename.c_str(), &sStat) != 0) + osFilename = CPLFormFilenameSafe(poDS->pszPath, "blob", nullptr); if (poOpenInfo->eAccess == GA_ReadOnly) { - poDS->fpBlob = VSIFOpenL(pszFilename, "rb"); + poDS->fpBlob = VSIFOpenL(osFilename.c_str(), "rb"); if (poDS->fpBlob == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Unable to open file %s for read access.", pszFilename); + "Unable to open file %s for read access.", + osFilename.c_str()); return nullptr; } } else { - poDS->fpBlob = VSIFOpenL(pszFilename, "rb+"); + poDS->fpBlob = VSIFOpenL(osFilename.c_str(), "rb+"); if (poDS->fpBlob == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Unable to open file %s for update access.", pszFilename); + "Unable to open file %s for update access.", + osFilename.c_str()); return nullptr; } } @@ -1447,7 +1452,7 @@ GDALDataset *HKVDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Build the overview filename, as blob file = "_ovr". */ /* -------------------------------------------------------------------- */ - std::string osOvrFilename(pszFilename); + std::string osOvrFilename(osFilename); osOvrFilename += "_ovr"; /* -------------------------------------------------------------------- */ @@ -1476,9 +1481,9 @@ GDALDataset *HKVDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Process the georef file if there is one. */ /* -------------------------------------------------------------------- */ - pszFilename = CPLFormFilename(poDS->pszPath, "georef", nullptr); - if (VSIStat(pszFilename, &sStat) == 0) - poDS->ProcessGeoref(pszFilename); + osFilename = CPLFormFilenameSafe(poDS->pszPath, "georef", nullptr); + if (VSIStat(osFilename.c_str(), &sStat) == 0) + poDS->ProcessGeoref(osFilename.c_str()); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ @@ -1531,10 +1536,10 @@ GDALDataset *HKVDataset::Create(const char *pszFilenameIn, int nXSize, /* -------------------------------------------------------------------- */ char *pszBaseDir = nullptr; - if (strlen(CPLGetPath(pszFilenameIn)) == 0) + if (strlen(CPLGetPathSafe(pszFilenameIn).c_str()) == 0) pszBaseDir = CPLStrdup("."); else - pszBaseDir = CPLStrdup(CPLGetPath(pszFilenameIn)); + pszBaseDir = CPLStrdup(CPLGetPathSafe(pszFilenameIn).c_str()); VSIStatBuf sStat; if (CPLStat(pszBaseDir, &sStat) != 0 || !VSI_ISDIR(sStat.st_mode)) @@ -1570,13 +1575,13 @@ GDALDataset *HKVDataset::Create(const char *pszFilenameIn, int nXSize, /* Create the blob file. */ /* -------------------------------------------------------------------- */ - const char *pszFilename = - CPLFormFilename(pszFilenameIn, "image_data", nullptr); - FILE *fp = VSIFOpen(pszFilename, "wb"); + const std::string osFilename = + CPLFormFilenameSafe(pszFilenameIn, "image_data", nullptr); + FILE *fp = VSIFOpen(osFilename.c_str(), "wb"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Couldn't create %s.\n", - pszFilename); + osFilename.c_str()); return nullptr; } @@ -1620,14 +1625,14 @@ CPLErr HKVDataset::Delete(const char *pszName) if (EQUAL(papszFiles[i], ".") || EQUAL(papszFiles[i], "..")) continue; - const char *pszTarget = - CPLFormFilename(pszName, papszFiles[i], nullptr); - if (VSIUnlink(pszTarget) != 0) + const std::string osTarget = + CPLFormFilenameSafe(pszName, papszFiles[i], nullptr); + if (VSIUnlink(osTarget.c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Unable to delete file %s," "HKVDataset Delete(%s) failed.", - pszTarget, pszName); + osTarget.c_str(), pszName); CSLDestroy(papszFiles); return CE_Failure; } diff --git a/frmts/raw/iscedataset.cpp b/frmts/raw/iscedataset.cpp index 9f9fe873d2bd..76f9ec13f184 100644 --- a/frmts/raw/iscedataset.cpp +++ b/frmts/raw/iscedataset.cpp @@ -104,7 +104,7 @@ static CPLString getXMLFilename(GDALOpenInfo *poOpenInfo) if (papszSiblingFiles == nullptr) { osXMLFilename = - CPLFormFilename(nullptr, poOpenInfo->pszFilename, "xml"); + CPLFormFilenameSafe(nullptr, poOpenInfo->pszFilename, "xml"); VSIStatBufL psXMLStatBuf; if (VSIStatL(osXMLFilename, &psXMLStatBuf) != 0) { @@ -117,15 +117,16 @@ static CPLString getXMLFilename(GDALOpenInfo *poOpenInfo) /* We need to tear apart the filename to form a .xml */ /* filename. */ /* ------------------------------------------------------------ */ - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); const CPLString osName = CPLGetFilename(poOpenInfo->pszFilename); - const int iFile = CSLFindString( - papszSiblingFiles, CPLFormFilename(nullptr, osName, "xml")); + const int iFile = + CSLFindString(papszSiblingFiles, + CPLFormFilenameSafe(nullptr, osName, "xml").c_str()); if (iFile >= 0) { osXMLFilename = - CPLFormFilename(osPath, papszSiblingFiles[iFile], nullptr); + CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr); } } @@ -238,10 +239,10 @@ CPLErr ISCEDataset::FlushCache(bool bAtClosing) CPLAddXMLAttributeAndValue(psTmpNode, "name", "ACCESS_MODE"); CPLCreateXMLElementAndValue(psTmpNode, "value", "read"); - const char *pszFilename = CPLGetBasename(pszXMLFilename); psTmpNode = CPLCreateXMLNode(psDocNode, CXT_Element, "property"); CPLAddXMLAttributeAndValue(psTmpNode, "name", "FILE_NAME"); - CPLCreateXMLElementAndValue(psTmpNode, "value", pszFilename); + CPLCreateXMLElementAndValue(psTmpNode, "value", + CPLGetBasenameSafe(pszXMLFilename).c_str()); /* -------------------------------------------------------------------- */ /* Then, add the ISCE domain metadata. */ @@ -811,8 +812,9 @@ GDALDataset *ISCEDataset::Create(const char *pszFilename, int nXSize, /* -------------------------------------------------------------------- */ /* Write the XML file. */ /* -------------------------------------------------------------------- */ - const char *pszXMLFilename = CPLFormFilename(nullptr, pszFilename, "xml"); - CPLSerializeXMLTreeToFile(psDocNode, pszXMLFilename); + const std::string osXMLFilename = + CPLFormFilenameSafe(nullptr, pszFilename, "xml"); + CPLSerializeXMLTreeToFile(psDocNode, osXMLFilename.c_str()); /* -------------------------------------------------------------------- */ /* Free the XML Doc. */ diff --git a/frmts/raw/landataset.cpp b/frmts/raw/landataset.cpp index 44b30a18122a..6ac32d4f1ec8 100644 --- a/frmts/raw/landataset.cpp +++ b/frmts/raw/landataset.cpp @@ -576,10 +576,12 @@ GDALDataset *LANDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Check for a trailer file with a colormap in it. */ /* -------------------------------------------------------------------- */ - char *pszPath = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); - char *pszBasename = CPLStrdup(CPLGetBasename(poOpenInfo->pszFilename)); - const char *pszTRLFilename = CPLFormCIFilename(pszPath, pszBasename, "trl"); - VSILFILE *fpTRL = VSIFOpenL(pszTRLFilename, "rb"); + char *pszPath = CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); + char *pszBasename = + CPLStrdup(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str()); + const std::string osTRLFilename = + CPLFormCIFilenameSafe(pszPath, pszBasename, "trl"); + VSILFILE *fpTRL = VSIFOpenL(osTRLFilename.c_str(), "rb"); if (fpTRL != nullptr) { char szTRLData[896] = {'\0'}; @@ -793,13 +795,13 @@ void LANDataset::CheckForStatistics() /* -------------------------------------------------------------------- */ /* Do we have a statistics file? */ /* -------------------------------------------------------------------- */ - osSTAFilename = CPLResetExtension(GetDescription(), "sta"); + osSTAFilename = CPLResetExtensionSafe(GetDescription(), "sta"); VSILFILE *fpSTA = VSIFOpenL(osSTAFilename, "r"); if (fpSTA == nullptr && VSIIsCaseSensitiveFS(osSTAFilename)) { - osSTAFilename = CPLResetExtension(GetDescription(), "STA"); + osSTAFilename = CPLResetExtensionSafe(GetDescription(), "STA"); fpSTA = VSIFOpenL(osSTAFilename, "r"); } diff --git a/frmts/raw/lcpdataset.cpp b/frmts/raw/lcpdataset.cpp index 34294b7bc348..bf2e282f9186 100644 --- a/frmts/raw/lcpdataset.cpp +++ b/frmts/raw/lcpdataset.cpp @@ -181,7 +181,7 @@ int LCPDataset::Identify(GDALOpenInfo *poOpenInfo) /* Check file extension */ /* -------------------------------------------------------------------- */ #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - const char *pszFileExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszFileExtension = poOpenInfo->osExtension.c_str(); if (!EQUAL(pszFileExtension, "lcp")) { return FALSE; @@ -740,17 +740,19 @@ GDALDataset *LCPDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Try to read projection file. */ /* -------------------------------------------------------------------- */ - char *const pszDirname = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); + char *const pszDirname = + CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); char *const pszBasename = - CPLStrdup(CPLGetBasename(poOpenInfo->pszFilename)); + CPLStrdup(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str()); - poDS->osPrjFilename = CPLFormFilename(pszDirname, pszBasename, "prj"); + poDS->osPrjFilename = CPLFormFilenameSafe(pszDirname, pszBasename, "prj"); VSIStatBufL sStatBuf; int nRet = VSIStatL(poDS->osPrjFilename, &sStatBuf); if (nRet != 0 && VSIIsCaseSensitiveFS(poDS->osPrjFilename)) { - poDS->osPrjFilename = CPLFormFilename(pszDirname, pszBasename, "PRJ"); + poDS->osPrjFilename = + CPLFormFilenameSafe(pszDirname, pszBasename, "PRJ"); nRet = VSIStatL(poDS->osPrjFilename, &sStatBuf); } @@ -1603,10 +1605,12 @@ GDALDataset *LCPDataset::CreateCopy(const char *pszFilename, poSrcSRS->exportToWkt(&pszESRIProjection, apszOptions); if (pszESRIProjection) { - char *const pszDirname = CPLStrdup(CPLGetPath(pszFilename)); - char *const pszBasename = CPLStrdup(CPLGetBasename(pszFilename)); - char *pszPrjFilename = - CPLStrdup(CPLFormFilename(pszDirname, pszBasename, "prj")); + char *const pszDirname = + CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); + char *const pszBasename = + CPLStrdup(CPLGetBasenameSafe(pszFilename).c_str()); + char *pszPrjFilename = CPLStrdup( + CPLFormFilenameSafe(pszDirname, pszBasename, "prj").c_str()); fp = VSIFOpenL(pszPrjFilename, "wt"); if (fp != nullptr) { diff --git a/frmts/raw/loslasdataset.cpp b/frmts/raw/loslasdataset.cpp index 1bcab248cb86..eeae1d80abc8 100644 --- a/frmts/raw/loslasdataset.cpp +++ b/frmts/raw/loslasdataset.cpp @@ -153,7 +153,7 @@ int LOSLASDataset::Identify(GDALOpenInfo *poOpenInfo) return FALSE; #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (!EQUAL(pszExt, "las") && !EQUAL(pszExt, "los") && !EQUAL(pszExt, "geo")) return FALSE; #endif @@ -242,17 +242,17 @@ GDALDataset *LOSLASDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; poDS->SetBand(1, std::move(poBand)); - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "las")) + if (poOpenInfo->IsExtensionEqualToCI("las")) { poDS->GetRasterBand(1)->SetDescription("Latitude Offset (arc seconds)"); } - else if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "los")) + else if (poOpenInfo->IsExtensionEqualToCI("los")) { poDS->GetRasterBand(1)->SetDescription( "Longitude Offset (arc seconds)"); poDS->GetRasterBand(1)->SetMetadataItem("positive_value", "west"); } - else if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "geo")) + else if (poOpenInfo->IsExtensionEqualToCI("geo")) { poDS->GetRasterBand(1)->SetDescription("Geoid undulation (meters)"); } diff --git a/frmts/raw/mffdataset.cpp b/frmts/raw/mffdataset.cpp index 30b5f4471e70..002c36d622ec 100644 --- a/frmts/raw/mffdataset.cpp +++ b/frmts/raw/mffdataset.cpp @@ -667,7 +667,7 @@ GDALDataset *MFFDataset::Open(GDALOpenInfo *poOpenInfo) if (poOpenInfo->nHeaderBytes < 17 || poOpenInfo->fpL == nullptr) return nullptr; - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "hdr")) + if (!poOpenInfo->IsExtensionEqualToCI("hdr")) return nullptr; /* -------------------------------------------------------------------- */ @@ -784,10 +784,12 @@ GDALDataset *MFFDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Read the directory to find matching band files. */ /* -------------------------------------------------------------------- */ - char *const pszTargetPath = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); + char *const pszTargetPath = + CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); char *const pszTargetBase = - CPLStrdup(CPLGetBasename(poOpenInfo->pszFilename)); - char **papszDirFiles = VSIReadDir(CPLGetPath(poOpenInfo->pszFilename)); + CPLStrdup(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str()); + char **papszDirFiles = + VSIReadDir(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); if (papszDirFiles == nullptr) { CPLFree(pszTargetPath); @@ -798,21 +800,21 @@ GDALDataset *MFFDataset::Open(GDALOpenInfo *poOpenInfo) int nSkipped = 0; for (int nRawBand = 0; true; nRawBand++) { - const char *pszExtension = nullptr; - /* Find the next raw band file. */ int i = 0; // Used after for. for (; papszDirFiles[i] != nullptr; i++) { - if (!EQUAL(CPLGetBasename(papszDirFiles[i]), pszTargetBase)) + if (!EQUAL(CPLGetBasenameSafe(papszDirFiles[i]).c_str(), + pszTargetBase)) continue; - pszExtension = CPLGetExtension(papszDirFiles[i]); - if (strlen(pszExtension) >= 2 && - isdigit(static_cast(pszExtension[1])) && - atoi(pszExtension + 1) == nRawBand && - strchr("bBcCiIjJrRxXzZ", pszExtension[0]) != nullptr) + const std::string osExtension = + CPLGetExtensionSafe(papszDirFiles[i]); + if (osExtension.size() >= 2 && + isdigit(static_cast(osExtension[1])) && + atoi(osExtension.c_str() + 1) == nRawBand && + strchr("bBcCiIjJrRxXzZ", osExtension[0]) != nullptr) break; } @@ -820,27 +822,27 @@ GDALDataset *MFFDataset::Open(GDALOpenInfo *poOpenInfo) break; /* open the file for required level of access */ - const char *pszRawFilename = - CPLFormFilename(pszTargetPath, papszDirFiles[i], nullptr); + const std::string osRawFilename = + CPLFormFilenameSafe(pszTargetPath, papszDirFiles[i], nullptr); VSILFILE *fpRaw = nullptr; if (poOpenInfo->eAccess == GA_Update) - fpRaw = VSIFOpenL(pszRawFilename, "rb+"); + fpRaw = VSIFOpenL(osRawFilename.c_str(), "rb+"); else - fpRaw = VSIFOpenL(pszRawFilename, "rb"); + fpRaw = VSIFOpenL(osRawFilename.c_str(), "rb"); if (fpRaw == nullptr) { CPLError(CE_Warning, CPLE_OpenFailed, - "Unable to open %s ... skipping.", pszRawFilename); + "Unable to open %s ... skipping.", osRawFilename.c_str()); nSkipped++; continue; } poDS->m_papszFileList = - CSLAddString(poDS->m_papszFileList, pszRawFilename); + CSLAddString(poDS->m_papszFileList, osRawFilename.c_str()); GDALDataType eDataType = GDT_Unknown; - pszExtension = CPLGetExtension(papszDirFiles[i]); + const std::string osExt = CPLGetExtensionSafe(papszDirFiles[i]); if (pszRefinedType != nullptr) { if (EQUAL(pszRefinedType, "C*4")) @@ -888,23 +890,23 @@ GDALDataset *MFFDataset::Open(GDALOpenInfo *poOpenInfo) continue; } } - else if (STARTS_WITH_CI(pszExtension, "b")) + else if (STARTS_WITH_CI(osExt.c_str(), "b")) { eDataType = GDT_Byte; } - else if (STARTS_WITH_CI(pszExtension, "i")) + else if (STARTS_WITH_CI(osExt.c_str(), "i")) { eDataType = GDT_UInt16; } - else if (STARTS_WITH_CI(pszExtension, "j")) + else if (STARTS_WITH_CI(osExt.c_str(), "j")) { eDataType = GDT_CInt16; } - else if (STARTS_WITH_CI(pszExtension, "r")) + else if (STARTS_WITH_CI(osExt.c_str(), "r")) { eDataType = GDT_Float32; } - else if (STARTS_WITH_CI(pszExtension, "x")) + else if (STARTS_WITH_CI(osExt.c_str(), "x")) { eDataType = GDT_CFloat32; } @@ -913,7 +915,7 @@ GDALDataset *MFFDataset::Open(GDALOpenInfo *poOpenInfo) CPLError(CE_Warning, CPLE_OpenFailed, "Unable to open band %d because extension %s is not " "handled. Skipping.", - nRawBand + 1, pszExtension); + nRawBand + 1, osExt.c_str()); nSkipped++; CPL_IGNORE_RET_VAL(VSIFCloseL(fpRaw)); continue; @@ -1098,13 +1100,14 @@ GDALDataset *MFFDataset::Create(const char *pszFilenameIn, int nXSize, /* -------------------------------------------------------------------- */ /* Create the header file. */ /* -------------------------------------------------------------------- */ - const char *pszFilename = CPLFormFilename(nullptr, pszBaseFilename, "hdr"); + std::string osFilename = + CPLFormFilenameSafe(nullptr, pszBaseFilename, "hdr"); - VSILFILE *fp = VSIFOpenL(pszFilename, "wt"); + VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "wt"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Couldn't create %s.\n", - pszFilename); + osFilename.c_str()); CPLFree(pszBaseFilename); return nullptr; } @@ -1143,12 +1146,12 @@ GDALDataset *MFFDataset::Create(const char *pszFilenameIn, int nXSize, else if (eType == GDT_CFloat32) CPLsnprintf(szExtension, sizeof(szExtension), "x%02d", iBand); - pszFilename = CPLFormFilename(nullptr, pszBaseFilename, szExtension); - fp = VSIFOpenL(pszFilename, "wb"); + osFilename = CPLFormFilenameSafe(nullptr, pszBaseFilename, szExtension); + fp = VSIFOpenL(osFilename.c_str(), "wb"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Couldn't create %s.\n", - pszFilename); + osFilename.c_str()); CPLFree(pszBaseFilename); return nullptr; } @@ -1169,7 +1172,7 @@ GDALDataset *MFFDataset::Create(const char *pszFilenameIn, int nXSize, /* -------------------------------------------------------------------- */ strcat(pszBaseFilename, ".hdr"); GDALDataset *poDS = - static_cast(GDALOpen(pszBaseFilename, GA_Update)); + GDALDataset::Open(pszBaseFilename, GDAL_OF_RASTER | GDAL_OF_UPDATE); CPLFree(pszBaseFilename); return poDS; @@ -1311,14 +1314,14 @@ GDALDataset *MFFDataset::CreateCopy(const char *pszFilename, break; } - const char *pszFilenameGEO = - CPLFormFilename(nullptr, pszBaseFilename, "hdr"); + const std::string osFilenameGEO = + CPLFormFilenameSafe(nullptr, pszBaseFilename, "hdr"); - VSILFILE *fp = VSIFOpenL(pszFilenameGEO, "at"); + VSILFILE *fp = VSIFOpenL(osFilenameGEO.c_str(), "at"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Couldn't open %s for appending.\n", pszFilenameGEO); + "Couldn't open %s for appending.\n", osFilenameGEO.c_str()); CPLFree(pszBaseFilename); return nullptr; } diff --git a/frmts/raw/ndfdataset.cpp b/frmts/raw/ndfdataset.cpp index ec5559fdbf63..b339ae89a8bb 100644 --- a/frmts/raw/ndfdataset.cpp +++ b/frmts/raw/ndfdataset.cpp @@ -287,12 +287,12 @@ GDALDataset *NDFDataset::Open(GDALOpenInfo *poOpenInfo) snprintf(szBandExtension, sizeof(szBandExtension), "I%d", iBand + 1); osFilename = - CPLResetExtension(poOpenInfo->pszFilename, szBandExtension); + CPLResetExtensionSafe(poOpenInfo->pszFilename, szBandExtension); } else { - CPLString osBasePath = CPLGetPath(poOpenInfo->pszFilename); - osFilename = CPLFormFilename(osBasePath, osFilename, nullptr); + CPLString osBasePath = CPLGetPathSafe(poOpenInfo->pszFilename); + osFilename = CPLFormFilenameSafe(osBasePath, osFilename, nullptr); } VSILFILE *fpRaw = VSIFOpenL(osFilename, "rb"); diff --git a/frmts/raw/noaabdataset.cpp b/frmts/raw/noaabdataset.cpp index 1e39b75a92bd..3054d4fb3109 100644 --- a/frmts/raw/noaabdataset.cpp +++ b/frmts/raw/noaabdataset.cpp @@ -132,7 +132,7 @@ int NOAA_B_Dataset::IdentifyEx(GDALOpenInfo *poOpenInfo, bool &bBigEndianOut) return FALSE; #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "b")) + if (!poOpenInfo->IsExtensionEqualToCI("b")) return FALSE; #endif diff --git a/frmts/raw/pauxdataset.cpp b/frmts/raw/pauxdataset.cpp index 11fd271d727e..34c044e76281 100644 --- a/frmts/raw/pauxdataset.cpp +++ b/frmts/raw/pauxdataset.cpp @@ -597,7 +597,7 @@ GDALDataset *PAuxDataset::Open(GDALOpenInfo *poOpenInfo) CPLString osTarget = poOpenInfo->pszFilename; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "aux") && + if (poOpenInfo->IsExtensionEqualToCI("aux") && STARTS_WITH_CI(reinterpret_cast(poOpenInfo->pabyHeader), "AuxilaryTarget: ")) { @@ -613,15 +613,15 @@ GDALDataset *PAuxDataset::Open(GDALOpenInfo *poOpenInfo) } szAuxTarget[sizeof(szAuxTarget) - 1] = '\0'; - const std::string osPath(CPLGetPath(poOpenInfo->pszFilename)); - osTarget = CPLFormFilename(osPath.c_str(), szAuxTarget, nullptr); + const std::string osPath(CPLGetPathSafe(poOpenInfo->pszFilename)); + osTarget = CPLFormFilenameSafe(osPath.c_str(), szAuxTarget, nullptr); } /* -------------------------------------------------------------------- */ /* Now we need to tear apart the filename to form a .aux */ /* filename. */ /* -------------------------------------------------------------------- */ - CPLString osAuxFilename = CPLResetExtension(osTarget, "aux"); + CPLString osAuxFilename = CPLResetExtensionSafe(osTarget, "aux"); /* -------------------------------------------------------------------- */ /* Do we have a .aux file? */ @@ -636,7 +636,7 @@ GDALDataset *PAuxDataset::Open(GDALOpenInfo *poOpenInfo) VSILFILE *fp = VSIFOpenL(osAuxFilename, "r"); if (fp == nullptr) { - osAuxFilename = CPLResetExtension(osTarget, "AUX"); + osAuxFilename = CPLResetExtensionSafe(osTarget, "AUX"); fp = VSIFOpenL(osAuxFilename, "r"); } @@ -1010,7 +1010,8 @@ GDALDataset *PAuxDataset::Create(const char *pszFilename, int nXSize, static CPLErr PAuxDelete(const char *pszBasename) { - VSILFILE *fp = VSIFOpenL(CPLResetExtension(pszBasename, "aux"), "r"); + VSILFILE *fp = + VSIFOpenL(CPLResetExtensionSafe(pszBasename, "aux").c_str(), "r"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, @@ -1039,7 +1040,7 @@ static CPLErr PAuxDelete(const char *pszBasename) return CE_Failure; } - VSIUnlink(CPLResetExtension(pszBasename, "aux")); + VSIUnlink(CPLResetExtensionSafe(pszBasename, "aux").c_str()); return CE_None; } diff --git a/frmts/raw/pnmdataset.cpp b/frmts/raw/pnmdataset.cpp index 70241d02e9a7..54b04ef17fda 100644 --- a/frmts/raw/pnmdataset.cpp +++ b/frmts/raw/pnmdataset.cpp @@ -328,7 +328,7 @@ GDALDataset *PNMDataset::Create(const char *pszFilename, int nXSize, int nYSize, return nullptr; } - const CPLString osExt(CPLGetExtension(pszFilename)); + const CPLString osExt(CPLGetExtensionSafe(pszFilename)); if (nBandsIn == 1) { if (!EQUAL(osExt, "PGM")) diff --git a/frmts/raw/roipacdataset.cpp b/frmts/raw/roipacdataset.cpp index 1943cb38a480..bb2262f0d301 100644 --- a/frmts/raw/roipacdataset.cpp +++ b/frmts/raw/roipacdataset.cpp @@ -72,7 +72,7 @@ static CPLString getRscFilename(GDALOpenInfo *poOpenInfo) if (papszSiblingFiles == nullptr) { const CPLString osRscFilename = - CPLFormFilename(nullptr, poOpenInfo->pszFilename, "rsc"); + CPLFormFilenameSafe(nullptr, poOpenInfo->pszFilename, "rsc"); VSIStatBufL psRscStatBuf; if (VSIStatL(osRscFilename, &psRscStatBuf) != 0) { @@ -85,14 +85,14 @@ static CPLString getRscFilename(GDALOpenInfo *poOpenInfo) /* We need to tear apart the filename to form a .rsc */ /* filename. */ /* ------------------------------------------------------------ */ - const CPLString osPath = CPLGetPath(poOpenInfo->pszFilename); + const CPLString osPath = CPLGetPathSafe(poOpenInfo->pszFilename); const CPLString osName = CPLGetFilename(poOpenInfo->pszFilename); - int iFile = CSLFindString(papszSiblingFiles, - CPLFormFilename(nullptr, osName, "rsc")); + int iFile = CSLFindString( + papszSiblingFiles, CPLFormFilenameSafe(nullptr, osName, "rsc").c_str()); if (iFile >= 0) { - return CPLFormFilename(osPath, papszSiblingFiles[iFile], nullptr); + return CPLFormFilenameSafe(osPath, papszSiblingFiles[iFile], nullptr); } return ""; @@ -259,7 +259,7 @@ GDALDataset *ROIPACDataset::Open(GDALOpenInfo *poOpenInfo) PIXEL } eInterleave = UNKNOWN; - const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExtension = poOpenInfo->osExtension.c_str(); if (strcmp(pszExtension, "raw") == 0) { /* ------------------------------------------------------------ */ @@ -506,7 +506,7 @@ int ROIPACDataset::Identify(GDALOpenInfo *poOpenInfo) /* Check if: */ /* * 1. The data file extension is known */ /* -------------------------------------------------------------------- */ - const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExtension = poOpenInfo->osExtension.c_str(); if (strcmp(pszExtension, "raw") == 0) { /* Since gdal do not read natively CInt8, more work is needed @@ -548,7 +548,8 @@ GDALDataset *ROIPACDataset::Create(const char *pszFilename, int nXSize, /* -------------------------------------------------------------------- */ /* Verify input options. */ /* -------------------------------------------------------------------- */ - const char *pszExtension = CPLGetExtension(pszFilename); + const std::string osExtension = CPLGetExtensionSafe(pszFilename); + const char *pszExtension = osExtension.c_str(); if (strcmp(pszExtension, "int") == 0 || strcmp(pszExtension, "slc") == 0) { if (nBandsIn != 1 || eType != GDT_CFloat32) @@ -637,12 +638,13 @@ GDALDataset *ROIPACDataset::Create(const char *pszFilename, int nXSize, /* -------------------------------------------------------------------- */ /* Open the RSC file. */ /* -------------------------------------------------------------------- */ - const char *pszRSCFilename = CPLFormFilename(nullptr, pszFilename, "rsc"); - fp = VSIFOpenL(pszRSCFilename, "wt"); + const std::string osRSCFilename = + CPLFormFilenameSafe(nullptr, pszFilename, "rsc"); + fp = VSIFOpenL(osRSCFilename.c_str(), "wt"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Attempt to create file `%s' failed.", pszRSCFilename); + "Attempt to create file `%s' failed.", osRSCFilename.c_str()); return nullptr; } diff --git a/frmts/raw/rrasterdataset.cpp b/frmts/raw/rrasterdataset.cpp index ef5c26f368da..198373f28ab7 100644 --- a/frmts/raw/rrasterdataset.cpp +++ b/frmts/raw/rrasterdataset.cpp @@ -918,7 +918,7 @@ int RRASTERDataset::Identify(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->nHeaderBytes < 40 || poOpenInfo->fpL == nullptr || - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "grd")) + !poOpenInfo->IsExtensionEqualToCI("grd")) { return FALSE; } @@ -1176,25 +1176,25 @@ GDALDataset *RRASTERDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; } - CPLString osDirname(CPLGetDirname(poOpenInfo->pszFilename)); - CPLString osBasename(CPLGetBasename(poOpenInfo->pszFilename)); - CPLString osGRDExtension(CPLGetExtension(poOpenInfo->pszFilename)); + CPLString osDirname(CPLGetDirnameSafe(poOpenInfo->pszFilename)); + CPLString osBasename(CPLGetBasenameSafe(poOpenInfo->pszFilename)); + CPLString osGRDExtension(poOpenInfo->osExtension); CPLString osGRIExtension((osGRDExtension[0] == 'g') ? "gri" : "GRI"); char **papszSiblings = poOpenInfo->GetSiblingFiles(); if (papszSiblings) { - int iFile = - CSLFindString(papszSiblings, - CPLFormFilename(nullptr, osBasename, osGRIExtension)); + int iFile = CSLFindString( + papszSiblings, + CPLFormFilenameSafe(nullptr, osBasename, osGRIExtension).c_str()); if (iFile < 0) return nullptr; poDS->m_osGriFilename = - CPLFormFilename(osDirname, papszSiblings[iFile], nullptr); + CPLFormFilenameSafe(osDirname, papszSiblings[iFile], nullptr); } else { poDS->m_osGriFilename = - CPLFormFilename(osDirname, osBasename, osGRIExtension); + CPLFormFilenameSafe(osDirname, osBasename, osGRIExtension); } VSILFILE *fpImage = @@ -1420,7 +1420,7 @@ GDALDataset *RRASTERDataset::Create(const char *pszFilename, int nXSize, return nullptr; } - CPLString osGRDExtension(CPLGetExtension(pszFilename)); + CPLString osGRDExtension(CPLGetExtensionSafe(pszFilename)); if (!EQUAL(osGRDExtension, "grd")) { CPLError(CE_Failure, CPLE_NotSupported, @@ -1442,7 +1442,7 @@ GDALDataset *RRASTERDataset::Create(const char *pszFilename, int nXSize, const std::string osGRIExtension((osGRDExtension[0] == 'g') ? "gri" : "GRI"); const std::string osGriFilename( - CPLResetExtension(pszFilename, osGRIExtension.c_str())); + CPLResetExtensionSafe(pszFilename, osGRIExtension.c_str())); // Try to create the file. VSILFILE *fpImage = VSIFOpenL(osGriFilename.c_str(), "wb+"); diff --git a/frmts/raw/snodasdataset.cpp b/frmts/raw/snodasdataset.cpp index 08d5d1904af6..27e82bd0fc41 100644 --- a/frmts/raw/snodasdataset.cpp +++ b/frmts/raw/snodasdataset.cpp @@ -431,8 +431,9 @@ GDALDataset *SNODASDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Open target binary file. */ /* -------------------------------------------------------------------- */ - const char *pszPath = CPLGetPath(poOpenInfo->pszFilename); - osDataFilename = CPLFormFilename(pszPath, osDataFilename, nullptr); + const std::string osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + osDataFilename = + CPLFormFilenameSafe(osPath.c_str(), osDataFilename, nullptr); VSILFILE *fpRaw = VSIFOpenL(osDataFilename, "rb"); diff --git a/frmts/rcm/rcmdataset.cpp b/frmts/rcm/rcmdataset.cpp index 46248c14c7c1..0d0abc14b411 100644 --- a/frmts/rcm/rcmdataset.cpp +++ b/frmts/rcm/rcmdataset.cpp @@ -1105,15 +1105,16 @@ GDALDataset *RCMDataset::Open(GDALOpenInfo *poOpenInfo) { /* Check for directory access when there is a product.xml file in the directory. */ - osMDFilename = CPLFormCIFilename(pszFilename, "product.xml", nullptr); + osMDFilename = + CPLFormCIFilenameSafe(pszFilename, "product.xml", nullptr); VSIStatBufL sStat; if (VSIStatL(osMDFilename, &sStat) != 0) { /* If not, check for directory extra 'metadata' access when there is a product.xml file in the directory. */ - osMDFilename = - CPLFormCIFilename(pszFilename, GetMetadataProduct(), nullptr); + osMDFilename = CPLFormCIFilenameSafe(pszFilename, + GetMetadataProduct(), nullptr); } } else @@ -1416,7 +1417,7 @@ GDALDataset *RCMDataset::Open(GDALOpenInfo *poOpenInfo) // XML std::string osNoiseLevelsValues; - const CPLString osPath = CPLGetPath(osMDFilename); + const CPLString osPath = CPLGetPathSafe(osMDFilename); /* Get a list of all polarizations */ CPLXMLNode *psSourceAttrs = @@ -1548,8 +1549,8 @@ GDALDataset *RCMDataset::Open(GDALOpenInfo *poOpenInfo) if (pszIncidenceAngleFileName != nullptr) { - CPLString osIncidenceAngleFilePath = CPLFormFilename( - CPLFormFilename(osPath, CALIBRATION_FOLDER, nullptr), + CPLString osIncidenceAngleFilePath = CPLFormFilenameSafe( + CPLFormFilenameSafe(osPath, CALIBRATION_FOLDER, nullptr).c_str(), pszIncidenceAngleFileName, nullptr); /* Check if the file exist */ @@ -1660,8 +1661,9 @@ GDALDataset *RCMDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ - const CPLString oNoiseLevelPath = CPLFormFilename( - CPLFormFilename(osPath, CALIBRATION_FOLDER, nullptr), + const CPLString oNoiseLevelPath = CPLFormFilenameSafe( + CPLFormFilenameSafe(osPath, CALIBRATION_FOLDER, nullptr) + .c_str(), pszNoiseLevelFile, nullptr); if (IsValidXMLFile(oNoiseLevelPath)) { @@ -1716,8 +1718,9 @@ GDALDataset *RCMDataset::Open(GDALOpenInfo *poOpenInfo) /* called 'calibration' from the 'metadata' folder */ /* -------------------------------------------------------------------- */ - const CPLString osLUTFilePath = CPLFormFilename( - CPLFormFilename(osPath, CALIBRATION_FOLDER, nullptr), + const CPLString osLUTFilePath = CPLFormFilenameSafe( + CPLFormFilenameSafe(osPath, CALIBRATION_FOLDER, nullptr) + .c_str(), pszLUTFile, nullptr); if (EQUAL(pszLUTType, "Beta Nought") && @@ -1871,8 +1874,8 @@ GDALDataset *RCMDataset::Open(GDALOpenInfo *poOpenInfo) /* Form full filename (path of product.xml + basename). */ /* -------------------------------------------------------------------- */ - char *pszFullname = - CPLStrdup(CPLFormFilename(osPath, pszBasedFilename, nullptr)); + char *pszFullname = CPLStrdup( + CPLFormFilenameSafe(osPath, pszBasedFilename, nullptr).c_str()); /* -------------------------------------------------------------------- */ diff --git a/frmts/rcm/rcmdrivercore.cpp b/frmts/rcm/rcmdrivercore.cpp index e2a1fd436226..2766c810de06 100644 --- a/frmts/rcm/rcmdrivercore.cpp +++ b/frmts/rcm/rcmdrivercore.cpp @@ -26,9 +26,9 @@ int RCMDatasetIdentify(GDALOpenInfo *poOpenInfo) if (poOpenInfo->bIsDirectory) { - const auto IsRCM = [](const CPLString &osMDFilename) + const auto IsRCM = [](const std::string &osMDFilename) { - CPLXMLNode *psProduct = CPLParseXMLFile(osMDFilename); + CPLXMLNode *psProduct = CPLParseXMLFile(osMDFilename.c_str()); if (psProduct == nullptr) return FALSE; @@ -57,11 +57,11 @@ int RCMDatasetIdentify(GDALOpenInfo *poOpenInfo) /* Check for directory access when there is a product.xml file in the directory. */ - CPLString osMDFilename = - CPLFormCIFilename(poOpenInfo->pszFilename, "product.xml", nullptr); + const std::string osMDFilename = CPLFormCIFilenameSafe( + poOpenInfo->pszFilename, "product.xml", nullptr); VSIStatBufL sStat; - if (VSIStatL(osMDFilename, &sStat) == 0) + if (VSIStatL(osMDFilename.c_str(), &sStat) == 0) { return IsRCM(osMDFilename); } @@ -69,11 +69,11 @@ int RCMDatasetIdentify(GDALOpenInfo *poOpenInfo) /* If not, check for directory extra 'metadata' access when there is a product.xml file in the directory. */ - CPLString osMDFilenameMetadata = CPLFormCIFilename( + const std::string osMDFilenameMetadata = CPLFormCIFilenameSafe( poOpenInfo->pszFilename, GetMetadataProduct(), nullptr); VSIStatBufL sStatMetadata; - if (VSIStatL(osMDFilenameMetadata, &sStatMetadata) == 0) + if (VSIStatL(osMDFilenameMetadata.c_str(), &sStatMetadata) == 0) { return IsRCM(osMDFilenameMetadata); } diff --git a/frmts/rik/rikdataset.cpp b/frmts/rik/rikdataset.cpp index 9f50b6e4eb75..fc65bd822ac7 100644 --- a/frmts/rik/rikdataset.cpp +++ b/frmts/rik/rikdataset.cpp @@ -714,7 +714,7 @@ int RIKDataset::Identify(GDALOpenInfo *poOpenInfo) return FALSE; } - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "rik")) + if (poOpenInfo->IsExtensionEqualToCI("rik")) return TRUE; // We really need Open to be able to conclude diff --git a/frmts/rs2/rs2dataset.cpp b/frmts/rs2/rs2dataset.cpp index eab4a415e668..3f3aaff395fd 100644 --- a/frmts/rs2/rs2dataset.cpp +++ b/frmts/rs2/rs2dataset.cpp @@ -30,7 +30,8 @@ typedef enum eCalibration_t static bool IsValidXMLFile(const char *pszPath, const char *pszLut) { /* Return true for valid xml file, false otherwise */ - char *pszLutFile = VSIStrdup(CPLFormFilename(pszPath, pszLut, nullptr)); + char *pszLutFile = + VSIStrdup(CPLFormFilenameSafe(pszPath, pszLut, nullptr).c_str()); CPLXMLTreeCloser psLut(CPLParseXMLFile(pszLutFile)); @@ -632,8 +633,8 @@ int RS2Dataset::Identify(GDALOpenInfo *poOpenInfo) directory. */ if (poOpenInfo->bIsDirectory) { - CPLString osMDFilename = - CPLFormCIFilename(poOpenInfo->pszFilename, "product.xml", nullptr); + const CPLString osMDFilename = CPLFormCIFilenameSafe( + poOpenInfo->pszFilename, "product.xml", nullptr); GDALOpenInfo oOpenInfo(osMDFilename.c_str(), GA_ReadOnly); return Identify(&oOpenInfo); @@ -709,7 +710,8 @@ GDALDataset *RS2Dataset::Open(GDALOpenInfo *poOpenInfo) CPLString osMDFilename; if (poOpenInfo->bIsDirectory) { - osMDFilename = CPLFormCIFilename(pszFilename, "product.xml", nullptr); + osMDFilename = + CPLFormCIFilenameSafe(pszFilename, "product.xml", nullptr); } else osMDFilename = pszFilename; @@ -846,7 +848,7 @@ GDALDataset *RS2Dataset::Open(GDALOpenInfo *poOpenInfo) CPLString osGammaLUT; CPLString osSigma0LUT; - char *pszPath = CPLStrdup(CPLGetPath(osMDFilename)); + char *pszPath = CPLStrdup(CPLGetPathSafe(osMDFilename).c_str()); const int nFLen = static_cast(osMDFilename.size()); CPLXMLNode *psNode = psImageAttributes->psChild; @@ -864,7 +866,7 @@ GDALDataset *RS2Dataset::Open(GDALOpenInfo *poOpenInfo) CPLGetXMLValue(psNode, "incidenceAngleCorrection", ""); const char *pszLUTFile = CPLGetXMLValue(psNode, "", ""); CPLString osLUTFilePath = - CPLFormFilename(pszPath, pszLUTFile, nullptr); + CPLFormFilenameSafe(pszPath, pszLUTFile, nullptr); if (EQUAL(pszLUTType, "")) continue; @@ -944,8 +946,8 @@ GDALDataset *RS2Dataset::Open(GDALOpenInfo *poOpenInfo) /* Form full filename (path of product.xml + basename). */ /* -------------------------------------------------------------------- */ - char *pszFullname = - CPLStrdup(CPLFormFilename(pszPath, pszBasename, nullptr)); + char *pszFullname = CPLStrdup( + CPLFormFilenameSafe(pszPath, pszBasename, nullptr).c_str()); /* -------------------------------------------------------------------- */ @@ -1012,7 +1014,7 @@ GDALDataset *RS2Dataset::Open(GDALOpenInfo *poOpenInfo) } RS2CalibRasterBand *poBand = new RS2CalibRasterBand( poDS, CPLGetXMLValue(psNode, "pole", ""), eDataType, poBandFile, - eCalib, CPLFormFilename(pszPath, pszLUT, nullptr)); + eCalib, CPLFormFilenameSafe(pszPath, pszLUT, nullptr).c_str()); poDS->SetBand(poDS->GetRasterCount() + 1, poBand); } diff --git a/frmts/safe/safedataset.cpp b/frmts/safe/safedataset.cpp index b489a87751df..ab46337b324d 100644 --- a/frmts/safe/safedataset.cpp +++ b/frmts/safe/safedataset.cpp @@ -777,8 +777,8 @@ int SAFEDataset::Identify(GDALOpenInfo *poOpenInfo) if (poOpenInfo->bIsDirectory) { VSIStatBufL sStat; - CPLString osMDFilename = CPLFormCIFilename(poOpenInfo->pszFilename, - "manifest.safe", nullptr); + CPLString osMDFilename = CPLFormCIFilenameSafe( + poOpenInfo->pszFilename, "manifest.safe", nullptr); if (VSIStatL(osMDFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode)) { @@ -985,8 +985,8 @@ GDALDataset *SAFEDataset::Open(GDALOpenInfo *poOpenInfo) if (poOpenInfo->bIsDirectory) { - osMDFilename = - CPLFormCIFilename(osMDFilename.c_str(), "manifest.safe", nullptr); + osMDFilename = CPLFormCIFilenameSafe(osMDFilename.c_str(), + "manifest.safe", nullptr); } /* -------------------------------------------------------------------- */ @@ -997,7 +997,7 @@ GDALDataset *SAFEDataset::Open(GDALOpenInfo *poOpenInfo) if (psManifest == nullptr) return nullptr; - CPLString osPath(CPLGetPath(osMDFilename)); + CPLString osPath(CPLGetPathSafe(osMDFilename)); /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ @@ -1146,9 +1146,9 @@ GDALDataset *SAFEDataset::Open(GDALOpenInfo *poOpenInfo) // open Annotation XML file const CPLString osAnnotationFilePath = - CPLFormFilename(osPath, pszAnnotation, nullptr); + CPLFormFilenameSafe(osPath, pszAnnotation, nullptr); const CPLString osCalibrationFilePath = - CPLFormFilename(osPath, pszCalibration, nullptr); + CPLFormFilenameSafe(osPath, pszCalibration, nullptr); CPLXMLTreeCloser psAnnotation( CPLParseXMLFile(osAnnotationFilePath)); @@ -1292,7 +1292,7 @@ GDALDataset *SAFEDataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ const std::string osFullFilename( - CPLFormFilename(osPath, pszMeasurement, nullptr)); + CPLFormFilenameSafe(osPath, pszMeasurement, nullptr)); /* -------------------------------------------------------------------- */ diff --git a/frmts/saga/sagadataset.cpp b/frmts/saga/sagadataset.cpp index 843501e2c3e2..f2de3e1e0cef 100644 --- a/frmts/saga/sagadataset.cpp +++ b/frmts/saga/sagadataset.cpp @@ -305,9 +305,10 @@ SAGADataset::~SAGADataset() if (headerDirty) { SAGARasterBand *poGRB = static_cast(GetRasterBand(1)); - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); - const CPLString osFilename = CPLFormCIFilename(osPath, osName, ".sgrd"); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); + const CPLString osFilename = + CPLFormCIFilenameSafe(osPath, osName, ".sgrd"); WriteHeader(osFilename, poGRB->GetRasterDataType(), poGRB->nRasterXSize, poGRB->nRasterYSize, poGRB->m_Xmin, poGRB->m_Ymin, poGRB->m_Cellsize, poGRB->m_NoData, 1.0, false); @@ -323,20 +324,20 @@ SAGADataset::~SAGADataset() char **SAGADataset::GetFileList() { - const CPLString osPath = CPLGetPath(GetDescription()); - const CPLString osName = CPLGetBasename(GetDescription()); + const CPLString osPath = CPLGetPathSafe(GetDescription()); + const CPLString osName = CPLGetBasenameSafe(GetDescription()); // Main data file, etc. char **papszFileList = GDALPamDataset::GetFileList(); - if (!EQUAL(CPLGetExtension(GetDescription()), "sg-grd-z")) + if (!EQUAL(CPLGetExtensionSafe(GetDescription()).c_str(), "sg-grd-z")) { // Header file. - CPLString osFilename = CPLFormCIFilename(osPath, osName, ".sgrd"); + CPLString osFilename = CPLFormCIFilenameSafe(osPath, osName, ".sgrd"); papszFileList = CSLAddString(papszFileList, osFilename); // projections file. - osFilename = CPLFormCIFilename(osPath, osName, "prj"); + osFilename = CPLFormCIFilenameSafe(osPath, osName, "prj"); VSIStatBufL sStatBuf; if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) papszFileList = CSLAddString(papszFileList, osFilename); @@ -383,7 +384,8 @@ CPLErr SAGADataset::SetSpatialRef(const OGRSpatialReference *poSRS) /* -------------------------------------------------------------------- */ /* Write to .prj file. */ /* -------------------------------------------------------------------- */ - const CPLString osPrjFilename = CPLResetExtension(GetDescription(), "prj"); + const CPLString osPrjFilename = + CPLResetExtensionSafe(GetDescription(), "prj"); VSILFILE *l_fp = VSIFOpenL(osPrjFilename.c_str(), "wt"); if (l_fp != nullptr) { @@ -409,16 +411,17 @@ GDALDataset *SAGADataset::Open(GDALOpenInfo *poOpenInfo) /* We assume the user is pointing to the binary (i.e. .sdat) file or a */ /* compressed raster (.sg-grd-z) file. */ /* -------------------------------------------------------------------- */ - CPLString osExtension(CPLGetExtension(poOpenInfo->pszFilename)); + const auto &osExtension = poOpenInfo->osExtension; - if (!EQUAL(osExtension, "sdat") && !EQUAL(osExtension, "sg-grd-z")) + if (!EQUAL(osExtension.c_str(), "sdat") && + !EQUAL(osExtension.c_str(), "sg-grd-z")) { return nullptr; } CPLString osPath, osFullname, osName, osHDRFilename; - if (EQUAL(osExtension, "sg-grd-z") && + if (EQUAL(osExtension.c_str(), "sg-grd-z") && !STARTS_WITH(poOpenInfo->pszFilename, "/vsizip")) { osPath = "/vsizip/{"; @@ -432,7 +435,7 @@ GDALDataset *SAGADataset::Open(GDALOpenInfo *poOpenInfo) CPLString file; for (int iFile = 0; filesinzip[iFile] != nullptr; iFile++) { - if (EQUAL(CPLGetExtension(filesinzip[iFile]), "sdat")) + if (EQUAL(CPLGetExtensionSafe(filesinzip[iFile]).c_str(), "sdat")) { file = filesinzip[iFile]; break; @@ -441,17 +444,19 @@ GDALDataset *SAGADataset::Open(GDALOpenInfo *poOpenInfo) CSLDestroy(filesinzip); - osFullname = CPLFormFilename(osPath, file, nullptr); - osName = CPLGetBasename(file); - osHDRFilename = CPLFormFilename(osPath, CPLGetBasename(file), "sgrd"); + osFullname = CPLFormFilenameSafe(osPath, file, nullptr); + osName = CPLGetBasenameSafe(file); + osHDRFilename = CPLFormFilenameSafe( + osPath, CPLGetBasenameSafe(file).c_str(), "sgrd"); } else { osFullname = poOpenInfo->pszFilename; - osPath = CPLGetPath(poOpenInfo->pszFilename); - osName = CPLGetBasename(poOpenInfo->pszFilename); - osHDRFilename = CPLFormCIFilename( - osPath, CPLGetBasename(poOpenInfo->pszFilename), "sgrd"); + osPath = CPLGetPathSafe(poOpenInfo->pszFilename); + osName = CPLGetBasenameSafe(poOpenInfo->pszFilename); + osHDRFilename = CPLFormCIFilenameSafe( + osPath, CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str(), + "sgrd"); } VSILFILE *fp = VSIFOpenL(osHDRFilename, "r"); @@ -659,15 +664,16 @@ GDALDataset *SAGADataset::Open(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* Check for a .prj file. */ /* -------------------------------------------------------------------- */ - const char *pszPrjFilename = CPLFormCIFilename(osPath, osName, "prj"); + const std::string osPrjFilename = + CPLFormCIFilenameSafe(osPath, osName, "prj"); - fp = VSIFOpenL(pszPrjFilename, "r"); + fp = VSIFOpenL(osPrjFilename.c_str(), "r"); if (fp != nullptr) { VSIFCloseL(fp); - char **papszLines = CSLLoad(pszPrjFilename); + char **papszLines = CSLLoad(osPrjFilename.c_str()); poDS->m_oSRS.importFromESRI(papszLines); @@ -786,7 +792,7 @@ CPLErr SAGADataset::WriteHeader(CPLString osHDRFilename, GDALDataType eType, return CE_Failure; } - VSIFPrintfL(fp, "NAME\t= %s\n", CPLGetBasename(osHDRFilename)); + VSIFPrintfL(fp, "NAME\t= %s\n", CPLGetBasenameSafe(osHDRFilename).c_str()); VSIFPrintfL(fp, "DESCRIPTION\t=\n"); VSIFPrintfL(fp, "UNIT\t=\n"); VSIFPrintfL(fp, "DATAFILE_OFFSET\t= 0\n"); @@ -930,7 +936,7 @@ GDALDataset *SAGADataset::Create(const char *pszFilename, int nXSize, void *abyNoData = &dfNoDataForAlignment; GDALCopyWords(&dfNoDataVal, GDT_Float64, 0, abyNoData, eType, 0, 1); - const CPLString osHdrFilename = CPLResetExtension(pszFilename, "sgrd"); + const CPLString osHdrFilename = CPLResetExtensionSafe(pszFilename, "sgrd"); CPLErr eErr = WriteHeader(osHdrFilename, eType, nXSize, nYSize, 0.0, 0.0, 1.0, dfNoDataVal, 1.0, false); diff --git a/frmts/sdts/sdtscatd.cpp b/frmts/sdts/sdtscatd.cpp index a7b6a90d1c60..5dc1bd964411 100644 --- a/frmts/sdts/sdtscatd.cpp +++ b/frmts/sdts/sdtscatd.cpp @@ -172,7 +172,8 @@ int SDTS_CATD::Read(const char *pszFilename) /* -------------------------------------------------------------------- */ poEntry->pszFullPath = CPLStrdup( - CPLFormCIFilename(pszPrefixPath, poEntry->pszFile, nullptr)); + CPLFormCIFilenameSafe(pszPrefixPath, poEntry->pszFile, nullptr) + .c_str()); /* -------------------------------------------------------------------- */ diff --git a/frmts/sentinel2/sentinel2dataset.cpp b/frmts/sentinel2/sentinel2dataset.cpp index 2d97eb187405..f6ac1c946978 100644 --- a/frmts/sentinel2/sentinel2dataset.cpp +++ b/frmts/sentinel2/sentinel2dataset.cpp @@ -397,7 +397,7 @@ int SENTINEL2Dataset::Identify(GDALOpenInfo *poOpenInfo) STARTS_WITH_CI(pszJustFilename, "S2B_OPER_PRD_MSI") || STARTS_WITH_CI(pszJustFilename, "S2A_USER_PRD_MSI") || STARTS_WITH_CI(pszJustFilename, "S2B_USER_PRD_MSI")) && - EQUAL(CPLGetExtension(pszJustFilename), "zip")) + EQUAL(CPLGetExtensionSafe(pszJustFilename).c_str(), "zip")) { return TRUE; } @@ -501,13 +501,13 @@ GDALDataset *SENTINEL2Dataset::Open(GDALOpenInfo *poOpenInfo) STARTS_WITH_CI(pszJustFilename, "S2B_OPER_PRD_MSI") || STARTS_WITH_CI(pszJustFilename, "S2A_USER_PRD_MSI") || STARTS_WITH_CI(pszJustFilename, "S2B_USER_PRD_MSI")) && - EQUAL(CPLGetExtension(pszJustFilename), "zip")) + EQUAL(CPLGetExtensionSafe(pszJustFilename).c_str(), "zip")) { - const CPLString osBasename(CPLGetBasename(pszJustFilename)); + const CPLString osBasename(CPLGetBasenameSafe(pszJustFilename)); CPLString osFilename(poOpenInfo->pszFilename); CPLString osMTD(osBasename); // Normally given above constraints, osMTD.size() should be >= 16 - // but if pszJustFilename is too long, CPLGetBasename() will return + // but if pszJustFilename is too long, CPLGetBasenameSafe().c_str() will return // an empty string. if (osMTD.size() < 16) return nullptr; @@ -527,15 +527,15 @@ GDALDataset *SENTINEL2Dataset::Open(GDALOpenInfo *poOpenInfo) } else if ((STARTS_WITH_CI(pszJustFilename, "S2A_MSIL1C_") || STARTS_WITH_CI(pszJustFilename, "S2B_MSIL1C_")) && - EQUAL(CPLGetExtension(pszJustFilename), "zip")) + EQUAL(CPLGetExtensionSafe(pszJustFilename).c_str(), "zip")) { - const CPLString osBasename(CPLGetBasename(pszJustFilename)); + const CPLString osBasename(CPLGetBasenameSafe(pszJustFilename)); CPLString osFilename(poOpenInfo->pszFilename); CPLString osSAFE(osBasename); // S2B_MSIL1C_20171004T233419_N0206_R001_T54DWM_20171005T001811.SAFE.zip // has .SAFE.zip extension, but other products have just a .zip // extension. So for the subdir in the zip only add .SAFE when needed - if (!EQUAL(CPLGetExtension(osSAFE), "SAFE")) + if (!EQUAL(CPLGetExtensionSafe(osSAFE).c_str(), "SAFE")) osSAFE += ".SAFE"; osFilename = osFilename + "/" + osSAFE + "/MTD_MSIL1C.xml"; if (strncmp(osFilename, "/vsizip/", strlen("/vsizip/")) != 0) @@ -546,15 +546,15 @@ GDALDataset *SENTINEL2Dataset::Open(GDALOpenInfo *poOpenInfo) } else if ((STARTS_WITH_CI(pszJustFilename, "S2A_MSIL2A_") || STARTS_WITH_CI(pszJustFilename, "S2B_MSIL2A_")) && - EQUAL(CPLGetExtension(pszJustFilename), "zip")) + EQUAL(CPLGetExtensionSafe(pszJustFilename).c_str(), "zip")) { - const CPLString osBasename(CPLGetBasename(pszJustFilename)); + const CPLString osBasename(CPLGetBasenameSafe(pszJustFilename)); CPLString osFilename(poOpenInfo->pszFilename); CPLString osSAFE(osBasename); // S2B_MSIL1C_20171004T233419_N0206_R001_T54DWM_20171005T001811.SAFE.zip // has .SAFE.zip extension, but other products have just a .zip // extension. So for the subdir in the zip only add .SAFE when needed - if (!EQUAL(CPLGetExtension(osSAFE), "SAFE")) + if (!EQUAL(CPLGetExtensionSafe(osSAFE).c_str(), "SAFE")) osSAFE += ".SAFE"; osFilename = osFilename + "/" + osSAFE + "/MTD_MSIL2A.xml"; if (strncmp(osFilename, "/vsizip/", strlen("/vsizip/")) != 0) @@ -878,7 +878,7 @@ static bool SENTINEL2GetGranuleInfo( /************************************************************************/ // For the sake of simplifying our unit tests, we limit the use of \\ to when -// it is strictly necessary. Otherwise we could use CPLFormFilename()... +// it is strictly necessary. Otherwise we could use CPLFormFilenameSafe()... static char SENTINEL2GetPathSeparator(const char *pszBasename) { if (STARTS_WITH_CI(pszBasename, "\\\\?\\")) @@ -935,7 +935,7 @@ static bool SENTINEL2GetGranuleList( return false; } - CPLString osDirname(CPLGetDirname(pszFilename)); + CPLString osDirname(CPLGetDirnameSafe(pszFilename)); #ifdef HAVE_READLINK char szPointerFilename[2048]; int nBytes = static_cast( @@ -945,7 +945,7 @@ static bool SENTINEL2GetGranuleList( const int nOffset = std::min(nBytes, static_cast(sizeof(szPointerFilename) - 1)); szPointerFilename[nOffset] = '\0'; - osDirname = CPLGetDirname(szPointerFilename); + osDirname = CPLGetDirnameSafe(szPointerFilename); } #endif @@ -1726,18 +1726,21 @@ static CPLString SENTINEL2GetMainMTDFilenameFromGranuleMTD(const char *pszFilename) { // Look for product MTD file - CPLString osTopDir(CPLFormFilename( - CPLFormFilename(CPLGetDirname(pszFilename), "..", nullptr), "..", - nullptr)); + CPLString osTopDir(CPLFormFilenameSafe( + CPLFormFilenameSafe(CPLGetDirnameSafe(pszFilename).c_str(), "..", + nullptr) + .c_str(), + "..", nullptr)); // Workaround to avoid long filenames on Windows if (CPLIsFilenameRelative(pszFilename)) { // GRANULE/bla/bla.xml - const char *pszPath = CPLGetPath(pszFilename); - if (strchr(pszPath, '/') || strchr(pszPath, '\\')) + const std::string osPath = CPLGetPathSafe(pszFilename); + if (osPath.find('/') != std::string::npos || + osPath.find('\\') != std::string::npos) { - osTopDir = CPLGetPath(CPLGetPath(pszPath)); + osTopDir = CPLGetPathSafe(CPLGetPathSafe(osPath.c_str()).c_str()); if (osTopDir == "") osTopDir = "."; } @@ -1752,7 +1755,7 @@ SENTINEL2GetMainMTDFilenameFromGranuleMTD(const char *pszFilename) STARTS_WITH_CI(*papszIter, "S2B_")) && EQUALN(*papszIter + strlen("S2A_XXXX"), "_MTD", 4)) { - osMainMTD = CPLFormFilename(osTopDir, *papszIter, nullptr); + osMainMTD = CPLFormFilenameSafe(osTopDir, *papszIter, nullptr); break; } } @@ -1816,9 +1819,9 @@ static void SENTINEL2GetResolutionSetAndMainMDFromGranule( if (atoi(osBandName) < 10) osBandName = "0" + osBandName; - CPLString osTile(SENTINEL2GetTilename(CPLGetPath(pszFilename), - CPLGetBasename(pszFilename), - osBandName)); + CPLString osTile(SENTINEL2GetTilename( + CPLGetPathSafe(pszFilename).c_str(), + CPLGetBasenameSafe(pszFilename).c_str(), osBandName)); VSIStatBufL sStat; if (VSIStatExL(osTile, &sStat, VSI_STAT_EXISTS_FLAG) == 0) { @@ -2050,9 +2053,9 @@ GDALDataset *SENTINEL2Dataset::OpenL1BSubdataset(GDALOpenInfo *poOpenInfo) { for (size_t i = 0; i < aosBands.size(); i++) { - CPLString osTile(SENTINEL2GetTilename(CPLGetPath(osFilename), - CPLGetBasename(osFilename), - aosBands[i])); + CPLString osTile(SENTINEL2GetTilename( + CPLGetPathSafe(osFilename).c_str(), + CPLGetBasenameSafe(osFilename).c_str(), aosBands[i])); if (SENTINEL2GetTileInfo(osTile, &nCols, &nRows, &nBits)) { if (nBits <= 16) @@ -2161,7 +2164,8 @@ GDALDataset *SENTINEL2Dataset::OpenL1BSubdataset(GDALOpenInfo *poOpenInfo) osBandName = aosBands[0]; CPLString osTile(SENTINEL2GetTilename( - CPLGetPath(osFilename), CPLGetBasename(osFilename), osBandName)); + CPLGetPathSafe(osFilename).c_str(), + CPLGetBasenameSafe(osFilename).c_str(), osBandName)); bool bTileFound = false; if (nValMax == 0) @@ -2326,7 +2330,7 @@ static bool SENTINEL2GetGranuleList_L1CSafeCompact( return false; } - CPLString osDirname(CPLGetDirname(pszFilename)); + CPLString osDirname(CPLGetDirnameSafe(pszFilename)); #ifdef HAVE_READLINK char szPointerFilename[2048]; int nBytes = static_cast( @@ -2336,7 +2340,7 @@ static bool SENTINEL2GetGranuleList_L1CSafeCompact( const int nOffset = std::min(nBytes, static_cast(sizeof(szPointerFilename) - 1)); szPointerFilename[nOffset] = '\0'; - osDirname = CPLGetDirname(szPointerFilename); + osDirname = CPLGetDirnameSafe(szPointerFilename); } #endif @@ -2371,9 +2375,10 @@ static bool SENTINEL2GetGranuleList_L1CSafeCompact( 3); // strip B12 // GRANULE/L1C_T30TXT_A007999_20170102T111441/IMG_DATA/T30TXT_20170102T111442_B12 // --> GRANULE/L1C_T30TXT_A007999_20170102T111441/MTD_TL.xml - oDesc.osMTDTLPath = osDirname + chSeparator + - CPLGetDirname(CPLGetDirname(pszImageFile)) + - chSeparator + "MTD_TL.xml"; + oDesc.osMTDTLPath = + osDirname + chSeparator + + CPLGetDirnameSafe(CPLGetDirnameSafe(pszImageFile).c_str()) + + chSeparator + "MTD_TL.xml"; osList.push_back(oDesc); } } @@ -2417,7 +2422,7 @@ static bool SENTINEL2GetGranuleList_L2ASafeCompact( } } - CPLString osDirname(CPLGetDirname(pszFilename)); + CPLString osDirname(CPLGetDirnameSafe(pszFilename)); #ifdef HAVE_READLINK char szPointerFilename[2048]; int nBytes = static_cast( @@ -2427,7 +2432,7 @@ static bool SENTINEL2GetGranuleList_L2ASafeCompact( const int nOffset = std::min(nBytes, static_cast(sizeof(szPointerFilename) - 1)); szPointerFilename[nOffset] = '\0'; - osDirname = CPLGetDirname(szPointerFilename); + osDirname = CPLGetDirnameSafe(szPointerFilename); } #endif @@ -2471,8 +2476,9 @@ static bool SENTINEL2GetGranuleList_L2ASafeCompact( oDesc.osBandPrefixPath.resize(oDesc.osBandPrefixPath.size() - 36); // GRANULE/L1C_T30TXT_A007999_20170102T111441/IMG_DATA/T30TXT_20170102T111442_B12_60m // --> GRANULE/L1C_T30TXT_A007999_20170102T111441/MTD_TL.xml - oDesc.osMTDTLPath = osDirname + chSeparator + - CPLGetDirname(CPLGetDirname(pszImageFile)); + oDesc.osMTDTLPath = + osDirname + chSeparator + + CPLGetDirnameSafe(CPLGetDirnameSafe(pszImageFile).c_str()); if (oDesc.osMTDTLPath.size() < 9) { CPLDebug("SENTINEL2", "MTDTL path too short"); @@ -3579,7 +3585,7 @@ SENTINEL2Dataset *SENTINEL2Dataset::CreateL1CL2ADataset( dfMinY = dfLRY; SENTINEL2GranuleInfo oGranuleInfo; - oGranuleInfo.osPath = CPLGetPath(aosGranuleList[i]); + oGranuleInfo.osPath = CPLGetPathSafe(aosGranuleList[i]); if (bIsSafeCompact) { oGranuleInfo.osBandPrefixPath = diff --git a/frmts/sigdem/sigdemdataset.cpp b/frmts/sigdem/sigdemdataset.cpp index 17d45cdff3d3..fc697fa138bc 100644 --- a/frmts/sigdem/sigdemdataset.cpp +++ b/frmts/sigdem/sigdemdataset.cpp @@ -262,7 +262,8 @@ GDALDataset *SIGDEMDataset::CreateCopy(const char *pszFilename, { if (!EQUAL(pszProjection, "")) { - CPLString osPrjFilename = CPLResetExtension(pszFilename, "prj"); + const CPLString osPrjFilename = + CPLResetExtensionSafe(pszFilename, "prj"); VSILFILE *fpProj = VSIFOpenL(osPrjFilename, "wt"); if (fpProj != nullptr) { @@ -353,12 +354,13 @@ GDALDataset *SIGDEMDataset::Open(GDALOpenInfo *poOpenInfo) else { CPLString osPrjFilename = - CPLResetExtension(poOpenInfo->pszFilename, "prj"); + CPLResetExtensionSafe(poOpenInfo->pszFilename, "prj"); VSIStatBufL sStatBuf; int nRet = VSIStatL(osPrjFilename, &sStatBuf); if (nRet != 0 && VSIIsCaseSensitiveFS(osPrjFilename)) { - osPrjFilename = CPLResetExtension(poOpenInfo->pszFilename, "PRJ"); + osPrjFilename = + CPLResetExtensionSafe(poOpenInfo->pszFilename, "PRJ"); nRet = VSIStatL(osPrjFilename, &sStatBuf); } diff --git a/frmts/srtmhgt/srtmhgtdataset.cpp b/frmts/srtmhgt/srtmhgtdataset.cpp index cfba2c36c39c..bd53116d6a8d 100644 --- a/frmts/srtmhgt/srtmhgtdataset.cpp +++ b/frmts/srtmhgt/srtmhgtdataset.cpp @@ -183,7 +183,8 @@ double SRTMHGTRasterBand::GetNoDataValue(int *pbSuccess) const char *SRTMHGTRasterBand::GetUnitType() { - const char *pszExt = CPLGetExtension(poDS->GetDescription()); + const std::string osExt = CPLGetExtensionSafe(poDS->GetDescription()); + const char *pszExt = osExt.c_str(); if (EQUAL(pszExt, "err") || EQUAL(pszExt, "img") || EQUAL(pszExt, "num") || EQUAL(pszExt, "swb")) { diff --git a/frmts/stacta/stactadataset.cpp b/frmts/stacta/stactadataset.cpp index 9173a2426fa4..60ebd3d00152 100644 --- a/frmts/stacta/stactadataset.cpp +++ b/frmts/stacta/stactadataset.cpp @@ -648,8 +648,7 @@ int STACTADataset::Identify(GDALOpenInfo *poOpenInfo) if ( #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - (!bIsSingleDriver && - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "json")) || + (!bIsSingleDriver && !poOpenInfo->IsExtensionEqualToCI("json")) || #endif poOpenInfo->nHeaderBytes == 0) { @@ -859,8 +858,8 @@ bool STACTADataset::Open(GDALOpenInfo *poOpenInfo) { if (STARTS_WITH(osURLTemplate, "./")) osURLTemplate = osURLTemplate.substr(2); - osURLTemplate = CPLProjectRelativeFilename(CPLGetDirname(osFilename), - osURLTemplate); + osURLTemplate = CPLProjectRelativeFilenameSafe( + CPLGetDirnameSafe(osFilename).c_str(), osURLTemplate); } // Parse optional tile matrix set limits diff --git a/frmts/tga/tgadataset.cpp b/frmts/tga/tgadataset.cpp index 08e5fe617f9a..84a6ca75ae7f 100644 --- a/frmts/tga/tgadataset.cpp +++ b/frmts/tga/tgadataset.cpp @@ -158,7 +158,7 @@ int GDALTGADataset::Identify(GDALOpenInfo *poOpenInfo) return TRUE; } - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "tga")) + if (!poOpenInfo->IsExtensionEqualToCI("tga")) return FALSE; return TRUE; } diff --git a/frmts/til/tildataset.cpp b/frmts/til/tildataset.cpp index 846bf516892f..8825d121d2b6 100644 --- a/frmts/til/tildataset.cpp +++ b/frmts/til/tildataset.cpp @@ -174,7 +174,7 @@ int TILDataset::Identify(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->nHeaderBytes < 200 || - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "TIL")) + !poOpenInfo->IsExtensionEqualToCI("TIL")) return FALSE; if (strstr((const char *)poOpenInfo->pabyHeader, "numTiles") == nullptr) @@ -204,7 +204,7 @@ GDALDataset *TILDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; } - CPLString osDirname = CPLGetDirname(poOpenInfo->pszFilename); + CPLString osDirname = CPLGetDirnameSafe(poOpenInfo->pszFilename); // get metadata reader @@ -291,7 +291,7 @@ GDALDataset *TILDataset::Open(GDALOpenInfo *poOpenInfo) if (pszFilename[strlen(pszFilename) - 1] == '"') const_cast(pszFilename)[strlen(pszFilename) - 1] = '\0'; - CPLString osFilename = CPLFormFilename(osDirname, pszFilename, nullptr); + CPLString osFilename = CPLFormFilenameSafe(osDirname, pszFilename, nullptr); GDALDataset *poTemplateDS = GDALDataset::FromHandle(GDALOpen(osFilename, GA_ReadOnly)); if (poTemplateDS == nullptr || poTemplateDS->GetRasterCount() == 0) @@ -378,7 +378,7 @@ GDALDataset *TILDataset::Open(GDALOpenInfo *poOpenInfo) pszFilename++; if (pszFilename[strlen(pszFilename) - 1] == '"') const_cast(pszFilename)[strlen(pszFilename) - 1] = '\0'; - osFilename = CPLFormFilename(osDirname, pszFilename, nullptr); + osFilename = CPLFormFilenameSafe(osDirname, pszFilename, nullptr); poDS->m_aosFilenames.push_back(osFilename); osKey.Printf("TILE_%d.ULColOffset", iTile); diff --git a/frmts/tiledb/tiledbcommon.cpp b/frmts/tiledb/tiledbcommon.cpp index 4bce16ea7860..0373abe826fc 100644 --- a/frmts/tiledb/tiledbcommon.cpp +++ b/frmts/tiledb/tiledbcommon.cpp @@ -34,7 +34,7 @@ CPLString TileDBDataset::VSI_to_tiledb_uri(const char *pszUri) { char *pszCurDir = CPLGetCurrentDir(); if (pszCurDir) - osUri = CPLFormFilename(pszCurDir, pszUri, nullptr); + osUri = CPLFormFilenameSafe(pszCurDir, pszUri, nullptr); CPLFree(pszCurDir); } } diff --git a/frmts/tiledb/tiledbdense.cpp b/frmts/tiledb/tiledbdense.cpp index 22493681e2ba..f3079e20085c 100644 --- a/frmts/tiledb/tiledbdense.cpp +++ b/frmts/tiledb/tiledbdense.cpp @@ -348,8 +348,8 @@ CPLErr TileDBRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, if (eErr == CE_None) { - CPLString osName = CPLString().Printf( - "%s", CPLGetBasename(poAttrDS->GetDescription())); + CPLString osName = + CPLGetBasenameSafe(poAttrDS->GetDescription()); SetBuffer(poQuery.get(), eAttrType, osName, pAttrBlock, nValues); @@ -1240,7 +1240,7 @@ CPLErr TileDBRasterDataset::TryLoadCachedXML(CSLConstList /*papszSiblingFiles*/, /* -------------------------------------------------------------------- */ - CPLString osPath(CPLGetPath(psPam->pszPamFilename)); + CPLString osPath(CPLGetPathSafe(psPam->pszPamFilename)); const CPLErr eErr = XMLInit(psTree, osPath); CPLDestroyXMLNode(psTree); @@ -1352,7 +1352,6 @@ GDALDataset *TileDBRasterDataset::OpenInternal(GDALOpenInfo *poOpenInfo, poDS->nTimestamp = std::strtoull(pszTimestamp, nullptr, 10); CPLString osURI; - CPLString osAux; CPLString osSubdataset; std::string osAttrNameTmp; @@ -1387,11 +1386,12 @@ GDALDataset *TileDBRasterDataset::OpenInternal(GDALOpenInfo *poOpenInfo, osURI = TileDBDataset::VSI_to_tiledb_uri(poOpenInfo->pszFilename); } - const char *pszArrayName = CPLGetBasename(osURI); - osAux.Printf("%s.tdb", pszArrayName); + CPLString osAux = CPLGetBasenameSafe(osURI); + osAux += ".tdb"; // aux file is in array folder - poDS->SetPhysicalFilename(CPLFormFilename(osURI, osAux, nullptr)); + poDS->SetPhysicalFilename( + CPLFormFilenameSafe(osURI, osAux, nullptr).c_str()); // Initialize any PAM information. poDS->SetDescription(osURI); @@ -1401,7 +1401,7 @@ GDALDataset *TileDBRasterDataset::OpenInternal(GDALOpenInfo *poOpenInfo, poDS->m_bDatasetInGroup = true; // Full resolution raster array - poDS->m_osArrayURI = CPLFormFilename(osURI.c_str(), "l_0", nullptr); + poDS->m_osArrayURI = CPLFormFilenameSafe(osURI.c_str(), "l_0", nullptr); } const tiledb_query_type_t eMode = @@ -2111,7 +2111,8 @@ TileDBRasterDataset *TileDBRasterDataset::CreateLL(const char *pszFilename, } // Full resolution raster array - poDS->m_osArrayURI = CPLFormFilename(pszFilename, "l_0", nullptr); + poDS->m_osArrayURI = + CPLFormFilenameSafe(pszFilename, "l_0", nullptr); } else { @@ -2157,12 +2158,11 @@ TileDBRasterDataset *TileDBRasterDataset::CreateLL(const char *pszFilename, } } - CPLString osAux; - const char *pszArrayName = CPLGetBasename(pszFilename); - osAux.Printf("%s.tdb", pszArrayName); + CPLString osAux = CPLGetBasenameSafe(pszFilename); + osAux += ".tdb"; poDS->SetPhysicalFilename( - CPLFormFilename(pszFilename, osAux.c_str(), nullptr)); + CPLFormFilenameSafe(pszFilename, osAux.c_str(), nullptr).c_str()); // Initialize PAM information. poDS->SetDescription(pszFilename); @@ -2285,13 +2285,13 @@ bool TileDBRasterDataset::DeferredCreate(bool bCreateArray) // be reported as subdatasets on future reads for (const auto &poAttrDS : m_lpoAttributeDS) { - const char *pszAttrName = - CPLGetBasename(poAttrDS->GetDescription()); + const std::string osAttrName = + CPLGetBasenameSafe(poAttrDS->GetDescription()); GDALRasterBand *poAttrBand = poAttrDS->GetRasterBand(1); int bHasNoData = false; const double dfNoData = poAttrBand->GetNoDataValue(&bHasNoData); - CreateAttribute(poAttrBand->GetRasterDataType(), pszAttrName, 1, - CPL_TO_BOOL(bHasNoData), dfNoData); + CreateAttribute(poAttrBand->GetRasterDataType(), osAttrName.c_str(), + 1, CPL_TO_BOOL(bHasNoData), dfNoData); } if (bCreateArray) @@ -2602,7 +2602,7 @@ TileDBRasterDataset *TileDBRasterDataset::Create(const char *pszFilename, { aosImageStruct.SetNameValue( CPLString().Printf("TILEDB_ATTRIBUTE_%i", ++i), - CPLGetBasename(poAttrDS->GetDescription())); + CPLGetBasenameSafe(poAttrDS->GetDescription()).c_str()); } } poDS->SetMetadata(aosImageStruct.List(), "IMAGE_STRUCTURE"); @@ -2809,8 +2809,8 @@ void TileDBRasterDataset::LoadOverviews() for (int i = 0; i < m_nOverviewCountFromMetadata; ++i) { const std::string osArrayName = CPLSPrintf("l_%d", 1 + i); - std::string osOvrDatasetName = - CPLFormFilename(GetDescription(), osArrayName.c_str(), nullptr); + const std::string osOvrDatasetName = + CPLFormFilenameSafe(GetDescription(), osArrayName.c_str(), nullptr); GDALOpenInfo oOpenInfo(osOvrDatasetName.c_str(), eAccess); oOpenInfo.papszOpenOptions = aosOpenOptions.List(); @@ -3012,8 +3012,8 @@ CPLErr TileDBRasterDataset::IBuildOverviews( const std::string osArrayName = CPLSPrintf("l_%d", 1 + int(m_apoOverviewDS.size())); - std::string osOvrDatasetName = - CPLFormFilename(GetDescription(), osArrayName.c_str(), nullptr); + const std::string osOvrDatasetName = CPLFormFilenameSafe( + GetDescription(), osArrayName.c_str(), nullptr); auto poOvrDS = std::unique_ptr( Create(osOvrDatasetName.c_str(), nOXSize, nOYSize, nBands, diff --git a/frmts/tiledb/tiledbsparse.cpp b/frmts/tiledb/tiledbsparse.cpp index e4ede677f9e2..9dfbc0a35fc3 100644 --- a/frmts/tiledb/tiledbsparse.cpp +++ b/frmts/tiledb/tiledbsparse.cpp @@ -229,8 +229,9 @@ GDALDataset *OGRTileDBDataset::Open(GDALOpenInfo *poOpenInfo, { auto poLayer = std::make_unique( poDS.get(), osLayerFilename.c_str(), - osLayerName.has_value() ? (*osLayerName).c_str() - : CPLGetBasename(osLayerFilename.c_str()), + osLayerName.has_value() + ? (*osLayerName).c_str() + : CPLGetBasenameSafe(osLayerFilename.c_str()).c_str(), wkbUnknown, nullptr); poLayer->m_bUpdatable = poOpenInfo->eAccess == GA_Update; if (!poLayer->InitFromStorage(poDS->m_ctx.get(), nTimestamp, @@ -358,7 +359,8 @@ OGRTileDBDataset::ICreateLayer(const char *pszName, std::string osFilename = GetDescription(); if (!m_osGroupName.empty()) { - osFilename = CPLFormFilename(m_osGroupName.c_str(), "layers", nullptr); + osFilename = + CPLFormFilenameSafe(m_osGroupName.c_str(), "layers", nullptr); if (!STARTS_WITH(m_osGroupName.c_str(), "s3://") && !STARTS_WITH(m_osGroupName.c_str(), "gcs://")) { @@ -366,7 +368,7 @@ OGRTileDBDataset::ICreateLayer(const char *pszName, if (VSIStatL(osFilename.c_str(), &sStat) != 0) VSIMkdir(osFilename.c_str(), 0755); } - osFilename = CPLFormFilename(osFilename.c_str(), pszName, nullptr); + osFilename = CPLFormFilenameSafe(osFilename.c_str(), pszName, nullptr); } auto poLayer = std::make_unique( this, osFilename.c_str(), pszName, eGType, poSpatialRef); diff --git a/frmts/tsx/tsxdataset.cpp b/frmts/tsx/tsxdataset.cpp index 114708a7d92c..d40b17b38737 100644 --- a/frmts/tsx/tsxdataset.cpp +++ b/frmts/tsx/tsxdataset.cpp @@ -252,15 +252,18 @@ int TSXDataset::Identify(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->bIsDirectory) { - const CPLString osFilename = CPLFormCIFilename( + const CPLString osFilename = CPLFormCIFilenameSafe( poOpenInfo->pszFilename, CPLGetFilename(poOpenInfo->pszFilename), "xml"); /* Check if the filename contains TSX1_SAR (TerraSAR-X) or TDX1_SAR * (TanDEM-X) or PAZ1_SAR (PAZ) */ - if (!(STARTS_WITH_CI(CPLGetBasename(osFilename), "TSX1_SAR") || - STARTS_WITH_CI(CPLGetBasename(osFilename), "TDX1_SAR") || - STARTS_WITH_CI(CPLGetBasename(osFilename), "PAZ1_SAR"))) + if (!(STARTS_WITH_CI(CPLGetBasenameSafe(osFilename).c_str(), + "TSX1_SAR") || + STARTS_WITH_CI(CPLGetBasenameSafe(osFilename).c_str(), + "TDX1_SAR") || + STARTS_WITH_CI(CPLGetBasenameSafe(osFilename).c_str(), + "PAZ1_SAR"))) return 0; VSIStatBufL sStat; @@ -273,9 +276,12 @@ int TSXDataset::Identify(GDALOpenInfo *poOpenInfo) /* Check if the filename contains TSX1_SAR (TerraSAR-X) or TDX1_SAR * (TanDEM-X) or PAZ1_SAR (PAZ) */ - if (!(STARTS_WITH_CI(CPLGetBasename(poOpenInfo->pszFilename), "TSX1_SAR") || - STARTS_WITH_CI(CPLGetBasename(poOpenInfo->pszFilename), "TDX1_SAR") || - STARTS_WITH_CI(CPLGetBasename(poOpenInfo->pszFilename), "PAZ1_SAR"))) + if (!(STARTS_WITH_CI(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str(), + "TSX1_SAR") || + STARTS_WITH_CI(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str(), + "TDX1_SAR") || + STARTS_WITH_CI(CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str(), + "PAZ1_SAR"))) return 0; /* finally look for the bIsDirectory) { - osFilename = - CPLFormCIFilename(poOpenInfo->pszFilename, - CPLGetFilename(poOpenInfo->pszFilename), "xml"); + osFilename = CPLFormCIFilenameSafe( + poOpenInfo->pszFilename, CPLGetFilename(poOpenInfo->pszFilename), + "xml"); } else osFilename = poOpenInfo->pszFilename; @@ -589,9 +595,9 @@ GDALDataset *TSXDataset::Open(GDALOpenInfo *poOpenInfo) psComponent != nullptr; psComponent = psComponent->psNext) { const char *pszType = nullptr; - const char *pszPath = - CPLFormFilename(CPLGetDirname(osFilename), - GetFilePath(psComponent, &pszType).c_str(), ""); + const std::string osPath = + CPLFormFilenameSafe(CPLGetDirnameSafe(osFilename).c_str(), + GetFilePath(psComponent, &pszType).c_str(), ""); const char *pszPolLayer = CPLGetXMLValue(psComponent, "polLayer", " "); if (!STARTS_WITH_CI(pszType, " ")) @@ -599,13 +605,13 @@ GDALDataset *TSXDataset::Open(GDALOpenInfo *poOpenInfo) if (STARTS_WITH_CI(pszType, "MAPPING_GRID")) { /* the mapping grid... save as a metadata item this path */ - poDS->SetMetadataItem("MAPPING_GRID", pszPath); + poDS->SetMetadataItem("MAPPING_GRID", osPath.c_str()); } else if (STARTS_WITH_CI(pszType, "GEOREF")) { /* save the path to the georef data for later use */ CPLFree(pszGeorefFile); - pszGeorefFile = CPLStrdup(pszPath); + pszGeorefFile = CPLStrdup(osPath.c_str()); } } else if (!STARTS_WITH_CI(pszPolLayer, " ") && @@ -636,7 +642,7 @@ GDALDataset *TSXDataset::Open(GDALOpenInfo *poOpenInfo) /* try opening the file that represents that band */ GDALDataset *poBandData = - GDALDataset::FromHandle(GDALOpen(pszPath, GA_ReadOnly)); + GDALDataset::FromHandle(GDALOpen(osPath.c_str(), GA_ReadOnly)); if (poBandData != nullptr) { TSXRasterBand *poBand = diff --git a/frmts/vrt/vrtdataset.cpp b/frmts/vrt/vrtdataset.cpp index 2ab37fea1f67..b8b7df6a16fd 100644 --- a/frmts/vrt/vrtdataset.cpp +++ b/frmts/vrt/vrtdataset.cpp @@ -160,7 +160,7 @@ CPLErr VRTFlushCacheStruct::FlushCache(T &obj, bool bAtClosing) obj.m_bNeedsFlush = false; // Serialize XML representation to disk - const std::string osVRTPath(CPLGetPath(obj.GetDescription())); + const std::string osVRTPath(CPLGetPathSafe(obj.GetDescription())); CPLXMLNode *psDSTree = obj.T::SerializeToXML(osVRTPath.c_str()); if (!CPLSerializeXMLTreeToFile(psDSTree, obj.GetDescription())) eErr = CE_Failure; @@ -182,7 +182,7 @@ char **VRTDataset::GetMetadata(const char *pszDomain) const char *pszDescription = GetDescription(); char *l_pszVRTPath = CPLStrdup( pszDescription[0] && !STARTS_WITH(pszDescription, "(pabyOut); char *pszCurDir = CPLGetCurrentDir(); - const char *currentVrtFilename = - CPLProjectRelativeFilename(pszCurDir, poOpenInfo->pszFilename); + std::string currentVrtFilename = + CPLProjectRelativeFilenameSafe(pszCurDir, poOpenInfo->pszFilename); CPLString osInitialCurrentVrtFilename(currentVrtFilename); CPLFree(pszCurDir); @@ -808,7 +808,7 @@ GDALDataset *VRTDataset::Open(GDALOpenInfo *poOpenInfo) while (true) { VSIStatBuf statBuffer; - int lstatCode = lstat(currentVrtFilename, &statBuffer); + int lstatCode = lstat(currentVrtFilename.c_str(), &statBuffer); if (lstatCode == -1) { if (errno == ENOENT) @@ -821,7 +821,7 @@ GDALDataset *VRTDataset::Open(GDALOpenInfo *poOpenInfo) CPL_IGNORE_RET_VAL(VSIFCloseL(fp)); CPLFree(pszXML); CPLError(CE_Failure, CPLE_FileIO, "Failed to lstat %s: %s", - currentVrtFilename, VSIStrerror(errno)); + currentVrtFilename.c_str(), VSIStrerror(errno)); return nullptr; } } @@ -831,8 +831,9 @@ GDALDataset *VRTDataset::Open(GDALOpenInfo *poOpenInfo) break; } - const int bufferSize = static_cast(readlink( - currentVrtFilename, filenameBuffer, sizeof(filenameBuffer))); + const int bufferSize = static_cast( + readlink(currentVrtFilename.c_str(), filenameBuffer, + sizeof(filenameBuffer))); if (bufferSize != -1) { filenameBuffer[std::min( @@ -840,8 +841,9 @@ GDALDataset *VRTDataset::Open(GDALOpenInfo *poOpenInfo) 0; // The filename in filenameBuffer might be a relative path // from the linkfile resolve it before looping - currentVrtFilename = CPLProjectRelativeFilename( - CPLGetDirname(currentVrtFilename), filenameBuffer); + currentVrtFilename = CPLProjectRelativeFilenameSafe( + CPLGetDirnameSafe(currentVrtFilename.c_str()).c_str(), + filenameBuffer); } else { @@ -849,16 +851,18 @@ GDALDataset *VRTDataset::Open(GDALOpenInfo *poOpenInfo) CPLFree(pszXML); CPLError(CE_Failure, CPLE_FileIO, "Failed to read filename from symlink %s: %s", - currentVrtFilename, VSIStrerror(errno)); + currentVrtFilename.c_str(), VSIStrerror(errno)); return nullptr; } } #endif // HAVE_READLINK && HAVE_LSTAT if (osInitialCurrentVrtFilename == currentVrtFilename) - pszVRTPath = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); + pszVRTPath = + CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); else - pszVRTPath = CPLStrdup(CPLGetPath(currentVrtFilename)); + pszVRTPath = + CPLStrdup(CPLGetPathSafe(currentVrtFilename.c_str()).c_str()); CPL_IGNORE_RET_VAL(VSIFCloseL(fp)); } @@ -1675,7 +1679,8 @@ CPLErr VRTDataset::AddBand(GDALDataType eType, char **papszOptions) VRTRawRasterBand *poBand = new VRTRawRasterBand(this, GetRasterCount() + 1, eType); - char *l_pszVRTPath = CPLStrdup(CPLGetPath(GetDescription())); + char *l_pszVRTPath = + CPLStrdup(CPLGetPathSafe(GetDescription()).c_str()); if (EQUAL(l_pszVRTPath, "")) { CPLFree(l_pszVRTPath); @@ -3020,7 +3025,8 @@ std::string VRTDataset::BuildSourceFilename(const char *pszFilename, { auto path{oSubDSInfo->GetPathComponent()}; osSrcDSName = oSubDSInfo->ModifyPathComponent( - CPLProjectRelativeFilename(pszVRTPath, path.c_str())); + CPLProjectRelativeFilenameSafe(pszVRTPath, path.c_str()) + .c_str()); GDALDestroySubdatasetInfo(oSubDSInfo); } else @@ -3047,8 +3053,8 @@ std::string VRTDataset::BuildSourceFilename(const char *pszFilename, CPLString osPrefixFilename = pszFilename; osPrefixFilename.resize(pszLastPart - pszFilename); osSrcDSName = - osPrefixFilename + - CPLProjectRelativeFilename(pszVRTPath, pszLastPart); + osPrefixFilename + CPLProjectRelativeFilenameSafe( + pszVRTPath, pszLastPart); bDone = true; } else if (STARTS_WITH_CI(pszSyntax + osPrefix.size(), @@ -3067,7 +3073,7 @@ std::string VRTDataset::BuildSourceFilename(const char *pszFilename, const CPLString osSuffix = osFilename.substr(nPos); osFilename.resize(nPos); osSrcDSName = osPrefix + - CPLProjectRelativeFilename( + CPLProjectRelativeFilenameSafe( pszVRTPath, osFilename) + osSuffix; bDone = true; @@ -3084,13 +3090,13 @@ std::string VRTDataset::BuildSourceFilename(const char *pszFilename, // Simplify path by replacing "foo/a/../b" with "foo/b" while (STARTS_WITH(pszFilename, "../")) { - osVRTPath = CPLGetPath(osVRTPath.c_str()); + osVRTPath = CPLGetPathSafe(osVRTPath.c_str()); pszFilename += strlen("../"); } } - osSrcDSName = - CPLProjectRelativeFilename(osVRTPath.c_str(), pszFilename); + osSrcDSName = CPLProjectRelativeFilenameSafe(osVRTPath.c_str(), + pszFilename); } } } diff --git a/frmts/vrt/vrtdriver.cpp b/frmts/vrt/vrtdriver.cpp index 6a4eb013f690..c084db88712a 100644 --- a/frmts/vrt/vrtdriver.cpp +++ b/frmts/vrt/vrtdriver.cpp @@ -187,7 +187,7 @@ static GDALDataset *VRTCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, /* Convert tree to a single block of XML text. */ /* -------------------------------------------------------------------- */ - char *pszVRTPath = CPLStrdup(CPLGetPath(pszFilename)); + char *pszVRTPath = CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); poSrcVRTDS->UnsetPreservedRelativeFilenames(); CPLXMLNode *psDSTree = poSrcVRTDS->SerializeToXML(pszVRTPath); diff --git a/frmts/vrt/vrtmultidim.cpp b/frmts/vrt/vrtmultidim.cpp index c9359939fa30..cfdf00d2a284 100644 --- a/frmts/vrt/vrtmultidim.cpp +++ b/frmts/vrt/vrtmultidim.cpp @@ -1937,8 +1937,8 @@ bool VRTMDArraySourceFromArray::Read(const GUInt64 *arrayStartIdx, const std::string osFilename = m_bRelativeToVRT - ? std::string(CPLProjectRelativeFilename( - m_poDstArray->GetVRTPath().c_str(), m_osFilename.c_str())) + ? CPLProjectRelativeFilenameSafe(m_poDstArray->GetVRTPath().c_str(), + m_osFilename.c_str()) : m_osFilename; const std::string key(CreateKey(osFilename)); @@ -2668,8 +2668,8 @@ ParseSingleSourceArray(const CPLXMLNode *psSingleSourceArray, } const std::string osSourceFilename( bRelativeToVRT - ? CPLProjectRelativeFilename(pszVRTPath, pszSourceFilename) - : pszSourceFilename); + ? CPLProjectRelativeFilenameSafe(pszVRTPath, pszSourceFilename) + : std::string(pszSourceFilename)); auto poDS = std::unique_ptr( GDALDataset::Open(osSourceFilename.c_str(), GDAL_OF_MULTIDIM_RASTER | GDAL_OF_VERBOSE_ERROR, diff --git a/frmts/vrt/vrtpansharpened.cpp b/frmts/vrt/vrtpansharpened.cpp index a265369efded..06c4c3f0e754 100644 --- a/frmts/vrt/vrtpansharpened.cpp +++ b/frmts/vrt/vrtpansharpened.cpp @@ -317,9 +317,8 @@ CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree, return CE_Failure; } - const char *pszSourceFilename = - CPLGetXMLValue(psPanchroBand, "SourceFilename", nullptr); - if (pszSourceFilename == nullptr) + osSourceFilename = CPLGetXMLValue(psPanchroBand, "SourceFilename", ""); + if (osSourceFilename.empty()) { CPLError(CE_Failure, CPLE_AppDefined, "PanchroBand.SourceFilename missing"); @@ -329,12 +328,11 @@ CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree, psPanchroBand, "SourceFilename.relativetoVRT", "0"))); if (bRelativeToVRT) { - const char *pszAbs = - CPLProjectRelativeFilename(pszVRTPathIn, pszSourceFilename); - m_oMapToRelativeFilenames[pszAbs] = pszSourceFilename; - pszSourceFilename = pszAbs; + const std::string osAbs = CPLProjectRelativeFilenameSafe( + pszVRTPathIn, osSourceFilename.c_str()); + m_oMapToRelativeFilenames[osAbs] = osSourceFilename; + osSourceFilename = osAbs; } - osSourceFilename = pszSourceFilename; const CPLStringList aosOpenOptions( GDALDeserializeOpenOptionsFromXML(psPanchroBand)); @@ -518,9 +516,8 @@ CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree, } else { - const char *pszSourceFilename = - CPLGetXMLValue(psIter, "SourceFilename", nullptr); - if (pszSourceFilename == nullptr) + osSourceFilename = CPLGetXMLValue(psIter, "SourceFilename", ""); + if (osSourceFilename.empty()) { CPLError(CE_Failure, CPLE_AppDefined, "SpectralBand.SourceFilename missing"); @@ -530,12 +527,11 @@ CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree, CPLGetXMLValue(psIter, "SourceFilename.relativetoVRT", "0")); if (bRelativeToVRT) { - const char *pszAbs = - CPLProjectRelativeFilename(pszVRTPathIn, pszSourceFilename); - m_oMapToRelativeFilenames[pszAbs] = pszSourceFilename; - pszSourceFilename = pszAbs; + const std::string osAbs = CPLProjectRelativeFilenameSafe( + pszVRTPathIn, osSourceFilename.c_str()); + m_oMapToRelativeFilenames[osAbs] = osSourceFilename; + osSourceFilename = osAbs; } - osSourceFilename = pszSourceFilename; poDataset = oMapNamesToDataset[osSourceFilename]; if (poDataset == nullptr) { @@ -933,15 +929,12 @@ CPLErr VRTPansharpenedDataset::XMLInit(const CPLXMLNode *psTree, } else { - const char *pszSourceFilename = - CPLGetXMLValue(psIter, "SourceFilename", nullptr); - CPLAssert(pszSourceFilename); + osSourceFilename = CPLGetXMLValue(psIter, "SourceFilename", ""); const bool bRelativeToVRT = CPL_TO_BOOL(atoi( CPLGetXMLValue(psIter, "SourceFilename.relativetoVRT", "0"))); if (bRelativeToVRT) - pszSourceFilename = - CPLProjectRelativeFilename(pszVRTPathIn, pszSourceFilename); - osSourceFilename = pszSourceFilename; + osSourceFilename = CPLProjectRelativeFilenameSafe( + pszVRTPathIn, osSourceFilename.c_str()); poDataset = oMapNamesToDataset[osSourceFilename]; CPLAssert(poDataset); const char *pszSourceBand = diff --git a/frmts/vrt/vrtrasterband.cpp b/frmts/vrt/vrtrasterband.cpp index 2698926b777c..e7934238c6b0 100644 --- a/frmts/vrt/vrtrasterband.cpp +++ b/frmts/vrt/vrtrasterband.cpp @@ -517,8 +517,9 @@ CPLErr VRTRasterBand::XMLInit(const CPLXMLNode *psTree, const char *pszVRTPath, if (pszVRTPath != nullptr && atoi(CPLGetXMLValue(psFileNameNode, "relativetoVRT", "0"))) { - pszSrcDSName = - CPLStrdup(CPLProjectRelativeFilename(pszVRTPath, pszFilename)); + pszSrcDSName = CPLStrdup( + CPLProjectRelativeFilenameSafe(pszVRTPath, pszFilename) + .c_str()); } else pszSrcDSName = CPLStrdup(pszFilename); diff --git a/frmts/vrt/vrtrawrasterband.cpp b/frmts/vrt/vrtrawrasterband.cpp index 3bbfb668a664..2e1809505124 100644 --- a/frmts/vrt/vrtrawrasterband.cpp +++ b/frmts/vrt/vrtrawrasterband.cpp @@ -179,8 +179,8 @@ CPLErr VRTRawRasterBand::SetRawLink(const char *pszFilename, char *pszExpandedFilename = nullptr; if (pszVRTPath != nullptr && bRelativeToVRTIn) { - pszExpandedFilename = - CPLStrdup(CPLProjectRelativeFilename(pszVRTPath, pszFilename)); + pszExpandedFilename = CPLStrdup( + CPLProjectRelativeFilenameSafe(pszVRTPath, pszFilename).c_str()); } else { @@ -494,9 +494,9 @@ void VRTRawRasterBand::GetFileList(char ***ppapszFileList, int *pnSize, /* -------------------------------------------------------------------- */ CPLString osSourceFilename; if (m_bRelativeToVRT && strlen(poDS->GetDescription()) > 0) - osSourceFilename = - CPLFormFilename(CPLGetDirname(poDS->GetDescription()), - m_pszSourceFilename, nullptr); + osSourceFilename = CPLFormFilenameSafe( + CPLGetDirnameSafe(poDS->GetDescription()).c_str(), + m_pszSourceFilename, nullptr); else osSourceFilename = m_pszSourceFilename; diff --git a/frmts/vrt/vrtsources.cpp b/frmts/vrt/vrtsources.cpp index 4418920ce14d..c16b085b950e 100644 --- a/frmts/vrt/vrtsources.cpp +++ b/frmts/vrt/vrtsources.cpp @@ -439,15 +439,15 @@ void VRTSimpleSource::AddSourceFilenameNode(const char *pszVRTPath, !CPLIsFilenameRelative(osVRTFilename.c_str()) && pszCurDir != nullptr) { - osSourceDataset = - CPLFormFilename(pszCurDir, osSourceDataset.c_str(), nullptr); + osSourceDataset = CPLFormFilenameSafe( + pszCurDir, osSourceDataset.c_str(), nullptr); } else if (!CPLIsFilenameRelative(osSourceDataset.c_str()) && CPLIsFilenameRelative(osVRTFilename.c_str()) && pszCurDir != nullptr) { osVRTFilename = - CPLFormFilename(pszCurDir, osVRTFilename.c_str(), nullptr); + CPLFormFilenameSafe(pszCurDir, osVRTFilename.c_str(), nullptr); } CPLFree(pszCurDir); osSourceFilename = CPLExtractRelativePath( diff --git a/frmts/vrt/vrtwarped.cpp b/frmts/vrt/vrtwarped.cpp index 229cdc749c55..77c9b332861d 100644 --- a/frmts/vrt/vrtwarped.cpp +++ b/frmts/vrt/vrtwarped.cpp @@ -1417,7 +1417,8 @@ CPLErr VRTWarpedDataset::XMLInit(const CPLXMLNode *psTree, if (bRelativeToVRT) pszAbsolutePath = CPLStrdup( - CPLProjectRelativeFilename(pszVRTPathIn, pszRelativePath)); + CPLProjectRelativeFilenameSafe(pszVRTPathIn, pszRelativePath) + .c_str()); else pszAbsolutePath = CPLStrdup(pszRelativePath); @@ -1727,15 +1728,15 @@ CPLXMLNode *VRTWarpedDataset::SerializeToXML(const char *pszVRTPathIn) !CPLIsFilenameRelative(osVRTFilename.c_str()) && pszCurDir != nullptr) { - osSourceDataset = CPLFormFilename( + osSourceDataset = CPLFormFilenameSafe( pszCurDir, osSourceDataset.c_str(), nullptr); } else if (!CPLIsFilenameRelative(osSourceDataset.c_str()) && CPLIsFilenameRelative(osVRTFilename.c_str()) && pszCurDir != nullptr) { - osVRTFilename = - CPLFormFilename(pszCurDir, osVRTFilename.c_str(), nullptr); + osVRTFilename = CPLFormFilenameSafe( + pszCurDir, osVRTFilename.c_str(), nullptr); } CPLFree(pszCurDir); char *pszRelativePath = CPLStrdup(CPLExtractRelativePath( diff --git a/frmts/wcs/wcsutils.cpp b/frmts/wcs/wcsutils.cpp index 912e7c3ef78c..f2839845a5a3 100644 --- a/frmts/wcs/wcsutils.cpp +++ b/frmts/wcs/wcsutils.cpp @@ -297,7 +297,7 @@ bool MakeDir(const std::string &dirname) VSIStatBufL stat; if (VSIStatL(dirname.c_str(), &stat) != 0) { - std::string parent = CPLGetDirname(dirname.c_str()); + std::string parent = CPLGetDirnameSafe(dirname.c_str()); if (!parent.empty() && parent != ".") { if (!MakeDir(parent)) @@ -390,7 +390,7 @@ bool SetupCache(std::string &cache, bool clear) #endif if (home) { - cache = CPLFormFilename(home, ".gdal", nullptr); + cache = CPLFormFilenameSafe(home, ".gdal", nullptr); } else { @@ -406,10 +406,10 @@ bool SetupCache(std::string &cache, bool clear) { std::string subdir = ".gdal_"; subdir += username; - cache = CPLFormFilename(dir, subdir.c_str(), nullptr); + cache = CPLFormFilenameSafe(dir, subdir.c_str(), nullptr); } } - cache = CPLFormFilename(cache.c_str(), "wcs_cache", nullptr); + cache = CPLFormFilenameSafe(cache.c_str(), "wcs_cache", nullptr); } if (!MakeDir(cache)) { @@ -425,14 +425,14 @@ bool SetupCache(std::string &cache, bool clear) { continue; } - std::string filepath = - CPLFormFilename(cache.c_str(), folder[i], nullptr); + const std::string filepath = + CPLFormFilenameSafe(cache.c_str(), folder[i], nullptr); remove(filepath.c_str()); } CSLDestroy(folder); } // make sure the index exists and is writable - std::string db = CPLFormFilename(cache.c_str(), "db", nullptr); + const std::string db = CPLFormFilenameSafe(cache.c_str(), "db", nullptr); VSILFILE *f = VSIFOpenL(db.c_str(), "r"); if (f) { @@ -465,7 +465,7 @@ static bool CompareStrings(const std::string &a, const std::string &b) std::vector ReadCache(const std::string &cache) { std::vector contents; - std::string db = CPLFormFilename(cache.c_str(), "db", nullptr); + const std::string db = CPLFormFilenameSafe(cache.c_str(), "db", nullptr); char **data = CSLLoad(db.c_str()); if (data) { @@ -502,7 +502,7 @@ bool DeleteEntryFromCache(const std::string &cache, const std::string &key, { // Depending on which one of key and value is not "" delete the relevant // entry. - std::string db = CPLFormFilename(cache.c_str(), "db", nullptr); + const std::string db = CPLFormFilenameSafe(cache.c_str(), "db", nullptr); char **data = CSLLoad(db.c_str()); // returns NULL in error and for empty files char **data2 = CSLAddNameValue(nullptr, "foo", "bar"); @@ -550,8 +550,8 @@ bool DeleteEntryFromCache(const std::string &cache, const std::string &key, std::string name = folder[i]; if (name.find(filename) != std::string::npos) { - std::string filepath = - CPLFormFilename(cache.c_str(), name.c_str(), nullptr); + const std::string filepath = + CPLFormFilenameSafe(cache.c_str(), name.c_str(), nullptr); if (VSIUnlink(filepath.c_str()) == -1) { // error but can't do much, raise a warning? @@ -575,7 +575,7 @@ CPLErr SearchCache(const std::string &cache, const std::string &url, std::string &filename, const std::string &ext, bool &found) { found = false; - std::string db = CPLFormFilename(cache.c_str(), "db", nullptr); + const std::string db = CPLFormFilenameSafe(cache.c_str(), "db", nullptr); VSILFILE *f = VSIFOpenL(db.c_str(), "r"); if (!f) { @@ -601,8 +601,8 @@ CPLErr SearchCache(const std::string &cache, const std::string &url, VSIFCloseL(f); if (found) { - filename = - CPLFormFilename(cache.c_str(), (filename + ext).c_str(), nullptr); + filename = CPLFormFilenameSafe(cache.c_str(), (filename + ext).c_str(), + nullptr); found = FileIsReadable(filename); // if not readable, we should delete the entry } @@ -624,7 +624,7 @@ CPLErr AddEntryToCache(const std::string &cache, const std::string &url, // todo: lock the cache // assuming the url is not in the cache const std::string store = filename; - const std::string db = CPLFormFilename(cache.c_str(), "db", nullptr); + const std::string db = CPLFormFilenameSafe(cache.c_str(), "db", nullptr); VSILFILE *f = VSIFOpenL(db.c_str(), "a"); if (!f) { @@ -650,8 +650,8 @@ CPLErr AddEntryToCache(const std::string &cache, const std::string &url, } } // replace X with random character from a-zA-Z - path = - CPLFormFilename(cache.c_str(), (filename + ext).c_str(), nullptr); + path = CPLFormFilenameSafe(cache.c_str(), (filename + ext).c_str(), + nullptr); } while (VSIStatExL(path.c_str(), &stat, VSI_STAT_EXISTS_FLAG) == 0); VSILFILE *f2 = VSIFOpenL(path.c_str(), "w"); if (f2) diff --git a/frmts/wms/gdalwmscache.cpp b/frmts/wms/gdalwmscache.cpp index f9b7bcedc3e2..3d3d9aca7882 100644 --- a/frmts/wms/gdalwmscache.cpp +++ b/frmts/wms/gdalwmscache.cpp @@ -76,7 +76,7 @@ class GDALWMSFileCache : public GDALWMSCacheImpl { // Warns if it fails to write, but returns success CPLString soFilePath = GetFilePath(pszKey); - MakeDirs(CPLGetDirname(soFilePath)); + MakeDirs(CPLGetDirnameSafe(soFilePath).c_str()); if (CPLCopyFile(soFilePath, osFileName) == CE_None) return CE_None; // Warn if it fails after folder creation @@ -120,10 +120,10 @@ class GDALWMSFileCache : public GDALWMSCacheImpl time_t nTime = time(nullptr); while (papszList[counter] != nullptr) { - const char *pszPath = - CPLFormFilename(m_soPath, papszList[counter], nullptr); + const std::string osPath = + CPLFormFilenameSafe(m_soPath, papszList[counter], nullptr); VSIStatBufL sStatBuf; - if (VSIStatL(pszPath, &sStatBuf) == 0) + if (VSIStatL(osPath.c_str(), &sStatBuf) == 0) { if (!VSI_ISDIR(sStatBuf.st_mode)) { @@ -145,9 +145,9 @@ class GDALWMSFileCache : public GDALWMSCacheImpl static_cast(toDelete.size())); for (size_t i = 0; i < toDelete.size(); ++i) { - const char *pszPath = - CPLFormFilename(m_soPath, papszList[toDelete[i]], nullptr); - VSIUnlink(pszPath); + const std::string osPath = CPLFormFilenameSafe( + m_soPath, papszList[toDelete[i]], nullptr); + VSIUnlink(osPath.c_str()); } } @@ -182,8 +182,7 @@ class GDALWMSFileCache : public GDALWMSCacheImpl return; } // Recursive makedirs, ignoring errors - const char *pszDirPath = CPLGetDirname(pszPath); - MakeDirs(pszDirPath); + MakeDirs(CPLGetDirnameSafe(pszPath).c_str()); VSIMkdir(pszPath, 0744); } @@ -234,7 +233,7 @@ CPLErr GDALWMSCache::Initialize(const char *pszUrl, CPLXMLNode *pConfig) NullifyIfEmpty(CPLGetConfigOption("XDG_CACHE_HOME", nullptr))) { m_osCachePath = - CPLFormFilename(pszXDG_CACHE_HOME, "gdalwmscache", nullptr); + CPLFormFilenameSafe(pszXDG_CACHE_HOME, "gdalwmscache", nullptr); } else { @@ -247,9 +246,9 @@ CPLErr GDALWMSCache::Initialize(const char *pszUrl, CPLXMLNode *pConfig) #endif if (pszHome) { - m_osCachePath = - CPLFormFilename(CPLFormFilename(pszHome, ".cache", nullptr), - "gdalwmscache", nullptr); + m_osCachePath = CPLFormFilenameSafe( + CPLFormFilenameSafe(pszHome, ".cache", nullptr).c_str(), + "gdalwmscache", nullptr); } else { @@ -273,13 +272,13 @@ CPLErr GDALWMSCache::Initialize(const char *pszUrl, CPLXMLNode *pConfig) if (pszUsername) { - m_osCachePath = CPLFormFilename( + m_osCachePath = CPLFormFilenameSafe( pszDir, CPLSPrintf("gdalwmscache_%s", pszUsername), nullptr); } else { - m_osCachePath = CPLFormFilename( + m_osCachePath = CPLFormFilenameSafe( pszDir, CPLSPrintf("gdalwmscache_%s", CPLMD5String(pszUrl ? pszUrl : "")), @@ -291,7 +290,7 @@ CPLErr GDALWMSCache::Initialize(const char *pszUrl, CPLXMLNode *pConfig) // Separate folder for each unique dataset url if (CPLTestBool(CPLGetXMLValue(pConfig, "Unique", "True"))) { - m_osCachePath = CPLFormFilename( + m_osCachePath = CPLFormFilenameSafe( m_osCachePath, CPLMD5String(pszUrl ? pszUrl : ""), nullptr); } CPLDebug("WMS", "Using %s for cache", m_osCachePath.c_str()); diff --git a/frmts/xpm/xpmdataset.cpp b/frmts/xpm/xpmdataset.cpp index 55168688f4d0..2623ce75eed1 100644 --- a/frmts/xpm/xpmdataset.cpp +++ b/frmts/xpm/xpmdataset.cpp @@ -332,7 +332,7 @@ static GDALDataset *XPMCreateCopy(const char *pszFilename, GDALDataset *poSrcDS, /* -------------------------------------------------------------------- */ bool bOK = VSIFPrintfL(fpPBM, "/* XPM */\n") >= 0; bOK &= VSIFPrintfL(fpPBM, "static char *%s[] = {\n", - CPLGetBasename(pszFilename)) >= 0; + CPLGetBasenameSafe(pszFilename).c_str()) >= 0; bOK &= VSIFPrintfL(fpPBM, "/* width height num_colors chars_per_pixel */\n") >= 0; diff --git a/frmts/xyz/xyzdataset.cpp b/frmts/xyz/xyzdataset.cpp index c6df2d7a7120..aaa64b03c7e3 100644 --- a/frmts/xyz/xyzdataset.cpp +++ b/frmts/xyz/xyzdataset.cpp @@ -707,7 +707,7 @@ int XYZDataset::IdentifyEx(GDALOpenInfo *poOpenInfo, int &bHasHeaderLine, nCommentLineCount = 0; CPLString osFilename(poOpenInfo->pszFilename); - if (EQUAL(CPLGetExtension(osFilename), "GRA") && + if (EQUAL(CPLGetExtensionSafe(osFilename).c_str(), "GRA") && !poOpenInfo->IsSingleAllowedDriver("XYZ")) { // IGNFHeightASCIIGRID .GRA diff --git a/frmts/zarr/zarr_array.cpp b/frmts/zarr/zarr_array.cpp index 5f038d8945db..f2e8ec04d352 100644 --- a/frmts/zarr/zarr_array.cpp +++ b/frmts/zarr/zarr_array.cpp @@ -2633,10 +2633,11 @@ void ZarrArray::ParentRenamed(const std::string &osNewParentFullName) // The parent necessarily exist, since it notified us CPLAssert(poParent); - m_osFilename = - CPLFormFilename(CPLFormFilename(poParent->GetDirectoryName().c_str(), - m_osName.c_str(), nullptr), - CPLGetFilename(m_osFilename.c_str()), nullptr); + m_osFilename = CPLFormFilenameSafe( + CPLFormFilenameSafe(poParent->GetDirectoryName().c_str(), + m_osName.c_str(), nullptr) + .c_str(), + CPLGetFilename(m_osFilename.c_str()), nullptr); } /************************************************************************/ @@ -2668,10 +2669,10 @@ bool ZarrArray::Rename(const std::string &osNewName) } const std::string osRootDirectoryName( - CPLGetDirname(CPLGetDirname(m_osFilename.c_str()))); - const std::string osOldDirectoryName = - CPLFormFilename(osRootDirectoryName.c_str(), m_osName.c_str(), nullptr); - const std::string osNewDirectoryName = CPLFormFilename( + CPLGetDirnameSafe(CPLGetDirnameSafe(m_osFilename.c_str()).c_str())); + const std::string osOldDirectoryName = CPLFormFilenameSafe( + osRootDirectoryName.c_str(), m_osName.c_str(), nullptr); + const std::string osNewDirectoryName = CPLFormFilenameSafe( osRootDirectoryName.c_str(), osNewName.c_str(), nullptr); if (VSIRename(osOldDirectoryName.c_str(), osNewDirectoryName.c_str()) != 0) @@ -2685,8 +2686,8 @@ bool ZarrArray::Rename(const std::string &osNewName) osNewDirectoryName); m_osFilename = - CPLFormFilename(osNewDirectoryName.c_str(), - CPLGetFilename(m_osFilename.c_str()), nullptr); + CPLFormFilenameSafe(osNewDirectoryName.c_str(), + CPLGetFilename(m_osFilename.c_str()), nullptr); if (poParent) { diff --git a/frmts/zarr/zarr_group.cpp b/frmts/zarr/zarr_group.cpp index 18dfec79bf26..73acbf0c7912 100644 --- a/frmts/zarr/zarr_group.cpp +++ b/frmts/zarr/zarr_group.cpp @@ -107,7 +107,7 @@ bool ZarrGroupBase::DeleteGroup(const std::string &osName, } const std::string osSubDirName = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); if (VSIRmdirRecursive(osSubDirName.c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot delete %s", @@ -252,7 +252,7 @@ bool ZarrGroupBase::DeleteMDArray(const std::string &osName, } const std::string osSubDirName = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); if (VSIRmdirRecursive(osSubDirName.c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot delete %s", @@ -527,8 +527,8 @@ void ZarrGroupBase::ParentRenamed(const std::string &osNewParentFullName) // The parent necessarily exist, since it notified us CPLAssert(pParent); - m_osDirectoryName = CPLFormFilename(pParent->m_osDirectoryName.c_str(), - m_osName.c_str(), nullptr); + m_osDirectoryName = CPLFormFilenameSafe(pParent->m_osDirectoryName.c_str(), + m_osName.c_str(), nullptr); GDALGroup::ParentRenamed(osNewParentFullName); } diff --git a/frmts/zarr/zarr_sharedresource.cpp b/frmts/zarr/zarr_sharedresource.cpp index 76bed033c08f..414c3353b86b 100644 --- a/frmts/zarr/zarr_sharedresource.cpp +++ b/frmts/zarr/zarr_sharedresource.cpp @@ -31,7 +31,7 @@ ZarrSharedResource::ZarrSharedResource(const std::string &osRootDirectoryName, m_osRootDirectoryName.pop_back(); } m_poPAM = std::make_shared( - CPLFormFilename(m_osRootDirectoryName.c_str(), "pam", nullptr)); + CPLFormFilenameSafe(m_osRootDirectoryName.c_str(), "pam", nullptr)); } /************************************************************************/ @@ -56,8 +56,8 @@ ZarrSharedResource::~ZarrSharedResource() { CPLJSONDocument oDoc; oDoc.SetRoot(m_oObj); - oDoc.Save(CPLFormFilename(m_osRootDirectoryName.c_str(), ".zmetadata", - nullptr)); + oDoc.Save(CPLFormFilenameSafe(m_osRootDirectoryName.c_str(), + ".zmetadata", nullptr)); } } @@ -72,8 +72,8 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() poRG->SetUpdatable(m_bUpdatable); poRG->SetDirectoryName(m_osRootDirectoryName); - const std::string osZarrayFilename( - CPLFormFilename(m_osRootDirectoryName.c_str(), ".zarray", nullptr)); + const std::string osZarrayFilename(CPLFormFilenameSafe( + m_osRootDirectoryName.c_str(), ".zarray", nullptr)); VSIStatBufL sStat; if (VSIStatL(osZarrayFilename.c_str(), &sStat) == 0) { @@ -85,9 +85,9 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() { // If opening a NCZarr array, initialize its group from NCZarr // metadata. - const std::string osGroupFilename(CPLFormFilename( - CPLGetDirname(m_osRootDirectoryName.c_str()), ".zgroup", - nullptr)); + const std::string osGroupFilename(CPLFormFilenameSafe( + CPLGetDirnameSafe(m_osRootDirectoryName.c_str()).c_str(), + ".zgroup", nullptr)); if (VSIStatL(osGroupFilename.c_str(), &sStat) == 0) { CPLJSONDocument oDocGroup; @@ -99,7 +99,7 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() } } const std::string osArrayName( - CPLGetBasename(m_osRootDirectoryName.c_str())); + CPLGetBasenameSafe(m_osRootDirectoryName.c_str())); if (!poRG->LoadArray(osArrayName, osZarrayFilename, oRoot, false, CPLJSONObject())) return nullptr; @@ -107,7 +107,7 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() return poRG; } - const std::string osZmetadataFilename(CPLFormFilename( + const std::string osZmetadataFilename(CPLFormFilenameSafe( m_osRootDirectoryName.c_str(), ".zmetadata", nullptr)); if (CPLTestBool(CSLFetchNameValueDef(GetOpenOptions(), "USE_ZMETADATA", "YES")) && @@ -127,8 +127,8 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() return poRG; } - const std::string osGroupFilename( - CPLFormFilename(m_osRootDirectoryName.c_str(), ".zgroup", nullptr)); + const std::string osGroupFilename(CPLFormFilenameSafe( + m_osRootDirectoryName.c_str(), ".zgroup", nullptr)); if (VSIStatL(osGroupFilename.c_str(), &sStat) == 0) { CPLJSONDocument oDoc; @@ -146,8 +146,8 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() m_osRootDirectoryName); poRG_V3->SetUpdatable(m_bUpdatable); - const std::string osZarrJsonFilename( - CPLFormFilename(m_osRootDirectoryName.c_str(), "zarr.json", nullptr)); + const std::string osZarrJsonFilename(CPLFormFilenameSafe( + m_osRootDirectoryName.c_str(), "zarr.json", nullptr)); VSIStatBufL sStat; if (VSIStatL(osZarrJsonFilename.c_str(), &sStat) == 0) { @@ -165,7 +165,7 @@ std::shared_ptr ZarrSharedResource::OpenRootGroup() if (osNodeType == "array") { const std::string osArrayName( - CPLGetBasename(m_osRootDirectoryName.c_str())); + CPLGetBasenameSafe(m_osRootDirectoryName.c_str())); poRG_V3->SetExplored(); if (!poRG_V3->LoadArray(osArrayName, osZarrJsonFilename, oRoot)) return nullptr; diff --git a/frmts/zarr/zarr_v2_array.cpp b/frmts/zarr/zarr_v2_array.cpp index 42042344897e..ee5f1c161c4d 100644 --- a/frmts/zarr/zarr_v2_array.cpp +++ b/frmts/zarr/zarr_v2_array.cpp @@ -127,8 +127,9 @@ void ZarrV2Array::Flush() CPLJSONDocument oDoc; oDoc.SetRoot(oAttrs); - const std::string osAttrFilename = CPLFormFilename( - CPLGetDirname(m_osFilename.c_str()), ".zattrs", nullptr); + const std::string osAttrFilename = + CPLFormFilenameSafe(CPLGetDirnameSafe(m_osFilename.c_str()).c_str(), + ".zattrs", nullptr); oDoc.Save(osAttrFilename); m_poSharedResource->SetZMetadataItem(osAttrFilename, oAttrs); } @@ -872,7 +873,7 @@ bool ZarrV2Array::FlushDirtyTile() const if (m_osDimSeparator == "/") { - std::string osDir = CPLGetDirname(osFilename.c_str()); + std::string osDir = CPLGetDirnameSafe(osFilename.c_str()); VSIStatBufL sStat; if (VSIStatL(osDir.c_str(), &sStat) != 0) { @@ -987,8 +988,8 @@ std::string ZarrV2Array::BuildTileFilename(const uint64_t *tileIndices) const } } - return CPLFormFilename(CPLGetDirname(m_osFilename.c_str()), - osFilename.c_str(), nullptr); + return CPLFormFilenameSafe(CPLGetDirnameSafe(m_osFilename.c_str()).c_str(), + osFilename.c_str(), nullptr); } /************************************************************************/ @@ -997,7 +998,7 @@ std::string ZarrV2Array::BuildTileFilename(const uint64_t *tileIndices) const std::string ZarrV2Array::GetDataDirectory() const { - return std::string(CPLGetDirname(m_osFilename.c_str())); + return CPLGetDirnameSafe(m_osFilename.c_str()); } /************************************************************************/ @@ -1328,8 +1329,9 @@ ZarrV2Group::LoadArray(const std::string &osArrayName, if (!bLoadedFromZMetadata) { CPLJSONDocument oDoc; - const std::string osZattrsFilename(CPLFormFilename( - CPLGetDirname(osZarrayFilename.c_str()), ".zattrs", nullptr)); + const std::string osZattrsFilename(CPLFormFilenameSafe( + CPLGetDirnameSafe(osZarrayFilename.c_str()).c_str(), ".zattrs", + nullptr)); CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler); if (oDoc.Load(osZattrsFilename)) { @@ -1418,10 +1420,11 @@ ZarrV2Group::LoadArray(const std::string &osArrayName, std::string osDirName = m_osDirectoryName; while (true) { - const std::string osArrayFilenameDim = - CPLFormFilename(CPLFormFilename(osDirName.c_str(), - osDimName.c_str(), nullptr), - ".zarray", nullptr); + const std::string osArrayFilenameDim = CPLFormFilenameSafe( + CPLFormFilenameSafe(osDirName.c_str(), osDimName.c_str(), + nullptr) + .c_str(), + ".zarray", nullptr); VSIStatBufL sStat; if (VSIStatL(osArrayFilenameDim.c_str(), &sStat) == 0) { @@ -1437,7 +1440,7 @@ ZarrV2Group::LoadArray(const std::string &osArrayName, // Recurse to upper level for datasets such as // /vsis3/hrrrzarr/sfc/20210809/20210809_00z_anl.zarr/0.1_sigma_level/HAIL_max_fcst/0.1_sigma_level/HAIL_max_fcst const std::string osDirNameNew = - CPLGetPath(osDirName.c_str()); + CPLGetPathSafe(osDirName.c_str()); if (!osDirNameNew.empty() && osDirNameNew != osDirName) { osDirName = osDirNameNew; @@ -1895,9 +1898,10 @@ ZarrV2Group::LoadArray(const std::string &osArrayName, const std::string gridMappingName = gridMapping.ToString(); if (m_oMapMDArrays.find(gridMappingName) == m_oMapMDArrays.end()) { - const std::string osArrayFilenameDim = CPLFormFilename( - CPLFormFilename(m_osDirectoryName.c_str(), - gridMappingName.c_str(), nullptr), + const std::string osArrayFilenameDim = CPLFormFilenameSafe( + CPLFormFilenameSafe(m_osDirectoryName.c_str(), + gridMappingName.c_str(), nullptr) + .c_str(), ".zarray", nullptr); VSIStatBufL sStat; if (VSIStatL(osArrayFilenameDim.c_str(), &sStat) == 0) diff --git a/frmts/zarr/zarr_v2_group.cpp b/frmts/zarr/zarr_v2_group.cpp index bef685a6bfb4..5364cad43fd6 100644 --- a/frmts/zarr/zarr_v2_group.cpp +++ b/frmts/zarr/zarr_v2_group.cpp @@ -45,7 +45,7 @@ ZarrV2Group::~ZarrV2Group() CPLJSONDocument oDoc; oDoc.SetRoot(m_oAttrGroup.Serialize()); const std::string osAttrFilename = - CPLFormFilename(m_osDirectoryName.c_str(), ".zattrs", nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), ".zattrs", nullptr); oDoc.Save(osAttrFilename); m_poSharedResource->SetZMetadataItem(osAttrFilename, oDoc.GetRoot()); } @@ -84,11 +84,11 @@ void ZarrV2Group::ExploreDirectory() const // https://github.com/OSGeo/gdal/issues/8192 aosFiles[i][strlen(aosFiles[i]) - 1] != '/') { - const std::string osSubDir = CPLFormFilename( + const std::string osSubDir = CPLFormFilenameSafe( m_osDirectoryName.c_str(), aosFiles[i], nullptr); VSIStatBufL sStat; std::string osFilename = - CPLFormFilename(osSubDir.c_str(), ".zarray", nullptr); + CPLFormFilenameSafe(osSubDir.c_str(), ".zarray", nullptr); if (VSIStatL(osFilename.c_str(), &sStat) == 0) { if (std::find(m_aosArrays.begin(), m_aosArrays.end(), @@ -100,7 +100,7 @@ void ZarrV2Group::ExploreDirectory() const else { osFilename = - CPLFormFilename(osSubDir.c_str(), ".zgroup", nullptr); + CPLFormFilenameSafe(osSubDir.c_str(), ".zgroup", nullptr); if (VSIStatL(osFilename.c_str(), &sStat) == 0) m_aosGroups.emplace_back(aosFiles[i]); } @@ -124,11 +124,11 @@ std::shared_ptr ZarrV2Group::OpenZarrArray(const std::string &osName, if (!m_bReadFromZMetadata && !m_osDirectoryName.empty()) { - const std::string osSubDir = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + const std::string osSubDir = CPLFormFilenameSafe( + m_osDirectoryName.c_str(), osName.c_str(), nullptr); VSIStatBufL sStat; const std::string osZarrayFilename = - CPLFormFilename(osSubDir.c_str(), ".zarray", nullptr); + CPLFormFilenameSafe(osSubDir.c_str(), ".zarray", nullptr); if (VSIStatL(osZarrayFilename.c_str(), &sStat) == 0) { CPLJSONDocument oDoc; @@ -159,11 +159,11 @@ ZarrV2Group::OpenZarrGroup(const std::string &osName, CSLConstList) const if (!m_bReadFromZMetadata && !m_osDirectoryName.empty()) { - const std::string osSubDir = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + const std::string osSubDir = CPLFormFilenameSafe( + m_osDirectoryName.c_str(), osName.c_str(), nullptr); VSIStatBufL sStat; const std::string osZgroupFilename = - CPLFormFilename(osSubDir.c_str(), ".zgroup", nullptr); + CPLFormFilenameSafe(osSubDir.c_str(), ".zgroup", nullptr); if (VSIStatL(osZgroupFilename.c_str(), &sStat) == 0) { CPLJSONDocument oDoc; @@ -202,7 +202,7 @@ void ZarrV2Group::LoadAttributes() const CPLJSONDocument oDoc; const std::string osZattrsFilename( - CPLFormFilename(m_osDirectoryName.c_str(), ".zattrs", nullptr)); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), ".zattrs", nullptr)); CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler); if (!oDoc.Load(osZattrsFilename)) return; @@ -237,8 +237,8 @@ ZarrV2Group::GetOrCreateSubGroup(const std::string &osSubGroupFullname) poSubGroup->m_poParent = std::dynamic_pointer_cast( poBelongingGroup->m_pSelf.lock()); poSubGroup->SetDirectoryName( - CPLFormFilename(poBelongingGroup->m_osDirectoryName.c_str(), - poSubGroup->GetName().c_str(), nullptr)); + CPLFormFilenameSafe(poBelongingGroup->m_osDirectoryName.c_str(), + poSubGroup->GetName().c_str(), nullptr)); poSubGroup->m_bDirectoryExplored = true; poSubGroup->m_bAttributesLoaded = true; poSubGroup->m_bReadFromZMetadata = true; @@ -310,9 +310,10 @@ void ZarrV2Group::InitFromZMetadata(const CPLJSONObject &obj) nLastSlashPos == std::string::npos ? osArrayFullname : osArrayFullname.substr(nLastSlashPos + 1); - const std::string osZarrayFilename = CPLFormFilename( - CPLFormFilename(poBelongingGroup->m_osDirectoryName.c_str(), - osArrayName.c_str(), nullptr), + const std::string osZarrayFilename = CPLFormFilenameSafe( + CPLFormFilenameSafe(poBelongingGroup->m_osDirectoryName.c_str(), + osArrayName.c_str(), nullptr) + .c_str(), ".zarray", nullptr); poBelongingGroup->LoadArray(osArrayName, osZarrayFilename, oArray, true, oAttributes); @@ -415,8 +416,9 @@ bool ZarrV2Group::InitFromZGroup(const CPLJSONObject &obj) if (!obj["_NCZARR_SUPERBLOCK"].IsValid() && m_poParent.lock() == nullptr) { - const std::string osParentGroupFilename(CPLFormFilename( - CPLGetPath(m_osDirectoryName.c_str()), ".zgroup", nullptr)); + const std::string osParentGroupFilename(CPLFormFilenameSafe( + CPLGetPathSafe(m_osDirectoryName.c_str()).c_str(), ".zgroup", + nullptr)); VSIStatBufL sStat; if (VSIStatL(osParentGroupFilename.c_str(), &sStat) == 0) { @@ -427,7 +429,7 @@ bool ZarrV2Group::InitFromZGroup(const CPLJSONObject &obj) m_poSharedResource, std::string(), std::string()); poParent->m_bDirectoryExplored = true; poParent->SetDirectoryName( - CPLGetPath(m_osDirectoryName.c_str())); + CPLGetPathSafe(m_osDirectoryName.c_str())); poParent->InitFromZGroup(oDoc.GetRoot()); m_poParentStrongRef = poParent; m_poParent = poParent; @@ -551,7 +553,7 @@ std::shared_ptr ZarrV2Group::CreateOnDisk( } const std::string osZgroupFilename( - CPLFormFilename(osDirectoryName.c_str(), ".zgroup", nullptr)); + CPLFormFilenameSafe(osDirectoryName.c_str(), ".zgroup", nullptr)); VSILFILE *fp = VSIFOpenL(osZgroupFilename.c_str(), "wb"); if (!fp) { @@ -608,7 +610,7 @@ ZarrV2Group::CreateGroup(const std::string &osName, } const std::string osDirectoryName = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); auto poGroup = CreateOnDisk(m_poSharedResource, GetFullName(), osName, osDirectoryName); if (!poGroup) @@ -1058,7 +1060,7 @@ std::shared_ptr ZarrV2Group::CreateMDArray( } const std::string osZarrayDirectory = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); if (VSIMkdir(osZarrayDirectory.c_str(), 0755) != 0) { VSIStatBufL sStat; @@ -1093,7 +1095,7 @@ std::shared_ptr ZarrV2Group::CreateMDArray( if (!poArray) return nullptr; const std::string osZarrayFilename = - CPLFormFilename(osZarrayDirectory.c_str(), ".zarray", nullptr); + CPLFormFilenameSafe(osZarrayDirectory.c_str(), ".zarray", nullptr); poArray->SetNew(true); poArray->SetFilename(osZarrayFilename); poArray->SetDimSeparator(pszDimSeparator); diff --git a/frmts/zarr/zarr_v3_array.cpp b/frmts/zarr/zarr_v3_array.cpp index c81543a8255e..e3e54104f3c4 100644 --- a/frmts/zarr/zarr_v3_array.cpp +++ b/frmts/zarr/zarr_v3_array.cpp @@ -768,7 +768,7 @@ bool ZarrV3Array::FlushDirtyTile() const if (m_osDimSeparator == "/") { - std::string osDir = CPLGetDirname(osFilename.c_str()); + std::string osDir = CPLGetDirnameSafe(osFilename.c_str()); VSIStatBufL sStat; if (VSIStatL(osDir.c_str(), &sStat) != 0) { @@ -815,12 +815,13 @@ std::string ZarrV3Array::BuildTileFilename(const uint64_t *tileIndices) const { if (m_aoDims.empty()) { - return CPLFormFilename(CPLGetDirname(m_osFilename.c_str()), - m_bV2ChunkKeyEncoding ? "0" : "c", nullptr); + return CPLFormFilenameSafe( + CPLGetDirnameSafe(m_osFilename.c_str()).c_str(), + m_bV2ChunkKeyEncoding ? "0" : "c", nullptr); } else { - std::string osFilename(CPLGetDirname(m_osFilename.c_str())); + std::string osFilename(CPLGetDirnameSafe(m_osFilename.c_str())); osFilename += '/'; if (!m_bV2ChunkKeyEncoding) { @@ -842,7 +843,7 @@ std::string ZarrV3Array::BuildTileFilename(const uint64_t *tileIndices) const std::string ZarrV3Array::GetDataDirectory() const { - return std::string(CPLGetDirname(m_osFilename.c_str())); + return std::string(CPLGetDirnameSafe(m_osFilename.c_str())); } /************************************************************************/ @@ -1239,10 +1240,11 @@ ZarrV3Group::LoadArray(const std::string &osArrayName, std::string osDirName = m_osDirectoryName; while (true) { - const std::string osArrayFilenameDim = - CPLFormFilename(CPLFormFilename(osDirName.c_str(), - osDimName.c_str(), nullptr), - "zarr.json", nullptr); + const std::string osArrayFilenameDim = CPLFormFilenameSafe( + CPLFormFilenameSafe(osDirName.c_str(), osDimName.c_str(), + nullptr) + .c_str(), + "zarr.json", nullptr); VSIStatBufL sStat; if (VSIStatL(osArrayFilenameDim.c_str(), &sStat) == 0) { @@ -1258,7 +1260,7 @@ ZarrV3Group::LoadArray(const std::string &osArrayName, // Recurse to upper level for datasets such as // /vsis3/hrrrzarr/sfc/20210809/20210809_00z_anl.zarr/0.1_sigma_level/HAIL_max_fcst/0.1_sigma_level/HAIL_max_fcst const std::string osDirNameNew = - CPLGetPath(osDirName.c_str()); + CPLGetPathSafe(osDirName.c_str()); if (!osDirNameNew.empty() && osDirNameNew != osDirName) { osDirName = osDirNameNew; diff --git a/frmts/zarr/zarr_v3_group.cpp b/frmts/zarr/zarr_v3_group.cpp index 629138915b22..132e8dd839be 100644 --- a/frmts/zarr/zarr_v3_group.cpp +++ b/frmts/zarr/zarr_v3_group.cpp @@ -48,9 +48,9 @@ std::shared_ptr ZarrV3Group::OpenZarrArray(const std::string &osName, return oIter->second; const std::string osSubDir = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); const std::string osZarrayFilename = - CPLFormFilename(osSubDir.c_str(), "zarr.json", nullptr); + CPLFormFilenameSafe(osSubDir.c_str(), "zarr.json", nullptr); VSIStatBufL sStat; if (VSIStatL(osZarrayFilename.c_str(), &sStat) == 0) @@ -76,7 +76,7 @@ void ZarrV3Group::LoadAttributes() const m_bAttributesLoaded = true; const std::string osFilename = - CPLFormFilename(m_osDirectoryName.c_str(), "zarr.json", nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), "zarr.json", nullptr); VSIStatBufL sStat; if (VSIStatL(osFilename.c_str(), &sStat) == 0) @@ -106,11 +106,11 @@ void ZarrV3Group::ExploreDirectory() const { if (VSI_ISDIR(psEntry->nMode)) { - const std::string osSubDir = CPLFormFilename( + const std::string osSubDir = CPLFormFilenameSafe( m_osDirectoryName.c_str(), psEntry->pszName, nullptr); VSIStatBufL sStat; - std::string osZarrJsonFilename = - CPLFormFilename(osSubDir.c_str(), "zarr.json", nullptr); + const std::string osZarrJsonFilename = + CPLFormFilenameSafe(osSubDir.c_str(), "zarr.json", nullptr); if (VSIStatL(osZarrJsonFilename.c_str(), &sStat) == 0) { CPLJSONDocument oDoc; @@ -188,8 +188,8 @@ ZarrV3Group::~ZarrV3Group() oRoot.Add("zarr_format", 3); oRoot.Add("node_type", "group"); oRoot.Add("attributes", m_oAttrGroup.Serialize()); - const std::string osZarrJsonFilename = - CPLFormFilename(m_osDirectoryName.c_str(), "zarr.json", nullptr); + const std::string osZarrJsonFilename = CPLFormFilenameSafe( + m_osDirectoryName.c_str(), "zarr.json", nullptr); oDoc.Save(osZarrJsonFilename); } } @@ -209,9 +209,9 @@ ZarrV3Group::OpenZarrGroup(const std::string &osName, CSLConstList) const return oIter->second; const std::string osSubDir = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); const std::string osSubDirZarrJsonFilename = - CPLFormFilename(osSubDir.c_str(), "zarr.json", nullptr); + CPLFormFilenameSafe(osSubDir.c_str(), "zarr.json", nullptr); VSIStatBufL sStat; // Explicit group @@ -286,7 +286,7 @@ std::shared_ptr ZarrV3Group::CreateOnDisk( } const std::string osZarrJsonFilename( - CPLFormFilename(osDirectoryName.c_str(), "zarr.json", nullptr)); + CPLFormFilenameSafe(osDirectoryName.c_str(), "zarr.json", nullptr)); VSILFILE *fp = VSIFOpenL(osZarrJsonFilename.c_str(), "wb"); if (!fp) { @@ -342,7 +342,7 @@ ZarrV3Group::CreateGroup(const std::string &osName, } const std::string osDirectoryName = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); auto poGroup = CreateOnDisk(m_poSharedResource, GetFullName(), osName, osDirectoryName); if (!poGroup) @@ -537,7 +537,7 @@ std::shared_ptr ZarrV3Group::CreateMDArray( CSLFetchNameValueDef(papszOptions, "DIM_SEPARATOR", "/"); const std::string osArrayDirectory = - CPLFormFilename(m_osDirectoryName.c_str(), osName.c_str(), nullptr); + CPLFormFilenameSafe(m_osDirectoryName.c_str(), osName.c_str(), nullptr); if (VSIMkdir(osArrayDirectory.c_str(), 0755) != 0) { VSIStatBufL sStat; @@ -672,8 +672,8 @@ std::shared_ptr ZarrV3Group::CreateMDArray( if (!poArray) return nullptr; poArray->SetNew(true); - std::string osFilename = - CPLFormFilename(osArrayDirectory.c_str(), "zarr.json", nullptr); + const std::string osFilename = + CPLFormFilenameSafe(osArrayDirectory.c_str(), "zarr.json", nullptr); poArray->SetFilename(osFilename); poArray->SetDimSeparator(pszDimSeparator); poArray->SetDtype(dtype); diff --git a/frmts/zarr/zarrdriver.cpp b/frmts/zarr/zarrdriver.cpp index 08c1adbc86c1..87bff6e1ac93 100644 --- a/frmts/zarr/zarrdriver.cpp +++ b/frmts/zarr/zarrdriver.cpp @@ -1089,7 +1089,8 @@ GDALDataset *ZarrDataset::Create(const char *pszName, int nXSize, int nYSize, if (bAppendSubDS) { - VSIRmdir(CPLFormFilename(pszName, pszArrayName, nullptr)); + VSIRmdir( + CPLFormFilenameSafe(pszName, pszArrayName, nullptr).c_str()); } else { @@ -1104,18 +1105,22 @@ GDALDataset *ZarrDataset::Create(const char *pszName, int nXSize, int nYSize, { if (pszArrayName && strcmp(pszFile, pszArrayName) == 0) { - VSIRmdir(CPLFormFilename(pszName, pszFile, nullptr)); + VSIRmdir(CPLFormFilenameSafe(pszName, pszFile, nullptr) + .c_str()); } else if (!pszArrayName && - strcmp(pszFile, CPLGetBasename(pszName)) == 0) + strcmp(pszFile, + CPLGetBasenameSafe(pszName).c_str()) == 0) { - VSIRmdir(CPLFormFilename(pszName, pszFile, nullptr)); + VSIRmdir(CPLFormFilenameSafe(pszName, pszFile, nullptr) + .c_str()); } else if (strcmp(pszFile, ".zgroup") == 0 || strcmp(pszFile, ".zmetadata") == 0 || strcmp(pszFile, "zarr.json") == 0) { - VSIUnlink(CPLFormFilename(pszName, pszFile, nullptr)); + VSIUnlink(CPLFormFilenameSafe(pszName, pszFile, nullptr) + .c_str()); } } VSIRmdir(pszName); @@ -1175,8 +1180,8 @@ GDALDataset *ZarrDataset::Create(const char *pszName, int nXSize, int nYSize, nBandsIn) : nullptr); - const char *pszNonNullArrayName = - pszArrayName ? pszArrayName : CPLGetBasename(pszName); + const std::string osNonNullArrayName = + pszArrayName ? std::string(pszArrayName) : CPLGetBasenameSafe(pszName); if (poBandDim) { const std::vector> apoDims( @@ -1187,8 +1192,8 @@ GDALDataset *ZarrDataset::Create(const char *pszName, int nXSize, int nYSize, : std::vector>{ poDS->m_poDimY, poDS->m_poDimX, poBandDim}); poDS->m_poSingleArray = poRG->CreateMDArray( - pszNonNullArrayName, apoDims, GDALExtendedDataType::Create(eType), - papszOptions); + osNonNullArrayName.c_str(), apoDims, + GDALExtendedDataType::Create(eType), papszOptions); if (!poDS->m_poSingleArray) { CleanupCreatedFiles(); @@ -1210,7 +1215,7 @@ GDALDataset *ZarrDataset::Create(const char *pszName, int nXSize, int nYSize, for (int i = 0; i < nBandsIn; i++) { auto poArray = poRG->CreateMDArray( - nBandsIn == 1 ? pszNonNullArrayName + nBandsIn == 1 ? osNonNullArrayName.c_str() : pszArrayName ? CPLSPrintf("%s_band%d", pszArrayName, i + 1) : CPLSPrintf("Band%d", i + 1), apoDims, GDALExtendedDataType::Create(eType), papszOptions); diff --git a/frmts/zarr/zarrdrivercore.cpp b/frmts/zarr/zarrdrivercore.cpp index 26edfd935ca5..81ddbca4f8ab 100644 --- a/frmts/zarr/zarrdrivercore.cpp +++ b/frmts/zarr/zarrdrivercore.cpp @@ -19,18 +19,19 @@ static bool CheckExistenceOfOneZarrFile(const char *pszFilename) { - CPLString osMDFilename = CPLFormFilename(pszFilename, ".zarray", nullptr); + CPLString osMDFilename = + CPLFormFilenameSafe(pszFilename, ".zarray", nullptr); VSIStatBufL sStat; if (VSIStatL(osMDFilename, &sStat) == 0) return true; - osMDFilename = CPLFormFilename(pszFilename, ".zgroup", nullptr); + osMDFilename = CPLFormFilenameSafe(pszFilename, ".zgroup", nullptr); if (VSIStatL(osMDFilename, &sStat) == 0) return true; // Zarr V3 - osMDFilename = CPLFormFilename(pszFilename, "zarr.json", nullptr); + osMDFilename = CPLFormFilenameSafe(pszFilename, "zarr.json", nullptr); if (VSIStatL(osMDFilename, &sStat) == 0) return true; diff --git a/fuzzers/filename_fuzzer.cpp b/fuzzers/filename_fuzzer.cpp index f7300358c7b7..40f34da106c9 100644 --- a/fuzzers/filename_fuzzer.cpp +++ b/fuzzers/filename_fuzzer.cpp @@ -43,7 +43,7 @@ int LLVMFuzzerInitialize(int * /*argc*/, char ***argv) const char *exe_path = (*argv)[0]; if (CPLGetConfigOption("GDAL_DATA", nullptr) == nullptr) { - CPLSetConfigOption("GDAL_DATA", CPLGetPath(exe_path)); + CPLSetConfigOption("GDAL_DATA", CPLGetPathSafe(exe_path).c_str()); } CPLSetConfigOption("CPL_TMPDIR", "/tmp"); CPLSetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", "YES"); diff --git a/fuzzers/gdal_fuzzer.cpp b/fuzzers/gdal_fuzzer.cpp index ef66a37c8c17..6e9b70689ca1 100644 --- a/fuzzers/gdal_fuzzer.cpp +++ b/fuzzers/gdal_fuzzer.cpp @@ -68,7 +68,7 @@ int LLVMFuzzerInitialize(int * /*argc*/, char ***argv) const char *exe_path = (*argv)[0]; if (CPLGetConfigOption("GDAL_DATA", nullptr) == nullptr) { - CPLSetConfigOption("GDAL_DATA", CPLGetPath(exe_path)); + CPLSetConfigOption("GDAL_DATA", CPLGetPathSafe(exe_path).c_str()); } CPLSetConfigOption("CPL_TMPDIR", "/tmp"); CPLSetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", "YES"); diff --git a/fuzzers/gdal_translate_fuzzer.cpp b/fuzzers/gdal_translate_fuzzer.cpp index 07a850867bad..9da3553ea6e4 100644 --- a/fuzzers/gdal_translate_fuzzer.cpp +++ b/fuzzers/gdal_translate_fuzzer.cpp @@ -41,7 +41,7 @@ int LLVMFuzzerInitialize(int * /*argc*/, char ***argv) const char *exe_path = (*argv)[0]; if (CPLGetConfigOption("GDAL_DATA", nullptr) == nullptr) { - CPLSetConfigOption("GDAL_DATA", CPLGetPath(exe_path)); + CPLSetConfigOption("GDAL_DATA", CPLGetPathSafe(exe_path).c_str()); } CPLSetConfigOption("CPL_TMPDIR", "/tmp"); CPLSetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", "YES"); diff --git a/fuzzers/gdal_vector_translate_fuzzer.cpp b/fuzzers/gdal_vector_translate_fuzzer.cpp index 39222280cedc..5a304c1937c2 100644 --- a/fuzzers/gdal_vector_translate_fuzzer.cpp +++ b/fuzzers/gdal_vector_translate_fuzzer.cpp @@ -45,7 +45,7 @@ int LLVMFuzzerInitialize(int * /*argc*/, char ***argv) const char *exe_path = (*argv)[0]; if (CPLGetConfigOption("GDAL_DATA", nullptr) == nullptr) { - CPLSetConfigOption("GDAL_DATA", CPLGetPath(exe_path)); + CPLSetConfigOption("GDAL_DATA", CPLGetPathSafe(exe_path).c_str()); } CPLSetConfigOption("CPL_TMPDIR", "/tmp"); CPLSetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", "YES"); diff --git a/fuzzers/ogr_fuzzer.cpp b/fuzzers/ogr_fuzzer.cpp index 805473ce236e..a79b3ed0dd98 100644 --- a/fuzzers/ogr_fuzzer.cpp +++ b/fuzzers/ogr_fuzzer.cpp @@ -62,7 +62,7 @@ int LLVMFuzzerInitialize(int * /*argc*/, char ***argv) const char *exe_path = (*argv)[0]; if (CPLGetConfigOption("GDAL_DATA", nullptr) == nullptr) { - CPLSetConfigOption("GDAL_DATA", CPLGetPath(exe_path)); + CPLSetConfigOption("GDAL_DATA", CPLGetPathSafe(exe_path).c_str()); } CPLSetConfigOption("CPL_TMPDIR", "/tmp"); CPLSetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", "YES"); diff --git a/gcore/gdal_mdreader.cpp b/gcore/gdal_mdreader.cpp index 42aa5a2569cd..ae42d2c0fb3a 100644 --- a/gcore/gdal_mdreader.cpp +++ b/gcore/gdal_mdreader.cpp @@ -821,7 +821,7 @@ CPLErr GDALWriteRPCTXTFile(const char *pszFilename, char **papszMD) CPLErr GDALWriteRPBFile(const char *pszFilename, char **papszMD) { - CPLString osRPBFilename = CPLResetExtension(pszFilename, "RPB"); + const CPLString osRPBFilename = CPLResetExtensionSafe(pszFilename, "RPB"); if (papszMD == nullptr) { VSIUnlink(osRPBFilename); @@ -1106,7 +1106,7 @@ static void GDALWriteIMDMultiLine(VSILFILE *fp, const char *pszValue) CPLErr GDALWriteIMDFile(const char *pszFilename, char **papszMD) { - CPLString osRPBFilename = CPLResetExtension(pszFilename, "IMD"); + const CPLString osRPBFilename = CPLResetExtensionSafe(pszFilename, "IMD"); /* -------------------------------------------------------------------- */ /* Read file and parse. */ diff --git a/gcore/gdal_misc.cpp b/gcore/gdal_misc.cpp index bcd9a3930837..3d05c70e2a3d 100644 --- a/gcore/gdal_misc.cpp +++ b/gcore/gdal_misc.cpp @@ -1859,7 +1859,7 @@ CPLString GDALFindAssociatedFile(const char *pszBaseFilename, CPL_UNUSED int nFlags) { - CPLString osTarget = CPLResetExtension(pszBaseFilename, pszExt); + CPLString osTarget = CPLResetExtensionSafe(pszBaseFilename, pszExt); if (papszSiblingFiles == nullptr || // cppcheck-suppress knownConditionTrueFalse @@ -1876,7 +1876,7 @@ CPLString GDALFindAssociatedFile(const char *pszBaseFilename, else osAltExt = osAltExt.tolower(); - osTarget = CPLResetExtension(pszBaseFilename, osAltExt); + osTarget = CPLResetExtensionSafe(pszBaseFilename, osAltExt); if (VSIStatExL(osTarget, &sStatBuf, VSI_STAT_EXISTS_FLAG) != 0) return ""; @@ -2127,14 +2127,14 @@ int CPL_STDCALL GDALReadOziMapFile(const char *pszBaseFilename, /* -------------------------------------------------------------------- */ /* Try lower case, then upper case. */ /* -------------------------------------------------------------------- */ - const char *pszOzi = CPLResetExtension(pszBaseFilename, "map"); + std::string osOzi = CPLResetExtensionSafe(pszBaseFilename, "map"); - VSILFILE *fpOzi = VSIFOpenL(pszOzi, "rt"); + VSILFILE *fpOzi = VSIFOpenL(osOzi.c_str(), "rt"); - if (fpOzi == nullptr && VSIIsCaseSensitiveFS(pszOzi)) + if (fpOzi == nullptr && VSIIsCaseSensitiveFS(osOzi.c_str())) { - pszOzi = CPLResetExtension(pszBaseFilename, "MAP"); - fpOzi = VSIFOpenL(pszOzi, "rt"); + osOzi = CPLResetExtensionSafe(pszBaseFilename, "MAP"); + fpOzi = VSIFOpenL(osOzi.c_str(), "rt"); } if (fpOzi == nullptr) @@ -2145,8 +2145,8 @@ int CPL_STDCALL GDALReadOziMapFile(const char *pszBaseFilename, /* -------------------------------------------------------------------- */ /* We found the file, now load and parse it. */ /* -------------------------------------------------------------------- */ - return GDALLoadOziMapFile(pszOzi, padfGeoTransform, ppszWKT, pnGCPCount, - ppasGCPs); + return GDALLoadOziMapFile(osOzi.c_str(), padfGeoTransform, ppszWKT, + pnGCPCount, ppasGCPs); } /************************************************************************/ @@ -2333,13 +2333,14 @@ int GDALReadTabFile2(const char *pszBaseFilename, double *padfGeoTransform, if (!GDALCanFileAcceptSidecarFile(pszBaseFilename)) return FALSE; - const char *pszTAB = CPLResetExtension(pszBaseFilename, "tab"); + std::string osTAB = CPLResetExtensionSafe(pszBaseFilename, "tab"); if (papszSiblingFiles && // cppcheck-suppress knownConditionTrueFalse - GDALCanReliablyUseSiblingFileList(pszTAB)) + GDALCanReliablyUseSiblingFileList(osTAB.c_str())) { - int iSibling = CSLFindString(papszSiblingFiles, CPLGetFilename(pszTAB)); + int iSibling = + CSLFindString(papszSiblingFiles, CPLGetFilename(osTAB.c_str())); if (iSibling >= 0) { CPLString osTabFilename = pszBaseFilename; @@ -2361,12 +2362,12 @@ int GDALReadTabFile2(const char *pszBaseFilename, double *padfGeoTransform, /* Try lower case, then upper case. */ /* -------------------------------------------------------------------- */ - VSILFILE *fpTAB = VSIFOpenL(pszTAB, "rt"); + VSILFILE *fpTAB = VSIFOpenL(osTAB.c_str(), "rt"); - if (fpTAB == nullptr && VSIIsCaseSensitiveFS(pszTAB)) + if (fpTAB == nullptr && VSIIsCaseSensitiveFS(osTAB.c_str())) { - pszTAB = CPLResetExtension(pszBaseFilename, "TAB"); - fpTAB = VSIFOpenL(pszTAB, "rt"); + osTAB = CPLResetExtensionSafe(pszBaseFilename, "TAB"); + fpTAB = VSIFOpenL(osTAB.c_str(), "rt"); } if (fpTAB == nullptr) @@ -2377,11 +2378,11 @@ int GDALReadTabFile2(const char *pszBaseFilename, double *padfGeoTransform, /* -------------------------------------------------------------------- */ /* We found the file, now load and parse it. */ /* -------------------------------------------------------------------- */ - if (GDALLoadTabFile(pszTAB, padfGeoTransform, ppszWKT, pnGCPCount, + if (GDALLoadTabFile(osTAB.c_str(), padfGeoTransform, ppszWKT, pnGCPCount, ppasGCPs)) { if (ppszTabFileNameOut) - *ppszTabFileNameOut = CPLStrdup(pszTAB); + *ppszTabFileNameOut = CPLStrdup(osTAB.c_str()); return TRUE; } return FALSE; @@ -2541,7 +2542,7 @@ int GDALReadWorldFile2(const char *pszBaseFilename, const char *pszExtension, /* -------------------------------------------------------------------- */ if (pszExtension == nullptr) { - const std::string oBaseExt = CPLGetExtension(pszBaseFilename); + const std::string oBaseExt = CPLGetExtensionSafe(pszBaseFilename); if (oBaseExt.length() < 2) return FALSE; @@ -2591,14 +2592,14 @@ int GDALReadWorldFile2(const char *pszBaseFilename, const char *pszExtension, CPLTolower(static_cast(szExtLower[i]))); } - const char *pszTFW = CPLResetExtension(pszBaseFilename, szExtLower); + std::string osTFW = CPLResetExtensionSafe(pszBaseFilename, szExtLower); if (papszSiblingFiles && // cppcheck-suppress knownConditionTrueFalse - GDALCanReliablyUseSiblingFileList(pszTFW)) + GDALCanReliablyUseSiblingFileList(osTFW.c_str())) { const int iSibling = - CSLFindString(papszSiblingFiles, CPLGetFilename(pszTFW)); + CSLFindString(papszSiblingFiles, CPLGetFilename(osTFW.c_str())); if (iSibling >= 0) { CPLString osTFWFilename = pszBaseFilename; @@ -2620,12 +2621,14 @@ int GDALReadWorldFile2(const char *pszBaseFilename, const char *pszExtension, /* -------------------------------------------------------------------- */ VSIStatBufL sStatBuf; - bool bGotTFW = VSIStatExL(pszTFW, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0; + bool bGotTFW = + VSIStatExL(osTFW.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0; - if (!bGotTFW && VSIIsCaseSensitiveFS(pszTFW)) + if (!bGotTFW && VSIIsCaseSensitiveFS(osTFW.c_str())) { - pszTFW = CPLResetExtension(pszBaseFilename, szExtUpper); - bGotTFW = VSIStatExL(pszTFW, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0; + osTFW = CPLResetExtensionSafe(pszBaseFilename, szExtUpper); + bGotTFW = + VSIStatExL(osTFW.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0; } if (!bGotTFW) @@ -2634,10 +2637,10 @@ int GDALReadWorldFile2(const char *pszBaseFilename, const char *pszExtension, /* -------------------------------------------------------------------- */ /* We found the file, now load and parse it. */ /* -------------------------------------------------------------------- */ - if (GDALLoadWorldFile(pszTFW, padfGeoTransform)) + if (GDALLoadWorldFile(osTFW.c_str(), padfGeoTransform)) { if (ppszWorldFileNameOut) - *ppszWorldFileNameOut = CPLStrdup(pszTFW); + *ppszWorldFileNameOut = CPLStrdup(osTFW.c_str()); return TRUE; } return FALSE; @@ -2702,8 +2705,9 @@ int CPL_STDCALL GDALWriteWorldFile(const char *pszBaseFilename, /* -------------------------------------------------------------------- */ /* Update extension, and write to disk. */ /* -------------------------------------------------------------------- */ - const char *pszTFW = CPLResetExtension(pszBaseFilename, pszExtension); - VSILFILE *const fpTFW = VSIFOpenL(pszTFW, "wt"); + const std::string osTFW = + CPLResetExtensionSafe(pszBaseFilename, pszExtension); + VSILFILE *const fpTFW = VSIFOpenL(osTFW.c_str(), "wt"); if (fpTFW == nullptr) return FALSE; @@ -3655,13 +3659,14 @@ int CPL_STDCALL GDALGeneralCmdLineProcessor(int nArgc, char ***ppapszArgv, if (EQUAL(papszFiles[i], ".") || EQUAL(papszFiles[i], "..")) continue; - CPLString osOldPath, osNewPath; - osOldPath = CPLFormFilename(papszArgv[iArg + 1], papszFiles[i], - nullptr); + std::string osOldPath; + CPLString osNewPath; + osOldPath = CPLFormFilenameSafe(papszArgv[iArg + 1], + papszFiles[i], nullptr); osNewPath.Printf("/vsimem/%s", papszFiles[i]); VSIStatBufL sStatBuf; - if (VSIStatL(osOldPath, &sStatBuf) != 0 || + if (VSIStatL(osOldPath.c_str(), &sStatBuf) != 0 || VSI_ISDIR(sStatBuf.st_mode)) { CPLDebug("VSI", "Skipping preload of %s.", @@ -3672,7 +3677,7 @@ int CPL_STDCALL GDALGeneralCmdLineProcessor(int nArgc, char ***ppapszArgv, CPLDebug("VSI", "Preloading %s to %s.", osOldPath.c_str(), osNewPath.c_str()); - if (CPLCopyFile(osNewPath, osOldPath) != 0) + if (CPLCopyFile(osNewPath, osOldPath.c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to copy %s to /vsimem", osOldPath.c_str()); @@ -4356,7 +4361,7 @@ GDALDataset *GDALFindAssociatedAuxFile(const char *pszBasename, const char *pszAuxSuffixLC = "aux"; const char *pszAuxSuffixUC = "AUX"; - if (EQUAL(CPLGetExtension(pszBasename), pszAuxSuffixLC)) + if (EQUAL(CPLGetExtensionSafe(pszBasename).c_str(), pszAuxSuffixLC)) return nullptr; /* -------------------------------------------------------------------- */ @@ -4374,7 +4379,8 @@ GDALDataset *GDALFindAssociatedAuxFile(const char *pszBasename, /* has occurred. */ /* -------------------------------------------------------------------- */ CPLString osJustFile = CPLGetFilename(pszBasename); // without dir - CPLString osAuxFilename = CPLResetExtension(pszBasename, pszAuxSuffixLC); + CPLString osAuxFilename = + CPLResetExtensionSafe(pszBasename, pszAuxSuffixLC); GDALDataset *poODS = nullptr; GByte abyHeader[32]; @@ -4383,7 +4389,7 @@ GDALDataset *GDALFindAssociatedAuxFile(const char *pszBasename, if (fp == nullptr && VSIIsCaseSensitiveFS(osAuxFilename)) { // Can't found file with lower case suffix. Try the upper case one. - osAuxFilename = CPLResetExtension(pszBasename, pszAuxSuffixUC); + osAuxFilename = CPLResetExtensionSafe(pszBasename, pszAuxSuffixUC); fp = VSIFOpenL(osAuxFilename, "rb"); } diff --git a/gcore/gdal_pam.h b/gcore/gdal_pam.h index 781b6b602b3e..01a299e548f0 100644 --- a/gcore/gdal_pam.h +++ b/gcore/gdal_pam.h @@ -196,6 +196,9 @@ class CPL_DLL GDALPamDataset : public GDALDataset private: CPL_DISALLOW_COPY_ASSIGN(GDALPamDataset) + + // cached return of GetMetadataItem("OVERVIEW_FILE", "OVERVIEWS") + std::string m_osOverviewFile{}; }; //! @cond Doxygen_Suppress diff --git a/gcore/gdal_priv.h b/gcore/gdal_priv.h index 6405ebe9f6e3..4cf88355eacf 100644 --- a/gcore/gdal_priv.h +++ b/gcore/gdal_priv.h @@ -290,9 +290,9 @@ class CPL_DLL GDALDefaultOverviews /** Class for dataset open functions. */ class CPL_DLL GDALOpenInfo { - bool bHasGotSiblingFiles; - char **papszSiblingFiles; - int nHeaderBytesTried; + bool bHasGotSiblingFiles = false; + char **papszSiblingFiles = nullptr; + int nHeaderBytesTried = 0; public: GDALOpenInfo(const char *pszFile, int nOpenFlagsIn, @@ -300,30 +300,34 @@ class CPL_DLL GDALOpenInfo ~GDALOpenInfo(void); /** Filename */ - char *pszFilename; + char *pszFilename = nullptr; + + /** Result of CPLGetExtension(pszFilename); */ + std::string osExtension{}; + /** Open options */ - char **papszOpenOptions; + char **papszOpenOptions = nullptr; /** Access flag */ - GDALAccess eAccess; + GDALAccess eAccess = GA_ReadOnly; /** Open flags */ - int nOpenFlags; + int nOpenFlags = 0; /** Whether stat()'ing the file was successful */ - int bStatOK; + bool bStatOK = false; /** Whether the file is a directory */ - int bIsDirectory; + bool bIsDirectory = false; /** Pointer to the file */ - VSILFILE *fpL; + VSILFILE *fpL = nullptr; /** Number of bytes in pabyHeader */ - int nHeaderBytes; + int nHeaderBytes = 0; /** Buffer with first bytes of the file */ - GByte *pabyHeader; + GByte *pabyHeader = nullptr; /** Allowed drivers (NULL for all) */ - const char *const *papszAllowedDrivers; + const char *const *papszAllowedDrivers = nullptr; int TryToIngest(int nBytes); char **GetSiblingFiles(); @@ -332,6 +336,14 @@ class CPL_DLL GDALOpenInfo bool IsSingleAllowedDriver(const char *pszDriverName) const; + /** Return whether the extension of the file is equal to pszExt, using + * case-insensitive comparison. + * @since 3.11 */ + inline bool IsExtensionEqualToCI(const char *pszExt) const + { + return EQUAL(osExtension.c_str(), pszExt); + } + private: CPL_DISALLOW_COPY_ASSIGN(GDALOpenInfo) }; diff --git a/gcore/gdalalgorithm.cpp b/gcore/gdalalgorithm.cpp index fff0d219812e..26fd554e733c 100644 --- a/gcore/gdalalgorithm.cpp +++ b/gcore/gdalalgorithm.cpp @@ -1998,7 +1998,7 @@ GDALAlgorithm::AddInputDatasetArg(GDALArgDatasetValue *pValue, } } - std::string osDir = CPLGetDirname(currentValue.c_str()); + std::string osDir = CPLGetDirnameSafe(currentValue.c_str()); auto psDir = VSIOpenDir(osDir.c_str(), 0, nullptr); const std::string osSep = VSIGetDirectorySeparator(osDir.c_str()); if (currentValue.empty()) @@ -2018,7 +2018,7 @@ GDALAlgorithm::AddInputDatasetArg(GDALArgDatasetValue *pValue, { if (cpl::contains( oExtensions, - CPLString(CPLGetExtension(psEntry->pszName)) + CPLString(CPLGetExtensionSafe(psEntry->pszName)) .tolower()) || VSI_ISDIR(psEntry->nMode)) { @@ -2026,7 +2026,7 @@ GDALAlgorithm::AddInputDatasetArg(GDALArgDatasetValue *pValue, if (osDir.empty()) osVal = psEntry->pszName; else - osVal = CPLFormFilename( + osVal = CPLFormFilenameSafe( osDir.c_str(), psEntry->pszName, nullptr); if (VSI_ISDIR(psEntry->nMode)) osVal += osSep; @@ -2273,7 +2273,7 @@ GDALAlgorithm::AddOpenOptionsArg(std::vector *pValue) auto poDM = GetGDALDriverManager(); auto &datasetValue = inputArg->Get(); const auto &osDSName = datasetValue.GetName(); - const std::string osExt = CPLGetExtension(osDSName.c_str()); + const std::string osExt = CPLGetExtensionSafe(osDSName.c_str()); if (!osExt.empty()) { std::set oVisitedExtensions; @@ -2590,7 +2590,7 @@ GDALAlgorithm::AddCreationOptionsArg(std::vector *pValue) auto poDM = GetGDALDriverManager(); auto &datasetValue = outputArg->Get(); const auto &osDSName = datasetValue.GetName(); - const std::string osExt = CPLGetExtension(osDSName.c_str()); + const std::string osExt = CPLGetExtensionSafe(osDSName.c_str()); if (!osExt.empty()) { std::set oVisitedExtensions; @@ -2680,7 +2680,7 @@ GDALAlgorithm::AddLayerCreationOptionsArg(std::vector *pValue) auto poDM = GetGDALDriverManager(); auto &datasetValue = outputArg->Get(); const auto &osDSName = datasetValue.GetName(); - const std::string osExt = CPLGetExtension(osDSName.c_str()); + const std::string osExt = CPLGetExtensionSafe(osDSName.c_str()); if (!osExt.empty()) { std::set oVisitedExtensions; diff --git a/gcore/gdaldefaultoverviews.cpp b/gcore/gdaldefaultoverviews.cpp index d0dd813201cf..9bc80a2dd525 100644 --- a/gcore/gdaldefaultoverviews.cpp +++ b/gcore/gdaldefaultoverviews.cpp @@ -311,7 +311,7 @@ void GDALDefaultOverviews::OverviewScan() bool bTryFindAssociatedAuxFile = true; if (papszInitSiblingFiles) { - CPLString osAuxFilename = CPLResetExtension(pszInitName, "aux"); + CPLString osAuxFilename = CPLResetExtensionSafe(pszInitName, "aux"); int iSibling = CSLFindString(papszInitSiblingFiles, CPLGetFilename(osAuxFilename)); if (iSibling < 0) @@ -364,10 +364,10 @@ void GDALDefaultOverviews::OverviewScan() { if (STARTS_WITH_CI(pszProxyOvrFilename, ":::BASE:::")) { - const CPLString osPath = CPLGetPath(poDS->GetDescription()); + const CPLString osPath = CPLGetPathSafe(poDS->GetDescription()); - osOvrFilename = - CPLFormFilename(osPath, pszProxyOvrFilename + 10, nullptr); + osOvrFilename = CPLFormFilenameSafe( + osPath, pszProxyOvrFilename + 10, nullptr); } else { @@ -546,9 +546,10 @@ CPLErr GDALDefaultOverviews::CleanOverviews() const bool bUseRRD = CPLTestBool(CPLGetConfigOption("USE_RRD", "NO")); if (bUseRRD) - osOvrFilename = CPLResetExtension(poDS->GetDescription(), "aux"); + osOvrFilename = + CPLResetExtensionSafe(poDS->GetDescription(), "aux"); else - osOvrFilename.Printf("%s.ovr", poDS->GetDescription()); + osOvrFilename = std::string(poDS->GetDescription()).append(".ovr"); } else { @@ -666,7 +667,8 @@ CPLErr GDALDefaultOverviews::BuildOverviews( bOvrIsAux = pszUseRRD && CPLTestBool(pszUseRRD); if (bOvrIsAux) { - osOvrFilename = CPLResetExtension(poDS->GetDescription(), "aux"); + osOvrFilename = + CPLResetExtensionSafe(poDS->GetDescription(), "aux"); VSIStatBufL sStatBuf; if (VSIStatExL(osOvrFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0) @@ -1312,7 +1314,7 @@ int GDALDefaultOverviews::HaveMaskFile(char **papszSiblingFiles, pszBasename = poDS->GetDescription(); // Don't bother checking for masks of masks. - if (EQUAL(CPLGetExtension(pszBasename), "msk")) + if (EQUAL(CPLGetExtensionSafe(pszBasename).c_str(), "msk")) return FALSE; if (!GDALCanFileAcceptSidecarFile(pszBasename)) diff --git a/gcore/gdaldriver.cpp b/gcore/gdaldriver.cpp index 02974ac4e946..5ba07b6f8b0b 100644 --- a/gcore/gdaldriver.cpp +++ b/gcore/gdaldriver.cpp @@ -2919,7 +2919,7 @@ char **GDALGetOutputDriversForDatasetName(const char *pszDestDataset, { CPLStringList aosDriverNames; - std::string osExt = CPLGetExtension(pszDestDataset); + std::string osExt = CPLGetExtensionSafe(pszDestDataset); if (EQUAL(osExt.c_str(), "zip")) { const CPLString osLower(CPLString(pszDestDataset).tolower()); diff --git a/gcore/gdaldrivermanager.cpp b/gcore/gdaldrivermanager.cpp index 98aabe187a09..98ef8ae1f120 100644 --- a/gcore/gdaldrivermanager.cpp +++ b/gcore/gdaldrivermanager.cpp @@ -806,10 +806,9 @@ char **GDALDriverManager::GetSearchPaths(const char *pszGDAL_DRIVER_PATH) if (CPLGetExecPath(szExecPath, sizeof(szExecPath))) { - char szPluginDir[sizeof(szExecPath) + 50]; - strcpy(szPluginDir, CPLGetDirname(szExecPath)); - strcat(szPluginDir, "\\gdalplugins"); - papszSearchPaths = CSLAddString(papszSearchPaths, szPluginDir); + papszSearchPaths = CSLAddString( + papszSearchPaths, + (CPLGetDirnameSafe(szExecPath) + "\\gdalplugins").c_str()); } else { @@ -880,11 +879,11 @@ CPLErr GDALDriverManager::LoadPlugin(const char *name) const int nSearchPaths = aosSearchPaths.size(); for (int iDir = 0; iDir < nSearchPaths; ++iDir) { - CPLString osABISpecificDir = - CPLFormFilename(aosSearchPaths[iDir], osABIVersion, nullptr); + std::string osABISpecificDir = + CPLFormFilenameSafe(aosSearchPaths[iDir], osABIVersion, nullptr); VSIStatBufL sStatBuf; - if (VSIStatL(osABISpecificDir, &sStatBuf) != 0) + if (VSIStatL(osABISpecificDir.c_str(), &sStatBuf) != 0) osABISpecificDir = aosSearchPaths[iDir]; CPLString gdal_or_ogr[2] = {"gdal_", "ogr_"}; @@ -894,10 +893,10 @@ CPLErr GDALDriverManager::LoadPlugin(const char *name) { for (const CPLString &extension : platformExtensions) { - const char *pszFilename = CPLFormFilename( - osABISpecificDir, CPLSPrintf("%s%s", prefix.c_str(), name), - extension); - if (VSIStatL(pszFilename, &sStatBuf) != 0) + const std::string osFilename = CPLFormFilenameSafe( + osABISpecificDir.c_str(), + CPLSPrintf("%s%s", prefix.c_str(), name), extension); + if (VSIStatL(osFilename.c_str(), &sStatBuf) != 0) continue; CPLString osFuncName; @@ -911,13 +910,13 @@ CPLErr GDALDriverManager::LoadPlugin(const char *name) } CPLErrorReset(); CPLPushErrorHandler(CPLQuietErrorHandler); - void *pRegister = CPLGetSymbol(pszFilename, osFuncName); + void *pRegister = CPLGetSymbol(osFilename.c_str(), osFuncName); CPLPopErrorHandler(); if (pRegister == nullptr) { CPLString osLastErrorMsg(CPLGetLastErrorMsg()); osFuncName = "GDALRegisterMe"; - pRegister = CPLGetSymbol(pszFilename, osFuncName); + pRegister = CPLGetSymbol(osFilename.c_str(), osFuncName); if (pRegister == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, "%s", @@ -926,7 +925,7 @@ CPLErr GDALDriverManager::LoadPlugin(const char *name) } } CPLDebug("GDAL", "Registering %s using %s in %s", name, - osFuncName.c_str(), pszFilename); + osFuncName.c_str(), osFilename.c_str()); CPLErrorReset(); reinterpret_cast(pRegister)(); if (CPLGetErrorCounter() > 0) @@ -1012,27 +1011,28 @@ void GDALDriverManager::AutoLoadDrivers() bool bFoundOnePlugin = false; for (int iDir = 0; iDir < nSearchPaths; ++iDir) { - CPLString osABISpecificDir = - CPLFormFilename(papszSearchPaths[iDir], osABIVersion, nullptr); + std::string osABISpecificDir = + CPLFormFilenameSafe(papszSearchPaths[iDir], osABIVersion, nullptr); VSIStatBufL sStatBuf; - if (VSIStatL(osABISpecificDir, &sStatBuf) != 0) + if (VSIStatL(osABISpecificDir.c_str(), &sStatBuf) != 0) osABISpecificDir = papszSearchPaths[iDir]; - char **papszFiles = VSIReadDir(osABISpecificDir); + char **papszFiles = VSIReadDir(osABISpecificDir.c_str()); const int nFileCount = CSLCount(papszFiles); for (int iFile = 0; iFile < nFileCount; ++iFile) { - const char *pszExtension = CPLGetExtension(papszFiles[iFile]); + const CPLString osExtension = + CPLGetExtensionSafe(papszFiles[iFile]); - if (!EQUAL(pszExtension, "dll") && !EQUAL(pszExtension, "so") && - !EQUAL(pszExtension, "dylib")) + if (!EQUAL(osExtension, "dll") && !EQUAL(osExtension, "so") && + !EQUAL(osExtension, "dylib")) { if (strcmp(papszFiles[iFile], "drivers.ini") == 0) { - m_osDriversIniPath = CPLFormFilename( - osABISpecificDir, papszFiles[iFile], nullptr); + m_osDriversIniPath = CPLFormFilenameSafe( + osABISpecificDir.c_str(), papszFiles[iFile], nullptr); } continue; } @@ -1045,31 +1045,33 @@ void GDALDriverManager::AutoLoadDrivers() CPLString osFuncName; if (STARTS_WITH_CI(papszFiles[iFile], "gdal_")) { - osFuncName.Printf("GDALRegister_%s", - CPLGetBasename(papszFiles[iFile]) + - strlen("gdal_")); + osFuncName.Printf( + "GDALRegister_%s", + CPLGetBasenameSafe(papszFiles[iFile]).c_str() + + strlen("gdal_")); } else if (STARTS_WITH_CI(papszFiles[iFile], "ogr_")) { - osFuncName.Printf("RegisterOGR%s", - CPLGetBasename(papszFiles[iFile]) + - strlen("ogr_")); + osFuncName.Printf( + "RegisterOGR%s", + CPLGetBasenameSafe(papszFiles[iFile]).c_str() + + strlen("ogr_")); } else continue; - const char *pszFilename = - CPLFormFilename(osABISpecificDir, papszFiles[iFile], nullptr); + const std::string osFilename = CPLFormFilenameSafe( + osABISpecificDir.c_str(), papszFiles[iFile], nullptr); CPLErrorReset(); CPLPushErrorHandler(CPLQuietErrorHandler); - void *pRegister = CPLGetSymbol(pszFilename, osFuncName); + void *pRegister = CPLGetSymbol(osFilename.c_str(), osFuncName); CPLPopErrorHandler(); if (pRegister == nullptr) { CPLString osLastErrorMsg(CPLGetLastErrorMsg()); osFuncName = "GDALRegisterMe"; - pRegister = CPLGetSymbol(pszFilename, osFuncName); + pRegister = CPLGetSymbol(osFilename.c_str(), osFuncName); if (pRegister == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, "%s", @@ -1080,8 +1082,8 @@ void GDALDriverManager::AutoLoadDrivers() if (pRegister != nullptr) { bFoundOnePlugin = true; - CPLDebug("GDAL", "Auto register %s using %s.", pszFilename, - osFuncName.c_str()); + CPLDebug("GDAL", "Auto register %s using %s.", + osFilename.c_str(), osFuncName.c_str()); reinterpret_cast(pRegister)(); } @@ -1570,12 +1572,12 @@ std::string GDALDriverManager::GetPluginFullPath(const char *pszFilename) const { if (!m_osLastTriedDirectory.empty()) { - const char *pszFullFilename = CPLFormFilename( + std::string osFullFilename = CPLFormFilenameSafe( m_osLastTriedDirectory.c_str(), pszFilename, nullptr); VSIStatBufL sStatBuf; - if (VSIStatL(pszFullFilename, &sStatBuf) == 0) + if (VSIStatL(osFullFilename.c_str(), &sStatBuf) == 0) { - return pszFullFilename; + return osFullFilename; } } @@ -1614,18 +1616,18 @@ std::string GDALDriverManager::GetPluginFullPath(const char *pszFilename) const for (int iDir = 0; iDir < nSearchPaths; ++iDir) { std::string osABISpecificDir = - CPLFormFilename(aosSearchPaths[iDir], osABIVersion, nullptr); + CPLFormFilenameSafe(aosSearchPaths[iDir], osABIVersion, nullptr); VSIStatBufL sStatBuf; if (VSIStatL(osABISpecificDir.c_str(), &sStatBuf) != 0) osABISpecificDir = aosSearchPaths[iDir]; - const char *pszFullFilename = - CPLFormFilename(osABISpecificDir.c_str(), pszFilename, nullptr); - if (VSIStatL(pszFullFilename, &sStatBuf) == 0) + std::string osFullFilename = + CPLFormFilenameSafe(osABISpecificDir.c_str(), pszFilename, nullptr); + if (VSIStatL(osFullFilename.c_str(), &sStatBuf) == 0) { m_osLastTriedDirectory = std::move(osABISpecificDir); - return pszFullFilename; + return osFullFilename; } } diff --git a/gcore/gdaljp2abstractdataset.cpp b/gcore/gdaljp2abstractdataset.cpp index 7e6923db73eb..73c8da878306 100644 --- a/gcore/gdaljp2abstractdataset.cpp +++ b/gcore/gdaljp2abstractdataset.cpp @@ -438,7 +438,7 @@ void GDALJP2AbstractDataset::LoadVectorLayers(int bOpenRemoteResources) if (psFC != nullptr) { osGMLTmpFile = - CPLFormFilename(osTmpDir.c_str(), "my.gml", nullptr); + CPLFormFilenameSafe(osTmpDir.c_str(), "my.gml", nullptr); // Create temporary .gml file. CPLSerializeXMLTreeToFile(psFC, osGMLTmpFile); } @@ -473,7 +473,7 @@ void GDALJP2AbstractDataset::LoadVectorLayers(int bOpenRemoteResources) CPLSPrintf("xml:%s", pszBoxName)); if (papszBoxData != nullptr) { - osXSDTmpFile = CPLFormFilename( + osXSDTmpFile = CPLFormFilenameSafe( osTmpDir.c_str(), "my.xsd", nullptr); CPL_IGNORE_RET_VAL( VSIFCloseL(VSIFileFromMemBuffer( diff --git a/gcore/gdaljp2metadata.cpp b/gcore/gdaljp2metadata.cpp index e3f6442b2caa..746184e80e55 100644 --- a/gcore/gdaljp2metadata.cpp +++ b/gcore/gdaljp2metadata.cpp @@ -2711,8 +2711,9 @@ GDALJP2Box *GDALJP2Metadata::CreateGMLJP2V2(int nXSize, int nYSize, CPLXMLTreeCloser psGMLFile(nullptr); if (!aoGMLFiles[i].osFile.empty()) { - if (EQUAL(CPLGetExtension(aoGMLFiles[i].osFile), "gml") || - EQUAL(CPLGetExtension(aoGMLFiles[i].osFile), "xml")) + const CPLString osExt = + CPLGetExtensionSafe(aoGMLFiles[i].osFile); + if (EQUAL(osExt, "gml") || EQUAL(osExt, "xml")) { psGMLFile = CPLXMLTreeCloser(CPLParseXMLFile(aoGMLFiles[i].osFile)); @@ -2751,9 +2752,9 @@ GDALJP2Box *GDALJP2Metadata::CreateGMLJP2V2(int nXSize, int nYSize, nullptr, nullptr, nullptr); if (hSrcDS) { - CPLString osTmpFile = - CPLSPrintf("%s/%d/%s.gml", osTmpDir.c_str(), i, - CPLGetBasename(aoGMLFiles[i].osFile)); + const CPLString osTmpFile = + osTmpDir + "/" + std::to_string(i) + "/" + + CPLGetBasenameSafe(aoGMLFiles[i].osFile) + ".gml"; char **papszOptions = nullptr; papszOptions = CSLSetNameValue(papszOptions, "FORMAT", "GML3.2"); @@ -2859,10 +2860,9 @@ GDALJP2Box *GDALJP2Metadata::CreateGMLJP2V2(int nXSize, int nYSize, if (!aoGMLFiles[i].bInline || !aoGMLFiles[i].osRemoteResource.empty()) { - osTmpFile = - CPLSPrintf("%s/%d/%s.gml", osTmpDir.c_str(), i, - CPLGetBasename(aoGMLFiles[i].osFile)); - + osTmpFile = osTmpDir + "/" + std::to_string(i) + "/" + + CPLGetBasenameSafe(aoGMLFiles[i].osFile) + + ".gml"; GMLJP2V2BoxDesc oDesc; oDesc.osFile = osTmpFile; oDesc.osLabel = CPLGetFilename(oDesc.osFile); @@ -2930,13 +2930,15 @@ GDALJP2Box *GDALJP2Metadata::CreateGMLJP2V2(int nXSize, int nYSize, else if (CSLCount(papszTokens) == 2 && CPLIsFilenameRelative(papszTokens[1]) && VSIStatL( - CPLFormFilename( - CPLGetDirname(aoGMLFiles[i].osFile), - papszTokens[1], nullptr), + CPLFormFilenameSafe( + CPLGetDirnameSafe(aoGMLFiles[i].osFile) + .c_str(), + papszTokens[1], nullptr) + .c_str(), &sStat) == 0) { - osXSD = CPLFormFilename( - CPLGetDirname(aoGMLFiles[i].osFile), + osXSD = CPLFormFilenameSafe( + CPLGetDirnameSafe(aoGMLFiles[i].osFile).c_str(), papszTokens[1], nullptr); } if (!osXSD.empty()) @@ -3001,7 +3003,8 @@ GDALJP2Box *GDALJP2Metadata::CreateGMLJP2V2(int nXSize, int nYSize, { // Is the file already a KML file? CPLXMLTreeCloser psKMLFile(nullptr); - if (EQUAL(CPLGetExtension(aoAnnotations[i].osFile), "kml")) + if (EQUAL(CPLGetExtensionSafe(aoAnnotations[i].osFile).c_str(), + "kml")) psKMLFile = CPLXMLTreeCloser(CPLParseXMLFile(aoAnnotations[i].osFile)); GDALDriverH hDrv = nullptr; @@ -3039,9 +3042,9 @@ GDALJP2Box *GDALJP2Metadata::CreateGMLJP2V2(int nXSize, int nYSize, nullptr, nullptr, nullptr); if (hSrcDS) { - CPLString osTmpFile = - CPLSPrintf("%s/%d/%s.kml", osTmpDir.c_str(), i, - CPLGetBasename(aoAnnotations[i].osFile)); + const CPLString osTmpFile = + osTmpDir + "/" + std::to_string(i) + "/" + + CPLGetBasenameSafe(aoAnnotations[i].osFile) + ".kml"; char **papszOptions = nullptr; if (aoAnnotations.size() > 1) { diff --git a/gcore/gdaljp2structure.cpp b/gcore/gdaljp2structure.cpp index 44a338f649f9..532ab814f22c 100644 --- a/gcore/gdaljp2structure.cpp +++ b/gcore/gdaljp2structure.cpp @@ -251,7 +251,7 @@ static void DumpGeoTIFFBox(CPLXMLNode *psBox, GDALJP2Box &oBox, if (poDS) { const CPLString osTmpVRTFilename( - CPLResetExtension(osTmpFilename.c_str(), "vrt")); + CPLResetExtensionSafe(osTmpFilename.c_str(), "vrt")); GDALDataset *poVRTDS = poVRTDriver->CreateCopy( osTmpVRTFilename, poDS, FALSE, nullptr, nullptr, nullptr); GDALClose(poVRTDS); diff --git a/gcore/gdalmultidim.cpp b/gcore/gdalmultidim.cpp index 44764a6b2c7e..2832b5609e21 100644 --- a/gcore/gdalmultidim.cpp +++ b/gcore/gdalmultidim.cpp @@ -4420,7 +4420,7 @@ bool GDALMDArray::Read(const GUInt64 *arrayStartIdx, const size_t *count, { const auto &osFilename = GetFilename(); if (!osFilename.empty() && - !EQUAL(CPLGetExtension(osFilename.c_str()), "gmac")) + !EQUAL(CPLGetExtensionSafe(osFilename.c_str()).c_str(), "gmac")) { std::string osCacheFilename; auto poRG = GetCacheRootGroup(false, osCacheFilename); diff --git a/gcore/gdalopeninfo.cpp b/gcore/gdalopeninfo.cpp index d9d757783eb3..8b136ccc0e73 100644 --- a/gcore/gdalopeninfo.cpp +++ b/gcore/gdalopeninfo.cpp @@ -151,13 +151,10 @@ static GByte *GDALOpenInfoGetFileNotToOpen(const char *pszFilename, */ GDALOpenInfo::GDALOpenInfo(const char *pszFilenameIn, int nOpenFlagsIn, const char *const *papszSiblingsIn) - : bHasGotSiblingFiles(false), papszSiblingFiles(nullptr), - nHeaderBytesTried(0), pszFilename(CPLStrdup(pszFilenameIn)), - papszOpenOptions(nullptr), + : pszFilename(CPLStrdup(pszFilenameIn)), + osExtension(CPLGetExtensionSafe(pszFilenameIn)), eAccess(nOpenFlagsIn & GDAL_OF_UPDATE ? GA_Update : GA_ReadOnly), - nOpenFlags(nOpenFlagsIn), bStatOK(FALSE), bIsDirectory(FALSE), - fpL(nullptr), nHeaderBytes(0), pabyHeader(nullptr), - papszAllowedDrivers(nullptr) + nOpenFlags(nOpenFlagsIn) { if (STARTS_WITH(pszFilename, "MVT:/vsi")) return; @@ -205,7 +202,7 @@ GDALOpenInfo::GDALOpenInfo(const char *pszFilenameIn, int nOpenFlagsIn, STARTS_WITH(pszFilename, "/vsi7z/") || STARTS_WITH(pszFilename, "/vsirar/")) { - const char *pszExt = CPLGetExtension(pszFilename); + const char *pszExt = osExtension.c_str(); if (EQUAL(pszExt, "zip") || EQUAL(pszExt, "tar") || EQUAL(pszExt, "gz") || EQUAL(pszExt, "7z") || EQUAL(pszExt, "rar") || @@ -313,6 +310,7 @@ GDALOpenInfo::GDALOpenInfo(const char *pszFilenameIn, int nOpenFlagsIn, szPointerFilename[std::min(nBytes, nBufSize - 1)] = 0; CPLFree(pszFilename); pszFilename = CPLStrdup(szPointerFilename); + osExtension = CPLGetExtensionSafe(pszFilename); papszSiblingsIn = nullptr; bHasRetried = true; goto retry; @@ -407,7 +405,7 @@ char **GDALOpenInfo::GetSiblingFiles() return papszSiblingFiles; } - CPLString osDir = CPLGetDirname(pszFilename); + const CPLString osDir = CPLGetDirnameSafe(pszFilename); const int nMaxFiles = atoi(VSIGetPathSpecificOption( pszFilename, "GDAL_READDIR_LIMIT_ON_OPEN", "1000")); papszSiblingFiles = VSIReadDirEx(osDir, nMaxFiles); diff --git a/gcore/gdalorienteddataset.cpp b/gcore/gdalorienteddataset.cpp index 689f500cb0ac..e22a3b28e0c7 100644 --- a/gcore/gdalorienteddataset.cpp +++ b/gcore/gdalorienteddataset.cpp @@ -129,7 +129,7 @@ CPLErr GDALOrientedRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, if (static_cast(nRasterXSize) * nRasterYSize * nDTSize > 10 * 1024 * 1024) { - osTmpName = CPLGenerateTempFilename(nullptr); + osTmpName = CPLGenerateTempFilenameSafe(nullptr); } else { diff --git a/gcore/gdalpamdataset.cpp b/gcore/gdalpamdataset.cpp index 19bff652e651..b10b55e23f41 100644 --- a/gcore/gdalpamdataset.cpp +++ b/gcore/gdalpamdataset.cpp @@ -955,7 +955,7 @@ CPLErr GDALPamDataset::TryLoadXML(CSLConstList papszSiblingFiles) /* Initialize ourselves from this XML tree. */ /* -------------------------------------------------------------------- */ - CPLString osVRTPath(CPLGetPath(psPam->pszPamFilename)); + CPLString osVRTPath(CPLGetPathSafe(psPam->pszPamFilename)); const CPLErr eErr = XMLInit(psTree, osVRTPath); CPLDestroyXMLNode(psTree); @@ -1576,21 +1576,26 @@ const char *GDALPamDataset::GetMetadataItem(const char *pszName, else if (pszDomain != nullptr && EQUAL(pszDomain, "OVERVIEWS") && EQUAL(pszName, "OVERVIEW_FILE")) { - const char *pszOverviewFile = - GDALDataset::GetMetadataItem(pszName, pszDomain); + if (m_osOverviewFile.empty()) + { + const char *pszOverviewFile = + GDALDataset::GetMetadataItem(pszName, pszDomain); - if (pszOverviewFile == nullptr || - !STARTS_WITH_CI(pszOverviewFile, ":::BASE:::")) - return pszOverviewFile; + if (pszOverviewFile == nullptr || + !STARTS_WITH_CI(pszOverviewFile, ":::BASE:::")) + return pszOverviewFile; - CPLString osPath; + std::string osPath; - if (strlen(GetPhysicalFilename()) > 0) - osPath = CPLGetPath(GetPhysicalFilename()); - else - osPath = CPLGetPath(GetDescription()); + if (strlen(GetPhysicalFilename()) > 0) + osPath = CPLGetPathSafe(GetPhysicalFilename()); + else + osPath = CPLGetPathSafe(GetDescription()); - return CPLFormFilename(osPath, pszOverviewFile + 10, nullptr); + m_osOverviewFile = CPLFormFilenameSafe( + osPath.c_str(), pszOverviewFile + 10, nullptr); + } + return m_osOverviewFile.c_str(); } /* -------------------------------------------------------------------- */ @@ -1641,7 +1646,7 @@ CPLErr GDALPamDataset::TryLoadAux(CSLConstList papszSiblingFiles) if (papszSiblingFiles && GDALCanReliablyUseSiblingFileList(pszPhysicalFile)) { - CPLString osAuxFilename = CPLResetExtension(pszPhysicalFile, "aux"); + CPLString osAuxFilename = CPLResetExtensionSafe(pszPhysicalFile, "aux"); int iSibling = CSLFindString(papszSiblingFiles, CPLGetFilename(osAuxFilename)); if (iSibling < 0) diff --git a/gcore/gdalpamproxydb.cpp b/gcore/gdalpamproxydb.cpp index 14b4cc260613..75c1d36b68cc 100644 --- a/gcore/gdalpamproxydb.cpp +++ b/gcore/gdalpamproxydb.cpp @@ -89,8 +89,9 @@ void GDALPamProxyDB::LoadDB() /* Open the database relating original names to proxy .aux.xml */ /* file names. */ /* -------------------------------------------------------------------- */ - CPLString osDBName = CPLFormFilename(osProxyDBDir, "gdal_pam_proxy", "dat"); - VSILFILE *fpDB = VSIFOpenL(osDBName, "r"); + const std::string osDBName = + CPLFormFilenameSafe(osProxyDBDir, "gdal_pam_proxy", "dat"); + VSILFILE *fpDB = VSIFOpenL(osDBName.c_str(), "r"); nUpdateCounter = 0; if (fpDB == nullptr) @@ -185,9 +186,10 @@ void GDALPamProxyDB::SaveDB() /* Open the database relating original names to proxy .aux.xml */ /* file names. */ /* -------------------------------------------------------------------- */ - CPLString osDBName = CPLFormFilename(osProxyDBDir, "gdal_pam_proxy", "dat"); + const std::string osDBName = + CPLFormFilenameSafe(osProxyDBDir, "gdal_pam_proxy", "dat"); - void *hLock = CPLLockFile(osDBName, 1.0); + void *hLock = CPLLockFile(osDBName.c_str(), 1.0); // proceed even if lock fails - we need CPLBreakLockFile()! if (hLock == nullptr) @@ -198,7 +200,7 @@ void GDALPamProxyDB::SaveDB() osDBName.c_str()); } - VSILFILE *fpDB = VSIFOpenL(osDBName, "w"); + VSILFILE *fpDB = VSIFOpenL(osDBName.c_str(), "w"); if (fpDB == nullptr) { if (hLock) @@ -226,7 +228,7 @@ void GDALPamProxyDB::SaveDB() "Failed to write complete %s Pam Proxy DB.\n%s", osDBName.c_str(), VSIStrerror(errno)); CPL_IGNORE_RET_VAL(VSIFCloseL(fpDB)); - VSIUnlink(osDBName); + VSIUnlink(osDBName.c_str()); if (hLock) CPLUnlockFile(hLock); return; @@ -250,7 +252,7 @@ void GDALPamProxyDB::SaveDB() "Failed to write complete %s Pam Proxy DB.\n%s", osDBName.c_str(), VSIStrerror(errno)); CPL_IGNORE_RET_VAL(VSIFCloseL(fpDB)); - VSIUnlink(osDBName); + VSIUnlink(osDBName.c_str()); if (hLock) CPLUnlockFile(hLock); return; diff --git a/gcore/gdalpython.cpp b/gcore/gdalpython.cpp index 9e52bd1d1c55..a9160bdeee78 100644 --- a/gcore/gdalpython.cpp +++ b/gcore/gdalpython.cpp @@ -269,11 +269,11 @@ static bool LoadPythonAPI() for (const char *pszPathPart : aosPathParts) { struct stat sStat; - CPLString osPythonBinary( - CPLFormFilename(pszPathPart, "python", nullptr)); + std::string osPythonBinary( + CPLFormFilenameSafe(pszPathPart, "python", nullptr)); if (iTry == 0) osPythonBinary += "3"; - if (lstat(osPythonBinary, &sStat) != 0) + if (lstat(osPythonBinary.c_str(), &sStat) != 0) continue; CPLDebug("GDAL", "Found %s", osPythonBinary.c_str()); @@ -296,8 +296,9 @@ static bool LoadPythonAPI() const int nBufSize = 2048; std::vector oFilename(nBufSize); char *szPointerFilename = &oFilename[0]; - int nBytes = static_cast(readlink( - osPythonBinary, szPointerFilename, nBufSize)); + int nBytes = static_cast( + readlink(osPythonBinary.c_str(), + szPointerFilename, nBufSize)); if (nBytes != -1) { szPointerFilename[std::min(nBytes, @@ -309,14 +310,17 @@ static bool LoadPythonAPI() if (STARTS_WITH(osFilename, "python")) { - CPLString osResolvedFullLink; + std::string osResolvedFullLink; // If the filename is again a symlink, // resolve it if (CPLIsFilenameRelative(osFilename)) { - osResolvedFullLink = CPLFormFilename( - CPLGetPath(osPythonBinary), - osFilename, nullptr); + osResolvedFullLink = + CPLFormFilenameSafe( + CPLGetPathSafe( + osPythonBinary.c_str()) + .c_str(), + osFilename, nullptr); } else { @@ -325,8 +329,8 @@ static bool LoadPythonAPI() if (oSetAlreadyTriedLinks.find( osResolvedFullLink) == oSetAlreadyTriedLinks.end() && - lstat(osResolvedFullLink, &sStat) == - 0 && + lstat(osResolvedFullLink.c_str(), + &sStat) == 0 && S_ISLNK(sStat.st_mode)) { osPythonBinary = @@ -517,7 +521,7 @@ static bool LoadPythonAPI() // in the PATH if (libHandle == nullptr) { - CPLString osDLLName; + std::string osDLLName; char *pszPath = getenv("PATH"); if (pszPath != nullptr #ifdef DEBUG @@ -533,11 +537,11 @@ static bool LoadPythonAPI() for (const char *pszPathPart : aosPathParts) { VSIStatBufL sStat; - CPLString osPythonBinary( - CPLFormFilename(pszPathPart, "python.exe", nullptr)); + std::string osPythonBinary(CPLFormFilenameSafe( + pszPathPart, "python.exe", nullptr)); if (iTry == 1) osPythonBinary += "3"; - if (VSIStatL(osPythonBinary, &sStat) != 0) + if (VSIStatL(osPythonBinary.c_str(), &sStat) != 0) continue; CPLDebug("GDAL", "Found %s", osPythonBinary.c_str()); @@ -552,9 +556,10 @@ static bool LoadPythonAPI() STARTS_WITH_CI(pszFilename, "libpython3.")) && // do not load minimum API dll !EQUAL(pszFilename, "python3.dll") && - EQUAL(CPLGetExtension(pszFilename), "dll")) + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), + "dll")) { - osDLLName = CPLFormFilename( + osDLLName = CPLFormFilenameSafe( pszPathPart, pszFilename, nullptr); osPythonBinaryUsed = osPythonBinary; break; @@ -565,16 +570,18 @@ static bool LoadPythonAPI() // In python3.2, the dll is in the DLLs subdirectory if (osDLLName.empty()) { - const CPLString osDLLsDir( - CPLFormFilename(pszPathPart, "DLLs", nullptr)); - const CPLStringList aosFiles(VSIReadDir(osDLLsDir)); + const std::string osDLLsDir( + CPLFormFilenameSafe(pszPathPart, "DLLs", nullptr)); + const CPLStringList aosFiles( + VSIReadDir(osDLLsDir.c_str())); for (const char *pszFilename : aosFiles) { if (STARTS_WITH_CI(pszFilename, "python") && - EQUAL(CPLGetExtension(pszFilename), "dll")) + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), + "dll")) { - osDLLName = CPLFormFilename( - osDLLsDir, pszFilename, nullptr); + osDLLName = CPLFormFilenameSafe( + osDLLsDir.c_str(), pszFilename, nullptr); break; } } @@ -593,7 +600,7 @@ static bool LoadPythonAPI() UINT uOldErrorMode; uOldErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); - libHandle = LoadLibrary(osDLLName); + libHandle = LoadLibrary(osDLLName.c_str()); SetErrorMode(uOldErrorMode); if (libHandle != nullptr) { @@ -646,13 +653,14 @@ static bool LoadPythonAPI() #ifdef _WIN32 if (!osPythonBinaryUsed.empty() && getenv("PYTHONHOME") == nullptr) { - const char *pszPythonHome = CPLGetDirname(osPythonBinaryUsed.c_str()); + std::string osPythonHome = + CPLGetDirnameSafe(osPythonBinaryUsed.c_str()); VSIStatBufL sStat; bool bOK = false; // Test Windows Conda layout - const char *pszDirEncodings = - CPLFormFilename(pszPythonHome, "lib/encodings", nullptr); - if (VSIStatL(pszDirEncodings, &sStat) == 0) + std::string osDirEncodings = + CPLFormFilenameSafe(osPythonHome.c_str(), "lib/encodings", nullptr); + if (VSIStatL(osDirEncodings.c_str(), &sStat) == 0) { bOK = true; } @@ -663,13 +671,13 @@ static bool LoadPythonAPI() CSLTokenizeString2(osPythonVersion.c_str(), ".", 0)); if (aosVersionTokens.size() >= 3) { - pszPythonHome = CPLGetDirname(pszPythonHome); - pszDirEncodings = CPLFormFilename( - pszPythonHome, + osPythonHome = CPLGetDirnameSafe(osPythonHome.c_str()); + osDirEncodings = CPLFormFilenameSafe( + osPythonHome.c_str(), CPLSPrintf("lib/python%s.%s/encodings", aosVersionTokens[0], aosVersionTokens[1]), nullptr); - if (VSIStatL(pszDirEncodings, &sStat) == 0) + if (VSIStatL(osDirEncodings.c_str(), &sStat) == 0) { bOK = true; } @@ -678,12 +686,13 @@ static bool LoadPythonAPI() if (bOK) { static wchar_t wszPythonHome[4096]; - wchar_t *pwszPythonHome = - CPLRecodeToWChar(pszPythonHome, CPL_ENC_UTF8, CPL_ENC_UCS2); + wchar_t *pwszPythonHome = CPLRecodeToWChar( + osPythonHome.c_str(), CPL_ENC_UTF8, CPL_ENC_UCS2); const size_t nLength = wcslen(pwszPythonHome) + 1; if (nLength <= sizeof(wszPythonHome)) { - CPLDebug("GDAL", "Call Py_SetPythonHome(%s)", pszPythonHome); + CPLDebug("GDAL", "Call Py_SetPythonHome(%s)", + osPythonHome.c_str()); memcpy(wszPythonHome, pwszPythonHome, nLength * sizeof(wchar_t)); // The string must reside in static storage diff --git a/gcore/gdalpythondriverloader.cpp b/gcore/gdalpythondriverloader.cpp index 364f35d8dfeb..adc7bb7b25ab 100644 --- a/gcore/gdalpythondriverloader.cpp +++ b/gcore/gdalpythondriverloader.cpp @@ -1617,7 +1617,7 @@ bool PythonPluginDriver::LoadPlugin() GetPyExceptionString().c_str()); return false; } - const CPLString osPluginModuleName(CPLGetBasename(m_osFilename)); + const CPLString osPluginModuleName(CPLGetBasenameSafe(m_osFilename)); PyObject *poModule = PyImport_ExecCodeModule(osPluginModuleName, poCompiledString); Py_DecRef(poCompiledString); @@ -1956,22 +1956,22 @@ void GDALDriverManager::AutoLoadPythonDrivers() const int nSearchPaths = CSLCount(papszSearchPaths); for (int iDir = 0; iDir < nSearchPaths; ++iDir) { - CPLString osABISpecificDir = - CPLFormFilename(papszSearchPaths[iDir], osABIVersion, nullptr); + std::string osABISpecificDir = + CPLFormFilenameSafe(papszSearchPaths[iDir], osABIVersion, nullptr); VSIStatBufL sStatBuf; - if (VSIStatL(osABISpecificDir, &sStatBuf) != 0) + if (VSIStatL(osABISpecificDir.c_str(), &sStatBuf) != 0) osABISpecificDir = papszSearchPaths[iDir]; - char **papszFiles = CPLReadDir(osABISpecificDir); + char **papszFiles = CPLReadDir(osABISpecificDir.c_str()); for (int i = 0; papszFiles && papszFiles[i]; i++) { if ((STARTS_WITH_CI(papszFiles[i], "gdal_") || STARTS_WITH_CI(papszFiles[i], "ogr_")) && - EQUAL(CPLGetExtension(papszFiles[i]), "py")) + EQUAL(CPLGetExtensionSafe(papszFiles[i]).c_str(), "py")) { - aosPythonFiles.push_back( - CPLFormFilename(osABISpecificDir, papszFiles[i], nullptr)); + aosPythonFiles.push_back(CPLFormFilenameSafe( + osABISpecificDir.c_str(), papszFiles[i], nullptr)); } } CSLDestroy(papszFiles); diff --git a/gcore/mdreader/reader_alos.cpp b/gcore/mdreader/reader_alos.cpp index a9c2a6b67238..3ec9fc68a6cc 100644 --- a/gcore/mdreader/reader_alos.cpp +++ b/gcore/mdreader/reader_alos.cpp @@ -31,18 +31,18 @@ GDALMDReaderALOS::GDALMDReaderALOS(const char *pszPath, char **papszSiblingFiles) : GDALMDReaderBase(pszPath, papszSiblingFiles) { - CPLString osDirName = CPLGetDirname(pszPath); - CPLString osBaseName = CPLGetBasename(pszPath); + const CPLString osDirName = CPLGetDirnameSafe(pszPath); + const CPLString osBaseName = CPLGetBasenameSafe(pszPath); CPLString osIMDSourceFilename = - CPLFormFilename(osDirName, "summary", ".txt"); + CPLFormFilenameSafe(osDirName, "summary", ".txt"); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); } else { - osIMDSourceFilename = CPLFormFilename(osDirName, "SUMMARY", ".TXT"); + osIMDSourceFilename = CPLFormFilenameSafe(osDirName, "SUMMARY", ".TXT"); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); @@ -53,16 +53,18 @@ GDALMDReaderALOS::GDALMDReaderALOS(const char *pszPath, { // check if this is separate band or whole image // test without 6 symbols - CPLString osHDRFileName = CPLFormFilename( - osDirName, CPLSPrintf("HDR%s", osBaseName + 6), "txt"); + CPLString osHDRFileName = CPLFormFilenameSafe( + osDirName, (std::string("HDR") + (osBaseName.c_str() + 6)).c_str(), + "txt"); if (CPLCheckForFile(&osHDRFileName[0], papszSiblingFiles)) { m_osHDRSourceFilename = std::move(osHDRFileName); } else { - osHDRFileName = CPLFormFilename( - osDirName, CPLSPrintf("HDR%s", osBaseName + 6), "TXT"); + osHDRFileName = CPLFormFilenameSafe( + osDirName, + (std::string("HDR") + (osBaseName.c_str() + 6)).c_str(), "TXT"); if (CPLCheckForFile(&osHDRFileName[0], papszSiblingFiles)) { m_osHDRSourceFilename = std::move(osHDRFileName); @@ -73,16 +75,18 @@ GDALMDReaderALOS::GDALMDReaderALOS(const char *pszPath, // test without 3 symbols if (osBaseName.size() >= 3 && m_osHDRSourceFilename.empty()) { - CPLString osHDRFileName = CPLFormFilename( - osDirName, CPLSPrintf("HDR%s", osBaseName + 3), "txt"); + CPLString osHDRFileName = CPLFormFilenameSafe( + osDirName, (std::string("HDR") + (osBaseName.c_str() + 3)).c_str(), + "txt"); if (CPLCheckForFile(&osHDRFileName[0], papszSiblingFiles)) { m_osHDRSourceFilename = std::move(osHDRFileName); } else { - osHDRFileName = CPLFormFilename( - osDirName, CPLSPrintf("HDR%s", osBaseName + 3), "TXT"); + osHDRFileName = CPLFormFilenameSafe( + osDirName, + (std::string("HDR") + (osBaseName.c_str() + 3)).c_str(), "TXT"); if (CPLCheckForFile(&osHDRFileName[0], papszSiblingFiles)) { m_osHDRSourceFilename = std::move(osHDRFileName); @@ -93,16 +97,18 @@ GDALMDReaderALOS::GDALMDReaderALOS(const char *pszPath, // test without 6 symbols if (osBaseName.size() >= 6) { - CPLString osRPCFileName = CPLFormFilename( - osDirName, CPLSPrintf("RPC%s", osBaseName + 6), "txt"); + CPLString osRPCFileName = CPLFormFilenameSafe( + osDirName, (std::string("RPC") + (osBaseName.c_str() + 6)).c_str(), + "txt"); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPCFileName); } else { - osRPCFileName = CPLFormFilename( - osDirName, CPLSPrintf("RPC%s", osBaseName + 6), "TXT"); + osRPCFileName = CPLFormFilenameSafe( + osDirName, + (std::string("RPC") + (osBaseName.c_str() + 6)).c_str(), "TXT"); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPCFileName); @@ -113,16 +119,18 @@ GDALMDReaderALOS::GDALMDReaderALOS(const char *pszPath, // test without 3 symbols if (osBaseName.size() >= 3 && m_osRPBSourceFilename.empty()) { - CPLString osRPCFileName = CPLFormFilename( - osDirName, CPLSPrintf("RPC%s", osBaseName + 3), "txt"); + CPLString osRPCFileName = CPLFormFilenameSafe( + osDirName, (std::string("RPC") + (osBaseName.c_str() + 3)).c_str(), + "txt"); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPCFileName); } else { - osRPCFileName = CPLFormFilename( - osDirName, CPLSPrintf("RPC%s", osBaseName + 3), "TXT"); + osRPCFileName = CPLFormFilenameSafe( + osDirName, + (std::string("RPC") + (osBaseName.c_str() + 3)).c_str(), "TXT"); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPCFileName); diff --git a/gcore/mdreader/reader_eros.cpp b/gcore/mdreader/reader_eros.cpp index e2874ed5bc49..820770825d88 100644 --- a/gcore/mdreader/reader_eros.cpp +++ b/gcore/mdreader/reader_eros.cpp @@ -30,8 +30,8 @@ GDALMDReaderEROS::GDALMDReaderEROS(const char *pszPath, char **papszSiblingFiles) : GDALMDReaderBase(pszPath, papszSiblingFiles) { - CPLString osBaseName = CPLGetBasename(pszPath); - CPLString osDirName = CPLGetDirname(pszPath); + const CPLString osBaseName = CPLGetBasenameSafe(pszPath); + const CPLString osDirName = CPLGetDirnameSafe(pszPath); char szMetadataName[512] = {0}; size_t i; if (osBaseName.size() > 511) @@ -41,7 +41,7 @@ GDALMDReaderEROS::GDALMDReaderEROS(const char *pszPath, if (STARTS_WITH_CI(osBaseName + i, ".")) { std::string osPassFileName = - CPLFormFilename(osDirName, szMetadataName, "pass"); + CPLFormFilenameSafe(osDirName, szMetadataName, "pass"); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osPassFileName); @@ -50,7 +50,7 @@ GDALMDReaderEROS::GDALMDReaderEROS(const char *pszPath, else { osPassFileName = - CPLFormFilename(osDirName, szMetadataName, "PASS"); + CPLFormFilenameSafe(osDirName, szMetadataName, "PASS"); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osPassFileName); @@ -64,14 +64,15 @@ GDALMDReaderEROS::GDALMDReaderEROS(const char *pszPath, if (m_osIMDSourceFilename.empty()) { std::string osPassFileName = - CPLFormFilename(osDirName, szMetadataName, "pass"); + CPLFormFilenameSafe(osDirName, szMetadataName, "pass"); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osPassFileName); } else { - osPassFileName = CPLFormFilename(osDirName, szMetadataName, "PASS"); + osPassFileName = + CPLFormFilenameSafe(osDirName, szMetadataName, "PASS"); if (CPLCheckForFile(&osPassFileName[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osPassFileName); @@ -80,14 +81,14 @@ GDALMDReaderEROS::GDALMDReaderEROS(const char *pszPath, } std::string osRPCFileName = - CPLFormFilename(osDirName, szMetadataName, "rpc"); + CPLFormFilenameSafe(osDirName, szMetadataName, "rpc"); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPCFileName); } else { - osRPCFileName = CPLFormFilename(osDirName, szMetadataName, "RPC"); + osRPCFileName = CPLFormFilenameSafe(osDirName, szMetadataName, "RPC"); if (CPLCheckForFile(&osRPCFileName[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPCFileName); diff --git a/gcore/mdreader/reader_geo_eye.cpp b/gcore/mdreader/reader_geo_eye.cpp index b03e5647217e..0b7a204c4cad 100644 --- a/gcore/mdreader/reader_geo_eye.cpp +++ b/gcore/mdreader/reader_geo_eye.cpp @@ -33,8 +33,8 @@ GDALMDReaderGeoEye::GDALMDReaderGeoEye(const char *pszPath, : GDALMDReaderBase(pszPath, papszSiblingFiles) { - const CPLString osBaseName = CPLGetBasename(pszPath); - const CPLString osDirName = CPLGetDirname(pszPath); + const CPLString osBaseName = CPLGetBasenameSafe(pszPath); + const CPLString osDirName = CPLGetDirnameSafe(pszPath); // get _metadata.txt file @@ -47,7 +47,7 @@ GDALMDReaderGeoEye::GDALMDReaderGeoEye(const char *pszPath, osRadixMetadataName.resize(i); // form metadata file name - std::string osIMDSourceFilename = CPLFormFilename( + std::string osIMDSourceFilename = CPLFormFilenameSafe( osDirName, (osRadixMetadataName + "_metadata.txt").c_str(), nullptr); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { @@ -55,7 +55,7 @@ GDALMDReaderGeoEye::GDALMDReaderGeoEye(const char *pszPath, } else { - osIMDSourceFilename = CPLFormFilename( + osIMDSourceFilename = CPLFormFilenameSafe( osDirName, (osRadixMetadataName + "_METADATA.txt").c_str(), nullptr); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) @@ -67,15 +67,15 @@ GDALMDReaderGeoEye::GDALMDReaderGeoEye(const char *pszPath, // get _rpc.txt file std::string osRPBSourceFilename = - CPLFormFilename(osDirName, (osBaseName + "_rpc").c_str(), "txt"); + CPLFormFilenameSafe(osDirName, (osBaseName + "_rpc").c_str(), "txt"); if (CPLCheckForFile(&osRPBSourceFilename[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPBSourceFilename); } else { - osRPBSourceFilename = - CPLFormFilename(osDirName, (osBaseName + "_RPC").c_str(), "TXT"); + osRPBSourceFilename = CPLFormFilenameSafe( + osDirName, (osBaseName + "_RPC").c_str(), "TXT"); if (CPLCheckForFile(&osRPBSourceFilename[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPBSourceFilename); diff --git a/gcore/mdreader/reader_landsat.cpp b/gcore/mdreader/reader_landsat.cpp index 08d378f7efca..daebf700d95c 100644 --- a/gcore/mdreader/reader_landsat.cpp +++ b/gcore/mdreader/reader_landsat.cpp @@ -30,9 +30,9 @@ GDALMDReaderLandsat::GDALMDReaderLandsat(const char *pszPath, char **papszSiblingFiles) : GDALMDReaderBase(pszPath, papszSiblingFiles) { - const char *pszBaseName = CPLGetBasename(pszPath); - const char *pszDirName = CPLGetDirname(pszPath); - size_t nBaseNameLen = strlen(pszBaseName); + const std::string osBaseName = CPLGetBasenameSafe(pszPath); + const std::string osDirName = CPLGetDirnameSafe(pszPath); + size_t nBaseNameLen = osBaseName.size(); if (nBaseNameLen > 511) return; @@ -41,9 +41,8 @@ GDALMDReaderLandsat::GDALMDReaderLandsat(const char *pszPath, size_t i; for (i = 0; i < nBaseNameLen; i++) { - szMetadataName[i] = pszBaseName[i]; - if (STARTS_WITH_CI(pszBaseName + i, "_B") || - STARTS_WITH_CI(pszBaseName + i, "_b")) + szMetadataName[i] = osBaseName[i]; + if (STARTS_WITH_CI(osBaseName.c_str() + i, "_B")) { break; } @@ -53,7 +52,7 @@ GDALMDReaderLandsat::GDALMDReaderLandsat(const char *pszPath, CPLStrlcpy(szMetadataName + i, "_MTL.txt", 9); std::string osIMDSourceFilename = - CPLFormFilename(pszDirName, szMetadataName, nullptr); + CPLFormFilenameSafe(osDirName.c_str(), szMetadataName, nullptr); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); @@ -62,7 +61,7 @@ GDALMDReaderLandsat::GDALMDReaderLandsat(const char *pszPath, { CPLStrlcpy(szMetadataName + i, "_MTL.TXT", 9); osIMDSourceFilename = - CPLFormFilename(pszDirName, szMetadataName, nullptr); + CPLFormFilenameSafe(osDirName.c_str(), szMetadataName, nullptr); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); diff --git a/gcore/mdreader/reader_orb_view.cpp b/gcore/mdreader/reader_orb_view.cpp index 256d88fa810c..498f9fb4029e 100644 --- a/gcore/mdreader/reader_orb_view.cpp +++ b/gcore/mdreader/reader_orb_view.cpp @@ -33,19 +33,19 @@ GDALMDReaderOrbView::GDALMDReaderOrbView(const char *pszPath, GDALFindAssociatedFile(pszPath, "PVL", papszSiblingFiles, 0)), m_osRPBSourceFilename(CPLString()) { - const char *pszBaseName = CPLGetBasename(pszPath); - const char *pszDirName = CPLGetDirname(pszPath); + const std::string osBaseName = CPLGetBasenameSafe(pszPath); + const std::string osDirName = CPLGetDirnameSafe(pszPath); - std::string osRPBSourceFilename = - CPLFormFilename(pszDirName, CPLSPrintf("%s_rpc", pszBaseName), "txt"); + std::string osRPBSourceFilename = CPLFormFilenameSafe( + osDirName.c_str(), (osBaseName + "_rpc").c_str(), "txt"); if (CPLCheckForFile(&osRPBSourceFilename[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPBSourceFilename); } else { - osRPBSourceFilename = CPLFormFilename( - pszDirName, CPLSPrintf("%s_RPC", pszBaseName), "TXT"); + osRPBSourceFilename = CPLFormFilenameSafe( + osDirName.c_str(), (osBaseName + "_RPC").c_str(), "TXT"); if (CPLCheckForFile(&osRPBSourceFilename[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPBSourceFilename); diff --git a/gcore/mdreader/reader_pleiades.cpp b/gcore/mdreader/reader_pleiades.cpp index e933713d6f5a..ad51e65ad07a 100644 --- a/gcore/mdreader/reader_pleiades.cpp +++ b/gcore/mdreader/reader_pleiades.cpp @@ -35,17 +35,19 @@ GDALMDReaderPleiades::GDALMDReaderPleiades(const char *pszPath, : GDALMDReaderBase(pszPath, papszSiblingFiles), m_osBaseFilename(pszPath), m_osIMDSourceFilename(CPLString()), m_osRPBSourceFilename(CPLString()) { - const CPLString osBaseName = CPLGetBasename(pszPath); + const CPLString osBaseName = CPLGetBasenameSafe(pszPath); const size_t nBaseNameLen = osBaseName.size(); if (nBaseNameLen < 4 || nBaseNameLen > 511) return; - const CPLString osDirName = CPLGetDirname(pszPath); + const CPLString osDirName = CPLGetDirnameSafe(pszPath); - std::string osIMDSourceFilename = CPLFormFilename( - osDirName, CPLSPrintf("DIM_%s", osBaseName.c_str() + 4), "XML"); - std::string osRPBSourceFilename = CPLFormFilename( - osDirName, CPLSPrintf("RPC_%s", osBaseName.c_str() + 4), "XML"); + std::string osIMDSourceFilename = CPLFormFilenameSafe( + osDirName, (std::string("DIM_") + (osBaseName.c_str() + 4)).c_str(), + "XML"); + std::string osRPBSourceFilename = CPLFormFilenameSafe( + osDirName, (std::string("RPC_") + (osBaseName.c_str() + 4)).c_str(), + "XML"); // find last underline char sBaseName[512]; @@ -83,8 +85,8 @@ GDALMDReaderPleiades::GDALMDReaderPleiades(const char *pszPath, } else { - osIMDSourceFilename = - CPLFormFilename(osDirName, CPLSPrintf("DIM_%s", sBaseName), "XML"); + osIMDSourceFilename = CPLFormFilenameSafe( + osDirName, ("DIM_" + std::string(sBaseName)).c_str(), "XML"); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); @@ -97,8 +99,8 @@ GDALMDReaderPleiades::GDALMDReaderPleiades(const char *pszPath, } else { - osRPBSourceFilename = - CPLFormFilename(osDirName, CPLSPrintf("RPC_%s", sBaseName), "XML"); + osRPBSourceFilename = CPLFormFilenameSafe( + osDirName, ("RPC_" + std::string(sBaseName)).c_str(), "XML"); if (CPLCheckForFile(&osRPBSourceFilename[0], papszSiblingFiles)) { m_osRPBSourceFilename = std::move(osRPBSourceFilename); diff --git a/gcore/mdreader/reader_rapid_eye.cpp b/gcore/mdreader/reader_rapid_eye.cpp index 53e67fb710a8..625039184216 100644 --- a/gcore/mdreader/reader_rapid_eye.cpp +++ b/gcore/mdreader/reader_rapid_eye.cpp @@ -28,19 +28,19 @@ GDALMDReaderRapidEye::GDALMDReaderRapidEye(const char *pszPath, char **papszSiblingFiles) : GDALMDReaderBase(pszPath, papszSiblingFiles) { - const char *pszDirName = CPLGetDirname(pszPath); - const char *pszBaseName = CPLGetBasename(pszPath); + const std::string osDirName = CPLGetDirnameSafe(pszPath); + const std::string osBaseName = CPLGetBasenameSafe(pszPath); - std::string osIMDSourceFilename = CPLFormFilename( - pszDirName, CPLSPrintf("%s_metadata", pszBaseName), "xml"); + std::string osIMDSourceFilename = CPLFormFilenameSafe( + osDirName.c_str(), (osBaseName + "_metadata").c_str(), "xml"); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osXMLSourceFilename = std::move(osIMDSourceFilename); } else { - osIMDSourceFilename = CPLFormFilename( - pszDirName, CPLSPrintf("%s_METADATA", pszBaseName), "XML"); + osIMDSourceFilename = CPLFormFilenameSafe( + osDirName.c_str(), (osBaseName + "_METADATA").c_str(), "XML"); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osXMLSourceFilename = std::move(osIMDSourceFilename); diff --git a/gcore/mdreader/reader_spot.cpp b/gcore/mdreader/reader_spot.cpp index 9afea82598cb..db991034b8a8 100644 --- a/gcore/mdreader/reader_spot.cpp +++ b/gcore/mdreader/reader_spot.cpp @@ -31,12 +31,12 @@ GDALMDReaderSpot::GDALMDReaderSpot(const char *pszPath, char **papszSiblingFiles) : GDALMDReaderPleiades(pszPath, papszSiblingFiles) { - const char *pszDirName = CPLGetDirname(pszPath); + const std::string osDirName = CPLGetDirnameSafe(pszPath); if (m_osIMDSourceFilename.empty()) { std::string osIMDSourceFilename = - CPLFormFilename(pszDirName, "METADATA.DIM", nullptr); + CPLFormFilenameSafe(osDirName.c_str(), "METADATA.DIM", nullptr); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { @@ -45,7 +45,7 @@ GDALMDReaderSpot::GDALMDReaderSpot(const char *pszPath, else { osIMDSourceFilename = - CPLFormFilename(pszDirName, "metadata.dim", nullptr); + CPLFormFilenameSafe(osDirName.c_str(), "metadata.dim", nullptr); if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); @@ -61,7 +61,7 @@ GDALMDReaderSpot::GDALMDReaderSpot(const char *pszPath, if (EQUAL(CPLGetFilename(pszPath), "IMAGERY.TIF")) { std::string osIMDSourceFilename = - CPLSPrintf("%s\\METADATA.DIM", CPLGetPath(pszPath)); + CPLGetPathSafe(pszPath) + "\\METADATA.DIM"; if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { @@ -70,7 +70,7 @@ GDALMDReaderSpot::GDALMDReaderSpot(const char *pszPath, else { osIMDSourceFilename = - CPLSPrintf("%s\\metadata.dim", CPLGetPath(pszPath)); + CPLGetPathSafe(pszPath) + "\\metadata.dim"; if (CPLCheckForFile(&osIMDSourceFilename[0], papszSiblingFiles)) { m_osIMDSourceFilename = std::move(osIMDSourceFilename); diff --git a/gcore/overview.cpp b/gcore/overview.cpp index 44f5b7c84c9b..4aa10da83ff8 100644 --- a/gcore/overview.cpp +++ b/gcore/overview.cpp @@ -5431,7 +5431,7 @@ CPLErr GDALRegenerateOverviewsMultiBand( } if (osTmpFilename.empty()) { - osTmpFilename = CPLGenerateTempFilename(nullptr); + osTmpFilename = CPLGenerateTempFilenameSafe(nullptr); osTmpFilename += ".tif"; } CPLDebug("GDAL", diff --git a/gcore/tilematrixset.cpp b/gcore/tilematrixset.cpp index 21cd649543e6..3a6058785e7c 100644 --- a/gcore/tilematrixset.cpp +++ b/gcore/tilematrixset.cpp @@ -34,7 +34,8 @@ std::set TileMatrixSet::listPredefinedTileMatrixSets() const char *pszSomeFile = CPLFindFile("gdal", "tms_NZTM2000.json"); if (pszSomeFile) { - CPLStringList aosList(VSIReadDir(CPLGetDirname(pszSomeFile))); + CPLStringList aosList( + VSIReadDir(CPLGetDirnameSafe(pszSomeFile).c_str())); for (int i = 0; i < aosList.size(); i++) { const size_t nLen = strlen(aosList[i]); diff --git a/gnm/gnm_frmts/file/gnmfiledriver.cpp b/gnm/gnm_frmts/file/gnmfiledriver.cpp index 54b084996bf6..d7ed76ef78a0 100644 --- a/gnm/gnm_frmts/file/gnmfiledriver.cpp +++ b/gnm/gnm_frmts/file/gnmfiledriver.cpp @@ -54,11 +54,12 @@ static int GNMFileDriverIdentify(GDALOpenInfo *poOpenInfo) if (EQUAL(papszFiles[i], ".") || EQUAL(papszFiles[i], "..")) continue; - if (EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_META)) + const CPLString osBasename = CPLGetBasenameSafe(papszFiles[i]); + if (EQUAL(osBasename, GNM_SYSLAYER_META)) bHasMeta = true; - else if (EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_GRAPH)) + else if (EQUAL(osBasename, GNM_SYSLAYER_GRAPH)) bHasGraph = true; - else if (EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_FEATURES)) + else if (EQUAL(osBasename, GNM_SYSLAYER_FEATURES)) bHasFeatures = true; if (bHasMeta && bHasGraph && bHasFeatures) diff --git a/gnm/gnm_frmts/file/gnmfilenetwork.cpp b/gnm/gnm_frmts/file/gnmfilenetwork.cpp index cb1a1d08fc3b..54dcb7453e67 100644 --- a/gnm/gnm_frmts/file/gnmfilenetwork.cpp +++ b/gnm/gnm_frmts/file/gnmfilenetwork.cpp @@ -74,10 +74,10 @@ CPLErr GNMFileNetwork::Open(GDALOpenInfo *poOpenInfo) if (EQUAL(papszFiles[i], ".") || EQUAL(papszFiles[i], "..")) continue; - if (EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_META)) + if (EQUAL(CPLGetBasenameSafe(papszFiles[i]).c_str(), GNM_SYSLAYER_META)) { - soMetadatafile = - CPLFormFilename(m_soNetworkFullName, papszFiles[i], nullptr); + soMetadatafile = CPLFormFilenameSafe(m_soNetworkFullName, + papszFiles[i], nullptr); break; } } @@ -100,10 +100,10 @@ CPLErr GNMFileNetwork::Open(GDALOpenInfo *poOpenInfo) } m_poLayerDriver = m_pMetadataDS->GetDriver(); - CPLString osExt = CPLGetExtension(soMetadatafile); + const CPLString osExt = CPLGetExtensionSafe(soMetadatafile); - CPLString soGraphfile = - CPLFormFilename(m_soNetworkFullName, GNM_SYSLAYER_GRAPH, osExt); + const CPLString soGraphfile = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SYSLAYER_GRAPH, osExt); m_pGraphDS = (GDALDataset *)GDALOpenEx(soGraphfile, GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr); @@ -119,8 +119,8 @@ CPLErr GNMFileNetwork::Open(GDALOpenInfo *poOpenInfo) return CE_Failure; } - CPLString soFeaturesfile = - CPLFormFilename(m_soNetworkFullName, GNM_SYSLAYER_FEATURES, osExt); + const CPLString soFeaturesfile = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SYSLAYER_FEATURES, osExt); m_pFeaturesDS = (GDALDataset *)GDALOpenEx(soFeaturesfile, GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr); @@ -178,17 +178,18 @@ int GNMFileNetwork::CheckNetworkExist(const char *pszFilename, if (EQUAL(papszFiles[i], ".") || EQUAL(papszFiles[i], "..")) continue; - if (EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_META) || - EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_GRAPH) || - EQUAL(CPLGetBasename(papszFiles[i]), GNM_SYSLAYER_FEATURES) || + const CPLString osBasename = CPLGetBasenameSafe(papszFiles[i]); + if (EQUAL(osBasename, GNM_SYSLAYER_META) || + EQUAL(osBasename, GNM_SYSLAYER_GRAPH) || + EQUAL(osBasename, GNM_SYSLAYER_FEATURES) || EQUAL(papszFiles[i], GNM_SRSFILENAME)) { if (bOverwrite) { - const char *pszDeleteFile = CPLFormFilename( + const std::string osDeleteFile = CPLFormFilenameSafe( m_soNetworkFullName, papszFiles[i], nullptr); - CPLDebug("GNM", "Delete file: %s", pszDeleteFile); - if (VSIUnlink(pszDeleteFile) != 0) + CPLDebug("GNM", "Delete file: %s", osDeleteFile.c_str()); + if (VSIUnlink(osDeleteFile.c_str()) != 0) { return TRUE; } @@ -252,8 +253,8 @@ CPLErr GNMFileNetwork::CreateMetadataLayerFromFile(const char *pszFilename, return eResult; const char *pszExt = m_poLayerDriver->GetMetadataItem(GDAL_DMD_EXTENSION); - CPLString osDSFileName = - CPLFormFilename(m_soNetworkFullName, GNM_SYSLAYER_META, pszExt); + const CPLString osDSFileName = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SYSLAYER_META, pszExt); m_pMetadataDS = m_poLayerDriver->Create(osDSFileName, 0, 0, 0, GDT_Unknown, nullptr); @@ -271,9 +272,9 @@ CPLErr GNMFileNetwork::StoreNetworkSrs() { if (m_oSRS.IsEmpty()) return CE_None; - const char *pszSrsFileName = - CPLFormFilename(m_soNetworkFullName, GNM_SRSFILENAME, nullptr); - VSILFILE *fpSrsPrj = VSIFOpenL(pszSrsFileName, "w"); + const std::string osSrsFileName = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SRSFILENAME, nullptr); + VSILFILE *fpSrsPrj = VSIFOpenL(osSrsFileName.c_str(), "w"); if (fpSrsPrj != nullptr) { char *pszWKT = nullptr; @@ -294,9 +295,9 @@ CPLErr GNMFileNetwork::StoreNetworkSrs() CPLErr GNMFileNetwork::LoadNetworkSrs() { - const char *pszSrsFileName = - CPLFormFilename(m_soNetworkFullName, GNM_SRSFILENAME, nullptr); - char **papszLines = CSLLoad(pszSrsFileName); + const std::string osSrsFileName = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SRSFILENAME, nullptr); + char **papszLines = CSLLoad(osSrsFileName.c_str()); if (nullptr == papszLines) { CPLError(CE_Failure, CPLE_AppDefined, "Loading of '%s' layer failed", @@ -316,10 +317,11 @@ CPLErr GNMFileNetwork::DeleteMetadataLayer() { if (nullptr != m_pMetadataDS) { - const char *pszSrsFileName = - CPLFormFilename(m_soNetworkFullName, GNM_SRSFILENAME, nullptr); + const std::string osSrsFileName = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SRSFILENAME, nullptr); VSIUnlink( - pszSrsFileName); // just try to delete as file may not be existed + osSrsFileName + .c_str()); // just try to delete as file may not be existed return m_pMetadataDS->DeleteLayer(0) == OGRERR_NONE ? CE_None : CE_Failure; } @@ -338,8 +340,8 @@ CPLErr GNMFileNetwork::CreateGraphLayerFromFile(const char *pszFilename, return eResult; const char *pszExt = m_poLayerDriver->GetMetadataItem(GDAL_DMD_EXTENSION); - CPLString osDSFileName = - CPLFormFilename(m_soNetworkFullName, GNM_SYSLAYER_GRAPH, pszExt); + const CPLString osDSFileName = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SYSLAYER_GRAPH, pszExt); m_pGraphDS = m_poLayerDriver->Create(osDSFileName, 0, 0, 0, GDT_Unknown, nullptr); @@ -375,8 +377,8 @@ CPLErr GNMFileNetwork::CreateFeaturesLayerFromFile(const char *pszFilename, return eResult; const char *pszExt = m_poLayerDriver->GetMetadataItem(GDAL_DMD_EXTENSION); - CPLString osDSFileName = - CPLFormFilename(m_soNetworkFullName, GNM_SYSLAYER_FEATURES, pszExt); + const CPLString osDSFileName = + CPLFormFilenameSafe(m_soNetworkFullName, GNM_SYSLAYER_FEATURES, pszExt); m_pFeaturesDS = m_poLayerDriver->Create(osDSFileName, 0, 0, 0, GDT_Unknown, nullptr); @@ -423,8 +425,8 @@ CPLErr GNMFileNetwork::LoadNetworkLayer(const char *pszLayername) const char *pszExt = m_poLayerDriver->GetMetadataItem(GDAL_DMD_EXTENSION); - CPLString soFile = - CPLFormFilename(m_soNetworkFullName, pszLayername, pszExt); + const CPLString soFile = + CPLFormFilenameSafe(m_soNetworkFullName, pszLayername, pszExt); GDALDataset *poDS = (GDALDataset *)GDALOpenEx( soFile, GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr); if (nullptr == poDS) @@ -472,7 +474,7 @@ CPLErr GNMFileNetwork::FormPath(const char *pszFilename, char **papszOptions) return CE_Failure; } m_soNetworkFullName = - CPLFormFilename(pszFilename, pszNetworkName, nullptr); + CPLFormFilenameSafe(pszFilename, pszNetworkName, nullptr); CPLDebug("GNM", "Network name: %s", m_soNetworkFullName.c_str()); } @@ -550,7 +552,8 @@ OGRLayer *GNMFileNetwork::ICreateLayer(const char *pszName, // form path const char *pszExt = m_poLayerDriver->GetMetadataItem(GDAL_DMD_EXTENSION); - CPLString soPath = CPLFormFilename(m_soNetworkFullName, pszName, pszExt); + const CPLString soPath = + CPLFormFilenameSafe(m_soNetworkFullName, pszName, pszExt); GDALDataset *poDS = m_poLayerDriver->Create(soPath, 0, 0, 0, GDT_Unknown, papszOptions); diff --git a/ogr/ogr_geocoding.cpp b/ogr/ogr_geocoding.cpp index 0f99efb033c6..5b6aaafd363f 100644 --- a/ogr/ogr_geocoding.cpp +++ b/ogr/ogr_geocoding.cpp @@ -240,7 +240,7 @@ OGRGeocodingSessionH OGRGeocodeCreateSession(char **papszOptions) const char *pszCacheFilename = OGRGeocodeGetParameter( papszOptions, "CACHE_FILE", DEFAULT_CACHE_SQLITE); - CPLString osExt = CPLGetExtension(pszCacheFilename); + CPLString osExt = CPLGetExtensionSafe(pszCacheFilename); if (!(STARTS_WITH_CI(pszCacheFilename, "PG:") || EQUAL(osExt, "csv") || EQUAL(osExt, "sqlite"))) { @@ -394,7 +394,7 @@ static OGRLayer *OGRGeocodeGetCacheLayer(OGRGeocodingSessionH hSession, int *pnIdxBlob) { GDALDataset *poDS = hSession->poDS; - CPLString osExt = CPLGetExtension(hSession->pszCacheFilename); + CPLString osExt = CPLGetExtensionSafe(hSession->pszCacheFilename); if (poDS == nullptr) { diff --git a/ogr/ograpispy.cpp b/ogr/ograpispy.cpp index 316efa3ac7c2..145a55b14679 100644 --- a/ogr/ograpispy.cpp +++ b/ogr/ograpispy.cpp @@ -476,7 +476,7 @@ int OGRAPISpyOpenTakeSnapshot(const char *pszName, int bUpdate) CPLString osWorkingDir; while (true) { - osBaseDir = CPLFormFilename( + osBaseDir = CPLFormFilenameSafe( osSnapshotPath, CPLSPrintf("snapshot_%d", i), nullptr); if (VSIStatL(osBaseDir, &sStat) != 0) break; @@ -484,9 +484,9 @@ int OGRAPISpyOpenTakeSnapshot(const char *pszName, int bUpdate) } VSIMkdir(osSnapshotPath, 0777); VSIMkdir(osBaseDir, 0777); - osSrcDir = CPLFormFilename(osBaseDir, "source", nullptr); + osSrcDir = CPLFormFilenameSafe(osBaseDir, "source", nullptr); VSIMkdir(osSrcDir, 0777); - osWorkingDir = CPLFormFilename(osBaseDir, "working", nullptr); + osWorkingDir = CPLFormFilenameSafe(osBaseDir, "working", nullptr); VSIMkdir(osWorkingDir, 0777); OGRAPISpyFileReopen(); @@ -499,9 +499,9 @@ int OGRAPISpyOpenTakeSnapshot(const char *pszName, int bUpdate) fprintf(fpSpyFile, "os.mkdir('%s')\n", osWorkingDir.c_str()); for (char **papszIter = papszFileList; *papszIter; papszIter++) { - CPLString osSnapshotSrcFile = CPLFormFilename( + CPLString osSnapshotSrcFile = CPLFormFilenameSafe( osSrcDir, CPLGetFilename(*papszIter), nullptr); - CPLString osSnapshotWorkingFile = CPLFormFilename( + CPLString osSnapshotWorkingFile = CPLFormFilenameSafe( osWorkingDir, CPLGetFilename(*papszIter), nullptr); CPL_IGNORE_RET_VAL(CPLCopyFile(osSnapshotSrcFile, *papszIter)); CPL_IGNORE_RET_VAL( @@ -528,11 +528,12 @@ void OGRAPISpyOpen(const char *pszName, int bUpdate, int iSnapshot, CPLString osName; if (iSnapshot > 0) { - CPLString osBaseDir = CPLFormFilename( + CPLString osBaseDir = CPLFormFilenameSafe( osSnapshotPath, CPLSPrintf("snapshot_%d", iSnapshot), nullptr); - CPLString osWorkingDir = CPLFormFilename(osBaseDir, "working", nullptr); + CPLString osWorkingDir = + CPLFormFilenameSafe(osBaseDir, "working", nullptr); osName = - CPLFormFilename(osWorkingDir, CPLGetFilename(pszName), nullptr); + CPLFormFilenameSafe(osWorkingDir, CPLGetFilename(pszName), nullptr); pszName = osName.c_str(); if (*phDS != nullptr) diff --git a/ogr/ogrsf_frmts/adbc/ogradbcdataset.cpp b/ogr/ogrsf_frmts/adbc/ogradbcdataset.cpp index 2f5408c5c733..68085054ba87 100644 --- a/ogr/ogrsf_frmts/adbc/ogradbcdataset.cpp +++ b/ogr/ogrsf_frmts/adbc/ogradbcdataset.cpp @@ -218,8 +218,9 @@ bool OGRADBCDataset::Open(const GDALOpenInfo *poOpenInfo) const bool bIsSQLite3 = (pszADBCDriverName && EQUAL(pszADBCDriverName, "adbc_driver_sqlite")) || OGRADBCDriverIsSQLite3(poOpenInfo); - bool bIsParquet = OGRADBCDriverIsParquet(poOpenInfo) || - EQUAL(CPLGetExtension(pszFilename), "parquet"); + bool bIsParquet = + OGRADBCDriverIsParquet(poOpenInfo) || + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "parquet"); const char *pszSQL = CSLFetchNameValue(poOpenInfo->papszOpenOptions, "SQL"); if (!bIsParquet && pszSQL) { @@ -232,7 +233,8 @@ bool OGRADBCDataset::Open(const GDALOpenInfo *poOpenInfo) if (iPos2 != std::string::npos) { const std::string osFilename = osSQL.substr(iPos, iPos2 - iPos); - if (EQUAL(CPLGetExtension(osFilename.c_str()), "parquet")) + if (EQUAL(CPLGetExtensionSafe(osFilename.c_str()).c_str(), + "parquet")) { m_osParquetFilename = osFilename; bIsParquet = true; @@ -402,10 +404,10 @@ bool OGRADBCDataset::Open(const GDALOpenInfo *poOpenInfo) { if (m_osParquetFilename.empty()) m_osParquetFilename = pszFilename; - osLayerName = CPLGetBasename(m_osParquetFilename.c_str()); + osLayerName = CPLGetBasenameSafe(m_osParquetFilename.c_str()); if (osLayerName == "*") - osLayerName = - CPLGetBasename(CPLGetDirname(m_osParquetFilename.c_str())); + osLayerName = CPLGetBasenameSafe( + CPLGetDirnameSafe(m_osParquetFilename.c_str()).c_str()); if (!pszSQL) { osSQL = diff --git a/ogr/ogrsf_frmts/adbc/ogradbcdrivercore.cpp b/ogr/ogrsf_frmts/adbc/ogradbcdrivercore.cpp index e668ac1f3f12..2ff3bcaa5d46 100644 --- a/ogr/ogrsf_frmts/adbc/ogradbcdrivercore.cpp +++ b/ogr/ogrsf_frmts/adbc/ogradbcdrivercore.cpp @@ -64,7 +64,7 @@ int OGRADBCDriverIdentify(GDALOpenInfo *poOpenInfo) && GDALGetAdbcLoadDriverOverride() != nullptr #endif && !STARTS_WITH(poOpenInfo->pszFilename, "/vsi") && - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "mbtiles")); + !poOpenInfo->IsExtensionEqualToCI("mbtiles")); } /************************************************************************/ diff --git a/ogr/ogrsf_frmts/arrow/ogrfeatherdriver.cpp b/ogr/ogrsf_frmts/arrow/ogrfeatherdriver.cpp index 468a05d42ddf..94e8c9519242 100644 --- a/ogr/ogrsf_frmts/arrow/ogrfeatherdriver.cpp +++ b/ogr/ogrsf_frmts/arrow/ogrfeatherdriver.cpp @@ -44,7 +44,7 @@ static bool IsArrowIPCStream(GDALOpenInfo *poOpenInfo) memcmp(poOpenInfo->pabyHeader, "\xFF\xFF\xFF\xFF", CONTINUATION_SIZE) == 0) { - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (EQUAL(pszExt, "arrows") || EQUAL(pszExt, "ipc")) return true; @@ -170,7 +170,7 @@ static GDALDataset *OGRFeatherDriverOpen(GDALOpenInfo *poOpenInfo) char *pszCurDir = CPLGetCurrentDir(); if (pszCurDir == nullptr) return nullptr; - osPath = CPLFormFilename(pszCurDir, osPath.c_str(), nullptr); + osPath = CPLFormFilenameSafe(pszCurDir, osPath.c_str(), nullptr); CPLFree(pszCurDir); } @@ -216,7 +216,7 @@ static GDALDataset *OGRFeatherDriverOpen(GDALOpenInfo *poOpenInfo) const bool bSeekable = !STARTS_WITH_CI(poOpenInfo->pszFilename, "ARROW_IPC_STREAM:") && strcmp(poOpenInfo->pszFilename, "/vsistdin/") != 0; - std::string osLayername = CPLGetBasename(poOpenInfo->pszFilename); + std::string osLayername = CPLGetBasenameSafe(poOpenInfo->pszFilename); if (osLayername.empty()) osLayername = "layer"; auto poLayer = std::make_unique( @@ -256,7 +256,7 @@ static GDALDataset *OGRFeatherDriverOpen(GDALOpenInfo *poOpenInfo) } auto poRecordBatchReader = *result; auto poLayer = std::make_unique( - poDS.get(), CPLGetBasename(poOpenInfo->pszFilename), + poDS.get(), CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str(), poRecordBatchReader); poDS->SetLayer(std::move(poLayer)); } diff --git a/ogr/ogrsf_frmts/arrow/ogrfeatherdrivercore.cpp b/ogr/ogrsf_frmts/arrow/ogrfeatherdrivercore.cpp index 2c8f1064d2c8..2e66a5d77077 100644 --- a/ogr/ogrsf_frmts/arrow/ogrfeatherdrivercore.cpp +++ b/ogr/ogrsf_frmts/arrow/ogrfeatherdrivercore.cpp @@ -37,7 +37,7 @@ static int OGRFeatherDriverIsArrowIPCStreamBasic(GDALOpenInfo *poOpenInfo) memcmp(poOpenInfo->pabyHeader, "\xFF\xFF\xFF\xFF", CONTINUATION_SIZE) == 0) { - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (EQUAL(pszExt, "arrows") || EQUAL(pszExt, "ipc")) return true; diff --git a/ogr/ogrsf_frmts/arrow/ogrfeatherwriterlayer.cpp b/ogr/ogrsf_frmts/arrow/ogrfeatherwriterlayer.cpp index b09d42cfe23b..2c276244fa52 100644 --- a/ogr/ogrsf_frmts/arrow/ogrfeatherwriterlayer.cpp +++ b/ogr/ogrsf_frmts/arrow/ogrfeatherwriterlayer.cpp @@ -71,7 +71,7 @@ bool OGRFeatherWriterLayer::SetOptions(const std::string &osFilename, OGRwkbGeometryType eGType) { const char *pszDefaultFormat = - (EQUAL(CPLGetExtension(osFilename.c_str()), "arrows") || + (EQUAL(CPLGetExtensionSafe(osFilename.c_str()).c_str(), "arrows") || STARTS_WITH_CI(osFilename.c_str(), "/vsistdout")) ? "STREAM" : "FILE"; diff --git a/ogr/ogrsf_frmts/arrow_common/vsiarrowfilesystem.hpp b/ogr/ogrsf_frmts/arrow_common/vsiarrowfilesystem.hpp index e360f78f9ee4..19f22a8539e2 100644 --- a/ogr/ogrsf_frmts/arrow_common/vsiarrowfilesystem.hpp +++ b/ogr/ogrsf_frmts/arrow_common/vsiarrowfilesystem.hpp @@ -136,8 +136,8 @@ class VSIArrowFileSystem final : public arrow::fs::FileSystem while (const auto psEntry = VSIGetNextDirEntry(psDir)) { if (!bParquetFound) - bParquetFound = - EQUAL(CPLGetExtension(psEntry->pszName), "parquet"); + bParquetFound = EQUAL( + CPLGetExtensionSafe(psEntry->pszName).c_str(), "parquet"); const std::string osFilename = select.base_dir + '/' + psEntry->pszName; diff --git a/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp b/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp index 358c3725f838..2535acf34ea1 100644 --- a/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp +++ b/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp @@ -31,7 +31,8 @@ static GDALDataset *OGRAVCBinDriverOpen(GDALOpenInfo *poOpenInfo) bool bFoundCandidateFile = false; for (int i = 0; papszSiblingFiles[i] != nullptr; i++) { - if (EQUAL(CPLGetExtension(papszSiblingFiles[i]), "ADF")) + if (EQUAL(CPLGetExtensionSafe(papszSiblingFiles[i]).c_str(), + "ADF")) { bFoundCandidateFile = true; break; diff --git a/ogr/ogrsf_frmts/avc/ogravce00driver.cpp b/ogr/ogrsf_frmts/avc/ogravce00driver.cpp index 6cc2f9890439..1e3415e1eb03 100644 --- a/ogr/ogrsf_frmts/avc/ogravce00driver.cpp +++ b/ogr/ogrsf_frmts/avc/ogravce00driver.cpp @@ -18,7 +18,7 @@ static int OGRAVCE00DriverIdentify(GDALOpenInfo *poOpenInfo) { - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "E00")) + if (!poOpenInfo->IsExtensionEqualToCI("E00")) return FALSE; if (poOpenInfo->nHeaderBytes == 0) diff --git a/ogr/ogrsf_frmts/cad/gdalcaddataset.cpp b/ogr/ogrsf_frmts/cad/gdalcaddataset.cpp index a1fe3036ad1d..9a00feb78d72 100644 --- a/ogr/ogrsf_frmts/cad/gdalcaddataset.cpp +++ b/ogr/ogrsf_frmts/cad/gdalcaddataset.cpp @@ -226,11 +226,12 @@ int GDALCADDataset::Open(GDALOpenInfo *poOpenInfo, CADFileIO *pFileIO, { // TODO: Add support clipping region in neatline CPLString osImgFilename = pImage->getFilePath(); - CPLString osImgPath = CPLGetPath(osImgFilename); + CPLString osImgPath = CPLGetPathSafe(osImgFilename); if (osImgPath.empty()) { - osImgFilename = CPLFormFilename(CPLGetPath(osCADFilename), - osImgFilename, nullptr); + osImgFilename = + CPLFormFilenameSafe(CPLGetPathSafe(osCADFilename).c_str(), + osImgFilename, nullptr); } if (!CPLCheckForFile(const_cast(osImgFilename.c_str()), @@ -323,9 +324,9 @@ char **GDALCADDataset::GetFileList() /* duplicated papszFileList = CSLAddString( papszFileList, osCADFilename * );*/ - const char *pszPRJFilename = GetPrjFilePath(); - if (nullptr != pszPRJFilename) - papszFileList = CSLAddString(papszFileList, pszPRJFilename); + const std::string osPRJFilename = GetPrjFilePath(); + if (!osPRJFilename.empty()) + papszFileList = CSLAddString(papszFileList, osPRJFilename.c_str()); for (size_t i = 0; i < poCADFile->GetLayersCount(); ++i) { @@ -394,11 +395,11 @@ const OGRSpatialReference *GDALCADDataset::GetSpatialRef() const } else { - const char *pszPRJFilename = GetPrjFilePath(); - if (pszPRJFilename && pszPRJFilename[0]) // check if path exists + const std::string osPRJFilename = GetPrjFilePath(); + if (!osPRJFilename.empty()) // check if path exists { CPLPushErrorHandler(CPLQuietErrorHandler); - char **papszPRJData = CSLLoad(pszPRJFilename); + char **papszPRJData = CSLLoad(osPRJFilename.c_str()); CPLPopErrorHandler(); if (poSpatialReference->importFromESRI(papszPRJData) != @@ -419,17 +420,17 @@ const OGRSpatialReference *GDALCADDataset::GetSpatialRef() const return poSpatialReference; } -const char *GDALCADDataset::GetPrjFilePath() const +const std::string GDALCADDataset::GetPrjFilePath() const { - const char *pszPRJFilename = CPLResetExtension(osCADFilename, "prj"); - if (CPLCheckForFile((char *)pszPRJFilename, nullptr) == TRUE) - return pszPRJFilename; + std::string osPRJFilename = CPLResetExtensionSafe(osCADFilename, "prj"); + if (CPLCheckForFile(osPRJFilename.data(), nullptr) == TRUE) + return osPRJFilename; - pszPRJFilename = CPLResetExtension(osCADFilename, "PRJ"); - if (CPLCheckForFile((char *)pszPRJFilename, nullptr) == TRUE) - return pszPRJFilename; + osPRJFilename = CPLResetExtensionSafe(osCADFilename, "PRJ"); + if (CPLCheckForFile(osPRJFilename.data(), nullptr) == TRUE) + return osPRJFilename; - return ""; + return std::string(); } CPLErr GDALCADDataset::GetGeoTransform(double *padfGeoTransform) diff --git a/ogr/ogrsf_frmts/cad/ogr_cad.h b/ogr/ogrsf_frmts/cad/ogr_cad.h index 486d5cc2eb14..12185c0fdfe3 100644 --- a/ogr/ogrsf_frmts/cad/ogr_cad.h +++ b/ogr/ogrsf_frmts/cad/ogr_cad.h @@ -97,7 +97,7 @@ class GDALCADDataset final : public GDALDataset virtual int CloseDependentDatasets() override; protected: - const char *GetPrjFilePath() const; + const std::string GetPrjFilePath() const; void FillTransform(CADImage *pImage, double dfUnits); int GetCadEncoding() const; diff --git a/ogr/ogrsf_frmts/cad/ogrcaddrivercore.cpp b/ogr/ogrsf_frmts/cad/ogrcaddrivercore.cpp index a84dc39d6fda..2c0c88c8272f 100644 --- a/ogr/ogrsf_frmts/cad/ogrcaddrivercore.cpp +++ b/ogr/ogrsf_frmts/cad/ogrcaddrivercore.cpp @@ -25,7 +25,7 @@ static int OGRCADDriverIdentify(GDALOpenInfo *poOpenInfo) { #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "DWG")) + if (!poOpenInfo->IsExtensionEqualToCI("DWG")) return FALSE; #endif return poOpenInfo->nHeaderBytes >= 6 && poOpenInfo->pabyHeader[0] == 'A' && diff --git a/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp b/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp index a81cff8d4ce6..a21db151a15a 100644 --- a/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp +++ b/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp @@ -84,7 +84,7 @@ OGRErr OGRCSVEditableLayerSynchronizer::EditableSyncToDisk( const CPLString osLayerName(m_poCSVLayer->GetName()); const CPLString osFilename(m_poCSVLayer->GetFilename()); const bool bCreateCSVT = m_poCSVLayer->GetCreateCSVT(); - const CPLString osCSVTFilename(CPLResetExtension(osFilename, "csvt")); + const CPLString osCSVTFilename(CPLResetExtensionSafe(osFilename, "csvt")); VSIStatBufL sStatBuf; const bool bHasCSVT = VSIStatL(osCSVTFilename, &sStatBuf) == 0; CPLString osTmpFilename(osFilename); @@ -248,7 +248,7 @@ OGRErr OGRCSVEditableLayerSynchronizer::EditableSyncToDisk( CPLError(CE_Failure, CPLE_AppDefined, "Error while creating %s", osTmpFilename.c_str()); VSIUnlink(osTmpFilename); - VSIUnlink(CPLResetExtension(osTmpFilename, "csvt")); + VSIUnlink(CPLResetExtensionSafe(osTmpFilename, "csvt").c_str()); return eErr; } @@ -476,7 +476,7 @@ OGRLayer *OGRCSVDataSource::GetLayer(int iLayer) CPLString OGRCSVDataSource::GetRealExtension(CPLString osFilename) { - const CPLString osExt = CPLGetExtension(osFilename); + const CPLString osExt = CPLGetExtensionSafe(osFilename); if (STARTS_WITH(osFilename, "/vsigzip/") && EQUAL(osExt, "gz")) { if (osFilename.size() > 7 && @@ -631,12 +631,12 @@ bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn, { char **papszFiles = VSIReadDir(osFilename); if (CSLCount(papszFiles) != 1 || - !EQUAL(CPLGetExtension(papszFiles[0]), "CSV")) + !EQUAL(CPLGetExtensionSafe(papszFiles[0]).c_str(), "CSV")) { CSLDestroy(papszFiles); return FALSE; } - osFilename = CPLFormFilename(osFilename, papszFiles[0], nullptr); + osFilename = CPLFormFilenameSafe(osFilename, papszFiles[0], nullptr); CSLDestroy(papszFiles); return OpenTable(osFilename, papszOpenOptionsIn); } @@ -652,12 +652,12 @@ bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn, for (int i = 0; papszNames != nullptr && papszNames[i] != nullptr; i++) { const CPLString oSubFilename = - CPLFormFilename(osFilename, papszNames[i], nullptr); + CPLFormFilenameSafe(osFilename, papszNames[i], nullptr); if (EQUAL(papszNames[i], ".") || EQUAL(papszNames[i], "..")) continue; - if (EQUAL(CPLGetExtension(oSubFilename), "csvt")) + if (EQUAL(CPLGetExtensionSafe(oSubFilename).c_str(), "csvt")) continue; if (VSIStatL(oSubFilename, &sStatBuf) != 0 || @@ -667,7 +667,7 @@ bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn, continue; } - if (EQUAL(CPLGetExtension(oSubFilename), "csv")) + if (EQUAL(CPLGetExtensionSafe(oSubFilename).c_str(), "csv")) { if (!OpenTable(oSubFilename, papszOpenOptionsIn)) { @@ -679,7 +679,7 @@ bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn, // GNIS specific. else if (strlen(papszNames[i]) > 2 && STARTS_WITH_CI(papszNames[i] + 2, "_Features_") && - EQUAL(CPLGetExtension(papszNames[i]), "txt")) + EQUAL(CPLGetExtensionSafe(papszNames[i]).c_str(), "txt")) { bool bRet = OpenTable(oSubFilename, papszOpenOptionsIn, nullptr, "PRIM"); @@ -695,7 +695,7 @@ bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn, // GNIS specific. else if (strlen(papszNames[i]) > 2 && STARTS_WITH_CI(papszNames[i] + 2, "_FedCodes_") && - EQUAL(CPLGetExtension(papszNames[i]), "txt")) + EQUAL(CPLGetExtensionSafe(papszNames[i]).c_str(), "txt")) { if (!OpenTable(oSubFilename, papszOpenOptionsIn, nullptr, "PRIMARY")) @@ -868,8 +868,8 @@ bool OGRCSVDataSource::OpenTable(const char *pszFilename, strstr(pszFilename, "/vsizip/") == nullptr) fp = VSICreateBufferedReaderHandle(fp); - CPLString osLayerName = CPLGetBasename(pszFilename); - CPLString osExt = CPLGetExtension(pszFilename); + CPLString osLayerName = CPLGetBasenameSafe(pszFilename); + CPLString osExt = CPLGetExtensionSafe(pszFilename); if (STARTS_WITH(pszFilename, "/vsigzip/") && EQUAL(osExt, "gz")) { if (strlen(pszFilename) > 7 && @@ -1090,12 +1090,12 @@ OGRCSVDataSource::ICreateLayer(const char *pszLayerName, } else if (osDefaultCSVName != "") { - osFilename = CPLFormFilename(pszName, osDefaultCSVName, nullptr); + osFilename = CPLFormFilenameSafe(pszName, osDefaultCSVName, nullptr); osDefaultCSVName = ""; } else { - osFilename = CPLFormFilename(pszName, pszLayerName, "csv"); + osFilename = CPLFormFilenameSafe(pszName, pszLayerName, "csv"); } // Does this directory/file already exist? @@ -1228,8 +1228,8 @@ OGRCSVDataSource::ICreateLayer(const char *pszLayerName, poSpatialRef->exportToWkt(&pszWKT); if (pszWKT) { - VSILFILE *fpPRJ = - VSIFOpenL(CPLResetExtension(osFilename, "prj"), "wb"); + VSILFILE *fpPRJ = VSIFOpenL( + CPLResetExtensionSafe(osFilename, "prj").c_str(), "wb"); if (fpPRJ) { CPL_IGNORE_RET_VAL(VSIFPrintfL(fpPRJ, "%s\n", pszWKT)); diff --git a/ogr/ogrsf_frmts/csv/ogrcsvdriver.cpp b/ogr/ogrsf_frmts/csv/ogrcsvdriver.cpp index 3734315a4b3c..16160fb9833f 100644 --- a/ogr/ogrsf_frmts/csv/ogrcsvdriver.cpp +++ b/ogr/ogrsf_frmts/csv/ogrcsvdriver.cpp @@ -203,13 +203,13 @@ OGRCSVDriverCreate(const char *pszName, CPL_UNUSED int nBands, // If the target is not a simple .csv then create it as a directory. CPLString osDirName; - if (EQUAL(CPLGetExtension(pszName), "csv")) + if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "csv")) { - osDirName = CPLGetPath(pszName); + osDirName = CPLGetPathSafe(pszName); if (osDirName == "") osDirName = "."; - // HACK: CPLGetPath("/vsimem/foo.csv") = "/vsimem", but this is not + // HACK: CPLGetPathSafe("/vsimem/foo.csv") = "/vsimem", but this is not // recognized afterwards as a valid directory name. if (osDirName == "/vsimem") osDirName = "/vsimem/"; @@ -233,7 +233,7 @@ OGRCSVDriverCreate(const char *pszName, CPL_UNUSED int nBands, // Force it to open as a datasource. auto poDS = std::make_unique(); - if (EQUAL(CPLGetExtension(pszName), "csv")) + if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "csv")) { poDS->CreateForSingleFile(osDirName, pszName); } diff --git a/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp b/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp index 887f8902899e..ae283cf560e6 100644 --- a/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp +++ b/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp @@ -327,11 +327,10 @@ void OGRCSVLayer::BuildFeatureDefn(const char *pszNfdcGeomField, if (!bNew) { // Only try to read .csvt from files that have an extension - const char *pszExt = CPLGetExtension(pszFilename); - if (pszExt[0]) + if (!CPLGetExtensionSafe(pszFilename).empty()) { const std::string osCSVTFilename = - CPLResetExtension(pszFilename, "csvt"); + CPLResetExtensionSafe(pszFilename, "csvt"); VSILFILE *fpCSVT = VSIFOpenL(osCSVTFilename.c_str(), "r"); if (fpCSVT != nullptr) { @@ -778,7 +777,7 @@ void OGRCSVLayer::BuildFeatureDefn(const char *pszNfdcGeomField, poFeatureDefn->GetGeomFieldDefn(0)->GetSpatialRef() == nullptr) { VSILFILE *fpPRJ = - VSIFOpenL(CPLResetExtension(pszFilename, "prj"), "rb"); + VSIFOpenL(CPLResetExtensionSafe(pszFilename, "prj").c_str(), "rb"); if (fpPRJ != nullptr) { GByte *pabyRet = nullptr; @@ -1986,10 +1985,13 @@ OGRErr OGRCSVLayer::WriteHeader() VSILFILE *fpCSVT = nullptr; if (bCreateCSVT && iFile == 0) { - char *pszDirName = CPLStrdup(CPLGetDirname(pszFilename)); - char *pszBaseName = CPLStrdup(CPLGetBasename(pszFilename)); + char *pszDirName = + CPLStrdup(CPLGetDirnameSafe(pszFilename).c_str()); + char *pszBaseName = + CPLStrdup(CPLGetBasenameSafe(pszFilename).c_str()); fpCSVT = VSIFOpenL( - CPLFormFilename(pszDirName, pszBaseName, ".csvt"), "wb"); + CPLFormFilenameSafe(pszDirName, pszBaseName, ".csvt").c_str(), + "wb"); CPLFree(pszDirName); CPLFree(pszBaseName); } diff --git a/ogr/ogrsf_frmts/dgn/ogrdgndriver.cpp b/ogr/ogrsf_frmts/dgn/ogrdgndriver.cpp index 9a283aa3fe37..721c275f0fe4 100644 --- a/ogr/ogrsf_frmts/dgn/ogrdgndriver.cpp +++ b/ogr/ogrsf_frmts/dgn/ogrdgndriver.cpp @@ -35,7 +35,7 @@ static int OGRDGNDriverIdentify(GDALOpenInfo *poOpenInfo) poOpenInfo->fpL != nullptr && poOpenInfo->nHeaderBytes >= 512 && memcmp(poOpenInfo->pabyHeader, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1", 8) == 0 && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "DGN") && + poOpenInfo->IsExtensionEqualToCI("DGN") && VSIStat(poOpenInfo->pszFilename, &sStat) == 0 && GDALGetDriverByName("DGNV8") == nullptr) { diff --git a/ogr/ogrsf_frmts/dwg/ogrdgnv8drivercore.cpp b/ogr/ogrsf_frmts/dwg/ogrdgnv8drivercore.cpp index c0b0ddc9cbd1..2b01caf4f313 100644 --- a/ogr/ogrsf_frmts/dwg/ogrdgnv8drivercore.cpp +++ b/ogr/ogrsf_frmts/dwg/ogrdgnv8drivercore.cpp @@ -47,7 +47,7 @@ int OGRDGNV8DriverIdentify(GDALOpenInfo *poOpenInfo) } return poOpenInfo->fpL != nullptr && poOpenInfo->nHeaderBytes >= 512 && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "DGN") && + poOpenInfo->IsExtensionEqualToCI("DGN") && memcmp(poOpenInfo->pabyHeader, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1", 8) == 0 && VSIStat(poOpenInfo->pszFilename, &sStat) == 0; diff --git a/ogr/ogrsf_frmts/dwg/ogrdwgdrivercore.cpp b/ogr/ogrsf_frmts/dwg/ogrdwgdrivercore.cpp index c5feb81a3cf9..c345f1b77246 100644 --- a/ogr/ogrsf_frmts/dwg/ogrdwgdrivercore.cpp +++ b/ogr/ogrsf_frmts/dwg/ogrdwgdrivercore.cpp @@ -21,7 +21,7 @@ int OGRDWGDriverIdentify(GDALOpenInfo *poOpenInfo) { - return EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "dwg"); + return poOpenInfo->IsExtensionEqualToCI("dwg"); } /************************************************************************/ diff --git a/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp b/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp index 7bc8ca0c2806..e9b9712223f7 100644 --- a/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp +++ b/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp @@ -22,7 +22,7 @@ static int OGRDXFDriverIdentify(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->fpL == nullptr || poOpenInfo->nHeaderBytes == 0) return FALSE; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "dxf")) + if (poOpenInfo->IsExtensionEqualToCI("dxf")) return TRUE; const char *pszIter = (const char *)poOpenInfo->pabyHeader; bool bFoundZero = false; diff --git a/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp b/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp index 91135d0f18b3..c2f3a407a5b6 100644 --- a/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp +++ b/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp @@ -156,14 +156,15 @@ VSILFILE *OGREDIGEODataSource::OpenFile(const char *pszType, const CPLString &osExt) { CPLString osTmp = osLON + pszType; - CPLString osFilename = CPLFormCIFilename(CPLGetPath(GetDescription()), - osTmp.c_str(), osExt.c_str()); + CPLString osFilename = CPLFormCIFilenameSafe( + CPLGetPathSafe(GetDescription()).c_str(), osTmp.c_str(), osExt.c_str()); VSILFILE *fp = VSIFOpenL(osFilename, "rb"); if (fp == nullptr) { const CPLString osExtLower = CPLString(osExt).tolower(); - const CPLString osFilename2 = CPLFormCIFilename( - CPLGetPath(GetDescription()), osTmp.c_str(), osExtLower.c_str()); + const CPLString osFilename2 = + CPLFormCIFilenameSafe(CPLGetPathSafe(GetDescription()).c_str(), + osTmp.c_str(), osExtLower.c_str()); fp = VSIFOpenL(osFilename2, "rb"); if (fp == nullptr) { diff --git a/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp b/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp index ab8861c8ef86..9133ce8d8fe3 100644 --- a/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp +++ b/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp @@ -27,7 +27,7 @@ static int OGREDIGEODriverIdentify(GDALOpenInfo *poOpenInfo) { return poOpenInfo->fpL != nullptr && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "thf"); + poOpenInfo->IsExtensionEqualToCI("thf"); } /************************************************************************/ diff --git a/ogr/ogrsf_frmts/filegdb/FGdbDatasource.cpp b/ogr/ogrsf_frmts/filegdb/FGdbDatasource.cpp index ea9f244827a6..f7f731694d67 100644 --- a/ogr/ogrsf_frmts/filegdb/FGdbDatasource.cpp +++ b/ogr/ogrsf_frmts/filegdb/FGdbDatasource.cpp @@ -162,17 +162,18 @@ int FGdbDataSource::FixIndexes() m_pConnection->CloseGeodatabase(); const char *const apszDrivers[2] = {"OpenFileGDB", nullptr}; - const char *pszSystemCatalog = - CPLFormFilename(m_osFSName, "a00000001.gdbtable", nullptr); - auto poOpenFileGDBDS = std::unique_ptr(GDALDataset::Open( - pszSystemCatalog, GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr)); + const std::string osSystemCatalog = + CPLFormFilenameSafe(m_osFSName, "a00000001.gdbtable", nullptr); + auto poOpenFileGDBDS = std::unique_ptr( + GDALDataset::Open(osSystemCatalog.c_str(), GDAL_OF_VECTOR, + apszDrivers, nullptr, nullptr)); if (poOpenFileGDBDS == nullptr || poOpenFileGDBDS->GetLayer(0) == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s with OpenFileGDB driver. " "Should not happen. Some layers will be corrupted", - pszSystemCatalog); + osSystemCatalog.c_str()); bRet = FALSE; } else @@ -202,9 +203,12 @@ int FGdbDataSource::FixIndexes() } else { - if (!poFgdbLayer->EditIndexesForFIDHack(CPLFormFilename( - m_osFSName, CPLSPrintf("a%08x", (int)poF->GetFID()), - nullptr))) + if (!poFgdbLayer->EditIndexesForFIDHack( + CPLFormFilenameSafe( + m_osFSName, + CPLSPrintf("a%08x", (int)poF->GetFID()), + nullptr) + .c_str())) { bRet = FALSE; } @@ -499,12 +503,13 @@ bool FGdbDataSource::LoadLayers(const std::wstring &root) // they exist (despite ArcGIS itself showing them!) int iGDBItems = -1; const char *const apszDrivers[2] = {"OpenFileGDB", nullptr}; - const char *pszSystemCatalog = - CPLFormFilename(m_osFSName, "a00000001", "gdbtable"); + const std::string osSystemCatalog = + CPLFormFilenameSafe(m_osFSName, "a00000001", "gdbtable"); if (m_bUseOpenFileGDB) { - m_poOpenFileGDBDS.reset(GDALDataset::Open( - pszSystemCatalog, GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr)); + m_poOpenFileGDBDS.reset(GDALDataset::Open(osSystemCatalog.c_str(), + GDAL_OF_VECTOR, apszDrivers, + nullptr, nullptr)); } if (m_poOpenFileGDBDS != nullptr && m_poOpenFileGDBDS->GetLayer(0) != nullptr) @@ -547,10 +552,10 @@ bool FGdbDataSource::LoadLayers(const std::wstring &root) // it's too slow! if (iGDBItems >= 0) { - const char *pszGDBItems = CPLFormFilename( + const std::string osGDBItems = CPLFormFilenameSafe( m_osFSName, CPLSPrintf("a%08x", iGDBItems + 1), "gdbtable"); std::unique_ptr poGDBItems(GDALDataset::Open( - pszGDBItems, GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr)); + osGDBItems.c_str(), GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr)); if (poGDBItems != nullptr && poGDBItems->GetLayer(0) != nullptr) { if (OGRLayer *poItemsLayer = poGDBItems->GetLayer(0)) diff --git a/ogr/ogrsf_frmts/filegdb/FGdbDriver.cpp b/ogr/ogrsf_frmts/filegdb/FGdbDriver.cpp index 4c073ddafbac..ba4ae53c927b 100644 --- a/ogr/ogrsf_frmts/filegdb/FGdbDriver.cpp +++ b/ogr/ogrsf_frmts/filegdb/FGdbDriver.cpp @@ -192,8 +192,8 @@ OGRFileGDBDriverCreate(const char *pszName, CPL_UNUSED int nBands, /* Only accept names of form "filename.gdb" and */ /* also .gdb.zip to be able to return FGDB with MapServer OGR output (#4199) */ - const char *pszExt = CPLGetExtension(pszName); - if (!(EQUAL(pszExt, "gdb") || EQUAL(pszExt, "zip"))) + const std::string osExt = CPLGetExtensionSafe(pszName); + if (!(EQUAL(osExt.c_str(), "gdb") || EQUAL(osExt.c_str(), "zip"))) { CPLError(CE_Failure, CPLE_AppDefined, "FGDB data source name must use 'gdb' extension.\n"); @@ -327,8 +327,10 @@ OGRErr FGdbTransactionManager::StartTransaction(GDALDataset *&poDSInOut, EQUAL(*papszIter, "gdb") || EQUAL(*papszIter, "timestamps")) { if (CPLCopyFile( - CPLFormFilename(osEditedName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, nullptr)) != 0) + CPLFormFilenameSafe(osEditedName, *papszIter, nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str()) != 0) { bError = TRUE; CPLError(CE_Failure, CPLE_AppDefined, "Cannot copy %s", @@ -339,15 +341,16 @@ OGRErr FGdbTransactionManager::StartTransaction(GDALDataset *&poDSInOut, { CPLString osSourceFile; if (CPLIsFilenameRelative(osName)) - osSourceFile = CPLFormFilename( + osSourceFile = CPLFormFilenameSafe( CPLSPrintf("../%s", CPLGetFilename(osName.c_str())), *papszIter, nullptr); else osSourceFile = osName; if (EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE1") || CPLSymlink(osSourceFile, - CPLFormFilename(osEditedName.c_str(), *papszIter, - nullptr), + CPLFormFilenameSafe(osEditedName.c_str(), + *papszIter, nullptr) + .c_str(), nullptr) != 0) { bError = TRUE; @@ -471,22 +474,26 @@ OGRErr FGdbTransactionManager::CommitTransaction(GDALDataset *&poDSInOut, continue; VSIStatBufL sStat; if ((*papszIter)[0] == 'a' && - VSIStatL(CPLFormFilename(osEditedName, *papszIter, nullptr), + VSIStatL(CPLFormFilenameSafe(osEditedName, *papszIter, nullptr) + .c_str(), &sStat) != 0) { if (EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE1") || - VSIRename(CPLFormFilename(osName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, "tmp")) != 0) + VSIRename(CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, "tmp") + .c_str()) != 0) { - CPLError(CE_Failure, CPLE_AppDefined, - "Cannot rename %s to %s", - CPLFormFilename(osName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, "tmp")); + CPLError( + CE_Failure, CPLE_AppDefined, "Cannot rename %s to %s", + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, "tmp").c_str()); bError = TRUE; } else aosTmpFilesToClean.push_back( - CPLFormFilename(osName, *papszIter, "tmp")); + CPLFormFilenameSafe(osName, *papszIter, "tmp")); } } CSLDestroy(papszFiles); @@ -498,56 +505,72 @@ OGRErr FGdbTransactionManager::CommitTransaction(GDALDataset *&poDSInOut, if (strcmp(*papszIter, ".") == 0 || strcmp(*papszIter, "..") == 0) continue; struct stat sStat; - if (lstat(CPLFormFilename(osEditedName, *papszIter, nullptr), + if (lstat(CPLFormFilenameSafe(osEditedName, *papszIter, nullptr) + .c_str(), &sStat) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot stat %s", - CPLFormFilename(osEditedName, *papszIter, nullptr)); + CPLFormFilenameSafe(osEditedName, *papszIter, nullptr) + .c_str()); bError = TRUE; } else if (!S_ISLNK(sStat.st_mode)) { // If there was such a file in original directory, first rename // it as a temporary file - if (lstat(CPLFormFilename(osName, *papszIter, nullptr), + if (lstat(CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str(), &sStat) == 0) { if (EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE2") || - VSIRename(CPLFormFilename(osName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, "tmp")) != - 0) + VSIRename( + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, "tmp") + .c_str()) != 0) { - CPLError(CE_Failure, CPLE_AppDefined, - "Cannot rename %s to %s", - CPLFormFilename(osName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, "tmp")); + CPLError( + CE_Failure, CPLE_AppDefined, + "Cannot rename %s to %s", + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, "tmp") + .c_str()); bError = TRUE; } else aosTmpFilesToClean.push_back( - CPLFormFilename(osName, *papszIter, "tmp")); + CPLFormFilenameSafe(osName, *papszIter, "tmp")); } if (!bError) { if (EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE3") || CPLMoveFile( - CPLFormFilename(osName, *papszIter, nullptr), - CPLFormFilename(osEditedName, *papszIter, - nullptr)) != 0) + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str(), + CPLFormFilenameSafe(osEditedName, *papszIter, + nullptr) + .c_str()) != 0) { CPLError( CE_Failure, CPLE_AppDefined, "Cannot move %s to %s", - CPLFormFilename(osEditedName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, nullptr)); + CPLFormFilenameSafe(osEditedName, *papszIter, + nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str()); bError = TRUE; } else CPLDebug( "FileGDB", "Move %s to %s", - CPLFormFilename(osEditedName, *papszIter, nullptr), - CPLFormFilename(osName, *papszIter, nullptr)); + CPLFormFilenameSafe(osEditedName, *papszIter, + nullptr) + .c_str(), + CPLFormFilenameSafe(osName, *papszIter, nullptr) + .c_str()); } } } diff --git a/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp b/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp index 1b50500a030f..5b22f0df0ee6 100644 --- a/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp +++ b/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp @@ -198,9 +198,10 @@ int FGdbLayer::EditIndexesForFIDHack(const char *pszRadixTablename) { // Fix FIDs in .gdbtablx, .spx and .atx's - CPLString osGDBTablX = CPLResetExtension(pszRadixTablename, "gdbtablx"); - CPLString osNewGDBTablX = - CPLResetExtension(pszRadixTablename, "gdbtablx.new"); + const CPLString osGDBTablX = + CPLResetExtensionSafe(pszRadixTablename, "gdbtablx"); + const CPLString osNewGDBTablX = + CPLResetExtensionSafe(pszRadixTablename, "gdbtablx.new"); if (!EditGDBTablX(osGDBTablX, osNewGDBTablX)) { @@ -210,18 +211,18 @@ int FGdbLayer::EditIndexesForFIDHack(const char *pszRadixTablename) return FALSE; } - CPLString osDirectory(CPLGetPath(pszRadixTablename)); + CPLString osDirectory(CPLGetPathSafe(pszRadixTablename)); char **papszFiles = VSIReadDir(osDirectory); - CPLString osBasename(CPLGetBasename(pszRadixTablename)); + const CPLString osBasename(CPLGetBasenameSafe(pszRadixTablename)); int bRet = TRUE; for (char **papszIter = papszFiles; papszIter && *papszIter; papszIter++) { if (strncmp(*papszIter, osBasename.c_str(), osBasename.size()) == 0 && - (EQUAL(CPLGetExtension(*papszIter), "atx") || - EQUAL(CPLGetExtension(*papszIter), "spx"))) + (EQUAL(CPLGetExtensionSafe(*papszIter).c_str(), "atx") || + EQUAL(CPLGetExtensionSafe(*papszIter).c_str(), "spx"))) { - CPLString osIndex( - CPLFormFilename(osDirectory, *papszIter, nullptr)); + const CPLString osIndex( + CPLFormFilenameSafe(osDirectory, *papszIter, nullptr)); if (!EditATXOrSPX(osIndex)) { CPLError(CE_Failure, CPLE_AppDefined, @@ -4232,15 +4233,15 @@ int FGdbLayer::CreateRealCopy() char *apszDrivers[2] = {nullptr}; apszDrivers[0] = (char *)"OpenFileGDB"; apszDrivers[1] = nullptr; - const char *pszSystemCatalog = - CPLFormFilename(m_pDS->GetFSName(), "a00000001.gdbtable", nullptr); - GDALDataset *poOpenFileGDBDS = (GDALDataset *)GDALOpenEx( - pszSystemCatalog, GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr); + const std::string osSystemCatalog = + CPLFormFilenameSafe(m_pDS->GetFSName(), "a00000001.gdbtable", nullptr); + GDALDataset *poOpenFileGDBDS = GDALDataset::Open( + osSystemCatalog.c_str(), GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr); if (poOpenFileGDBDS == nullptr || poOpenFileGDBDS->GetLayer(0) == nullptr) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s with OpenFileGDB driver. Should not happen.", - pszSystemCatalog); + osSystemCatalog.c_str()); GDALClose(poOpenFileGDBDS); return FALSE; } @@ -4277,9 +4278,10 @@ int FGdbLayer::CreateRealCopy() if (strncmp(*papszIter, osBasename.c_str(), osBasename.size()) == 0) { if (CPLCopyFile( - CPLFormFilename(m_pDS->GetFSName(), *papszIter, "tmp"), - CPLFormFilename(m_pDS->GetFSName(), *papszIter, nullptr)) != - 0) + CPLFormFilenameSafe(m_pDS->GetFSName(), *papszIter, "tmp") + .c_str(), + CPLFormFilenameSafe(m_pDS->GetFSName(), *papszIter, nullptr) + .c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot copy %s", *papszIter); @@ -4294,11 +4296,14 @@ int FGdbLayer::CreateRealCopy() // Rename the .tmp into normal filenames for (size_t i = 0; !bError && i < aoFiles.size(); i++) { - if (VSIUnlink(CPLFormFilename(m_pDS->GetFSName(), aoFiles[i], - nullptr)) != 0 || + if (VSIUnlink( + CPLFormFilenameSafe(m_pDS->GetFSName(), aoFiles[i], nullptr) + .c_str()) != 0 || VSIRename( - CPLFormFilename(m_pDS->GetFSName(), aoFiles[i], "tmp"), - CPLFormFilename(m_pDS->GetFSName(), aoFiles[i], nullptr)) != 0) + CPLFormFilenameSafe(m_pDS->GetFSName(), aoFiles[i], "tmp") + .c_str(), + CPLFormFilenameSafe(m_pDS->GetFSName(), aoFiles[i], nullptr) + .c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot rename %s.tmp", aoFiles[i].c_str()); diff --git a/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobufdataset.cpp b/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobufdataset.cpp index 356506d0ddf4..dbd2b259e919 100644 --- a/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobufdataset.cpp +++ b/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobufdataset.cpp @@ -91,10 +91,12 @@ static CPLErr OGRFlatGoBufDriverDelete(const char *pszDataSource) papszDirEntries != nullptr && papszDirEntries[iFile] != nullptr; iFile++) { - if (EQUAL(CPLGetExtension(papszDirEntries[iFile]), "fgb")) + if (EQUAL(CPLGetExtensionSafe(papszDirEntries[iFile]).c_str(), + "fgb")) { - VSIUnlink(CPLFormFilename(pszDataSource, papszDirEntries[iFile], - nullptr)); + VSIUnlink(CPLFormFilenameSafe(pszDataSource, + papszDirEntries[iFile], nullptr) + .c_str()); } } @@ -245,7 +247,7 @@ GDALDataset *OGRFlatGeobufDataset::Open(GDALOpenInfo *poOpenInfo) { if (strcmp(aosFiles[i], ".") == 0 || strcmp(aosFiles[i], "..") == 0) continue; - if (EQUAL(CPLGetExtension(aosFiles[i]), "fgb")) + if (EQUAL(CPLGetExtensionSafe(aosFiles[i]).c_str(), "fgb")) nCountFGB++; else nCountNonFGB++; @@ -258,10 +260,10 @@ GDALDataset *OGRFlatGeobufDataset::Open(GDALOpenInfo *poOpenInfo) } for (int i = 0; i < aosFiles.size(); i++) { - if (EQUAL(CPLGetExtension(aosFiles[i]), "fgb")) + if (EQUAL(CPLGetExtensionSafe(aosFiles[i]).c_str(), "fgb")) { - CPLString osFilename(CPLFormFilename(poOpenInfo->pszFilename, - aosFiles[i], nullptr)); + const CPLString osFilename(CPLFormFilenameSafe( + poOpenInfo->pszFilename, aosFiles[i], nullptr)); VSILFILE *fp = VSIFOpenL(osFilename, "rb"); if (fp) { @@ -335,7 +337,7 @@ GDALDataset *OGRFlatGeobufDataset::Create(const char *pszName, int /* nBands */, } bool bIsDir = false; - if (!EQUAL(CPLGetExtension(pszName), "fgb")) + if (!EQUAL(CPLGetExtensionSafe(pszName).c_str(), "fgb")) { if (VSIMkdir(pszName, 0755) != 0) { @@ -379,7 +381,7 @@ int OGRFlatGeobufDataset::TestCapability(const char *pszCap) static CPLString LaunderLayerName(const char *pszLayerName) { - std::string osRet(CPLLaunderForFilename(pszLayerName, nullptr)); + std::string osRet(CPLLaunderForFilenameSafe(pszLayerName, nullptr)); if (osRet != pszLayerName) { CPLError(CE_Warning, CPLE_AppDefined, @@ -424,7 +426,7 @@ OGRFlatGeobufDataset::ICreateLayer(const char *pszLayerName, CPLString osFilename; if (m_bIsDir) - osFilename = CPLFormFilename( + osFilename = CPLFormFilenameSafe( GetDescription(), LaunderLayerName(pszLayerName).c_str(), "fgb"); else osFilename = GetDescription(); diff --git a/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobuflayer.cpp b/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobuflayer.cpp index 0889526680dc..76863d7718d7 100644 --- a/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobuflayer.cpp +++ b/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobuflayer.cpp @@ -2455,14 +2455,14 @@ void OGRFlatGeobufLayer::ResetReading() std::string OGRFlatGeobufLayer::GetTempFilePath(const CPLString &fileName, CSLConstList papszOptions) { - const CPLString osDirname(CPLGetPath(fileName.c_str())); - const CPLString osBasename(CPLGetBasename(fileName.c_str())); + const CPLString osDirname(CPLGetPathSafe(fileName.c_str())); + const CPLString osBasename(CPLGetBasenameSafe(fileName.c_str())); const char *pszTempDir = CSLFetchNameValue(papszOptions, "TEMPORARY_DIR"); std::string osTempFile = - pszTempDir ? CPLFormFilename(pszTempDir, osBasename, nullptr) + pszTempDir ? CPLFormFilenameSafe(pszTempDir, osBasename, nullptr) : (STARTS_WITH(fileName, "/vsi") && !STARTS_WITH(fileName, "/vsimem/")) - ? CPLGenerateTempFilename(osBasename) - : CPLFormFilename(osDirname, osBasename, nullptr); + ? CPLGenerateTempFilenameSafe(osBasename) + : CPLFormFilenameSafe(osDirname, osBasename, nullptr); osTempFile += "_temp.fgb"; return osTempFile; } diff --git a/ogr/ogrsf_frmts/generic/ogr_miattrind.cpp b/ogr/ogrsf_frmts/generic/ogr_miattrind.cpp index f16b994c3926..93dba0d9d15a 100644 --- a/ogr/ogrsf_frmts/generic/ogr_miattrind.cpp +++ b/ogr/ogrsf_frmts/generic/ogr_miattrind.cpp @@ -164,9 +164,11 @@ OGRErr OGRMILayerAttrIndex::Initialize(const char *pszIndexPathIn, if (STARTS_WITH_CI(pszIndexPathIn, "")) return LoadConfigFromXML(pszIndexPathIn); - pszMetadataFilename = CPLStrdup(CPLResetExtension(pszIndexPathIn, "idm")); + pszMetadataFilename = + CPLStrdup(CPLResetExtensionSafe(pszIndexPathIn, "idm").c_str()); - pszMIINDFilename = CPLStrdup(CPLResetExtension(pszIndexPathIn, "ind")); + pszMIINDFilename = + CPLStrdup(CPLResetExtensionSafe(pszIndexPathIn, "ind").c_str()); /* -------------------------------------------------------------------- */ /* If a metadata file already exists, load it. */ diff --git a/ogr/ogrsf_frmts/geoconcept/geoconcept.c b/ogr/ogrsf_frmts/geoconcept/geoconcept.c index 39e9c3e46256..f2e2f9dd3518 100644 --- a/ogr/ogrsf_frmts/geoconcept/geoconcept.c +++ b/ogr/ogrsf_frmts/geoconcept/geoconcept.c @@ -991,9 +991,11 @@ static void GCIOAPI_CALL _Destroy_GCIO(GCExportFileH **hGXT, int delFile) { VSIFCloseL(GetGCHandle_GCIO(*hGXT)); SetGCHandle_GCIO(*hGXT, NULL); - VSIUnlink(CPLFormFilename(GetGCPath_GCIO(*hGXT), - GetGCBasename_GCIO(*hGXT), - GetGCExtension_GCIO(*hGXT))); + char *pszTmp = CPLStrdup(CPLFormFilename(GetGCPath_GCIO(*hGXT), + GetGCBasename_GCIO(*hGXT), + GetGCExtension_GCIO(*hGXT))); + VSIUnlink(pszTmp); + VSIFree(pszTmp); } _ReInit_GCIO(*hGXT); CPLFree(*hGXT); @@ -2762,21 +2764,24 @@ GCExportFileH GCIOAPI_CALL1(*) VSILFILE *h; /* file must exists ... */ - if (!(h = VSIFOpenL(CPLFormFilename(GetGCPath_GCIO(hGXT), - GetGCBasename_GCIO(hGXT), - GetGCExtension_GCIO(hGXT)), - "rt"))) + char *pszTmp = CPLStrdup(CPLFormFilename(GetGCPath_GCIO(hGXT), + GetGCBasename_GCIO(hGXT), + GetGCExtension_GCIO(hGXT))); + if (!(h = VSIFOpenL(pszTmp, "rt"))) { _Destroy_GCIO(&hGXT, FALSE); + CPLFree(pszTmp); return NULL; } + CPLFree(pszTmp); VSIFCloseL(h); } - SetGCHandle_GCIO(hGXT, VSIFOpenL(CPLFormFilename(GetGCPath_GCIO(hGXT), - GetGCBasename_GCIO(hGXT), - GetGCExtension_GCIO(hGXT)), - mode)); + char *pszTmp = CPLStrdup(CPLFormFilename(GetGCPath_GCIO(hGXT), + GetGCBasename_GCIO(hGXT), + GetGCExtension_GCIO(hGXT))); + SetGCHandle_GCIO(hGXT, VSIFOpenL(pszTmp, mode)); + CPLFree(pszTmp); if (!GetGCHandle_GCIO(hGXT)) { _Destroy_GCIO(&hGXT, FALSE); @@ -2791,11 +2796,11 @@ GCExportFileH GCIOAPI_CALL1(*) GCExportFileH *hGCT; hGCT = _Create_GCIO(gctPath, "gct", "-"); - SetGCHandle_GCIO( - hGCT, VSIFOpenL(CPLFormFilename(GetGCPath_GCIO(hGCT), - GetGCBasename_GCIO(hGCT), - GetGCExtension_GCIO(hGCT)), - "r")); + pszTmp = CPLStrdup(CPLFormFilename(GetGCPath_GCIO(hGCT), + GetGCBasename_GCIO(hGCT), + GetGCExtension_GCIO(hGCT))); + SetGCHandle_GCIO(hGCT, VSIFOpenL(pszTmp, "r")); + CPLFree(pszTmp); if (!GetGCHandle_GCIO(hGCT)) { CPLError(CE_Failure, CPLE_NotSupported, diff --git a/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdatasource.cpp b/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdatasource.cpp index 1f5a1ff54806..9fed6a8c57e1 100644 --- a/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdatasource.cpp +++ b/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdatasource.cpp @@ -120,13 +120,12 @@ int OGRGeoconceptDataSource::LoadFile(const char *pszMode) { if (_pszExt == nullptr) { - const char *pszExtension = CPLGetExtension(GetDescription()); - _pszExt = CPLStrdup(pszExtension); + _pszExt = CPLStrdup(CPLGetExtensionSafe(GetDescription()).c_str()); } CPLStrlwr(_pszExt); if (!_pszDirectory) - _pszDirectory = CPLStrdup(CPLGetPath(GetDescription())); + _pszDirectory = CPLStrdup(CPLGetPathSafe(GetDescription()).c_str()); if ((_hGXT = Open_GCIO(GetDescription(), _pszExt, pszMode, _pszGCT)) == nullptr) @@ -212,7 +211,7 @@ int OGRGeoconceptDataSource::Create(const char *pszName, char **papszOptions) const char *pszExtension = CSLFetchNameValue(papszOptions, "EXTENSION"); if (pszExtension == nullptr) { - _pszExt = CPLStrdup(CPLGetExtension(pszName)); + _pszExt = CPLStrdup(CPLGetExtensionSafe(pszName).c_str()); } else { @@ -234,21 +233,22 @@ int OGRGeoconceptDataSource::Create(const char *pszName, char **papszOptions) _pszDirectory = CPLStrdup(pszName); CPLFree(_pszExt); _pszExt = CPLStrdup("gxt"); - char *pszbName = CPLStrdup(CPLGetBasename(pszName)); + char *pszbName = CPLStrdup(CPLGetBasenameSafe(pszName).c_str()); if (strlen(pszbName) == 0) { /* pszName ends with '/' */ CPLFree(pszbName); char *pszNameDup = CPLStrdup(pszName); pszNameDup[strlen(pszName) - 2] = '\0'; - pszbName = CPLStrdup(CPLGetBasename(pszNameDup)); + pszbName = CPLStrdup(CPLGetBasenameSafe(pszNameDup).c_str()); CPLFree(pszNameDup); } - SetDescription(CPLFormFilename(_pszDirectory, pszbName, nullptr)); + SetDescription( + CPLFormFilenameSafe(_pszDirectory, pszbName, nullptr).c_str()); CPLFree(pszbName); } else { - _pszDirectory = CPLStrdup(CPLGetPath(pszName)); + _pszDirectory = CPLStrdup(CPLGetPathSafe(pszName).c_str()); SetDescription(pszName); } diff --git a/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdriver.cpp b/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdriver.cpp index 7153cf580a30..c739dbc99bc4 100644 --- a/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdriver.cpp +++ b/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptdriver.cpp @@ -27,8 +27,9 @@ static GDALDataset *OGRGeoconceptDriverOpen(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ /* We will only consider .gxt and .txt files. */ /* -------------------------------------------------------------------- */ - const char *pszExtension = CPLGetExtension(pszFilename); - if (!EQUAL(pszExtension, "gxt") && !EQUAL(pszExtension, "txt")) + const std::string osExtension = CPLGetExtensionSafe(pszFilename); + if (!EQUAL(osExtension.c_str(), "gxt") && + !EQUAL(osExtension.c_str(), "txt")) { return nullptr; } @@ -85,8 +86,8 @@ static GDALDataset *OGRGeoconceptDriverCreate(const char *pszName, /* Does it end with the extension .gxt indicating the user likely */ /* wants to create a single file set? */ /* -------------------------------------------------------------------- */ - else if (EQUAL(CPLGetExtension(pszName), "gxt") || - EQUAL(CPLGetExtension(pszName), "txt")) + else if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "gxt") || + EQUAL(CPLGetExtensionSafe(pszName).c_str(), "txt")) { /* bSingleNewFile = TRUE; */ } @@ -124,15 +125,15 @@ static CPLErr OGRGeoconceptDriverDelete(const char *pszDataSource) } if (VSI_ISREG(sStatBuf.st_mode) && - (EQUAL(CPLGetExtension(pszDataSource), "gxt") || - EQUAL(CPLGetExtension(pszDataSource), "txt"))) + (EQUAL(CPLGetExtensionSafe(pszDataSource).c_str(), "gxt") || + EQUAL(CPLGetExtensionSafe(pszDataSource).c_str(), "txt"))) { for (int iExt = 0; apszExtensions[iExt] != nullptr; iExt++) { - const char *pszFile = - CPLResetExtension(pszDataSource, apszExtensions[iExt]); - if (VSIStatL(pszFile, &sStatBuf) == 0) - VSIUnlink(pszFile); + const std::string osFile = + CPLResetExtensionSafe(pszDataSource, apszExtensions[iExt]); + if (VSIStatL(osFile.c_str(), &sStatBuf) == 0) + VSIUnlink(osFile.c_str()); } } else if (VSI_ISDIR(sStatBuf.st_mode)) @@ -143,11 +144,13 @@ static CPLErr OGRGeoconceptDriverDelete(const char *pszDataSource) papszDirEntries != nullptr && papszDirEntries[iFile] != nullptr; iFile++) { - if (CSLFindString(const_cast(apszExtensions), - CPLGetExtension(papszDirEntries[iFile])) != -1) + if (CSLFindString( + const_cast(apszExtensions), + CPLGetExtensionSafe(papszDirEntries[iFile]).c_str()) != -1) { - VSIUnlink(CPLFormFilename(pszDataSource, papszDirEntries[iFile], - nullptr)); + VSIUnlink(CPLFormFilenameSafe(pszDataSource, + papszDirEntries[iFile], nullptr) + .c_str()); } } diff --git a/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp b/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp index 7b1290589e1c..3c5610047fd5 100644 --- a/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp +++ b/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp @@ -96,13 +96,13 @@ void OGRESRIJSONReader::ReadLayers(OGRGeoJSONDataSource *poDS, OGRSpatialReference *poSRS = OGRESRIJSONReadSpatialReference(poGJObject_); - const char *pszName = "ESRIJSON"; + std::string osName = "ESRIJSON"; if (eSourceType == eGeoJSONSourceFile) { - pszName = poDS->GetDescription(); - if (STARTS_WITH_CI(pszName, "ESRIJSON:")) - pszName += strlen("ESRIJSON:"); - pszName = CPLGetBasename(pszName); + osName = poDS->GetDescription(); + if (STARTS_WITH_CI(osName.c_str(), "ESRIJSON:")) + osName = osName.substr(strlen("ESRIJSON:")); + osName = CPLGetBasenameSafe(osName.c_str()); } auto eGeomType = OGRESRIJSONGetGeometryType(poGJObject_); @@ -141,7 +141,8 @@ void OGRESRIJSONReader::ReadLayers(OGRGeoJSONDataSource *poDS, } } - poLayer_ = new OGRGeoJSONLayer(pszName, poSRS, eGeomType, poDS, nullptr); + poLayer_ = + new OGRGeoJSONLayer(osName.c_str(), poSRS, eGeomType, poDS, nullptr); if (poSRS != nullptr) poSRS->Release(); diff --git a/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp b/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp index fddf907519f1..41e41b2146a5 100644 --- a/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp +++ b/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp @@ -415,14 +415,15 @@ bool OGRGeoJSONReader::FirstPassReadLayer(OGRGeoJSONDataSource *poDS, VSIFSeekL(fp, 0, SEEK_SET); bFirstSeg_ = true; - const char *pszName = poDS->GetDescription(); - if (STARTS_WITH_CI(pszName, "GeoJSON:")) - pszName += strlen("GeoJSON:"); - pszName = CPLGetBasename(pszName); - pszName = OGRGeoJSONLayer::GetValidLayerName(pszName); - - OGRGeoJSONLayer *poLayer = new OGRGeoJSONLayer( - pszName, nullptr, OGRGeoJSONLayer::DefaultGeometryType, poDS, this); + std::string osName = poDS->GetDescription(); + if (STARTS_WITH_CI(osName.c_str(), "GeoJSON:")) + osName = osName.substr(strlen("GeoJSON:")); + osName = CPLGetBasenameSafe(osName.c_str()); + osName = OGRGeoJSONLayer::GetValidLayerName(osName.c_str()); + + OGRGeoJSONLayer *poLayer = + new OGRGeoJSONLayer(osName.c_str(), nullptr, + OGRGeoJSONLayer::DefaultGeometryType, poDS, this); OGRGeoJSONReaderStreamingParser oParser(*this, poLayer, true, bStoreNativeData_); @@ -911,7 +912,12 @@ void OGRGeoJSONReader::ReadLayer(OGRGeoJSONDataSource *poDS, CPLErrorReset(); // Figure out layer name - if (pszName == nullptr) + std::string osName; + if (pszName) + { + osName = pszName; + } + else { if (GeoJSONObject::eFeatureCollection == objType) { @@ -922,20 +928,25 @@ void OGRGeoJSONReader::ReadLayer(OGRGeoJSONDataSource *poDS, pszName = json_object_get_string(poName); } } - if (pszName == nullptr) + if (pszName) + { + osName = pszName; + } + else { const char *pszDesc = poDS->GetDescription(); if (strchr(pszDesc, '?') == nullptr && strchr(pszDesc, '{') == nullptr) { - pszName = CPLGetBasename(pszDesc); + osName = CPLGetBasenameSafe(pszDesc); } } } - pszName = OGRGeoJSONLayer::GetValidLayerName(pszName); + osName = OGRGeoJSONLayer::GetValidLayerName(osName.c_str()); OGRGeoJSONLayer *poLayer = new OGRGeoJSONLayer( - pszName, nullptr, OGRGeoJSONLayer::DefaultGeometryType, poDS, nullptr); + osName.c_str(), nullptr, OGRGeoJSONLayer::DefaultGeometryType, poDS, + nullptr); OGRSpatialReference *poSRS = OGRGeoJSONReadSpatialReference(poObj); bool bDefaultSRS = false; diff --git a/ogr/ogrsf_frmts/geojson/ogrgeojsonseqdriver.cpp b/ogr/ogrsf_frmts/geojson/ogrgeojsonseqdriver.cpp index b41e6c3ab86b..3688e95a91db 100644 --- a/ogr/ogrsf_frmts/geojson/ogrgeojsonseqdriver.cpp +++ b/ogr/ogrsf_frmts/geojson/ogrgeojsonseqdriver.cpp @@ -789,13 +789,13 @@ bool OGRGeoJSONSeqDataSource::Open(GDALOpenInfo *poOpenInfo, { if (pszUnprefixedFilename != poOpenInfo->pszFilename) { - osLayerName = CPLGetBasename(pszUnprefixedFilename); + osLayerName = CPLGetBasenameSafe(pszUnprefixedFilename); m_fp = VSIFOpenL(pszUnprefixedFilename, poOpenInfo->eAccess == GA_Update ? "rb+" : "rb"); } else { - osLayerName = CPLGetBasename(poOpenInfo->pszFilename); + osLayerName = CPLGetBasenameSafe(poOpenInfo->pszFilename); std::swap(m_fp, poOpenInfo->fpL); } } @@ -912,7 +912,7 @@ bool OGRGeoJSONSeqDataSource::Create(const char *pszName, eAccess = GA_Update; - m_bIsRSSeparated = EQUAL(CPLGetExtension(pszName), "GEOJSONS"); + m_bIsRSSeparated = EQUAL(CPLGetExtensionSafe(pszName).c_str(), "GEOJSONS"); return true; } diff --git a/ogr/ogrsf_frmts/gml/gmlregistry.cpp b/ogr/ogrsf_frmts/gml/gmlregistry.cpp index 381dfd3c9cbe..196d6957daa3 100644 --- a/ogr/ogrsf_frmts/gml/gmlregistry.cpp +++ b/ogr/ogrsf_frmts/gml/gmlregistry.cpp @@ -128,41 +128,39 @@ bool GMLRegistryFeatureType::Parse(const char *pszRegistryFilename, CPLXMLNode *psNode) { const char *pszElementName = CPLGetXMLValue(psNode, "elementName", nullptr); - const char *pszSchemaLocation = - CPLGetXMLValue(psNode, "schemaLocation", nullptr); - const char *pszGFSSchemaLocation = - CPLGetXMLValue(psNode, "gfsSchemaLocation", nullptr); + osSchemaLocation = CPLGetXMLValue(psNode, "schemaLocation", ""); + osGFSSchemaLocation = CPLGetXMLValue(psNode, "gfsSchemaLocation", ""); if (pszElementName == nullptr || - (pszSchemaLocation == nullptr && pszGFSSchemaLocation == nullptr)) + (osSchemaLocation.empty() && osGFSSchemaLocation.empty())) return false; const char *pszElementValue = CPLGetXMLValue(psNode, "elementValue", nullptr); osElementName = pszElementName; - if (pszSchemaLocation != nullptr) + if (!osSchemaLocation.empty()) { if (pszRegistryFilename[0] && - !STARTS_WITH(pszSchemaLocation, "http://") && - !STARTS_WITH(pszSchemaLocation, "https://") && - CPLIsFilenameRelative(pszSchemaLocation)) + !STARTS_WITH(osSchemaLocation.c_str(), "http://") && + !STARTS_WITH(osSchemaLocation.c_str(), "https://") && + CPLIsFilenameRelative(osSchemaLocation.c_str())) { - pszSchemaLocation = CPLFormFilename(CPLGetPath(pszRegistryFilename), - pszSchemaLocation, nullptr); + osSchemaLocation = + CPLFormFilenameSafe(CPLGetPathSafe(pszRegistryFilename).c_str(), + osSchemaLocation.c_str(), nullptr); } - osSchemaLocation = pszSchemaLocation; } - else if (pszGFSSchemaLocation != nullptr) + else if (!osGFSSchemaLocation.empty()) { if (pszRegistryFilename[0] && - !STARTS_WITH(pszGFSSchemaLocation, "http://") && - !STARTS_WITH(pszGFSSchemaLocation, "https://") && - CPLIsFilenameRelative(pszGFSSchemaLocation)) + !STARTS_WITH(osGFSSchemaLocation.c_str(), "http://") && + !STARTS_WITH(osGFSSchemaLocation.c_str(), "https://") && + CPLIsFilenameRelative(osGFSSchemaLocation.c_str())) { - pszGFSSchemaLocation = CPLFormFilename( - CPLGetPath(pszRegistryFilename), pszGFSSchemaLocation, nullptr); + osGFSSchemaLocation = + CPLFormFilenameSafe(CPLGetPathSafe(pszRegistryFilename).c_str(), + osGFSSchemaLocation.c_str(), nullptr); } - osGFSSchemaLocation = pszGFSSchemaLocation; } if (pszElementValue != nullptr) diff --git a/ogr/ogrsf_frmts/gml/hugefileresolver.cpp b/ogr/ogrsf_frmts/gml/hugefileresolver.cpp index b80e9073a479..f1748cb54ea2 100644 --- a/ogr/ogrsf_frmts/gml/hugefileresolver.cpp +++ b/ogr/ogrsf_frmts/gml/hugefileresolver.cpp @@ -1842,8 +1842,8 @@ bool GMLReader::ParseXMLHugeFile(const char *pszOutputFilename, /* -------------------------------------------------------------------- */ /* Creating/Opening the SQLite DB file */ /* -------------------------------------------------------------------- */ - const CPLString osSQLiteFilename = - CPLResetExtension(m_pszFilename, "sqlite"); + const std::string osSQLiteFilename = + CPLResetExtensionSafe(m_pszFilename, "sqlite"); const char *pszSQLiteFilename = osSQLiteFilename.c_str(); VSIStatBufL statBufL; diff --git a/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp b/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp index 1020e0dcfe0a..2f441ce4e792 100644 --- a/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp +++ b/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp @@ -429,7 +429,7 @@ bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo) // it transparently with /vsigzip/. if (static_cast(szHeader[0]) == 0x1f && static_cast(szHeader[1]) == 0x8b && - EQUAL(CPLGetExtension(pszFilename), "gz") && + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "gz") && !STARTS_WITH(pszFilename, "/vsigzip/")) { if (fpToClose) @@ -755,8 +755,8 @@ bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo) { // When no option is given or is not recognised, // use the same file name with the extension changed to .resolved.gml - pszXlinkResolvedFilename = - CPLStrdup(CPLResetExtension(pszFilename, "resolved.gml")); + pszXlinkResolvedFilename = CPLStrdup( + CPLResetExtensionSafe(pszFilename, "resolved.gml").c_str()); // Check if the file already exists. VSIStatBufL sResStatBuf, sGMLStatBuf; @@ -857,7 +857,7 @@ bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo) CPLString osGFSFilename; if (!bIsWFSFromServer) { - osGFSFilename = CPLResetExtension(pszFilename, "gfs"); + osGFSFilename = CPLResetExtensionSafe(pszFilename, "gfs"); if (STARTS_WITH(osGFSFilename, "/vsigzip/")) osGFSFilename = osGFSFilename.substr(strlen("/vsigzip/")); } @@ -883,12 +883,14 @@ bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo) bHaveSchema = poReader->LoadClasses(osGFSFilename); if (bHaveSchema) { - pszXSDFilenameTmp = CPLResetExtension(pszFilename, "xsd"); - if (VSIStatExL(pszXSDFilenameTmp, &sGMLStatBuf, + const std::string osXSDFilenameTmp = + CPLResetExtensionSafe(pszFilename, "xsd"); + if (VSIStatExL(osXSDFilenameTmp.c_str(), &sGMLStatBuf, VSI_STAT_EXISTS_FLAG) == 0) { CPLDebug("GML", "Using %s file, ignoring %s", - osGFSFilename.c_str(), pszXSDFilenameTmp); + osGFSFilename.c_str(), + osXSDFilenameTmp.c_str()); } } } @@ -909,7 +911,7 @@ bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo) VSIStatBufL sXSDStatBuf; if (osXSDFilename.empty()) { - osXSDFilename = CPLResetExtension(pszFilename, "xsd"); + osXSDFilename = CPLResetExtensionSafe(pszFilename, "xsd"); if (bCheckAuxFile && VSIStatExL(osXSDFilename, &sXSDStatBuf, VSI_STAT_EXISTS_FLAG) == 0) { @@ -1902,9 +1904,10 @@ bool OGRGMLDataSource::Create(const char *pszFilename, char **papszOptions) } else if (STARTS_WITH(pszFilename, "/vsizip/")) { - if (EQUAL(CPLGetExtension(pszFilename), "zip")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "zip")) { - SetDescription(CPLFormFilename(pszFilename, "out.gml", nullptr)); + SetDescription( + CPLFormFilenameSafe(pszFilename, "out.gml", nullptr).c_str()); } fpOutput = VSIFOpenExL(GetDescription(), "wb", true); @@ -1959,13 +1962,15 @@ bool OGRGMLDataSource::Create(const char *pszFilename, char **papszOptions) } else if (pszSchemaOpt == nullptr || EQUAL(pszSchemaOpt, "EXTERNAL")) { - char *pszBasename = CPLStrdup(CPLGetBasename(GetDescription())); + char *pszBasename = + CPLStrdup(CPLGetBasenameSafe(GetDescription()).c_str()); PrintLine( fpOutput, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""); PrintLine(fpOutput, " xsi:schemaLocation=\"%s %s\"", - pszTargetNameSpace, CPLResetExtension(pszBasename, "xsd")); + pszTargetNameSpace, + CPLResetExtensionSafe(pszBasename, "xsd").c_str()); CPLFree(pszBasename); } @@ -2363,14 +2368,15 @@ void OGRGMLDataSource::InsertHeader() VSILFILE *fpSchema = nullptr; if (pszSchemaOpt == nullptr || EQUAL(pszSchemaOpt, "EXTERNAL")) { - const char *pszXSDFilename = CPLResetExtension(GetDescription(), "xsd"); + const std::string l_osXSDFilename = + CPLResetExtensionSafe(GetDescription(), "xsd"); - fpSchema = VSIFOpenL(pszXSDFilename, "wt"); + fpSchema = VSIFOpenL(l_osXSDFilename.c_str(), "wt"); if (fpSchema == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open file %.500s for schema output.", - pszXSDFilename); + l_osXSDFilename.c_str()); return; } PrintLine(fpSchema, ""); diff --git a/ogr/ogrsf_frmts/gml/ogrgmldriver.cpp b/ogr/ogrsf_frmts/gml/ogrgmldriver.cpp index 6ff5d56408aa..6b25e1c53481 100644 --- a/ogr/ogrsf_frmts/gml/ogrgmldriver.cpp +++ b/ogr/ogrsf_frmts/gml/ogrgmldriver.cpp @@ -32,7 +32,7 @@ static int OGRGMLDriverIdentify(GDALOpenInfo *poOpenInfo) /* it transparently with /vsigzip/ */ else if (poOpenInfo->pabyHeader[0] == 0x1f && poOpenInfo->pabyHeader[1] == 0x8b && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "gz") && + poOpenInfo->IsExtensionEqualToCI("gz") && !STARTS_WITH(poOpenInfo->pszFilename, "/vsigzip/")) { return -1; /* must be later checked */ diff --git a/ogr/ogrsf_frmts/gml/resolvexlinks.cpp b/ogr/ogrsf_frmts/gml/resolvexlinks.cpp index 9940a3b1d2ee..6b687efd5ea2 100644 --- a/ogr/ogrsf_frmts/gml/resolvexlinks.cpp +++ b/ogr/ogrsf_frmts/gml/resolvexlinks.cpp @@ -573,7 +573,8 @@ bool GMLReader::ResolveXlinks(const char *pszFile, bool *pbOutIsTempFile, if (bTryWithTempFile) { - pszTmpName = CPLStrdup(CPLGenerateTempFilename("ResolvedGML")); + pszTmpName = + CPLStrdup(CPLGenerateTempFilenameSafe("ResolvedGML").c_str()); if (!CPLSerializeXMLTreeToFile(papsSrcTree[0], pszTmpName)) { CPLError(CE_Failure, CPLE_FileIO, diff --git a/ogr/ogrsf_frmts/gmlas/ogrgmlasconf.cpp b/ogr/ogrsf_frmts/gmlas/ogrgmlasconf.cpp index 6e0e966c490b..80d97e9bf176 100644 --- a/ogr/ogrsf_frmts/gmlas/ogrgmlasconf.cpp +++ b/ogr/ogrsf_frmts/gmlas/ogrgmlasconf.cpp @@ -35,7 +35,7 @@ CPLString GMLASConfiguration::GetBaseCacheDirectory() #endif if (pszHome != nullptr) { - return CPLFormFilename(pszHome, ".gdal", nullptr); + return CPLFormFilenameSafe(pszHome, ".gdal", nullptr); } else { @@ -53,8 +53,8 @@ CPLString GMLASConfiguration::GetBaseCacheDirectory() if (pszDir != nullptr && pszUsername != nullptr) { - return CPLFormFilename(pszDir, CPLSPrintf(".gdal_%s", pszUsername), - nullptr); + return CPLFormFilenameSafe( + pszDir, CPLSPrintf(".gdal_%s", pszUsername), nullptr); } } return CPLString(); @@ -76,8 +76,8 @@ void GMLASConfiguration::Finalize() } else { - m_osXSDCacheDirectory = CPLFormFilename(m_osXSDCacheDirectory, - "gmlas_xsd_cache", nullptr); + m_osXSDCacheDirectory = CPLFormFilenameSafe( + m_osXSDCacheDirectory, "gmlas_xsd_cache", nullptr); CPLDebug("GMLAS", "XSD cache directory: %s", m_osXSDCacheDirectory.c_str()); } @@ -564,7 +564,7 @@ bool GMLASXLinkResolutionConf::LoadFromXML(CPLXMLNode *psRoot) m_osCacheDirectory = GMLASConfiguration::GetBaseCacheDirectory(); if (!m_osCacheDirectory.empty()) { - m_osCacheDirectory = CPLFormFilename( + m_osCacheDirectory = CPLFormFilenameSafe( m_osCacheDirectory, "xlink_resolved_cache", nullptr); } } diff --git a/ogr/ogrsf_frmts/gmlas/ogrgmlasdatasource.cpp b/ogr/ogrsf_frmts/gmlas/ogrgmlasdatasource.cpp index 4e2261d76a56..d6b0b784cd14 100644 --- a/ogr/ogrsf_frmts/gmlas/ogrgmlasdatasource.cpp +++ b/ogr/ogrsf_frmts/gmlas/ogrgmlasdatasource.cpp @@ -468,7 +468,8 @@ void OGRGMLASDataSource::FillOtherMetadataLayer( { oFeature.SetField( szVALUE, - CPLFormFilename(pszCurDir, osConfigFile, nullptr)); + CPLFormFilenameSafe(pszCurDir, osConfigFile, nullptr) + .c_str()); } else { @@ -520,7 +521,7 @@ void OGRGMLASDataSource::FillOtherMetadataLayer( CPLIsFilenameRelative(m_osGMLFilename) && pszCurDir != nullptr) { osAbsoluteGMLFilename = - CPLFormFilename(pszCurDir, m_osGMLFilename, nullptr); + CPLFormFilenameSafe(pszCurDir, m_osGMLFilename, nullptr); } else osAbsoluteGMLFilename = m_osGMLFilename; @@ -534,7 +535,7 @@ void OGRGMLASDataSource::FillOtherMetadataLayer( for (int i = 0; i < static_cast(aoXSDs.size()); i++) { const CPLString osURI(aoXSDs[i].first); - const CPLString osXSDFilename(aoXSDs[i].second); + const std::string osXSDFilename(aoXSDs[i].second); oSetVisitedURI.insert(osURI); @@ -557,10 +558,10 @@ void OGRGMLASDataSource::FillOtherMetadataLayer( const CPLString osAbsoluteXSDFilename( (osXSDFilename.find("http://") != 0 && osXSDFilename.find("https://") != 0 && - CPLIsFilenameRelative(osXSDFilename)) - ? CPLString( - CPLFormFilename(CPLGetDirname(osAbsoluteGMLFilename), - osXSDFilename, nullptr)) + CPLIsFilenameRelative(osXSDFilename.c_str())) + ? CPLFormFilenameSafe( + CPLGetDirnameSafe(osAbsoluteGMLFilename).c_str(), + osXSDFilename.c_str(), nullptr) : osXSDFilename); oFeature.SetField(szVALUE, osAbsoluteXSDFilename.c_str()); CPL_IGNORE_RET_VAL( @@ -652,7 +653,8 @@ OGRGMLASDataSource::BuildXSDVector(const CPLString &osXSDFilenames) CPLIsFilenameRelative(papszTokens[i]) && pszCurDir != nullptr) { aoXSDs.push_back(PairURIFilename( - "", CPLFormFilename(pszCurDir, papszTokens[i], nullptr))); + "", CPLFormFilenameSafe(pszCurDir, papszTokens[i], nullptr) + .c_str())); } else { @@ -734,10 +736,10 @@ bool OGRGMLASDataSource::Open(GDALOpenInfo *poOpenInfo) m_oConf.m_nMaximumFieldsForFlattening); oAnalyzer.SetAlwaysGenerateOGRId(m_oConf.m_bAlwaysGenerateOGRId); - m_osGMLFilename = - STARTS_WITH_CI(poOpenInfo->pszFilename, szGMLAS_PREFIX) - ? CPLExpandTilde(poOpenInfo->pszFilename + strlen(szGMLAS_PREFIX)) - : poOpenInfo->pszFilename; + m_osGMLFilename = STARTS_WITH_CI(poOpenInfo->pszFilename, szGMLAS_PREFIX) + ? CPLExpandTildeSafe(poOpenInfo->pszFilename + + strlen(szGMLAS_PREFIX)) + : poOpenInfo->pszFilename; CPLString osXSDFilenames = CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, szXSD_OPTION, ""); @@ -859,9 +861,9 @@ bool OGRGMLASDataSource::Open(GDALOpenInfo *poOpenInfo) szHANDLE_MULTIPLE_IMPORTS_OPTION, m_oConf.m_bHandleMultipleImports); - bool bRet = - oAnalyzer.Analyze(m_oCache, CPLGetDirname(m_osGMLFilename), aoXSDs, - m_bSchemaFullChecking, m_bHandleMultipleImports); + bool bRet = oAnalyzer.Analyze( + m_oCache, CPLGetDirnameSafe(m_osGMLFilename).c_str(), aoXSDs, + m_bSchemaFullChecking, m_bHandleMultipleImports); if (!bRet) { return false; diff --git a/ogr/ogrsf_frmts/gmlas/ogrgmlasreader.cpp b/ogr/ogrsf_frmts/gmlas/ogrgmlasreader.cpp index 41ceb0ea9d4c..a137ba4758b0 100644 --- a/ogr/ogrsf_frmts/gmlas/ogrgmlasreader.cpp +++ b/ogr/ogrsf_frmts/gmlas/ogrgmlasreader.cpp @@ -261,7 +261,8 @@ void GMLASBaseEntityResolver::notifyClosing(const CPLString &osFilename) { CPLDebug("GMLAS", "Closing %s", osFilename.c_str()); - CPLAssert(m_aosPathStack.back() == CPLString(CPLGetDirname(osFilename))); + CPLAssert(m_aosPathStack.back() == + CPLString(CPLGetDirnameSafe(osFilename))); m_aosPathStack.pop_back(); } @@ -334,7 +335,7 @@ GMLASBaseEntityResolver::resolveEntity(const XMLCh *const /*publicId*/, DoExtraSchemaProcessing(osNewPath, fp); } - m_aosPathStack.push_back(CPLGetDirname(osNewPath)); + m_aosPathStack.push_back(CPLGetDirnameSafe(osNewPath).c_str()); GMLASInputSource *poIS = new GMLASInputSource(osNewPath, fp); poIS->SetClosingCallback(this); return poIS; @@ -449,7 +450,8 @@ bool GMLASReader::LoadXSDInParser( (osXSDFilename.find("http://") != 0 && osXSDFilename.find("https://") != 0 && CPLIsFilenameRelative(osXSDFilename)) - ? CPLString(CPLFormFilename(osBaseDirname, osXSDFilename, nullptr)) + ? CPLString( + CPLFormFilenameSafe(osBaseDirname, osXSDFilename, nullptr)) : osXSDFilename); for (int iPass = 0; iPass <= 1; ++iPass) @@ -469,7 +471,7 @@ bool GMLASReader::LoadXSDInParser( bHandleMultipleImports); // Install a temporary entity resolved based on the current XSD - CPLString osXSDDirname(CPLGetDirname(osModifXSDFilename)); + CPLString osXSDDirname(CPLGetDirnameSafe(osModifXSDFilename)); if (osXSDFilename.find("http://") == 0 || osXSDFilename.find("https://") == 0) { @@ -640,7 +642,7 @@ bool GMLASReader::Init(const char *pszFilename, m_poSAXReader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, false); - CPLString osBaseDirname(CPLGetDirname(pszFilename)); + CPLString osBaseDirname(CPLGetDirnameSafe(pszFilename)); // In the case the schemas are explicitly passed, we must do special // processing diff --git a/ogr/ogrsf_frmts/gmlas/ogrgmlaswriter.cpp b/ogr/ogrsf_frmts/gmlas/ogrgmlaswriter.cpp index dd2791daf8f3..aba5c1b3749c 100644 --- a/ogr/ogrsf_frmts/gmlas/ogrgmlaswriter.cpp +++ b/ogr/ogrsf_frmts/gmlas/ogrgmlaswriter.cpp @@ -495,7 +495,7 @@ bool GMLASWriter::Write(GDALProgressFunc pfnProgress, void *pProgressData) // Write .xsd if (bWFS2FeatureCollection) - VSIUnlink(CPLResetExtension(m_osFilename, "xsd")); + VSIUnlink(CPLResetExtensionSafe(m_osFilename, "xsd").c_str()); else if (bGenerateXSD && !WriteXSD(osOutXSDFilename, aoXSDs)) return false; @@ -579,7 +579,7 @@ bool GMLASWriter::WriteXSD(const CPLString &osXSDFilenameIn, const CPLString osXSDFilename( !osXSDFilenameIn.empty() ? osXSDFilenameIn - : CPLString(CPLResetExtension(m_osFilename, "xsd"))); + : CPLString(CPLResetExtensionSafe(m_osFilename, "xsd"))); VSILFILE *fpXSD = VSIFOpenL(osXSDFilename, "wb"); if (fpXSD == nullptr) { @@ -666,7 +666,7 @@ bool GMLASWriter::WriteXMLHeader( } // Delete potentially existing .gfs file - VSIUnlink(CPLResetExtension(m_osFilename, "gfs")); + VSIUnlink(CPLResetExtensionSafe(m_osFilename, "gfs").c_str()); std::map aoWrittenPrefixes; aoWrittenPrefixes[szXSI_PREFIX] = szXSI_URI; @@ -723,8 +723,8 @@ bool GMLASWriter::WriteXMLHeader( const CPLString osXSDFilename( !osXSDFilenameIn.empty() ? osXSDFilenameIn - : CPLString( - CPLGetFilename(CPLResetExtension(m_osFilename, "xsd")))); + : CPLString(CPLGetFilename( + CPLResetExtensionSafe(m_osFilename, "xsd").c_str()))); osSchemaURI += m_osTargetNameSpace; osSchemaURI += " "; osSchemaURI += osXSDFilename; @@ -2819,7 +2819,7 @@ GDALDataset *OGRGMLASDriverCreateCopy(const char *pszFilename, GDALProgressFunc pfnProgress, void *pProgressData) { - if (strcmp(CPLGetExtension(pszFilename), "xsd") == 0) + if (strcmp(CPLGetExtensionSafe(pszFilename).c_str(), "xsd") == 0) { CPLError(CE_Failure, CPLE_AppDefined, ".xsd extension is not valid"); return nullptr; diff --git a/ogr/ogrsf_frmts/gmlas/ogrgmlasxsdcache.cpp b/ogr/ogrsf_frmts/gmlas/ogrgmlasxsdcache.cpp index bf9abaf108de..9a2d0eabf0e6 100644 --- a/ogr/ogrsf_frmts/gmlas/ogrgmlasxsdcache.cpp +++ b/ogr/ogrsf_frmts/gmlas/ogrgmlasxsdcache.cpp @@ -39,7 +39,7 @@ bool GMLASResourceCache::RecursivelyCreateDirectoryIfNeeded( return true; } - std::string osParent = CPLGetDirname(osDirname.c_str()); + std::string osParent = CPLGetDirnameSafe(osDirname.c_str()); if (!osParent.empty() && osParent != ".") { if (!RecursivelyCreateDirectoryIfNeeded(osParent.c_str())) @@ -115,8 +115,8 @@ std::string GMLASResourceCache::GetCachedFilename(const std::string &osResource) osLaunderedName.c_str()); } - return CPLFormFilename(m_osCacheDirectory.c_str(), osLaunderedName.c_str(), - nullptr); + return CPLFormFilenameSafe(m_osCacheDirectory.c_str(), + osLaunderedName.c_str(), nullptr); } /************************************************************************/ @@ -268,12 +268,12 @@ VSILFILE *GMLASXSDCache::Open(const std::string &osResource, STARTS_WITH(osResourceModified.c_str(), "..\\")) && !osBasePathModified.empty()) { - osBasePathModified = CPLGetDirname(osBasePathModified.c_str()); + osBasePathModified = CPLGetDirnameSafe(osBasePathModified.c_str()); osResourceModified = osResourceModified.substr(3); } - osOutFilename = CPLFormFilename(osBasePathModified.c_str(), - osResourceModified.c_str(), nullptr); + osOutFilename = CPLFormFilenameSafe( + osBasePathModified.c_str(), osResourceModified.c_str(), nullptr); } CPLDebug("GMLAS", "Resolving %s (%s) to %s", osResource.c_str(), diff --git a/ogr/ogrsf_frmts/gmlutils/parsexsd.cpp b/ogr/ogrsf_frmts/gmlutils/parsexsd.cpp index bec8fae945a4..e1770e4bdd94 100644 --- a/ogr/ogrsf_frmts/gmlutils/parsexsd.cpp +++ b/ogr/ogrsf_frmts/gmlutils/parsexsd.cpp @@ -865,23 +865,19 @@ static GMLFeatureClass *GMLParseFeatureType(CPLXMLNode *psSchemaNode, } /************************************************************************/ -/* ExcludeBaseGMLSchemas() */ +/* ExcludeBaseGMLSchemas() */ /************************************************************************/ -static bool ExcludeBaseGMLSchemas(const char *pszFilename) +static bool ExcludeBaseGMLSchemas(const std::string &osFilename) { // List of substrings to exclude const std::vector excludedBaseGMLReferencedSchemasList = { "/gml/3.2.1/", "gml/3.1.1/", "/gml/2.1.2/", "/gmlsfProfile/"}; - if (pszFilename != nullptr) + for (const auto &pattern : excludedBaseGMLReferencedSchemasList) { - const std::string osFilename(pszFilename); - for (const auto &pattern : excludedBaseGMLReferencedSchemasList) + if (osFilename.find(pattern) != std::string::npos) { - if (osFilename.find(pattern) != std::string::npos) - { - return false; // Found one of the excluded base GML referenced schema - } + return false; // Found one of the excluded base GML referenced schema } } return true; // None of the base GML referenced schemas were found @@ -964,32 +960,32 @@ static void CPLXMLSchemaResolveInclude(const char *pszMainSchemaLocation, CPLXMLNode *psThis = psSchemaNode->psChild; for (; psThis != nullptr; psThis = psThis->psNext) { - const char *pszSchemaLocation = - CPLGetXMLValue(psThis, "schemaLocation", nullptr); + std::string osSchemaLocation = + CPLGetXMLValue(psThis, "schemaLocation", ""); if (psThis->eType == CXT_Element && (EQUAL(psThis->pszValue, "include") || (bUseSchemaImports == TRUE && EQUAL(psThis->pszValue, "import") && - ExcludeBaseGMLSchemas(pszSchemaLocation)))) + ExcludeBaseGMLSchemas(osSchemaLocation)))) { - if (pszSchemaLocation != nullptr && - osAlreadyIncluded.count(pszSchemaLocation) == 0) + if (!osSchemaLocation.empty() && + osAlreadyIncluded.count(osSchemaLocation) == 0) { - osAlreadyIncluded.insert(pszSchemaLocation); + osAlreadyIncluded.insert(osSchemaLocation); - if (!STARTS_WITH(pszSchemaLocation, "http://") && - !STARTS_WITH(pszSchemaLocation, "https://") && - CPLIsFilenameRelative(pszSchemaLocation)) + if (!STARTS_WITH(osSchemaLocation.c_str(), "http://") && + !STARTS_WITH(osSchemaLocation.c_str(), "https://") && + CPLIsFilenameRelative(osSchemaLocation.c_str())) { - pszSchemaLocation = - CPLFormFilename(CPLGetPath(pszMainSchemaLocation), - pszSchemaLocation, nullptr); + osSchemaLocation = CPLFormFilenameSafe( + CPLGetPathSafe(pszMainSchemaLocation).c_str(), + osSchemaLocation.c_str(), nullptr); } CPLXMLNode *psIncludedXSDTree = - GMLParseXMLFile(pszSchemaLocation); + GMLParseXMLFile(osSchemaLocation.c_str()); if (psIncludedXSDTree != nullptr) { CPLStripXMLNamespace(psIncludedXSDTree, nullptr, TRUE); diff --git a/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp b/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp index c96cc625e9f7..1c481e62c189 100644 --- a/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp +++ b/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp @@ -113,7 +113,7 @@ OGRGmtDataSource::ICreateLayer(const char *pszLayerName, /* layer name with the name from the gmt. */ /* -------------------------------------------------------------------- */ - CPLString osPath = CPLGetPath(GetDescription()); + CPLString osPath = CPLGetPathSafe(GetDescription()); CPLString osFilename(GetDescription()); const char *pszFlags = "wb+"; @@ -122,8 +122,8 @@ OGRGmtDataSource::ICreateLayer(const char *pszLayerName, if (STARTS_WITH(osFilename, "/vsistdout")) pszFlags = "wb"; - else if (!EQUAL(CPLGetExtension(GetDescription()), "gmt")) - osFilename = CPLFormFilename(osPath, pszLayerName, "gmt"); + else if (!EQUAL(CPLGetExtensionSafe(GetDescription()).c_str(), "gmt")) + osFilename = CPLFormFilenameSafe(osPath, pszLayerName, "gmt"); /* -------------------------------------------------------------------- */ /* Open the file. */ diff --git a/ogr/ogrsf_frmts/gmt/ogrgmtdriver.cpp b/ogr/ogrsf_frmts/gmt/ogrgmtdriver.cpp index 97886cfb234e..f697e6b17f3a 100644 --- a/ogr/ogrsf_frmts/gmt/ogrgmtdriver.cpp +++ b/ogr/ogrsf_frmts/gmt/ogrgmtdriver.cpp @@ -26,7 +26,7 @@ static int OGRGMTDriverIdentify(GDALOpenInfo *poOpenInfo) if (poOpenInfo->nHeaderBytes && strstr(pszHeader, "@VGMT") != nullptr) return true; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "GMT")) + if (poOpenInfo->IsExtensionEqualToCI("GMT")) return true; return false; diff --git a/ogr/ogrsf_frmts/gmt/ogrgmtlayer.cpp b/ogr/ogrsf_frmts/gmt/ogrgmtlayer.cpp index cfe60261fc78..c1297d847380 100644 --- a/ogr/ogrsf_frmts/gmt/ogrgmtlayer.cpp +++ b/ogr/ogrsf_frmts/gmt/ogrgmtlayer.cpp @@ -37,7 +37,7 @@ OGRGmtLayer::OGRGmtLayer(GDALDataset *poDS, const char *pszFilename, /* -------------------------------------------------------------------- */ /* Create the feature definition */ /* -------------------------------------------------------------------- */ - poFeatureDefn = new OGRFeatureDefn(CPLGetBasename(pszFilename)); + poFeatureDefn = new OGRFeatureDefn(CPLGetBasenameSafe(pszFilename).c_str()); SetDescription(poFeatureDefn->GetName()); poFeatureDefn->Reference(); diff --git a/ogr/ogrsf_frmts/gpkg/gdalgeopackagerasterband.cpp b/ogr/ogrsf_frmts/gpkg/gdalgeopackagerasterband.cpp index eec28da3e7fa..c29fb8b9639d 100644 --- a/ogr/ogrsf_frmts/gpkg/gdalgeopackagerasterband.cpp +++ b/ogr/ogrsf_frmts/gpkg/gdalgeopackagerasterband.cpp @@ -2918,7 +2918,7 @@ GDALGPKGMBTilesLikePseudoDataset::DoPartialFlushOfPartialTilesIfNecessary() { m_nLastSpaceCheckTimestamp = nCurTimeStamp; GIntBig nFreeSpace = - VSIGetDiskFreeSpace(CPLGetDirname(m_osTempDBFilename)); + VSIGetDiskFreeSpace(CPLGetDirnameSafe(m_osTempDBFilename).c_str()); bool bTryFreeing = false; if (nFreeSpace >= 0 && nFreeSpace < 1024 * 1024 * 1024) { @@ -2989,7 +2989,7 @@ CPLErr GDALGPKGMBTilesLikePseudoDataset::WriteShiftedTile( const char *pszBaseFilename = m_poParentDS ? m_poParentDS->IGetFilename() : IGetFilename(); m_osTempDBFilename = - CPLResetExtension(pszBaseFilename, "partial_tiles.db"); + CPLResetExtensionSafe(pszBaseFilename, "partial_tiles.db"); CPLPushErrorHandler(CPLQuietErrorHandler); VSIUnlink(m_osTempDBFilename); CPLPopErrorHandler(); diff --git a/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp b/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp index 2aa330ad5101..f9ab53c0f1cc 100644 --- a/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp +++ b/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp @@ -5131,8 +5131,8 @@ int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize, { m_osFinalFilename = pszFilename; } - m_pszFilename = - CPLStrdup(CPLGenerateTempFilename(CPLGetFilename(pszFilename))); + m_pszFilename = CPLStrdup( + CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str()); CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename); } else @@ -5555,9 +5555,9 @@ int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize, if (nBandsIn != 0) { - const char *pszTableName = CPLGetBasename(m_pszFilename); - m_osRasterTable = - CSLFetchNameValueDef(papszOptions, "RASTER_TABLE", pszTableName); + const std::string osTableName = CPLGetBasenameSafe(m_pszFilename); + m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE", + osTableName.c_str()); if (m_osRasterTable.empty()) { CPLError(CE_Failure, CPLE_AppDefined, @@ -6026,9 +6026,9 @@ GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename, CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) && CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr) { - CPLString osBasename( - CPLGetBasename(GetUnderlyingDataset(poSrcDS)->GetDescription())); - apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename); + const std::string osBasename(CPLGetBasenameSafe( + GetUnderlyingDataset(poSrcDS)->GetDescription())); + apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str()); } if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4) diff --git a/ogr/ogrsf_frmts/gpkg/ogrgeopackagedriver.cpp b/ogr/ogrsf_frmts/gpkg/ogrgeopackagedriver.cpp index 20e097fd9043..5995438d38df 100644 --- a/ogr/ogrsf_frmts/gpkg/ogrgeopackagedriver.cpp +++ b/ogr/ogrsf_frmts/gpkg/ogrgeopackagedriver.cpp @@ -81,7 +81,7 @@ static int OGRGeoPackageDriverIdentify(GDALOpenInfo *poOpenInfo, /* http://opengis.github.io/geopackage/#_file_extension_name */ /* But be tolerant, if the GPKG application id is found, because some */ /* producers don't necessarily honour that requirement (#6396) */ - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); const bool bIsRecognizedExtension = EQUAL(pszExt, "GPKG") || EQUAL(pszExt, "GPKX"); @@ -216,7 +216,7 @@ static int OGRGeoPackageDriverIdentify(GDALOpenInfo *poOpenInfo, && !EQUAL(CPLGetFilename(poOpenInfo->pszFilename), ".cur_input") #endif && !(STARTS_WITH(poOpenInfo->pszFilename, "/vsizip/") && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "zip")) && + poOpenInfo->IsExtensionEqualToCI("zip")) && !STARTS_WITH(poOpenInfo->pszFilename, "/vsigzip/")) { if (bEmitWarning) @@ -364,16 +364,16 @@ static GDALDataset *OGRGeoPackageDriverCreate(const char *pszFilename, } else { - const char *pszExt = CPLGetExtension(pszFilename); + const std::string osExt = CPLGetExtensionSafe(pszFilename); const bool bIsRecognizedExtension = - EQUAL(pszExt, "GPKG") || EQUAL(pszExt, "GPKX"); + EQUAL(osExt.c_str(), "GPKG") || EQUAL(osExt.c_str(), "GPKX"); if (!bIsRecognizedExtension) { CPLError( CE_Warning, CPLE_AppDefined, "The filename extension should be 'gpkg' instead of '%s' " "to conform to the GPKG specification.", - pszExt); + osExt.c_str()); } } } diff --git a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp index 00cd9eb51e28..aba77b8bbf85 100644 --- a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp +++ b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp @@ -240,7 +240,7 @@ int OGRGPSBabelDataSource::Open(const char *pszDatasourceName, const char *pszOptionUseTempFile = CPLGetConfigOption("USE_TEMPFILE", nullptr); if (pszOptionUseTempFile && CPLTestBool(pszOptionUseTempFile)) - osTmpFileName = CPLGenerateTempFilename(nullptr); + osTmpFileName = CPLGenerateTempFilenameSafe(nullptr); else osTmpFileName = VSIMemGenerateHiddenFilename("gpsbabel"); diff --git a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldriver.cpp b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldriver.cpp index 023a241752cc..f1ece454f29b 100644 --- a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldriver.cpp +++ b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldriver.cpp @@ -85,7 +85,7 @@ OGRGPSBabelDriverIdentifyInternal(GDALOpenInfo *poOpenInfo, poOpenInfo->pabyHeader[2] <= 'Z' && poOpenInfo->pabyHeader[3] >= 'A' && poOpenInfo->pabyHeader[3] <= 'Z' && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "igc")) + poOpenInfo->IsExtensionEqualToCI("igc")) pszGPSBabelDriverName = "igc"; static int bGPSBabelFound = -1; diff --git a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabelwritedatasource.cpp b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabelwritedatasource.cpp index f4eacc2d9a27..d0a866d24a9b 100644 --- a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabelwritedatasource.cpp +++ b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabelwritedatasource.cpp @@ -173,7 +173,7 @@ int OGRGPSBabelWriteDataSource::Create(const char *pszNameIn, if (pszOptionUseTempFile == nullptr) pszOptionUseTempFile = CPLGetConfigOption("USE_TEMPFILE", nullptr); if (pszOptionUseTempFile && CPLTestBool(pszOptionUseTempFile)) - osTmpFileName = CPLGenerateTempFilename(nullptr); + osTmpFileName = CPLGenerateTempFilenameSafe(nullptr); else osTmpFileName = VSIMemGenerateHiddenFilename("gpsbabel"); diff --git a/ogr/ogrsf_frmts/gtfs/ogrgtfsdriver.cpp b/ogr/ogrsf_frmts/gtfs/ogrgtfsdriver.cpp index fadc35e722fc..7a40e6f9630e 100644 --- a/ogr/ogrsf_frmts/gtfs/ogrgtfsdriver.cpp +++ b/ogr/ogrsf_frmts/gtfs/ogrgtfsdriver.cpp @@ -547,7 +547,7 @@ int OGRGTFSDataset::Identify(GDALOpenInfo *poOpenInfo) return TRUE; } - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "zip")) + if (!poOpenInfo->IsExtensionEqualToCI("zip")) return FALSE; // Check first filename in ZIP @@ -607,7 +607,7 @@ GDALDataset *OGRGTFSDataset::Open(GDALOpenInfo *poOpenInfo) const std::string osBaseDir( (!STARTS_WITH(pszGTFSFilename, "/vsizip/") && - EQUAL(CPLGetExtension(pszGTFSFilename), "zip")) + EQUAL(CPLGetExtensionSafe(pszGTFSFilename).c_str(), "zip")) ? std::string("/vsizip/{").append(pszGTFSFilename).append("}") : std::string(pszGTFSFilename)); @@ -618,7 +618,7 @@ GDALDataset *OGRGTFSDataset::Open(GDALOpenInfo *poOpenInfo) std::string osShapesFilename; for (const char *pszFilename : cpl::Iterate(aosFilenames)) { - if (!EQUAL(CPLGetExtension(pszFilename), "txt")) + if (!EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "txt")) continue; for (const char *pszFilenameInDir : apszRequiredFiles) { @@ -644,7 +644,7 @@ GDALDataset *OGRGTFSDataset::Open(GDALOpenInfo *poOpenInfo) { poDS->m_apoLayers.emplace_back( std::make_unique( - osBaseDir, CPLGetBasename(pszFilename), + osBaseDir, CPLGetBasenameSafe(pszFilename).c_str(), std::move(poCSVDataset))); } } diff --git a/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp b/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp index 9e8c7e0b9747..eca845762021 100644 --- a/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp +++ b/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp @@ -60,12 +60,12 @@ int OGRIdrisiDataSource::Open(const char *pszFilename) // -------------------------------------------------------------------- // Look for .vdc file // -------------------------------------------------------------------- - const char *pszVDCFilename = CPLResetExtension(pszFilename, "vdc"); - VSILFILE *fpVDC = VSIFOpenL(pszVDCFilename, "rb"); + std::string osVDCFilename = CPLResetExtensionSafe(pszFilename, "vdc"); + VSILFILE *fpVDC = VSIFOpenL(osVDCFilename.c_str(), "rb"); if (fpVDC == nullptr) { - pszVDCFilename = CPLResetExtension(pszFilename, "VDC"); - fpVDC = VSIFOpenL(pszVDCFilename, "rb"); + osVDCFilename = CPLResetExtensionSafe(pszFilename, "VDC"); + fpVDC = VSIFOpenL(osVDCFilename.c_str(), "rb"); } char **papszVDC = nullptr; @@ -75,7 +75,7 @@ int OGRIdrisiDataSource::Open(const char *pszFilename) fpVDC = nullptr; CPLPushErrorHandler(CPLQuietErrorHandler); - papszVDC = CSLLoad2(pszVDCFilename, 1024, 256, nullptr); + papszVDC = CSLLoad2(osVDCFilename.c_str(), 1024, 256, nullptr); CPLPopErrorHandler(); CPLErrorReset(); } @@ -141,8 +141,9 @@ int OGRIdrisiDataSource::Open(const char *pszFilename) const char *pszMinY = CSLFetchNameValue(papszVDC, "min. Y"); const char *pszMaxY = CSLFetchNameValue(papszVDC, "max. Y"); - OGRIdrisiLayer *poLayer = new OGRIdrisiLayer( - pszFilename, CPLGetBasename(pszFilename), fpVCT, eType, pszWTKString); + OGRIdrisiLayer *poLayer = + new OGRIdrisiLayer(pszFilename, CPLGetBasenameSafe(pszFilename).c_str(), + fpVCT, eType, pszWTKString); papoLayers = static_cast(CPLMalloc(sizeof(OGRLayer *))); papoLayers[nLayers++] = poLayer; diff --git a/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp b/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp index f2ede08b4700..e386829156d7 100644 --- a/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp +++ b/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp @@ -30,7 +30,7 @@ static GDALDataset *OGRIdrisiOpen(GDALOpenInfo *poOpenInfo) // -------------------------------------------------------------------- // Does this appear to be a .vct file? // -------------------------------------------------------------------- - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "vct")) + if (!poOpenInfo->IsExtensionEqualToCI("vct")) return nullptr; auto poDS = std::make_unique(); diff --git a/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp b/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp index e410293c63da..4f1a0cd22184 100644 --- a/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp +++ b/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp @@ -89,12 +89,12 @@ bool OGRIdrisiLayer::Detect_AVL_ADC(const char *pszFilename) // -------------------------------------------------------------------- // Look for .adc file // -------------------------------------------------------------------- - const char *pszADCFilename = CPLResetExtension(pszFilename, "adc"); - VSILFILE *fpADC = VSIFOpenL(pszADCFilename, "rb"); + std::string osADCFilename = CPLResetExtensionSafe(pszFilename, "adc"); + VSILFILE *fpADC = VSIFOpenL(osADCFilename.c_str(), "rb"); if (fpADC == nullptr) { - pszADCFilename = CPLResetExtension(pszFilename, "ADC"); - fpADC = VSIFOpenL(pszADCFilename, "rb"); + osADCFilename = CPLResetExtensionSafe(pszFilename, "ADC"); + fpADC = VSIFOpenL(osADCFilename.c_str(), "rb"); } char **papszADC = nullptr; @@ -104,7 +104,7 @@ bool OGRIdrisiLayer::Detect_AVL_ADC(const char *pszFilename) fpADC = nullptr; CPLPushErrorHandler(CPLQuietErrorHandler); - papszADC = CSLLoad2(pszADCFilename, 1024, 256, nullptr); + papszADC = CSLLoad2(osADCFilename.c_str(), 1024, 256, nullptr); CPLPopErrorHandler(); CPLErrorReset(); } @@ -150,12 +150,12 @@ bool OGRIdrisiLayer::Detect_AVL_ADC(const char *pszFilename) // -------------------------------------------------------------------- // Look for .avl file // -------------------------------------------------------------------- - const char *pszAVLFilename = CPLResetExtension(pszFilename, "avl"); - fpAVL = VSIFOpenL(pszAVLFilename, "rb"); + std::string osAVLFilename = CPLResetExtensionSafe(pszFilename, "avl"); + fpAVL = VSIFOpenL(osAVLFilename.c_str(), "rb"); if (fpAVL == nullptr) { - pszAVLFilename = CPLResetExtension(pszFilename, "AVL"); - fpAVL = VSIFOpenL(pszAVLFilename, "rb"); + osAVLFilename = CPLResetExtensionSafe(pszFilename, "AVL"); + fpAVL = VSIFOpenL(osAVLFilename.c_str(), "rb"); } if (fpAVL == nullptr) { diff --git a/ogr/ogrsf_frmts/ili/ogrili2datasource.cpp b/ogr/ogrsf_frmts/ili/ogrili2datasource.cpp index 42cfc9c9acda..b9207acd7e0d 100644 --- a/ogr/ogrsf_frmts/ili/ogrili2datasource.cpp +++ b/ogr/ogrsf_frmts/ili/ogrili2datasource.cpp @@ -194,10 +194,10 @@ int OGRILI2DataSource::Create(const char *pszFilename, } else if (STARTS_WITH(pszName, "/vsizip/")) { - if (EQUAL(CPLGetExtension(pszName), "zip")) + if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "zip")) { - char *pszNewName = - CPLStrdup(CPLFormFilename(pszName, "out.xtf", nullptr)); + char *pszNewName = CPLStrdup( + CPLFormFilenameSafe(pszName, "out.xtf", nullptr).c_str()); CPLFree(pszName); pszName = pszNewName; } diff --git a/ogr/ogrsf_frmts/jml/ogrjmldataset.cpp b/ogr/ogrsf_frmts/jml/ogrjmldataset.cpp index 966c441e4bad..9a446f73117e 100644 --- a/ogr/ogrsf_frmts/jml/ogrjmldataset.cpp +++ b/ogr/ogrsf_frmts/jml/ogrjmldataset.cpp @@ -103,8 +103,8 @@ GDALDataset *OGRJMLDataset::Open(GDALOpenInfo *poOpenInfo) poDS->fp = poOpenInfo->fpL; poOpenInfo->fpL = nullptr; - poDS->poLayer = new OGRJMLLayer(CPLGetBasename(poOpenInfo->pszFilename), - poDS, poDS->fp); + poDS->poLayer = new OGRJMLLayer( + CPLGetBasenameSafe(poOpenInfo->pszFilename).c_str(), poDS, poDS->fp); return poDS; #endif diff --git a/ogr/ogrsf_frmts/jsonfg/ogrjsonfgdataset.cpp b/ogr/ogrsf_frmts/jsonfg/ogrjsonfgdataset.cpp index b055f091048d..c10829ac0a1c 100644 --- a/ogr/ogrsf_frmts/jsonfg/ogrjsonfgdataset.cpp +++ b/ogr/ogrsf_frmts/jsonfg/ogrjsonfgdataset.cpp @@ -199,7 +199,7 @@ bool OGRJSONFGDataset::Open(GDALOpenInfo *poOpenInfo, return false; } SetDescription(pszUnprefixed); - osDefaultLayerName = CPLGetBasename(pszUnprefixed); + osDefaultLayerName = CPLGetBasenameSafe(pszUnprefixed); eAccess = poOpenInfo->eAccess; // Ingests the first bytes of the file in pszGeoData_ diff --git a/ogr/ogrsf_frmts/libkml/ogrlibkmldatasource.cpp b/ogr/ogrsf_frmts/libkml/ogrlibkmldatasource.cpp index 20a3ddca7567..66111ab7d51e 100644 --- a/ogr/ogrsf_frmts/libkml/ogrlibkmldatasource.cpp +++ b/ogr/ogrsf_frmts/libkml/ogrlibkmldatasource.cpp @@ -402,8 +402,8 @@ bool OGRLIBKMLDataSource::WriteKmz() EQUAL(CPLGetConfigOption("CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""), "FORCED")) { - osTmpFilename = - CPLGenerateTempFilename(CPLGetBasename(GetDescription())); + osTmpFilename = CPLGenerateTempFilenameSafe( + CPLGetBasenameSafe(GetDescription()).c_str()); } void *hZIP = CPLCreateZip(osTmpFilename.empty() ? GetDescription() @@ -584,10 +584,10 @@ bool OGRLIBKMLDataSource::WriteDir() std::string oKmlOut = kmldom::SerializePretty(m_poKmlDocKmlRoot); OGRLIBKMLPostProcessOutput(oKmlOut); - const char *pszOutfile = - CPLFormFilename(GetDescription(), "doc.kml", nullptr); + const std::string osOutfile = + CPLFormFilenameSafe(GetDescription(), "doc.kml", nullptr); - VSILFILE *fp = VSIFOpenExL(pszOutfile, "wb", true); + VSILFILE *fp = VSIFOpenExL(osOutfile.c_str(), "wb", true); if (fp == nullptr) { CPLError(CE_Failure, CPLE_FileIO, "Error writing %s to %s: %s", @@ -634,10 +634,10 @@ bool OGRLIBKMLDataSource::WriteDir() std::string oKmlOut = kmldom::SerializePretty(poKmlKml); OGRLIBKMLPostProcessOutput(oKmlOut); - const char *pszOutfile = CPLFormFilename( + const std::string osOutfile = CPLFormFilenameSafe( GetDescription(), papoLayers[iLayer]->GetFileName(), nullptr); - VSILFILE *fp = VSIFOpenL(pszOutfile, "wb"); + VSILFILE *fp = VSIFOpenL(osOutfile.c_str(), "wb"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_FileIO, "ERROR Writing %s to %s", @@ -660,10 +660,10 @@ bool OGRLIBKMLDataSource::WriteDir() std::string oKmlOut = kmldom::SerializePretty(poKmlKml); OGRLIBKMLPostProcessOutput(oKmlOut); - const char *pszOutfile = - CPLFormFilename(GetDescription(), "style.kml", nullptr); + const std::string osOutfile = + CPLFormFilenameSafe(GetDescription(), "style.kml", nullptr); - VSILFILE *fp = VSIFOpenL(pszOutfile, "wb"); + VSILFILE *fp = VSIFOpenL(osOutfile.c_str(), "wb"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_FileIO, "ERROR Writing %s to %s", @@ -1123,7 +1123,7 @@ int OGRLIBKMLDataSource::OpenKml(const char *pszFilename, int bUpdateIn) /***** if there is placemarks in the root its a layer *****/ if (nPlacemarks) { - std::string layername_default(CPLGetBasename(pszFilename)); + std::string layername_default(CPLGetBasenameSafe(pszFilename)); if (m_poKmlDSContainer->has_name()) { @@ -1289,8 +1289,7 @@ int OGRLIBKMLDataSource::OpenKmz(const char *pszFilename, int bUpdateIn) const std::string osLayerName = poKmlNetworkLink->has_name() ? poKmlNetworkLink->get_name() - : std::string( - CPLGetBasename(oKmlHref.get_path().c_str())); + : CPLGetBasenameSafe(oKmlHref.get_path().c_str()); AddLayer(osLayerName.c_str(), wkbUnknown, nullptr, this, std::move(poKmlLyrRoot), poKmlLyrContainer, @@ -1327,7 +1326,7 @@ int OGRLIBKMLDataSource::OpenKmz(const char *pszFilename, int bUpdateIn) /***** if there is placemarks in the root its a layer *****/ if (nPlacemarks) { - std::string layername_default(CPLGetBasename(pszFilename)); + std::string layername_default(CPLGetBasenameSafe(pszFilename)); if (poKmlContainer->has_name()) { @@ -1376,15 +1375,15 @@ int OGRLIBKMLDataSource::OpenDir(const char *pszFilename, int bUpdateIn) for (int iFile = 0; iFile < nFiles; iFile++) { /***** make sure its a .kml file *****/ - if (!EQUAL(CPLGetExtension(papszDirList[iFile]), "kml")) + if (!EQUAL(CPLGetExtensionSafe(papszDirList[iFile]).c_str(), "kml")) continue; /***** read the file *****/ std::string oKmlKml; char szBuffer[1024 + 1] = {}; - CPLString osFilePath = - CPLFormFilename(pszFilename, papszDirList[iFile], nullptr); + const CPLString osFilePath = + CPLFormFilenameSafe(pszFilename, papszDirList[iFile], nullptr); VSILFILE *fp = VSIFOpenL(osFilePath, "rb"); if (fp == nullptr) @@ -1454,7 +1453,7 @@ int OGRLIBKMLDataSource::OpenDir(const char *pszFilename, int bUpdateIn) const std::string osLayerName = poKmlContainer->has_name() ? poKmlContainer->get_name() - : std::string(CPLGetBasename(osFilePath.c_str())); + : std::string(CPLGetBasenameSafe(osFilePath.c_str())); /***** create the layer *****/ AddLayer(osLayerName.c_str(), wkbUnknown, nullptr, this, @@ -1493,7 +1492,7 @@ static bool CheckIsKMZ(const char *pszFilename) bool bFoundKML = false; while (papszIter && *papszIter) { - if (EQUAL(CPLGetExtension(*papszIter), "kml")) + if (EQUAL(CPLGetExtensionSafe(*papszIter).c_str(), "kml")) { bFoundKML = true; break; @@ -1528,13 +1527,13 @@ int OGRLIBKMLDataSource::Open(const char *pszFilename, int bUpdateIn) } /***** kml *****/ - if (EQUAL(CPLGetExtension(pszFilename), "kml")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "kml")) { return OpenKml(pszFilename, bUpdate); } /***** kmz *****/ - if (EQUAL(CPLGetExtension(pszFilename), "kmz")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "kmz")) { return OpenKmz(pszFilename, bUpdate); } @@ -1949,11 +1948,11 @@ int OGRLIBKMLDataSource::Create(const char *pszFilename, char **papszOptions) /***** kml *****/ if (strcmp(pszFilename, "/vsistdout/") == 0 || STARTS_WITH(pszFilename, "/vsigzip/") || - EQUAL(CPLGetExtension(pszFilename), "kml")) + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "kml")) return CreateKml(pszFilename, papszOptions); /***** kmz *****/ - if (EQUAL(CPLGetExtension(pszFilename), "kmz")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "kmz")) return CreateKmz(pszFilename, papszOptions); /***** dir *****/ @@ -2115,16 +2114,16 @@ OGRErr OGRLIBKMLDataSource::DeleteLayer(int iLayer) DeleteLayerKmz(iLayer); /***** delete the file the layer corresponds to *****/ - const char *pszFilePath = CPLFormFilename( + const std::string osFilePath = CPLFormFilenameSafe( GetDescription(), papoLayers[iLayer]->GetFileName(), nullptr); VSIStatBufL oStatBufL; - if (!VSIStatL(pszFilePath, &oStatBufL)) + if (!VSIStatL(osFilePath.c_str(), &oStatBufL)) { - if (VSIUnlink(pszFilePath)) + if (VSIUnlink(osFilePath.c_str())) { CPLError(CE_Failure, CPLE_AppDefined, "ERROR Deleting Layer %s from filesystem as %s", - papoLayers[iLayer]->GetName(), pszFilePath); + papoLayers[iLayer]->GetName(), osFilePath.c_str()); } } } @@ -2237,9 +2236,10 @@ OGRLIBKMLLayer *OGRLIBKMLDataSource::CreateLayerKmz( OGRLIBKMLGetSanitizedNCName(pszLayerName).c_str()); } - OGRLIBKMLLayer *poOgrLayer = AddLayer( - pszLayerName, eGType, poSRS, this, nullptr, poKmlDocument, - CPLFormFilename(nullptr, pszLayerName, ".kml"), TRUE, bUpdate, 1); + OGRLIBKMLLayer *poOgrLayer = + AddLayer(pszLayerName, eGType, poSRS, this, nullptr, poKmlDocument, + CPLFormFilenameSafe(nullptr, pszLayerName, ".kml").c_str(), + TRUE, bUpdate, 1); /***** add the layer name as a *****/ if (!m_poKmlUpdate) diff --git a/ogr/ogrsf_frmts/libkml/ogrlibkmldriver.cpp b/ogr/ogrsf_frmts/libkml/ogrlibkmldriver.cpp index 0a517c879fe7..0a96239a0bcd 100644 --- a/ogr/ogrsf_frmts/libkml/ogrlibkmldriver.cpp +++ b/ogr/ogrsf_frmts/libkml/ogrlibkmldriver.cpp @@ -125,14 +125,14 @@ static CPLErr OGRLIBKMLDriverDelete(const char *pszName) } /***** kml *****/ - else if (EQUAL(CPLGetExtension(pszName), "kml")) + else if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "kml")) { if (VSIUnlink(pszName) < 0) return CE_Failure; } /***** kmz *****/ - else if (EQUAL(CPLGetExtension(pszName), "kmz")) + else if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "kmz")) { if (VSIUnlink(pszName) < 0) return CE_Failure; diff --git a/ogr/ogrsf_frmts/libkml/ogrlibkmldrivercore.cpp b/ogr/ogrsf_frmts/libkml/ogrlibkmldrivercore.cpp index f477587ee883..1f02330e24cb 100644 --- a/ogr/ogrsf_frmts/libkml/ogrlibkmldrivercore.cpp +++ b/ogr/ogrsf_frmts/libkml/ogrlibkmldrivercore.cpp @@ -26,7 +26,7 @@ int OGRLIBKMLDriverIdentify(GDALOpenInfo *poOpenInfo) if (poOpenInfo->bIsDirectory) return -1; - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (EQUAL(pszExt, "kml") || EQUAL(pszExt, "kmz")) { return TRUE; diff --git a/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp b/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp index cda52e30a18c..3bcee5adbebf 100644 --- a/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp +++ b/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp @@ -662,7 +662,7 @@ FeaturePtr feat2kml(OGRLIBKMLDataSource *poOgrDS, OGRLIBKMLLayer *poOgrLayer, link->set_href(pszURL); // Collada 3D file? - if (EQUAL(CPLGetExtension(pszURL), "dae") && + if (EQUAL(CPLGetExtensionSafe(pszURL).c_str(), "dae") && CPLTestBool(CPLGetConfigOption("LIBKML_ADD_RESOURCE_MAP", "TRUE"))) { VSILFILE *fp = nullptr; @@ -697,12 +697,12 @@ FeaturePtr feat2kml(OGRLIBKMLDataSource *poOgrDS, OGRLIBKMLLayer *poOgrLayer, { CPLString osImage(pszInitFrom); osImage.resize(pszInitFromEnd - pszInitFrom); - const char *const pszExtension = - CPLGetExtension(osImage); - if (EQUAL(pszExtension, "jpg") || - EQUAL(pszExtension, "jpeg") || - EQUAL(pszExtension, "png") || - EQUAL(pszExtension, "gif")) + const std::string osExtension = + CPLGetExtensionSafe(osImage); + if (EQUAL(osExtension.c_str(), "jpg") || + EQUAL(osExtension.c_str(), "jpeg") || + EQUAL(osExtension.c_str(), "png") || + EQUAL(osExtension.c_str(), "gif")) { if (!resourceMap) resourceMap = @@ -713,12 +713,14 @@ FeaturePtr feat2kml(OGRLIBKMLDataSource *poOgrDS, OGRLIBKMLLayer *poOgrLayer, { if (STARTS_WITH(pszURL, "http")) alias->set_targethref(CPLSPrintf( - "%s/%s", CPLGetPath(pszURL), + "%s/%s", + CPLGetPathSafe(pszURL).c_str(), osImage.c_str())); else alias->set_targethref( - CPLFormFilename(CPLGetPath(pszURL), - osImage, nullptr)); + CPLFormFilenameSafe( + CPLGetPathSafe(pszURL).c_str(), + osImage, nullptr)); } else alias->set_targethref(osImage); diff --git a/ogr/ogrsf_frmts/libkml/ogrlibkmlfeaturestyle.cpp b/ogr/ogrsf_frmts/libkml/ogrlibkmlfeaturestyle.cpp index f730708815ee..dfba6f4fbdd8 100644 --- a/ogr/ogrsf_frmts/libkml/ogrlibkmlfeaturestyle.cpp +++ b/ogr/ogrsf_frmts/libkml/ogrlibkmlfeaturestyle.cpp @@ -247,8 +247,9 @@ void kml2featurestyle(FeaturePtr poKmlFeature, OGRLIBKMLDataSource *poOgrDS, } else if (CPLIsFilenameRelative(osUrlTmp.c_str())) { - osUrlTmp = CPLFormFilename( - CPLGetDirname(poOgrDS->GetDescription()), + osUrlTmp = CPLFormFilenameSafe( + CPLGetDirnameSafe(poOgrDS->GetDescription()) + .c_str(), osUrlTmp.c_str(), nullptr); } CPLDebug("LIBKML", "Trying to resolve style %s", diff --git a/ogr/ogrsf_frmts/libkml/ogrlibkmlstyle.cpp b/ogr/ogrsf_frmts/libkml/ogrlibkmlstyle.cpp index d7cc67c28236..472b7fc10b77 100644 --- a/ogr/ogrsf_frmts/libkml/ogrlibkmlstyle.cpp +++ b/ogr/ogrsf_frmts/libkml/ogrlibkmlstyle.cpp @@ -792,9 +792,10 @@ static StyleSelectorPtr StyleFromStyleURL(const StyleMapPtr &stylemap, /***** try it as a url then a file *****/ VSILFILE *fp = nullptr; - if ((fp = - VSIFOpenL(CPLFormFilename("/vsicurl/", pszUrlTmp, nullptr), - "r")) != nullptr || + if ((fp = VSIFOpenL( + CPLFormFilenameSafe("/vsicurl/", pszUrlTmp, nullptr) + .c_str(), + "r")) != nullptr || (fp = VSIFOpenL(pszUrlTmp, "r")) != nullptr) { char szbuf[1025] = {}; diff --git a/ogr/ogrsf_frmts/lvbag/ogrlvbagdriver.cpp b/ogr/ogrsf_frmts/lvbag/ogrlvbagdriver.cpp index c857b32f2943..e257a7cb8175 100644 --- a/ogr/ogrsf_frmts/lvbag/ogrlvbagdriver.cpp +++ b/ogr/ogrsf_frmts/lvbag/ogrlvbagdriver.cpp @@ -77,11 +77,11 @@ GDALDataset *OGRLVBAGDriverOpen(GDALOpenInfo *poOpenInfo) char **papszNames = VSIReadDir(pszFilename); for (int i = 0; papszNames != nullptr && papszNames[i] != nullptr; ++i) { - if (!EQUAL(CPLGetExtension(papszNames[i]), "xml")) + if (!EQUAL(CPLGetExtensionSafe(papszNames[i]).c_str(), "xml")) continue; const CPLString oSubFilename = - CPLFormFilename(pszFilename, papszNames[i], nullptr); + CPLFormFilenameSafe(pszFilename, papszNames[i], nullptr); if (EQUAL(papszNames[i], ".") || EQUAL(papszNames[i], "..")) continue; diff --git a/ogr/ogrsf_frmts/lvbag/ogrlvbaglayer.cpp b/ogr/ogrsf_frmts/lvbag/ogrlvbaglayer.cpp index b5550ee3f3f9..fb88e82bbbc4 100644 --- a/ogr/ogrsf_frmts/lvbag/ogrlvbaglayer.cpp +++ b/ogr/ogrsf_frmts/lvbag/ogrlvbaglayer.cpp @@ -39,7 +39,7 @@ OGRLVBAGLayer::OGRLVBAGLayer(const char *pszFilename, OGRLayerPool *poPoolIn, nAttributeElementDepth{0}, eAddressRefState{AddressRefState::ADDRESS_PRIMARY}, bCollectData{false} { - SetDescription(CPLGetBasename(pszFilename)); + SetDescription(CPLGetBasenameSafe(pszFilename).c_str()); poFeatureDefn->Reference(); } diff --git a/ogr/ogrsf_frmts/mapml/ogrmapmldataset.cpp b/ogr/ogrsf_frmts/mapml/ogrmapmldataset.cpp index 55a20dcde61a..eebd79906200 100644 --- a/ogr/ogrsf_frmts/mapml/ogrmapmldataset.cpp +++ b/ogr/ogrsf_frmts/mapml/ogrmapmldataset.cpp @@ -218,7 +218,8 @@ GDALDataset *OGRMapMLReaderDataset::Open(GDALOpenInfo *poOpenInfo) CPLXMLNode *psBody = CPLGetXMLNode(psRoot, "=mapml.body"); if (psBody == nullptr) return nullptr; - const CPLString osDefaultLayerName(CPLGetBasename(poOpenInfo->pszFilename)); + const CPLString osDefaultLayerName( + CPLGetBasenameSafe(poOpenInfo->pszFilename)); std::set oSetLayerNames; for (auto psNode = psBody->psChild; psNode; psNode = psNode->psNext) { diff --git a/ogr/ogrsf_frmts/miramon/ogrmiramondatasource.cpp b/ogr/ogrsf_frmts/miramon/ogrmiramondatasource.cpp index a9e182ea78d7..e5c246ae42fa 100644 --- a/ogr/ogrsf_frmts/miramon/ogrmiramondatasource.cpp +++ b/ogr/ogrsf_frmts/miramon/ogrmiramondatasource.cpp @@ -50,14 +50,18 @@ bool OGRMiraMonDataSource::Open(const char *pszFilename, VSILFILE *fp, if (!m_osRootName.empty()) { - const char *pszExtension = CPLGetExtension(m_osRootName.c_str()); - if (!EQUAL(pszExtension, "pol") && !EQUAL(pszExtension, "arc") && - !EQUAL(pszExtension, "pnt")) + const std::string osExtension = + CPLGetExtensionSafe(m_osRootName.c_str()); + if (!EQUAL(osExtension.c_str(), "pol") && + !EQUAL(osExtension.c_str(), "arc") && + !EQUAL(osExtension.c_str(), "pnt")) { CPLStrlcpy(m_MMMap.pszMapName, - CPLFormFilename(m_osRootName.c_str(), - CPLGetBasename(m_osRootName.c_str()), - "mmm"), + CPLFormFilenameSafe( + m_osRootName.c_str(), + CPLGetBasenameSafe(m_osRootName.c_str()).c_str(), + "mmm") + .c_str(), sizeof(m_MMMap.pszMapName)); if (!m_MMMap.nNumberOfLayers) { @@ -79,7 +83,7 @@ bool OGRMiraMonDataSource::Open(const char *pszFilename, VSILFILE *fp, VSIFPrintfL(m_MMMap.fMMMap, "\n"); VSIFPrintfL(m_MMMap.fMMMap, "[DOCUMENT]\n"); VSIFPrintfL(m_MMMap.fMMMap, "Titol= %s(map)\n", - CPLGetBasename(poLayer->GetName())); + CPLGetBasenameSafe(poLayer->GetName()).c_str()); VSIFPrintfL(m_MMMap.fMMMap, "\n"); } } @@ -142,18 +146,18 @@ OGRMiraMonDataSource::ICreateLayer(const char *pszLayerName, /* of the file is where to write, and the layer name is the */ /* dataset name (without extension). */ /* -------------------------------------------------------------------- */ - const char *pszExtension = CPLGetExtension(m_osRootName.c_str()); + const std::string osExtension = CPLGetExtensionSafe(m_osRootName.c_str()); std::string osFullMMLayerName; - if (EQUAL(pszExtension, "pol") || EQUAL(pszExtension, "arc") || - EQUAL(pszExtension, "pnt")) + if (EQUAL(osExtension.c_str(), "pol") || + EQUAL(osExtension.c_str(), "arc") || EQUAL(osExtension.c_str(), "pnt")) { - osFullMMLayerName = CPLResetExtension(m_osRootName.c_str(), ""); + osFullMMLayerName = CPLResetExtensionSafe(m_osRootName.c_str(), ""); if (!osFullMMLayerName.empty()) osFullMMLayerName.pop_back(); // Checking that the folder where to write exists const std::string osDestFolder = - CPLGetDirname(osFullMMLayerName.c_str()); + CPLGetDirnameSafe(osFullMMLayerName.c_str()); if (!STARTS_WITH(osDestFolder.c_str(), "/vsimem")) { VSIStatBufL sStat; @@ -169,7 +173,7 @@ OGRMiraMonDataSource::ICreateLayer(const char *pszLayerName, else { osFullMMLayerName = - CPLFormFilename(m_osRootName.c_str(), pszLayerName, ""); + CPLFormFilenameSafe(m_osRootName.c_str(), pszLayerName, ""); /* -------------------------------------------------------------------- */ /* Let's create the folder if it's not already created. */ diff --git a/ogr/ogrsf_frmts/miramon/ogrmiramondriver.cpp b/ogr/ogrsf_frmts/miramon/ogrmiramondriver.cpp index 2fd6ad739db9..ec3d05585f82 100644 --- a/ogr/ogrsf_frmts/miramon/ogrmiramondriver.cpp +++ b/ogr/ogrsf_frmts/miramon/ogrmiramondriver.cpp @@ -32,9 +32,9 @@ static int OGRMiraMonDriverIdentify(GDALOpenInfo *poOpenInfo) { if (poOpenInfo->fpL == nullptr || poOpenInfo->nHeaderBytes < 7) return FALSE; - else if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "PNT") || - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "ARC") || - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "POL")) + else if (poOpenInfo->IsExtensionEqualToCI("PNT") || + poOpenInfo->IsExtensionEqualToCI("ARC") || + poOpenInfo->IsExtensionEqualToCI("POL")) { // Format if ((poOpenInfo->pabyHeader[0] == 'P' && diff --git a/ogr/ogrsf_frmts/miramon/ogrmiramonlayer.cpp b/ogr/ogrsf_frmts/miramon/ogrmiramonlayer.cpp index 38ebde55979a..f72d3bb83235 100644 --- a/ogr/ogrsf_frmts/miramon/ogrmiramonlayer.cpp +++ b/ogr/ogrsf_frmts/miramon/ogrmiramonlayer.cpp @@ -35,7 +35,8 @@ OGRMiraMonLayer::OGRMiraMonLayer(GDALDataset *poDS, const char *pszFilename, /* -------------------------------------------------------------------- */ /* Create the feature definition */ /* -------------------------------------------------------------------- */ - m_poFeatureDefn = new OGRFeatureDefn(CPLGetBasename(pszFilename)); + m_poFeatureDefn = + new OGRFeatureDefn(CPLGetBasenameSafe(pszFilename).c_str()); SetDescription(m_poFeatureDefn->GetName()); m_poFeatureDefn->Reference(); @@ -2858,98 +2859,123 @@ void OGRMiraMonLayer::AddToFileList(CPLStringList &oFileList) oFileList.AddStringDirectly( VSIGetCanonicalFilename(phMiraMonLayer->pszSrcLayerName)); char *pszMMExt = - CPLStrdup(CPLGetExtension(phMiraMonLayer->pszSrcLayerName)); + CPLStrdup(CPLGetExtensionSafe(phMiraMonLayer->pszSrcLayerName).c_str()); if (phMiraMonLayer->bIsPoint) { // As it's explicit on documentation a point has also two more files: // FILE_NAME_WITHOUT_EXTENSION.pnt --> FILE_NAME_WITHOUT_EXTENSION + T.rel - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "T.rel" : "T.REL", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.pnt --> FILE_NAME_WITHOUT_EXTENSION + T.dbf - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "T.dbf" : "T.DBF", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); } else if (phMiraMonLayer->bIsArc && !phMiraMonLayer->bIsPolygon) { // As it's explicit on documentation a point has also five more files: // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + A.rel - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'a') ? "A.rel" : "A.REL", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + A.dbf - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'a') ? "A.dbf" : "A.DBF", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + .nod - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'a') ? ".nod" : ".NOD", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + N.rel - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'a') ? "N.rel" : "N.REL", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + N.dbf - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'a') ? "N.dbf" : "N.DBF", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); } else if (phMiraMonLayer->bIsPolygon) { // As it's explicit on documentation a point has also eight more files: - const char *szCompleteArcFileName; char szArcFileName[MM_CPL_PATH_BUF_SIZE]; // FILE_NAME_WITHOUT_EXTENSION.pol --> FILE_NAME_WITHOUT_EXTENSION + P.rel - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "P.rel" : "P.REL", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // The name of the arc is in THIS metadata file char *pszArcLayerName = MMReturnValueFromSectionINIFile( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr), + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str(), SECTION_OVVW_ASPECTES_TECNICS, KEY_ArcSource); if (!pszArcLayerName) { @@ -2961,64 +2987,83 @@ void OGRMiraMonLayer::AddToFileList(CPLStringList &oFileList) MM_RemoveInitial_and_FinalQuotationMarks(szArcFileName); // If extension is not specified ".arc" will be used - if (MMIsEmptyString(CPLGetExtension(pszArcLayerName))) + if (MMIsEmptyString(CPLGetExtensionSafe(pszArcLayerName).c_str())) CPLStrlcat(szArcFileName, (pszMMExt[0] == 'p') ? ".arc" : ".ARC", MM_CPL_PATH_BUF_SIZE); CPLFree(pszArcLayerName); - szCompleteArcFileName = - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szArcFileName, nullptr); + const std::string osCompleteArcFileName = CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szArcFileName, nullptr); // The arc that has the coordinates of the polygon oFileList.AddStringDirectly( - VSIGetCanonicalFilename(szCompleteArcFileName)); + VSIGetCanonicalFilename(osCompleteArcFileName.c_str())); // FILE_NAME_WITHOUT_EXTENSION.pol --> FILE_NAME_WITHOUT_EXTENSION + P.dbf - CPLStrlcpy(szAuxFile, CPLGetBasename(phMiraMonLayer->pszSrcLayerName), + CPLStrlcpy(szAuxFile, + CPLGetBasenameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "P.dbf" : "P.DBF", MM_CPL_PATH_BUF_SIZE); oFileList.AddStringDirectly(VSIGetCanonicalFilename( - CPLFormFilename(CPLGetDirname(phMiraMonLayer->pszSrcLayerName), - szAuxFile, nullptr))); + CPLFormFilenameSafe( + CPLGetDirnameSafe(phMiraMonLayer->pszSrcLayerName).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + A.rel - const char *pszBaseArcName = CPLGetBasename(szCompleteArcFileName); - CPLStrlcpy(szAuxFile, pszBaseArcName, MM_CPL_PATH_BUF_SIZE); + const std::string osBaseArcName = + CPLGetBasenameSafe(osCompleteArcFileName.c_str()); + CPLStrlcpy(szAuxFile, osBaseArcName.c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "A.rel" : "A.REL", MM_CPL_PATH_BUF_SIZE); - oFileList.AddStringDirectly(VSIGetCanonicalFilename(CPLFormFilename( - CPLGetDirname(szCompleteArcFileName), szAuxFile, nullptr))); + oFileList.AddStringDirectly(VSIGetCanonicalFilename( + CPLFormFilenameSafe( + CPLGetDirnameSafe(osCompleteArcFileName.c_str()).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + A.dbf - CPLStrlcpy(szAuxFile, pszBaseArcName, MM_CPL_PATH_BUF_SIZE); + CPLStrlcpy(szAuxFile, osBaseArcName.c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "A.dbf" : "A.DBF", MM_CPL_PATH_BUF_SIZE); - oFileList.AddStringDirectly(VSIGetCanonicalFilename(CPLFormFilename( - CPLGetDirname(szCompleteArcFileName), szAuxFile, nullptr))); + oFileList.AddStringDirectly(VSIGetCanonicalFilename( + CPLFormFilenameSafe( + CPLGetDirnameSafe(osCompleteArcFileName.c_str()).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + .nod - CPLStrlcpy(szAuxFile, pszBaseArcName, MM_CPL_PATH_BUF_SIZE); + CPLStrlcpy(szAuxFile, osBaseArcName.c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? ".nod" : ".NOD", MM_CPL_PATH_BUF_SIZE); - oFileList.AddStringDirectly(VSIGetCanonicalFilename(CPLFormFilename( - CPLGetDirname(szCompleteArcFileName), szAuxFile, nullptr))); + oFileList.AddStringDirectly(VSIGetCanonicalFilename( + CPLFormFilenameSafe( + CPLGetDirnameSafe(osCompleteArcFileName.c_str()).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + N.rel - CPLStrlcpy(szAuxFile, pszBaseArcName, MM_CPL_PATH_BUF_SIZE); + CPLStrlcpy(szAuxFile, osBaseArcName.c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "N.rel" : "N.REL", MM_CPL_PATH_BUF_SIZE); - oFileList.AddStringDirectly(VSIGetCanonicalFilename(CPLFormFilename( - CPLGetDirname(szCompleteArcFileName), szAuxFile, nullptr))); + oFileList.AddStringDirectly(VSIGetCanonicalFilename( + CPLFormFilenameSafe( + CPLGetDirnameSafe(osCompleteArcFileName.c_str()).c_str(), + szAuxFile, nullptr) + .c_str())); // FILE_NAME_WITHOUT_EXTENSION.arc --> FILE_NAME_WITHOUT_EXTENSION + N.dbf - CPLStrlcpy(szAuxFile, pszBaseArcName, MM_CPL_PATH_BUF_SIZE); + CPLStrlcpy(szAuxFile, osBaseArcName.c_str(), MM_CPL_PATH_BUF_SIZE); CPLStrlcat(szAuxFile, (pszMMExt[0] == 'p') ? "N.dbf" : "N.DBF", MM_CPL_PATH_BUF_SIZE); - oFileList.AddStringDirectly(VSIGetCanonicalFilename(CPLFormFilename( - CPLGetDirname(szCompleteArcFileName), szAuxFile, nullptr))); + oFileList.AddStringDirectly(VSIGetCanonicalFilename( + CPLFormFilenameSafe( + CPLGetDirnameSafe(osCompleteArcFileName.c_str()).c_str(), + szAuxFile, nullptr) + .c_str())); } CPLFree(pszMMExt); } diff --git a/ogr/ogrsf_frmts/mitab/mitab_feature.cpp b/ogr/ogrsf_frmts/mitab/mitab_feature.cpp index 608fceb1ef6f..9f54eaa2c235 100644 --- a/ogr/ogrsf_frmts/mitab/mitab_feature.cpp +++ b/ogr/ogrsf_frmts/mitab/mitab_feature.cpp @@ -1797,9 +1797,9 @@ const char *TABCustomPoint::GetSymbolStyleString(double dfAngle) const int nAngle = static_cast(dfAngle); const char *pszStyle; - const char *pszExt = CPLGetExtension(GetSymbolNameRef()); + const std::string osExt = CPLGetExtensionSafe(GetSymbolNameRef()); char szLowerExt[8] = ""; - const char *pszPtr = pszExt; + const char *pszPtr = osExt.c_str(); int i; for (i = 0; i < 7 && *pszPtr != '\0' && *pszPtr != ' '; i++, pszPtr++) diff --git a/ogr/ogrsf_frmts/mitab/mitab_ogr_datasource.cpp b/ogr/ogrsf_frmts/mitab/mitab_ogr_datasource.cpp index 4d08b80c6344..6adffc0b5574 100644 --- a/ogr/ogrsf_frmts/mitab/mitab_ogr_datasource.cpp +++ b/ogr/ogrsf_frmts/mitab/mitab_ogr_datasource.cpp @@ -68,8 +68,8 @@ int OGRTABDataSource::Create(const char *pszName, char **papszOptions) const char *pszOpt = CSLFetchNameValue(papszOptions, "FORMAT"); if (pszOpt != nullptr && EQUAL(pszOpt, "MIF")) m_bCreateMIF = TRUE; - else if (EQUAL(CPLGetExtension(pszName), "mif") || - EQUAL(CPLGetExtension(pszName), "mid")) + else if (EQUAL(CPLGetExtensionSafe(pszName).c_str(), "mif") || + EQUAL(CPLGetExtensionSafe(pszName).c_str(), "mid")) m_bCreateMIF = TRUE; if ((pszOpt = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX_MODE")) != @@ -86,7 +86,7 @@ int OGRTABDataSource::Create(const char *pszName, char **papszOptions) // Create a new empty directory. VSIStatBufL sStat; - if (strlen(CPLGetExtension(pszName)) == 0) + if (strlen(CPLGetExtensionSafe(pszName).c_str()) == 0) { if (VSIStatL(pszName, &sStat) == 0) { @@ -145,7 +145,7 @@ int OGRTABDataSource::Create(const char *pszName, char **papszOptions) m_papoLayers = static_cast(CPLMalloc(sizeof(void *))); m_papoLayers[0] = poFile; - m_pszDirectory = CPLStrdup(CPLGetPath(pszName)); + m_pszDirectory = CPLStrdup(CPLGetPathSafe(pszName).c_str()); m_bSingleFile = TRUE; } @@ -178,7 +178,8 @@ int OGRTABDataSource::Open(GDALOpenInfo *poOpenInfo, int bTestOpen) m_papoLayers = static_cast(CPLMalloc(sizeof(void *))); m_papoLayers[0] = poFile; - m_pszDirectory = CPLStrdup(CPLGetPath(poOpenInfo->pszFilename)); + m_pszDirectory = + CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str()); m_bSingleFile = TRUE; m_bSingleLayerAlreadyCreated = TRUE; @@ -196,13 +197,17 @@ int OGRTABDataSource::Open(GDALOpenInfo *poOpenInfo, int bTestOpen) papszFileList != nullptr && papszFileList[iFile] != nullptr; iFile++) { - const char *pszExtension = CPLGetExtension(papszFileList[iFile]); + const std::string osExtension = + CPLGetExtensionSafe(papszFileList[iFile]); - if (!EQUAL(pszExtension, "tab") && !EQUAL(pszExtension, "mif")) + if (!EQUAL(osExtension.c_str(), "tab") && + !EQUAL(osExtension.c_str(), "mif")) continue; - char *pszSubFilename = CPLStrdup( - CPLFormFilename(m_pszDirectory, papszFileList[iFile], nullptr)); + char *pszSubFilename = + CPLStrdup(CPLFormFilenameSafe(m_pszDirectory, + papszFileList[iFile], nullptr) + .c_str()); IMapInfoFile *poFile = IMapInfoFile::SmartOpen( this, pszSubFilename, GetUpdate(), bTestOpen); @@ -325,8 +330,9 @@ OGRTABDataSource::ICreateLayer(const char *pszLayerName, { if (m_bCreateMIF) { - pszFullFilename = - CPLStrdup(CPLFormFilename(m_pszDirectory, pszLayerName, "mif")); + pszFullFilename = CPLStrdup( + CPLFormFilenameSafe(m_pszDirectory, pszLayerName, "mif") + .c_str()); poFile = new MIFFile(this); @@ -339,8 +345,9 @@ OGRTABDataSource::ICreateLayer(const char *pszLayerName, } else { - pszFullFilename = - CPLStrdup(CPLFormFilename(m_pszDirectory, pszLayerName, "tab")); + pszFullFilename = CPLStrdup( + CPLFormFilenameSafe(m_pszDirectory, pszLayerName, "tab") + .c_str()); TABFile *poTABFile = new TABFile(this); @@ -465,10 +472,11 @@ char **OGRTABDataSource::GetFileList() papszDirEntries != nullptr && papszDirEntries[iFile] != nullptr; iFile++) { - if (CSLFindString(apszExtensions, - CPLGetExtension(papszDirEntries[iFile])) != -1) + if (CSLFindString( + apszExtensions, + CPLGetExtensionSafe(papszDirEntries[iFile]).c_str()) != -1) { - osList.AddString(CPLFormFilename( + osList.push_back(CPLFormFilenameSafe( GetDescription(), papszDirEntries[iFile], nullptr)); } } @@ -481,8 +489,8 @@ char **OGRTABDataSource::GetFileList() static const char *const apszTABExtensions[] = {"tab", "map", "ind", "dat", "id", nullptr}; const char *const *papszExtensions = nullptr; - if (EQUAL(CPLGetExtension(GetDescription()), "mif") || - EQUAL(CPLGetExtension(GetDescription()), "mid")) + if (EQUAL(CPLGetExtensionSafe(GetDescription()).c_str(), "mif") || + EQUAL(CPLGetExtensionSafe(GetDescription()).c_str(), "mid")) { papszExtensions = apszMIFExtensions; } @@ -493,19 +501,19 @@ char **OGRTABDataSource::GetFileList() const char *const *papszIter = papszExtensions; while (*papszIter) { - const char *pszFile = - CPLResetExtension(GetDescription(), *papszIter); - if (VSIStatL(pszFile, &sStatBuf) != 0) + std::string osFile = + CPLResetExtensionSafe(GetDescription(), *papszIter); + if (VSIStatL(osFile.c_str(), &sStatBuf) != 0) { - pszFile = CPLResetExtension(GetDescription(), - CPLString(*papszIter).toupper()); - if (VSIStatL(pszFile, &sStatBuf) != 0) + osFile = CPLResetExtensionSafe(GetDescription(), + CPLString(*papszIter).toupper()); + if (VSIStatL(osFile.c_str(), &sStatBuf) != 0) { - pszFile = nullptr; + osFile.clear(); } } - if (pszFile) - osList.AddString(pszFile); + if (!osFile.empty()) + osList.AddString(osFile.c_str()); papszIter++; } } diff --git a/ogr/ogrsf_frmts/mitab/mitab_ogr_driver.cpp b/ogr/ogrsf_frmts/mitab/mitab_ogr_driver.cpp index 7dff86f9a47f..00958b20adee 100644 --- a/ogr/ogrsf_frmts/mitab/mitab_ogr_driver.cpp +++ b/ogr/ogrsf_frmts/mitab/mitab_ogr_driver.cpp @@ -30,12 +30,12 @@ static int OGRTABDriverIdentify(GDALOpenInfo *poOpenInfo) return -1; // Unsure. if (poOpenInfo->fpL == nullptr) return FALSE; - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MIF") || - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MID")) + if (poOpenInfo->IsExtensionEqualToCI("MIF") || + poOpenInfo->IsExtensionEqualToCI("MID")) { return TRUE; } - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "TAB")) + if (poOpenInfo->IsExtensionEqualToCI("TAB")) { for (int i = 0; i < poOpenInfo->nHeaderBytes; i++) { @@ -72,8 +72,8 @@ static GDALDataset *OGRTABDriverOpen(GDALOpenInfo *poOpenInfo) return nullptr; } - if (EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MIF") || - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "MID")) + if (poOpenInfo->IsExtensionEqualToCI("MIF") || + poOpenInfo->IsExtensionEqualToCI("MID")) { if (poOpenInfo->eAccess == GA_Update) return nullptr; diff --git a/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp b/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp index a402d2874223..af224c74d8a5 100644 --- a/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp +++ b/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp @@ -551,14 +551,15 @@ int TABFile::Open(const char *pszFname, TABAccess eAccess, { if (!bHasIndex) { - const char *pszIndFilename = CPLFormCIFilename( - CPLGetPath(pszFname), CPLGetBasename(pszFname), - (bUpperCase) ? "IND" : "ind"); + const std::string osIndFilename = + CPLFormCIFilenameSafe(CPLGetPathSafe(pszFname).c_str(), + CPLGetBasenameSafe(pszFname).c_str(), + (bUpperCase) ? "IND" : "ind"); VSIStatBufL sStat; - if (VSIStatL(pszIndFilename, &sStat) == 0) + if (VSIStatL(osIndFilename.c_str(), &sStat) == 0) { CPLCreateXMLElementAndValue(psRoot, "MIIDFilename", - pszIndFilename); + osIndFilename.c_str()); } else { diff --git a/ogr/ogrsf_frmts/mvt/ogrmvtdataset.cpp b/ogr/ogrsf_frmts/mvt/ogrmvtdataset.cpp index 9ab77fc4d3ce..c8e713c2cf35 100644 --- a/ogr/ogrsf_frmts/mvt/ogrmvtdataset.cpp +++ b/ogr/ogrsf_frmts/mvt/ogrmvtdataset.cpp @@ -1589,11 +1589,11 @@ void OGRMVTDirectoryLayer::ReadNewSubDir() : (1 << m_nZ))) { m_aosSubDirName = - CPLFormFilename(m_osDirName, - (m_bUseReadDir || !m_aosDirContent.empty()) - ? m_aosDirContent[m_nXIndex] - : CPLSPrintf("%d", m_nXIndex), - nullptr); + CPLFormFilenameSafe(m_osDirName, + (m_bUseReadDir || !m_aosDirContent.empty()) + ? m_aosDirContent[m_nXIndex] + : CPLSPrintf("%d", m_nXIndex), + nullptr); if (m_bUseReadDir) { m_aosSubDirContent = @@ -1625,7 +1625,7 @@ void OGRMVTDirectoryLayer::OpenTile() m_poCurrentTile = nullptr; if (m_nYIndex < (m_bUseReadDir ? m_aosSubDirContent.Count() : (1 << m_nZ))) { - CPLString osFilename = CPLFormFilename( + CPLString osFilename = CPLFormFilenameSafe( m_aosSubDirName, m_bUseReadDir ? m_aosSubDirContent[m_nYIndex] : CPLSPrintf("%d.%s", m_nYIndex, @@ -1668,8 +1668,9 @@ void OGRMVTDirectoryLayer::OpenTileIfNeeded() if (m_bUseReadDir) { while (m_nYIndex < m_aosSubDirContent.Count() && - (CPLGetValueType(CPLGetBasename( - m_aosSubDirContent[m_nYIndex])) != CPL_VALUE_INTEGER || + (CPLGetValueType( + CPLGetBasenameSafe(m_aosSubDirContent[m_nYIndex]) + .c_str()) != CPL_VALUE_INTEGER || !IsBetween(atoi(m_aosSubDirContent[m_nYIndex]), m_nFilterMinY, m_nFilterMaxY))) { @@ -1849,8 +1850,8 @@ OGRFeature *OGRMVTDirectoryLayer::GetFeature(GIntBig nFID) const int nX = static_cast(nFID & ((1 << m_nZ) - 1)); const int nY = static_cast((nFID >> m_nZ) & ((1 << m_nZ) - 1)); const GIntBig nTileFID = nFID >> (2 * m_nZ); - const CPLString osFilename = CPLFormFilename( - CPLFormFilename(m_osDirName, CPLSPrintf("%d", nX), nullptr), + const CPLString osFilename = CPLFormFilenameSafe( + CPLFormFilenameSafe(m_osDirName, CPLSPrintf("%d", nX), nullptr).c_str(), CPLSPrintf("%d.%s", nY, m_poDS->m_osTileExtension.c_str()), nullptr); GDALOpenInfo oOpenInfo(("MVT:" + osFilename).c_str(), GA_ReadOnly); oOpenInfo.papszOpenOptions = CSLSetNameValue( @@ -1954,8 +1955,9 @@ static int OGRMVTDriverIdentify(GDALOpenInfo *poOpenInfo) CPL_VALUE_INTEGER) { VSIStatBufL sStat; - CPLString osMetadataFile(CPLFormFilename( - CPLGetPath(poOpenInfo->pszFilename), "metadata.json", nullptr)); + CPLString osMetadataFile(CPLFormFilenameSafe( + CPLGetPathSafe(poOpenInfo->pszFilename).c_str(), + "metadata.json", nullptr)); const char *pszMetadataFile = CSLFetchNameValue( poOpenInfo->papszOpenOptions, "METADATA_FILE"); if (pszMetadataFile) @@ -1973,10 +1975,10 @@ static int OGRMVTDriverIdentify(GDALOpenInfo *poOpenInfo) { // tileserver-gl metadata file: // If opening /path/to/foo/0, try looking for /path/to/foo.json - CPLString osParentDir(CPLGetPath(poOpenInfo->pszFilename)); + CPLString osParentDir(CPLGetPathSafe(poOpenInfo->pszFilename)); osMetadataFile = - CPLFormFilename(CPLGetPath(osParentDir), - CPLGetFilename(osParentDir), "json"); + CPLFormFilenameSafe(CPLGetPathSafe(osParentDir).c_str(), + CPLGetFilename(osParentDir), "json"); if (VSIStatL(osMetadataFile, &sStat) == 0) { return TRUE; @@ -1984,28 +1986,29 @@ static int OGRMVTDriverIdentify(GDALOpenInfo *poOpenInfo) } // At least 3 files, to include the dummy . and .. - CPLStringList aosDirContent( - VSIReadDirEx(poOpenInfo->pszFilename, 3)); - aosDirContent = StripDummyEntries(aosDirContent); + const CPLStringList aosDirContent = StripDummyEntries( + CPLStringList(VSIReadDirEx(poOpenInfo->pszFilename, 3))); if (!aosDirContent.empty() && CPLGetValueType(aosDirContent[0]) == CPL_VALUE_INTEGER) { - CPLString osSubDir = CPLFormFilename(poOpenInfo->pszFilename, - aosDirContent[0], nullptr); + const std::string osSubDir = CPLFormFilenameSafe( + poOpenInfo->pszFilename, aosDirContent[0], nullptr); // At least 3 files, to include the dummy . and .. - CPLStringList aosSubDirContent(VSIReadDirEx(osSubDir, 10)); - aosSubDirContent = StripDummyEntries(aosSubDirContent); - CPLString osTileExtension(CSLFetchNameValueDef( + const CPLStringList aosSubDirContent = StripDummyEntries( + CPLStringList(VSIReadDirEx(osSubDir.c_str(), 10))); + const std::string osTileExtension(CSLFetchNameValueDef( poOpenInfo->papszOpenOptions, "TILE_EXTENSION", "pbf")); for (int i = 0; i < aosSubDirContent.Count(); i++) { - if (CPLGetValueType(CPLGetBasename(aosSubDirContent[i])) == + if (CPLGetValueType( + CPLGetBasenameSafe(aosSubDirContent[i]).c_str()) == CPL_VALUE_INTEGER) { - CPLString osExtension( - CPLGetExtension(aosSubDirContent[i])); - if (EQUAL(osExtension, osTileExtension) || - EQUAL(osExtension, "mvt")) + const std::string osExtension( + CPLGetExtensionSafe(aosSubDirContent[i])); + if (EQUAL(osExtension.c_str(), + osTileExtension.c_str()) || + EQUAL(osExtension.c_str(), "mvt")) { return TRUE; } @@ -2540,8 +2543,9 @@ GDALDataset *OGRMVTDataset::OpenDirectory(GDALOpenInfo *poOpenInfo) if (nZ < 0 || nZ > 30) return nullptr; - CPLString osMetadataFile(CPLFormFilename( - CPLGetPath(poOpenInfo->pszFilename), "metadata.json", nullptr)); + CPLString osMetadataFile( + CPLFormFilenameSafe(CPLGetPathSafe(poOpenInfo->pszFilename).c_str(), + "metadata.json", nullptr)); const char *pszMetadataFile = CSLFetchNameValue(poOpenInfo->papszOpenOptions, "METADATA_FILE"); if (pszMetadataFile) @@ -2582,10 +2586,11 @@ GDALDataset *OGRMVTDataset::OpenDirectory(GDALOpenInfo *poOpenInfo) // tileserver-gl metadata file: // If opening /path/to/foo/0, try looking for // /path/to/foo.json - CPLString osParentDir(CPLGetPath(poOpenInfo->pszFilename)); - osMetadataFile = - CPLFormFilename(CPLGetPath(osParentDir), - CPLGetFilename(osParentDir), "json"); + CPLString osParentDir( + CPLGetPathSafe(poOpenInfo->pszFilename)); + osMetadataFile = CPLFormFilenameSafe( + CPLGetPathSafe(osParentDir).c_str(), + CPLGetFilename(osParentDir), "json"); continue; } } @@ -2606,9 +2611,10 @@ GDALDataset *OGRMVTDataset::OpenDirectory(GDALOpenInfo *poOpenInfo) { // tileserver-gl metadata file: // If opening /path/to/foo/0, try looking for /path/to/foo.json - CPLString osParentDir(CPLGetPath(poOpenInfo->pszFilename)); - osMetadataFile = CPLFormFilename( - CPLGetPath(osParentDir), CPLGetFilename(osParentDir), "json"); + CPLString osParentDir(CPLGetPathSafe(poOpenInfo->pszFilename)); + osMetadataFile = + CPLFormFilenameSafe(CPLGetPathSafe(osParentDir).c_str(), + CPLGetFilename(osParentDir), "json"); bMetadataFileExists = (VSIStatL(osMetadataFile, &sStat) == 0); } } @@ -2645,7 +2651,7 @@ GDALDataset *OGRMVTDataset::OpenDirectory(GDALOpenInfo *poOpenInfo) continue; } } - CPLString osSubDir = CPLFormFilename( + CPLString osSubDir = CPLFormFilenameSafe( poOpenInfo->pszFilename, bTryToListDir ? aosDirContent[i] : CPLSPrintf("%d", i), nullptr); @@ -2661,13 +2667,14 @@ GDALDataset *OGRMVTDataset::OpenDirectory(GDALOpenInfo *poOpenInfo) { if (bTryToListDir) { - if (CPLGetValueType(CPLGetBasename(aosSubDirContent[j])) != + if (CPLGetValueType( + CPLGetBasenameSafe(aosSubDirContent[j]).c_str()) != CPL_VALUE_INTEGER) { continue; } } - CPLString osFilename(CPLFormFilename( + const std::string osFilename(CPLFormFilenameSafe( osSubDir, bTryToListDir ? aosSubDirContent[j] @@ -2966,9 +2973,10 @@ GDALDataset *OGRMVTDataset::Open(GDALOpenInfo *poOpenInfo) return nullptr; } - CPLString osY = CPLGetBasename(osFilename); - CPLString osX = CPLGetBasename(CPLGetPath(osFilename)); - CPLString osZ = CPLGetBasename(CPLGetPath(CPLGetPath(osFilename))); + CPLString osY = CPLGetBasenameSafe(osFilename); + CPLString osX = CPLGetBasenameSafe(CPLGetPathSafe(osFilename).c_str()); + CPLString osZ = CPLGetBasenameSafe( + CPLGetPathSafe(CPLGetPathSafe(osFilename).c_str()).c_str()); size_t nPos = osY.find('.'); if (nPos != std::string::npos) osY.resize(nPos); @@ -2983,9 +2991,11 @@ GDALDataset *OGRMVTDataset::Open(GDALOpenInfo *poOpenInfo) CPLGetValueType(osY) == CPL_VALUE_INTEGER && CPLGetValueType(osZ) == CPL_VALUE_INTEGER) { - osMetadataFile = - CPLFormFilename(CPLGetPath(CPLGetPath(CPLGetPath(osFilename))), - "metadata.json", nullptr); + osMetadataFile = CPLFormFilenameSafe( + CPLGetPathSafe( + CPLGetPathSafe(CPLGetPathSafe(osFilename).c_str()).c_str()) + .c_str(), + "metadata.json", nullptr); if (osMetadataFile.find("/vsigzip/") == 0) { osMetadataFile = osMetadataFile.substr(strlen("/vsigzip/")); @@ -3093,7 +3103,8 @@ GDALDataset *OGRMVTDataset::Open(GDALOpenInfo *poOpenInfo) int nX = 0; int nY = 0; int nZ = 0; - CPLString osBasename(CPLGetBasename(CPLGetBasename(osFilename))); + CPLString osBasename( + CPLGetBasenameSafe(CPLGetBasenameSafe(osFilename).c_str())); if (sscanf(osBasename, "%d-%d-%d", &nZ, &nX, &nY) == 3 || sscanf(osBasename, "%d_%d_%d", &nZ, &nX, &nY) == 3) { @@ -5279,24 +5290,25 @@ bool OGRMVTWriterDataset::CreateOutput() } else { - CPLString osZDirname(CPLFormFilename( + const std::string osZDirname(CPLFormFilenameSafe( GetDescription(), CPLSPrintf("%d", nZ), nullptr)); - CPLString osXDirname( - CPLFormFilename(osZDirname, CPLSPrintf("%d", nX), nullptr)); + const std::string osXDirname(CPLFormFilenameSafe( + osZDirname.c_str(), CPLSPrintf("%d", nX), nullptr)); if (nZ != nLastZ) { - VSIMkdir(osZDirname, 0755); + VSIMkdir(osZDirname.c_str(), 0755); nLastZ = nZ; nLastX = -1; } if (nX != nLastX) { - VSIMkdir(osXDirname, 0755); + VSIMkdir(osXDirname.c_str(), 0755); nLastX = nX; } - CPLString osTileFilename(CPLFormFilename( - osXDirname, CPLSPrintf("%d", nY), m_osExtension.c_str())); - VSILFILE *fpOut = VSIFOpenL(osTileFilename, "wb"); + const std::string osTileFilename( + CPLFormFilenameSafe(osXDirname.c_str(), CPLSPrintf("%d", nY), + m_osExtension.c_str())); + VSILFILE *fpOut = VSIFOpenL(osTileFilename.c_str(), "wb"); if (fpOut) { const size_t nRet = VSIFWriteL(oTileBuffer.data(), 1, @@ -5688,7 +5700,7 @@ bool OGRMVTWriterDataset::GenerateMetadata( } return oDoc.Save( - CPLFormFilename(GetDescription(), "metadata.json", nullptr)); + CPLFormFilenameSafe(GetDescription(), "metadata.json", nullptr)); } /************************************************************************/ @@ -5956,7 +5968,8 @@ GDALDataset *OGRMVTWriterDataset::Create(const char *pszFilename, int nXSize, } const char *pszFormat = CSLFetchNameValue(papszOptions, "FORMAT"); - const bool bMBTILESExt = EQUAL(CPLGetExtension(pszFilename), "mbtiles"); + const bool bMBTILESExt = + EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "mbtiles"); if (pszFormat == nullptr && bMBTILESExt) { pszFormat = "MBTILES"; @@ -6133,8 +6146,8 @@ GDALDataset *OGRMVTWriterDataset::Create(const char *pszFilename, int nXSize, } } - poDS->m_osName = - CSLFetchNameValueDef(papszOptions, "NAME", CPLGetBasename(pszFilename)); + poDS->m_osName = CSLFetchNameValueDef( + papszOptions, "NAME", CPLGetBasenameSafe(pszFilename).c_str()); poDS->m_osDescription = CSLFetchNameValueDef(papszOptions, "DESCRIPTION", poDS->m_osDescription.c_str()); poDS->m_osType = diff --git a/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp b/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp index 7142f7c955af..7d8402a839f0 100644 --- a/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp +++ b/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp @@ -67,8 +67,6 @@ int OGRNASDataSource::Open(const char *pszNewName) bool bHaveSchema = false; bool bHaveTemplate = false; - const char *pszGFSFilename; - VSIStatBufL sGFSStatBuf; // Is some NAS Feature Schema (.gfs) TEMPLATE required? const char *pszNASTemplateName = CPLGetConfigOption("NAS_GFS_TEMPLATE", ""); @@ -93,8 +91,10 @@ int OGRNASDataSource::Open(const char *pszNewName) /* Can we find a NAS Feature Schema (.gfs) for the input file? */ /* -------------------------------------------------------------------- */ - pszGFSFilename = CPLResetExtension(pszNewName, "gfs"); - if (VSIStatL(pszGFSFilename, &sGFSStatBuf) == 0) + const std::string osGFSFilename = + CPLResetExtensionSafe(pszNewName, "gfs"); + VSIStatBufL sGFSStatBuf; + if (VSIStatL(osGFSFilename.c_str(), &sGFSStatBuf) == 0) { VSIStatBufL sNASStatBuf; if (VSIStatL(pszNewName, &sNASStatBuf) == 0 && @@ -103,11 +103,11 @@ int OGRNASDataSource::Open(const char *pszNewName) CPLDebug("NAS", "Found %s but ignoring because it appears " "be older than the associated NAS file.", - pszGFSFilename); + osGFSFilename.c_str()); } else { - bHaveSchema = poReader->LoadClasses(pszGFSFilename); + bHaveSchema = poReader->LoadClasses(osGFSFilename.c_str()); } } @@ -144,18 +144,20 @@ int OGRNASDataSource::Open(const char *pszNewName) { VSILFILE *fp = nullptr; - pszGFSFilename = CPLResetExtension(pszNewName, "gfs"); - if (VSIStatL(pszGFSFilename, &sGFSStatBuf) != 0 && - (fp = VSIFOpenL(pszGFSFilename, "wt")) != nullptr) + const std::string osGFSFilename = + CPLResetExtensionSafe(pszNewName, "gfs"); + VSIStatBufL sGFSStatBuf; + if (VSIStatL(osGFSFilename.c_str(), &sGFSStatBuf) != 0 && + (fp = VSIFOpenL(osGFSFilename.c_str(), "wt")) != nullptr) { VSIFCloseL(fp); - poReader->SaveClasses(pszGFSFilename); + poReader->SaveClasses(osGFSFilename.c_str()); } else { CPLDebug("NAS", "Not saving %s. File already exists or can't be created.", - pszGFSFilename); + osGFSFilename.c_str()); } } diff --git a/ogr/ogrsf_frmts/ngw/ogrngwdriver.cpp b/ogr/ogrsf_frmts/ngw/ogrngwdriver.cpp index 29815da4a84a..f6ae91baebd1 100644 --- a/ogr/ogrsf_frmts/ngw/ogrngwdriver.cpp +++ b/ogr/ogrsf_frmts/ngw/ogrngwdriver.cpp @@ -277,7 +277,7 @@ static GDALDataset *OGRNGWDriverCreateCopy(const char *pszFilename, // Compress to minimize network transfer. const char *apszOptions[] = {"COMPRESS=LZW", "NUM_THREADS=ALL_CPUS", nullptr}; - std::string osTempFilename = CPLGenerateTempFilename("ngw_tmp"); + std::string osTempFilename = CPLGenerateTempFilenameSafe("ngw_tmp"); osTempFilename += ".tif"; GDALDataset *poTmpDS = poDriver->CreateCopy( osTempFilename.c_str(), poSrcDS, bStrict, @@ -305,8 +305,8 @@ static GDALDataset *OGRNGWDriverCreateCopy(const char *pszFilename, for (int i = 0; i < oaFiles.size(); ++i) { // Check extension tif - const char *pszExt = CPLGetExtension(oaFiles[i]); - if (pszExt && EQUALN(pszExt, "tif", 3)) + const std::string osExt = CPLGetExtensionSafe(oaFiles[i]); + if (EQUALN(osExt.c_str(), "tif", 3)) { osFilename = oaFiles[i]; break; diff --git a/ogr/ogrsf_frmts/oapif/ogroapifdriver.cpp b/ogr/ogrsf_frmts/oapif/ogroapifdriver.cpp index 0c759fcc6f69..76623a3e441f 100644 --- a/ogr/ogrsf_frmts/oapif/ogroapifdriver.cpp +++ b/ogr/ogrsf_frmts/oapif/ogroapifdriver.cpp @@ -303,7 +303,7 @@ CPLString OGROAPIFDataset::ResolveURL(const CPLString &osURL, // Cf https://datatracker.ietf.org/doc/html/rfc3986#section-5.4 // Partial implementation for usual cases... const std::string osRequestURLBase = - CPLGetPath(CleanURL(osRequestURL).c_str()); + CPLGetPathSafe(CleanURL(osRequestURL).c_str()); if (!osURL.empty() && osURL[0] == '/') osRet = m_osServerBaseURL + osURL; else if (osURL.size() > 2 && osURL[0] == '.' && osURL[1] == '/') @@ -315,7 +315,7 @@ CPLString OGROAPIFDataset::ResolveURL(const CPLString &osURL, while (osRet.size() > 3 && osRet[0] == '.' && osRet[1] == '.' && osRet[2] == '/') { - osModifiedRequestURL = CPLGetPath(osModifiedRequestURL.c_str()); + osModifiedRequestURL = CPLGetPathSafe(osModifiedRequestURL.c_str()); osRet = osRet.substr(3); } osRet = osModifiedRequestURL + "/" + osRet; diff --git a/ogr/ogrsf_frmts/oci/ogrociloaderlayer.cpp b/ogr/ogrsf_frmts/oci/ogrociloaderlayer.cpp index 6f501cefa8b3..59afd84b4856 100644 --- a/ogr/ogrsf_frmts/oci/ogrociloaderlayer.cpp +++ b/ogr/ogrsf_frmts/oci/ogrociloaderlayer.cpp @@ -124,17 +124,18 @@ void OGROCILoaderLayer::WriteLoaderHeader() } else if (nLDRMode == LDRM_VARIABLE) { - const char *pszDataFilename = - CPLResetExtension(pszLoaderFilename, "dat"); - fpData = VSIFOpen(pszDataFilename, "wb"); + const std::string osDataFilename = + CPLResetExtensionSafe(pszLoaderFilename, "dat"); + fpData = VSIFOpen(osDataFilename.c_str(), "wb"); if (fpData == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, - "Unable to open data output file `%s'.", pszDataFilename); + "Unable to open data output file `%s'.", + osDataFilename.c_str()); return; } - VSIFPrintf(fpLoader, "INFILE %s \"var 8\"\n", pszDataFilename); + VSIFPrintf(fpLoader, "INFILE %s \"var 8\"\n", osDataFilename.c_str()); } const char *pszExpectedFIDName = CPLGetConfigOption("OCI_FID", "OGR_FID"); diff --git a/ogr/ogrsf_frmts/odbc/ogrodbcdatasource.cpp b/ogr/ogrsf_frmts/odbc/ogrodbcdatasource.cpp index 3b6ab44fcf7c..65b8017fef78 100644 --- a/ogr/ogrsf_frmts/odbc/ogrodbcdatasource.cpp +++ b/ogr/ogrsf_frmts/odbc/ogrodbcdatasource.cpp @@ -185,7 +185,7 @@ int OGRODBCDataSource::Open(GDALOpenInfo *poOpenInfo) constexpr const char *ODBC_PREFIX = "ODBC:"; if (!STARTS_WITH_CI(pszNewName, ODBC_PREFIX) && OGRODBCDriverIsSupportedMsAccessFileExtension( - CPLGetExtension(pszNewName))) + CPLGetExtensionSafe(pszNewName).c_str())) return OpenMDB(poOpenInfo); /* -------------------------------------------------------------------- */ diff --git a/ogr/ogrsf_frmts/odbc/ogrodbcdrivercore.cpp b/ogr/ogrsf_frmts/odbc/ogrodbcdrivercore.cpp index 22ec4aa32ae1..93f32dc48229 100644 --- a/ogr/ogrsf_frmts/odbc/ogrodbcdrivercore.cpp +++ b/ogr/ogrsf_frmts/odbc/ogrodbcdrivercore.cpp @@ -40,7 +40,7 @@ int OGRODBCDriverIdentify(GDALOpenInfo *poOpenInfo) if (STARTS_WITH_CI(poOpenInfo->pszFilename, "ODBC:")) return TRUE; - const char *psExtension(CPLGetExtension(poOpenInfo->pszFilename)); + const char *psExtension = poOpenInfo->osExtension.c_str(); if (EQUAL(psExtension, "mdb")) return -1; // Could potentially be a PGeo MDB database diff --git a/ogr/ogrsf_frmts/ods/ogrodsdriver.cpp b/ogr/ogrsf_frmts/ods/ogrodsdriver.cpp index 215527e11eec..af7625b12dcf 100644 --- a/ogr/ogrsf_frmts/ods/ogrodsdriver.cpp +++ b/ogr/ogrsf_frmts/ods/ogrodsdriver.cpp @@ -39,7 +39,7 @@ static int OGRODSDriverIdentify(GDALOpenInfo *poOpenInfo) "pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (!EQUAL(pszExt, "ODS") && !EQUAL(pszExt, "ODS}")) return FALSE; @@ -170,7 +170,7 @@ static GDALDataset *OGRODSDriverCreate(const char *pszName, int /* nXSize */, char **papszOptions) { - if (!EQUAL(CPLGetExtension(pszName), "ODS")) + if (!EQUAL(CPLGetExtensionSafe(pszName).c_str(), "ODS")) { CPLError(CE_Failure, CPLE_AppDefined, "File extension should be ODS"); return nullptr; diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbindex.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbindex.cpp index e96ca20007e7..80bb5a351bd5 100644 --- a/ogr/ogrsf_frmts/openfilegdb/filegdbindex.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/filegdbindex.cpp @@ -1026,9 +1026,9 @@ static const char *FileGDBValueToStr(OGRFieldType eOGRFieldType, int FileGDBIndex::GetMaxWidthInBytes(const FileGDBTable *poTable) const { - const char *pszAtxName = CPLResetExtension( + const std::string osAtxName = CPLResetExtensionSafe( poTable->GetFilename().c_str(), (GetIndexName() + ".atx").c_str()); - VSILFILE *fpCurIdx = VSIFOpenL(pszAtxName, "rb"); + VSILFILE *fpCurIdx = VSIFOpenL(osAtxName.c_str(), "rb"); if (fpCurIdx == nullptr) return 0; @@ -1130,12 +1130,14 @@ int FileGDBIndexIterator::SetConstraint(int nFieldIdx, FileGDBSQLOp op, return FALSE; } - const char *pszAtxName = - CPLFormFilename(CPLGetPath(poParent->GetFilename().c_str()), - CPLGetBasename(poParent->GetFilename().c_str()), - CPLSPrintf("%s.atx", poIndex->GetIndexName().c_str())); + const std::string osAtxName = + CPLFormFilenameSafe( + CPLGetPathSafe(poParent->GetFilename().c_str()).c_str(), + CPLGetBasenameSafe(poParent->GetFilename().c_str()).c_str(), + poIndex->GetIndexName().c_str()) + .append(".atx"); - if (!ReadTrailer(pszAtxName)) + if (!ReadTrailer(osAtxName.c_str())) return FALSE; returnErrorIf(m_nValueCountInIdx > static_cast(poParent->GetValidRecordCount())); @@ -2483,11 +2485,11 @@ bool FileGDBSpatialIndexIteratorImpl::Init() { const bool errorRetValue = false; - const char *pszSpxName = - CPLFormFilename(CPLGetPath(poParent->GetFilename().c_str()), - CPLGetBasename(poParent->GetFilename().c_str()), "spx"); + const std::string osSpxName = CPLFormFilenameSafe( + CPLGetPathSafe(poParent->GetFilename().c_str()).c_str(), + CPLGetBasenameSafe(poParent->GetFilename().c_str()).c_str(), "spx"); - if (!ReadTrailer(pszSpxName)) + if (!ReadTrailer(osSpxName.c_str())) return false; returnErrorIf(m_nValueSize != sizeof(uint64_t)); @@ -2511,7 +2513,8 @@ bool FileGDBSpatialIndexIteratorImpl::Init() // The FileGDB driver does not use the .spx file in that situation, // so do we. CPLDebug("OpenFileGDB", - "Cannot use %s as the grid resolution is invalid", pszSpxName); + "Cannot use %s as the grid resolution is invalid", + osSpxName.c_str()); return false; } @@ -2544,7 +2547,7 @@ bool FileGDBSpatialIndexIteratorImpl::Init() CPLError(CE_Warning, CPLE_AppDefined, "Cannot use %s as the index depth(=1) is suspicious " "(it should rather be 2)", - pszSpxName); + osSpxName.c_str()); return false; } } diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbindex_write.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbindex_write.cpp index 242d431fcb73..4b2c3f9d6a58 100644 --- a/ogr/ogrsf_frmts/openfilegdb/filegdbindex_write.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/filegdbindex_write.cpp @@ -54,13 +54,15 @@ void FileGDBTable::RemoveIndices() osUCIndexFieldName.toupper(); if (osUCIndexFieldName == osUCGeomFieldName) { - VSIUnlink(CPLResetExtension(m_osFilename.c_str(), "spx")); + VSIUnlink( + CPLResetExtensionSafe(m_osFilename.c_str(), "spx").c_str()); } else { - VSIUnlink( - CPLResetExtension(m_osFilename.c_str(), - (poIndex->GetIndexName() + ".atx").c_str())); + VSIUnlink(CPLResetExtensionSafe( + m_osFilename.c_str(), + (poIndex->GetIndexName() + ".atx").c_str()) + .c_str()); } } @@ -264,8 +266,9 @@ void FileGDBTable::CreateGdbIndexesFile() WriteUInt16(abyBuffer, 0); // unknown semantics } - VSILFILE *fp = - VSIFOpenL(CPLResetExtension(m_osFilename.c_str(), "gdbindexes"), "wb"); + VSILFILE *fp = VSIFOpenL( + CPLResetExtensionSafe(m_osFilename.c_str(), "gdbindexes").c_str(), + "wb"); if (fp == nullptr) return; CPL_IGNORE_RET_VAL(VSIFWriteL(abyBuffer.data(), abyBuffer.size(), 1, fp)); @@ -1271,7 +1274,7 @@ bool FileGDBTable::CreateSpatialIndex() } const std::string osSPXFilename( - CPLResetExtension(m_osFilename.c_str(), "spx")); + CPLResetExtensionSafe(m_osFilename.c_str(), "spx")); VSILFILE *fp = VSIFOpenL(osSPXFilename.c_str(), "wb"); if (fp == nullptr) return false; @@ -1314,7 +1317,7 @@ bool FileGDBTable::CreateAttributeIndex(const FileGDBIndex *poIndex) return false; } - const std::string osIdxFilename(CPLResetExtension( + const std::string osIdxFilename(CPLResetExtensionSafe( m_osFilename.c_str(), (poIndex->GetIndexName() + ".atx").c_str())); VSILFILE *fp = VSIFOpenL(osIdxFilename.c_str(), "wb"); if (fp == nullptr) diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp index 3ed8d567843b..27ab42f44786 100644 --- a/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp @@ -870,14 +870,15 @@ bool FileGDBTable::Open(const char *pszFilename, bool bUpdate, m_nHeaderBufferMaxSize = GetInt32(abyHeader + 8, 0); - CPLString osTableXName; + std::string osTableXName; if (m_bUpdate || (m_nValidRecordCount > 0 && !CPLTestBool(CPLGetConfigOption( "OPENFILEGDB_IGNORE_GDBTABLX", "false")))) { - osTableXName = CPLFormFilename(CPLGetPath(pszFilename), - CPLGetBasename(pszFilename), "gdbtablx"); - m_fpTableX = VSIFOpenL(osTableXName, m_bUpdate ? "r+b" : "rb"); + osTableXName = CPLFormFilenameSafe( + CPLGetPathSafe(pszFilename).c_str(), + CPLGetBasenameSafe(pszFilename).c_str(), "gdbtablx"); + m_fpTableX = VSIFOpenL(osTableXName.c_str(), m_bUpdate ? "r+b" : "rb"); if (m_fpTableX == nullptr) { if (m_bUpdate) @@ -2478,14 +2479,15 @@ int FileGDBTable::GetIndexCount() m_bHasReadGDBIndexes = TRUE; - const char *pszIndexesName = - CPLFormFilename(CPLGetPath(m_osFilename.c_str()), - CPLGetBasename(m_osFilename.c_str()), "gdbindexes"); - VSILFILE *fpIndexes = VSIFOpenL(pszIndexesName, "rb"); + const std::string osIndexesName = CPLFormFilenameSafe( + CPLGetPathSafe(m_osFilename.c_str()).c_str(), + CPLGetBasenameSafe(m_osFilename.c_str()).c_str(), "gdbindexes"); + VSILFILE *fpIndexes = VSIFOpenL(osIndexesName.c_str(), "rb"); VSIStatBufL sStat; if (fpIndexes == nullptr) { - if (VSIStatExL(pszIndexesName, &sStat, VSI_STAT_EXISTS_FLAG) == 0) + if (VSIStatExL(osIndexesName.c_str(), &sStat, VSI_STAT_EXISTS_FLAG) == + 0) returnError(); else return 0; @@ -2520,8 +2522,8 @@ int FileGDBTable::GetIndexCount() const int iBlockKeyFieldIdx = GetFieldIdx("block_key"); if (iBlockKeyFieldIdx >= 0) { - std::string osAtxFilename = - CPLResetExtension(m_osFilename.c_str(), "blk_key_index.atx"); + const std::string osAtxFilename = CPLResetExtensionSafe( + m_osFilename.c_str(), "blk_key_index.atx"); if (VSIStatExL(osAtxFilename.c_str(), &sStat, VSI_STAT_EXISTS_FLAG) == 0) { @@ -2574,7 +2576,7 @@ int FileGDBTable::GetIndexCount() // Cf files a00000029.gdbindexes, a000000ea.gdbindexes, a000000ed.gdbindexes, // a000000f8.gdbindexes, a000000fb.gdbindexes, a00000103.gdbindexes // from https://github.com/OSGeo/gdal/issues/11295#issuecomment-2491158506 - CPLDebug("OpenFileGDB", "Reading %s", pszIndexesName); + CPLDebug("OpenFileGDB", "Reading %s", osIndexesName.c_str()); CPLDebug( "OpenFileGDB", "Strange (deleted?) index descriptor at index %u of name %s", i, @@ -2669,12 +2671,12 @@ bool FileGDBTable::HasSpatialIndex() { if (m_nHasSpatialIndex < 0) { - const char *pszSpxName = - CPLFormFilename(CPLGetPath(m_osFilename.c_str()), - CPLGetBasename(m_osFilename.c_str()), "spx"); + const std::string osSpxName = CPLFormFilenameSafe( + CPLGetPathSafe(m_osFilename.c_str()).c_str(), + CPLGetBasenameSafe(m_osFilename.c_str()).c_str(), "spx"); VSIStatBufL sStat; m_nHasSpatialIndex = - (VSIStatExL(pszSpxName, &sStat, VSI_STAT_EXISTS_FLAG) == 0); + (VSIStatExL(osSpxName.c_str(), &sStat, VSI_STAT_EXISTS_FLAG) == 0); } return m_nHasSpatialIndex != FALSE; } diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbtable_freelist.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbtable_freelist.cpp index d9ed1343807c..061f191cd7a9 100644 --- a/ogr/ogrsf_frmts/openfilegdb/filegdbtable_freelist.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/filegdbtable_freelist.cpp @@ -74,7 +74,7 @@ void FileGDBTable::AddEntryToFreelist(uint64_t nOffset, uint32_t nSize) return; const std::string osFilename = - CPLResetExtension(m_osFilename.c_str(), "freelist"); + CPLResetExtensionSafe(m_osFilename.c_str(), "freelist"); VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "rb+"); if (fp == nullptr) { @@ -239,7 +239,7 @@ uint64_t FileGDBTable::GetOffsetOfFreeAreaFromFreeList(uint32_t nSize) return OFFSET_MINUS_ONE; const std::string osFilename = - CPLResetExtension(m_osFilename.c_str(), "freelist"); + CPLResetExtensionSafe(m_osFilename.c_str(), "freelist"); VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "rb+"); m_nHasFreeList = fp != nullptr; if (fp == nullptr) @@ -529,7 +529,7 @@ uint64_t FileGDBTable::GetOffsetOfFreeAreaFromFreeList(uint32_t nSize) bool FileGDBTable::CheckFreeListConsistency() { const std::string osFilename = - CPLResetExtension(m_osFilename.c_str(), "freelist"); + CPLResetExtensionSafe(m_osFilename.c_str(), "freelist"); VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "rb"); if (fp == nullptr) return true; @@ -744,7 +744,7 @@ void FileGDBTable::DeleteFreeList() { m_bFreelistCanBeDeleted = false; m_nHasFreeList = -1; - VSIUnlink(CPLResetExtension(m_osFilename.c_str(), "freelist")); + VSIUnlink(CPLResetExtensionSafe(m_osFilename.c_str(), "freelist").c_str()); } } /* namespace OpenFileGDB */ diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write.cpp index 6addae4f5a96..8c0e7a8f06aa 100644 --- a/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write.cpp @@ -68,7 +68,7 @@ bool FileGDBTable::Create(const char *pszFilename, int nTablxOffsetSize, m_bGeomTypeHasM = bGeomTypeHasM; m_bHasReadGDBIndexes = TRUE; - if (!EQUAL(CPLGetExtension(pszFilename), "gdbtable")) + if (!EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "gdbtable")) { CPLError(CE_Failure, CPLE_AppDefined, "FileGDB table extension must be gdbtable"); @@ -85,7 +85,8 @@ bool FileGDBTable::Create(const char *pszFilename, int nTablxOffsetSize, return false; } - const std::string osTableXName = CPLResetExtension(pszFilename, "gdbtablx"); + const std::string osTableXName = + CPLResetExtensionSafe(pszFilename, "gdbtablx"); m_fpTableX = VSIFOpenL(osTableXName.c_str(), "wb+"); if (m_fpTableX == nullptr) { @@ -2127,12 +2128,12 @@ bool FileGDBTable::WholeFileRewriter::Begin() #endif )); - m_osGdbTablx = CPLFormFilename( - CPLGetPath(m_oTable.m_osFilename.c_str()), - CPLGetBasename(m_oTable.m_osFilename.c_str()), "gdbtablx"); + m_osGdbTablx = CPLFormFilenameSafe( + CPLGetPathSafe(m_oTable.m_osFilename.c_str()).c_str(), + CPLGetBasenameSafe(m_oTable.m_osFilename.c_str()).c_str(), "gdbtablx"); - m_osBackupGdbTable = - CPLResetExtension(m_oTable.m_osFilename.c_str(), "_backup.gdbtable"); + m_osBackupGdbTable = CPLResetExtensionSafe(m_oTable.m_osFilename.c_str(), + "_backup.gdbtable"); VSIStatBufL sStat; if (VSIStatL(m_osBackupGdbTable.c_str(), &sStat) == 0) { @@ -2143,7 +2144,7 @@ bool FileGDBTable::WholeFileRewriter::Begin() } m_osBackupGdbTablx = - CPLResetExtension(m_osGdbTablx.c_str(), "_backup.gdbtablx"); + CPLResetExtensionSafe(m_osGdbTablx.c_str(), "_backup.gdbtablx"); if (m_bModifyInPlace) { @@ -2188,10 +2189,10 @@ bool FileGDBTable::WholeFileRewriter::Begin() } else { - m_osTmpGdbTable = CPLResetExtension(m_oTable.m_osFilename.c_str(), - "_compress.gdbtable"); + m_osTmpGdbTable = CPLResetExtensionSafe(m_oTable.m_osFilename.c_str(), + "_compress.gdbtable"); m_osTmpGdbTablx = - CPLResetExtension(m_osGdbTablx.c_str(), "_compress.gdbtablx"); + CPLResetExtensionSafe(m_osGdbTablx.c_str(), "_compress.gdbtablx"); m_fpOldGdbtable = m_oTable.m_fpTable; m_fpOldGdbtablx = m_oTable.m_fpTableX; diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write_fields.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write_fields.cpp index af9e09ed4940..6f1a12549847 100644 --- a/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write_fields.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/filegdbtable_write_fields.cpp @@ -859,9 +859,11 @@ bool FileGDBTable::DeleteField(int iField) if (iField != m_iObjectIdField) { - VSIUnlink(CPLResetExtension( - m_osFilename.c_str(), - (m_apoIndexes[i]->GetIndexName() + ".atx").c_str())); + VSIUnlink( + CPLResetExtensionSafe( + m_osFilename.c_str(), + (m_apoIndexes[i]->GetIndexName() + ".atx").c_str()) + .c_str()); } m_apoIndexes.erase(m_apoIndexes.begin() + i); diff --git a/ogr/ogrsf_frmts/openfilegdb/gdalopenfilegdbrasterband.cpp b/ogr/ogrsf_frmts/openfilegdb/gdalopenfilegdbrasterband.cpp index 3d4c77c2be79..2100829c9477 100644 --- a/ogr/ogrsf_frmts/openfilegdb/gdalopenfilegdbrasterband.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/gdalopenfilegdbrasterband.cpp @@ -52,9 +52,9 @@ bool OGROpenFileGDBDataSource::OpenRaster(const GDALOpenInfo *poOpenInfo, FileGDBTable oTable; - const CPLString osBndFilename(CPLFormFilename( + const std::string osBndFilename(CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x.gdbtable", nBndIdx), nullptr)); - if (!oTable.Open(osBndFilename, false)) + if (!oTable.Open(osBndFilename.c_str(), false)) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot open table %s", osBndTableName.c_str()); @@ -454,9 +454,9 @@ bool OGROpenFileGDBDataSource::OpenRaster(const GDALOpenInfo *poOpenInfo, FileGDBTable oTableMain; - const CPLString osTableMain(CPLFormFilename( + const std::string osTableMain(CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x.gdbtable", nTableIdx), nullptr)); - if (oTableMain.Open(osTableMain, false)) + if (oTableMain.Open(osTableMain.c_str(), false)) { const int iRasterFieldIdx = oTableMain.GetFieldIdx("RASTER"); if (iRasterFieldIdx >= 0) diff --git a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource.cpp b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource.cpp index abeef39621f1..5e9a43ca0ccf 100644 --- a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource.cpp @@ -190,15 +190,15 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, sscanf(pszFilenameWithoutPath, "a%08x.gdbtable", &unInterestTable) == 1) { nInterestTable = static_cast(unInterestTable); - m_osDirName = CPLGetPath(m_osDirName); + m_osDirName = CPLGetPathSafe(m_osDirName); } - if (EQUAL(CPLGetExtension(m_osDirName), "zip") && + if (EQUAL(CPLGetExtensionSafe(m_osDirName).c_str(), "zip") && !STARTS_WITH(m_osDirName, "/vsizip/")) { m_osDirName = "/vsizip/" + m_osDirName; } - else if (EQUAL(CPLGetExtension(m_osDirName), "tar") && + else if (EQUAL(CPLGetExtensionSafe(m_osDirName).c_str(), "tar") && !STARTS_WITH(m_osDirName, "/vsitar/")) { m_osDirName = "/vsitar/" + m_osDirName; @@ -213,7 +213,7 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, for (int i = 0; papszDir && papszDir[i] != nullptr; i++) { VSIStatBufL sStat; - if (EQUAL(CPLGetExtension(papszDir[i]), "gdb") && + if (EQUAL(CPLGetExtensionSafe(papszDir[i]).c_str(), "gdb") && VSIStatL(CPLSPrintf("%s/%s", m_osDirName.c_str(), papszDir[i]), &sStat) == 0 && VSI_ISDIR(sStat.st_mode)) @@ -235,8 +235,8 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, CSLDestroy(papszDir); } - const std::string osTransactionBackupDirname = - CPLFormFilename(m_osDirName.c_str(), ".ogrtransaction_backup", nullptr); + const std::string osTransactionBackupDirname = CPLFormFilenameSafe( + m_osDirName.c_str(), ".ogrtransaction_backup", nullptr); VSIStatBufL sStat; if (VSIStatL(osTransactionBackupDirname.c_str(), &sStat) == 0) { @@ -269,7 +269,7 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, /* Explore catalog table */ m_osGDBSystemCatalogFilename = - CPLFormFilename(m_osDirName, "a00000001", "gdbtable"); + CPLFormFilenameSafe(m_osDirName, "a00000001", "gdbtable"); if (!FileExists(m_osGDBSystemCatalogFilename.c_str()) || !oTable.Open(m_osGDBSystemCatalogFilename.c_str(), poOpenInfo->eAccess == GA_Update)) @@ -280,9 +280,9 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, auto poLayer = std::make_unique( this, poOpenInfo->pszFilename, pszLyrName, "", "", eAccess == GA_Update); - const char *pszTablX = - CPLResetExtension(poOpenInfo->pszFilename, "gdbtablx"); - if ((!FileExists(pszTablX) && + const std::string osTablX = + CPLResetExtensionSafe(poOpenInfo->pszFilename, "gdbtablx"); + if ((!FileExists(osTablX.c_str()) && poLayer->GetLayerDefn()->GetFieldCount() == 0 && poLayer->GetFeatureCount() == 0) || !poLayer->IsValidLayerDefn()) @@ -329,7 +329,7 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, if (strcmp(psField->String, "GDB_SpatialRefs") == 0) { // Normally a00000003 - m_osGDBSpatialRefsFilename = CPLFormFilename( + m_osGDBSpatialRefsFilename = CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x.gdbtable", i + 1), nullptr); } @@ -337,7 +337,7 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, { // Normally a00000004 but it has been seen in some datasets // to not be a00000004 - m_osGDBItemsFilename = CPLFormFilename( + m_osGDBItemsFilename = CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x.gdbtable", i + 1), nullptr); iGDBItems = i; @@ -346,7 +346,7 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, { // Normally a00000006 but can be a00000005 sometimes (e.g // autotest/ogr/data/filegdb/Domains.gdb) - m_osGDBItemRelationshipsFilename = CPLFormFilename( + m_osGDBItemRelationshipsFilename = CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x.gdbtable", i + 1), nullptr); } @@ -444,7 +444,7 @@ bool OGROpenFileGDBDataSource::Open(const GDALOpenInfo *poOpenInfo, if (bListAllTables || !IsPrivateLayerName(oIter.first)) { const int idx = oIter.second; - CPLString osFilename(CPLFormFilename( + const CPLString osFilename(CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x", idx), "gdbtable")); if (!cpl::contains(oSetIgnoredRasterLayerTableNum, idx) && FileExists(osFilename)) @@ -519,8 +519,8 @@ OGRLayer *OGROpenFileGDBDataSource::AddLayer( { m_osMapNameToIdx.erase(oIter); - CPLString osFilename = - CPLFormFilename(m_osDirName, CPLSPrintf("a%08x", idx), "gdbtable"); + const CPLString osFilename = CPLFormFilenameSafe( + m_osDirName, CPLOPrintf("a%08x", idx).c_str(), "gdbtable"); if (FileExists(osFilename)) { nCandidateLayers++; @@ -528,9 +528,9 @@ OGRLayer *OGROpenFileGDBDataSource::AddLayer( if (m_papszFiles != nullptr) { const CPLString osSDC = - CPLResetExtension(osFilename, "gdbtable.sdc"); + CPLResetExtensionSafe(osFilename, "gdbtable.sdc"); const CPLString osCDF = - CPLResetExtension(osFilename, "gdbtable.cdf"); + CPLResetExtensionSafe(osFilename, "gdbtable.cdf"); if (FileExists(osCDF)) { nLayersCDF++; @@ -661,7 +661,7 @@ bool OGROpenFileGDBDataSource::OpenFileGDBv10( FileGDBTable oTable; - CPLString osFilename(CPLFormFilename( + const CPLString osFilename(CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x.gdbtable", iGDBItems + 1), nullptr)); // Normally we don't need to update in update mode the GDB_Items table, @@ -982,7 +982,7 @@ int OGROpenFileGDBDataSource::OpenFileGDBv9( CPLDebug("OpenFileGDB", "FileGDB v9"); /* Fetch names of layers */ - CPLString osFilename(CPLFormFilename( + CPLString osFilename(CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x", iGDBObjectClasses + 1), "gdbtable")); if (!poTable->Open(osFilename, false)) return FALSE; @@ -1038,7 +1038,7 @@ int OGROpenFileGDBDataSource::OpenFileGDBv9( poTable = std::make_unique(); /* Find tables that are spatial layers */ - osFilename = CPLFormFilename( + osFilename = CPLFormFilenameSafe( m_osDirName, CPLSPrintf("a%08x", iGDBFeatureClasses + 1), "gdbtable"); if (!poTable->Open(osFilename, false)) return FALSE; @@ -1212,8 +1212,8 @@ OGROpenFileGDBDataSource::BuildLayerFromName(const char *pszName) if (oIter != m_osMapNameToIdx.end()) { const int idx = oIter->second; - CPLString osFilename( - CPLFormFilename(m_osDirName, CPLSPrintf("a%08x", idx), "gdbtable")); + const CPLString osFilename(CPLFormFilenameSafe( + m_osDirName, CPLSPrintf("a%08x", idx), "gdbtable")); if (FileExists(osFilename)) { return std::make_unique( @@ -2113,8 +2113,8 @@ char **OGROpenFileGDBDataSource::GetFileList() if (osFilenameRadix.empty() || strncmp(*papszIter, osFilenameRadix, osFilenameRadix.size()) == 0) { - osStringList.AddString( - CPLFormFilename(m_osDirName, *papszIter, nullptr)); + osStringList.push_back( + CPLFormFilenameSafe(m_osDirName, *papszIter, nullptr)); } } CSLDestroy(papszFiles); diff --git a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource_write.cpp b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource_write.cpp index f5ab32612ed3..8656051f614f 100644 --- a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource_write.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdatasource_write.cpp @@ -549,7 +549,7 @@ bool OGROpenFileGDBDataSource::CreateGDBSystemCatalog() { // Write GDB_SystemCatalog file m_osGDBSystemCatalogFilename = - CPLFormFilename(m_osDirName.c_str(), "a00000001.gdbtable", nullptr); + CPLFormFilenameSafe(m_osDirName.c_str(), "a00000001.gdbtable", nullptr); FileGDBTable oTable; if (!oTable.Create(m_osGDBSystemCatalogFilename.c_str(), 4, FGTGT_NONE, false, false) || @@ -605,8 +605,8 @@ bool OGROpenFileGDBDataSource::CreateGDBSystemCatalog() bool OGROpenFileGDBDataSource::CreateGDBDBTune() { // Write GDB_DBTune file - const std::string osFilename( - CPLFormFilename(m_osDirName.c_str(), "a00000002.gdbtable", nullptr)); + const std::string osFilename(CPLFormFilenameSafe( + m_osDirName.c_str(), "a00000002.gdbtable", nullptr)); FileGDBTable oTable; if (!oTable.Create(osFilename.c_str(), 4, FGTGT_NONE, false, false) || !oTable.CreateField(std::make_unique( @@ -704,7 +704,7 @@ bool OGROpenFileGDBDataSource::CreateGDBSpatialRefs() { // Write GDB_SpatialRefs file m_osGDBSpatialRefsFilename = - CPLFormFilename(m_osDirName.c_str(), "a00000003.gdbtable", nullptr); + CPLFormFilenameSafe(m_osDirName.c_str(), "a00000003.gdbtable", nullptr); FileGDBTable oTable; if (!oTable.Create(m_osGDBSpatialRefsFilename.c_str(), 4, FGTGT_NONE, false, false) || @@ -808,7 +808,7 @@ bool OGROpenFileGDBDataSource::CreateGDBItems() } m_osGDBItemsFilename = - CPLFormFilename(m_osDirName.c_str(), "a00000004.gdbtable", nullptr); + CPLFormFilenameSafe(m_osDirName.c_str(), "a00000004.gdbtable", nullptr); FileGDBTable oTable; if (!oTable.Create(m_osGDBItemsFilename.c_str(), 4, FGTGT_POLYGON, false, false) || @@ -950,8 +950,8 @@ bool OGROpenFileGDBDataSource::CreateGDBItems() bool OGROpenFileGDBDataSource::CreateGDBItemTypes() { // Write GDB_ItemTypes file - const std::string osFilename( - CPLFormFilename(m_osDirName.c_str(), "a00000005.gdbtable", nullptr)); + const std::string osFilename(CPLFormFilenameSafe( + m_osDirName.c_str(), "a00000005.gdbtable", nullptr)); FileGDBTable oTable; if (!oTable.Create(osFilename.c_str(), 4, FGTGT_NONE, false, false) || !oTable.CreateField(std::make_unique( @@ -1073,7 +1073,7 @@ bool OGROpenFileGDBDataSource::CreateGDBItemRelationships() { // Write GDB_ItemRelationships file m_osGDBItemRelationshipsFilename = - CPLFormFilename(m_osDirName.c_str(), "a00000006.gdbtable", nullptr); + CPLFormFilenameSafe(m_osDirName.c_str(), "a00000006.gdbtable", nullptr); FileGDBTable oTable; if (!oTable.Create(m_osGDBItemRelationshipsFilename.c_str(), 4, FGTGT_NONE, false, false) || @@ -1130,8 +1130,8 @@ bool OGROpenFileGDBDataSource::CreateGDBItemRelationships() bool OGROpenFileGDBDataSource::CreateGDBItemRelationshipTypes() { // Write GDB_ItemRelationshipTypes file - const std::string osFilename( - CPLFormFilename(m_osDirName.c_str(), "a00000007.gdbtable", nullptr)); + const std::string osFilename(CPLFormFilenameSafe( + m_osDirName.c_str(), "a00000007.gdbtable", nullptr)); FileGDBTable oTable; if (!oTable.Create(osFilename.c_str(), 4, FGTGT_NONE, false, false) || !oTable.CreateField(std::make_unique( @@ -1277,7 +1277,7 @@ bool OGROpenFileGDBDataSource::CreateGDBItemRelationshipTypes() bool OGROpenFileGDBDataSource::Create(const char *pszName) { - if (!EQUAL(CPLGetExtension(pszName), "gdb")) + if (!EQUAL(CPLGetExtensionSafe(pszName).c_str(), "gdb")) { CPLError(CE_Failure, CPLE_NotSupported, "Extension of the directory should be gdb"); @@ -1306,7 +1306,8 @@ bool OGROpenFileGDBDataSource::Create(const char *pszName) { // Write "gdb" file - const std::string osFilename(CPLFormFilename(pszName, "gdb", nullptr)); + const std::string osFilename( + CPLFormFilenameSafe(pszName, "gdb", nullptr)); VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "wb"); if (!fp) return false; @@ -1318,7 +1319,7 @@ bool OGROpenFileGDBDataSource::Create(const char *pszName) { // Write "timestamps" file const std::string osFilename( - CPLFormFilename(pszName, "timestamps", nullptr)); + CPLFormFilenameSafe(pszName, "timestamps", nullptr)); VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "wb"); if (!fp) return false; @@ -1364,7 +1365,7 @@ OGROpenFileGDBDataSource::ICreateLayer(const char *pszLayerName, const int nTableNum = static_cast(1 + oTable.GetTotalRecordCount()); oTable.Close(); - const std::string osFilename(CPLFormFilename( + const std::string osFilename(CPLFormFilenameSafe( m_osDirName.c_str(), CPLSPrintf("a%08x.gdbtable", nTableNum), nullptr)); if (wkbFlatten(eType) == wkbLineString) @@ -1494,9 +1495,10 @@ OGRErr OGROpenFileGDBDataSource::DeleteLayer(int iLayer) } } - const std::string osDirname = CPLGetPath(poLayer->GetFilename().c_str()); + const std::string osDirname = + CPLGetPathSafe(poLayer->GetFilename().c_str()); const std::string osFilenameBase = - CPLGetBasename(poLayer->GetFilename().c_str()); + CPLGetBasenameSafe(poLayer->GetFilename().c_str()); if (m_bInTransaction) { @@ -1524,7 +1526,9 @@ OGRErr OGROpenFileGDBDataSource::DeleteLayer(int iLayer) { if (STARTS_WITH(*papszIter, osFilenameBase.c_str())) { - VSIUnlink(CPLFormFilename(osDirname.c_str(), *papszIter, nullptr)); + VSIUnlink( + CPLFormFilenameSafe(osDirname.c_str(), *papszIter, nullptr) + .c_str()); } } CSLDestroy(papszFiles); @@ -2357,8 +2361,8 @@ OGRErr OGROpenFileGDBDataSource::StartTransaction(int bForce) return OGRERR_FAILURE; } - m_osTransactionBackupDirname = - CPLFormFilename(m_osDirName.c_str(), ".ogrtransaction_backup", nullptr); + m_osTransactionBackupDirname = CPLFormFilenameSafe( + m_osDirName.c_str(), ".ogrtransaction_backup", nullptr); VSIStatBufL sStat; if (VSIStatL(m_osTransactionBackupDirname.c_str(), &sStat) == 0) { @@ -2395,15 +2399,15 @@ bool OGROpenFileGDBDataSource::BackupSystemTablesForTransaction() for (char **papszIter = papszFiles; papszIter != nullptr && *papszIter != nullptr; ++papszIter) { - const std::string osBasename = CPLGetBasename(*papszIter); + const std::string osBasename = CPLGetBasenameSafe(*papszIter); if (osBasename.size() == strlen("a00000001") && osBasename.compare(0, 8, "a0000000") == 0 && osBasename[8] >= '1' && osBasename[8] <= '8') { - std::string osDestFilename = CPLFormFilename( + const std::string osDestFilename = CPLFormFilenameSafe( m_osTransactionBackupDirname.c_str(), *papszIter, nullptr); - std::string osSourceFilename = - CPLFormFilename(m_osDirName.c_str(), *papszIter, nullptr); + const std::string osSourceFilename = + CPLFormFilenameSafe(m_osDirName.c_str(), *papszIter, nullptr); if (CPLCopyFile(osDestFilename.c_str(), osSourceFilename.c_str()) != 0) { @@ -2471,14 +2475,14 @@ OGRErr OGROpenFileGDBDataSource::RollbackTransaction() for (char **papszIter = papszFiles; papszIter != nullptr && *papszIter != nullptr; ++papszIter) { - const std::string osBasename = CPLGetBasename(*papszIter); + const std::string osBasename = CPLGetBasenameSafe(*papszIter); if (osBasename.size() == strlen("a00000001") && osBasename.compare(0, 8, "a0000000") == 0 && osBasename[8] >= '1' && osBasename[8] <= '8') { - std::string osDestFilename = - CPLFormFilename(m_osDirName.c_str(), *papszIter, nullptr); - std::string osSourceFilename = CPLFormFilename( + const std::string osDestFilename = CPLFormFilenameSafe( + m_osDirName.c_str(), *papszIter, nullptr); + const std::string osSourceFilename = CPLFormFilenameSafe( m_osTransactionBackupDirname.c_str(), *papszIter, nullptr); if (CPLCopyFile(osDestFilename.c_str(), osSourceFilename.c_str()) != 0) @@ -2500,18 +2504,18 @@ OGRErr OGROpenFileGDBDataSource::RollbackTransaction() for (auto poLayer : m_oSetLayersCreatedInTransaction) { const std::string osThisBasename = - CPLGetBasename(poLayer->GetFilename().c_str()); + CPLGetBasenameSafe(poLayer->GetFilename().c_str()); poLayer->Close(); char **papszFiles = VSIReadDir(m_osDirName.c_str()); for (char **papszIter = papszFiles; papszIter != nullptr && *papszIter != nullptr; ++papszIter) { - const std::string osBasename = CPLGetBasename(*papszIter); + const std::string osBasename = CPLGetBasenameSafe(*papszIter); if (osBasename == osThisBasename) { - std::string osDestFilename = - CPLFormFilename(m_osDirName.c_str(), *papszIter, nullptr); + const std::string osDestFilename = CPLFormFilenameSafe( + m_osDirName.c_str(), *papszIter, nullptr); VSIUnlink(osDestFilename.c_str()); } } diff --git a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdriver.cpp b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdriver.cpp index 05c1c6c3b522..105632cccb28 100644 --- a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdriver.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdriver.cpp @@ -37,36 +37,10 @@ static GDALDataset *OGROpenFileGDBDriverOpen(GDALOpenInfo *poOpenInfo) { const char *pszFilename = poOpenInfo->pszFilename; -#ifdef FOR_FUSIL - CPLString osOrigFilename(pszFilename); -#endif if (OGROpenFileGDBDriverIdentify(poOpenInfo, pszFilename) == GDAL_IDENTIFY_FALSE) return nullptr; -#ifdef FOR_FUSIL - const char *pszSrcDir = CPLGetConfigOption("FUSIL_SRC_DIR", NULL); - if (pszSrcDir != NULL && VSIStatL(osOrigFilename, &stat) == 0 && - VSI_ISREG(stat.st_mode)) - { - /* Copy all files from FUSIL_SRC_DIR to directory of pszFilename */ - /* except pszFilename itself */ - CPLString osSave(pszFilename); - char **papszFiles = VSIReadDir(pszSrcDir); - for (int i = 0; papszFiles[i] != NULL; i++) - { - if (strcmp(papszFiles[i], CPLGetFilename(osOrigFilename)) != 0) - { - CPLCopyFile(CPLFormFilename(CPLGetPath(osOrigFilename), - papszFiles[i], NULL), - CPLFormFilename(pszSrcDir, papszFiles[i], NULL)); - } - } - CSLDestroy(papszFiles); - pszFilename = CPLFormFilename("", osSave.c_str(), NULL); - } -#endif - #ifdef DEBUG /* For AFL, so that .cur_input is detected as the archive filename */ if (poOpenInfo->fpL != nullptr && @@ -157,7 +131,7 @@ static CPLErr OGROpenFileGDBDriverDelete(const char *pszFilename) if (strcmp(aosFiles[i], ".") != 0 && strcmp(aosFiles[i], "..") != 0) { const std::string osFilename( - CPLFormFilename(pszFilename, aosFiles[i], nullptr)); + CPLFormFilenameSafe(pszFilename, aosFiles[i], nullptr)); if (VSIUnlink(osFilename.c_str()) != 0) { CPLError(CE_Failure, CPLE_FileIO, "Cannot delete %s", diff --git a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdrivercore.cpp b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdrivercore.cpp index bc294654d90a..f5c77358dc43 100644 --- a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdrivercore.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdbdrivercore.cpp @@ -27,11 +27,6 @@ GDALIdentifyEnum OGROpenFileGDBDriverIdentify(GDALOpenInfo *poOpenInfo, if (STARTS_WITH(pszFilename, "OpenFileGDB:")) return GDAL_IDENTIFY_TRUE; - // FUSIL is a fuzzer -#ifdef FOR_FUSIL - CPLString osOrigFilename(pszFilename); -#endif - // First check if we have to do any work. size_t nLen = strlen(pszFilename); if (ENDS_WITH(pszFilename, nLen, ".gdb") || @@ -49,7 +44,8 @@ GDALIdentifyEnum OGROpenFileGDBDriverIdentify(GDALOpenInfo *poOpenInfo, VSIStatBufL stat; if (!(STARTS_WITH(pszFilename, "/vsicurl/") && VSIStatL( - CPLFormFilename(pszFilename, "a00000001", "gdbtable"), + CPLFormFilenameSafe(pszFilename, "a00000001", "gdbtable") + .c_str(), &stat) == 0)) { return GDAL_IDENTIFY_FALSE; @@ -104,24 +100,6 @@ GDALIdentifyEnum OGROpenFileGDBDriverIdentify(GDALOpenInfo *poOpenInfo, { return GDAL_IDENTIFY_TRUE; } -#ifdef FOR_FUSIL - /* To be able to test fuzzer on any auxiliary files used (indexes, etc.) */ - else if (strlen(CPLGetBasename(pszFilename)) == 9 && - CPLGetBasename(pszFilename)[0] == 'a') - { - pszFilename = CPLFormFilename(CPLGetPath(pszFilename), - CPLGetBasename(pszFilename), "gdbtable"); - return GDAL_IDENTIFY_TRUE; - } - else if (strlen(CPLGetBasename(CPLGetBasename(pszFilename))) == 9 && - CPLGetBasename(CPLGetBasename(pszFilename))[0] == 'a') - { - pszFilename = CPLFormFilename( - CPLGetPath(pszFilename), - CPLGetBasename(CPLGetBasename(pszFilename)), "gdbtable"); - return GDAL_IDENTIFY_TRUE; - } -#endif #ifdef DEBUG /* For AFL, so that .cur_input is detected as the archive filename */ diff --git a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer_write.cpp b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer_write.cpp index e760d726f233..bf8a3d484b15 100644 --- a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer_write.cpp +++ b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer_write.cpp @@ -2944,19 +2944,20 @@ bool OGROpenFileGDBLayer::BeginEmulatedTransaction() bool bRet = true; - const std::string osThisDirname = CPLGetPath(m_osGDBFilename.c_str()); - const std::string osThisBasename = CPLGetBasename(m_osGDBFilename.c_str()); + const std::string osThisDirname = CPLGetPathSafe(m_osGDBFilename.c_str()); + const std::string osThisBasename = + CPLGetBasenameSafe(m_osGDBFilename.c_str()); char **papszFiles = VSIReadDir(osThisDirname.c_str()); for (char **papszIter = papszFiles; papszIter != nullptr && *papszIter != nullptr; ++papszIter) { - const std::string osBasename = CPLGetBasename(*papszIter); + const std::string osBasename = CPLGetBasenameSafe(*papszIter); if (osBasename == osThisBasename) { - std::string osDestFilename = CPLFormFilename( + const std::string osDestFilename = CPLFormFilenameSafe( m_poDS->GetBackupDirName().c_str(), *papszIter, nullptr); - std::string osSourceFilename = - CPLFormFilename(osThisDirname.c_str(), *papszIter, nullptr); + const std::string osSourceFilename = + CPLFormFilenameSafe(osThisDirname.c_str(), *papszIter, nullptr); if (CPLCopyFile(osDestFilename.c_str(), osSourceFilename.c_str()) != 0) { @@ -3019,8 +3020,9 @@ bool OGROpenFileGDBLayer::RollbackEmulatedTransaction() bool bRet = true; - const std::string osThisDirname = CPLGetPath(m_osGDBFilename.c_str()); - const std::string osThisBasename = CPLGetBasename(m_osGDBFilename.c_str()); + const std::string osThisDirname = CPLGetPathSafe(m_osGDBFilename.c_str()); + const std::string osThisBasename = + CPLGetBasenameSafe(m_osGDBFilename.c_str()); // Delete files in working directory that match our basename { @@ -3028,11 +3030,11 @@ bool OGROpenFileGDBLayer::RollbackEmulatedTransaction() for (char **papszIter = papszFiles; papszIter != nullptr && *papszIter != nullptr; ++papszIter) { - const std::string osBasename = CPLGetBasename(*papszIter); + const std::string osBasename = CPLGetBasenameSafe(*papszIter); if (osBasename == osThisBasename) { - std::string osDestFilename = - CPLFormFilename(osThisDirname.c_str(), *papszIter, nullptr); + const std::string osDestFilename = CPLFormFilenameSafe( + osThisDirname.c_str(), *papszIter, nullptr); VSIUnlink(osDestFilename.c_str()); } } @@ -3046,13 +3048,13 @@ bool OGROpenFileGDBLayer::RollbackEmulatedTransaction() for (char **papszIter = papszFiles; papszIter != nullptr && *papszIter != nullptr; ++papszIter) { - const std::string osBasename = CPLGetBasename(*papszIter); + const std::string osBasename = CPLGetBasenameSafe(*papszIter); if (osBasename == osThisBasename) { bBackupFound = true; - std::string osDestFilename = - CPLFormFilename(osThisDirname.c_str(), *papszIter, nullptr); - std::string osSourceFilename = CPLFormFilename( + const std::string osDestFilename = CPLFormFilenameSafe( + osThisDirname.c_str(), *papszIter, nullptr); + const std::string osSourceFilename = CPLFormFilenameSafe( m_poDS->GetBackupDirName().c_str(), *papszIter, nullptr); if (CPLCopyFile(osDestFilename.c_str(), osSourceFilename.c_str()) != 0) diff --git a/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp b/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp index f8ca69fb883a..4f05a40d5c69 100644 --- a/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp +++ b/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp @@ -2896,7 +2896,7 @@ int OGROSMDataSource::Open(const char *pszFilename, VSIUnlink(m_osNodesFilename); m_bInMemoryNodesFile = false; - m_osNodesFilename = CPLGenerateTempFilename("osm_tmp_nodes"); + m_osNodesFilename = CPLGenerateTempFilenameSafe("osm_tmp_nodes"); m_fpNodes = VSIFOpenL(m_osNodesFilename, "wb+"); if (m_fpNodes == nullptr) @@ -3000,7 +3000,7 @@ bool OGROSMDataSource::CreateTempDB() if (!bSuccess) { - m_osTmpDBName = CPLGenerateTempFilename("osm_tmp"); + m_osTmpDBName = CPLGenerateTempFilenameSafe("osm_tmp"); rc = sqlite3_open(m_osTmpDBName.c_str(), &m_hDB); /* On Unix filesystems, you can remove a file even if it */ @@ -4072,7 +4072,7 @@ bool OGROSMDataSource::TransferToDiskIfNecesserary() m_fpNodes = nullptr; const std::string osNewTmpDBName( - CPLGenerateTempFilename("osm_tmp_nodes")); + CPLGenerateTempFilenameSafe("osm_tmp_nodes")); CPLDebug("OSM", "%s too big for RAM. Transferring it onto disk in %s", @@ -4153,7 +4153,7 @@ bool OGROSMDataSource::TransferToDiskIfNecesserary() CloseDB(); const std::string osNewTmpDBName( - CPLGenerateTempFilename("osm_tmp")); + CPLGenerateTempFilenameSafe("osm_tmp")); CPLDebug("OSM", "%s too big for RAM. Transferring it onto disk in %s", diff --git a/ogr/ogrsf_frmts/parquet/ogrparquetdriver.cpp b/ogr/ogrsf_frmts/parquet/ogrparquetdriver.cpp index 2cf4524baab2..5e22d7614dbd 100644 --- a/ogr/ogrsf_frmts/parquet/ogrparquetdriver.cpp +++ b/ogr/ogrsf_frmts/parquet/ogrparquetdriver.cpp @@ -47,8 +47,8 @@ static GDALDataset *OpenFromDatasetFactory( const bool bIsVSI = STARTS_WITH(osBasePath.c_str(), "/vsi"); auto poDS = std::make_unique(poMemoryPool); auto poLayer = std::make_unique( - poDS.get(), CPLGetBasename(osBasePath.c_str()), bIsVSI, dataset, - papszOpenOptions); + poDS.get(), CPLGetBasenameSafe(osBasePath.c_str()).c_str(), bIsVSI, + dataset, papszOpenOptions); poDS->SetLayer(std::move(poLayer)); poDS->SetFileSystem(fs); return poDS.release(); @@ -86,7 +86,7 @@ GetFileSystem(std::string &osBasePathInOut, char *pszCurDir = CPLGetCurrentDir(); if (pszCurDir == nullptr) return {nullptr, osFSFilename}; - osPath = CPLFormFilename(pszCurDir, osPath.c_str(), nullptr); + osPath = CPLFormFilenameSafe(pszCurDir, osPath.c_str(), nullptr); CPLFree(pszCurDir); } PARQUET_ASSIGN_OR_THROW( @@ -331,8 +331,8 @@ static GDALDataset *OGRParquetDriverOpen(GDALOpenInfo *poOpenInfo) VSIStatBufL sStat; if (!osBasePath.empty() && osBasePath.back() == '/') osBasePath.pop_back(); - std::string osMetadataPath = - CPLFormFilename(osBasePath.c_str(), "_metadata", nullptr); + const std::string osMetadataPath = + CPLFormFilenameSafe(osBasePath.c_str(), "_metadata", nullptr); if (CPLTestBool( CPLGetConfigOption("OGR_PARQUET_USE_METADATA_FILE", "YES")) && VSIStatL((osMetadataPath + osQueryParameters).c_str(), &sStat) == 0) @@ -362,7 +362,8 @@ static GDALDataset *OGRParquetDriverOpen(GDALOpenInfo *poOpenInfo) const CPLStringList aosFiles(VSIReadDir(osBasePath.c_str())); for (const char *pszFilename : cpl::Iterate(aosFiles)) { - if (EQUAL(CPLGetExtension(pszFilename), "parquet")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), + "parquet")) { bLikelyParquetDataset = true; break; @@ -370,8 +371,9 @@ static GDALDataset *OGRParquetDriverOpen(GDALOpenInfo *poOpenInfo) else if (strchr(pszFilename, '=')) { // HIVE partitioning - if (VSIStatL(CPLFormFilename(osBasePath.c_str(), - pszFilename, nullptr), + if (VSIStatL(CPLFormFilenameSafe(osBasePath.c_str(), + pszFilename, nullptr) + .c_str(), &sStat) == 0 && VSI_ISDIR(sStat.st_mode)) { @@ -464,7 +466,7 @@ static GDALDataset *OGRParquetDriverOpen(GDALOpenInfo *poOpenInfo) auto poDS = std::make_unique(poMemoryPool); auto poLayer = std::make_unique( - poDS.get(), CPLGetBasename(osFilename.c_str()), + poDS.get(), CPLGetBasenameSafe(osFilename.c_str()).c_str(), std::move(arrow_reader), poOpenInfo->papszOpenOptions); // For debug purposes: return a layer with the extent of each row group diff --git a/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp b/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp index 3d7dbf2cd197..0a39e4ddcf28 100644 --- a/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp +++ b/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp @@ -146,9 +146,10 @@ bool OGRPDSDataSource::LoadTable(const char *pszFilename, int nRecordSize, osTableLink.c_str()); return false; } - CPLString osTPath = CPLGetPath(pszFilename); + CPLString osTPath = CPLGetPathSafe(pszFilename); CleanString(osTableFilename); - osTableFilename = CPLFormCIFilename(osTPath, osTableFilename, nullptr); + osTableFilename = + CPLFormCIFilenameSafe(osTPath, osTableFilename, nullptr); } else { @@ -178,10 +179,10 @@ bool OGRPDSDataSource::LoadTable(const char *pszFilename, int nRecordSize, } else { - CPLString osTPath = CPLGetPath(pszFilename); + CPLString osTPath = CPLGetPathSafe(pszFilename); CleanString(osTableFilename); osTableFilename = - CPLFormCIFilename(osTPath, osTableFilename, nullptr); + CPLFormCIFilenameSafe(osTPath, osTableFilename, nullptr); nStartBytes = 0; } } @@ -229,10 +230,10 @@ bool OGRPDSDataSource::LoadTable(const char *pszFilename, int nRecordSize, oKeywords.GetKeyword(MakeAttr(osTableID, "^STRUCTURE"), ""); if (!osTableStructure.empty()) { - CPLString osTPath = CPLGetPath(pszFilename); + CPLString osTPath = CPLGetPathSafe(pszFilename); CleanString(osTableStructure); osTableStructure = - CPLFormCIFilename(osTPath, osTableStructure, nullptr); + CPLFormCIFilenameSafe(osTPath, osTableStructure, nullptr); } GByte *pabyRecord = (GByte *)VSI_MALLOC_VERBOSE(nRecordSize + 1); diff --git a/ogr/ogrsf_frmts/pgeo/ogrpgeodriver.cpp b/ogr/ogrsf_frmts/pgeo/ogrpgeodriver.cpp index 6fd8f9b0bf13..419f2f98f3e3 100644 --- a/ogr/ogrsf_frmts/pgeo/ogrpgeodriver.cpp +++ b/ogr/ogrsf_frmts/pgeo/ogrpgeodriver.cpp @@ -24,7 +24,7 @@ static int OGRPGeoDriverIdentify(GDALOpenInfo *poOpenInfo) if (STARTS_WITH_CI(poOpenInfo->pszFilename, "PGEO:")) return TRUE; - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "mdb")) + if (!poOpenInfo->IsExtensionEqualToCI("mdb")) return FALSE; // Could potentially be a PGeo or generic ODBC database diff --git a/ogr/ogrsf_frmts/pmtiles/ogrpmtilesfrommbtiles.cpp b/ogr/ogrsf_frmts/pmtiles/ogrpmtilesfrommbtiles.cpp index 48eb19e9d846..c56b24a9b3cf 100644 --- a/ogr/ogrsf_frmts/pmtiles/ogrpmtilesfrommbtiles.cpp +++ b/ogr/ogrsf_frmts/pmtiles/ogrpmtilesfrommbtiles.cpp @@ -330,7 +330,7 @@ bool OGRPMTilesConvertFromMBTiles(const char *pszDestName, std::string osTmpFile(std::string(pszDestName) + ".tmp"); if (!VSIIsLocal(pszDestName)) { - osTmpFile = CPLGenerateTempFilename(CPLGetFilename(pszDestName)); + osTmpFile = CPLGenerateTempFilenameSafe(CPLGetFilename(pszDestName)); } auto poTmpFile = diff --git a/ogr/ogrsf_frmts/pmtiles/ogrpmtileswriterdataset.cpp b/ogr/ogrsf_frmts/pmtiles/ogrpmtileswriterdataset.cpp index 9267ccb39fef..6edf8ac521e8 100644 --- a/ogr/ogrsf_frmts/pmtiles/ogrpmtileswriterdataset.cpp +++ b/ogr/ogrsf_frmts/pmtiles/ogrpmtileswriterdataset.cpp @@ -79,12 +79,13 @@ bool OGRPMTilesWriterDataset::Create(const char *pszFilename, std::string osTmpFile(pszFilename); if (!VSIIsLocal(pszFilename)) { - osTmpFile = CPLGenerateTempFilename(CPLGetFilename(pszFilename)); + osTmpFile = CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)); } osTmpFile += ".tmp.mbtiles"; if (!aosOptions.FetchNameValue("NAME")) - aosOptions.SetNameValue("NAME", CPLGetBasename(pszFilename)); + aosOptions.SetNameValue("NAME", + CPLGetBasenameSafe(pszFilename).c_str()); m_poMBTilesWriterDataset.reset(OGRMVTWriterDatasetCreate( osTmpFile.c_str(), 0, 0, 0, GDT_Unknown, aosOptions.List())); diff --git a/ogr/ogrsf_frmts/s57/s57classregistrar.cpp b/ogr/ogrsf_frmts/s57/s57classregistrar.cpp index 18f66cc04fec..739789063bce 100644 --- a/ogr/ogrsf_frmts/s57/s57classregistrar.cpp +++ b/ogr/ogrsf_frmts/s57/s57classregistrar.cpp @@ -79,20 +79,21 @@ bool S57ClassRegistrar::FindFile(const char *pszTarget, VSILFILE **pfp) { - const char *pszFilename = nullptr; + std::string osFilename; *pfp = nullptr; if (pszDirectory == nullptr) { #if defined(USE_ONLY_EMBEDDED_RESOURCE_FILES) - pszFilename = pszTarget; + const char *pszFilename = pszTarget; #else - pszFilename = CPLFindFile("s57", pszTarget); + const char *pszFilename = CPLFindFile("s57", pszTarget); if (pszFilename == nullptr) pszFilename = pszTarget; #endif - if (EQUAL(pszFilename, pszTarget)) + osFilename = pszFilename; + if (EQUAL(osFilename.c_str(), pszTarget)) { #ifdef EMBED_RESOURCE_FILES const char *pszContent = S57GetEmbeddedCSV(pszTarget); @@ -111,21 +112,21 @@ bool S57ClassRegistrar::FindFile(const char *pszTarget, } else { - pszFilename = CPLFormFilename(pszDirectory, pszTarget, nullptr); + osFilename = CPLFormFilenameSafe(pszDirectory, pszTarget, nullptr); } #ifdef EMBED_RESOURCE_FILES if (!(*pfp)) #endif { - *pfp = VSIFOpenL(pszFilename, "rb"); + *pfp = VSIFOpenL(osFilename.c_str(), "rb"); } if (*pfp == nullptr) { if (bReportErr) CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open %s.\n", - pszFilename); + osFilename.c_str()); return FALSE; } diff --git a/ogr/ogrsf_frmts/s57/s57filecollector.cpp b/ogr/ogrsf_frmts/s57/s57filecollector.cpp index ab56a7b1b5c9..fa856af2a6ef 100644 --- a/ogr/ogrsf_frmts/s57/s57filecollector.cpp +++ b/ogr/ogrsf_frmts/s57/s57filecollector.cpp @@ -52,7 +52,8 @@ char **S57FileCollector(const char *pszDataset) iFile++) { char *pszFullFile = CPLStrdup( - CPLFormFilename(pszDataset, papszDirFiles[iFile], nullptr)); + CPLFormFilenameSafe(pszDataset, papszDirFiles[iFile], nullptr) + .c_str()); // Add to list if it is an S-57 _data_ file. if (VSIStat(pszFullFile, &sStatBuf) == 0 && @@ -100,20 +101,23 @@ char **S57FileCollector(const char *pszDataset) /* correct name for the ENC_ROOT directory if available and */ /* build a base path for our purposes. */ /* -------------------------------------------------------------------- */ - char *pszCatDir = CPLStrdup(CPLGetPath(pszDataset)); + char *pszCatDir = CPLStrdup(CPLGetPathSafe(pszDataset).c_str()); char *pszRootDir = nullptr; - if (CPLStat(CPLFormFilename(pszCatDir, "ENC_ROOT", nullptr), &sStatBuf) == - 0 && + if (CPLStat(CPLFormFilenameSafe(pszCatDir, "ENC_ROOT", nullptr).c_str(), + &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode)) { - pszRootDir = CPLStrdup(CPLFormFilename(pszCatDir, "ENC_ROOT", nullptr)); + pszRootDir = CPLStrdup( + CPLFormFilenameSafe(pszCatDir, "ENC_ROOT", nullptr).c_str()); } - else if (CPLStat(CPLFormFilename(pszCatDir, "enc_root", nullptr), - &sStatBuf) == 0 && + else if (CPLStat( + CPLFormFilenameSafe(pszCatDir, "enc_root", nullptr).c_str(), + &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode)) { - pszRootDir = CPLStrdup(CPLFormFilename(pszCatDir, "enc_root", nullptr)); + pszRootDir = CPLStrdup( + CPLFormFilenameSafe(pszCatDir, "enc_root", nullptr).c_str()); } if (pszRootDir) @@ -135,14 +139,15 @@ char **S57FileCollector(const char *pszDataset) // Often there is an extra ENC_ROOT in the path, try finding // this file. - const char *pszWholePath = - CPLFormFilename(pszCatDir, pszFile, nullptr); - if (CPLStat(pszWholePath, &sStatBuf) != 0 && pszRootDir != nullptr) + std::string osWholePath = + CPLFormFilenameSafe(pszCatDir, pszFile, nullptr); + if (CPLStat(osWholePath.c_str(), &sStatBuf) != 0 && + pszRootDir != nullptr) { - pszWholePath = CPLFormFilename(pszRootDir, pszFile, nullptr); + osWholePath = CPLFormFilenameSafe(pszRootDir, pszFile, nullptr); } - if (CPLStat(pszWholePath, &sStatBuf) != 0) + if (CPLStat(osWholePath.c_str(), &sStatBuf) != 0) { CPLError(CE_Warning, CPLE_OpenFailed, "Can't find file %s from catalog %s.", pszFile, @@ -150,8 +155,8 @@ char **S57FileCollector(const char *pszDataset) continue; } - papszRetList = CSLAddString(papszRetList, pszWholePath); - CPLDebug("S57", "Got path %s from CATALOG.", pszWholePath); + papszRetList = CSLAddString(papszRetList, osWholePath.c_str()); + CPLDebug("S57", "Got path %s from CATALOG.", osWholePath.c_str()); } } diff --git a/ogr/ogrsf_frmts/s57/s57reader.cpp b/ogr/ogrsf_frmts/s57/s57reader.cpp index e1be6cbdf48d..d80a151ebf6a 100644 --- a/ogr/ogrsf_frmts/s57/s57reader.cpp +++ b/ogr/ogrsf_frmts/s57/s57reader.cpp @@ -3369,7 +3369,7 @@ bool S57Reader::FindAndApplyUpdates(const char *pszPath) if (pszPath == nullptr) pszPath = pszModuleName; - if (!EQUAL(CPLGetExtension(pszPath), "000")) + if (!EQUAL(CPLGetExtensionSafe(pszPath).c_str(), "000")) { CPLError(CE_Failure, CPLE_AppDefined, "Can't apply updates to a base file with a different\n" @@ -3412,8 +3412,8 @@ bool S57Reader::FindAndApplyUpdates(const char *pszPath) DDFModule oUpdateModule; // trying current dir first - char *pszUpdateFilename = - CPLStrdup(CPLResetExtension(pszPath, extension.c_str())); + char *pszUpdateFilename = CPLStrdup( + CPLResetExtensionSafe(pszPath, extension.c_str()).c_str()); VSILFILE *file = VSIFOpenL(pszUpdateFilename, "r"); if (file) @@ -3430,14 +3430,16 @@ bool S57Reader::FindAndApplyUpdates(const char *pszPath) } else // File is store on Primar generated CD. { - char *pszBaseFileDir = CPLStrdup(CPLGetDirname(pszPath)); - char *pszFileDir = CPLStrdup(CPLGetDirname(pszBaseFileDir)); + char *pszBaseFileDir = + CPLStrdup(CPLGetDirnameSafe(pszPath).c_str()); + char *pszFileDir = + CPLStrdup(CPLGetDirnameSafe(pszBaseFileDir).c_str()); CPLString remotefile(pszFileDir); remotefile.append("/"); remotefile.append(dirname); remotefile.append("/"); - remotefile.append(CPLGetBasename(pszPath)); + remotefile.append(CPLGetBasenameSafe(pszPath).c_str()); remotefile.append("."); remotefile.append(extension); bSuccess = diff --git a/ogr/ogrsf_frmts/sdts/ogrsdtsdriver.cpp b/ogr/ogrsf_frmts/sdts/ogrsdtsdriver.cpp index 37a186f4c435..a1b4b522ccbf 100644 --- a/ogr/ogrsf_frmts/sdts/ogrsdtsdriver.cpp +++ b/ogr/ogrsf_frmts/sdts/ogrsdtsdriver.cpp @@ -20,7 +20,7 @@ static GDALDataset *OGRSDTSDriverOpen(GDALOpenInfo *poOpenInfo) { - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "DDF")) + if (!poOpenInfo->IsExtensionEqualToCI("DDF")) return nullptr; if (poOpenInfo->nHeaderBytes < 10) return nullptr; diff --git a/ogr/ogrsf_frmts/selafin/ogrselafindatasource.cpp b/ogr/ogrsf_frmts/selafin/ogrselafindatasource.cpp index 510cffbc5d29..f33dab842680 100644 --- a/ogr/ogrsf_frmts/selafin/ogrselafindatasource.cpp +++ b/ogr/ogrsf_frmts/selafin/ogrselafindatasource.cpp @@ -373,7 +373,7 @@ int OGRSelafinDataSource::Open(const char *pszFilename, int bUpdateIn, CSLDestroy(papszFiles); return FALSE; } - osFilename = CPLFormFilename(osFilename, papszFiles[0], nullptr); + osFilename = CPLFormFilenameSafe(osFilename, papszFiles[0], nullptr); CSLDestroy(papszFiles); return OpenTable(osFilename); } @@ -388,8 +388,8 @@ int OGRSelafinDataSource::Open(const char *pszFilename, int bUpdateIn, char **papszNames = VSIReadDir(osFilename); for (i = 0; papszNames != NULL && papszNames[i] != NULL; i++) { - CPLString oSubFilename = - CPLFormFilename(osFilename, papszNames[i], NULL); + const CPLString oSubFilename = + CPLFormFilenameSafe(osFilename, papszNames[i], NULL); if (EQUAL(papszNames[i], ".") || EQUAL(papszNames[i], "..")) continue; if (VSIStatL(oSubFilename, &sStatBuf) != 0 || @@ -469,7 +469,7 @@ int OGRSelafinDataSource::OpenTable(const char *pszFilename) } */ // Get layer base name - CPLString osBaseLayerName = CPLGetBasename(pszFilename); + CPLString osBaseLayerName = CPLGetBasenameSafe(pszFilename); // Read header of file to get common information for all layers // poHeader now owns fp diff --git a/ogr/ogrsf_frmts/selafin/ogrselafinlayer.cpp b/ogr/ogrsf_frmts/selafin/ogrselafinlayer.cpp index 9405099772fc..0e1e30bb1689 100644 --- a/ogr/ogrsf_frmts/selafin/ogrselafinlayer.cpp +++ b/ogr/ogrsf_frmts/selafin/ogrselafinlayer.cpp @@ -51,7 +51,8 @@ OGRSelafinLayer::OGRSelafinLayer(GDALDataset *poDS, const char *pszLayerNameP, SelafinTypeDef eTypeP) : m_poDS(poDS), eType(eTypeP), bUpdate(CPL_TO_BOOL(bUpdateP)), nStepNumber(nStepNumberP), poHeader(poHeaderP), - poFeatureDefn(new OGRFeatureDefn(CPLGetBasename(pszLayerNameP))), + poFeatureDefn( + new OGRFeatureDefn(CPLGetBasenameSafe(pszLayerNameP).c_str())), poSpatialRef(nullptr), nCurrentId(-1) { #ifdef DEBUG_VERBOSE @@ -595,19 +596,19 @@ OGRErr OGRSelafinLayer::ICreateFeature(OGRFeature *poFeature) // Now comes the real insertion. Since values have to be inserted nearly // everywhere in the file and we don't want to store everything in memory to // overwrite it, we create a new copy of it where we write the new values - const char *pszTempfile = CPLGenerateTempFilename(nullptr); - VSILFILE *fpNew = VSIFOpenL(pszTempfile, "wb+"); + const std::string osTempfile = CPLGenerateTempFilenameSafe(nullptr); + VSILFILE *fpNew = VSIFOpenL(osTempfile.c_str(), "wb+"); if (fpNew == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open temporary file %s with write access, %s.", - pszTempfile, VSIStrerror(errno)); + osTempfile.c_str(), VSIStrerror(errno)); return OGRERR_FAILURE; } if (Selafin::write_header(fpNew, poHeader) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int i = 0; i < poHeader->nSteps; ++i) @@ -622,7 +623,7 @@ OGRErr OGRSelafinLayer::ICreateFeature(OGRFeature *poFeature) Selafin::write_integer(fpNew, 4) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int j = 0; j < poHeader->nVar; ++j) @@ -632,7 +633,7 @@ OGRErr OGRSelafinLayer::ICreateFeature(OGRFeature *poFeature) poHeader->nFileSize) == -1) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } padfValues = (double *)CPLRealloc( @@ -640,7 +641,7 @@ OGRErr OGRSelafinLayer::ICreateFeature(OGRFeature *poFeature) if (padfValues == nullptr) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } if (eType == POINTS) @@ -653,7 +654,7 @@ OGRErr OGRSelafinLayer::ICreateFeature(OGRFeature *poFeature) { CPLFree(padfValues); VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } CPLFree(padfValues); @@ -664,7 +665,7 @@ OGRErr OGRSelafinLayer::ICreateFeature(OGRFeature *poFeature) // the old one. This way, even if something goes bad, we can still recover // the layer. The copy process is format-agnostic. MoveOverwrite(poHeader->fp, fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); poHeader->UpdateFileSize(); return OGRERR_NONE; } @@ -721,19 +722,19 @@ OGRErr OGRSelafinLayer::CreateField(const OGRFieldDefn *poField, // Now comes the real insertion. Since values have to be inserted nearly // everywhere in the file and we don't want to store everything in memory to // overwrite it, we create a new copy of it where we write the new values - const char *pszTempfile = CPLGenerateTempFilename(nullptr); - VSILFILE *fpNew = VSIFOpenL(pszTempfile, "wb+"); + const std::string osTempfile = CPLGenerateTempFilenameSafe(nullptr); + VSILFILE *fpNew = VSIFOpenL(osTempfile.c_str(), "wb+"); if (fpNew == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open temporary file %s with write access, %s.", - pszTempfile, VSIStrerror(errno)); + osTempfile.c_str(), VSIStrerror(errno)); return OGRERR_FAILURE; } if (Selafin::write_header(fpNew, poHeader) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int i = 0; i < poHeader->nSteps; ++i) @@ -748,7 +749,7 @@ OGRErr OGRSelafinLayer::CreateField(const OGRFieldDefn *poField, Selafin::write_integer(fpNew, 4) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } double *padfValues = nullptr; @@ -758,7 +759,7 @@ OGRErr OGRSelafinLayer::CreateField(const OGRFieldDefn *poField, poHeader->nFileSize) == -1) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } if (Selafin::write_floatarray(fpNew, padfValues, @@ -766,7 +767,7 @@ OGRErr OGRSelafinLayer::CreateField(const OGRFieldDefn *poField, { CPLFree(padfValues); VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } CPLFree(padfValues); @@ -780,13 +781,13 @@ OGRErr OGRSelafinLayer::CreateField(const OGRFieldDefn *poField, { CPLFree(padfValues); VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } CPLFree(padfValues); } MoveOverwrite(poHeader->fp, fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); poHeader->UpdateFileSize(); return OGRERR_NONE; } @@ -812,19 +813,19 @@ OGRErr OGRSelafinLayer::DeleteField(int iField) // Now comes the real deletion. Since values have to be deleted nearly // everywhere in the file and we don't want to store everything in memory to // overwrite it, we create a new copy of it where we write the new values - const char *pszTempfile = CPLGenerateTempFilename(nullptr); - VSILFILE *fpNew = VSIFOpenL(pszTempfile, "wb+"); + const std::string osTempfile = CPLGenerateTempFilenameSafe(nullptr); + VSILFILE *fpNew = VSIFOpenL(osTempfile.c_str(), "wb+"); if (fpNew == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open temporary file %s with write access, %s.", - pszTempfile, VSIStrerror(errno)); + osTempfile.c_str(), VSIStrerror(errno)); return OGRERR_FAILURE; } if (Selafin::write_header(fpNew, poHeader) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int i = 0; i < poHeader->nSteps; ++i) @@ -839,7 +840,7 @@ OGRErr OGRSelafinLayer::DeleteField(int iField) Selafin::write_integer(fpNew, 4) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int j = 0; j < poHeader->nVar; ++j) @@ -849,7 +850,7 @@ OGRErr OGRSelafinLayer::DeleteField(int iField) poHeader->nFileSize) == -1) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } if (j != iField) @@ -859,7 +860,7 @@ OGRErr OGRSelafinLayer::DeleteField(int iField) { CPLFree(padfValues); VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } } @@ -867,7 +868,7 @@ OGRErr OGRSelafinLayer::DeleteField(int iField) } } MoveOverwrite(poHeader->fp, fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); poHeader->UpdateFileSize(); return OGRERR_NONE; } @@ -890,19 +891,19 @@ OGRErr OGRSelafinLayer::ReorderFields(int *panMap) poFeatureDefn->ReorderFieldDefns(panMap); // Now comes the real change. - const char *pszTempfile = CPLGenerateTempFilename(nullptr); - VSILFILE *fpNew = VSIFOpenL(pszTempfile, "wb+"); + const std::string osTempfile = CPLGenerateTempFilenameSafe(nullptr); + VSILFILE *fpNew = VSIFOpenL(osTempfile.c_str(), "wb+"); if (fpNew == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open temporary file %s with write access, %s.", - pszTempfile, VSIStrerror(errno)); + osTempfile.c_str(), VSIStrerror(errno)); return OGRERR_FAILURE; } if (Selafin::write_header(fpNew, poHeader) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } double *padfValues = nullptr; @@ -918,7 +919,7 @@ OGRErr OGRSelafinLayer::ReorderFields(int *panMap) Selafin::write_integer(fpNew, 4) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int j = 0; j < poHeader->nVar; ++j) @@ -929,7 +930,7 @@ OGRErr OGRSelafinLayer::ReorderFields(int *panMap) poHeader->nFileSize) == -1) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } if (Selafin::write_floatarray(fpNew, padfValues, @@ -937,14 +938,14 @@ OGRErr OGRSelafinLayer::ReorderFields(int *panMap) { CPLFree(padfValues); VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } CPLFree(padfValues); } } MoveOverwrite(poHeader->fp, fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); poHeader->UpdateFileSize(); return OGRERR_NONE; } @@ -1015,19 +1016,19 @@ OGRErr OGRSelafinLayer::DeleteFeature(GIntBig nFID) } // Now we perform the deletion by creating a new temporary layer - const char *pszTempfile = CPLGenerateTempFilename(nullptr); - VSILFILE *fpNew = VSIFOpenL(pszTempfile, "wb+"); + const std::string osTempfile = CPLGenerateTempFilenameSafe(nullptr); + VSILFILE *fpNew = VSIFOpenL(osTempfile.c_str(), "wb+"); if (fpNew == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open temporary file %s with write access, %s.", - pszTempfile, VSIStrerror(errno)); + osTempfile.c_str(), VSIStrerror(errno)); return OGRERR_FAILURE; } if (Selafin::write_header(fpNew, poHeader) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int i = 0; i < poHeader->nSteps; ++i) @@ -1042,7 +1043,7 @@ OGRErr OGRSelafinLayer::DeleteFeature(GIntBig nFID) Selafin::write_integer(fpNew, 4) == 0) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } for (int j = 0; j < poHeader->nVar; ++j) @@ -1052,7 +1053,7 @@ OGRErr OGRSelafinLayer::DeleteFeature(GIntBig nFID) poHeader->nFileSize) == -1) { VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } if (eType == POINTS) @@ -1065,7 +1066,7 @@ OGRErr OGRSelafinLayer::DeleteFeature(GIntBig nFID) { CPLFree(padfValues); VSIFCloseL(fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); return OGRERR_FAILURE; } CPLFree(padfValues); @@ -1076,7 +1077,7 @@ OGRErr OGRSelafinLayer::DeleteFeature(GIntBig nFID) // the old one. This way, even if something goes bad, we can still recover // the layer. The copy process is format-agnostic. MoveOverwrite(poHeader->fp, fpNew); - VSIUnlink(pszTempfile); + VSIUnlink(osTempfile.c_str()); poHeader->UpdateFileSize(); return OGRERR_NONE; diff --git a/ogr/ogrsf_frmts/shape/ogrshapedatasource.cpp b/ogr/ogrsf_frmts/shape/ogrshapedatasource.cpp index 1fc8b36710d4..aff25906c179 100644 --- a/ogr/ogrsf_frmts/shape/ogrshapedatasource.cpp +++ b/ogr/ogrsf_frmts/shape/ogrshapedatasource.cpp @@ -155,7 +155,8 @@ bool OGRShapeDataSource::OpenZip(GDALOpenInfo *poOpenInfo, SetDescription(pszOriFilename); m_bIsZip = true; - m_bSingleLayerZip = EQUAL(CPLGetExtension(pszOriFilename), "shz"); + m_bSingleLayerZip = + EQUAL(CPLGetExtensionSafe(pszOriFilename).c_str(), "shz"); if (!m_bSingleLayerZip) { @@ -188,7 +189,8 @@ bool OGRShapeDataSource::CreateZip(const char *pszOriFilename) return false; eAccess = GA_Update; m_bIsZip = true; - m_bSingleLayerZip = EQUAL(CPLGetExtension(pszOriFilename), "shz"); + m_bSingleLayerZip = + EQUAL(CPLGetExtensionSafe(pszOriFilename).c_str(), "shz"); return true; } @@ -266,8 +268,7 @@ bool OGRShapeDataSource::Open(GDALOpenInfo *poOpenInfo, bool bTestOpen, for (int iCan = 0; iCan < nCandidateCount; iCan++) { const char *pszCandidate = papszCandidates[iCan]; - const char *pszLayerName = CPLGetBasename(pszCandidate); - CPLString osLayerName(pszLayerName); + CPLString osLayerName(CPLGetBasenameSafe(pszCandidate)); #ifdef _WIN32 // On Windows, as filenames are case insensitive, a shapefile layer // can be made of foo.shp and FOO.DBF, so to detect unique layer @@ -282,8 +283,8 @@ bool OGRShapeDataSource::Open(GDALOpenInfo *poOpenInfo, bool bTestOpen, !EQUAL(pszCandidate + strlen(pszCandidate) - 4, ".shp")) continue; - char *pszFilename = - CPLStrdup(CPLFormFilename(pszNewName, pszCandidate, nullptr)); + char *pszFilename = CPLStrdup( + CPLFormFilenameSafe(pszNewName, pszCandidate, nullptr).c_str()); osLayerNameSet.insert(osLayerName); #ifdef IMMEDIATE_OPENING @@ -308,8 +309,8 @@ bool OGRShapeDataSource::Open(GDALOpenInfo *poOpenInfo, bool bTestOpen, for (int iCan = 0; iCan < nCandidateCount; iCan++) { const char *pszCandidate = papszCandidates[iCan]; - const char *pszLayerName = CPLGetBasename(pszCandidate); - CPLString osLayerName(pszLayerName); + const std::string osLayerNameOri = CPLGetBasenameSafe(pszCandidate); + CPLString osLayerName(osLayerNameOri); #ifdef _WIN32 osLayerName.toupper(); #endif @@ -334,16 +335,17 @@ bool OGRShapeDataSource::Open(GDALOpenInfo *poOpenInfo, bool bTestOpen, { const char *pszCandidate2 = papszCandidates[iCan2]; - if (EQUALN(pszCandidate2, pszLayerName, strlen(pszLayerName)) && - EQUAL(pszCandidate2 + strlen(pszLayerName), ".tab")) + if (EQUALN(pszCandidate2, osLayerNameOri.c_str(), + osLayerNameOri.size()) && + EQUAL(pszCandidate2 + osLayerNameOri.size(), ".tab")) bFoundTAB = true; } if (bFoundTAB) continue; - char *pszFilename = - CPLStrdup(CPLFormFilename(pszNewName, pszCandidate, nullptr)); + char *pszFilename = CPLStrdup( + CPLFormFilenameSafe(pszNewName, pszCandidate, nullptr).c_str()); osLayerNameSet.insert(osLayerName); @@ -386,10 +388,11 @@ bool OGRShapeDataSource::Open(GDALOpenInfo *poOpenInfo, bool bTestOpen, bool OGRShapeDataSource::OpenFile(const char *pszNewName, bool bUpdate) { - const char *pszExtension = CPLGetExtension(pszNewName); + const std::string osExtension = CPLGetExtensionSafe(pszNewName); - if (!EQUAL(pszExtension, "shp") && !EQUAL(pszExtension, "shx") && - !EQUAL(pszExtension, "dbf")) + if (!EQUAL(osExtension.c_str(), "shp") && + !EQUAL(osExtension.c_str(), "shx") && + !EQUAL(osExtension.c_str(), "dbf")) return false; /* -------------------------------------------------------------------- */ @@ -412,7 +415,7 @@ bool OGRShapeDataSource::OpenFile(const char *pszNewName, bool bUpdate) const bool bRestoreSHX = CPLTestBool(CPLGetConfigOption("SHAPE_RESTORE_SHX", "FALSE")); - if (bRestoreSHX && EQUAL(CPLGetExtension(pszNewName), "dbf") && + if (bRestoreSHX && EQUAL(CPLGetExtensionSafe(pszNewName).c_str(), "dbf") && CPLGetLastErrorMsg()[0] != '\0') { CPLString osMsg = CPLGetLastErrorMsg(); @@ -422,7 +425,7 @@ bool OGRShapeDataSource::OpenFile(const char *pszNewName, bool bUpdate) else { if (hSHP == nullptr && - (!EQUAL(CPLGetExtension(pszNewName), "dbf") || + (!EQUAL(CPLGetExtensionSafe(pszNewName).c_str(), "dbf") || strstr(CPLGetLastErrorMsg(), ".shp") == nullptr)) { CPLString osMsg = CPLGetLastErrorMsg(); @@ -440,7 +443,8 @@ bool OGRShapeDataSource::OpenFile(const char *pszNewName, bool bUpdate) /* file or has to refer to the actual .dbf file. */ /* -------------------------------------------------------------------- */ DBFHandle hDBF = nullptr; - if (hSHP != nullptr || EQUAL(CPLGetExtension(pszNewName), "dbf")) + if (hSHP != nullptr || + EQUAL(CPLGetExtensionSafe(pszNewName).c_str(), "dbf")) { if (bRealUpdateAccess) { @@ -450,19 +454,19 @@ bool OGRShapeDataSource::OpenFile(const char *pszNewName, bool bUpdate) for (int i = 0; i < 2; i++) { VSIStatBufL sStat; - const char *pszDBFName = - CPLResetExtension(pszNewName, (i == 0) ? "dbf" : "DBF"); + const std::string osDBFName = CPLResetExtensionSafe( + pszNewName, (i == 0) ? "dbf" : "DBF"); VSILFILE *fp = nullptr; - if (VSIStatExL(pszDBFName, &sStat, VSI_STAT_EXISTS_FLAG) == - 0) + if (VSIStatExL(osDBFName.c_str(), &sStat, + VSI_STAT_EXISTS_FLAG) == 0) { - fp = VSIFOpenL(pszDBFName, "r+"); + fp = VSIFOpenL(osDBFName.c_str(), "r+"); if (fp == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "%s exists, " "but cannot be opened in update mode", - pszDBFName); + osDBFName.c_str()); SHPClose(hSHP); return false; } @@ -536,7 +540,7 @@ void OGRShapeDataSource::AddLayer(OGRShapeLayer *poLayer) static CPLString LaunderLayerName(const char *pszLayerName) { - std::string osRet(CPLLaunderForFilename(pszLayerName, nullptr)); + std::string osRet(CPLLaunderForFilenameSafe(pszLayerName, nullptr)); if (osRet != pszLayerName) { CPLError(CE_Warning, CPLE_AppDefined, @@ -783,11 +787,12 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, if (bSingleFileDataSource && nLayers == 0) { - char *pszPath = CPLStrdup(CPLGetPath(GetDescription())); - char *pszFBasename = CPLStrdup(CPLGetBasename(GetDescription())); + char *pszPath = CPLStrdup(CPLGetPathSafe(GetDescription()).c_str()); + char *pszFBasename = + CPLStrdup(CPLGetBasenameSafe(GetDescription()).c_str()); - pszFilenameWithoutExt = - CPLStrdup(CPLFormFilename(pszPath, pszFBasename, nullptr)); + pszFilenameWithoutExt = CPLStrdup( + CPLFormFilenameSafe(pszPath, pszFBasename, nullptr).c_str()); CPLFree(pszFBasename); CPLFree(pszPath); @@ -800,9 +805,11 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, // directory as 'foo.shp' // So technically, we will not be any longer a single file // datasource ... Ahem ahem. - char *pszPath = CPLStrdup(CPLGetPath(GetDescription())); - pszFilenameWithoutExt = CPLStrdup(CPLFormFilename( - pszPath, LaunderLayerName(pszLayerName).c_str(), nullptr)); + char *pszPath = CPLStrdup(CPLGetPathSafe(GetDescription()).c_str()); + pszFilenameWithoutExt = CPLStrdup( + CPLFormFilenameSafe(pszPath, LaunderLayerName(pszLayerName).c_str(), + nullptr) + .c_str()); CPLFree(pszPath); } else @@ -810,8 +817,10 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, const std::string osDir(m_osTemporaryUnzipDir.empty() ? std::string(GetDescription()) : m_osTemporaryUnzipDir); - pszFilenameWithoutExt = CPLStrdup(CPLFormFilename( - osDir.c_str(), LaunderLayerName(pszLayerName).c_str(), nullptr)); + pszFilenameWithoutExt = CPLStrdup( + CPLFormFilenameSafe(osDir.c_str(), + LaunderLayerName(pszLayerName).c_str(), nullptr) + .c_str()); } /* -------------------------------------------------------------------- */ @@ -824,8 +833,8 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, if (nShapeType != SHPT_NULL) { - char *pszFilename = - CPLStrdup(CPLFormFilename(nullptr, pszFilenameWithoutExt, "shp")); + char *pszFilename = CPLStrdup( + CPLFormFilenameSafe(nullptr, pszFilenameWithoutExt, "shp").c_str()); hSHP = SHPCreateLL(pszFilename, nShapeType, const_cast(VSI_SHP_GetHook(l_b2GBLimit))); @@ -850,8 +859,8 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, /* -------------------------------------------------------------------- */ /* Create a DBF file. */ /* -------------------------------------------------------------------- */ - char *pszFilename = - CPLStrdup(CPLFormFilename(nullptr, pszFilenameWithoutExt, "dbf")); + char *pszFilename = CPLStrdup( + CPLFormFilenameSafe(nullptr, pszFilenameWithoutExt, "dbf").c_str()); DBFHandle hDBF = DBFCreateLL(pszFilename, (pszLDID != nullptr) ? pszLDID : "LDID/87", @@ -876,7 +885,8 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, OGRSpatialReference *poSRSClone = nullptr; if (poSRS != nullptr) { - osPrjFilename = CPLFormFilename(nullptr, pszFilenameWithoutExt, "prj"); + osPrjFilename = + CPLFormFilenameSafe(nullptr, pszFilenameWithoutExt, "prj"); poSRSClone = poSRS->Clone(); char *pszWKT = nullptr; @@ -898,8 +908,8 @@ OGRShapeDataSource::ICreateLayer(const char *pszLayerName, // OGRShapeLayer constructor expects a filename with an extension (that // could be random actually), otherwise this is going to cause problems with // layer names that have a dot (not speaking about the one before the shp) - pszFilename = - CPLStrdup(CPLFormFilename(nullptr, pszFilenameWithoutExt, "shp")); + pszFilename = CPLStrdup( + CPLFormFilenameSafe(nullptr, pszFilenameWithoutExt, "shp").c_str()); OGRShapeLayer *poLayer = new OGRShapeLayer(this, pszFilename, hSHP, hDBF, poSRSClone, @@ -965,12 +975,12 @@ int OGRShapeDataSource::GetLayerCount() for (size_t i = 0; i < oVectorLayerName.size(); i++) { const char *pszFilename = oVectorLayerName[i].c_str(); - const char *pszLayerName = CPLGetBasename(pszFilename); + const std::string osLayerName = CPLGetBasenameSafe(pszFilename); int j = 0; // Used after for. for (; j < nLayers; j++) { - if (strcmp(papoLayers[j]->GetName(), pszLayerName) == 0) + if (papoLayers[j]->GetName() == osLayerName) break; } if (j < nLayers) @@ -1030,16 +1040,16 @@ OGRLayer *OGRShapeDataSource::GetLayerByName(const char *pszLayerNameIn) for (size_t i = 0; i < oVectorLayerName.size(); i++) { const char *pszFilename = oVectorLayerName[i].c_str(); - const char *pszLayerName = CPLGetBasename(pszFilename); + const std::string osLayerName = CPLGetBasenameSafe(pszFilename); if (j == 0) { - if (strcmp(pszLayerName, pszLayerNameIn) != 0) + if (osLayerName != pszLayerNameIn) continue; } else { - if (!EQUAL(pszLayerName, pszLayerNameIn)) + if (!EQUAL(osLayerName.c_str(), pszLayerNameIn)) continue; } @@ -1317,11 +1327,11 @@ OGRErr OGRShapeDataSource::DeleteLayer(int iLayer) OGRShapeDataSource::GetExtensionsForDeletion(); for (int iExt = 0; papszExtensions[iExt] != nullptr; iExt++) { - const char *pszFile = - CPLResetExtension(pszFilename, papszExtensions[iExt]); + const std::string osFile = + CPLResetExtensionSafe(pszFilename, papszExtensions[iExt]); VSIStatBufL sStatBuf; - if (VSIStatL(pszFile, &sStatBuf) == 0) - VSIUnlink(pszFile); + if (VSIStatL(osFile.c_str(), &sStatBuf) == 0) + VSIUnlink(osFile.c_str()); } CPLFree(pszFilename); @@ -1519,8 +1529,8 @@ bool OGRShapeDataSource::UncompressIfNeeded() const char *pszFilename = aosFiles[i]; if (!EQUAL(pszFilename, ".") && !EQUAL(pszFilename, "..")) { - CPLString osSrcFile( - CPLFormFilename(osVSIZipDirname, pszFilename, nullptr)); + const CPLString osSrcFile( + CPLFormFilenameSafe(osVSIZipDirname, pszFilename, nullptr)); VSIStatBufL sStat; if (VSIStatL(osSrcFile, &sStat) == 0) { @@ -1551,10 +1561,10 @@ bool OGRShapeDataSource::UncompressIfNeeded() const char *pszFilename = aosFiles[i]; if (!EQUAL(pszFilename, ".") && !EQUAL(pszFilename, "..")) { - CPLString osSrcFile( - CPLFormFilename(osVSIZipDirname, pszFilename, nullptr)); - CPLString osDestFile( - CPLFormFilename(osTemporaryDir, pszFilename, nullptr)); + const CPLString osSrcFile( + CPLFormFilenameSafe(osVSIZipDirname, pszFilename, nullptr)); + const CPLString osDestFile( + CPLFormFilenameSafe(osTemporaryDir, pszFilename, nullptr)); if (CPLCopyFile(osDestFile, osSrcFile) != 0) { VSIRmdirRecursive(osTemporaryDir); @@ -1606,8 +1616,8 @@ bool OGRShapeDataSource::RecompressIfNeeded( for (int i = 0; i < aosFiles.size(); i++) { sortedFiles.emplace_back(aosFiles[i]); - CPLString osSrcFile( - CPLFormFilename(m_osTemporaryUnzipDir, aosFiles[i], nullptr)); + const CPLString osSrcFile( + CPLFormFilenameSafe(m_osTemporaryUnzipDir, aosFiles[i], nullptr)); VSIStatBufL sStat; if (VSIStatL(osSrcFile, &sStat) == 0) { @@ -1621,11 +1631,13 @@ bool OGRShapeDataSource::RecompressIfNeeded( [&oMapLayerOrder](const CPLString &a, const CPLString &b) { int iA = INT_MAX; - auto oIterA = oMapLayerOrder.find(CPLGetBasename(a)); + auto oIterA = + oMapLayerOrder.find(CPLGetBasenameSafe(a).c_str()); if (oIterA != oMapLayerOrder.end()) iA = oIterA->second; int iB = INT_MAX; - auto oIterB = oMapLayerOrder.find(CPLGetBasename(b)); + auto oIterB = + oMapLayerOrder.find(CPLGetBasenameSafe(b).c_str()); if (oIterB != oMapLayerOrder.end()) iB = oIterB->second; if (iA < iB) @@ -1634,11 +1646,9 @@ bool OGRShapeDataSource::RecompressIfNeeded( return false; if (iA != INT_MAX) { - const char *pszExtA = CPLGetExtension(a); - const char *pszExtB = CPLGetExtension(b); - if (EQUAL(pszExtA, "shp")) + if (EQUAL(CPLGetExtensionSafe(a).c_str(), "shp")) return true; - if (EQUAL(pszExtB, "shp")) + if (EQUAL(CPLGetExtensionSafe(b).c_str(), "shp")) return false; } return a < b; @@ -1662,10 +1672,10 @@ bool OGRShapeDataSource::RecompressIfNeeded( const char *pszFilename = osFilename.c_str(); if (!EQUAL(pszFilename, ".") && !EQUAL(pszFilename, "..")) { - CPLString osSrcFile( - CPLFormFilename(m_osTemporaryUnzipDir, pszFilename, nullptr)); - CPLString osDestFile( - CPLFormFilename(osTmpZipWithVSIZip, pszFilename, nullptr)); + const CPLString osSrcFile(CPLFormFilenameSafe( + m_osTemporaryUnzipDir, pszFilename, nullptr)); + const CPLString osDestFile( + CPLFormFilenameSafe(osTmpZipWithVSIZip, pszFilename, nullptr)); if (CPLCopyFile(osDestFile, osSrcFile) != 0) { VSIFCloseL(fpZIP); diff --git a/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp b/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp index ef8a1b08ea61..b51bdf35fd45 100644 --- a/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp +++ b/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp @@ -48,7 +48,7 @@ static int OGRShapeDriverIdentify(GDALOpenInfo *poOpenInfo) { return FALSE; } - const std::string osExt(CPLGetExtension(poOpenInfo->pszFilename)); + const std::string &osExt = poOpenInfo->osExtension; if (EQUAL(osExt.c_str(), "SHP") || EQUAL(osExt.c_str(), "SHX")) { return poOpenInfo->nHeaderBytes >= 4 && @@ -118,7 +118,7 @@ static GDALDataset *OGRShapeDriverOpen(GDALOpenInfo *poOpenInfo) } #endif - CPLString osExt(CPLGetExtension(poOpenInfo->pszFilename)); + CPLString osExt(CPLGetExtensionSafe(poOpenInfo->pszFilename)); if (!STARTS_WITH(poOpenInfo->pszFilename, "/vsizip/") && (EQUAL(osExt, "shz") || (EQUAL(osExt, "zip") && @@ -163,7 +163,7 @@ static GDALDataset *OGRShapeDriverCreate(const char *pszName, int /* nBands */, char ** /* papszOptions */) { bool bSingleNewFile = false; - CPLString osExt(CPLGetExtension(pszName)); + CPLString osExt(CPLGetExtensionSafe(pszName)); /* -------------------------------------------------------------------- */ /* Is the target a valid existing directory? */ @@ -253,7 +253,7 @@ static CPLErr OGRShapeDriverDelete(const char *pszDataSource) return CE_Failure; } - CPLString osExt(CPLGetExtension(pszDataSource)); + CPLString osExt(CPLGetExtensionSafe(pszDataSource)); if (VSI_ISREG(sStatBuf.st_mode) && (EQUAL(osExt, "shz") || (EQUAL(osExt, "zip") && @@ -272,10 +272,10 @@ static CPLErr OGRShapeDriverDelete(const char *pszDataSource) { for (int iExt = 0; papszExtensions[iExt] != nullptr; iExt++) { - const char *pszFile = - CPLResetExtension(pszDataSource, papszExtensions[iExt]); - if (VSIStatL(pszFile, &sStatBuf) == 0) - VSIUnlink(pszFile); + const std::string osFile = + CPLResetExtensionSafe(pszDataSource, papszExtensions[iExt]); + if (VSIStatL(osFile.c_str(), &sStatBuf) == 0) + VSIUnlink(osFile.c_str()); } } else if (VSI_ISDIR(sStatBuf.st_mode)) @@ -286,11 +286,13 @@ static CPLErr OGRShapeDriverDelete(const char *pszDataSource) papszDirEntries != nullptr && papszDirEntries[iFile] != nullptr; iFile++) { - if (CSLFindString(papszExtensions, - CPLGetExtension(papszDirEntries[iFile])) != -1) + if (CSLFindString( + papszExtensions, + CPLGetExtensionSafe(papszDirEntries[iFile]).c_str()) != -1) { - VSIUnlink(CPLFormFilename(pszDataSource, papszDirEntries[iFile], - nullptr)); + VSIUnlink(CPLFormFilenameSafe(pszDataSource, + papszDirEntries[iFile], nullptr) + .c_str()); } } diff --git a/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp b/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp index 00f5c812395e..17a5868c60be 100644 --- a/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp +++ b/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp @@ -142,7 +142,7 @@ OGRShapeLayer::OGRShapeLayer(OGRShapeDataSource *poDSIn, SetMetadataItem("SOURCE_ENCODING", osEncoding, "SHAPEFILE"); poFeatureDefn = SHPReadOGRFeatureDefn( - CPLGetBasename(pszFullName), hSHP, hDBF, osEncoding, + CPLGetBasenameSafe(pszFullName).c_str(), hSHP, hDBF, osEncoding, CPLFetchBool(poDS->GetOpenOptions(), "ADJUST_TYPE", false)); // To make sure that @@ -589,9 +589,9 @@ bool OGRShapeLayer::CheckForQIX() if (bCheckedForQIX) return hQIX != nullptr; - const char *pszQIXFilename = CPLResetExtension(pszFullName, "qix"); + const std::string osQIXFilename = CPLResetExtensionSafe(pszFullName, "qix"); - hQIX = SHPOpenDiskTree(pszQIXFilename, nullptr); + hQIX = SHPOpenDiskTree(osQIXFilename.c_str(), nullptr); bCheckedForQIX = true; @@ -608,9 +608,9 @@ bool OGRShapeLayer::CheckForSBN() if (bCheckedForSBN) return hSBN != nullptr; - const char *pszSBNFilename = CPLResetExtension(pszFullName, "sbn"); + const std::string osSBNFilename = CPLResetExtensionSafe(pszFullName, "sbn"); - hSBN = SBNOpenDiskTree(pszSBNFilename, nullptr); + hSBN = SBNOpenDiskTree(osSBNFilename.c_str(), nullptr); bCheckedForSBN = true; @@ -1876,7 +1876,7 @@ OGRErr OGRShapeLayer::CreateField(const OGRFieldDefn *poFieldDefn, bool bDBFJustCreated = false; if (hDBF == nullptr) { - const CPLString osFilename = CPLResetExtension(pszFullName, "dbf"); + const CPLString osFilename = CPLResetExtensionSafe(pszFullName, "dbf"); hDBF = DBFCreate(osFilename); if (hDBF == nullptr) @@ -2355,7 +2355,8 @@ OGRErr OGRShapeLayer::AlterGeomFieldDefn( { if (poFieldDefn->GetPrjFilename().empty()) { - poFieldDefn->SetPrjFilename(CPLResetExtension(pszFullName, "prj")); + poFieldDefn->SetPrjFilename( + CPLResetExtensionSafe(pszFullName, "prj").c_str()); } const auto poNewSRSRef = poNewGeomFieldDefn->GetSpatialRef(); @@ -2423,20 +2424,20 @@ const OGRSpatialReference *OGRShapeGeomFieldDefn::GetSpatialRef() const /* -------------------------------------------------------------------- */ /* Is there an associated .prj file we can read? */ /* -------------------------------------------------------------------- */ - const char *pszPrjFile = CPLResetExtension(pszFullName, "prj"); + std::string l_osPrjFile = CPLResetExtensionSafe(pszFullName, "prj"); char *apszOptions[] = { const_cast("EMIT_ERROR_IF_CANNOT_OPEN_FILE=FALSE"), nullptr}; - char **papszLines = CSLLoad2(pszPrjFile, -1, -1, apszOptions); + char **papszLines = CSLLoad2(l_osPrjFile.c_str(), -1, -1, apszOptions); if (papszLines == nullptr) { - pszPrjFile = CPLResetExtension(pszFullName, "PRJ"); - papszLines = CSLLoad2(pszPrjFile, -1, -1, apszOptions); + l_osPrjFile = CPLResetExtensionSafe(pszFullName, "PRJ"); + papszLines = CSLLoad2(l_osPrjFile.c_str(), -1, -1, apszOptions); } if (papszLines != nullptr) { - osPrjFile = pszPrjFile; + osPrjFile = std::move(l_osPrjFile); auto poSRSNonConst = new OGRSpatialReference(); poSRSNonConst->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); @@ -2639,13 +2640,14 @@ OGRErr OGRShapeLayer::DropSpatialIndex() if (bHadQIX) { - const char *pszQIXFilename = CPLResetExtension(pszFullName, "qix"); - CPLDebug("SHAPE", "Unlinking index file %s", pszQIXFilename); + const std::string osQIXFilename = + CPLResetExtensionSafe(pszFullName, "qix"); + CPLDebug("SHAPE", "Unlinking index file %s", osQIXFilename.c_str()); - if (VSIUnlink(pszQIXFilename) != 0) + if (VSIUnlink(osQIXFilename.c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, - "Failed to delete file %s.\n%s", pszQIXFilename, + "Failed to delete file %s.\n%s", osQIXFilename.c_str(), VSIStrerror(errno)); return OGRERR_FAILURE; } @@ -2656,15 +2658,15 @@ OGRErr OGRShapeLayer::DropSpatialIndex() const char papszExt[2][4] = {"sbn", "sbx"}; for (int i = 0; i < 2; i++) { - const char *pszIndexFilename = - CPLResetExtension(pszFullName, papszExt[i]); + const std::string osIndexFilename = + CPLResetExtensionSafe(pszFullName, papszExt[i]); CPLDebug("SHAPE", "Trying to unlink index file %s", - pszIndexFilename); + osIndexFilename.c_str()); - if (VSIUnlink(pszIndexFilename) != 0) + if (VSIUnlink(osIndexFilename.c_str()) != 0) { CPLDebug("SHAPE", "Failed to delete file %s.\n%s", - pszIndexFilename, VSIStrerror(errno)); + osIndexFilename.c_str(), VSIStrerror(errno)); } } } @@ -2716,7 +2718,8 @@ OGRErr OGRShapeLayer::CreateSpatialIndex(int nMaxDepth) /* -------------------------------------------------------------------- */ /* Dump tree to .qix file. */ /* -------------------------------------------------------------------- */ - char *pszQIXFilename = CPLStrdup(CPLResetExtension(pszFullName, "qix")); + char *pszQIXFilename = + CPLStrdup(CPLResetExtensionSafe(pszFullName, "qix").c_str()); CPLDebug("SHAPE", "Creating index file %s", pszQIXFilename); @@ -2835,8 +2838,8 @@ OGRErr OGRShapeLayer::Repack() /* -------------------------------------------------------------------- */ /* Find existing filenames with exact case (see #3293). */ /* -------------------------------------------------------------------- */ - const CPLString osDirname(CPLGetPath(pszFullName)); - const CPLString osBasename(CPLGetBasename(pszFullName)); + const CPLString osDirname(CPLGetPathSafe(pszFullName)); + const CPLString osBasename(CPLGetBasenameSafe(pszFullName)); CPLString osDBFName; CPLString osSHPName; @@ -2847,9 +2850,9 @@ OGRErr OGRShapeLayer::Repack() while (papszCandidates != nullptr && papszCandidates[i] != nullptr) { const CPLString osCandidateBasename = - CPLGetBasename(papszCandidates[i]); + CPLGetBasenameSafe(papszCandidates[i]); const CPLString osCandidateExtension = - CPLGetExtension(papszCandidates[i]); + CPLGetExtensionSafe(papszCandidates[i]); #ifdef _WIN32 // On Windows, as filenames are case insensitive, a shapefile layer can // be made of foo.shp and FOO.DBF, so use case insensitive comparison. @@ -2860,16 +2863,16 @@ OGRErr OGRShapeLayer::Repack() { if (EQUAL(osCandidateExtension, "dbf")) osDBFName = - CPLFormFilename(osDirname, papszCandidates[i], nullptr); + CPLFormFilenameSafe(osDirname, papszCandidates[i], nullptr); else if (EQUAL(osCandidateExtension, "shp")) osSHPName = - CPLFormFilename(osDirname, papszCandidates[i], nullptr); + CPLFormFilenameSafe(osDirname, papszCandidates[i], nullptr); else if (EQUAL(osCandidateExtension, "shx")) osSHXName = - CPLFormFilename(osDirname, papszCandidates[i], nullptr); + CPLFormFilenameSafe(osDirname, papszCandidates[i], nullptr); else if (EQUAL(osCandidateExtension, "cpg")) osCPGName = - CPLFormFilename(osDirname, papszCandidates[i], nullptr); + CPLFormFilenameSafe(osDirname, papszCandidates[i], nullptr); } i++; @@ -2924,7 +2927,7 @@ OGRErr OGRShapeLayer::Repack() CPLDebug("Shape", "REPACK: repacking .dbf"); bMustReopenDBF = true; - oTempFileDBF = CPLFormFilename(osDirname, osBasename, nullptr); + oTempFileDBF = CPLFormFilenameSafe(osDirname, osBasename, nullptr); oTempFileDBF += "_packed.dbf"; DBFHandle hNewDBF = DBFCloneEmpty(hDBF, oTempFileDBF); @@ -2939,7 +2942,7 @@ OGRErr OGRShapeLayer::Repack() if (!osCPGName.empty()) { CPLString oCPGTempFile = - CPLFormFilename(osDirname, osBasename, nullptr); + CPLFormFilenameSafe(osDirname, osBasename, nullptr); oCPGTempFile += "_packed.cpg"; ForceDeleteFile(oCPGTempFile); } @@ -3010,9 +3013,9 @@ OGRErr OGRShapeLayer::Repack() { CPLDebug("Shape", "REPACK: repacking .shp + .shx"); - oTempFileSHP = CPLFormFilename(osDirname, osBasename, nullptr); + oTempFileSHP = CPLFormFilenameSafe(osDirname, osBasename, nullptr); oTempFileSHP += "_packed.shp"; - oTempFileSHX = CPLFormFilename(osDirname, osBasename, nullptr); + oTempFileSHX = CPLFormFilenameSafe(osDirname, osBasename, nullptr); oTempFileSHX += "_packed.shx"; SHPHandle hNewSHP = SHPCreate(oTempFileSHP, hSHP->nShapeType); @@ -3606,7 +3609,7 @@ bool OGRShapeLayer::ReopenFileDescriptors() if (hDBF == nullptr) { CPLError(CE_Failure, CPLE_OpenFailed, "Cannot reopen %s", - CPLResetExtension(pszFullName, "dbf")); + CPLResetExtensionSafe(pszFullName, "dbf").c_str()); eFileDescriptorsState = FD_CANNOT_REOPEN; return false; } @@ -3661,10 +3664,11 @@ void OGRShapeLayer::AddToFileList(CPLStringList &oFileList) { const char *pszSHPFilename = VSI_SHP_GetFilename(hSHP->fpSHP); oFileList.AddStringDirectly(VSIGetCanonicalFilename(pszSHPFilename)); - const char *pszSHPExt = CPLGetExtension(pszSHPFilename); - const char *pszSHXFilename = CPLResetExtension( - pszSHPFilename, (pszSHPExt[0] == 's') ? "shx" : "SHX"); - oFileList.AddStringDirectly(VSIGetCanonicalFilename(pszSHXFilename)); + const std::string osSHPExt = CPLGetExtensionSafe(pszSHPFilename); + const std::string osSHXFilename = CPLResetExtensionSafe( + pszSHPFilename, (osSHPExt[0] == 's') ? "shx" : "SHX"); + oFileList.AddStringDirectly( + VSIGetCanonicalFilename(osSHXFilename.c_str())); } if (hDBF) @@ -3673,11 +3677,11 @@ void OGRShapeLayer::AddToFileList(CPLStringList &oFileList) oFileList.AddStringDirectly(VSIGetCanonicalFilename(pszDBFFilename)); if (hDBF->pszCodePage != nullptr && hDBF->iLanguageDriver == 0) { - const char *pszDBFExt = CPLGetExtension(pszDBFFilename); - const char *pszCPGFilename = CPLResetExtension( - pszDBFFilename, (pszDBFExt[0] == 'd') ? "cpg" : "CPG"); + const std::string osDBFExt = CPLGetExtensionSafe(pszDBFFilename); + const std::string osCPGFilename = CPLResetExtensionSafe( + pszDBFFilename, (osDBFExt[0] == 'd') ? "cpg" : "CPG"); oFileList.AddStringDirectly( - VSIGetCanonicalFilename(pszCPGFilename)); + VSIGetCanonicalFilename(osCPGFilename.c_str())); } } @@ -3693,18 +3697,21 @@ void OGRShapeLayer::AddToFileList(CPLStringList &oFileList) } if (CheckForQIX()) { - const char *pszQIXFilename = CPLResetExtension(pszFullName, "qix"); + const std::string osQIXFilename = + CPLResetExtensionSafe(pszFullName, "qix"); oFileList.AddStringDirectly( - VSIGetCanonicalFilename(pszQIXFilename)); + VSIGetCanonicalFilename(osQIXFilename.c_str())); } else if (CheckForSBN()) { - const char *pszSBNFilename = CPLResetExtension(pszFullName, "sbn"); + const std::string osSBNFilename = + CPLResetExtensionSafe(pszFullName, "sbn"); oFileList.AddStringDirectly( - VSIGetCanonicalFilename(pszSBNFilename)); - const char *pszSBXFilename = CPLResetExtension(pszFullName, "sbx"); + VSIGetCanonicalFilename(osSBNFilename.c_str())); + const std::string osSBXFilename = + CPLResetExtensionSafe(pszFullName, "sbx"); oFileList.AddStringDirectly( - VSIGetCanonicalFilename(pszSBXFilename)); + VSIGetCanonicalFilename(osSBXFilename.c_str())); } } } @@ -3725,14 +3732,17 @@ void OGRShapeLayer::UpdateFollowingDeOrRecompression() OGRShapeGeomFieldDefn *poGeomFieldDefn = cpl::down_cast( GetLayerDefn()->GetGeomFieldDefn(0)); - poGeomFieldDefn->SetPrjFilename(CPLFormFilename( - osDSDir.c_str(), - CPLGetFilename(poGeomFieldDefn->GetPrjFilename().c_str()), - nullptr)); + poGeomFieldDefn->SetPrjFilename( + CPLFormFilenameSafe( + osDSDir.c_str(), + CPLGetFilename(poGeomFieldDefn->GetPrjFilename().c_str()), + nullptr) + .c_str()); } char *pszNewFullName = CPLStrdup( - CPLFormFilename(osDSDir, CPLGetFilename(pszFullName), nullptr)); + CPLFormFilenameSafe(osDSDir, CPLGetFilename(pszFullName), nullptr) + .c_str()); CPLFree(pszFullName); pszFullName = pszNewFullName; CloseUnderlyingLayer(); @@ -3760,11 +3770,12 @@ OGRErr OGRShapeLayer::Rename(const char *pszNewName) CPLStringList oFileList; AddToFileList(oFileList); - const std::string osDirname = CPLGetPath(pszFullName); + const std::string osDirname = CPLGetPathSafe(pszFullName); for (int i = 0; i < oFileList.size(); ++i) { - const std::string osRenamedFile = CPLFormFilename( - osDirname.c_str(), pszNewName, CPLGetExtension(oFileList[i])); + const std::string osRenamedFile = + CPLFormFilenameSafe(osDirname.c_str(), pszNewName, + CPLGetExtensionSafe(oFileList[i]).c_str()); VSIStatBufL sStat; if (VSIStatL(osRenamedFile.c_str(), &sStat) == 0) { @@ -3778,8 +3789,9 @@ OGRErr OGRShapeLayer::Rename(const char *pszNewName) for (int i = 0; i < oFileList.size(); ++i) { - const std::string osRenamedFile = CPLFormFilename( - osDirname.c_str(), pszNewName, CPLGetExtension(oFileList[i])); + const std::string osRenamedFile = + CPLFormFilenameSafe(osDirname.c_str(), pszNewName, + CPLGetExtensionSafe(oFileList[i]).c_str()); if (VSIRename(oFileList[i], osRenamedFile.c_str()) != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot rename %s to %s", @@ -3793,13 +3805,18 @@ OGRErr OGRShapeLayer::Rename(const char *pszNewName) OGRShapeGeomFieldDefn *poGeomFieldDefn = cpl::down_cast( GetLayerDefn()->GetGeomFieldDefn(0)); - poGeomFieldDefn->SetPrjFilename(CPLFormFilename( - osDirname.c_str(), pszNewName, - CPLGetExtension(poGeomFieldDefn->GetPrjFilename().c_str()))); - } - - char *pszNewFullName = CPLStrdup(CPLFormFilename( - osDirname.c_str(), pszNewName, CPLGetExtension(pszFullName))); + poGeomFieldDefn->SetPrjFilename( + CPLFormFilenameSafe( + osDirname.c_str(), pszNewName, + CPLGetExtensionSafe(poGeomFieldDefn->GetPrjFilename().c_str()) + .c_str()) + .c_str()); + } + + char *pszNewFullName = + CPLStrdup(CPLFormFilenameSafe(osDirname.c_str(), pszNewName, + CPLGetExtensionSafe(pszFullName).c_str()) + .c_str()); CPLFree(pszFullName); pszFullName = pszNewFullName; diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitedatasource.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitedatasource.cpp index f3cf706cecc8..d51c2b0aa947 100644 --- a/ogr/ogrsf_frmts/sqlite/ogrsqlitedatasource.cpp +++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitedatasource.cpp @@ -1913,8 +1913,8 @@ bool OGRSQLiteDataSource::Create(const char *pszNameIn, char **papszOptions) if (bUseTempFile) { m_osFinalFilename = pszNameIn; - m_pszFilename = - CPLStrdup(CPLGenerateTempFilename(CPLGetFilename(pszNameIn))); + m_pszFilename = CPLStrdup( + CPLGenerateTempFilenameSafe(CPLGetFilename(pszNameIn)).c_str()); CPLDebug("SQLITE", "Creating temporary file %s", m_pszFilename); } else diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitedriver.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitedriver.cpp index 1ee09e64de5d..d83156fb6bc7 100644 --- a/ogr/ogrsf_frmts/sqlite/ogrsqlitedriver.cpp +++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitedriver.cpp @@ -45,7 +45,7 @@ static int OGRSQLiteDriverIdentify(GDALOpenInfo *poOpenInfo) return TRUE; } - CPLString osExt(CPLGetExtension(poOpenInfo->pszFilename)); + CPLString osExt(CPLGetExtensionSafe(poOpenInfo->pszFilename)); if (EQUAL(osExt, "gpkg") && GDALGetDriverByName("GPKG") != nullptr) { return FALSE; @@ -179,11 +179,11 @@ static GDALDataset *OGRSQLiteDriverOpen(GDALOpenInfo *poOpenInfo) if (pszLastDot) *pszLastDot = '\0'; - const char *pszTableName = CPLGetBasename(pszSQLiteFilename); + const std::string osTableName = CPLGetBasenameSafe(pszSQLiteFilename); char *pszSQL = CPLStrdup(CPLSPrintf( "CREATE VIRTUAL TABLE %s USING VirtualShape(%s, CP1252, -1)", - pszTableName, pszSQLiteFilename)); + osTableName.c_str(), pszSQLiteFilename)); poDS->ExecuteSQL(pszSQL, nullptr, nullptr); CPLFree(pszSQL); CPLFree(pszSQLiteFilename); diff --git a/ogr/ogrsf_frmts/sqlite/rasterlite2.cpp b/ogr/ogrsf_frmts/sqlite/rasterlite2.cpp index 019c5a15af24..43edf9459a32 100644 --- a/ogr/ogrsf_frmts/sqlite/rasterlite2.cpp +++ b/ogr/ogrsf_frmts/sqlite/rasterlite2.cpp @@ -2004,8 +2004,8 @@ GDALDataset *OGRSQLiteDriverCreateCopy(const char *pszName, } } - CPLString osCoverageName(CSLFetchNameValueDef(papszOptions, "COVERAGE", - CPLGetBasename(pszName))); + const std::string osCoverageName(CSLFetchNameValueDef( + papszOptions, "COVERAGE", CPLGetBasenameSafe(pszName).c_str())); // Check if the coverage already exists rl2CoveragePtr cvg = nullptr; char *pszSQL = sqlite3_mprintf( @@ -2019,7 +2019,7 @@ GDALDataset *OGRSQLiteDriverCreateCopy(const char *pszName, if (nRowCount == 1) { cvg = rl2_create_coverage_from_dbms(poDS->GetDB(), nullptr, - osCoverageName); + osCoverageName.c_str()); if (cvg == nullptr) { delete poDS; @@ -2071,7 +2071,7 @@ GDALDataset *OGRSQLiteDriverCreateCopy(const char *pszName, } if (rl2_create_dbms_coverage( - poDS->GetDB(), osCoverageName, nSampleType, nPixelType, + poDS->GetDB(), osCoverageName.c_str(), nSampleType, nPixelType, nBandCount, nCompression, nQuality, nTileWidth, nTileHeight, nSRSId, dfXRes, dfYRes, pNoData, pPalette, bStrictResolution, bMixedResolutions, bSectionPaths, bSectionMD5, bSectionSummary, @@ -2092,7 +2092,7 @@ GDALDataset *OGRSQLiteDriverCreateCopy(const char *pszName, if (cvg == nullptr) { cvg = rl2_create_coverage_from_dbms(poDS->GetDB(), nullptr, - osCoverageName); + osCoverageName.c_str()); if (cvg == nullptr) { if (pPalette) @@ -2109,8 +2109,8 @@ GDALDataset *OGRSQLiteDriverCreateCopy(const char *pszName, double dfYMax = adfGeoTransform[3]; double dfYMin = dfYMax + adfGeoTransform[5] * poSrcDS->GetRasterYSize(); - CPLString osSectionName( - CSLFetchNameValueDef(papszOptions, "SECTION", CPLGetBasename(pszName))); + CPLString osSectionName(CSLFetchNameValueDef( + papszOptions, "SECTION", CPLGetBasenameSafe(pszName).c_str())); const bool bPyramidize = CPLFetchBool(papszOptions, "PYRAMIDIZE", false); RasterLite2CallbackData cbk_data; cbk_data.poSrcDS = poSrcDS; @@ -2148,7 +2148,7 @@ GDALDataset *OGRSQLiteDriverCreateCopy(const char *pszName, GDALOpenInfo oOpenInfo( CPLSPrintf("RASTERLITE2:%s:%s", EscapeNameAndQuoteIfNeeded(pszName).c_str(), - EscapeNameAndQuoteIfNeeded(osCoverageName).c_str()), + EscapeNameAndQuoteIfNeeded(osCoverageName.c_str()).c_str()), GDAL_OF_RASTER | GDAL_OF_UPDATE); poDS->Open(&oOpenInfo); return poDS; diff --git a/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp b/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp index 2ee4681b7bda..6b5105fc0043 100644 --- a/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp +++ b/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp @@ -127,7 +127,7 @@ int OGRSVGDataSource::Open(const char *pszFilename) /* Try to open the file. */ /* -------------------------------------------------------------------- */ CPLString osFilename; // keep in that scope - if (EQUAL(CPLGetExtension(pszFilename), "svgz") && + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "svgz") && strstr(pszFilename, "/vsigzip/") == nullptr) { osFilename = CPLString("/vsigzip/") + pszFilename; diff --git a/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp b/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp index 3116a2334191..b8e7a0832065 100644 --- a/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp +++ b/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp @@ -203,30 +203,30 @@ int OGRSXFDataSource::Open(const char *pszFilename, bool bUpdateIn, /*---------------- TRY READ THE RSC FILE HEADER -----------------------*/ CPLString soRSCRileName; - const char *pszRSCRileName = + std::string osRSCRileNameCandidate = CSLFetchNameValueDef(papszOpenOpts, "SXF_RSC_FILENAME", CPLGetConfigOption("SXF_RSC_FILENAME", "")); - if (pszRSCRileName != nullptr && - CPLCheckForFile((char *)pszRSCRileName, nullptr) == TRUE) + if (!osRSCRileNameCandidate.empty() && + CPLCheckForFile(osRSCRileNameCandidate.data(), nullptr) == TRUE) { - soRSCRileName = pszRSCRileName; + soRSCRileName = osRSCRileNameCandidate; } if (soRSCRileName.empty()) { - pszRSCRileName = CPLResetExtension(pszFilename, "rsc"); - if (CPLCheckForFile((char *)pszRSCRileName, nullptr) == TRUE) + osRSCRileNameCandidate = CPLResetExtensionSafe(pszFilename, "rsc"); + if (CPLCheckForFile(osRSCRileNameCandidate.data(), nullptr) == TRUE) { - soRSCRileName = pszRSCRileName; + soRSCRileName = osRSCRileNameCandidate; } } if (soRSCRileName.empty()) { - pszRSCRileName = CPLResetExtension(pszFilename, "RSC"); - if (CPLCheckForFile((char *)pszRSCRileName, nullptr) == TRUE) + osRSCRileNameCandidate = CPLResetExtensionSafe(pszFilename, "RSC"); + if (CPLCheckForFile(osRSCRileNameCandidate.data(), nullptr) == TRUE) { - soRSCRileName = pszRSCRileName; + soRSCRileName = osRSCRileNameCandidate; } } @@ -237,9 +237,9 @@ int OGRSXFDataSource::Open(const char *pszFilename, bool bUpdateIn, if (soRSCRileName.empty()) { #if defined(USE_ONLY_EMBEDDED_RESOURCE_FILES) - pszRSCRileName = nullptr; + const char *pszRSCRileName = nullptr; #else - pszRSCRileName = CPLFindFile("gdal", "default.rsc"); + const char *pszRSCRileName = CPLFindFile("gdal", "default.rsc"); #endif #ifdef EMBED_RESOURCE_FILES if (!pszRSCRileName || EQUAL(pszRSCRileName, "default.rsc")) diff --git a/ogr/ogrsf_frmts/sxf/ogrsxfdriver.cpp b/ogr/ogrsf_frmts/sxf/ogrsxfdriver.cpp index 91bfd6b02df2..de7c41f6d545 100644 --- a/ogr/ogrsf_frmts/sxf/ogrsxfdriver.cpp +++ b/ogr/ogrsf_frmts/sxf/ogrsxfdriver.cpp @@ -28,7 +28,7 @@ static GDALDataset *OGRSXFDriverOpen(GDALOpenInfo *poOpenInfo) /* -------------------------------------------------------------------- */ VSIStatBufL sStatBuf; - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "sxf") || + if (!poOpenInfo->IsExtensionEqualToCI("sxf") || VSIStatL(poOpenInfo->pszFilename, &sStatBuf) != 0 || !VSI_ISREG(sStatBuf.st_mode)) return nullptr; @@ -51,8 +51,8 @@ static GDALDataset *OGRSXFDriverOpen(GDALOpenInfo *poOpenInfo) static int OGRSXFDriverIdentify(GDALOpenInfo *poOpenInfo) { - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "sxf") || - !poOpenInfo->bStatOK || poOpenInfo->bIsDirectory) + if (!poOpenInfo->IsExtensionEqualToCI("sxf") || !poOpenInfo->bStatOK || + poOpenInfo->bIsDirectory) { return GDAL_IDENTIFY_FALSE; } @@ -91,9 +91,10 @@ static CPLErr OGRSXFDriverDelete(const char *pszName) for (int iExt = 0; apszExtensions[iExt] != nullptr; iExt++) { - const char *pszFile = CPLResetExtension(pszName, apszExtensions[iExt]); - if (VSIStatL(pszFile, &sStatBuf) == 0) - VSIUnlink(pszFile); + const std::string osFile = + CPLResetExtensionSafe(pszName, apszExtensions[iExt]); + if (VSIStatL(osFile.c_str(), &sStatBuf) == 0) + VSIUnlink(osFile.c_str()); } return CE_None; diff --git a/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp b/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp index f68546c8c948..edaacdaa8092 100644 --- a/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp +++ b/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp @@ -339,7 +339,7 @@ int OGRTigerDataSource::Open(const char *pszFilename, int bTestOpen, return FALSE; } - pszPath = CPLStrdup(CPLGetPath(pszFilename)); + pszPath = CPLStrdup(CPLGetPathSafe(pszFilename).c_str()); strncpy(szModule, CPLGetFilename(pszFilename), sizeof(szModule) - 1); /* Make sure the buffer is 0 terminated */ @@ -363,8 +363,9 @@ int OGRTigerDataSource::Open(const char *pszFilename, int bTestOpen, size_t nCandidateLen = strlen(candidateFileList[i]); if (papszLimitedFileList != nullptr && - CSLFindString(papszLimitedFileList, - CPLGetBasename(candidateFileList[i])) == -1) + CSLFindString( + papszLimitedFileList, + CPLGetBasenameSafe(candidateFileList[i]).c_str()) == -1) { continue; } diff --git a/ogr/ogrsf_frmts/vdv/ogrvdvdatasource.cpp b/ogr/ogrsf_frmts/vdv/ogrvdvdatasource.cpp index ba9653a3a027..040e1d0426bb 100644 --- a/ogr/ogrsf_frmts/vdv/ogrvdvdatasource.cpp +++ b/ogr/ogrsf_frmts/vdv/ogrvdvdatasource.cpp @@ -190,8 +190,8 @@ void OGRIDFDataSource::Parse() } else { - osTmpFilename = - CPLGenerateTempFilename(CPLGetBasename(m_osFilename)); + osTmpFilename = CPLGenerateTempFilenameSafe( + CPLGetBasenameSafe(m_osFilename).c_str()); osTmpFilename += ".gpkg"; } VSIUnlink(osTmpFilename); @@ -1185,7 +1185,7 @@ GDALDataset *OGRVDVDataSource::Open(GDALOpenInfo *poOpenInfo) if (EQUAL(*papszIter, ".") || EQUAL(*papszIter, "..")) continue; nFiles++; - const std::string osExtension(CPLGetExtension(*papszIter)); + const std::string osExtension(CPLGetExtensionSafe(*papszIter)); int nCount = ++oMapOtherExtensions[osExtension]; if (osMajorityExtension == "" || nCount > oMapOtherExtensions[osMajorityExtension]) @@ -1206,8 +1206,9 @@ GDALDataset *OGRVDVDataSource::Open(GDALOpenInfo *poOpenInfo) // And check that one of those files is a VDV one if it isn't .x10 if (osMajorityExtension != "x10") { - GDALOpenInfo oOpenInfo(CPLFormFilename(poOpenInfo->pszFilename, - osMajorityFile, nullptr), + GDALOpenInfo oOpenInfo(CPLFormFilenameSafe(poOpenInfo->pszFilename, + osMajorityFile, nullptr) + .c_str(), GA_ReadOnly); if (OGRVDVDriverIdentify(&oOpenInfo) != TRUE) { @@ -1225,18 +1226,22 @@ GDALDataset *OGRVDVDataSource::Open(GDALOpenInfo *poOpenInfo) for (char **papszIter = papszFiles; papszIter && *papszIter; ++papszIter) { - if (!EQUAL(CPLGetExtension(*papszIter), osMajorityExtension)) + if (!EQUAL(CPLGetExtensionSafe(*papszIter).c_str(), + osMajorityExtension)) continue; - VSILFILE *fp = VSIFOpenL( - CPLFormFilename(poOpenInfo->pszFilename, *papszIter, nullptr), - "rb"); + VSILFILE *fp = + VSIFOpenL(CPLFormFilenameSafe(poOpenInfo->pszFilename, + *papszIter, nullptr) + .c_str(), + "rb"); if (fp == nullptr) continue; poDS->m_papoLayers = static_cast( CPLRealloc(poDS->m_papoLayers, sizeof(OGRLayer *) * (poDS->m_nLayerCount + 1))); - poDS->m_papoLayers[poDS->m_nLayerCount] = new OGRVDVLayer( - poDS, CPLGetBasename(*papszIter), fp, true, false, 0); + poDS->m_papoLayers[poDS->m_nLayerCount] = + new OGRVDVLayer(poDS, CPLGetBasenameSafe(*papszIter).c_str(), + fp, true, false, 0); poDS->m_nLayerCount++; } CSLDestroy(papszFiles); @@ -1913,8 +1918,8 @@ OGRVDVDataSource::ICreateLayer(const char *pszLayerName, { CPLString osExtension = CSLFetchNameValueDef(papszOptions, "EXTENSION", "x10"); - CPLString osFilename = - CPLFormFilename(m_osFilename, pszLayerName, osExtension); + const CPLString osFilename = + CPLFormFilenameSafe(m_osFilename, pszLayerName, osExtension); fpL = VSIFOpenL(osFilename, "wb"); if (fpL == nullptr) { diff --git a/ogr/ogrsf_frmts/vfk/ogrvfkdrivercore.cpp b/ogr/ogrsf_frmts/vfk/ogrvfkdrivercore.cpp index 435238cb882d..0b1692e85c5b 100644 --- a/ogr/ogrsf_frmts/vfk/ogrvfkdrivercore.cpp +++ b/ogr/ogrsf_frmts/vfk/ogrvfkdrivercore.cpp @@ -32,7 +32,7 @@ int OGRVFKDriverIdentify(GDALOpenInfo *poOpenInfo) VFK driver, the real check is done by VFKReaderSQLite */ if (poOpenInfo->nHeaderBytes >= 100 && STARTS_WITH((const char *)poOpenInfo->pabyHeader, "SQLite format 3") && - !EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "gpkg")) + !poOpenInfo->IsExtensionEqualToCI("gpkg")) { // The driver is not ready for virtual file systems if (STARTS_WITH(poOpenInfo->pszFilename, "/vsi")) diff --git a/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp b/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp index 5d8ee5e81c15..be17d30d448c 100644 --- a/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp +++ b/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp @@ -54,7 +54,7 @@ VFKReaderSQLite::VFKReaderSQLite(const GDALOpenInfo *poOpenInfo) } else { - osDbName = CPLResetExtension(m_pszFilename, "db"); + osDbName = CPLResetExtensionSafe(m_pszFilename, "db"); } nLen = osDbName.length(); if (nLen > 2048) diff --git a/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp b/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp index e96c85ff0115..9caf46103252 100644 --- a/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp +++ b/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp @@ -738,7 +738,7 @@ bool OGRVRTDataSource::Initialize(CPLXMLNode *psTreeIn, const char *pszNewName, // Set name, and capture the directory path so we can use it // for relative datasources. - CPLString osVRTDirectory = CPLGetPath(pszNewName); + CPLString osVRTDirectory = CPLGetPathSafe(pszNewName); // Look for the OGRVRTDataSource node, it might be after an node. CPLXMLNode *psVRTDSXML = CPLGetXMLNode(psTree, "=OGRVRTDataSource"); diff --git a/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp b/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp index fec13e5afa7e..af258e0943ea 100644 --- a/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp +++ b/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp @@ -581,7 +581,7 @@ bool OGRVRTLayer::FullInitialize() nLastPart -= 2; CPLString osPrefix(osSrcDSName); osPrefix.resize(nLastPart); - osSrcDSName = osPrefix + CPLProjectRelativeFilename( + osSrcDSName = osPrefix + CPLProjectRelativeFilenameSafe( osVRTDirectory, osSrcDSName.c_str() + nLastPart); bDone = true; @@ -590,8 +590,8 @@ bool OGRVRTLayer::FullInitialize() } if (!bDone) { - osSrcDSName = - CPLProjectRelativeFilename(osVRTDirectory, osSrcDSName.c_str()); + osSrcDSName = CPLProjectRelativeFilenameSafe(osVRTDirectory, + osSrcDSName.c_str()); } } diff --git a/ogr/ogrsf_frmts/wasp/ogrwaspdatasource.cpp b/ogr/ogrsf_frmts/wasp/ogrwaspdatasource.cpp index d9bce9c9111f..06a11a4bf7ba 100644 --- a/ogr/ogrsf_frmts/wasp/ogrwaspdatasource.cpp +++ b/ogr/ogrsf_frmts/wasp/ogrwaspdatasource.cpp @@ -102,7 +102,8 @@ OGRErr OGRWAsPDataSource::Load(bool bSilent) CPLReadLineL(hFile); CPLReadLineL(hFile); - oLayer.reset(new OGRWAsPLayer(this, CPLGetBasename(sFilename.c_str()), + oLayer.reset(new OGRWAsPLayer(this, + CPLGetBasenameSafe(sFilename.c_str()).c_str(), hFile, poSpatialRef)); if (poSpatialRef) poSpatialRef->Release(); @@ -299,8 +300,8 @@ OGRWAsPDataSource::ICreateLayer(const char *pszName, poSRSClone->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } oLayer.reset(new OGRWAsPLayer( - this, CPLGetBasename(pszName), hFile, poSRSClone, sFirstField, - sSecondField, sGeomField, bMerge, pdfTolerance.release(), + this, CPLGetBasenameSafe(pszName).c_str(), hFile, poSRSClone, + sFirstField, sSecondField, sGeomField, bMerge, pdfTolerance.release(), pdfAdjacentPointTolerance.release(), pdfPointToCircleRadius.release())); if (poSRSClone) poSRSClone->Release(); diff --git a/ogr/ogrsf_frmts/wasp/ogrwaspdriver.cpp b/ogr/ogrsf_frmts/wasp/ogrwaspdriver.cpp index 390e12c48679..9a8487ecbd99 100644 --- a/ogr/ogrsf_frmts/wasp/ogrwaspdriver.cpp +++ b/ogr/ogrsf_frmts/wasp/ogrwaspdriver.cpp @@ -26,7 +26,7 @@ static GDALDataset *OGRWAsPDriverOpen(GDALOpenInfo *poOpenInfo) return nullptr; } - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "map")) + if (!poOpenInfo->IsExtensionEqualToCI("map")) { return nullptr; } diff --git a/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp b/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp index 0a8dcc8e004c..2770fbdfe166 100644 --- a/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp +++ b/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp @@ -999,7 +999,8 @@ GDALDataset *OGRWFSLayer::FetchGetFeature(int nRequestMaxFeatures) /* GML is a special case. It needs the .xsd file that has been saved */ /* as file.xsd, so we cannot used the attachment filename */ else if (pszAttachmentFilename && - !EQUAL(CPLGetExtension(pszAttachmentFilename), "GML")) + !EQUAL(CPLGetExtensionSafe(pszAttachmentFilename).c_str(), + "GML")) { osTmpFileName = m_osTmpDir + "/"; osTmpFileName += pszAttachmentFilename; @@ -1071,8 +1072,8 @@ GDALDataset *OGRWFSLayer::FetchGetFeature(int nRequestMaxFeatures) for (int i = 0; papszFileList != nullptr && papszFileList[i] != nullptr; i++) { - CPLString osFullFilename = - CPLFormFilename(osTmpFileName, papszFileList[i], nullptr); + const CPLString osFullFilename = + CPLFormFilenameSafe(osTmpFileName, papszFileList[i], nullptr); hDrv = GDALIdentifyDriver(osFullFilename, nullptr); if (hDrv != nullptr && hDrv == GDALGetDriverByName("GML")) papszOpenOptions = apszGMLOpenOptions; diff --git a/ogr/ogrsf_frmts/xls/ogrxlsdatasource.cpp b/ogr/ogrsf_frmts/xls/ogrxlsdatasource.cpp index c37579a904d8..13740ac86c00 100644 --- a/ogr/ogrsf_frmts/xls/ogrxlsdatasource.cpp +++ b/ogr/ogrsf_frmts/xls/ogrxlsdatasource.cpp @@ -93,9 +93,9 @@ int OGRXLSDataSource::Open(const char *pszFilename, int bUpdateIn) { CPLErrorReset(); - // FIXME: CPLGenerateTempFilename() would normally be expected to + // FIXME: CPLGenerateTempFilenameSafe() would normally be expected to // return a UTF-8 filename but I doubt it does in all cases. - m_osTempFilename = CPLGenerateTempFilename("temp_xls"); + m_osTempFilename = CPLGenerateTempFilenameSafe("temp_xls"); m_osANSIFilename = m_osTempFilename; CPLCopyFile(m_osANSIFilename, pszFilename); CPLDebug("XLS", "Create temporary file: %s", diff --git a/ogr/ogrsf_frmts/xls/ogrxlsdriver.cpp b/ogr/ogrsf_frmts/xls/ogrxlsdriver.cpp index 156939149398..bc108fae9cd1 100644 --- a/ogr/ogrsf_frmts/xls/ogrxlsdriver.cpp +++ b/ogr/ogrsf_frmts/xls/ogrxlsdriver.cpp @@ -26,7 +26,7 @@ static GDALDataset *OGRXLSDriverOpen(GDALOpenInfo *poOpenInfo) return nullptr; } - if (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "XLS")) + if (!poOpenInfo->IsExtensionEqualToCI("XLS")) { return nullptr; } diff --git a/ogr/ogrsf_frmts/xls/ogrxlsdrivercore.cpp b/ogr/ogrsf_frmts/xls/ogrxlsdrivercore.cpp index 97121f7c0a12..0eca1187dbdc 100644 --- a/ogr/ogrsf_frmts/xls/ogrxlsdrivercore.cpp +++ b/ogr/ogrsf_frmts/xls/ogrxlsdrivercore.cpp @@ -21,7 +21,7 @@ static int OGRXLSDriverIdentify(GDALOpenInfo *poOpenInfo) { - return EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "XLS"); + return poOpenInfo->IsExtensionEqualToCI("XLS"); } /************************************************************************/ diff --git a/ogr/ogrsf_frmts/xlsx/ogrxlsxdriver.cpp b/ogr/ogrsf_frmts/xlsx/ogrxlsxdriver.cpp index 1f71941d3e78..d969a9c6b457 100644 --- a/ogr/ogrsf_frmts/xlsx/ogrxlsxdriver.cpp +++ b/ogr/ogrsf_frmts/xlsx/ogrxlsxdriver.cpp @@ -39,7 +39,7 @@ static int OGRXLSXDriverIdentify(GDALOpenInfo *poOpenInfo) if (STARTS_WITH(poOpenInfo->pszFilename, "/vsizip/") || STARTS_WITH(poOpenInfo->pszFilename, "/vsitar/")) { - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); return EQUAL(pszExt, "XLSX") || EQUAL(pszExt, "XLSM") || EQUAL(pszExt, "XLSX}") || EQUAL(pszExt, "XLSM}"); } @@ -62,7 +62,7 @@ static int OGRXLSXDriverIdentify(GDALOpenInfo *poOpenInfo) { return TRUE; } - const char *pszExt = CPLGetExtension(poOpenInfo->pszFilename); + const char *pszExt = poOpenInfo->osExtension.c_str(); if (EQUAL(pszExt, "XLSX") || EQUAL(pszExt, "XLSM")) { CPLDebug( @@ -176,7 +176,7 @@ static GDALDataset *OGRXLSXDriverCreate(const char *pszName, int /* nXSize */, char **papszOptions) { - if (!EQUAL(CPLGetExtension(pszName), "XLSX")) + if (!EQUAL(CPLGetExtensionSafe(pszName).c_str(), "XLSX")) { CPLError(CE_Failure, CPLE_AppDefined, "File extension should be XLSX"); return nullptr; diff --git a/ogr/ogrsf_frmts/xodr/ogrxodrdrivercore.cpp b/ogr/ogrsf_frmts/xodr/ogrxodrdrivercore.cpp index a8abf37c4a4f..9dce67c462bd 100644 --- a/ogr/ogrsf_frmts/xodr/ogrxodrdrivercore.cpp +++ b/ogr/ogrsf_frmts/xodr/ogrxodrdrivercore.cpp @@ -21,7 +21,7 @@ int OGRXODRDriverIdentify(GDALOpenInfo *poOpenInfo) { return poOpenInfo->fpL != nullptr && - EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "xodr") && + poOpenInfo->IsExtensionEqualToCI("xodr") && !STARTS_WITH(poOpenInfo->pszFilename, "/vsi"); } diff --git a/port/CMakeLists.txt b/port/CMakeLists.txt index 1d566b461d57..3a66abb533f1 100644 --- a/port/CMakeLists.txt +++ b/port/CMakeLists.txt @@ -112,6 +112,8 @@ target_sources(${GDAL_LIB_TARGET_NAME} PRIVATE $) target_compile_options(cpl PRIVATE ${GDAL_CXX_WARNING_FLAGS} ${WFLAG_OLD_STYLE_CAST} ${WFLAG_EFFCXX}) set_property(TARGET cpl PROPERTY POSITION_INDEPENDENT_CODE ${GDAL_OBJECT_LIBRARIES_POSITION_INDEPENDENT_CODE}) +set_property(SOURCE cpl_path.cpp PROPERTY SKIP_UNITY_BUILD_INCLUSION ON) + # include path to generated cpl_config.h target_include_directories(cpl PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) diff --git a/port/cpl_conv.cpp b/port/cpl_conv.cpp index af6920a18b6b..e2bb55ee0e31 100644 --- a/port/cpl_conv.cpp +++ b/port/cpl_conv.cpp @@ -2481,9 +2481,12 @@ void CPLLoadConfigOptionsFromPredefinedFiles() else { #ifdef SYSCONFDIR - pszFile = CPLFormFilename(CPLFormFilename(SYSCONFDIR, "gdal", nullptr), - "gdalrc", nullptr); - CPLLoadConfigOptionsFromFile(pszFile, false); + CPLLoadConfigOptionsFromFile( + CPLFormFilenameSafe( + CPLFormFilenameSafe(SYSCONFDIR, "gdal", nullptr).c_str(), + "gdalrc", nullptr) + .c_str(), + false); #endif #ifdef _WIN32 @@ -2493,9 +2496,12 @@ void CPLLoadConfigOptionsFromPredefinedFiles() #endif if (pszHome != nullptr) { - pszFile = CPLFormFilename( - CPLFormFilename(pszHome, ".gdal", nullptr), "gdalrc", nullptr); - CPLLoadConfigOptionsFromFile(pszFile, false); + CPLLoadConfigOptionsFromFile( + CPLFormFilenameSafe( + CPLFormFilenameSafe(pszHome, ".gdal", nullptr).c_str(), + "gdalrc", nullptr) + .c_str(), + false); } } } @@ -3106,7 +3112,7 @@ int CPLUnlinkTree(const char *pszPath) continue; const std::string osSubPath = - CPLFormFilename(pszPath, papszItems[i], nullptr); + CPLFormFilenameSafe(pszPath, papszItems[i], nullptr); const int nErr = CPLUnlinkTree(osSubPath.c_str()); @@ -3197,9 +3203,9 @@ int CPLCopyTree(const char *pszNewPath, const char *pszOldPath) continue; const std::string osNewSubPath = - CPLFormFilename(pszNewPath, papszItems[i], nullptr); + CPLFormFilenameSafe(pszNewPath, papszItems[i], nullptr); const std::string osOldSubPath = - CPLFormFilename(pszOldPath, papszItems[i], nullptr); + CPLFormFilenameSafe(pszOldPath, papszItems[i], nullptr); const int nErr = CPLCopyTree(osNewSubPath.c_str(), osOldSubPath.c_str()); diff --git a/port/cpl_conv.h b/port/cpl_conv.h index 1df8c48eff21..ee330af2e27a 100644 --- a/port/cpl_conv.h +++ b/port/cpl_conv.h @@ -151,17 +151,18 @@ int CPL_DLL CPLGetExecPath(char *pszPathBuf, int nMaxLength); /* -------------------------------------------------------------------- */ /* Filename handling functions. */ /* -------------------------------------------------------------------- */ + +#if defined(DOXYGEN_SKIP) || !defined(__cplusplus) || \ + !defined(GDAL_COMPILATION) || \ + (defined(__cplusplus) && defined(ALLOW_DEPRECATED_CPL_PATH_FUNCTIONS)) const char CPL_DLL * CPLGetPath(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; const char CPL_DLL * CPLGetDirname(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; const char CPL_DLL * -CPLGetFilename(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; -const char CPL_DLL * CPLGetBasename(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; const char CPL_DLL * CPLGetExtension(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; -char CPL_DLL *CPLGetCurrentDir(void); const char CPL_DLL *CPLFormFilename( const char *pszPath, const char *pszBasename, const char *pszExtension) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; @@ -173,24 +174,61 @@ const char CPL_DLL *CPLResetExtension(const char *, const char *) const char CPL_DLL *CPLProjectRelativeFilename(const char *pszProjectDir, const char *pszSecondaryFilename) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; -int CPL_DLL CPLIsFilenameRelative(const char *pszFilename); -const char CPL_DLL *CPLExtractRelativePath(const char *, const char *, int *) - CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; const char CPL_DLL * CPLCleanTrailingSlash(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; -char CPL_DLL ** -CPLCorrespondingPaths(const char *pszOldFilename, const char *pszNewFilename, - char **papszFileList) CPL_WARN_UNUSED_RESULT; -int CPL_DLL CPLCheckForFile(char *pszFilename, char **papszSiblingList); - const char CPL_DLL *CPLGenerateTempFilename(const char *pszStem) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; const char CPL_DLL *CPLExpandTilde(const char *pszFilename) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; -const char CPL_DLL *CPLGetHomeDir(void) CPL_WARN_UNUSED_RESULT; const char CPL_DLL * CPLLaunderForFilename(const char *pszName, const char *pszOutputPath) CPL_WARN_UNUSED_RESULT; +#endif + +char CPL_DLL *CPLGetCurrentDir(void); +const char CPL_DLL * +CPLGetFilename(const char *) CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; +int CPL_DLL CPLIsFilenameRelative(const char *pszFilename); +const char CPL_DLL *CPLExtractRelativePath(const char *, const char *, int *) + CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL; +char CPL_DLL ** +CPLCorrespondingPaths(const char *pszOldFilename, const char *pszNewFilename, + char **papszFileList) CPL_WARN_UNUSED_RESULT; +int CPL_DLL CPLCheckForFile(char *pszFilename, char **papszSiblingList); + +const char CPL_DLL *CPLGetHomeDir(void) CPL_WARN_UNUSED_RESULT; + +#if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS) + +extern "C++" +{ + std::string CPL_DLL CPLGetPathSafe(const char *) CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLGetDirnameSafe(const char *) CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLGetBasenameSafe(const char *) CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLGetExtensionSafe(const char *) + CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLFormFilenameSafe( + const char *pszPath, const char *pszBasename, + const char *pszExtension = nullptr) CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLFormCIFilenameSafe( + const char *pszPath, const char *pszBasename, + const char *pszExtension = nullptr) CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLResetExtensionSafe(const char *, const char *) + CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLProjectRelativeFilenameSafe( + const char *pszProjectDir, + const char *pszSecondaryFilename) CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLCleanTrailingSlashSafe(const char *pszPath) + CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLGenerateTempFilenameSafe(const char *pszStem) + CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLExpandTildeSafe(const char *pszFilename) + CPL_WARN_UNUSED_RESULT; + std::string CPL_DLL CPLLaunderForFilenameSafe( + const char *pszName, const char *pszOutputPath) CPL_WARN_UNUSED_RESULT; +} + +#endif // defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS) /* -------------------------------------------------------------------- */ /* Find File Function */ diff --git a/port/cpl_findfile.cpp b/port/cpl_findfile.cpp index 35c7eb9dab20..dfa74bae9e9d 100644 --- a/port/cpl_findfile.cpp +++ b/port/cpl_findfile.cpp @@ -139,12 +139,12 @@ const char *CPLDefaultFindFile(const char *pszClass, const char *pszBasename) for (int i = nLocations - 1; i >= 0; i--) { - const char *pszResult = CPLFormFilename( + const std::string osResult = CPLFormFilenameSafe( pTLSData->papszFinderLocations[i], pszBasename, nullptr); VSIStatBufL sStat; - if (VSIStatL(pszResult, &sStat) == 0) - return pszResult; + if (VSIStatL(osResult.c_str(), &sStat) == 0) + return CPLSPrintf("%s", osResult.c_str()); } if (EQUAL(pszClass, "gdal") && !CPLGetConfigOption("GDAL_DATA", nullptr)) diff --git a/port/cpl_known_config_options.h b/port/cpl_known_config_options.h index 667dbf90d5e1..03639da712d4 100644 --- a/port/cpl_known_config_options.h +++ b/port/cpl_known_config_options.h @@ -224,7 +224,6 @@ constexpr static const char* const apszKnownConfigOptions[] = "FGDB_STRING_WIDTH", // from FGdbUtils.cpp "FILEGDB_DISABLE_SPARSE_PAGES", // from FGdbLayer.cpp "FORCE_BLOCKSIZE", // from hfaopen.cpp - "FUSIL_SRC_DIR", // from ogropenfilegdbdriver.cpp "GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC", // from JPEG_band.cpp, jpgdataset.cpp "GDAL_BAG_BLOCK_SIZE", // from bagdataset.cpp "GDAL_BAG_MAX_SIZE_VARRES_MAP", // from bagdataset.cpp diff --git a/port/cpl_odbc.cpp b/port/cpl_odbc.cpp index 377e80a7f28c..ea1d0c2a5f5f 100644 --- a/port/cpl_odbc.cpp +++ b/port/cpl_odbc.cpp @@ -167,11 +167,8 @@ bool CPLODBCDriverInstaller::FindMdbToolsDriverLib(CPLString &osDriverFile) if (VSIStat(pszDrvCfg, &sStatBuf) == 0 && VSI_ISDIR(sStatBuf.st_mode)) { // Find default library in custom directory - const char *pszDriverFile = - CPLFormFilename(pszDrvCfg, "libmdbodbc.so", nullptr); - CPLAssert(nullptr != pszDriverFile); - - strLibPath = pszDriverFile; + strLibPath = + CPLFormFilenameSafe(pszDrvCfg, "libmdbodbc.so", nullptr); } if (LibraryExists(strLibPath.c_str())) @@ -216,14 +213,12 @@ bool CPLODBCDriverInstaller::FindMdbToolsDriverLib(CPLString &osDriverFile) { for (const char *pszLibName : apszLibNames) { - const char *pszDriverFile = - CPLFormFilename(pszPath, pszLibName, nullptr); - CPLAssert(nullptr != pszDriverFile); - - if (LibraryExists(pszDriverFile)) + const std::string osDriverFileAttempt = + CPLFormFilenameSafe(pszPath, pszLibName, nullptr); + if (LibraryExists(osDriverFileAttempt.c_str())) { // Save default driver path - osDriverFile = pszDriverFile; + osDriverFile = osDriverFileAttempt; return true; } } diff --git a/port/cpl_path.cpp b/port/cpl_path.cpp index 092a4dac9705..e50e46a0eab0 100644 --- a/port/cpl_path.cpp +++ b/port/cpl_path.cpp @@ -11,6 +11,8 @@ * SPDX-License-Identifier: MIT ****************************************************************************/ +#define ALLOW_DEPRECATED_CPL_PATH_FUNCTIONS + #include "cpl_port.h" #include "cpl_conv.h" @@ -81,6 +83,27 @@ static char *CPLGetStaticResult() return pachBuffer; } +/************************************************************************/ +/* CPLPathReturnTLSString() */ +/************************************************************************/ + +static const char *CPLPathReturnTLSString(const std::string &osRes, + const char *pszFuncName) +{ + if (osRes.size() >= CPL_PATH_BUF_SIZE) + { + CPLError(CE_Failure, CPLE_AppDefined, "Too long result for %s()", + pszFuncName); + return ""; + } + + char *pszStaticResult = CPLGetStaticResult(); + if (pszStaticResult == nullptr) + return CPLStaticBufferTooSmall(pszStaticResult); + memcpy(pszStaticResult, osRes.c_str(), osRes.size() + 1); + return pszStaticResult; +} + /************************************************************************/ /* CPLFindFilenameStart() */ /************************************************************************/ @@ -100,7 +123,7 @@ static int CPLFindFilenameStart(const char *pszFilename, size_t nStart = 0) } /************************************************************************/ -/* CPLGetPath() */ +/* CPLGetPathSafe() */ /************************************************************************/ /** @@ -111,27 +134,23 @@ static int CPLFindFilenameStart(const char *pszFilename, size_t nStart = 0) * will be returned (not NULL). * * \code{.cpp} - * CPLGetPath( "abc/def.xyz" ) == "abc" - * CPLGetPath( "/abc/def/" ) == "/abc/def" - * CPLGetPath( "/" ) == "/" - * CPLGetPath( "/abc/def" ) == "/abc" - * CPLGetPath( "abc" ) == "" + * CPLGetPathSafe( "abc/def.xyz" ) == "abc" + * CPLGetPathSafe( "/abc/def/" ) == "/abc/def" + * CPLGetPathSafe( "/" ) == "/" + * CPLGetPathSafe( "/abc/def" ) == "/abc" + * CPLGetPathSafe( "abc" ) == "" * \endcode * * @param pszFilename the filename potentially including a path. * - * @return Path in an internal string which must not be freed. The string - * may be destroyed by the next CPL filename handling call. The returned - * will generally not contain a trailing path separator. + * @return Path. + * + * @since 3.11 */ -const char *CPLGetPath(const char *pszFilename) +std::string CPLGetPathSafe(const char *pszFilename) { - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - size_t nSuffixPos = 0; if (STARTS_WITH(pszFilename, "/vsicurl/http")) { @@ -157,7 +176,8 @@ const char *CPLGetPath(const char *pszFilename) char *pszUnescaped = CPLUnescapeString(aosTokens[i], nullptr, CPLES_URL); char *pszPath = CPLEscapeString( - CPLGetPath(pszUnescaped + strlen("url=")), -1, CPLES_URL); + CPLGetPathSafe(pszUnescaped + strlen("url=")).c_str(), -1, + CPLES_URL); osRet += "url="; osRet += pszPath; CPLFree(pszPath); @@ -168,57 +188,45 @@ const char *CPLGetPath(const char *pszFilename) osRet += aosTokens[i]; } } - CPLStrlcpy(pszStaticResult, osRet.c_str(), CPL_PATH_BUF_SIZE); - return pszStaticResult; + return osRet; } const int iFileStart = CPLFindFilenameStart(pszFilename, nSuffixPos); - if (iFileStart >= CPL_PATH_BUF_SIZE) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszFilename >= pszStaticResult && - pszFilename < pszStaticResult + CPL_PATH_BUF_SIZE)); - if (iFileStart == 0) { - strcpy(pszStaticResult, ""); - return pszStaticResult; + return std::string(); } - CPLStrlcpy(pszStaticResult, pszFilename, - static_cast(iFileStart) + 1); + std::string osRet(pszFilename, iFileStart); - if (iFileStart > 1 && (pszStaticResult[iFileStart - 1] == '/' || - pszStaticResult[iFileStart - 1] == '\\')) - pszStaticResult[iFileStart - 1] = '\0'; + if (iFileStart > 1 && (osRet.back() == '/' || osRet.back() == '\\')) + osRet.pop_back(); if (nSuffixPos) { - if (CPLStrlcat(pszStaticResult, pszFilename + nSuffixPos, - CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE) - return CPLStaticBufferTooSmall(pszStaticResult); + osRet += (pszFilename + nSuffixPos); } - return pszStaticResult; + return osRet; } /************************************************************************/ -/* CPLGetDirname() */ +/* CPLGetPath() */ /************************************************************************/ /** * Extract directory path portion of filename. * * Returns a string containing the directory path portion of the passed - * filename. If there is no path in the passed filename the dot will be - * returned. It is the only difference from CPLGetPath(). + * filename. If there is no path in the passed filename an empty string + * will be returned (not NULL). * * \code{.cpp} - * CPLGetDirname( "abc/def.xyz" ) == "abc" - * CPLGetDirname( "/abc/def/" ) == "/abc/def" - * CPLGetDirname( "/" ) == "/" - * CPLGetDirname( "/abc/def" ) == "/abc" - * CPLGetDirname( "abc" ) == "." + * CPLGetPath( "abc/def.xyz" ) == "abc" + * CPLGetPath( "/abc/def/" ) == "/abc/def" + * CPLGetPath( "/" ) == "/" + * CPLGetPath( "/abc/def" ) == "/abc" + * CPLGetPath( "abc" ) == "" * \endcode * * @param pszFilename the filename potentially including a path. @@ -226,15 +234,45 @@ const char *CPLGetPath(const char *pszFilename) * @return Path in an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. The returned * will generally not contain a trailing path separator. + * + * @deprecated If using C++, prefer using CPLGetPathSafe() instead */ -const char *CPLGetDirname(const char *pszFilename) +const char *CPLGetPath(const char *pszFilename) { - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); + return CPLPathReturnTLSString(CPLGetPathSafe(pszFilename), __FUNCTION__); +} +/************************************************************************/ +/* CPLGetDirname() */ +/************************************************************************/ + +/** + * Extract directory path portion of filename. + * + * Returns a string containing the directory path portion of the passed + * filename. If there is no path in the passed filename the dot will be + * returned. It is the only difference from CPLGetPath(). + * + * \code{.cpp} + * CPLGetDirnameSafe( "abc/def.xyz" ) == "abc" + * CPLGetDirnameSafe( "/abc/def/" ) == "/abc/def" + * CPLGetDirnameSafe( "/" ) == "/" + * CPLGetDirnameSafe( "/abc/def" ) == "/abc" + * CPLGetDirnameSafe( "abc" ) == "." + * \endcode + * + * @param pszFilename the filename potentially including a path. + * + * @return Path + * + * @since 3.11 + */ + +std::string CPLGetDirnameSafe(const char *pszFilename) + +{ size_t nSuffixPos = 0; if (STARTS_WITH(pszFilename, "/vsicurl/http")) { @@ -272,38 +310,58 @@ const char *CPLGetDirname(const char *pszFilename) osRet += aosTokens[i]; } } - CPLStrlcpy(pszStaticResult, osRet.c_str(), CPL_PATH_BUF_SIZE); - return pszStaticResult; + return osRet; } const int iFileStart = CPLFindFilenameStart(pszFilename, nSuffixPos); - if (iFileStart >= CPL_PATH_BUF_SIZE) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszFilename >= pszStaticResult && - pszFilename < pszStaticResult + CPL_PATH_BUF_SIZE)); - if (iFileStart == 0) { - strcpy(pszStaticResult, "."); - return pszStaticResult; + return std::string("."); } - CPLStrlcpy(pszStaticResult, pszFilename, - static_cast(iFileStart) + 1); + std::string osRet(pszFilename, iFileStart); - if (iFileStart > 1 && (pszStaticResult[iFileStart - 1] == '/' || - pszStaticResult[iFileStart - 1] == '\\')) - pszStaticResult[iFileStart - 1] = '\0'; + if (iFileStart > 1 && (osRet.back() == '/' || osRet.back() == '\\')) + osRet.pop_back(); if (nSuffixPos) { - if (CPLStrlcat(pszStaticResult, pszFilename + nSuffixPos, - CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE) - return CPLStaticBufferTooSmall(pszStaticResult); + osRet += (pszFilename + nSuffixPos); } - return pszStaticResult; + return osRet; +} + +/************************************************************************/ +/* CPLGetDirname() */ +/************************************************************************/ + +/** + * Extract directory path portion of filename. + * + * Returns a string containing the directory path portion of the passed + * filename. If there is no path in the passed filename the dot will be + * returned. It is the only difference from CPLGetPath(). + * + * \code{.cpp} + * CPLGetDirname( "abc/def.xyz" ) == "abc" + * CPLGetDirname( "/abc/def/" ) == "/abc/def" + * CPLGetDirname( "/" ) == "/" + * CPLGetDirname( "/abc/def" ) == "/abc" + * CPLGetDirname( "abc" ) == "." + * \endcode + * + * @param pszFilename the filename potentially including a path. + * + * @return Path in an internal string which must not be freed. The string + * may be destroyed by the next CPL filename handling call. The returned + * will generally not contain a trailing path separator. + */ + +const char *CPLGetDirname(const char *pszFilename) + +{ + return CPLPathReturnTLSString(CPLGetDirnameSafe(pszFilename), __FUNCTION__); } /************************************************************************/ @@ -338,7 +396,7 @@ const char *CPLGetFilename(const char *pszFullFilename) } /************************************************************************/ -/* CPLGetBasename() */ +/* CPLGetBasenameSafe() */ /************************************************************************/ /** @@ -356,22 +414,16 @@ const char *CPLGetFilename(const char *pszFullFilename) * * @param pszFullFilename the full filename potentially including a path. * - * @return just the non-directory, non-extension portion of the path in - * an internal string which must not be freed. The string - * may be destroyed by the next CPL filename handling call. + * @return just the non-directory, non-extension portion of the path + * + * @since 3.11 */ -const char *CPLGetBasename(const char *pszFullFilename) +std::string CPLGetBasenameSafe(const char *pszFullFilename) { const size_t iFileStart = static_cast(CPLFindFilenameStart(pszFullFilename)); - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszFullFilename >= pszStaticResult && - pszFullFilename < pszStaticResult + CPL_PATH_BUF_SIZE)); size_t iExtStart = strlen(pszFullFilename); for (; iExtStart > iFileStart && pszFullFilename[iExtStart] != '.'; @@ -383,17 +435,44 @@ const char *CPLGetBasename(const char *pszFullFilename) iExtStart = strlen(pszFullFilename); const size_t nLength = iExtStart - iFileStart; + return std::string(pszFullFilename + iFileStart, nLength); +} - if (nLength >= static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); +/************************************************************************/ +/* CPLGetBasename() */ +/************************************************************************/ + +/** + * Extract basename (non-directory, non-extension) portion of filename. + * + * Returns a string containing the file basename portion of the passed + * name. If there is no basename (passed value ends in trailing directory + * separator, or filename starts with a dot) an empty string is returned. + * + * \code{.cpp} + * CPLGetBasename( "abc/def.xyz" ) == "def" + * CPLGetBasename( "abc/def" ) == "def" + * CPLGetBasename( "abc/def/" ) == "" + * \endcode + * + * @param pszFullFilename the full filename potentially including a path. + * + * @return just the non-directory, non-extension portion of the path in + * an internal string which must not be freed. The string + * may be destroyed by the next CPL filename handling call. + * + * @deprecated If using C++, prefer using CPLGetBasenameSafe() instead + */ - CPLStrlcpy(pszStaticResult, pszFullFilename + iFileStart, nLength + 1); +const char *CPLGetBasename(const char *pszFullFilename) - return pszStaticResult; +{ + return CPLPathReturnTLSString(CPLGetBasenameSafe(pszFullFilename), + __FUNCTION__); } /************************************************************************/ -/* CPLGetExtension() */ +/* CPLGetExtensionSafe() */ /************************************************************************/ /** @@ -404,32 +483,25 @@ const char *CPLGetBasename(const char *pszFullFilename) * is returned. The returned extension will not include the period. * * \code{.cpp} - * CPLGetExtension( "abc/def.xyz" ) == "xyz" - * CPLGetExtension( "abc/def" ) == "" + * CPLGetExtensionSafe( "abc/def.xyz" ) == "xyz" + * CPLGetExtensionSafe( "abc/def" ) == "" * \endcode * * @param pszFullFilename the full filename potentially including a path. * - * @return just the extension portion of the path in - * an internal string which must not be freed. The string - * may be destroyed by the next CPL filename handling call. + * @return just the extension portion of the path. + * + * @since 3.11 */ -const char *CPLGetExtension(const char *pszFullFilename) +std::string CPLGetExtensionSafe(const char *pszFullFilename) { if (pszFullFilename[0] == '\0') - return ""; + return std::string(); size_t iFileStart = static_cast(CPLFindFilenameStart(pszFullFilename)); - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszFullFilename >= pszStaticResult && - pszFullFilename < pszStaticResult + CPL_PATH_BUF_SIZE)); - size_t iExtStart = strlen(pszFullFilename); for (; iExtStart > iFileStart && pszFullFilename[iExtStart] != '.'; iExtStart--) @@ -445,11 +517,39 @@ const char *CPLGetExtension(const char *pszFullFilename) if (strlen(pszFullFilename + iExtStart + 1) > knMaxExtensionSize) return ""; - if (CPLStrlcpy(pszStaticResult, pszFullFilename + iExtStart + 1, - CPL_PATH_BUF_SIZE) >= static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); + return std::string(pszFullFilename + iExtStart + 1); +} - return pszStaticResult; +/************************************************************************/ +/* CPLGetExtension() */ +/************************************************************************/ + +/** + * Extract filename extension from full filename. + * + * Returns a string containing the extension portion of the passed + * name. If there is no extension (the filename has no dot) an empty string + * is returned. The returned extension will not include the period. + * + * \code{.cpp} + * CPLGetExtension( "abc/def.xyz" ) == "xyz" + * CPLGetExtension( "abc/def" ) == "" + * \endcode + * + * @param pszFullFilename the full filename potentially including a path. + * + * @return just the extension portion of the path in + * an internal string which must not be freed. The string + * may be destroyed by the next CPL filename handling call. + * + * @deprecated If using C++, prefer using CPLGetExtensionSafe() instead + */ + +const char *CPLGetExtension(const char *pszFullFilename) + +{ + return CPLPathReturnTLSString(CPLGetExtensionSafe(pszFullFilename), + __FUNCTION__); } /************************************************************************/ @@ -511,60 +611,69 @@ char *CPLGetCurrentDir() * @param pszPath the input path, this string is not altered. * @param pszExt the new extension to apply to the given path. * - * @return an altered filename with the new extension. Do not - * modify or free the returned string. The string may be destroyed by the - * next CPL call. + * @return an altered filename with the new extension. + * + * @since 3.11 */ -const char *CPLResetExtension(const char *pszPath, const char *pszExt) +std::string CPLResetExtensionSafe(const char *pszPath, const char *pszExt) { - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszPath >= pszStaticResult && - pszPath < pszStaticResult + CPL_PATH_BUF_SIZE)); + std::string osRet(pszPath); /* -------------------------------------------------------------------- */ /* First, try and strip off any existing extension. */ /* -------------------------------------------------------------------- */ - if (CPLStrlcpy(pszStaticResult, pszPath, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); - if (*pszStaticResult) + for (size_t i = osRet.size(); i > 0;) { - for (size_t i = strlen(pszStaticResult) - 1; i > 0; i--) + --i; + if (osRet[i] == '.') { - if (pszStaticResult[i] == '.') - { - pszStaticResult[i] = '\0'; - break; - } - - if (pszStaticResult[i] == '/' || pszStaticResult[i] == '\\' || - pszStaticResult[i] == ':') - break; + osRet.resize(i); + break; + } + else if (osRet[i] == '/' || osRet[i] == '\\' || osRet[i] == ':') + { + break; } } /* -------------------------------------------------------------------- */ /* Append the new extension. */ /* -------------------------------------------------------------------- */ - if (CPLStrlcat(pszStaticResult, ".", CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE) || - CPLStrlcat(pszStaticResult, pszExt, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) - { - return CPLStaticBufferTooSmall(pszStaticResult); - } + osRet += '.'; + osRet += pszExt; - return pszStaticResult; + return osRet; } /************************************************************************/ -/* CPLFormFilename() */ +/* CPLResetExtension() */ +/************************************************************************/ + +/** + * Replace the extension with the provided one. + * + * @param pszPath the input path, this string is not altered. + * @param pszExt the new extension to apply to the given path. + * + * @return an altered filename with the new extension. Do not + * modify or free the returned string. The string may be destroyed by the + * next CPL call. + * + * @deprecated If using C++, prefer using CPLResetExtensionSafe() instead + */ + +const char *CPLResetExtension(const char *pszPath, const char *pszExt) + +{ + return CPLPathReturnTLSString(CPLResetExtensionSafe(pszPath, pszExt), + __FUNCTION__); +} + +/************************************************************************/ +/* CPLFormFilenameSafe() */ /************************************************************************/ /** @@ -574,11 +683,11 @@ const char *CPLResetExtension(const char *pszPath, const char *pszExt) * an extension if desired. * * \code{.cpp} - * CPLFormFilename("abc/xyz", "def", ".dat" ) == "abc/xyz/def.dat" - * CPLFormFilename(NULL,"def", NULL ) == "def" - * CPLFormFilename(NULL, "abc/def.dat", NULL ) == "abc/def.dat" - * CPLFormFilename("/abc/xyz/", "def.dat", NULL ) == "/abc/xyz/def.dat" - * CPLFormFilename("/a/b/c", "../d", NULL ) == "/a/b/d" (since 3.10.1) + * CPLFormFilenameSafe("abc/xyz", "def", ".dat" ) == "abc/xyz/def.dat" + * CPLFormFilenameSafe(NULL,"def", NULL ) == "def" + * CPLFormFilenameSafe(NULL, "abc/def.dat", NULL ) == "abc/def.dat" + * CPLFormFilenameSafe("/abc/xyz/", "def.dat", NULL ) == "/abc/xyz/def.dat" + * CPLFormFilenameSafe("/a/b/c", "../d", NULL ) == "/a/b/d" (since 3.10.1) * \endcode * * @param pszPath directory path to the directory containing the file. This @@ -591,24 +700,15 @@ const char *CPLResetExtension(const char *pszPath, const char *pszExt) * @param pszExtension file extension, optionally including the period. May * be NULL. * - * @return a fully formed filename in an internal static string. Do not - * modify or free the returned string. The string may be destroyed by the - * next CPL call. + * @return a fully formed filename. + * + * @since 3.11 */ -const char *CPLFormFilename(const char *pszPath, const char *pszBasename, - const char *pszExtension) +std::string CPLFormFilenameSafe(const char *pszPath, const char *pszBasename, + const char *pszExtension) { - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszPath >= pszStaticResult && - pszPath < pszStaticResult + CPL_PATH_BUF_SIZE)); - CPLAssert(!(pszBasename >= pszStaticResult && - pszBasename < pszStaticResult + CPL_PATH_BUF_SIZE)); - if (pszBasename[0] == '.' && (pszBasename[1] == '/' || pszBasename[1] == '\\')) pszBasename += 2; @@ -708,37 +808,68 @@ const char *CPLFormFilename(const char *pszPath, const char *pszBasename, else if (pszExtension[0] != '.' && strlen(pszExtension) > 0) pszAddedExtSep = "."; - if (nLenPath >= static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); + std::string osRes; + osRes.reserve(nLenPath + strlen(pszAddedPathSep) + strlen(pszBasename) + + strlen(pszAddedExtSep) + strlen(pszExtension) + + (nSuffixPos ? strlen(pszPath + nSuffixPos) : 0)); + osRes.assign(pszPath, nLenPath); + osRes += pszAddedPathSep; + osRes += pszBasename; + osRes += pszAddedExtSep; + osRes += pszExtension; - // coverity[overrun-buffer-arg] - memcpy(pszStaticResult, pszPath, nLenPath); - pszStaticResult[nLenPath] = 0; - - if (CPLStrlcat(pszStaticResult, pszAddedPathSep, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE) || - CPLStrlcat(pszStaticResult, pszBasename, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE) || - CPLStrlcat(pszStaticResult, pszAddedExtSep, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE) || - CPLStrlcat(pszStaticResult, pszExtension, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) + if (nSuffixPos) { - return CPLStaticBufferTooSmall(pszStaticResult); + osRes += (pszPath + nSuffixPos); } - if (nSuffixPos && - CPLStrlcat(pszStaticResult, pszPath + nSuffixPos, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) - { - return CPLStaticBufferTooSmall(pszStaticResult); - } + return osRes; +} - return pszStaticResult; +/************************************************************************/ +/* CPLFormFilename() */ +/************************************************************************/ + +/** + * Build a full file path from a passed path, file basename and extension. + * + * The path, and extension are optional. The basename may in fact contain + * an extension if desired. + * + * \code{.cpp} + * CPLFormFilename("abc/xyz", "def", ".dat" ) == "abc/xyz/def.dat" + * CPLFormFilename(NULL,"def", NULL ) == "def" + * CPLFormFilename(NULL, "abc/def.dat", NULL ) == "abc/def.dat" + * CPLFormFilename("/abc/xyz/", "def.dat", NULL ) == "/abc/xyz/def.dat" + * CPLFormFilename("/a/b/c", "../d", NULL ) == "/a/b/d" (since 3.10.1) + * \endcode + * + * @param pszPath directory path to the directory containing the file. This + * may be relative or absolute, and may have a trailing path separator or + * not. May be NULL. + * + * @param pszBasename file basename. May optionally have path and/or + * extension. Must *NOT* be NULL. + * + * @param pszExtension file extension, optionally including the period. May + * be NULL. + * + * @return a fully formed filename in an internal static string. Do not + * modify or free the returned string. The string may be destroyed by the + * next CPL call. + * + * @deprecated If using C++, prefer using CPLFormFilenameSafe() instead + */ +const char *CPLFormFilename(const char *pszPath, const char *pszBasename, + const char *pszExtension) + +{ + return CPLPathReturnTLSString( + CPLFormFilenameSafe(pszPath, pszBasename, pszExtension), __FUNCTION__); } /************************************************************************/ -/* CPLFormCIFilename() */ +/* CPLFormCIFilenameSafe() */ /************************************************************************/ /** @@ -760,18 +891,18 @@ const char *CPLFormFilename(const char *pszPath, const char *pszBasename, * @param pszExtension file extension, optionally including the period. May * be NULL. * - * @return a fully formed filename in an internal static string. Do not - * modify or free the returned string. The string may be destroyed by the - * next CPL call. + * @return a fully formed filename. + * + * @since 3.11 */ -const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename, - const char *pszExtension) +std::string CPLFormCIFilenameSafe(const char *pszPath, const char *pszBasename, + const char *pszExtension) { // On case insensitive filesystems, just default to CPLFormFilename(). if (!VSIIsCaseSensitiveFS(pszPath)) - return CPLFormFilename(pszPath, pszBasename, pszExtension); + return CPLFormFilenameSafe(pszPath, pszBasename, pszExtension); const char *pszAddedExtSep = ""; size_t nLen = strlen(pszBasename) + 2; @@ -791,9 +922,10 @@ const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename, snprintf(pszFilename, nLen, "%s%s%s", pszBasename, pszAddedExtSep, pszExtension); - const char *pszFullPath = CPLFormFilename(pszPath, pszFilename, nullptr); + std::string osRet = CPLFormFilenameSafe(pszPath, pszFilename, nullptr); VSIStatBufL sStatBuf; - int nStatRet = VSIStatExL(pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG); + int nStatRet = VSIStatExL(osRet.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG); + if (nStatRet != 0) { for (size_t i = 0; pszFilename[i] != '\0'; i++) @@ -801,12 +933,12 @@ const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename, pszFilename[i] = static_cast(CPLToupper(pszFilename[i])); } - const std::string osTmpPath( - CPLFormFilename(pszPath, pszFilename, nullptr)); + std::string osTmpPath( + CPLFormFilenameSafe(pszPath, pszFilename, nullptr)); nStatRet = VSIStatExL(osTmpPath.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG); if (nStatRet == 0) - pszFullPath = CPLFormFilename(pszPath, pszFilename, nullptr); + osRet = std::move(osTmpPath); } if (nStatRet != 0) @@ -817,20 +949,110 @@ const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename, CPLTolower(static_cast(pszFilename[i]))); } - const std::string osTmpPath( - CPLFormFilename(pszPath, pszFilename, nullptr)); + std::string osTmpPath( + CPLFormFilenameSafe(pszPath, pszFilename, nullptr)); nStatRet = VSIStatExL(osTmpPath.c_str(), &sStatBuf, VSI_STAT_EXISTS_FLAG); if (nStatRet == 0) - pszFullPath = CPLFormFilename(pszPath, pszFilename, nullptr); + osRet = std::move(osTmpPath); } if (nStatRet != 0) - pszFullPath = CPLFormFilename(pszPath, pszBasename, pszExtension); + osRet = CPLFormFilenameSafe(pszPath, pszBasename, pszExtension); CPLFree(pszFilename); - return pszFullPath; + return osRet; +} + +/************************************************************************/ +/* CPLFormCIFilename() */ +/************************************************************************/ + +/** + * Case insensitive file searching, returning full path. + * + * This function tries to return the path to a file regardless of + * whether the file exactly matches the basename, and extension case, or + * is all upper case, or all lower case. The path is treated as case + * sensitive. This function is equivalent to CPLFormFilename() on + * case insensitive file systems (like Windows). + * + * @param pszPath directory path to the directory containing the file. This + * may be relative or absolute, and may have a trailing path separator or + * not. May be NULL. + * + * @param pszBasename file basename. May optionally have path and/or + * extension. May not be NULL. + * + * @param pszExtension file extension, optionally including the period. May + * be NULL. + * + * @return a fully formed filename in an internal static string. Do not + * modify or free the returned string. The string may be destroyed by the + * next CPL call. + * + * @deprecated If using C++, prefer using CPLFormCIFilenameSafe() instead +*/ + +const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename, + const char *pszExtension) + +{ + return CPLPathReturnTLSString( + CPLFormCIFilenameSafe(pszPath, pszBasename, pszExtension), + __FUNCTION__); +} + +/************************************************************************/ +/* CPLProjectRelativeFilenameSafe() */ +/************************************************************************/ + +/** + * Find a file relative to a project file. + * + * Given the path to a "project" directory, and a path to a secondary file + * referenced from that project, build a path to the secondary file + * that the current application can use. If the secondary path is already + * absolute, rather than relative, then it will be returned unaltered. + * + * Examples: + * \code{.cpp} + * CPLProjectRelativeFilenameSafe("abc/def", "tmp/abc.gif") == "abc/def/tmp/abc.gif" + * CPLProjectRelativeFilenameSafe("abc/def", "/tmp/abc.gif") == "/tmp/abc.gif" + * CPLProjectRelativeFilenameSafe("/xy", "abc.gif") == "/xy/abc.gif" + * CPLProjectRelativeFilenameSafe("/abc/def", "../abc.gif") == "/abc/def/../abc.gif" + * CPLProjectRelativeFilenameSafe("C:\WIN", "abc.gif") == "C:\WIN\abc.gif" + * \endcode + * + * @param pszProjectDir the directory relative to which the secondary files + * path should be interpreted. + * @param pszSecondaryFilename the filename (potentially with path) that + * is to be interpreted relative to the project directory. + * + * @return a composed path to the secondary file. + * + * @since 3.11 + */ + +std::string CPLProjectRelativeFilenameSafe(const char *pszProjectDir, + const char *pszSecondaryFilename) + +{ + if (pszProjectDir == nullptr || pszProjectDir[0] == 0 || + !CPLIsFilenameRelative(pszSecondaryFilename)) + { + return pszSecondaryFilename; + } + + std::string osRes(pszProjectDir); + if (osRes.back() != '/' && osRes.back() != '\\') + { + osRes += VSIGetDirectorySeparator(pszProjectDir); + } + + osRes += pszSecondaryFilename; + return osRes; } /************************************************************************/ @@ -862,45 +1084,17 @@ const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename, * @return a composed path to the secondary file. The returned string is * internal and should not be altered, freed, or depending on past the next * CPL call. + * + * @deprecated If using C++, prefer using CPLProjectRelativeFilenameSafe() instead */ const char *CPLProjectRelativeFilename(const char *pszProjectDir, const char *pszSecondaryFilename) { - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLAssert(!(pszProjectDir >= pszStaticResult && - pszProjectDir < pszStaticResult + CPL_PATH_BUF_SIZE)); - CPLAssert(!(pszSecondaryFilename >= pszStaticResult && - pszSecondaryFilename < pszStaticResult + CPL_PATH_BUF_SIZE)); - - if (!CPLIsFilenameRelative(pszSecondaryFilename)) - return pszSecondaryFilename; - - if (pszProjectDir == nullptr || strlen(pszProjectDir) == 0) - return pszSecondaryFilename; - - if (CPLStrlcpy(pszStaticResult, pszProjectDir, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); - - if (pszProjectDir[strlen(pszProjectDir) - 1] != '/' && - pszProjectDir[strlen(pszProjectDir) - 1] != '\\') - { - const char *pszAddedPathSep = VSIGetDirectorySeparator(pszProjectDir); - if (CPLStrlcat(pszStaticResult, pszAddedPathSep, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); - } - - if (CPLStrlcat(pszStaticResult, pszSecondaryFilename, CPL_PATH_BUF_SIZE) >= - static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); - - return pszStaticResult; + return CPLPathReturnTLSString( + CPLProjectRelativeFilenameSafe(pszProjectDir, pszSecondaryFilename), + __FUNCTION__); } /************************************************************************/ @@ -1026,6 +1220,41 @@ const char *CPLExtractRelativePath(const char *pszBaseDir, return pszTarget + nBasePathLen + 1; } +/************************************************************************/ +/* CPLCleanTrailingSlashSafe() */ +/************************************************************************/ + +/** + * Remove trailing forward/backward slash from the path for UNIX/Windows resp. + * + * Returns a string containing the portion of the passed path string with + * trailing slash removed. If there is no path in the passed filename + * an empty string will be returned (not NULL). + * + * \code{.cpp} + * CPLCleanTrailingSlashSafe( "abc/def/" ) == "abc/def" + * CPLCleanTrailingSlashSafe( "abc/def" ) == "abc/def" + * CPLCleanTrailingSlashSafe( "c:\\abc\\def\\" ) == "c:\\abc\\def" + * CPLCleanTrailingSlashSafe( "c:\\abc\\def" ) == "c:\\abc\\def" + * CPLCleanTrailingSlashSafe( "abc" ) == "abc" + * \endcode + * + * @param pszPath the path to be cleaned up + * + * @return Path + * + * @since 3.11 + */ + +std::string CPLCleanTrailingSlashSafe(const char *pszPath) + +{ + std::string osRes(pszPath); + if (!osRes.empty() && (osRes.back() == '\\' || osRes.back() == '/')) + osRes.pop_back(); + return osRes; +} + /************************************************************************/ /* CPLCleanTrailingSlash() */ /************************************************************************/ @@ -1049,28 +1278,15 @@ const char *CPLExtractRelativePath(const char *pszBaseDir, * * @return Path in an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. + * + * @deprecated If using C++, prefer using CPLCleanTrailingSlashSafe() instead */ const char *CPLCleanTrailingSlash(const char *pszPath) { - char *pszStaticResult = CPLGetStaticResult(); - if (pszStaticResult == nullptr) - return CPLStaticBufferTooSmall(pszStaticResult); - CPLAssert(!(pszPath >= pszStaticResult && - pszPath < pszStaticResult + CPL_PATH_BUF_SIZE)); - - const size_t iPathLength = strlen(pszPath); - if (iPathLength >= static_cast(CPL_PATH_BUF_SIZE)) - return CPLStaticBufferTooSmall(pszStaticResult); - - CPLStrlcpy(pszStaticResult, pszPath, iPathLength + 1); - - if (iPathLength > 0 && (pszStaticResult[iPathLength - 1] == '\\' || - pszStaticResult[iPathLength - 1] == '/')) - pszStaticResult[iPathLength - 1] = '\0'; - - return pszStaticResult; + return CPLPathReturnTLSString(CPLCleanTrailingSlashSafe(pszPath), + __FUNCTION__); } /************************************************************************/ @@ -1118,9 +1334,9 @@ char **CPLCorrespondingPaths(const char *pszOldFilename, return CSLAddString(nullptr, pszNewFilename); } - const CPLString osOldPath = CPLGetPath(pszOldFilename); - const CPLString osOldBasename = CPLGetBasename(pszOldFilename); - const CPLString osNewBasename = CPLGetBasename(pszNewFilename); + const std::string osOldPath = CPLGetPathSafe(pszOldFilename); + const std::string osOldBasename = CPLGetBasenameSafe(pszOldFilename); + const std::string osNewBasename = CPLGetBasenameSafe(pszNewFilename); /* -------------------------------------------------------------------- */ /* If the basename is changing, verify that all source files */ @@ -1130,14 +1346,15 @@ char **CPLCorrespondingPaths(const char *pszOldFilename, { for (int i = 0; papszFileList[i] != nullptr; i++) { - if (osOldBasename == CPLGetBasename(papszFileList[i])) + if (osOldBasename == CPLGetBasenameSafe(papszFileList[i])) continue; - const CPLString osFilePath = CPLGetPath(papszFileList[i]); - const CPLString osFileName = CPLGetFilename(papszFileList[i]); + const std::string osFilePath = CPLGetPathSafe(papszFileList[i]); + const std::string osFileName = CPLGetFilename(papszFileList[i]); - if (!EQUALN(osFileName, osOldBasename, osOldBasename.size()) || - !EQUAL(osFilePath, osOldPath) || + if (!EQUALN(osFileName.c_str(), osOldBasename.c_str(), + osOldBasename.size()) || + !EQUAL(osFilePath.c_str(), osOldPath.c_str()) || osFileName[osOldBasename.size()] != '.') { CPLError(CE_Failure, CPLE_AppDefined, @@ -1153,9 +1370,9 @@ char **CPLCorrespondingPaths(const char *pszOldFilename, /* -------------------------------------------------------------------- */ if (osOldBasename != osNewBasename) { - const CPLString osOldExtra = + const std::string osOldExtra = CPLGetFilename(pszOldFilename) + osOldBasename.size(); - const CPLString osNewExtra = + const std::string osNewExtra = CPLGetFilename(pszNewFilename) + osNewBasename.size(); if (osOldExtra != osNewExtra) @@ -1171,26 +1388,28 @@ char **CPLCorrespondingPaths(const char *pszOldFilename, /* Generate the new filenames. */ /* -------------------------------------------------------------------- */ char **papszNewList = nullptr; - const CPLString osNewPath = CPLGetPath(pszNewFilename); + const std::string osNewPath = CPLGetPathSafe(pszNewFilename); for (int i = 0; papszFileList[i] != nullptr; i++) { - const CPLString osOldFilename = CPLGetFilename(papszFileList[i]); + const std::string osOldFilename = CPLGetFilename(papszFileList[i]); - const CPLString osNewFilename = + const std::string osNewFilename = osOldBasename == osNewBasename - ? CPLFormFilename(osNewPath, osOldFilename, nullptr) - : CPLFormFilename(osNewPath, osNewBasename, - osOldFilename.c_str() + osOldBasename.size()); + ? CPLFormFilenameSafe(osNewPath.c_str(), osOldFilename.c_str(), + nullptr) + : CPLFormFilenameSafe(osNewPath.c_str(), osNewBasename.c_str(), + osOldFilename.c_str() + + osOldBasename.size()); - papszNewList = CSLAddString(papszNewList, osNewFilename); + papszNewList = CSLAddString(papszNewList, osNewFilename.c_str()); } return papszNewList; } /************************************************************************/ -/* CPLGenerateTempFilename() */ +/* CPLGenerateTempFilenameSafe() */ /************************************************************************/ /** @@ -1202,10 +1421,12 @@ char **CPLCorrespondingPaths(const char *pszOldFilename, * * @param pszStem if non-NULL this will be part of the filename. * - * @return a filename which is valid till the next CPL call in this thread. + * @return a filename + * + * @since 3.11 */ -const char *CPLGenerateTempFilename(const char *pszStem) +std::string CPLGenerateTempFilenameSafe(const char *pszStem) { const char *pszDir = CPLGetConfigOption("CPL_TMPDIR", nullptr); @@ -1227,11 +1448,36 @@ const char *CPLGenerateTempFilename(const char *pszStem) osFilename.Printf("%s_%d_%d", pszStem, CPLGetCurrentProcessID(), CPLAtomicInc(&nTempFileCounter)); - return CPLFormFilename(pszDir, osFilename, nullptr); + return CPLFormFilenameSafe(pszDir, osFilename.c_str(), nullptr); } /************************************************************************/ -/* CPLExpandTilde() */ +/* CPLGenerateTempFilename() */ +/************************************************************************/ + +/** + * Generate temporary file name. + * + * Returns a filename that may be used for a temporary file. The location + * of the file tries to follow operating system semantics but may be + * forced via the CPL_TMPDIR configuration option. + * + * @param pszStem if non-NULL this will be part of the filename. + * + * @return a filename which is valid till the next CPL call in this thread. + * + * @deprecated If using C++, prefer using CPLCleanTrailingSlashSafe() instead + */ + +const char *CPLGenerateTempFilename(const char *pszStem) + +{ + return CPLPathReturnTLSString(CPLGenerateTempFilenameSafe(pszStem), + __FUNCTION__); +} + +/************************************************************************/ +/* CPLExpandTildeSafe() */ /************************************************************************/ /** @@ -1243,10 +1489,10 @@ const char *CPLGenerateTempFilename(const char *pszStem) * * @return an expanded filename. * - * @since GDAL 2.2 + * @since GDAL 3.11 */ -const char *CPLExpandTilde(const char *pszFilename) +std::string CPLExpandTildeSafe(const char *pszFilename) { if (!STARTS_WITH_CI(pszFilename, "~/")) @@ -1256,7 +1502,32 @@ const char *CPLExpandTilde(const char *pszFilename) if (pszHome == nullptr) return pszFilename; - return CPLFormFilename(pszHome, pszFilename + 2, nullptr); + return CPLFormFilenameSafe(pszHome, pszFilename + 2, nullptr); +} + +/************************************************************************/ +/* CPLExpandTilde() */ +/************************************************************************/ + +/** + * Expands ~/ at start of filename. + * + * Assumes that the HOME configuration option is defined. + * + * @param pszFilename filename potentially starting with ~/ + * + * @return an expanded filename. + * + * @since GDAL 2.2 + * + * @deprecated If using C++, prefer using CPLExpandTildeSafe() instead + */ + +const char *CPLExpandTilde(const char *pszFilename) + +{ + return CPLPathReturnTLSString(CPLExpandTildeSafe(pszFilename), + __FUNCTION__); } /************************************************************************/ @@ -1285,7 +1556,7 @@ const char *CPLGetHomeDir() } /************************************************************************/ -/* CPLLaunderForFilename() */ +/* CPLLaunderForFilenameSafe() */ /************************************************************************/ /** @@ -1296,11 +1567,11 @@ const char *CPLGetHomeDir() * Unused for now. May be NULL. * @return the laundered name. * - * @since GDAL 3.1 + * @since GDAL 3.11 */ -const char *CPLLaunderForFilename(const char *pszName, - CPL_UNUSED const char *pszOutputPath) +std::string CPLLaunderForFilenameSafe(const char *pszName, + CPL_UNUSED const char *pszOutputPath) { std::string osRet(pszName); for (char &ch : osRet) @@ -1312,5 +1583,29 @@ const char *CPLLaunderForFilename(const char *pszName, ch = '_'; } } - return CPLSPrintf("%s", osRet.c_str()); + return osRet; +} + +/************************************************************************/ +/* CPLLaunderForFilename() */ +/************************************************************************/ + +/** + * Launder a string to be compatible of a filename. + * + * @param pszName The input string to launder. + * @param pszOutputPath The directory where the file would be created. + * Unused for now. May be NULL. + * @return the laundered name. + * + * @since GDAL 3.1 + * + * @deprecated If using C++, prefer using CPLLaunderForFilenameSafe() instead + */ + +const char *CPLLaunderForFilename(const char *pszName, + const char *pszOutputPath) +{ + return CPLPathReturnTLSString( + CPLLaunderForFilenameSafe(pszName, pszOutputPath), __FUNCTION__); } diff --git a/port/cpl_vsi_mem.cpp b/port/cpl_vsi_mem.cpp index 0092de0b05bd..7394f5580604 100644 --- a/port/cpl_vsi_mem.cpp +++ b/port/cpl_vsi_mem.cpp @@ -193,7 +193,7 @@ class VSIMemFilesystemHandler final : public VSIFilesystemHandler CPL_DISALLOW_COPY_ASSIGN(VSIMemFilesystemHandler) public: - std::map> oFileList{}; + std::map> oFileList{}; CPLMutex *hMutex = nullptr; explicit VSIMemFilesystemHandler(const char *pszPrefix) @@ -631,7 +631,7 @@ VSIVirtualHandle *VSIMemFilesystemHandler::Open(const char *pszFilename, { CPLMutexHolder oHolder(&hMutex); - const CPLString osFilename = NormalizePath(pszFilename); + const std::string osFilename = NormalizePath(pszFilename); if (osFilename.empty()) return nullptr; @@ -647,9 +647,10 @@ VSIVirtualHandle *VSIMemFilesystemHandler::Open(const char *pszFilename, /* Get the filename we are opening, create if needed. */ /* -------------------------------------------------------------------- */ std::shared_ptr poFile = nullptr; - if (oFileList.find(osFilename) != oFileList.end()) + const auto oIter = oFileList.find(osFilename); + if (oIter != oFileList.end()) { - poFile = oFileList[osFilename]; + poFile = oIter->second; } // If no file and opening in read, error out. @@ -667,14 +668,14 @@ VSIVirtualHandle *VSIMemFilesystemHandler::Open(const char *pszFilename, // Create. if (poFile == nullptr) { - const char *pszFileDir = CPLGetPath(osFilename.c_str()); - if (VSIMkdirRecursive(pszFileDir, 0755) == -1) + const std::string osFileDir = CPLGetPathSafe(osFilename.c_str()); + if (VSIMkdirRecursive(osFileDir.c_str(), 0755) == -1) { if (bSetError) { VSIError(VSIE_FileError, "Could not create directory %s for writing", - pszFileDir); + osFileDir.c_str()); } errno = ENOENT; return nullptr; @@ -742,11 +743,11 @@ int VSIMemFilesystemHandler::Stat(const char *pszFilename, { CPLMutexHolder oHolder(&hMutex); - const CPLString osFilename = NormalizePath(pszFilename); + const std::string osFilename = NormalizePath(pszFilename); memset(pStatBuf, 0, sizeof(VSIStatBufL)); - if (osFilename + '/' == m_osPrefix || osFilename == m_osPrefix) + if (osFilename == m_osPrefix || osFilename + '/' == m_osPrefix) { pStatBuf->st_size = 0; pStatBuf->st_mode = S_IFDIR; @@ -798,7 +799,7 @@ int VSIMemFilesystemHandler::Unlink(const char *pszFilename) int VSIMemFilesystemHandler::Unlink_unlocked(const char *pszFilename) { - const CPLString osFilename = NormalizePath(pszFilename); + const std::string osFilename = NormalizePath(pszFilename); auto oIter = oFileList.find(osFilename); if (oIter == oFileList.end()) @@ -826,7 +827,7 @@ int VSIMemFilesystemHandler::Mkdir(const char *pszPathname, long /* nMode */) { CPLMutexHolder oHolder(&hMutex); - const CPLString osPathname = NormalizePath(pszPathname); + const std::string osPathname = NormalizePath(pszPathname); if (STARTS_WITH(osPathname.c_str(), szHIDDEN_DIRNAME)) { if (osPathname.size() == strlen(szHIDDEN_DIRNAME)) @@ -1042,8 +1043,8 @@ int VSIMemFilesystemHandler::Rename(const char *pszOldPath, { CPLMutexHolder oHolder(&hMutex); - const CPLString osOldPath = NormalizePath(pszOldPath); - const CPLString osNewPath = NormalizePath(pszNewPath); + const std::string osOldPath = NormalizePath(pszOldPath); + const std::string osNewPath = NormalizePath(pszNewPath); if (!STARTS_WITH(pszNewPath, m_osPrefix.c_str())) return -1; @@ -1056,15 +1057,15 @@ int VSIMemFilesystemHandler::Rename(const char *pszOldPath, return -1; } - std::map>::iterator it = + std::map>::iterator it = oFileList.find(osOldPath); - while (it != oFileList.end() && it->first.ifind(osOldPath) == 0) + while (it != oFileList.end() && it->first.find(osOldPath) == 0) { - const CPLString osRemainder = it->first.substr(osOldPath.size()); + const std::string osRemainder = it->first.substr(osOldPath.size()); if (osRemainder.empty() || osRemainder[0] == '/') { - const CPLString osNewFullPath = osNewPath + osRemainder; - Unlink_unlocked(osNewFullPath); + const std::string osNewFullPath = osNewPath + osRemainder; + Unlink_unlocked(osNewFullPath.c_str()); oFileList[osNewFullPath] = it->second; it->second->osFilename = osNewFullPath; oFileList.erase(it++); @@ -1223,11 +1224,12 @@ VSILFILE *VSIFileFromMemBuffer(const char *pszFilename, GByte *pabyData, // ownership of pabyData. if (!osFilename.empty()) { - const char *pszFileDir = CPLGetPath(osFilename.c_str()); - if (VSIMkdirRecursive(pszFileDir, 0755) == -1) + const std::string osFileDir = CPLGetPathSafe(osFilename.c_str()); + if (VSIMkdirRecursive(osFileDir.c_str(), 0755) == -1) { VSIError(VSIE_FileError, - "Could not create directory %s for writing", pszFileDir); + "Could not create directory %s for writing", + osFileDir.c_str()); errno = ENOENT; return nullptr; } @@ -1293,7 +1295,7 @@ GByte *VSIGetMemFileBuffer(const char *pszFilename, vsi_l_offset *pnDataLength, if (pszFilename == nullptr) return nullptr; - const CPLString osFilename = + const std::string osFilename = VSIMemFilesystemHandler::NormalizePath(pszFilename); CPLMutexHolder oHolder(&poHandler->hMutex); diff --git a/port/cpl_vsil.cpp b/port/cpl_vsil.cpp index 7d96ee033dda..b705a749a839 100644 --- a/port/cpl_vsil.cpp +++ b/port/cpl_vsil.cpp @@ -659,7 +659,7 @@ int VSIMkdirRecursive(const char *pszPathname, long mode) { return VSI_ISDIR(sStat.st_mode) ? 0 : -1; } - const CPLString osParentPath(CPLGetPath(osPathname)); + const std::string osParentPath(CPLGetPathSafe(osPathname)); // Prevent crazy paths from recursing forever. if (osParentPath == osPathname || @@ -668,9 +668,9 @@ int VSIMkdirRecursive(const char *pszPathname, long mode) return -1; } - if (VSIStatL(osParentPath, &sStat) != 0) + if (VSIStatL(osParentPath.c_str(), &sStat) != 0) { - if (VSIMkdirRecursive(osParentPath, mode) != 0) + if (VSIMkdirRecursive(osParentPath.c_str(), mode) != 0) return -1; } @@ -2087,18 +2087,18 @@ bool VSIFilesystemHandler::Sync(const char *pszSource, const char *pszTarget, if (VSI_ISDIR(sSource.st_mode)) { - CPLString osTargetDir(pszTarget); + std::string osTargetDir(pszTarget); if (osSource.back() != '/' && osSource.back() != '\\') { - osTargetDir = CPLFormFilename(osTargetDir, - CPLGetFilename(pszSource), nullptr); + osTargetDir = CPLFormFilenameSafe( + osTargetDir.c_str(), CPLGetFilename(pszSource), nullptr); } VSIStatBufL sTarget; bool ret = true; - if (VSIStatL(osTargetDir, &sTarget) < 0) + if (VSIStatL(osTargetDir.c_str(), &sTarget) < 0) { - if (VSIMkdirRecursive(osTargetDir, 0755) < 0) + if (VSIMkdirRecursive(osTargetDir.c_str(), 0755) < 0) { CPLError(CE_Failure, CPLE_FileIO, "Cannot create directory %s", osTargetDir.c_str()); @@ -2131,17 +2131,17 @@ bool VSIFilesystemHandler::Sync(const char *pszSource, const char *pszTarget, { continue; } - CPLString osSubSource( - CPLFormFilename(osSourceWithoutSlash, *iter, nullptr)); - CPLString osSubTarget( - CPLFormFilename(osTargetDir, *iter, nullptr)); + const std::string osSubSource(CPLFormFilenameSafe( + osSourceWithoutSlash.c_str(), *iter, nullptr)); + const std::string osSubTarget( + CPLFormFilenameSafe(osTargetDir.c_str(), *iter, nullptr)); // coverity[divide_by_zero] void *pScaledProgress = GDALCreateScaledProgress( double(iFile) / nFileCount, double(iFile + 1) / nFileCount, pProgressFunc, pProgressData); - ret = Sync((osSubSource + SOURCE_SEP).c_str(), osSubTarget, - aosChildOptions.List(), GDALScaledProgress, - pScaledProgress, nullptr); + ret = Sync((osSubSource + SOURCE_SEP).c_str(), + osSubTarget.c_str(), aosChildOptions.List(), + GDALScaledProgress, pScaledProgress, nullptr); GDALDestroyScaledProgress(pScaledProgress); if (!ret) { @@ -2154,15 +2154,15 @@ bool VSIFilesystemHandler::Sync(const char *pszSource, const char *pszTarget, } VSIStatBufL sTarget; - CPLString osTarget(pszTarget); - if (VSIStatL(osTarget, &sTarget) == 0) + std::string osTarget(pszTarget); + if (VSIStatL(osTarget.c_str(), &sTarget) == 0) { bool bTargetIsFile = true; if (VSI_ISDIR(sTarget.st_mode)) { - osTarget = - CPLFormFilename(osTarget, CPLGetFilename(pszSource), nullptr); - bTargetIsFile = VSIStatL(osTarget, &sTarget) == 0 && + osTarget = CPLFormFilenameSafe(osTarget.c_str(), + CPLGetFilename(pszSource), nullptr); + bTargetIsFile = VSIStatL(osTarget.c_str(), &sTarget) == 0 && !CPL_TO_BOOL(VSI_ISDIR(sTarget.st_mode)); } if (bTargetIsFile) diff --git a/port/cpl_vsil_abstract_archive.cpp b/port/cpl_vsil_abstract_archive.cpp index 5b1e9a577574..e10736b2fe74 100644 --- a/port/cpl_vsil_abstract_archive.cpp +++ b/port/cpl_vsil_abstract_archive.cpp @@ -452,12 +452,7 @@ char *VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename, const std::vector oExtensions = GetExtensions(); int nAttempts = 0; - // If we are called with pszFilename being one of the TLS buffers returned - // by cpl_path.cpp functions, then a call to Stat() in the loop (and its - // cascaded calls to other cpl_path.cpp functions) might lead to altering - // the buffer to be altered, hence take a copy - const std::string osFilenameCopy(pszFilename); - while (i < static_cast(osFilenameCopy.size())) + while (pszFilename[i]) { int nToSkip = 0; @@ -465,7 +460,7 @@ char *VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename, iter != oExtensions.end(); ++iter) { const CPLString &osExtension = *iter; - if (EQUALN(osFilenameCopy.c_str() + i, osExtension.c_str(), + if (EQUALN(pszFilename + i, osExtension.c_str(), osExtension.size())) { nToSkip = static_cast(osExtension.size()); @@ -475,8 +470,7 @@ char *VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename, #ifdef DEBUG // For AFL, so that .cur_input is detected as the archive filename. - if (EQUALN(osFilenameCopy.c_str() + i, ".cur_input", - strlen(".cur_input"))) + if (EQUALN(pszFilename + i, ".cur_input", strlen(".cur_input"))) { nToSkip = static_cast(strlen(".cur_input")); } @@ -492,7 +486,7 @@ char *VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename, break; } VSIStatBufL statBuf; - char *archiveFilename = CPLStrdup(osFilenameCopy.c_str()); + char *archiveFilename = CPLStrdup(pszFilename); bool bArchiveFileExists = false; if (IsEitherSlash(archiveFilename[i + nToSkip])) @@ -533,11 +527,10 @@ char *VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename, if (bArchiveFileExists) { - if (IsEitherSlash(osFilenameCopy[i + nToSkip]) && - i + nToSkip + 1 < static_cast(osFilenameCopy.size())) + if (IsEitherSlash(pszFilename[i + nToSkip])) { - osFileInArchive = CompactFilename(osFilenameCopy.c_str() + - i + nToSkip + 1); + osFileInArchive = + CompactFilename(pszFilename + i + nToSkip + 1); } else { @@ -549,25 +542,15 @@ char *VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename, { const char lastC = osFileInArchive.back(); if (IsEitherSlash(lastC)) - osFileInArchive.pop_back(); + osFileInArchive.resize(osFileInArchive.size() - 1); } - // Messy! Restore the TLS buffer if it has been altered - if (osFilenameCopy != pszFilename) - strcpy(const_cast(pszFilename), - osFilenameCopy.c_str()); - return archiveFilename; } CPLFree(archiveFilename); } i++; } - - // Messy! Restore the TLS buffer if it has been altered - if (osFilenameCopy != pszFilename) - strcpy(const_cast(pszFilename), osFilenameCopy.c_str()); - return nullptr; } diff --git a/port/cpl_vsil_adls.cpp b/port/cpl_vsil_adls.cpp index 5039e295810b..723ee36ed795 100644 --- a/port/cpl_vsil_adls.cpp +++ b/port/cpl_vsil_adls.cpp @@ -1186,7 +1186,8 @@ void VSIADLSWriteHandle::InvalidateParentDirectory() m_poFS->InvalidateCachedData(m_poHandleHelper->GetURLNoKVP().c_str()); const std::string osFilenameWithoutSlash(RemoveTrailingSlash(m_osFilename)); - m_poFS->InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + m_poFS->InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } /************************************************************************/ @@ -1316,7 +1317,7 @@ int VSIADLSFSHandler::Rename(const char *oldpath, const char *newpath) InvalidateCachedData(GetURLFromFilename(oldpath).c_str()); InvalidateCachedData(GetURLFromFilename(newpath).c_str()); - InvalidateDirContent(CPLGetDirname(oldpath)); + InvalidateDirContent(CPLGetDirnameSafe(oldpath)); const CPLStringList aosHTTPOptions(CPLHTTPGetOptionsFromEnv(oldpath)); const CPLHTTPRetryParameters oRetryParameters(aosHTTPOptions); @@ -1443,7 +1444,7 @@ int VSIADLSFSHandler::MkdirInternal(const char *pszDirname, long nMode, InvalidateCachedData(GetURLFromFilename(osDirname.c_str()).c_str()); InvalidateCachedData( GetURLFromFilename(osDirnameWithoutEndSlash.c_str()).c_str()); - InvalidateDirContent(CPLGetDirname(osDirnameWithoutEndSlash.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(osDirnameWithoutEndSlash.c_str())); int nRet = 0; @@ -1591,7 +1592,7 @@ int VSIADLSFSHandler::RmdirInternal(const char *pszDirname, bool bRecursive) InvalidateCachedData(GetURLFromFilename(osDirname.c_str()).c_str()); InvalidateCachedData( GetURLFromFilename(osDirnameWithoutEndSlash.c_str()).c_str()); - InvalidateDirContent(CPLGetDirname(osDirnameWithoutEndSlash.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(osDirnameWithoutEndSlash.c_str())); if (bRecursive) { PartialClearCache(osDirnameWithoutEndSlash.c_str()); @@ -1831,7 +1832,8 @@ int VSIADLSFSHandler::CopyObject(const char *oldpath, const char *newpath, const std::string osFilenameWithoutSlash( RemoveTrailingSlash(newpath)); - InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } curl_easy_cleanup(hCurlHandle); @@ -1857,7 +1859,7 @@ bool VSIADLSFSHandler::UploadFile( if (event == Event::CREATE_FILE) { InvalidateCachedData(poHandleHelper->GetURLNoKVP().c_str()); - InvalidateDirContent(CPLGetDirname(osFilename.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(osFilename.c_str())); } const CPLStringList aosHTTPOptions( diff --git a/port/cpl_vsil_az.cpp b/port/cpl_vsil_az.cpp index 1b115a9430a3..fdfaa2d69d85 100644 --- a/port/cpl_vsil_az.cpp +++ b/port/cpl_vsil_az.cpp @@ -1241,7 +1241,8 @@ void VSIAzureWriteHandle::InvalidateParentDirectory() std::string osFilenameWithoutSlash(m_osFilename); if (!osFilenameWithoutSlash.empty() && osFilenameWithoutSlash.back() == '/') osFilenameWithoutSlash.pop_back(); - m_poFS->InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + m_poFS->InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } /************************************************************************/ @@ -1456,7 +1457,7 @@ void VSIAzureFSHandler::InvalidateRecursive(const std::string &osDirnameIn) { InvalidateDirContent(osDirname.c_str()); InvalidateCachedData(GetURLFromFilename(osDirname.c_str()).c_str()); - osDirname = CPLGetDirname(osDirname.c_str()); + osDirname = CPLGetDirnameSafe(osDirname.c_str()); } } @@ -1470,7 +1471,7 @@ int VSIAzureFSHandler::Unlink(const char *pszFilename) if (ret != 0) return ret; - InvalidateRecursive(CPLGetDirname(pszFilename)); + InvalidateRecursive(CPLGetDirnameSafe(pszFilename)); return 0; } @@ -1736,7 +1737,7 @@ int VSIAzureFSHandler::MkdirInternal(const char *pszDirname, long /* nMode */, InvalidateCachedData(GetURLFromFilename(osDirname.c_str()).c_str()); InvalidateCachedData( GetURLFromFilename(osDirnameWithoutEndSlash.c_str()).c_str()); - InvalidateDirContent(CPLGetDirname(osDirnameWithoutEndSlash.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(osDirnameWithoutEndSlash.c_str())); VSILFILE *fp = VSIFOpenL((osDirname + GDAL_MARKER_FOR_DIR).c_str(), "wb"); if (fp != nullptr) @@ -1898,7 +1899,7 @@ int VSIAzureFSHandler::Rmdir(const char *pszDirname) InvalidateCachedData(GetURLFromFilename(osDirname.c_str()).c_str()); InvalidateCachedData( GetURLFromFilename(osDirnameWithoutEndSlash.c_str()).c_str()); - InvalidateRecursive(CPLGetDirname(osDirnameWithoutEndSlash.c_str())); + InvalidateRecursive(CPLGetDirnameSafe(osDirnameWithoutEndSlash.c_str())); if (osDirnameWithoutEndSlash.find('/', GetFSPrefix().size()) == std::string::npos) { @@ -2168,7 +2169,8 @@ int VSIAzureFSHandler::CopyObject(const char *oldpath, const char *newpath, osFilenameWithoutSlash.resize(osFilenameWithoutSlash.size() - 1); - InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } curl_easy_cleanup(hCurlHandle); diff --git a/port/cpl_vsil_chunked_write_handle.cpp b/port/cpl_vsil_chunked_write_handle.cpp index 2d21f91013eb..41d498d7915a 100644 --- a/port/cpl_vsil_chunked_write_handle.cpp +++ b/port/cpl_vsil_chunked_write_handle.cpp @@ -91,7 +91,8 @@ void VSIChunkedWriteHandle::InvalidateParentDirectory() std::string osFilenameWithoutSlash(m_osFilename); if (!osFilenameWithoutSlash.empty() && osFilenameWithoutSlash.back() == '/') osFilenameWithoutSlash.pop_back(); - m_poFS->InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + m_poFS->InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } /************************************************************************/ diff --git a/port/cpl_vsil_curl.cpp b/port/cpl_vsil_curl.cpp index 9ea17cabf2c0..78d876fd6b4a 100644 --- a/port/cpl_vsil_curl.cpp +++ b/port/cpl_vsil_curl.cpp @@ -518,7 +518,7 @@ VSICurlHandle::~VSICurlHandle() if (!m_bCached) { poFS->InvalidateCachedData(m_pszURL); - poFS->InvalidateDirContent(CPLGetDirname(m_osFilename.c_str())); + poFS->InvalidateDirContent(CPLGetDirnameSafe(m_osFilename.c_str())); } CPLFree(m_pszURL); } @@ -4285,11 +4285,11 @@ VSIVirtualHandle *VSICurlFilesystemHandlerBase::Open(const char *pszFilename, cachedFileProp) && cachedFileProp.eExists == EXIST_YES) && strchr(CPLGetFilename(osFilename.c_str()), '.') != nullptr && - !STARTS_WITH(CPLGetExtension(osFilename.c_str()), "zip") && + !STARTS_WITH(CPLGetExtensionSafe(osFilename.c_str()).c_str(), "zip") && !bSkipReadDir) { char **papszFileList = ReadDirInternal( - (std::string(CPLGetDirname(osFilename.c_str())) + '/').c_str(), 0, + (CPLGetDirnameSafe(osFilename.c_str()) + '/').c_str(), 0, &bGotFileList); const bool bFound = VSICurlIsFileInList(papszFileList, @@ -5304,13 +5304,14 @@ int VSICurlFilesystemHandlerBase::Stat(const char *pszFilename, return -1; } else if (strchr(CPLGetFilename(osFilename.c_str()), '.') != nullptr && - !STARTS_WITH_CI(CPLGetExtension(osFilename.c_str()), "zip") && + !STARTS_WITH_CI(CPLGetExtensionSafe(osFilename.c_str()).c_str(), + "zip") && strstr(osFilename.c_str(), ".zip.") != nullptr && strstr(osFilename.c_str(), ".ZIP.") != nullptr && !bSkipReadDir) { bool bGotFileList = false; char **papszFileList = ReadDirInternal( - CPLGetDirname(osFilename.c_str()), 0, &bGotFileList); + CPLGetDirnameSafe(osFilename.c_str()).c_str(), 0, &bGotFileList); const bool bFound = VSICurlIsFileInList(papszFileList, CPLGetFilename(osFilename.c_str())) != -1; @@ -5481,15 +5482,16 @@ char **VSICurlFilesystemHandlerBase::ReadDirInternal(const char *pszDirname, /* InvalidateDirContent() */ /************************************************************************/ -void VSICurlFilesystemHandlerBase::InvalidateDirContent(const char *pszDirname) +void VSICurlFilesystemHandlerBase::InvalidateDirContent( + const std::string &osDirname) { CPLMutexHolder oHolder(&hMutex); CachedDirList oCachedDirList; - if (oCacheDirList.tryGet(std::string(pszDirname), oCachedDirList)) + if (oCacheDirList.tryGet(osDirname, oCachedDirList)) { nCachedFilesInDirList -= oCachedDirList.oFileList.size(); - oCacheDirList.remove(std::string(pszDirname)); + oCacheDirList.remove(osDirname); } } @@ -5511,7 +5513,7 @@ char **VSICurlFilesystemHandlerBase::SiblingFiles(const char *pszFilename) { /* Small optimization to avoid unnecessary stat'ing from PAux or ENVI */ /* drivers. The MBTiles driver needs no companion file. */ - if (EQUAL(CPLGetExtension(pszFilename), "mbtiles")) + if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "mbtiles")) { return static_cast(CPLCalloc(1, sizeof(char *))); } @@ -6207,12 +6209,12 @@ struct curl_slist *VSICurlSetContentTypeFromExt(struct curl_slist *poList, {"png", "image/png"}, }; - const char *pszExt = CPLGetExtension(pszPath); - if (pszExt) + const std::string osExt = CPLGetExtensionSafe(pszPath); + if (!osExt.empty()) { for (const auto &pair : aosExtMimePairs) { - if (EQUAL(pszExt, pair.ext)) + if (EQUAL(osExt.c_str(), pair.ext)) { const std::string osContentType( diff --git a/port/cpl_vsil_curl_class.h b/port/cpl_vsil_curl_class.h index 7b36e2f9adb9..7908de18bc9e 100644 --- a/port/cpl_vsil_curl_class.h +++ b/port/cpl_vsil_curl_class.h @@ -269,7 +269,7 @@ class VSICurlFilesystemHandlerBase : public VSIFilesystemHandler char **ReadDirInternal(const char *pszDirname, int nMaxFiles, bool *pbGotFileList); - void InvalidateDirContent(const char *pszDirname); + void InvalidateDirContent(const std::string &osDirname); virtual const char *GetDebugKey() const = 0; diff --git a/port/cpl_vsil_s3.cpp b/port/cpl_vsil_s3.cpp index ef3b9b2d3529..1c5110b4bc88 100644 --- a/port/cpl_vsil_s3.cpp +++ b/port/cpl_vsil_s3.cpp @@ -957,7 +957,7 @@ std::string IVSIS3LikeFSHandlerWithMultipartUpload::InitiateMultipartUpload( else { InvalidateCachedData(poS3HandleHelper->GetURL().c_str()); - InvalidateDirContent(CPLGetDirname(osFilename.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(osFilename.c_str())); CPLXMLNode *psNode = CPLParseXMLString(requestHelper.sWriteFuncData.pBuffer); @@ -1188,7 +1188,8 @@ void VSIMultipartWriteHandle::InvalidateParentDirectory() std::string osFilenameWithoutSlash(m_osFilename); if (!osFilenameWithoutSlash.empty() && osFilenameWithoutSlash.back() == '/') osFilenameWithoutSlash.pop_back(); - m_poFS->InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + m_poFS->InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } /************************************************************************/ @@ -1786,7 +1787,7 @@ VSIVirtualHandle *VSICurlFilesystemHandlerBaseWritable::Open( return nullptr; } - const std::string osTmpFilename(CPLGenerateTempFilename(nullptr)); + const std::string osTmpFilename(CPLGenerateTempFilenameSafe(nullptr)); if (strchr(pszAccess, 'r')) { auto poExistingFile = @@ -1831,7 +1832,7 @@ VSIVirtualHandle *VSICurlFilesystemHandlerBaseWritable::Open( // If there's directory content for the directory where this file // belongs to, use it to detect if the object does not exist CachedDirList cachedDirList; - const std::string osDirname(CPLGetDirname(pszFilename)); + const std::string osDirname(CPLGetDirnameSafe(pszFilename)); if (STARTS_WITH_CI(osDirname.c_str(), GetFSPrefix().c_str()) && GetCachedDirList(osDirname.c_str(), cachedDirList) && cachedDirList.bGotFileList) @@ -2260,7 +2261,7 @@ std::set VSIS3FSHandler::DeleteObjects(const char *pszBucket, InvalidateCachedData( (poS3HandleHelper->GetURL() + osKey).c_str()); - InvalidateDirContent(CPLGetDirname( + InvalidateDirContent(CPLGetDirnameSafe( (GetFSPrefix() + pszBucket + "/" + osKey) .c_str())); } @@ -2628,7 +2629,8 @@ int IVSIS3LikeFSHandler::MkdirInternal(const char *pszDirname, long /*nMode*/, std::string osDirnameWithoutEndSlash(osDirname); osDirnameWithoutEndSlash.pop_back(); - InvalidateDirContent(CPLGetDirname(osDirnameWithoutEndSlash.c_str())); + InvalidateDirContent( + CPLGetDirnameSafe(osDirnameWithoutEndSlash.c_str())); FileProp cachedFileProp; GetCachedFileProp(GetURLFromFilename(osDirname.c_str()).c_str(), @@ -2742,7 +2744,8 @@ int IVSIS3LikeFSHandler::Stat(const char *pszFilename, VSIStatBufL *pStatBuf, // If there's directory content for the directory where this file belongs // to, use it to detect if the object does not exist CachedDirList cachedDirList; - const std::string osDirname(CPLGetDirname(osFilenameWithoutSlash.c_str())); + const std::string osDirname( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); if (STARTS_WITH_CI(osDirname.c_str(), GetFSPrefix().c_str()) && GetCachedDirList(osDirname.c_str(), cachedDirList) && cachedDirList.bGotFileList) @@ -2912,9 +2915,9 @@ int IVSIS3LikeFSHandler::Rename(const char *oldpath, const char *newpath) for (int i = 0; i < aosList.size(); i++) { const std::string osSrc = - CPLFormFilename(oldpath, aosList[i], nullptr); + CPLFormFilenameSafe(oldpath, aosList[i], nullptr); const std::string osTarget = - CPLFormFilename(newpath, aosList[i], nullptr); + CPLFormFilenameSafe(newpath, aosList[i], nullptr); if (Rename(osSrc.c_str(), osTarget.c_str()) != 0) { return -1; @@ -3066,7 +3069,8 @@ int IVSIS3LikeFSHandler::CopyObject(const char *oldpath, const char *newpath, osFilenameWithoutSlash.resize(osFilenameWithoutSlash.size() - 1); - InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } curl_easy_cleanup(hCurlHandle); @@ -3166,7 +3170,8 @@ int IVSIS3LikeFSHandler::DeleteObject(const char *pszFilename) osFilenameWithoutSlash.resize(osFilenameWithoutSlash.size() - 1); - InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } curl_easy_cleanup(hCurlHandle); @@ -4235,8 +4240,8 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, osTargetDir = pszTarget; if (osSource.back() != '/' && osSource.back() != '\\') { - osTargetDir = CPLFormFilename(osTargetDir.c_str(), - CPLGetFilename(pszSource), nullptr); + osTargetDir = CPLFormFilenameSafe( + osTargetDir.c_str(), CPLGetFilename(pszSource), nullptr); } if (!poSourceDir) @@ -4300,7 +4305,7 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, if (oSetTargetSubdirs.find(osDstName) == oSetTargetSubdirs.end()) { - const std::string osTargetSubdir(CPLFormFilename( + const std::string osTargetSubdir(CPLFormFilenameSafe( osTargetDir.c_str(), osDstName.c_str(), nullptr)); aoSetDirsToCreate.insert(osTargetSubdir); } @@ -4368,9 +4373,9 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, if (chunk.nStartOffset != 0) continue; const std::string osSubSource( - CPLFormFilename(osSourceWithoutSlash.c_str(), - chunk.osSrcFilename.c_str(), nullptr)); - const std::string osSubTarget(CPLFormFilename( + CPLFormFilenameSafe(osSourceWithoutSlash.c_str(), + chunk.osSrcFilename.c_str(), nullptr)); + const std::string osSubTarget(CPLFormFilenameSafe( osTargetDir.c_str(), chunk.osDstFilename.c_str(), nullptr)); bool bSkip = false; const auto oIterExistingTarget = @@ -4492,9 +4497,9 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, const auto &chunk = aoChunksToCopy[iChunk]; CPLAssert(chunk.nStartOffset == 0); const std::string osSubSource( - CPLFormFilename(osSourceWithoutSlash.c_str(), - chunk.osSrcFilename.c_str(), nullptr)); - const std::string osSubTarget(CPLFormFilename( + CPLFormFilenameSafe(osSourceWithoutSlash.c_str(), + chunk.osSrcFilename.c_str(), nullptr)); + const std::string osSubTarget(CPLFormFilenameSafe( osTargetDir.c_str(), chunk.osDstFilename.c_str(), nullptr)); // coverity[divide_by_zero] void *pScaledProgress = GDALCreateScaledProgress( @@ -4530,8 +4535,8 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, bTargetIsFile = true; if (VSI_ISDIR(sTarget.st_mode)) { - osTarget = CPLFormFilename(osTarget.c_str(), - CPLGetFilename(pszSource), nullptr); + osTarget = CPLFormFilenameSafe( + osTarget.c_str(), CPLGetFilename(pszSource), nullptr); bTargetIsFile = VSIStatL(osTarget.c_str(), &sTarget) == 0 && !CPL_TO_BOOL(VSI_ISDIR(sTarget.st_mode)); } @@ -4794,14 +4799,16 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, queue->aoChunksToCopy[queue->anIndexToCopy[idx]]; const std::string osSubSource( queue->osTargetDir.empty() - ? queue->osSource.c_str() - : CPLFormFilename(queue->osSourceDir.c_str(), - chunk.osSrcFilename.c_str(), nullptr)); + ? queue->osSource + : CPLFormFilenameSafe(queue->osSourceDir.c_str(), + chunk.osSrcFilename.c_str(), + nullptr)); const std::string osSubTarget( queue->osTargetDir.empty() - ? queue->osTarget.c_str() - : CPLFormFilename(queue->osTargetDir.c_str(), - chunk.osDstFilename.c_str(), nullptr)); + ? queue->osTarget + : CPLFormFilenameSafe(queue->osTargetDir.c_str(), + chunk.osDstFilename.c_str(), + nullptr)); ProgressData progressData; progressData.nFileSize = chunk.nSize; @@ -4964,7 +4971,7 @@ bool IVSIS3LikeFSHandler::Sync(const char *pszSource, const char *pszTarget, oSetKeysToRemove.insert(kv.first); InvalidateCachedData(poS3HandleHelper->GetURL().c_str()); - InvalidateDirContent(CPLGetDirname(kv.first.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(kv.first.c_str())); } } } diff --git a/port/cpl_vsil_sparsefile.cpp b/port/cpl_vsil_sparsefile.cpp index 62eb5b9bd65b..3f36e59a213c 100644 --- a/port/cpl_vsil_sparsefile.cpp +++ b/port/cpl_vsil_sparsefile.cpp @@ -454,9 +454,9 @@ VSIVirtualHandle *VSISparseFileFilesystemHandler::Open( oRegion.osFilename = CPLGetXMLValue(psRegion, "Filename", ""); if (atoi(CPLGetXMLValue(psRegion, "Filename.relative", "0")) != 0) { - const CPLString osSFPath = CPLGetPath(osSparseFilePath); - oRegion.osFilename = - CPLFormFilename(osSFPath, oRegion.osFilename, nullptr); + const std::string osSFPath = CPLGetPathSafe(osSparseFilePath); + oRegion.osFilename = CPLFormFilenameSafe( + osSFPath.c_str(), oRegion.osFilename, nullptr); } // TODO(schwehr): Symbolic constant and an explanation for 32. diff --git a/port/cpl_vsil_swift.cpp b/port/cpl_vsil_swift.cpp index bcaea3585c2f..ae2c749f45e2 100644 --- a/port/cpl_vsil_swift.cpp +++ b/port/cpl_vsil_swift.cpp @@ -453,7 +453,8 @@ int VSISwiftFSHandler::Stat(const char *pszFilename, VSIStatBufL *pStatBuf, if (std::count(osFilename.begin(), osFilename.end(), '/') < 2) return -1; - char **papszContents = VSIReadDir(CPLGetPath(osFilename.c_str())); + char **papszContents = + VSIReadDir(CPLGetPathSafe(osFilename.c_str()).c_str()); int nRet = CSLFindStringCaseSensitive( papszContents, CPLGetFilename(osFilename.c_str())) >= 0 ? 0 diff --git a/port/cpl_vsil_unix_stdio_64.cpp b/port/cpl_vsil_unix_stdio_64.cpp index f6a7f9252e8f..336dc16d8523 100644 --- a/port/cpl_vsil_unix_stdio_64.cpp +++ b/port/cpl_vsil_unix_stdio_64.cpp @@ -1006,7 +1006,7 @@ bool VSIUnixStdioFilesystemHandler::SupportsSequentialWrite( VSIStatBufL sStat; if (VSIStatL(pszPath, &sStat) == 0) return access(pszPath, W_OK) == 0; - return access(CPLGetDirname(pszPath), W_OK) == 0; + return access(CPLGetDirnameSafe(pszPath).c_str(), W_OK) == 0; } /************************************************************************/ diff --git a/port/cpl_vsil_webhdfs.cpp b/port/cpl_vsil_webhdfs.cpp index 419bbca5ea1b..357c87f80f8c 100644 --- a/port/cpl_vsil_webhdfs.cpp +++ b/port/cpl_vsil_webhdfs.cpp @@ -269,7 +269,8 @@ void VSIWebHDFSWriteHandle::InvalidateParentDirectory() std::string osFilenameWithoutSlash(m_osFilename); if (!osFilenameWithoutSlash.empty() && osFilenameWithoutSlash.back() == '/') osFilenameWithoutSlash.pop_back(); - m_poFS->InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + m_poFS->InvalidateDirContent( + CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } /************************************************************************/ @@ -740,7 +741,7 @@ int VSIWebHDFSFSHandler::Unlink(const char *pszFilename) osFilenameWithoutSlash.back() == '/') osFilenameWithoutSlash.pop_back(); - InvalidateDirContent(CPLGetDirname(osFilenameWithoutSlash.c_str())); + InvalidateDirContent(CPLGetDirnameSafe(osFilenameWithoutSlash.c_str())); } else { @@ -856,7 +857,8 @@ int VSIWebHDFSFSHandler::Mkdir(const char *pszDirname, long nMode) } if (bOK) { - InvalidateDirContent(CPLGetDirname(osDirnameWithoutEndSlash.c_str())); + InvalidateDirContent( + CPLGetDirnameSafe(osDirnameWithoutEndSlash.c_str())); FileProp cachedFileProp; cachedFileProp.eExists = EXIST_YES; diff --git a/port/cpl_xml_validate.cpp b/port/cpl_xml_validate.cpp index 81b6266fa06d..396caa7b9dfd 100644 --- a/port/cpl_xml_validate.cpp +++ b/port/cpl_xml_validate.cpp @@ -425,8 +425,10 @@ static CPLXMLNode *CPLLoadSchemaStrInternal(CPLHashSet *hSetSchemas, strcmp(psIter->psChild->pszValue, "schemaLocation") == 0) { const char *pszIncludeSchema = psIter->psChild->psChild->pszValue; - char *pszFullFilename = CPLStrdup(CPLFormFilename( - CPLGetPath(pszFile), pszIncludeSchema, nullptr)); + char *pszFullFilename = + CPLStrdup(CPLFormFilenameSafe(CPLGetPathSafe(pszFile).c_str(), + pszIncludeSchema, nullptr) + .c_str()); CPLFixPath(pszFullFilename); @@ -503,8 +505,9 @@ static CPLXMLNode *CPLLoadSchemaStrInternal(CPLHashSet *hSetSchemas, strstr(pszFile, "/vsimem/CPLValidateXML_") == nullptr) { char *pszFullFilename = CPLStrdup( - CPLFormFilename(CPLGetPath(pszFile), - psIter2->psChild->pszValue, nullptr)); + CPLFormFilenameSafe(CPLGetPathSafe(pszFile).c_str(), + psIter2->psChild->pszValue, nullptr) + .c_str()); CPLFixPath(pszFullFilename); CPLFree(psIter2->psChild->pszValue); psIter2->psChild->pszValue = pszFullFilename; diff --git a/port/vsipreload.cpp b/port/vsipreload.cpp index cab537f79b3f..78073c5e5b0d 100644 --- a/port/vsipreload.cpp +++ b/port/vsipreload.cpp @@ -618,7 +618,7 @@ int CPL_DLL __xstat(int ver, const char *path, struct stat *buf) std::string newpath; if ((!osCurDir.empty() && path[0] != '/')) { - newpath = CPLFormFilename(osCurDir.c_str(), path, nullptr); + newpath = CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr); path = newpath.c_str(); } const int ret = VSIStatL(path, &sStatBufL); @@ -663,17 +663,20 @@ int CPL_DLL __lxstat(int ver, const char *path, struct stat *buf) std::string newpath; if ((!osCurDir.empty() && path[0] != '/')) { - newpath = CPLFormFilename(osCurDir.c_str(), path, nullptr); - path = newpath.c_str(); + newpath = CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr); } - const int ret = VSIStatL(path, &sStatBufL); - sStatBufL.st_ino = static_cast(CPLHashSetHashStr(path)); + else + { + newpath = path; + } + const int ret = VSIStatL(newpath.c_str(), &sStatBufL); + sStatBufL.st_ino = static_cast(CPLHashSetHashStr(newpath.c_str())); if (ret == 0) { copyVSIStatBufLToBuf(&sStatBufL, buf); if (DEBUG_VSIPRELOAD_COND) fprintf(stderr, "__lxstat(%s) ret = 0, mode = %d, size=%d\n", - path, sStatBufL.st_mode, + newpath.c_str(), sStatBufL.st_mode, static_cast(sStatBufL.st_size)); } return ret; @@ -710,7 +713,7 @@ int CPL_DLL __xstat64(int ver, const char *path, struct stat64 *buf) std::string newpath; if ((!osCurDir.empty() && path[0] != '/')) { - newpath = CPLFormFilename(osCurDir.c_str(), path, nullptr); + newpath = CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr); path = newpath.c_str(); } auto oIter = oSetFilesToPreventRecursion.insert(path); @@ -1048,8 +1051,9 @@ static int myopen(const char *path, int flags, ...) if (DEBUG_VSIPRELOAD_COND) { if (!osCurDir.empty() && path[0] != '/') - fprintf(stderr, "open(%s)\n", - CPLFormFilename(osCurDir.c_str(), path, nullptr)); + fprintf( + stderr, "open(%s)\n", + CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr).c_str()); else fprintf(stderr, "open(%s)\n", path); } @@ -1062,8 +1066,8 @@ static int myopen(const char *path, int flags, ...) (flags & O_DIRECTORY) != 0) { VSIStatBufL sStatBufL; - char *newname = const_cast( - CPLFormFilename(osCurDir.c_str(), path, nullptr)); + char *newname = CPLStrdup( + CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr).c_str()); if (strchr(osCurDir.c_str(), '/') != nullptr && strcmp(path, "..") == 0) { for (int i = 0; i < 2; ++i) @@ -1082,6 +1086,7 @@ static int myopen(const char *path, int flags, ...) } else fd = -1; + CPLFree(newname); } else if (STARTS_WITH(path, "/vsi")) fd = VSIFopenHelper(path, flags); @@ -1117,8 +1122,9 @@ int CPL_DLL open64(const char *path, int flags, ...) if (DEBUG_VSIPRELOAD_COND) { if (!osCurDir.empty() && path[0] != '/') - fprintf(stderr, "open64(%s)\n", - CPLFormFilename(osCurDir.c_str(), path, nullptr)); + fprintf( + stderr, "open64(%s)\n", + CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr).c_str()); else fprintf(stderr, "open64(%s)\n", path); } @@ -1131,8 +1137,8 @@ int CPL_DLL open64(const char *path, int flags, ...) (flags & O_DIRECTORY) != 0) { VSIStatBufL sStatBufL; - char *newname = const_cast( - CPLFormFilename(osCurDir.c_str(), path, nullptr)); + char *newname = CPLStrdup( + CPLFormFilenameSafe(osCurDir.c_str(), path, nullptr).c_str()); if (strchr(osCurDir.c_str(), '/') != nullptr && strcmp(path, "..") == 0) { for (int i = 0; i < 2; ++i) @@ -1151,6 +1157,7 @@ int CPL_DLL open64(const char *path, int flags, ...) } else fd = -1; + CPLFree(newname); } else if (STARTS_WITH(path, "/vsi")) fd = VSIFopenHelper(path, flags); @@ -1410,17 +1417,23 @@ int CPL_DLL __fxstatat(int ver, int dirfd, const char *pathname, if (!osCurDir.empty() || STARTS_WITH(pathname, "/vsi")) { VSIStatBufL sStatBufL; + std::string osPathname; if (!osCurDir.empty() && dirfd == AT_FDCWD && pathname[0] != '/') - pathname = CPLFormFilename(osCurDir.c_str(), pathname, nullptr); - const int ret = VSIStatL(pathname, &sStatBufL); - sStatBufL.st_ino = static_cast(CPLHashSetHashStr(pathname)); + osPathname = + CPLFormFilenameSafe(osCurDir.c_str(), pathname, nullptr); + else + osPathname = pathname; + const int ret = VSIStatL(osPathname.c_str(), &sStatBufL); + sStatBufL.st_ino = + static_cast(CPLHashSetHashStr(osPathname.c_str())); if (ret == 0) { copyVSIStatBufLToBuf(&sStatBufL, buf); if (DEBUG_VSIPRELOAD_COND) fprintf(stderr, "__fxstatat(%s) ret = 0, mode = %d, size = %d\n", - pathname, buf->st_mode, static_cast(buf->st_size)); + osPathname.c_str(), buf->st_mode, + static_cast(buf->st_size)); } return ret; } @@ -1579,13 +1592,17 @@ DIR CPL_DLL *opendir(const char *name) if (!osCurDir.empty() || STARTS_WITH(name, "/vsi")) { char **papszDir; + std::string osName; if (!osCurDir.empty() && name[0] != '/') - name = CPLFormFilename(osCurDir.c_str(), name, nullptr); - papszDir = VSIReadDir(name); + osName = CPLFormFilenameSafe(osCurDir.c_str(), name, nullptr); + else + osName = name; + papszDir = VSIReadDir(osName.c_str()); if (papszDir == nullptr) { VSIStatBufL sStatBufL; - if (VSIStatL(name, &sStatBufL) == 0 && S_ISDIR(sStatBufL.st_mode)) + if (VSIStatL(osName.c_str(), &sStatBufL) == 0 && + S_ISDIR(sStatBufL.st_mode)) { papszDir = static_cast(CPLMalloc(sizeof(char *))); papszDir[0] = nullptr; @@ -1602,7 +1619,7 @@ DIR CPL_DLL *opendir(const char *name) CSLDestroy(papszDir); return nullptr; } - mydir->pszDirname = CPLStrdup(name); + mydir->pszDirname = CPLStrdup(osName.c_str()); mydir->papszDir = papszDir; mydir->nIter = 0; mydir->fd = -1; @@ -1635,7 +1652,8 @@ static bool filldir(VSIDIRPreload *mydir) mydir->ent.d_reclen = sizeof(mydir->ent); VSIStatBufL sStatBufL; CPL_IGNORE_RET_VAL(VSIStatL( - CPLFormFilename(mydir->pszDirname, pszName, nullptr), &sStatBufL)); + CPLFormFilenameSafe(mydir->pszDirname, pszName, nullptr).c_str(), + &sStatBufL)); if (DEBUG_VSIPRELOAD_COND && S_ISDIR(sStatBufL.st_mode)) fprintf(stderr, "%s is dir\n", pszName); mydir->ent.d_type = S_ISDIR(sStatBufL.st_mode) ? DT_DIR