From f202bd52b35c82508555af722a8ad0f04910c403 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 9 Jul 2024 23:34:35 +0200 Subject: [PATCH] mappostgresql.c: avoid potential invalid use of strcpy() --- src/mappostgresql.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/mappostgresql.c b/src/mappostgresql.c index f474650e35..deadbd8a60 100644 --- a/src/mappostgresql.c +++ b/src/mappostgresql.c @@ -308,14 +308,18 @@ int msPOSTGRESQLJoinNext(joinObj *join) { for (i = 0; i < join->numitems; i++) { length += 8 + strlen(join->items[i]) + 2; } + if (length > 1024 * 1024) { + msSetError(MS_MEMERR, "Too many joins.\n", "msPOSTGRESQLJoinNext()"); + return MS_FAILURE; + } - columns = (char *)malloc(length); + columns = (char *)malloc(length + 1); if (!columns) { msSetError(MS_MEMERR, "Failure to malloc.\n", "msPOSTGRESQLJoinNext()"); return MS_FAILURE; } - strcpy(columns, ""); + columns[0] = 0; for (i = 0; i < join->numitems; i++) { strcat(columns, "\""); strcat(columns, join->items[i]); @@ -326,14 +330,15 @@ int msPOSTGRESQLJoinNext(joinObj *join) { } /* Create the query string. */ - sql = (char *)malloc(26 + strlen(columns) + strlen(join->table) + - strlen(join->to) + strlen(joininfo->from_value)); + const size_t nSize = 26 + strlen(columns) + strlen(join->table) + + strlen(join->to) + strlen(joininfo->from_value); + sql = (char *)malloc(nSize); if (!sql) { msSetError(MS_MEMERR, "Failure to malloc.\n", "msPOSTGRESQLJoinNext()"); return MS_FAILURE; } - sprintf(sql, "SELECT %s FROM %s WHERE %s = '%s'", columns, join->table, - join->to, joininfo->from_value); + snprintf(sql, nSize, "SELECT %s FROM %s WHERE %s = '%s'", columns, + join->table, join->to, joininfo->from_value); if (joininfo->layer_debug) { msDebug("msPOSTGRESQLJoinNext(): executing %s.\n", sql); }