From 224b6825dcef26e0dd86483453b6854e6b888181 Mon Sep 17 00:00:00 2001
From: Amul Sul <sulamul@gmail.com>
Date: Mon, 13 Nov 2017 12:30:28 +0530
Subject: [PATCH] argument validation

---
 src/backend/catalog/partition.c | 29 ++++++++++++++++++++++++-----
 1 file changed, 24 insertions(+), 5 deletions(-)

diff --git a/src/backend/catalog/partition.c b/src/backend/catalog/partition.c
index cff59ed055..b170d10d5e 100644
--- a/src/backend/catalog/partition.c
+++ b/src/backend/catalog/partition.c
@@ -3407,6 +3407,17 @@ satisfies_hash_partition(PG_FUNCTION_ARGS)
 	ColumnsHashData *my_extra;
 	uint64		rowHash = 0;
 
+	/*
+	 * Return false if any of the following violated:
+	 *
+	 * 	1. Parent id must be valid relation id,
+	 * 	2. Modulus must be a positive integer and
+	 * 	3. Remainder must be a non-negative integer less than the modulus.
+	 */
+	if (!OidIsValid(parentId) || modulus <= 0 || remainder < 0 ||
+		modulus <= remainder)
+		PG_RETURN_BOOL(false);
+
 	/*
 	 * Cache hash function information.
 	 */
@@ -3418,6 +3429,19 @@ satisfies_hash_partition(PG_FUNCTION_ARGS)
 		PartitionKey key;
 		int j;
 
+		/* Open parent relation and fetch partition keyinfo */
+		parent = heap_open(parentId, AccessShareLock);
+
+		/* Return false if given parent is not a partitioned relation */
+		if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
+		{
+			heap_close(parent, AccessShareLock);
+			PG_RETURN_BOOL(false);
+		}
+
+		key = RelationGetPartitionKey(parent);
+		Assert(key->partnatts == nkeys);
+
 		fcinfo->flinfo->fn_extra =
 			MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
 								   offsetof(ColumnsHashData, partsupfunc) +
@@ -3426,11 +3450,6 @@ satisfies_hash_partition(PG_FUNCTION_ARGS)
 		my_extra->nkeys = nkeys;
 		my_extra->relid = parentId;
 
-		/* Open parent relation and fetch partition keyinfo */
-		parent = heap_open(parentId, AccessShareLock);
-		key = RelationGetPartitionKey(parent);
-
-		Assert(key->partnatts == nkeys);
 		for (j = 0; j < nkeys; ++j)
 			fmgr_info_copy(&my_extra->partsupfunc[j],
 						   key->partsupfunc,
-- 
2.14.1

