From a46017da1ad67054da537e815ef9c7ff40898875 Mon Sep 17 00:00:00 2001
From: Mahendra Singh Thalor <mahi6run@gmail.com>
Date: Fri, 21 Mar 2025 17:41:21 +0530
Subject: [PATCH] block database name with newline or carriage return in name

while creating database, if database name has any newline or carriage
return character in name, then through error becuase these special
character are not allowed in dbname when dump command is executed.
---
 src/backend/commands/dbcommands.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c
index 5fbbcdaabb1..b0c4e33b634 100644
--- a/src/backend/commands/dbcommands.c
+++ b/src/backend/commands/dbcommands.c
@@ -138,6 +138,7 @@ static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid,
 static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid,
 										Oid src_tsid, Oid dst_tsid);
 static void recovery_create_dbdir(char *path, bool only_tblspc);
+static bool is_name_contain_lfcr(char *name);
 
 /*
  * Create a new database using the WAL_LOG strategy.
@@ -741,6 +742,13 @@ createdb(ParseState *pstate, const CreatedbStmt *stmt)
 	CreateDBStrategy dbstrategy = CREATEDB_WAL_LOG;
 	createdb_failure_params fparms;
 
+	/* Report error if dbname have newline or carriage return in name. */
+	if (is_name_contain_lfcr(dbname))
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
+				errmsg("database name contains a newline or carriage return character"),
+				errhint("newline or carriage return character is not allowed in database name"));
+
 	/* Extract options from the statement node tree */
 	foreach(option, stmt->options)
 	{
@@ -3443,3 +3451,22 @@ dbase_redo(XLogReaderState *record)
 	else
 		elog(PANIC, "dbase_redo: unknown op code %u", info);
 }
+
+/*
+ * is_name_contain_lfcr
+ *
+ * If dbame has \n or \r in the name, then will return true.
+ */
+static bool
+is_name_contain_lfcr(char *name)
+{
+	const char *p;
+
+	for (p = name; *p; p++)
+	{
+		if (*p == '\n' || *p == '\r')
+			return true;
+	}
+
+	return false;
+}
-- 
2.39.3

