From c1ec2ad6939b85dce3c692a1633e4d45facd292d Mon Sep 17 00:00:00 2001
From: Corey Huinker <corey.huinker@gmail.com>
Date: Thu, 30 Apr 2026 13:01:15 -0400
Subject: [PATCH v1] Replace strncpy with pg_mbcliplen plus memcpy.

---
 contrib/postgres_fdw/postgres_fdw.c | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)

diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index c42cb690c7b..ed72e02ced7 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -27,6 +27,7 @@
 #include "executor/spi.h"
 #include "foreign/fdwapi.h"
 #include "funcapi.h"
+#include "mb/pg_wchar.h"
 #include "miscadmin.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
@@ -5907,6 +5908,20 @@ fetch_attstats(PGconn *conn, int server_version_num,
 	return res;
 }
 
+/*
+ * Copy a untrusted string into a NameData conforming string buffer.
+ */
+static void
+attname_copy(char *dest, char *src)
+{
+	int len = strlen(src);
+
+	if (len >= NAMEDATALEN)
+		len = pg_mbcliplen(src, len, NAMEDATALEN - 1);
+
+	memcpy(dest, src, len+1);
+}
+
 /*
  * Build the mapping of local columns to remote columns and create a column
  * list used for constructing the fetch_attstats query.
@@ -5957,8 +5972,8 @@ build_remattrmap(Relation relation, List *va_cols,
 		appendStringInfoString(column_list, quote_identifier(remote_attname));
 
 		remattrmap[attrcnt].local_attnum = attnum;
-		strncpy(remattrmap[attrcnt].local_attname, attname, NAMEDATALEN);
-		strncpy(remattrmap[attrcnt].remote_attname, remote_attname, NAMEDATALEN);
+		attname_copy(remattrmap[attrcnt].local_attname, attname);
+		attname_copy(remattrmap[attrcnt].remote_attname, remote_attname);
 		remattrmap[attrcnt].res_index = -1;
 		attrcnt++;
 	}

base-commit: 5642a0367c2fe69684800c5d5c5929c20d99ef72
-- 
2.54.0

