[packages/postgresql/POSTGRESQL_8_3] Rel 3. Fix build with zlib/Tcl 8.6/C99, TLS 1.3 key update; backport critical CVE fixes from upstrea

arekm arekm at pld-linux.org
Fri Nov 13 17:30:04 CET 2026


commit f47a9a58475d9ccc1942668cfc13f29fb19cfda3
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Fri Nov 13 17:29:38 2026 +0100

    Rel 3. Fix build with zlib/Tcl 8.6/C99, TLS 1.3 key update; backport
    critical CVE fixes from upstream, Debian ELTS, CentOS and RHEL
    Fixes CVE-2026-116335 CVE-2026-116332 CVE-2026-116331 CVE-2026-116323
    Fixes CVE-2026-116320 CVE-2026-116319 CVE-2026-116316 CVE-2026-116307
    Fixes CVE-2026-16239 CVE-2026-14680 CVE-2026-14669 CVE-2026-6478
    Fixes CVE-2026-6477 CVE-2026-6474 CVE-2026-6473 CVE-2026-2006
    Fixes CVE-2026-2005 CVE-2025-1094 CVE-2024-10979 CVE-2024-10977
    Fixes CVE-2023-5869 CVE-2023-2454 CVE-2022-1552 CVE-2021-32027
    Fixes CVE-2021-23222 CVE-2021-23214 CVE-2020-25695 CVE-2019-10208
    Fixes CVE-2017-7546 CVE-2016-5424 CVE-2016-5423 CVE-2016-0773
    Fixes CVE-2015-3165 CVE-2015-0244 CVE-2015-0243 CVE-2015-0241
    Fixes CVE-2014-0065 CVE-2014-0064 CVE-2014-0063 CVE-2014-0062
    Fixes CVE-2014-0061 CVE-2014-0060 CVE-2013-1900

 postgresql-CVE-2013-1900.patch    |   31 +
 postgresql-CVE-2014-0060.patch    |  228 ++++++
 postgresql-CVE-2014-0061.patch    |  190 +++++
 postgresql-CVE-2014-0062.patch    | 1041 +++++++++++++++++++++++++++
 postgresql-CVE-2014-0063.patch    |  228 ++++++
 postgresql-CVE-2014-0064.patch    |  435 ++++++++++++
 postgresql-CVE-2014-0065.patch    |  268 +++++++
 postgresql-CVE-2015-0241.patch    |   19 +
 postgresql-CVE-2015-0243.patch    |  173 +++++
 postgresql-CVE-2015-0244.patch    |  579 +++++++++++++++
 postgresql-CVE-2015-3165.patch    |  116 ++++
 postgresql-CVE-2016-0773.patch    |  153 ++++
 postgresql-CVE-2016-5423.patch    |  291 ++++++++
 postgresql-CVE-2016-5424.patch    |  225 ++++++
 postgresql-CVE-2017-7546.patch    |  111 +++
 postgresql-CVE-2019-10208.patch   |  124 ++++
 postgresql-CVE-2020-25695.patch   |   64 ++
 postgresql-CVE-2021-23214.patch   |   56 ++
 postgresql-CVE-2021-23222.patch   |   48 ++
 postgresql-CVE-2021-32027.patch   |  143 ++++
 postgresql-CVE-2022-1552.patch    |  371 ++++++++++
 postgresql-CVE-2023-2454.patch    |   88 +++
 postgresql-CVE-2023-5869.patch    |  193 +++++
 postgresql-CVE-2024-10977.patch   |   45 ++
 postgresql-CVE-2024-10979.patch   |   33 +
 postgresql-CVE-2025-1094.patch    |  708 +++++++++++++++++++
 postgresql-CVE-2026-116307.patch  |  131 ++++
 postgresql-CVE-2026-116316.patch  |   74 ++
 postgresql-CVE-2026-116319.patch  |   60 ++
 postgresql-CVE-2026-116320.patch  |   83 +++
 postgresql-CVE-2026-116323.patch  |   31 +
 postgresql-CVE-2026-116331.patch  |   30 +
 postgresql-CVE-2026-116332.patch  |   65 ++
 postgresql-CVE-2026-116335.patch  |  348 ++++++++++
 postgresql-CVE-2026-14669.patch   |   24 +
 postgresql-CVE-2026-14680.patch   |  139 ++++
 postgresql-CVE-2026-16239.patch   |  143 ++++
 postgresql-CVE-2026-2005.patch    |   34 +
 postgresql-CVE-2026-2006.patch    | 1391 +++++++++++++++++++++++++++++++++++++
 postgresql-CVE-2026-6473.patch    |   90 +++
 postgresql-CVE-2026-6474.patch    |   52 ++
 postgresql-CVE-2026-6477.patch    |  178 +++++
 postgresql-CVE-2026-6478.patch    |   40 ++
 postgresql-configure-c99.patch    |   37 +
 postgresql-openssl3.patch         |   11 +-
 postgresql-tcl86-const.patch      |   35 +
 postgresql-tests-tzdata.patch     |   19 +-
 postgresql-tls13-key-update.patch |   27 +
 postgresql-zlib-gzfile.patch      |   75 ++
 postgresql.spec                   |  105 ++-
 50 files changed, 9171 insertions(+), 12 deletions(-)
---
diff --git a/postgresql.spec b/postgresql.spec
index 3a2c41b..678ec05 100644
--- a/postgresql.spec
+++ b/postgresql.spec
@@ -21,7 +21,7 @@ Summary(uk.UTF-8):	PostgreSQL - система керування базами 
 Summary(zh_CN.UTF-8):	PostgreSQL 客户端程序和库文件
 Name:		postgresql
 Version:	8.3.23
-Release:	2
+Release:	3
 License:	BSD
 Group:		Applications/Databases
 Source0:	https://ftp.postgresql.org/pub/source/v%{version}/%{name}-%{version}.tar.bz2
@@ -41,6 +41,53 @@ Patch7:		%{name}-flexible-array-member.patch
 Patch8:		%{name}-format-security.patch
 Patch9:		%{name}-tests-tzdata.patch
 Patch10:	%{name}-openldap26.patch
+Patch11:	%{name}-zlib-gzfile.patch
+Patch12:	%{name}-tls13-key-update.patch
+Patch13:	%{name}-CVE-2021-23214.patch
+Patch14:	%{name}-CVE-2021-23222.patch
+Patch15:	%{name}-CVE-2024-10977.patch
+Patch16:	%{name}-tcl86-const.patch
+Patch17:	%{name}-configure-c99.patch
+Patch18:	%{name}-CVE-2013-1900.patch
+Patch19:	%{name}-CVE-2014-0060.patch
+Patch20:	%{name}-CVE-2014-0061.patch
+Patch21:	%{name}-CVE-2014-0063.patch
+Patch22:	%{name}-CVE-2014-0064.patch
+Patch23:	%{name}-CVE-2014-0065.patch
+Patch24:	%{name}-CVE-2015-0241.patch
+Patch25:	%{name}-CVE-2015-0243.patch
+Patch26:	%{name}-CVE-2015-0244.patch
+Patch27:	%{name}-CVE-2015-3165.patch
+Patch28:	%{name}-CVE-2016-0773.patch
+Patch29:	%{name}-CVE-2016-5423.patch
+Patch30:	%{name}-CVE-2017-7546.patch
+Patch31:	%{name}-CVE-2026-6478.patch
+Patch32:	%{name}-CVE-2026-6474.patch
+Patch33:	%{name}-CVE-2026-14680.patch
+Patch34:	%{name}-CVE-2021-32027.patch
+Patch35:	%{name}-CVE-2023-5869.patch
+Patch36:	%{name}-CVE-2026-14669.patch
+Patch37:	%{name}-CVE-2026-6473.patch
+Patch38:	%{name}-CVE-2026-116332.patch
+Patch39:	%{name}-CVE-2026-16239.patch
+Patch40:	%{name}-CVE-2020-25695.patch
+Patch41:	%{name}-CVE-2022-1552.patch
+Patch42:	%{name}-CVE-2026-116316.patch
+Patch43:	%{name}-CVE-2019-10208.patch
+Patch44:	%{name}-CVE-2023-2454.patch
+Patch45:	%{name}-CVE-2024-10979.patch
+Patch46:	%{name}-CVE-2026-116307.patch
+Patch47:	%{name}-CVE-2026-116319.patch
+Patch48:	%{name}-CVE-2026-116320.patch
+Patch49:	%{name}-CVE-2026-116323.patch
+Patch50:	%{name}-CVE-2026-116331.patch
+Patch51:	%{name}-CVE-2026-116335.patch
+Patch52:	%{name}-CVE-2026-2005.patch
+Patch53:	%{name}-CVE-2026-6477.patch
+Patch54:	%{name}-CVE-2016-5424.patch
+Patch55:	%{name}-CVE-2026-2006.patch
+Patch56:	%{name}-CVE-2014-0062.patch
+Patch57:	%{name}-CVE-2025-1094.patch
 URL:		http://www.postgresql.org/
 BuildRequires:	autoconf
 BuildRequires:	automake
@@ -767,8 +814,59 @@ Różne moduły dołączone do PostgreSQL-a.
 %patch -P6 -p1
 %patch -P7 -p1
 %patch -P8 -p1
+# expected output differs with the tzdata version; pg_regress accepts either file
+for t in date timestamp timestamptz horology; do
+	cp -p src/test/regress/expected/$t.out src/test/regress/expected/${t}_1.out
+done
 %patch -P9 -p1
 %patch -P10 -p1
+%patch -P11 -p1
+%patch -P12 -p1
+%patch -P13 -p1
+%patch -P14 -p1
+%patch -P15 -p1
+%patch -P16 -p1
+%patch -P17 -p1
+%patch -P18 -p1
+%patch -P19 -p1
+%patch -P20 -p1
+%patch -P21 -p1
+%patch -P22 -p1
+%patch -P23 -p1
+%patch -P24 -p1
+%patch -P25 -p1
+%patch -P26 -p1
+%patch -P27 -p1
+%patch -P28 -p1
+%patch -P29 -p1
+%patch -P30 -p1
+%patch -P31 -p1
+%patch -P32 -p1
+%patch -P33 -p1
+%patch -P34 -p1
+%patch -P35 -p1
+%patch -P36 -p1
+%patch -P37 -p1
+%patch -P38 -p1
+%patch -P39 -p1
+%patch -P40 -p1
+%patch -P41 -p1
+%patch -P42 -p1
+%patch -P43 -p1
+%patch -P44 -p1
+%patch -P45 -p1
+%patch -P46 -p1
+%patch -P47 -p1
+%patch -P48 -p1
+%patch -P49 -p1
+%patch -P50 -p1
+%patch -P51 -p1
+%patch -P52 -p1
+%patch -P53 -p1
+%patch -P54 -p1
+%patch -P55 -p1
+%patch -P56 -p1
+%patch -P57 -p1
 
 tar xzf doc/man*.tar.gz
 
@@ -784,8 +882,9 @@ find src -name \*.l -o -name \*.y | xargs touch
 %build
 %{__aclocal} -I config
 %{__autoconf}
+# 8.3 sources predate C23 (typedef char bool)
 %configure \
-	CFLAGS="%{rpmcflags} -std=gnu89 -DNEED_REENTRANT_FUNCS" \
+	CFLAGS="%{rpmcflags} -std=gnu17 -DNEED_REENTRANT_FUNCS" \
 	%{?with_python:PYTHON=%{__python}} \
 	--disable-rpath \
 	--enable-depend \
@@ -808,7 +907,7 @@ find src -name \*.l -o -name \*.y | xargs touch
 %{__make}
 
 for mod in %{contrib_modules}; do \
-	flags="%{rpmcflags} -std=gnu89 -DNEED_REENTRANT_FUNCS"
+	flags="%{rpmcflags} -std=gnu17 -DNEED_REENTRANT_FUNCS"
 	if [ $mod = xml2 ]; then flags="$flags -I/usr/include/libxml2"; fi
 	%{__make} -C contrib/$mod CFLAGS="$flags"
 done
diff --git a/postgresql-CVE-2013-1900.patch b/postgresql-CVE-2013-1900.patch
new file mode 100644
index 0000000..e572b37
--- /dev/null
+++ b/postgresql-CVE-2013-1900.patch
@@ -0,0 +1,31 @@
+Reset the OpenSSL random state in each postmaster child, so backends do
+not share it.
+Source: upstream a6bd75a127 (REL8_4)
+
+diff --git a/src/backend/postmaster/fork_process.c b/src/backend/postmaster/fork_process.c
+index d67e4c6..597527a 100644
+--- a/src/backend/postmaster/fork_process.c
++++ b/src/backend/postmaster/fork_process.c
+@@ -15,6 +15,9 @@
+ #include <time.h>
+ #include <sys/time.h>
+ #include <unistd.h>
++#ifdef USE_SSL
++#include <openssl/rand.h>
++#endif
+ 
+ #ifndef WIN32
+ /*
+@@ -60,6 +63,12 @@ fork_process(void)
+ 		setitimer(ITIMER_PROF, &prof_itimer, NULL);
+ #endif
+ 
++		/*
++		 * Make sure processes do not share OpenSSL randomness state.
++		 */
++#ifdef USE_SSL
++		RAND_cleanup();
++#endif
+ 	}
+ 
+ 	return result;
diff --git a/postgresql-CVE-2014-0060.patch b/postgresql-CVE-2014-0060.patch
new file mode 100644
index 0000000..6e3e48a
--- /dev/null
+++ b/postgresql-CVE-2014-0060.patch
@@ -0,0 +1,228 @@
+Shore up ADMIN OPTION restrictions: SET ROLE no longer grants the right
+to GRANT/REVOKE a role.
+Source: upstream ff35425c8f (REL8_4)
+
+diff --git a/doc/src/sgml/ref/grant.sgml b/doc/src/sgml/ref/grant.sgml
+index 75706fd..13175bb 100644
+--- a/doc/src/sgml/ref/grant.sgml
++++ b/doc/src/sgml/ref/grant.sgml
+@@ -322,11 +322,13 @@ GRANT <replaceable class="PARAMETER">role</replaceable> [, ...] TO <replaceable
+   <para>
+    If <literal>WITH ADMIN OPTION</literal> is specified, the member can
+    in turn grant membership in the role to others, and revoke membership
+-   in the role as well.  Without the admin option, ordinary users cannot do
+-   that.  However,
+-   database superusers can grant or revoke membership in any role to anyone.
+-   Roles having <literal>CREATEROLE</> privilege can grant or revoke
+-   membership in any role that is not a superuser.
++   in the role as well.  Without the admin option, ordinary users cannot
++   do that.  A role is not considered to hold <literal>WITH ADMIN
++   OPTION</literal> on itself, but it may grant or revoke membership in
++   itself from a database session where the session user matches the
++   role.  Database superusers can grant or revoke membership in any role
++   to anyone.  Roles having <literal>CREATEROLE</> privilege can grant
++   or revoke membership in any role that is not a superuser.
+   </para>
+ 
+   <para>
+diff --git a/src/backend/commands/user.c b/src/backend/commands/user.c
+index 34e24fd..6a8832e 100644
+--- a/src/backend/commands/user.c
++++ b/src/backend/commands/user.c
+@@ -1296,7 +1296,16 @@ AddRoleMems(const char *rolename, Oid roleid,
+ 							rolename)));
+ 	}
+ 
+-	/* XXX not sure about this check */
++	/*
++	 * The role membership grantor of record has little significance at
++	 * present.  Nonetheless, inasmuch as users might look to it for a crude
++	 * audit trail, let only superusers impute the grant to a third party.
++	 *
++	 * Before lifting this restriction, give the member == role case of
++	 * is_admin_of_role() a fresh look.  Ensure that the current role cannot
++	 * use an explicit grantor specification to take advantage of the session
++	 * user's self-admin right.
++	 */
+ 	if (grantorId != GetUserId() && !superuser())
+ 		ereport(ERROR,
+ 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+diff --git a/src/backend/utils/adt/acl.c b/src/backend/utils/adt/acl.c
+index fadc4e3..0d119e8 100644
+--- a/src/backend/utils/adt/acl.c
++++ b/src/backend/utils/adt/acl.c
+@@ -2810,6 +2810,11 @@ pg_role_aclcheck(Oid role_oid, Oid roleid, AclMode mode)
+ {
+ 	if (mode & ACL_GRANT_OPTION_FOR(ACL_CREATE))
+ 	{
++		/*
++		 * XXX For roleid == role_oid, is_admin_of_role() also examines the
++		 * session and call stack.  That suits two-argument pg_has_role(), but
++		 * it gives the three-argument version a lamentable whimsy.
++		 */
+ 		if (is_admin_of_role(roleid, role_oid))
+ 			return ACLCHECK_OK;
+ 	}
+@@ -3131,11 +3136,9 @@ is_member_of_role_nosuper(Oid member, Oid role)
+ 
+ 
+ /*
+- * Is member an admin of role (directly or indirectly)?  That is, is it
+- * a member WITH ADMIN OPTION?
+- *
+- * We could cache the result as for is_member_of_role, but currently this
+- * is not used in any performance-critical paths, so we don't.
++ * Is member an admin of role?  That is, is member the role itself (subject to
++ * restrictions below), a member (directly or indirectly) WITH ADMIN OPTION,
++ * or a superuser?
+  */
+ bool
+ is_admin_of_role(Oid member, Oid role)
+@@ -3144,14 +3147,41 @@ is_admin_of_role(Oid member, Oid role)
+ 	List	   *roles_list;
+ 	ListCell   *l;
+ 
+-	/* Fast path for simple case */
+-	if (member == role)
+-		return true;
+-
+-	/* Superusers have every privilege, so are part of every role */
+ 	if (superuser_arg(member))
+ 		return true;
+ 
++	if (member == role)
++		/*
++		 * A role can admin itself when it matches the session user and we're
++		 * outside any security-restricted operation, SECURITY DEFINER or
++		 * similar context.  SQL-standard roles cannot self-admin.  However,
++		 * SQL-standard users are distinct from roles, and they are not
++		 * grantable like roles: PostgreSQL's role-user duality extends the
++		 * standard.  Checking for a session user match has the effect of
++		 * letting a role self-admin only when it's conspicuously behaving
++		 * like a user.  Note that allowing self-admin under a mere SET ROLE
++		 * would make WITH ADMIN OPTION largely irrelevant; any member could
++		 * SET ROLE to issue the otherwise-forbidden command.
++		 *
++		 * Withholding self-admin in a security-restricted operation prevents
++		 * object owners from harnessing the session user identity during
++		 * administrative maintenance.  Suppose Alice owns a database, has
++		 * issued "GRANT alice TO bob", and runs a daily ANALYZE.  Bob creates
++		 * an alice-owned SECURITY DEFINER function that issues "REVOKE alice
++		 * FROM carol".  If he creates an expression index calling that
++		 * function, Alice will attempt the REVOKE during each ANALYZE.
++		 * Checking InSecurityRestrictedOperation() thwarts that attack.
++		 *
++		 * Withholding self-admin in SECURITY DEFINER functions makes their
++		 * behavior independent of the calling user.  There's no security or
++		 * SQL-standard-conformance need for that restriction, though.
++		 *
++		 * A role cannot have actual WITH ADMIN OPTION on itself, because that
++		 * would imply a membership loop.  Therefore, we're done either way.
++		 */
++		return member == GetSessionUserId() &&
++			!InLocalUserIdChange() && !InSecurityRestrictedOperation();
++
+ 	/*
+ 	 * Find all the roles that member is a member of, including multi-level
+ 	 * recursion.  We build a list in the same way that is_member_of_role does
+diff --git a/src/test/regress/expected/privileges.out b/src/test/regress/expected/privileges.out
+index a5941e1..83ee0ff 100644
+--- a/src/test/regress/expected/privileges.out
++++ b/src/test/regress/expected/privileges.out
+@@ -26,7 +26,7 @@ ALTER GROUP regressgroup1 ADD USER regressuser4;
+ ALTER GROUP regressgroup2 ADD USER regressuser2;	-- duplicate
+ NOTICE:  role "regressuser2" is already a member of role "regressgroup2"
+ ALTER GROUP regressgroup2 DROP USER regressuser2;
+-ALTER GROUP regressgroup2 ADD USER regressuser4;
++GRANT regressgroup2 TO regressuser4 WITH ADMIN OPTION;
+ -- test owner privileges
+ SET SESSION AUTHORIZATION regressuser1;
+ SELECT session_user, current_user;
+@@ -583,6 +583,40 @@ SELECT has_table_privilege('regressuser1', 'atest4', 'SELECT WITH GRANT OPTION')
+  t
+ (1 row)
+ 
++-- Admin options
++SET SESSION AUTHORIZATION regressuser4;
++CREATE FUNCTION dogrant_ok() RETURNS void LANGUAGE sql SECURITY DEFINER AS
++	'GRANT regressgroup2 TO regressuser5';
++GRANT regressgroup2 TO regressuser5; -- ok: had ADMIN OPTION
++SET ROLE regressgroup2;
++GRANT regressgroup2 TO regressuser5; -- fails: SET ROLE suspended privilege
++ERROR:  must have admin option on role "regressgroup2"
++SET SESSION AUTHORIZATION regressuser1;
++GRANT regressgroup2 TO regressuser5; -- fails: no ADMIN OPTION
++ERROR:  must have admin option on role "regressgroup2"
++SELECT dogrant_ok();			-- ok: SECURITY DEFINER conveys ADMIN
++NOTICE:  role "regressuser5" is already a member of role "regressgroup2"
++CONTEXT:  SQL function "dogrant_ok" statement 1
++ dogrant_ok 
++------------
++ 
++(1 row)
++
++SET ROLE regressgroup2;
++GRANT regressgroup2 TO regressuser5; -- fails: SET ROLE did not help
++ERROR:  must have admin option on role "regressgroup2"
++SET SESSION AUTHORIZATION regressgroup2;
++GRANT regressgroup2 TO regressuser5; -- ok: a role can self-admin
++NOTICE:  role "regressuser5" is already a member of role "regressgroup2"
++CREATE FUNCTION dogrant_fails() RETURNS void LANGUAGE sql SECURITY DEFINER AS
++	'GRANT regressgroup2 TO regressuser5';
++SELECT dogrant_fails();			-- fails: no self-admin in SECURITY DEFINER
++ERROR:  must have admin option on role "regressgroup2"
++CONTEXT:  SQL function "dogrant_fails" statement 1
++DROP FUNCTION dogrant_fails();
++SET SESSION AUTHORIZATION regressuser4;
++DROP FUNCTION dogrant_ok();
++REVOKE regressgroup2 FROM regressuser5;
+ -- test that dependent privileges are revoked (or not) properly
+ \c -
+ set session role regressuser1;
+diff --git a/src/test/regress/sql/privileges.sql b/src/test/regress/sql/privileges.sql
+index 1b1e1d4..4b69647 100644
+--- a/src/test/regress/sql/privileges.sql
++++ b/src/test/regress/sql/privileges.sql
+@@ -34,7 +34,7 @@ ALTER GROUP regressgroup1 ADD USER regressuser4;
+ 
+ ALTER GROUP regressgroup2 ADD USER regressuser2;	-- duplicate
+ ALTER GROUP regressgroup2 DROP USER regressuser2;
+-ALTER GROUP regressgroup2 ADD USER regressuser4;
++GRANT regressgroup2 TO regressuser4 WITH ADMIN OPTION;
+ 
+ 
+ -- test owner privileges
+@@ -334,6 +334,33 @@ SELECT has_table_privilege('regressuser3', 'atest4', 'SELECT'); -- false
+ SELECT has_table_privilege('regressuser1', 'atest4', 'SELECT WITH GRANT OPTION'); -- true
+ 
+ 
++-- Admin options
++
++SET SESSION AUTHORIZATION regressuser4;
++CREATE FUNCTION dogrant_ok() RETURNS void LANGUAGE sql SECURITY DEFINER AS
++	'GRANT regressgroup2 TO regressuser5';
++GRANT regressgroup2 TO regressuser5; -- ok: had ADMIN OPTION
++SET ROLE regressgroup2;
++GRANT regressgroup2 TO regressuser5; -- fails: SET ROLE suspended privilege
++
++SET SESSION AUTHORIZATION regressuser1;
++GRANT regressgroup2 TO regressuser5; -- fails: no ADMIN OPTION
++SELECT dogrant_ok();			-- ok: SECURITY DEFINER conveys ADMIN
++SET ROLE regressgroup2;
++GRANT regressgroup2 TO regressuser5; -- fails: SET ROLE did not help
++
++SET SESSION AUTHORIZATION regressgroup2;
++GRANT regressgroup2 TO regressuser5; -- ok: a role can self-admin
++CREATE FUNCTION dogrant_fails() RETURNS void LANGUAGE sql SECURITY DEFINER AS
++	'GRANT regressgroup2 TO regressuser5';
++SELECT dogrant_fails();			-- fails: no self-admin in SECURITY DEFINER
++DROP FUNCTION dogrant_fails();
++
++SET SESSION AUTHORIZATION regressuser4;
++DROP FUNCTION dogrant_ok();
++REVOKE regressgroup2 FROM regressuser5;
++
++
+ -- test that dependent privileges are revoked (or not) properly
+ \c -
+ 
diff --git a/postgresql-CVE-2014-0061.patch b/postgresql-CVE-2014-0061.patch
new file mode 100644
index 0000000..616c836
--- /dev/null
+++ b/postgresql-CVE-2014-0061.patch
@@ -0,0 +1,190 @@
+Check that the caller may use the language and function in explicit
+calls to PL validators.
+Source: upstream 823b9dc256 (REL8_4)
+
+diff --git a/src/backend/catalog/pg_proc.c b/src/backend/catalog/pg_proc.c
+index 22c3861..84d07eb 100644
+--- a/src/backend/catalog/pg_proc.c
++++ b/src/backend/catalog/pg_proc.c
+@@ -458,6 +458,9 @@ fmgr_internal_validator(PG_FUNCTION_ARGS)
+ 	Datum		tmp;
+ 	char	   *prosrc;
+ 
++	if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
++		PG_RETURN_VOID();
++
+ 	/*
+ 	 * We do not honor check_function_bodies since it's unlikely the function
+ 	 * name will be found later if it isn't there now.
+@@ -507,6 +510,9 @@ fmgr_c_validator(PG_FUNCTION_ARGS)
+ 	char	   *prosrc;
+ 	char	   *probin;
+ 
++	if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
++		PG_RETURN_VOID();
++
+ 	/*
+ 	 * It'd be most consistent to skip the check if !check_function_bodies,
+ 	 * but the purpose of that switch is to be helpful for pg_dump loading,
+@@ -558,6 +564,9 @@ fmgr_sql_validator(PG_FUNCTION_ARGS)
+ 	bool		haspolyarg;
+ 	int			i;
+ 
++	if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
++		PG_RETURN_VOID();
++
+ 	tuple = SearchSysCache(PROCOID,
+ 						   ObjectIdGetDatum(funcoid),
+ 						   0, 0, 0);
+diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
+index 0d42e29..22a320d 100644
+--- a/src/backend/commands/functioncmds.c
++++ b/src/backend/commands/functioncmds.c
+@@ -804,7 +804,6 @@ CreateFunction(CreateFunctionStmt *stmt)
+ 					prorows);
+ }
+ 
+-
+ /*
+  * RemoveFunction
+  *		Deletes a function.
+diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c
+index 46f64a3..ea97efd 100644
+--- a/src/backend/utils/fmgr/fmgr.c
++++ b/src/backend/utils/fmgr/fmgr.c
+@@ -24,6 +24,7 @@
+ #include "miscadmin.h"
+ #include "parser/parse_expr.h"
+ #include "utils/builtins.h"
++#include "utils/acl.h"
+ #include "utils/fmgrtab.h"
+ #include "utils/guc.h"
+ #include "utils/lsyscache.h"
+@@ -2265,3 +2266,87 @@ get_call_expr_argtype(Node *expr, int argnum)
+ 
+ 	return argtype;
+ }
++
++/*-------------------------------------------------------------------------
++ *		Support routines for procedural language implementations
++ *-------------------------------------------------------------------------
++ */
++
++/*
++ * Verify that a validator is actually associated with the language of a
++ * particular function and that the user has access to both the language and
++ * the function.  All validators should call this before doing anything
++ * substantial.  Doing so ensures a user cannot achieve anything with explicit
++ * calls to validators that he could not achieve with CREATE FUNCTION or by
++ * simply calling an existing function.
++ *
++ * When this function returns false, callers should skip all validation work
++ * and call PG_RETURN_VOID().  This never happens at present; it is reserved
++ * for future expansion.
++ *
++ * In particular, checking that the validator corresponds to the function's
++ * language allows untrusted language validators to assume they process only
++ * superuser-chosen source code.  (Untrusted language call handlers, by
++ * definition, do assume that.)  A user lacking the USAGE language privilege
++ * would be unable to reach the validator through CREATE FUNCTION, so we check
++ * that to block explicit calls as well.  Checking the EXECUTE privilege on
++ * the function is often superfluous, because most users can clone the
++ * function to get an executable copy.  It is meaningful against users with no
++ * database TEMP right and no permanent schema CREATE right, thereby unable to
++ * create any function.  Also, if the function tracks persistent state by
++ * function OID or name, validating the original function might permit more
++ * mischief than creating and validating a clone thereof.
++ */
++bool
++CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
++{
++	HeapTuple	procTup;
++	HeapTuple	langTup;
++	Form_pg_proc procStruct;
++	Form_pg_language langStruct;
++	AclResult	aclresult;
++
++	/* Get the function's pg_proc entry */
++	procTup = SearchSysCache(PROCOID, ObjectIdGetDatum(functionOid), 0, 0, 0);
++	if (!HeapTupleIsValid(procTup))
++		elog(ERROR, "cache lookup failed for function %u", functionOid);
++	procStruct = (Form_pg_proc) GETSTRUCT(procTup);
++
++	/*
++	 * Fetch pg_language entry to know if this is the correct validation
++	 * function for that pg_proc entry.
++	 */
++	langTup = SearchSysCache(LANGOID, ObjectIdGetDatum(procStruct->prolang),
++							 0, 0, 0);
++	if (!HeapTupleIsValid(langTup))
++		elog(ERROR, "cache lookup failed for language %u", procStruct->prolang);
++	langStruct = (Form_pg_language) GETSTRUCT(langTup);
++
++	if (langStruct->lanvalidator != validatorOid)
++		ereport(ERROR,
++				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
++				 errmsg("language validation function %u called for language %u instead of %u",
++						validatorOid, procStruct->prolang,
++						langStruct->lanvalidator)));
++
++	/* first validate that we have permissions to use the language */
++	aclresult = pg_language_aclcheck(procStruct->prolang, GetUserId(),
++									 ACL_USAGE);
++	if (aclresult != ACLCHECK_OK)
++		aclcheck_error(aclresult, ACL_KIND_LANGUAGE,
++					   NameStr(langStruct->lanname));
++
++	/*
++	 * Check whether we are allowed to execute the function itself. If we can
++	 * execute it, there should be no possible side-effect of
++	 * compiling/validation that execution can't have.
++	 */
++	aclresult = pg_proc_aclcheck(functionOid, GetUserId(), ACL_EXECUTE);
++	if (aclresult != ACLCHECK_OK)
++		aclcheck_error(aclresult, ACL_KIND_PROC, NameStr(procStruct->proname));
++
++	ReleaseSysCache(procTup);
++	ReleaseSysCache(langTup);
++
++	return true;
++}
+diff --git a/src/include/fmgr.h b/src/include/fmgr.h
+index 07bce55..032db08 100644
+--- a/src/include/fmgr.h
++++ b/src/include/fmgr.h
+@@ -518,6 +518,7 @@ extern void load_file(const char *filename, bool restricted);
+ extern void **find_rendezvous_variable(const char *varName);
+ 
+ 
++extern bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid);
+ /*
+  * !!! OLD INTERFACE !!!
+  *
+diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
+index 1536ea0..04c194c 100644
+--- a/src/pl/plperl/plperl.c
++++ b/src/pl/plperl/plperl.c
+@@ -1074,6 +1074,9 @@ plperl_validator(PG_FUNCTION_ARGS)
+ 	bool		istrigger = false;
+ 	int			i;
+ 
++	if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
++		PG_RETURN_VOID();
++
+ 	/* Get the new function's pg_proc entry */
+ 	tuple = SearchSysCache(PROCOID,
+ 						   ObjectIdGetDatum(funcoid),
+diff --git a/src/pl/plpgsql/src/pl_handler.c b/src/pl/plpgsql/src/pl_handler.c
+index 1042e8a..5b51311 100644
+--- a/src/pl/plpgsql/src/pl_handler.c
++++ b/src/pl/plpgsql/src/pl_handler.c
+@@ -136,6 +136,9 @@ plpgsql_validator(PG_FUNCTION_ARGS)
+ 	bool		istrigger = false;
+ 	int			i;
+ 
++	if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
++		PG_RETURN_VOID();
++
+ 	/* Get the new function's pg_proc entry */
+ 	tuple = SearchSysCache(PROCOID,
+ 						   ObjectIdGetDatum(funcoid),
diff --git a/postgresql-CVE-2014-0062.patch b/postgresql-CVE-2014-0062.patch
new file mode 100644
index 0000000..ae320c0
--- /dev/null
+++ b/postgresql-CVE-2014-0062.patch
@@ -0,0 +1,1041 @@
+Avoid repeated name lookups during table and index DDL (changes
+DefineIndex, AlterTable, CreateTrigger signatures).
+Source: upstream e464761333 (REL8_4); also sets old_pktable_oid as 9.2+
+does
+
+diff --git a/src/backend/bootstrap/bootparse.y b/src/backend/bootstrap/bootparse.y
+index a6b904f..e9d2120 100644
+--- a/src/backend/bootstrap/bootparse.y
++++ b/src/backend/bootstrap/bootparse.y
+@@ -27,6 +27,7 @@
+ #include "bootstrap/bootstrap.h"
+ #include "catalog/catalog.h"
+ #include "catalog/heap.h"
++#include "catalog/namespace.h"
+ #include "catalog/pg_am.h"
+ #include "catalog/pg_attribute.h"
+ #include "catalog/pg_authid.h"
+@@ -244,9 +245,14 @@ Boot_InsertStmt:
+ Boot_DeclareIndexStmt:
+ 		  XDECLARE INDEX boot_ident oidspec ON boot_ident USING boot_ident LPAREN boot_index_params RPAREN
+ 				{
++					Oid		relationId;
++
+ 					do_start();
+ 
+-					DefineIndex(makeRangeVar(NULL, LexIDStr($6)),
++					relationId = RangeVarGetRelid(makeRangeVar(NULL, LexIDStr($6)),
++												  false);
++
++					DefineIndex(relationId,
+ 								LexIDStr($3),
+ 								$4,
+ 								LexIDStr($8),
+@@ -262,9 +268,14 @@ Boot_DeclareIndexStmt:
+ Boot_DeclareUniqueIndexStmt:
+ 		  XDECLARE UNIQUE INDEX boot_ident oidspec ON boot_ident USING boot_ident LPAREN boot_index_params RPAREN
+ 				{
++					Oid		relationId;
++
+ 					do_start();
+ 
+-					DefineIndex(makeRangeVar(NULL, LexIDStr($7)),
++					relationId = RangeVarGetRelid(makeRangeVar(NULL, LexIDStr($7)),
++												  false);
++
++					DefineIndex(relationId,
+ 								LexIDStr($4),
+ 								$5,
+ 								LexIDStr($9),
+diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
+index 9039992..d180fad 100644
+--- a/src/backend/catalog/index.c
++++ b/src/backend/catalog/index.c
+@@ -88,7 +88,6 @@ static void validate_index_heapscan(Relation heapRelation,
+ 						IndexInfo *indexInfo,
+ 						Snapshot snapshot,
+ 						v_i_state *state);
+-static Oid	IndexGetRelation(Oid indexId);
+ 
+ 
+ /*
+@@ -2285,7 +2284,7 @@ index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
+  * IndexGetRelation: given an index's relation OID, get the OID of the
+  * relation it is an index on.	Uses the system cache.
+  */
+-static Oid
++Oid
+ IndexGetRelation(Oid indexId)
+ {
+ 	HeapTuple	tuple;
+diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
+index c25cfaa..eca2661 100644
+--- a/src/backend/catalog/pg_constraint.c
++++ b/src/backend/catalog/pg_constraint.c
+@@ -695,3 +695,22 @@ AlterConstraintNamespaces(Oid ownerId, Oid oldNspId,
+ 
+ 	heap_close(conRel, RowExclusiveLock);
+ }
++
++/*
++ * get_constraint_relation_oids
++ *		Find the IDs of the relations to which a constraint refers.
++ */
++void
++get_constraint_relation_oids(Oid constraint_oid, Oid *conrelid, Oid *confrelid)
++{
++	HeapTuple	tup;
++	Form_pg_constraint	con;
++
++	tup = SearchSysCache(CONSTROID, ObjectIdGetDatum(constraint_oid), 0, 0, 0);
++	if (!HeapTupleIsValid(tup)) /* should not happen */
++		elog(ERROR, "cache lookup failed for constraint %u", constraint_oid);
++	con = (Form_pg_constraint) GETSTRUCT(tup);
++	*conrelid = con->conrelid;
++	*confrelid = con->confrelid;
++	ReleaseSysCache(tup);
++}
+diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c
+index 8cf833a..69f0991 100644
+--- a/src/backend/commands/alter.c
++++ b/src/backend/commands/alter.c
+@@ -91,9 +91,8 @@ ExecRenameStmt(RenameStmt *stmt)
+ 			{
+ 				Oid			relid;
+ 
+-				CheckRelationOwnership(stmt->relation, true);
+-
+ 				relid = RangeVarGetRelid(stmt->relation, false);
++				CheckRelationOwnership(relid, true);
+ 
+ 				switch (stmt->renameType)
+ 				{
+@@ -181,7 +180,6 @@ ExecAlterObjectSchemaStmt(AlterObjectSchemaStmt *stmt)
+ 
+ 		case OBJECT_SEQUENCE:
+ 		case OBJECT_TABLE:
+-			CheckRelationOwnership(stmt->relation, true);
+ 			AlterTableNamespace(stmt->relation, stmt->newschema);
+ 			break;
+ 
+diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
+index 89f4a06..955032d 100644
+--- a/src/backend/commands/indexcmds.c
++++ b/src/backend/commands/indexcmds.c
+@@ -73,7 +73,8 @@ static bool relationHasPrimaryKey(Relation rel);
+  * DefineIndex
+  *		Creates a new index.
+  *
+- * 'heapRelation': the relation the index will apply to.
++ * 'relationId': the OID of the heap relation on which the index is to be
++ *		created
+  * 'indexRelationName': the name for the new index, or NULL to indicate
+  *		that a nonconflicting default name should be picked.
+  * 'indexRelationId': normally InvalidOid, but during bootstrap can be
+@@ -98,7 +99,7 @@ static bool relationHasPrimaryKey(Relation rel);
+  * 'concurrent': avoid blocking writers to the table while building.
+  */
+ void
+-DefineIndex(RangeVar *heapRelation,
++DefineIndex(Oid relationId,
+ 			char *indexRelationName,
+ 			Oid indexRelationId,
+ 			char *accessMethodName,
+@@ -117,7 +118,6 @@ DefineIndex(RangeVar *heapRelation,
+ {
+ 	Oid		   *classObjectId;
+ 	Oid			accessMethodId;
+-	Oid			relationId;
+ 	Oid			namespaceId;
+ 	Oid			tablespaceId;
+ 	Relation	rel;
+@@ -134,6 +134,7 @@ DefineIndex(RangeVar *heapRelation,
+ 	VirtualTransactionId *old_snapshots;
+ 	LockRelId	heaprelid;
+ 	LOCKTAG		heaplocktag;
++	LOCKMODE	lockmode;
+ 	Snapshot	snapshot;
+ 	Oid			root_save_userid;
+ 	int			root_save_sec_context;
+@@ -154,14 +155,18 @@ DefineIndex(RangeVar *heapRelation,
+ 						INDEX_MAX_KEYS)));
+ 
+ 	/*
+-	 * Open heap relation, acquire a suitable lock on it, remember its OID
+-	 *
+ 	 * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
+ 	 * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
+ 	 * (but not VACUUM).
++	 *
++	 * NB: Caller is responsible for making sure that relationId refers
++	 * to the relation on which the index should be built; except in bootstrap
++	 * mode, this will typically require the caller to have already locked
++	 * the relation.  To avoid lock upgrade hazards, that lock should be at
++	 * least as strong as the one we take here.
+ 	 */
+-	rel = heap_openrv(heapRelation,
+-					  (concurrent ? ShareUpdateExclusiveLock : ShareLock));
++	lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
++	rel = heap_open(relationId, lockmode);
+ 
+ 	/*
+ 	 * Switch to the table owner's userid, so that any index functions are run
+@@ -182,7 +187,7 @@ DefineIndex(RangeVar *heapRelation,
+ 		ereport(ERROR,
+ 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ 				 errmsg("\"%s\" is not a table",
+-						heapRelation->relname)));
++						RelationGetRelationName(rel))));
+ 
+ 	/*
+ 	 * Don't try to CREATE INDEX on temp tables of other backends.
+@@ -560,7 +565,7 @@ DefineIndex(RangeVar *heapRelation,
+ 	 */
+ 
+ 	/* Open and lock the parent heap relation */
+-	rel = heap_openrv(heapRelation, ShareUpdateExclusiveLock);
++	rel = heap_open(relationId, ShareUpdateExclusiveLock);
+ 
+ 	/*
+ 	 * Switch to the table owner's userid, so that any index functions are run
+diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
+index ca17411..aeb5475 100644
+--- a/src/backend/commands/tablecmds.c
++++ b/src/backend/commands/tablecmds.c
+@@ -59,6 +59,7 @@
+ #include "rewrite/rewriteHandler.h"
+ #include "rewrite/rewriteManip.h"
+ #include "storage/smgr.h"
++#include "tcop/utility.h"
+ #include "utils/acl.h"
+ #include "utils/builtins.h"
+ #include "utils/fmgroids.h"
+@@ -192,8 +193,8 @@ static Oid transformFkeyCheckAttrs(Relation pkrel,
+ 						Oid *opclasses);
+ static void validateForeignKeyConstraint(FkConstraint *fkconstraint,
+ 							 Relation rel, Relation pkrel, Oid constraintOid);
+-static void createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+-						 Oid constraintOid);
++static void createForeignKeyTriggers(Relation rel, Oid refRelOid,
++						 FkConstraint *fkconstraint, Oid constraintOid);
+ static void ATController(Relation rel, List *cmds, bool recurse);
+ static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
+ 		  bool recurse, bool recursing);
+@@ -244,7 +245,8 @@ static void ATPrepAlterColumnType(List **wqueue,
+ static void ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
+ 					  const char *colName, TypeName *typename);
+ static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab);
+-static void ATPostAlterTypeParse(char *cmd, List **wqueue);
++static void ATPostAlterTypeParse(Oid oldRelId, Oid refRelId, char *cmd,
++					 List **wqueue);
+ static void change_owner_recurse_to_sequences(Oid relationOid,
+ 								  Oid newOwnerId);
+ static void ATExecClusterOn(Relation rel, const char *indexName);
+@@ -1739,9 +1741,12 @@ CheckTableNotInUse(Relation rel, const char *stmt)
+  * the whole operation; we don't have to do anything special to clean up.
+  */
+ void
+-AlterTable(AlterTableStmt *stmt)
++AlterTable(Oid relid, AlterTableStmt *stmt)
+ {
+-	Relation	rel = relation_openrv(stmt->relation, AccessExclusiveLock);
++	Relation	rel;
++
++	/* Caller is required to provide an adequate lock. */
++	rel = relation_open(relid, NoLock);
+ 
+ 	CheckTableNotInUse(rel, "ALTER TABLE");
+ 
+@@ -3756,7 +3761,7 @@ ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
+ 
+ 	/* The IndexStmt has already been through transformIndexStmt */
+ 
+-	DefineIndex(stmt->relation, /* relation */
++	DefineIndex(RelationGetRelid(rel), /* relation */
+ 				stmt->idxname,	/* index name */
+ 				InvalidOid,		/* no predefined OID */
+ 				stmt->accessMethod,		/* am name */
+@@ -3900,7 +3905,10 @@ ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
+ 	 * table; trying to start with a lesser lock will just create a risk of
+ 	 * deadlock.)
+ 	 */
+-	pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
++	if (OidIsValid(fkconstraint->old_pktable_oid))
++		pkrel = heap_open(fkconstraint->old_pktable_oid, AccessExclusiveLock);
++	else
++		pkrel = heap_openrv(fkconstraint->pktable, AccessExclusiveLock);
+ 
+ 	/*
+ 	 * Validity and permissions checks
+@@ -4142,7 +4150,8 @@ ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
+ 	/*
+ 	 * Create the triggers that will enforce the constraint.
+ 	 */
+-	createForeignKeyTriggers(rel, fkconstraint, constrOid);
++	createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
++							 constrOid);
+ 
+ 	/*
+ 	 * Tell Phase 3 to check that the constraint is satisfied by existing rows
+@@ -4490,14 +4499,14 @@ validateForeignKeyConstraint(FkConstraint *fkconstraint,
+ }
+ 
+ static void
+-CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
++CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, FkConstraint *fkconstraint,
+ 					 Oid constraintOid, bool on_insert)
+ {
+ 	CreateTrigStmt *fk_trigger;
+ 
+ 	fk_trigger = makeNode(CreateTrigStmt);
+ 	fk_trigger->trigname = fkconstraint->constr_name;
+-	fk_trigger->relation = myRel;
++	fk_trigger->relation = NULL;
+ 	fk_trigger->before = false;
+ 	fk_trigger->row = true;
+ 
+@@ -4517,10 +4526,10 @@ CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
+ 	fk_trigger->isconstraint = true;
+ 	fk_trigger->deferrable = fkconstraint->deferrable;
+ 	fk_trigger->initdeferred = fkconstraint->initdeferred;
+-	fk_trigger->constrrel = fkconstraint->pktable;
++	fk_trigger->constrrel = NULL;
+ 	fk_trigger->args = NIL;
+ 
+-	(void) CreateTrigger(fk_trigger, constraintOid);
++	(void) CreateTrigger(fk_trigger, myRelOid, refRelOid, constraintOid);
+ 
+ 	/* Make changes-so-far visible */
+ 	CommandCounterIncrement();
+@@ -4530,17 +4539,13 @@ CreateFKCheckTrigger(RangeVar *myRel, FkConstraint *fkconstraint,
+  * Create the triggers that implement an FK constraint.
+  */
+ static void
+-createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+-						 Oid constraintOid)
++createForeignKeyTriggers(Relation rel, Oid refRelOid,
++						 FkConstraint *fkconstraint, Oid constraintOid)
+ {
+-	RangeVar   *myRel;
++	Oid			myRelOid;
+ 	CreateTrigStmt *fk_trigger;
+ 
+-	/*
+-	 * Reconstruct a RangeVar for my relation (not passed in, unfortunately).
+-	 */
+-	myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
+-						 pstrdup(RelationGetRelationName(rel)));
++	myRelOid = RelationGetRelid(rel);
+ 
+ 	/* Make changes-so-far visible */
+ 	CommandCounterIncrement();
+@@ -4551,14 +4556,14 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+ 	 */
+ 	fk_trigger = makeNode(CreateTrigStmt);
+ 	fk_trigger->trigname = fkconstraint->constr_name;
+-	fk_trigger->relation = fkconstraint->pktable;
++	fk_trigger->relation = NULL;
+ 	fk_trigger->before = false;
+ 	fk_trigger->row = true;
+ 	fk_trigger->actions[0] = 'd';
+ 	fk_trigger->actions[1] = '\0';
+ 
+ 	fk_trigger->isconstraint = true;
+-	fk_trigger->constrrel = myRel;
++	fk_trigger->constrrel = NULL;
+ 	switch (fkconstraint->fk_del_action)
+ 	{
+ 		case FKCONSTR_ACTION_NOACTION:
+@@ -4593,7 +4598,7 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+ 	}
+ 	fk_trigger->args = NIL;
+ 
+-	(void) CreateTrigger(fk_trigger, constraintOid);
++	(void) CreateTrigger(fk_trigger, refRelOid, myRelOid, constraintOid);
+ 
+ 	/* Make changes-so-far visible */
+ 	CommandCounterIncrement();
+@@ -4604,13 +4609,13 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+ 	 */
+ 	fk_trigger = makeNode(CreateTrigStmt);
+ 	fk_trigger->trigname = fkconstraint->constr_name;
+-	fk_trigger->relation = fkconstraint->pktable;
++	fk_trigger->relation = NULL;
+ 	fk_trigger->before = false;
+ 	fk_trigger->row = true;
+ 	fk_trigger->actions[0] = 'u';
+ 	fk_trigger->actions[1] = '\0';
+ 	fk_trigger->isconstraint = true;
+-	fk_trigger->constrrel = myRel;
++	fk_trigger->constrrel = NULL;
+ 	switch (fkconstraint->fk_upd_action)
+ 	{
+ 		case FKCONSTR_ACTION_NOACTION:
+@@ -4645,7 +4650,7 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+ 	}
+ 	fk_trigger->args = NIL;
+ 
+-	(void) CreateTrigger(fk_trigger, constraintOid);
++	(void) CreateTrigger(fk_trigger, refRelOid, myRelOid, constraintOid);
+ 
+ 	/* Make changes-so-far visible */
+ 	CommandCounterIncrement();
+@@ -4665,8 +4670,10 @@ createForeignKeyTriggers(Relation rel, FkConstraint *fkconstraint,
+ 	 * and the use of self-referential FKs is rare enough, that we live with
+ 	 * it for now.  There will be a real fix in PG 9.2.
+ 	 */
+-	CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, true);
+-	CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, false);
++	CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
++						 constraintOid, true);
++	CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
++						 constraintOid, false);
+ }
+ 
+ /*
+@@ -5189,7 +5196,8 @@ static void
+ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
+ {
+ 	ObjectAddress obj;
+-	ListCell   *l;
++	ListCell   *def_item;
++	ListCell   *oid_item;
+ 
+ 	/*
+ 	 * Re-parse the index and constraint definitions, and attach them to the
+@@ -5198,11 +5206,44 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
+ 	 * lock on the table the constraint is attached to, and we need to get
+ 	 * that before dropping.  It's safe because the parser won't actually look
+ 	 * at the catalogs to detect the existing entry.
+-	 */
+-	foreach(l, tab->changedIndexDefs)
+-		ATPostAlterTypeParse((char *) lfirst(l), wqueue);
+-	foreach(l, tab->changedConstraintDefs)
+-		ATPostAlterTypeParse((char *) lfirst(l), wqueue);
++	 *
++	 * We can't rely on the output of deparsing to tell us which relation
++	 * to operate on, because concurrent activity might have made the name
++	 * resolve differently.  Instead, we've got to use the OID of the
++	 * constraint or index we're processing to figure out which relation
++	 * to operate on.
++	 */
++	forboth(oid_item, tab->changedConstraintOids,
++			def_item, tab->changedConstraintDefs)
++	{
++		Oid		oldId = lfirst_oid(oid_item);
++		Oid		relid;
++		Oid		confrelid;
++
++		get_constraint_relation_oids(oldId, &relid, &confrelid);
++
++		/*
++		 * A FOREIGN KEY referencing the table we're modifying lives on
++		 * another table we may not have locked yet; DROP CONSTRAINT needs
++		 * AccessExclusiveLock there anyway.
++		 */
++		if (relid != tab->relid)
++			LockRelationOid(relid, AccessExclusiveLock);
++		ATPostAlterTypeParse(relid, confrelid,
++							 (char *) lfirst(def_item),
++							 wqueue);
++	}
++	forboth(oid_item, tab->changedIndexOids,
++			def_item, tab->changedIndexDefs)
++	{
++		Oid		oldId = lfirst_oid(oid_item);
++		Oid		relid;
++
++		relid = IndexGetRelation(oldId);
++		ATPostAlterTypeParse(relid, InvalidOid,
++							 (char *) lfirst(def_item),
++							 wqueue);
++	}
+ 
+ 	/*
+ 	 * Now we can drop the existing constraints and indexes --- constraints
+@@ -5212,18 +5253,18 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
+ 	 * should be okay to use DROP_RESTRICT here, since nothing else should be
+ 	 * depending on these objects.
+ 	 */
+-	foreach(l, tab->changedConstraintOids)
++	foreach(oid_item, tab->changedConstraintOids)
+ 	{
+ 		obj.classId = ConstraintRelationId;
+-		obj.objectId = lfirst_oid(l);
++		obj.objectId = lfirst_oid(oid_item);
+ 		obj.objectSubId = 0;
+ 		performDeletion(&obj, DROP_RESTRICT);
+ 	}
+ 
+-	foreach(l, tab->changedIndexOids)
++	foreach(oid_item, tab->changedIndexOids)
+ 	{
+ 		obj.classId = RelationRelationId;
+-		obj.objectId = lfirst_oid(l);
++		obj.objectId = lfirst_oid(oid_item);
+ 		obj.objectSubId = 0;
+ 		performDeletion(&obj, DROP_RESTRICT);
+ 	}
+@@ -5235,11 +5276,12 @@ ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab)
+ }
+ 
+ static void
+-ATPostAlterTypeParse(char *cmd, List **wqueue)
++ATPostAlterTypeParse(Oid oldRelId, Oid refRelId, char *cmd, List **wqueue)
+ {
+ 	List	   *raw_parsetree_list;
+ 	List	   *querytree_list;
+ 	ListCell   *list_item;
++	Relation	rel;
+ 
+ 	/*
+ 	 * We expect that we will get only ALTER TABLE and CREATE INDEX
+@@ -5255,16 +5297,21 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 
+ 		if (IsA(stmt, IndexStmt))
+ 			querytree_list = lappend(querytree_list,
+-									 transformIndexStmt((IndexStmt *) stmt,
++									 transformIndexStmt(oldRelId,
++														(IndexStmt *) stmt,
+ 														cmd));
+ 		else if (IsA(stmt, AlterTableStmt))
+ 			querytree_list = list_concat(querytree_list,
+-							 transformAlterTableStmt((AlterTableStmt *) stmt,
++							 transformAlterTableStmt(oldRelId,
++													 (AlterTableStmt *) stmt,
+ 													 cmd));
+ 		else
+ 			querytree_list = lappend(querytree_list, stmt);
+ 	}
+ 
++	/* Caller should already have acquired whatever lock we need. */
++	rel = relation_open(oldRelId, NoLock);
++
+ 	/*
+ 	 * Attach each generated command to the proper place in the work queue.
+ 	 * Note this could result in creation of entirely new work-queue entries.
+@@ -5272,7 +5319,6 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 	foreach(list_item, querytree_list)
+ 	{
+ 		Node	   *stm = (Node *) lfirst(list_item);
+-		Relation	rel;
+ 		AlteredTableInfo *tab;
+ 
+ 		switch (nodeTag(stm))
+@@ -5282,14 +5328,12 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 					IndexStmt  *stmt = (IndexStmt *) stm;
+ 					AlterTableCmd *newcmd;
+ 
+-					rel = relation_openrv(stmt->relation, AccessExclusiveLock);
+ 					tab = ATGetQueueEntry(wqueue, rel);
+ 					newcmd = makeNode(AlterTableCmd);
+ 					newcmd->subtype = AT_ReAddIndex;
+ 					newcmd->def = (Node *) stmt;
+ 					tab->subcmds[AT_PASS_OLD_INDEX] =
+ 						lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
+-					relation_close(rel, NoLock);
+ 					break;
+ 				}
+ 			case T_AlterTableStmt:
+@@ -5297,7 +5341,6 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 					AlterTableStmt *stmt = (AlterTableStmt *) stm;
+ 					ListCell   *lcmd;
+ 
+-					rel = relation_openrv(stmt->relation, AccessExclusiveLock);
+ 					tab = ATGetQueueEntry(wqueue, rel);
+ 					foreach(lcmd, stmt->cmds)
+ 					{
+@@ -5311,6 +5354,9 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 									lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
+ 								break;
+ 							case AT_AddConstraint:
++								/* re-add the FK against the same PK table */
++								if (IsA(cmd->def, FkConstraint))
++									((FkConstraint *) cmd->def)->old_pktable_oid = refRelId;
+ 								tab->subcmds[AT_PASS_OLD_CONSTR] =
+ 									lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
+ 								break;
+@@ -5319,7 +5365,6 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 									 (int) cmd->subtype);
+ 						}
+ 					}
+-					relation_close(rel, NoLock);
+ 					break;
+ 				}
+ 			default:
+@@ -5327,8 +5372,9 @@ ATPostAlterTypeParse(char *cmd, List **wqueue)
+ 					 (int) nodeTag(stm));
+ 		}
+ 	}
+-}
+ 
++	relation_close(rel, NoLock);
++}
+ 
+ /*
+  * ALTER TABLE OWNER
+@@ -6487,7 +6533,8 @@ ATExecDropInherit(Relation rel, RangeVar *parent)
+ /*
+  * Execute ALTER TABLE SET SCHEMA
+  *
+- * Note: caller must have checked ownership of the relation already
++ * WARNING WARNING WARNING: In previous *minor* releases the caller was
++ * responsible for checking ownership of the relation, but now we do it here.
+  */
+ void
+ AlterTableNamespace(RangeVar *relation, const char *newschema)
+@@ -6501,6 +6548,7 @@ AlterTableNamespace(RangeVar *relation, const char *newschema)
+ 	rel = relation_openrv(relation, AccessExclusiveLock);
+ 
+ 	relid = RelationGetRelid(rel);
++	CheckRelationOwnership(relid, true);
+ 	oldNspOid = RelationGetNamespace(rel);
+ 
+ 	/* Can we change the schema of this tuple? */
+diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
+index 0d1ba74..13ea8a1 100644
+--- a/src/backend/commands/trigger.c
++++ b/src/backend/commands/trigger.c
+@@ -64,6 +64,13 @@ static void AfterTriggerSaveEvent(ResultRelInfo *relinfo, int event,
+ /*
+  * Create a trigger.  Returns the OID of the created trigger.
+  *
++ * relOid, if nonzero, is the relation on which the trigger should be
++ * created.  If zero, the name provided in the statement will be looked up.
++ *
++ * refRelOid, if nonzero, is the relation to which the constraint trigger
++ * refers.  If zero, the constraint relation name provided in the statement
++ * will be looked up as needed.
++ *
+  * constraintOid, if nonzero, says that this trigger is being created
+  * internally to implement that constraint.  A suitable pg_depend entry will
+  * be made to link the trigger to that constraint.	constraintOid is zero when
+@@ -73,7 +80,8 @@ static void AfterTriggerSaveEvent(ResultRelInfo *relinfo, int event,
+  * but a foreign-key constraint.  This is a kluge for backwards compatibility.
+  */
+ Oid
+-CreateTrigger(CreateTrigStmt *stmt, Oid constraintOid)
++CreateTrigger(CreateTrigStmt *stmt, Oid relOid, Oid refRelOid,
++			  Oid constraintOid)
+ {
+ 	int16		tgtype;
+ 	int2vector *tgattr;
+@@ -99,7 +107,10 @@ CreateTrigger(CreateTrigStmt *stmt, Oid constraintOid)
+ 	ObjectAddress myself,
+ 				referenced;
+ 
+-	rel = heap_openrv(stmt->relation, AccessExclusiveLock);
++	if (OidIsValid(relOid))
++		rel = heap_open(relOid, AccessExclusiveLock);
++	else
++		rel = heap_openrv(stmt->relation, AccessExclusiveLock);
+ 
+ 	if (rel->rd_rel->relkind != RELKIND_RELATION)
+ 		ereport(ERROR,
+@@ -124,9 +135,12 @@ CreateTrigger(CreateTrigStmt *stmt, Oid constraintOid)
+ 			aclcheck_error(aclresult, ACL_KIND_CLASS,
+ 						   RelationGetRelationName(rel));
+ 
+-		if (stmt->constrrel != NULL)
++		if (OidIsValid(refRelOid) || stmt->constrrel != NULL)
+ 		{
+-			constrrelid = RangeVarGetRelid(stmt->constrrel, false);
++			if (OidIsValid(refRelOid))
++				constrrelid = refRelOid;
++			else
++				constrrelid = RangeVarGetRelid(stmt->constrrel, false);
+ 
+ 			aclresult = pg_class_aclcheck(constrrelid, GetUserId(),
+ 										  ACL_REFERENCES);
+@@ -289,7 +303,7 @@ CreateTrigger(CreateTrigStmt *stmt, Oid constraintOid)
+ 			ereport(ERROR,
+ 					(errcode(ERRCODE_DUPLICATE_OBJECT),
+ 				  errmsg("trigger \"%s\" for relation \"%s\" already exists",
+-						 trigname, stmt->relation->relname)));
++						 trigname, RelationGetRelationName(rel))));
+ 		found++;
+ 	}
+ 	systable_endscan(tgscan);
+diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c
+index 528a461..4199e9f 100644
+--- a/src/backend/nodes/copyfuncs.c
++++ b/src/backend/nodes/copyfuncs.c
+@@ -1545,6 +1545,7 @@ _copyFkConstraint(FkConstraint *from)
+ 	COPY_SCALAR_FIELD(deferrable);
+ 	COPY_SCALAR_FIELD(initdeferred);
+ 	COPY_SCALAR_FIELD(skip_validation);
++	COPY_SCALAR_FIELD(old_pktable_oid);
+ 
+ 	return newnode;
+ }
+diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c
+index e2509d4..008703b 100644
+--- a/src/backend/nodes/equalfuncs.c
++++ b/src/backend/nodes/equalfuncs.c
+@@ -1911,6 +1911,7 @@ _equalFkConstraint(FkConstraint *a, FkConstraint *b)
+ 	COMPARE_SCALAR_FIELD(deferrable);
+ 	COMPARE_SCALAR_FIELD(initdeferred);
+ 	COMPARE_SCALAR_FIELD(skip_validation);
++	COMPARE_SCALAR_FIELD(old_pktable_oid);
+ 
+ 	return true;
+ }
+diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
+index f754f17..216c4eb 100644
+--- a/src/backend/nodes/outfuncs.c
++++ b/src/backend/nodes/outfuncs.c
+@@ -2056,6 +2056,7 @@ _outFkConstraint(StringInfo str, FkConstraint *node)
+ 	WRITE_BOOL_FIELD(deferrable);
+ 	WRITE_BOOL_FIELD(initdeferred);
+ 	WRITE_BOOL_FIELD(skip_validation);
++	WRITE_OID_FIELD(old_pktable_oid);
+ }
+ 
+ 
+diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
+index 3c9462f..dcb77b7 100644
+--- a/src/backend/parser/parse_utilcmd.c
++++ b/src/backend/parser/parse_utilcmd.c
+@@ -1337,14 +1337,18 @@ transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
+  * a predicate expression.	There are several code paths that create indexes
+  * without bothering to call this, because they know they don't have any
+  * such expressions to deal with.
++ *
++ * To avoid race conditions, it's important that this function rely only on
++ * the passed-in relid (and not on stmt->relation) to determine the target
++ * relation.
+  */
+ IndexStmt *
+-transformIndexStmt(IndexStmt *stmt, const char *queryString)
++transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
+ {
+-	Relation	rel;
+ 	ParseState *pstate;
+ 	RangeTblEntry *rte;
+ 	ListCell   *l;
++	Relation	rel;
+ 
+ 	/*
+ 	 * We must not scribble on the passed-in IndexStmt, so copy it.  (This is
+@@ -1352,25 +1356,17 @@ transformIndexStmt(IndexStmt *stmt, const char *queryString)
+ 	 */
+ 	stmt = (IndexStmt *) copyObject(stmt);
+ 
+-	/*
+-	 * Open the parent table with appropriate locking.	We must do this
+-	 * because addRangeTableEntry() would acquire only AccessShareLock,
+-	 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
+-	 * of deadlock.  Make sure this stays in sync with the type of lock
+-	 * DefineIndex() wants.
+-	 */
+-	rel = heap_openrv(stmt->relation,
+-				  (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
+-
+ 	/* Set up pstate */
+ 	pstate = make_parsestate(NULL);
+ 	pstate->p_sourcetext = queryString;
+ 
+ 	/*
+ 	 * Put the parent table into the rtable so that the expressions can refer
+-	 * to its fields without qualification.
++	 * to its fields without qualification.  Caller is responsible for locking
++	 * relation, but we still need to open it.
+ 	 */
+-	rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
++	rel = relation_open(relid, NoLock);
++	rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
+ 
+ 	/* no to join list, yes to namespaces */
+ 	addRTEtoQuery(pstate, rte, false, true, true);
+@@ -1412,7 +1408,7 @@ transformIndexStmt(IndexStmt *stmt, const char *queryString)
+ 
+ 	free_parsestate(pstate);
+ 
+-	/* Close relation, but keep the lock */
++	/* Close relation */
+ 	heap_close(rel, NoLock);
+ 
+ 	return stmt;
+@@ -1699,9 +1695,14 @@ transformRuleStmt(RuleStmt *stmt, const char *queryString,
+  * Returns a List of utility commands to be done in sequence.  One of these
+  * will be the transformed AlterTableStmt, but there may be additional actions
+  * to be done before and after the actual AlterTable() call.
++ *
++ * To avoid race conditions, it's important that this function rely only on
++ * the passed-in relid (and not on stmt->relation) to determine the target
++ * relation.
+  */
+ List *
+-transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
++transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
++						const char *queryString)
+ {
+ 	Relation	rel;
+ 	ParseState *pstate;
+@@ -1720,14 +1721,8 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
+ 	 */
+ 	stmt = (AlterTableStmt *) copyObject(stmt);
+ 
+-	/*
+-	 * Acquire exclusive lock on the target relation, which will be held until
+-	 * end of transaction.	This ensures any decisions we make here based on
+-	 * the state of the relation will still be good at execution. We must get
+-	 * exclusive lock now because execution will; taking a lower grade lock
+-	 * now and trying to upgrade later risks deadlock.
+-	 */
+-	rel = relation_openrv(stmt->relation, AccessExclusiveLock);
++	/* Caller is responsible for locking the relation */
++	rel = relation_open(relid, NoLock);
+ 
+ 	/* Set up pstate */
+ 	pstate = make_parsestate(NULL);
+@@ -1861,7 +1856,7 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
+ 		Assert(IsA(idxstmt, IndexStmt));
+ 		newcmd = makeNode(AlterTableCmd);
+ 		newcmd->subtype = AT_AddIndex;
+-		newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
++		newcmd->def = (Node *) transformIndexStmt(relid, (IndexStmt *) idxstmt,
+ 												  queryString);
+ 		newcmds = lappend(newcmds, newcmd);
+ 	}
+@@ -1883,7 +1878,7 @@ transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
+ 		newcmds = lappend(newcmds, newcmd);
+ 	}
+ 
+-	/* Close rel but keep lock */
++	/* Close rel */
+ 	relation_close(rel, NoLock);
+ 
+ 	/*
+diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
+index c255cb7..b4fdd54 100644
+--- a/src/backend/tcop/utility.c
++++ b/src/backend/tcop/utility.c
+@@ -50,11 +50,13 @@
+ #include "rewrite/rewriteDefine.h"
+ #include "rewrite/rewriteRemove.h"
+ #include "storage/fd.h"
++#include "storage/lmgr.h"
+ #include "tcop/pquery.h"
+ #include "tcop/utility.h"
+ #include "utils/acl.h"
+ #include "utils/guc.h"
+ #include "utils/syscache.h"
++#include "utils/lsyscache.h"
+ 
+ 
+ /*
+@@ -219,12 +221,10 @@ CheckDropPermissions(RangeVar *rel, char rightkind, bool missing_ok)
+  * except when allowSystemTableMods is true.
+  */
+ void
+-CheckRelationOwnership(RangeVar *rel, bool noCatalogs)
++CheckRelationOwnership(Oid relOid, bool noCatalogs)
+ {
+-	Oid			relOid;
+ 	HeapTuple	tuple;
+ 
+-	relOid = RangeVarGetRelid(rel, false);
+ 	tuple = SearchSysCache(RELOID,
+ 						   ObjectIdGetDatum(relOid),
+ 						   0, 0, 0);
+@@ -233,7 +233,7 @@ CheckRelationOwnership(RangeVar *rel, bool noCatalogs)
+ 
+ 	if (!pg_class_ownercheck(relOid, GetUserId()))
+ 		aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
+-					   rel->relname);
++					   get_rel_name(relOid));
+ 
+ 	if (noCatalogs)
+ 	{
+@@ -242,7 +242,7 @@ CheckRelationOwnership(RangeVar *rel, bool noCatalogs)
+ 			ereport(ERROR,
+ 					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ 					 errmsg("permission denied: \"%s\" is a system catalog",
+-							rel->relname)));
++							get_rel_name(relOid))));
+ 	}
+ 
+ 	ReleaseSysCache(tuple);
+@@ -770,9 +770,21 @@ ProcessUtility(Node *parsetree,
+ 			{
+ 				List	   *stmts;
+ 				ListCell   *l;
++				AlterTableStmt *atstmt = (AlterTableStmt *) parsetree;
++				Oid			relid;
++
++				/*
++				 * Look up the relation OID just once, right here at the
++				 * beginning, so that we don't end up repeating the name
++				 * lookup later and latching onto a different relation
++				 * partway through.
++				 */
++				relid = RangeVarGetRelid(atstmt->relation, false);
++				LockRelationOid(relid, AccessExclusiveLock);
+ 
+ 				/* Run parse analysis ... */
+-				stmts = transformAlterTableStmt((AlterTableStmt *) parsetree,
++				stmts = transformAlterTableStmt(relid,
++												atstmt,
+ 												queryString);
+ 
+ 				/* ... and do it */
+@@ -783,7 +795,7 @@ ProcessUtility(Node *parsetree,
+ 					if (IsA(stmt, AlterTableStmt))
+ 					{
+ 						/* Do the table alteration proper */
+-						AlterTable((AlterTableStmt *) stmt);
++						AlterTable(relid, (AlterTableStmt *) stmt);
+ 					}
+ 					else
+ 					{
+@@ -927,18 +939,33 @@ ProcessUtility(Node *parsetree,
+ 		case T_IndexStmt:		/* CREATE INDEX */
+ 			{
+ 				IndexStmt  *stmt = (IndexStmt *) parsetree;
++				Oid			relid;
++				LOCKMODE	lockmode;
+ 
+ 				if (stmt->concurrent)
+ 					PreventTransactionChain(isTopLevel,
+ 											"CREATE INDEX CONCURRENTLY");
+ 
+-				CheckRelationOwnership(stmt->relation, true);
++				/*
++				 * Look up the relation OID just once, right here at the
++				 * beginning, so that we don't end up repeating the name
++				 * lookup later and latching onto a different relation
++				 * partway through.  To avoid lock upgrade hazards, it's
++				 * important that we take the strongest lock that will
++				 * eventually be needed here, so the lockmode calculation
++				 * needs to match what DefineIndex() does.
++				 */
++				lockmode = stmt->concurrent ? ShareUpdateExclusiveLock
++					: ShareLock;
++				relid = RangeVarGetRelid(stmt->relation, false);
++				LockRelationOid(relid, lockmode);
++				CheckRelationOwnership(relid, true);
+ 
+ 				/* Run parse analysis ... */
+-				stmt = transformIndexStmt(stmt, queryString);
++				stmt = transformIndexStmt(relid, stmt, queryString);
+ 
+ 				/* ... and do it */
+-				DefineIndex(stmt->relation,		/* relation */
++				DefineIndex(relid,		/* relation */
+ 							stmt->idxname,		/* index name */
+ 							InvalidOid, /* no predefined OID */
+ 							stmt->accessMethod, /* am name */
+@@ -1082,7 +1109,8 @@ ProcessUtility(Node *parsetree,
+ 			break;
+ 
+ 		case T_CreateTrigStmt:
+-			CreateTrigger((CreateTrigStmt *) parsetree, InvalidOid);
++			CreateTrigger((CreateTrigStmt *) parsetree, InvalidOid, InvalidOid,
++						  InvalidOid);
+ 			break;
+ 
+ 		case T_DropPropertyStmt:
+diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h
+index 2112319..e41f4d0 100644
+--- a/src/include/catalog/index.h
++++ b/src/include/catalog/index.h
+@@ -82,4 +82,6 @@ extern void index_set_state_flags(Oid indexId, IndexStateFlagsAction action);
+ extern void reindex_index(Oid indexId);
+ extern bool reindex_relation(Oid relid, bool toast_too);
+ 
++extern Oid	IndexGetRelation(Oid indexId);
++
+ #endif   /* INDEX_H */
+diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h
+index 4c0fd51..0af7aff 100644
+--- a/src/include/catalog/pg_constraint.h
++++ b/src/include/catalog/pg_constraint.h
+@@ -211,5 +211,6 @@ extern char *ChooseConstraintName(const char *name1, const char *name2,
+ 
+ extern void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId,
+ 						  Oid newNspId, bool isType);
++extern void get_constraint_relation_oids(Oid constraint_oid, Oid *conrelid, Oid *confrelid);
+ 
+ #endif   /* PG_CONSTRAINT_H */
+diff --git a/src/include/commands/defrem.h b/src/include/commands/defrem.h
+index 75a50b8..2b830bc 100644
+--- a/src/include/commands/defrem.h
++++ b/src/include/commands/defrem.h
+@@ -18,7 +18,7 @@
+ 
+ 
+ /* commands/indexcmds.c */
+-extern void DefineIndex(RangeVar *heapRelation,
++extern void DefineIndex(Oid relationId,
+ 			char *indexRelationName,
+ 			Oid indexRelationId,
+ 			char *accessMethodName,
+diff --git a/src/include/commands/tablecmds.h b/src/include/commands/tablecmds.h
+index 6638074..bc7a62d 100644
+--- a/src/include/commands/tablecmds.h
++++ b/src/include/commands/tablecmds.h
+@@ -22,7 +22,7 @@ extern Oid	DefineRelation(CreateStmt *stmt, char relkind);
+ 
+ extern void RemoveRelation(const RangeVar *relation, DropBehavior behavior);
+ 
+-extern void AlterTable(AlterTableStmt *stmt);
++extern void AlterTable(Oid relid, AlterTableStmt *stmt);
+ 
+ extern void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing);
+ 
+diff --git a/src/include/commands/trigger.h b/src/include/commands/trigger.h
+index 32214e6..0c09e7a 100644
+--- a/src/include/commands/trigger.h
++++ b/src/include/commands/trigger.h
+@@ -91,7 +91,8 @@ extern PGDLLIMPORT int	SessionReplicationRole;
+ #define TRIGGER_FIRES_ON_REPLICA			'R'
+ #define TRIGGER_DISABLED					'D'
+ 
+-extern Oid	CreateTrigger(CreateTrigStmt *stmt, Oid constraintOid);
++extern Oid CreateTrigger(CreateTrigStmt *stmt, Oid relOid, Oid refRelOid,
++			  Oid constraintOid);
+ 
+ extern void DropTrigger(Oid relid, const char *trigname,
+ 			DropBehavior behavior, bool missing_ok);
+diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
+index c973eea..452aaff 100644
+--- a/src/include/nodes/parsenodes.h
++++ b/src/include/nodes/parsenodes.h
+@@ -1196,6 +1196,7 @@ typedef struct FkConstraint
+ 	bool		deferrable;		/* DEFERRABLE */
+ 	bool		initdeferred;	/* INITIALLY DEFERRED */
+ 	bool		skip_validation;	/* skip validation of existing rows? */
++	Oid			old_pktable_oid; /* pg_constraint.confrelid of my former self */
+ } FkConstraint;
+ 
+ 
+diff --git a/src/include/parser/parse_utilcmd.h b/src/include/parser/parse_utilcmd.h
+index 517e986..5819361 100644
+--- a/src/include/parser/parse_utilcmd.h
++++ b/src/include/parser/parse_utilcmd.h
+@@ -18,9 +18,10 @@
+ 
+ 
+ extern List *transformCreateStmt(CreateStmt *stmt, const char *queryString);
+-extern List *transformAlterTableStmt(AlterTableStmt *stmt,
++extern List *transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
+ 						const char *queryString);
+-extern IndexStmt *transformIndexStmt(IndexStmt *stmt, const char *queryString);
++extern IndexStmt *transformIndexStmt(Oid relid, IndexStmt *stmt,
++				   const char *queryString);
+ extern void transformRuleStmt(RuleStmt *stmt, const char *queryString,
+ 				  List **actions, Node **whereClause);
+ extern List *transformCreateSchemaStmt(CreateSchemaStmt *stmt);
+diff --git a/src/include/tcop/utility.h b/src/include/tcop/utility.h
+index fbf7bb5..d5913c1 100644
+--- a/src/include/tcop/utility.h
++++ b/src/include/tcop/utility.h
+@@ -31,6 +31,6 @@ extern LogStmtLevel GetCommandLogLevel(Node *parsetree);
+ 
+ extern bool CommandIsReadOnly(Node *parsetree);
+ 
+-extern void CheckRelationOwnership(RangeVar *rel, bool noCatalogs);
++extern void CheckRelationOwnership(Oid relOid, bool noCatalogs);
+ 
+ #endif   /* UTILITY_H */
diff --git a/postgresql-CVE-2014-0063.patch b/postgresql-CVE-2014-0063.patch
new file mode 100644
index 0000000..7e88ec5
--- /dev/null
+++ b/postgresql-CVE-2014-0063.patch
@@ -0,0 +1,228 @@
+Fix overruns of fixed-size buffers with wide datetime input/output (ecpg
+test hunks dropped).
+Source: upstream d0ed1a6c04 (REL8_4)
+
+diff --git a/src/include/utils/datetime.h b/src/include/utils/datetime.h
+index ffb4c45..a7d5ad3 100644
+--- a/src/include/utils/datetime.h
++++ b/src/include/utils/datetime.h
+@@ -183,12 +183,17 @@
+ #define DTK_DATE_M		(DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY))
+ #define DTK_TIME_M		(DTK_M(HOUR) | DTK_M(MINUTE) | DTK_ALL_SECS_M)
+ 
+-#define MAXDATELEN		63		/* maximum possible length of an input date
+-								 * string (not counting tr. null) */
+-#define MAXDATEFIELDS	25		/* maximum possible number of fields in a date
+-								 * string */
+-#define TOKMAXLEN		10		/* only this many chars are stored in
+-								 * datetktbl */
++/*
++ * Working buffer size for input and output of interval, timestamp, etc.
++ * Inputs that need more working space will be rejected early.  Longer outputs
++ * will overrun buffers, so this must suffice for all possible output.  As of
++ * this writing, interval_out() needs the most space at ~90 bytes.
++ */
++#define MAXDATELEN		128
++/* maximum possible number of fields in a date string */
++#define MAXDATEFIELDS	25
++/* only this many chars are stored in datetktbl */
++#define TOKMAXLEN		10
+ 
+ /* keep this struct small; it gets used a lot */
+ typedef struct
+diff --git a/src/interfaces/ecpg/pgtypeslib/datetime.c b/src/interfaces/ecpg/pgtypeslib/datetime.c
+index 3910859..21259a6 100644
+--- a/src/interfaces/ecpg/pgtypeslib/datetime.c
++++ b/src/interfaces/ecpg/pgtypeslib/datetime.c
+@@ -61,14 +61,14 @@ PGTYPESdate_from_asc(char *str, char **endptr)
+ 	int			nf;
+ 	char	   *field[MAXDATEFIELDS];
+ 	int			ftype[MAXDATEFIELDS];
+-	char		lowstr[MAXDATELEN + 1];
++	char		lowstr[MAXDATELEN + MAXDATEFIELDS];
+ 	char	   *realptr;
+ 	char	  **ptr = (endptr != NULL) ? endptr : &realptr;
+ 
+ 	bool		EuroDates = FALSE;
+ 
+ 	errno = 0;
+-	if (strlen(str) >= sizeof(lowstr))
++	if (strlen(str) > MAXDATELEN)
+ 	{
+ 		errno = PGTYPES_DATE_BAD_DATE;
+ 		return INT_MIN;
+diff --git a/src/interfaces/ecpg/pgtypeslib/dt.h b/src/interfaces/ecpg/pgtypeslib/dt.h
+index 47905de..94b9930 100644
+--- a/src/interfaces/ecpg/pgtypeslib/dt.h
++++ b/src/interfaces/ecpg/pgtypeslib/dt.h
+@@ -170,12 +170,17 @@ typedef double fsec_t;
+ #define DTK_DATE_M		(DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY))
+ #define DTK_TIME_M		(DTK_M(HOUR) | DTK_M(MINUTE) | DTK_M(SECOND))
+ 
+-#define MAXDATELEN		51		/* maximum possible length of an input date
+-								 * string (not counting tr. null) */
+-#define MAXDATEFIELDS	25		/* maximum possible number of fields in a date
+-								 * string */
+-#define TOKMAXLEN		10		/* only this many chars are stored in
+-								 * datetktbl */
++/*
++ * Working buffer size for input and output of interval, timestamp, etc.
++ * Inputs that need more working space will be rejected early.  Longer outputs
++ * will overrun buffers, so this must suffice for all possible output.  As of
++ * this writing, PGTYPESinterval_to_asc() needs the most space at ~90 bytes.
++ */
++#define MAXDATELEN		128
++/* maximum possible number of fields in a date string */
++#define MAXDATEFIELDS	25
++/* only this many chars are stored in datetktbl */
++#define TOKMAXLEN		10
+ 
+ /* keep this struct small; it gets used a lot */
+ typedef struct
+diff --git a/src/interfaces/ecpg/pgtypeslib/dt_common.c b/src/interfaces/ecpg/pgtypeslib/dt_common.c
+index 62a9035..1190bbb 100644
+--- a/src/interfaces/ecpg/pgtypeslib/dt_common.c
++++ b/src/interfaces/ecpg/pgtypeslib/dt_common.c
+@@ -1137,15 +1137,22 @@ DecodeNumberField(int len, char *str, int fmask,
+ 	if ((cp = strchr(str, '.')) != NULL)
+ 	{
+ #ifdef HAVE_INT64_TIMESTAMP
+-		char		fstr[MAXDATELEN + 1];
++		char		fstr[7];
++		int			i;
++
++		cp++;
+ 
+ 		/*
+ 		 * OK, we have at most six digits to care about. Let's construct a
+-		 * string and then do the conversion to an integer.
++		 * string with those digits, zero-padded on the right, and then do
++		 * the conversion to an integer.
++		 *
++		 * XXX This truncates the seventh digit, unlike rounding it as do
++		 * the backend and the !HAVE_INT64_TIMESTAMP case.
+ 		 */
+-		strcpy(fstr, (cp + 1));
+-		strcpy(fstr + strlen(fstr), "000000");
+-		*(fstr + 6) = '\0';
++		for (i = 0; i < 6; i++)
++			fstr[i] = *cp != '\0' ? *cp++ : '0';
++		fstr[i] = '\0';
+ 		*fsec = strtol(fstr, NULL, 10);
+ #else
+ 		*fsec = strtod(cp, NULL);
+@@ -1497,15 +1504,22 @@ DecodeTime(char *str, int fmask, int *tmask, struct tm * tm, fsec_t *fsec)
+ 		else if (*cp == '.')
+ 		{
+ #ifdef HAVE_INT64_TIMESTAMP
+-			char		fstr[MAXDATELEN + 1];
++			char		fstr[7];
++			int			i;
++
++			cp++;
+ 
+ 			/*
+-			 * OK, we have at most six digits to work with. Let's construct a
+-			 * string and then do the conversion to an integer.
++			 * OK, we have at most six digits to care about. Let's construct a
++			 * string with those digits, zero-padded on the right, and then do
++			 * the conversion to an integer.
++			 *
++			 * XXX This truncates the seventh digit, unlike rounding it as do
++			 * the backend and the !HAVE_INT64_TIMESTAMP case.
+ 			 */
+-			strncpy(fstr, (cp + 1), 7);
+-			strcpy(fstr + strlen(fstr), "000000");
+-			*(fstr + 6) = '\0';
++			for (i = 0; i < 6; i++)
++				fstr[i] = *cp != '\0' ? *cp++ : '0';
++			fstr[i] = '\0';
+ 			*fsec = strtol(fstr, &cp, 10);
+ #else
+ 			str = cp;
+@@ -1631,6 +1645,9 @@ DecodePosixTimezone(char *str, int *tzp)
+  *	DTK_NUMBER can hold date fields (yy.ddd)
+  *	DTK_STRING can hold months (January) and time zones (PST)
+  *	DTK_DATE can hold Posix time zones (GMT-8)
++ *
++ * The "lowstr" work buffer must have at least strlen(timestr) + MAXDATEFIELDS
++ * bytes of space.  On output, field[] entries will point into it.
+  */
+ int
+ ParseDateTime(char *timestr, char *lowstr,
+@@ -1643,6 +1660,9 @@ ParseDateTime(char *timestr, char *lowstr,
+ 	/* outer loop through fields */
+ 	while (*(*endstr) != '\0')
+ 	{
++		/* Record start of current field */
++		if (nf >= MAXDATEFIELDS)
++			return -1;
+ 		field[nf] = lp;
+ 
+ 		/* leading digit? then date or time */
+@@ -1784,8 +1804,6 @@ ParseDateTime(char *timestr, char *lowstr,
+ 		/* force in a delimiter after each field */
+ 		*lp++ = '\0';
+ 		nf++;
+-		if (nf > MAXDATEFIELDS)
+-			return -1;
+ 	}
+ 
+ 	*numfields = nf;
+diff --git a/src/interfaces/ecpg/pgtypeslib/interval.c b/src/interfaces/ecpg/pgtypeslib/interval.c
+index a8f1899..44d987b 100644
+--- a/src/interfaces/ecpg/pgtypeslib/interval.c
++++ b/src/interfaces/ecpg/pgtypeslib/interval.c
+@@ -712,7 +712,7 @@ PGTYPESinterval_from_asc(char *str, char **endptr)
+ 	tm->tm_sec = 0;
+ 	fsec = 0;
+ 
+-	if (strlen(str) >= sizeof(lowstr))
++	if (strlen(str) > MAXDATELEN)
+ 	{
+ 		errno = PGTYPES_INTVL_BAD_INTERVAL;
+ 		return NULL;
+diff --git a/src/interfaces/ecpg/pgtypeslib/timestamp.c b/src/interfaces/ecpg/pgtypeslib/timestamp.c
+index c86f1a5..9a07060 100644
+--- a/src/interfaces/ecpg/pgtypeslib/timestamp.c
++++ b/src/interfaces/ecpg/pgtypeslib/timestamp.c
+@@ -286,7 +286,7 @@ PGTYPEStimestamp_from_asc(char *str, char **endptr)
+ 	char	   *realptr;
+ 	char	  **ptr = (endptr != NULL) ? endptr : &realptr;
+ 
+-	if (strlen(str) >= sizeof(lowstr))
++	if (strlen(str) > MAXDATELEN)
+ 	{
+ 		errno = PGTYPES_TS_BAD_TIMESTAMP;
+ 		return (noresult);
+diff --git a/src/test/regress/expected/interval.out b/src/test/regress/expected/interval.out
+index 5f35314..477c343 100644
+--- a/src/test/regress/expected/interval.out
++++ b/src/test/regress/expected/interval.out
+@@ -306,6 +306,13 @@ select '4 millenniums 5 centuries 4 decades 1 year 4 months 4 days 17 minutes 31
+  @ 4541 years 4 mons 4 days 17 mins 31 secs
+ (1 row)
+ 
++-- test long interval output
++select '100000000y 10mon -1000000000d -1000000000h -10min -10.000001s ago'::interval;
++                                       interval                                        
++---------------------------------------------------------------------------------------
++ @ 100000000 years 10 mons -1000000000 days -1000000000 hours -10 mins -10.00 secs ago
++(1 row)
++
+ -- test justify_hours() and justify_days()
+ SELECT justify_hours(interval '6 months 3 days 52 hours 3 minutes 2 seconds') as "6 mons 5 days 4 hours 3 mins 2 seconds";
+  6 mons 5 days 4 hours 3 mins 2 seconds 
+diff --git a/src/test/regress/sql/interval.sql b/src/test/regress/sql/interval.sql
+index 3541d68..d74a6d4 100644
+--- a/src/test/regress/sql/interval.sql
++++ b/src/test/regress/sql/interval.sql
+@@ -107,6 +107,8 @@ select avg(f1) from interval_tbl;
+ -- test long interval input
+ select '4 millenniums 5 centuries 4 decades 1 year 4 months 4 days 17 minutes 31 seconds'::interval;
+ 
++-- test long interval output
++select '100000000y 10mon -1000000000d -1000000000h -10min -10.000001s ago'::interval;
+ 
+ -- test justify_hours() and justify_days()
+ 
diff --git a/postgresql-CVE-2014-0064.patch b/postgresql-CVE-2014-0064.patch
new file mode 100644
index 0000000..42fa3db
--- /dev/null
+++ b/postgresql-CVE-2014-0064.patch
@@ -0,0 +1,435 @@
+Predict integer overflow to avoid buffer overruns in size calculations.
+Source: upstream 98be8a6eaa (REL8_4)
+
+diff --git a/contrib/intarray/_int.h b/contrib/intarray/_int.h
+index 0a1888d..58af78e 100644
+--- a/contrib/intarray/_int.h
++++ b/contrib/intarray/_int.h
+@@ -5,6 +5,7 @@
+ 
+ #include <float.h>
+ 
++#include "utils/memutils.h"
+ #include "access/gist.h"
+ #include "access/itup.h"
+ #include "access/skey.h"
+@@ -150,6 +151,7 @@ typedef struct
+ 
+ #define HDRSIZEQT	(VARHDRSZ + sizeof(int4))
+ #define COMPUTESIZE(size)	( HDRSIZEQT + size * sizeof(ITEM) )
++#define QUERYTYPEMAXITEMS	((MaxAllocSize - HDRSIZEQT) / sizeof(ITEM))
+ #define GETQUERY(x)  (ITEM*)( (char*)(x)+HDRSIZEQT )
+ 
+ #define END		0
+diff --git a/contrib/intarray/_int_bool.c b/contrib/intarray/_int_bool.c
+index ae37539..23d8dfc 100644
+--- a/contrib/intarray/_int_bool.c
++++ b/contrib/intarray/_int_bool.c
+@@ -1,4 +1,5 @@
+ #include "_int.h"
++#include "miscadmin.h"
+ 
+ PG_FUNCTION_INFO_V1(bqarr_in);
+ PG_FUNCTION_INFO_V1(bqarr_out);
+@@ -409,6 +410,9 @@ boolop(PG_FUNCTION_ARGS)
+ static void
+ findoprnd(ITEM * ptr, int4 *pos)
+ {
++	/* since this function recurses, it could be driven to stack overflow. */
++	check_stack_depth();
++
+ #ifdef BS_DEBUG
+ 	elog(DEBUG3, (ptr[*pos].type == OPR) ?
+ 		 "%d  %c" : "%d  %d", *pos, ptr[*pos].val);
+@@ -469,7 +473,13 @@ bqarr_in(PG_FUNCTION_ARGS)
+ 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ 				 errmsg("empty query")));
+ 
++	if (state.num > QUERYTYPEMAXITEMS)
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++		errmsg("number of query items (%d) exceeds the maximum allowed (%d)",
++			   state.num, (int) QUERYTYPEMAXITEMS)));
+ 	commonlen = COMPUTESIZE(state.num);
++
+ 	query = (QUERYTYPE *) palloc(commonlen);
+ 	SET_VARSIZE(query, commonlen);
+ 	query->size = state.num;
+diff --git a/contrib/ltree/ltree.h b/contrib/ltree/ltree.h
+index 9df18b7..8a540b8 100644
+--- a/contrib/ltree/ltree.h
++++ b/contrib/ltree/ltree.h
+@@ -6,6 +6,7 @@
+ #include "postgres.h"
+ 
+ #include "utils/builtins.h"
++#include "utils/memutils.h"
+ 
+ typedef struct
+ {
+@@ -112,6 +113,8 @@ typedef struct
+ 
+ #define HDRSIZEQT		MAXALIGN(VARHDRSZ + sizeof(int4))
+ #define COMPUTESIZE(size,lenofoperand)	( HDRSIZEQT + (size) * sizeof(ITEM) + (lenofoperand) )
++#define LTXTQUERY_TOO_BIG(size,lenofoperand) \
++	((size) > (MaxAllocSize - HDRSIZEQT - (lenofoperand)) / sizeof(ITEM))
+ #define GETQUERY(x)  (ITEM*)( (char*)(x)+HDRSIZEQT )
+ #define GETOPERAND(x)	( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )
+ 
+diff --git a/contrib/ltree/ltree_io.c b/contrib/ltree/ltree_io.c
+index ecc926e..d117e7c 100644
+--- a/contrib/ltree/ltree_io.c
++++ b/contrib/ltree/ltree_io.c
+@@ -8,6 +8,7 @@
+ #include <ctype.h>
+ #include "crc32.h"
+ 
++#include "utils/memutils.h"
+ PG_FUNCTION_INFO_V1(ltree_in);
+ Datum		ltree_in(PG_FUNCTION_ARGS);
+ 
+@@ -58,6 +59,11 @@ ltree_in(PG_FUNCTION_ARGS)
+ 		ptr++;
+ 	}
+ 
++	if (num + 1 > MaxAllocSize / sizeof(nodeitem))
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++			 errmsg("number of levels (%d) exceeds the maximum allowed (%d)",
++					num + 1, (int) (MaxAllocSize / sizeof(nodeitem)))));
+ 	list = lptr = (nodeitem *) palloc(sizeof(nodeitem) * (num + 1));
+ 	ptr = buf;
+ 	while (*ptr)
+@@ -208,6 +214,11 @@ lquery_in(PG_FUNCTION_ARGS)
+ 	}
+ 
+ 	num++;
++	if (num > MaxAllocSize / ITEMSIZE)
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++			 errmsg("number of levels (%d) exceeds the maximum allowed (%d)",
++					num, (int) (MaxAllocSize / ITEMSIZE))));
+ 	curqlevel = tmpql = (lquery_level *) palloc0(ITEMSIZE * num);
+ 	ptr = buf;
+ 	while (*ptr)
+diff --git a/contrib/ltree/ltxtquery_io.c b/contrib/ltree/ltxtquery_io.c
+index b87d05c..9d3d203 100644
+--- a/contrib/ltree/ltxtquery_io.c
++++ b/contrib/ltree/ltxtquery_io.c
+@@ -9,6 +9,7 @@
+ #include "crc32.h"
+ 
+ PG_FUNCTION_INFO_V1(ltxtq_in);
++#include "miscadmin.h"
+ Datum		ltxtq_in(PG_FUNCTION_ARGS);
+ 
+ PG_FUNCTION_INFO_V1(ltxtq_out);
+@@ -206,6 +207,9 @@ makepol(QPRS_STATE * state)
+ 	int4		lenstack = 0;
+ 	uint16		flag = 0;
+ 
++	/* since this function recurses, it could be driven to stack overflow */
++	check_stack_depth();
++
+ 	while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END)
+ 	{
+ 		switch (type)
+@@ -270,6 +274,9 @@ makepol(QPRS_STATE * state)
+ static void
+ findoprnd(ITEM * ptr, int4 *pos)
+ {
++	/* since this function recurses, it could be driven to stack overflow. */
++	check_stack_depth();
++
+ 	if (ptr[*pos].type == VAL || ptr[*pos].type == VALTRUE)
+ 	{
+ 		ptr[*pos].left = 0;
+@@ -334,8 +341,12 @@ queryin(char *buf)
+ 				 errmsg("syntax error"),
+ 				 errdetail("Empty query.")));
+ 
+-	/* make finish struct */
++	if (LTXTQUERY_TOO_BIG(state.num, state.sumlen))
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("ltxtquery is too large")));
+ 	commonlen = COMPUTESIZE(state.num, state.sumlen);
++
+ 	query = (ltxtquery *) palloc(commonlen);
+ 	SET_VARSIZE(query, commonlen);
+ 	query->size = state.num;
+diff --git a/src/backend/utils/adt/geo_ops.c b/src/backend/utils/adt/geo_ops.c
+index 29080ae..d959dd9 100644
+--- a/src/backend/utils/adt/geo_ops.c
++++ b/src/backend/utils/adt/geo_ops.c
+@@ -1401,6 +1401,7 @@ path_in(PG_FUNCTION_ARGS)
+ 	char	   *s;
+ 	int			npts;
+ 	int			size;
++	int			base_size;
+ 	int			depth = 0;
+ 
+ 	if ((npts = pair_count(str, ',')) <= 0)
+@@ -1419,7 +1420,15 @@ path_in(PG_FUNCTION_ARGS)
+ 		depth++;
+ 	}
+ 
+-	size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * npts;
++	base_size = sizeof(path->p[0]) * npts;
++	size = offsetof(PATH, p[0]) + base_size;
++
++	/* Check for integer overflow */
++	if (base_size / npts != sizeof(path->p[0]) || size <= base_size)
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("too many points requested")));
++
+ 	path = (PATH *) palloc(size);
+ 
+ 	SET_VARSIZE(path, size);
+@@ -3439,6 +3448,7 @@ poly_in(PG_FUNCTION_ARGS)
+ 	POLYGON    *poly;
+ 	int			npts;
+ 	int			size;
++	int			base_size;
+ 	int			isopen;
+ 	char	   *s;
+ 
+@@ -3447,7 +3457,15 @@ poly_in(PG_FUNCTION_ARGS)
+ 				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ 			  errmsg("invalid input syntax for type polygon: \"%s\"", str)));
+ 
+-	size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts;
++	base_size = sizeof(poly->p[0]) * npts;
++	size = offsetof(POLYGON, p[0]) + base_size;
++
++	/* Check for integer overflow */
++	if (base_size / npts != sizeof(poly->p[0]) || size <= base_size)
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("too many points requested")));
++
+ 	poly = (POLYGON *) palloc0(size);	/* zero any holes */
+ 
+ 	SET_VARSIZE(poly, size);
+@@ -4216,6 +4234,10 @@ path_poly(PG_FUNCTION_ARGS)
+ 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ 				 errmsg("open path cannot be converted to polygon")));
+ 
++	/*
++	 * Never overflows: the old size fit in MaxAllocSize, and the new size is
++	 * just a small constant larger.
++	 */
+ 	size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts;
+ 	poly = (POLYGON *) palloc(size);
+ 
+@@ -4321,6 +4343,10 @@ poly_path(PG_FUNCTION_ARGS)
+ 	int			size;
+ 	int			i;
+ 
++	/*
++	 * Never overflows: the old size fit in MaxAllocSize, and the new size is
++	 * smaller by a small constant.
++	 */
+ 	size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts;
+ 	path = (PATH *) palloc(size);
+ 
+diff --git a/src/backend/utils/adt/tsquery.c b/src/backend/utils/adt/tsquery.c
+index 4bbc3e0..93caa7e 100644
+--- a/src/backend/utils/adt/tsquery.c
++++ b/src/backend/utils/adt/tsquery.c
+@@ -506,8 +506,13 @@ parse_tsquery(char *buf,
+ 		return query;
+ 	}
+ 
+-	/* Pack the QueryItems in the final TSQuery struct to return to caller */
++	if (TSQUERY_TOO_BIG(list_length(state.polstr), state.sumlen))
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("tsquery is too large")));
+ 	commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen);
++
++	/* Pack the QueryItems in the final TSQuery struct to return to caller */
+ 	query = (TSQuery) palloc0(commonlen);
+ 	SET_VARSIZE(query, commonlen);
+ 	query->size = list_length(state.polstr);
+diff --git a/src/backend/utils/adt/tsquery_util.c b/src/backend/utils/adt/tsquery_util.c
+index 01afc4e..6113871 100644
+--- a/src/backend/utils/adt/tsquery_util.c
++++ b/src/backend/utils/adt/tsquery_util.c
+@@ -337,6 +337,11 @@ QTN2QT(QTNode *in)
+ 	QTN2QTState state;
+ 
+ 	cntsize(in, &sumlen, &nnode);
++
++	if (TSQUERY_TOO_BIG(nnode, sumlen))
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("tsquery is too large")));
+ 	len = COMPUTESIZE(nnode, sumlen);
+ 
+ 	out = (TSQuery) palloc0(len);
+diff --git a/src/backend/utils/adt/txid.c b/src/backend/utils/adt/txid.c
+index be79d18..72f48e1 100644
+--- a/src/backend/utils/adt/txid.c
++++ b/src/backend/utils/adt/txid.c
+@@ -26,6 +26,7 @@
+ #include "funcapi.h"
+ #include "libpq/pqformat.h"
+ #include "utils/builtins.h"
++#include "utils/memutils.h"
+ 
+ 
+ #ifndef INT64_IS_BUSTED
+@@ -69,6 +70,8 @@ typedef struct
+ 
+ #define TXID_SNAPSHOT_SIZE(nxip) \
+ 	(offsetof(TxidSnapshot, xip) + sizeof(txid) * (nxip))
++#define TXID_SNAPSHOT_MAX_NXIP \
++	((MaxAllocSize - offsetof(TxidSnapshot, xip)) / sizeof(txid))
+ 
+ /*
+  * Epoch values from xact.c
+@@ -444,20 +447,12 @@ txid_snapshot_recv(PG_FUNCTION_ARGS)
+ 	txid		last = 0;
+ 	int			nxip;
+ 	int			i;
+-	int			avail;
+-	int			expect;
+ 	txid		xmin,
+ 				xmax;
+ 
+-	/*
+-	 * load nxip and check for nonsense.
+-	 *
+-	 * (nxip > avail) check is against int overflows in 'expect'.
+-	 */
++	/* load and validate nxip */
+ 	nxip = pq_getmsgint(buf, 4);
+-	avail = buf->len - buf->cursor;
+-	expect = 8 + 8 + nxip * 8;
+-	if (nxip < 0 || nxip > avail || expect > avail)
++	if (nxip < 0 || nxip > TXID_SNAPSHOT_MAX_NXIP)
+ 		goto bad_format;
+ 
+ 	xmin = pq_getmsgint64(buf);
+diff --git a/src/backend/utils/adt/varbit.c b/src/backend/utils/adt/varbit.c
+index fdda29d..016f544 100644
+--- a/src/backend/utils/adt/varbit.c
++++ b/src/backend/utils/adt/varbit.c
+@@ -138,12 +138,22 @@ bit_in(PG_FUNCTION_ARGS)
+ 		sp = input_string;
+ 	}
+ 
++	/*
++	 * Determine bitlength from input string.  MaxAllocSize ensures a regular
++	 * input is small enough, but we must check hex input.
++	 */
+ 	slen = strlen(sp);
+-	/* Determine bitlength from input string */
+ 	if (bit_not_hex)
+ 		bitlen = slen;
+ 	else
++	{
++		if (slen > VARBITMAXLEN / 4)
++			ereport(ERROR,
++					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("bit string length exceeds the maximum allowed (%d)",
++						VARBITMAXLEN)));
+ 		bitlen = slen * 4;
++	}
+ 
+ 	/*
+ 	 * Sometimes atttypmod is not supplied. If it is supplied we need to make
+@@ -436,12 +446,22 @@ varbit_in(PG_FUNCTION_ARGS)
+ 		sp = input_string;
+ 	}
+ 
++	/*
++	 * Determine bitlength from input string.  MaxAllocSize ensures a regular
++	 * input is small enough, but we must check hex input.
++	 */
+ 	slen = strlen(sp);
+-	/* Determine bitlength from input string */
+ 	if (bit_not_hex)
+ 		bitlen = slen;
+ 	else
++	{
++		if (slen > VARBITMAXLEN / 4)
++			ereport(ERROR,
++					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("bit string length exceeds the maximum allowed (%d)",
++						VARBITMAXLEN)));
+ 		bitlen = slen * 4;
++	}
+ 
+ 	/*
+ 	 * Sometimes atttypmod is not supplied. If it is supplied we need to make
+@@ -520,6 +540,9 @@ varbit_in(PG_FUNCTION_ARGS)
+ 
+ /* varbit_out -
+  *	  Prints the string as bits to preserve length accurately
++ *
++ * XXX varbit_recv() and hex input to varbit_in() can load a value that this
++ * cannot emit.  Consider using hex output for such values.
+  */
+ Datum
+ varbit_out(PG_FUNCTION_ARGS)
+@@ -886,6 +909,11 @@ bitcat(PG_FUNCTION_ARGS)
+ 	bitlen1 = VARBITLEN(arg1);
+ 	bitlen2 = VARBITLEN(arg2);
+ 
++	if (bitlen1 > VARBITMAXLEN - bitlen2)
++		ereport(ERROR,
++				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
++				 errmsg("bit string length exceeds the maximum allowed (%d)",
++						VARBITMAXLEN)));
+ 	bytelen = VARBITTOTALLEN(bitlen1 + bitlen2);
+ 
+ 	result = (VarBit *) palloc(bytelen);
+diff --git a/src/include/tsearch/ts_type.h b/src/include/tsearch/ts_type.h
+index 9f5e63e..5bb4e47 100644
+--- a/src/include/tsearch/ts_type.h
++++ b/src/include/tsearch/ts_type.h
+@@ -13,6 +13,7 @@
+ #define _PG_TSTYPE_H_
+ 
+ #include "fmgr.h"
++#include "utils/memutils.h"
+ #include "utils/pg_crc.h"
+ 
+ 
+@@ -236,6 +237,8 @@ typedef TSQueryData *TSQuery;
+  * QueryItems, and lenofoperand is the total length of all operands
+  */
+ #define COMPUTESIZE(size, lenofoperand) ( HDRSIZETQ + (size) * sizeof(QueryItem) + (lenofoperand) )
++#define TSQUERY_TOO_BIG(size, lenofoperand) \
++	((size) > (MaxAllocSize - HDRSIZETQ - (lenofoperand)) / sizeof(QueryItem))
+ 
+ /* Returns a pointer to the first QueryItem in a TSVector */
+ #define GETQUERY(x)  ((QueryItem*)( (char*)(x)+HDRSIZETQ ))
+diff --git a/src/include/utils/varbit.h b/src/include/utils/varbit.h
+index 4d4cc57..04232d0 100644
+--- a/src/include/utils/varbit.h
++++ b/src/include/utils/varbit.h
+@@ -15,6 +15,8 @@
+ #ifndef VARBIT_H
+ #define VARBIT_H
+ 
++#include <limits.h>
++
+ #include "fmgr.h"
+ 
+ /*
+@@ -53,6 +55,11 @@ typedef struct
+ /* Number of bytes needed to store a bit string of a given length */
+ #define VARBITTOTALLEN(BITLEN)	(((BITLEN) + BITS_PER_BYTE-1)/BITS_PER_BYTE + \
+ 								 VARHDRSZ + VARBITHDRSZ)
++/*
++ * Maximum number of bits.  Several code sites assume no overflow from
++ * computing bitlen + X; VARBITTOTALLEN() has the largest such X.
++ */
++#define VARBITMAXLEN		(INT_MAX - BITS_PER_BYTE + 1)
+ /* pointer beyond the end of the bit string (like end() in STL containers) */
+ #define VARBITEND(PTR)		(((bits8 *) (PTR)) + VARSIZE(PTR))
+ /* Mask that will cover exactly one byte, i.e. BITS_PER_BYTE bits */
diff --git a/postgresql-CVE-2014-0065.patch b/postgresql-CVE-2014-0065.patch
new file mode 100644
index 0000000..78be576
--- /dev/null
+++ b/postgresql-CVE-2014-0065.patch
@@ -0,0 +1,268 @@
+Prevent overruns of fixed-size buffers; chkpass handles crypt()
+returning NULL (CVE-2014-0066).
+Source: upstream 69d2bc14ad (REL8_4)
+
+diff --git a/contrib/chkpass/chkpass.c b/contrib/chkpass/chkpass.c
+index 18cac99..cafeb8f 100644
+--- a/contrib/chkpass/chkpass.c
++++ b/contrib/chkpass/chkpass.c
+@@ -69,6 +69,7 @@ chkpass_in(PG_FUNCTION_ARGS)
+ 	char	   *str = PG_GETARG_CSTRING(0);
+ 	chkpass    *result;
+ 	char		mysalt[4];
++	char	   *crypt_output;
+ 	static char salt_chars[] =
+ 	"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ 
+@@ -91,7 +92,15 @@ chkpass_in(PG_FUNCTION_ARGS)
+ 	mysalt[1] = salt_chars[random() & 0x3f];
+ 	mysalt[2] = 0;				/* technically the terminator is not necessary
+ 								 * but I like to play safe */
+-	strcpy(result->password, crypt(str, mysalt));
++
++	crypt_output = crypt(str, mysalt);
++	if (crypt_output == NULL)
++		ereport(ERROR,
++				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
++				 errmsg("crypt() failed")));
++
++	strlcpy(result->password, crypt_output, sizeof(result->password));
++
+ 	PG_RETURN_POINTER(result);
+ }
+ 
+@@ -148,11 +157,18 @@ chkpass_eq(PG_FUNCTION_ARGS)
+ 	text	   *a2 = (text *) PG_GETARG_TEXT_P(1);
+ 	char		str[10];
+ 	int			sz;
++	char	   *crypt_output;
+ 
+ 	sz = Min(VARSIZE(a2) - VARHDRSZ, 8);
+ 	memcpy(str, VARDATA(a2), sz);
+ 	str[sz] = '\0';
+-	PG_RETURN_BOOL(strcmp(a1->password, crypt(str, a1->password)) == 0);
++	crypt_output = crypt(str, a1->password);
++	if (crypt_output == NULL)
++		ereport(ERROR,
++				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
++				 errmsg("crypt() failed")));
++
++	PG_RETURN_BOOL(strcmp(a1->password, crypt_output) == 0);
+ }
+ 
+ PG_FUNCTION_INFO_V1(chkpass_ne);
+@@ -163,9 +179,16 @@ chkpass_ne(PG_FUNCTION_ARGS)
+ 	text	   *a2 = (text *) PG_GETARG_TEXT_P(1);
+ 	char		str[10];
+ 	int			sz;
++	char	   *crypt_output;
+ 
+ 	sz = Min(VARSIZE(a2) - VARHDRSZ, 8);
+ 	memcpy(str, VARDATA(a2), sz);
+ 	str[sz] = '\0';
+-	PG_RETURN_BOOL(strcmp(a1->password, crypt(str, a1->password)) != 0);
++	crypt_output = crypt(str, a1->password);
++	if (crypt_output == NULL)
++		ereport(ERROR,
++				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
++				 errmsg("crypt() failed")));
++
++	PG_RETURN_BOOL(strcmp(a1->password, crypt_output) != 0);
+ }
+diff --git a/contrib/pg_standby/pg_standby.c b/contrib/pg_standby/pg_standby.c
+index 93139ed..560e3d2 100644
+--- a/contrib/pg_standby/pg_standby.c
++++ b/contrib/pg_standby/pg_standby.c
+@@ -308,7 +308,7 @@ SetWALFileNameForCleanup(void)
+ 		if (strcmp(restartWALFileName, nextWALFileName) > 0)
+ 			return false;
+ 
+-		strcpy(exclusiveCleanupFileName, restartWALFileName);
++		strlcpy(exclusiveCleanupFileName, restartWALFileName, sizeof(exclusiveCleanupFileName));
+ 		return true;
+ 	}
+ 
+diff --git a/src/backend/tsearch/spell.c b/src/backend/tsearch/spell.c
+index ac8dd42..6ab4fb3 100644
+--- a/src/backend/tsearch/spell.c
++++ b/src/backend/tsearch/spell.c
+@@ -181,7 +181,7 @@ NIAddSpell(IspellDict *Conf, const char *word, const char *flag)
+ 	}
+ 	Conf->Spell[Conf->nspell] = (SPELL *) tmpalloc(SPELLHDRSZ + strlen(word) + 1);
+ 	strcpy(Conf->Spell[Conf->nspell]->word, word);
+-	strncpy(Conf->Spell[Conf->nspell]->p.flag, flag, MAXFLAGLEN);
++	strlcpy(Conf->Spell[Conf->nspell]->p.flag, flag, MAXFLAGLEN);
+ 	Conf->nspell++;
+ }
+ 
+diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
+index c91a802..f7697aa 100644
+--- a/src/backend/utils/adt/datetime.c
++++ b/src/backend/utils/adt/datetime.c
+@@ -83,10 +83,10 @@ char	   *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
+  * Note that this table must be strictly alphabetically ordered to allow an
+  * O(ln(N)) search algorithm to be used.
+  *
+- * The text field is NOT guaranteed to be NULL-terminated.
++ * The token field is NOT guaranteed to be NULL-terminated.
+  *
+- * To keep this table reasonably small, we divide the lexval for TZ and DTZ
+- * entries by 15 (so they are on 15 minute boundaries) and truncate the text
++ * To keep this table reasonably small, we divide the value for TZ and DTZ
++ * entries by 15 (so they are on 15 minute boundaries) and truncate the token
+  * field at TOKMAXLEN characters.
+  * Formerly, we divided by 10 rather than 15 but there are a few time zones
+  * which are 30 or 45 minutes away from an even hour, most are on an hour
+@@ -101,7 +101,7 @@ static datetkn *timezonetktbl = NULL;
+ static int	sztimezonetktbl = 0;
+ 
+ static const datetkn datetktbl[] = {
+-/*	text, token, lexval */
++	/* token, type, value */
+ 	{EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
+ 	{"abstime", IGNORE_DTF, 0}, /* for pre-v6.1 "Invalid Abstime" */
+ 	{DA_D, ADBC, AD},			/* "ad" for years > 0 */
+@@ -182,7 +182,7 @@ static const datetkn datetktbl[] = {
+ static int	szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
+ 
+ static datetkn deltatktbl[] = {
+-	/* text, token, lexval */
++	/* token, type, value */
+ 	{"@", IGNORE_DTF, 0},		/* postgres relative prefix */
+ 	{DAGO, AGO, 0},				/* "ago" indicates negative time offset */
+ 	{"c", UNITS, DTK_CENTURY},	/* "century" relative */
+@@ -3832,6 +3832,7 @@ InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
+ 											n * sizeof(datetkn));
+ 	for (i = 0; i < n; i++)
+ 	{
++		/* do NOT use strlcpy here; token field need not be null-terminated */
+ 		strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
+ 		newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
+ 		TOVAL(&newtbl[i], abbrevs[i].offset / 60);
+diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
+index af8dc1b..2926c47 100644
+--- a/src/bin/initdb/initdb.c
++++ b/src/bin/initdb/initdb.c
+@@ -3155,7 +3155,7 @@ main(int argc, char *argv[])
+ 		fprintf(stderr, "%s", authwarning);
+ 
+ 	/* Get directory specification used to start this executable */
+-	strcpy(bin_dir, argv[0]);
++	strlcpy(bin_dir, argv[0], sizeof(bin_dir));
+ 	get_parent_directory(bin_dir);
+ 
+ 	printf(_("\nSuccess. You can now start the database server using:\n\n"
+diff --git a/src/interfaces/ecpg/preproc/pgc.l b/src/interfaces/ecpg/preproc/pgc.l
+index 2ad415d..6e4880b 100644
+--- a/src/interfaces/ecpg/preproc/pgc.l
++++ b/src/interfaces/ecpg/preproc/pgc.l
+@@ -1225,7 +1225,7 @@ parse_include(void)
+ 		yytext[i] = '\0';
+ 		memmove(yytext, yytext+1, strlen(yytext));
+ 	
+-		strncpy(inc_file, yytext, sizeof(inc_file));
++		strlcpy(inc_file, yytext, sizeof(inc_file));
+ 		yyin = fopen(inc_file, "r");
+ 		if (!yyin)
+ 		{
+diff --git a/src/interfaces/libpq/fe-protocol2.c b/src/interfaces/libpq/fe-protocol2.c
+index 69ee24f..352e09a 100644
+--- a/src/interfaces/libpq/fe-protocol2.c
++++ b/src/interfaces/libpq/fe-protocol2.c
+@@ -440,7 +440,7 @@ pqParseInput2(PGconn *conn)
+ 						if (!conn->result)
+ 							return;
+ 					}
+-					strncpy(conn->result->cmdStatus, conn->workBuffer.data,
++					strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
+ 							CMDSTATUS_LEN);
+ 					checkXactStatus(conn, conn->workBuffer.data);
+ 					conn->asyncStatus = PGASYNC_READY;
+diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
+index 89c0d50..1ff2ad5 100644
+--- a/src/interfaces/libpq/fe-protocol3.c
++++ b/src/interfaces/libpq/fe-protocol3.c
+@@ -205,7 +205,7 @@ pqParseInput3(PGconn *conn)
+ 						if (!conn->result)
+ 							return;
+ 					}
+-					strncpy(conn->result->cmdStatus, conn->workBuffer.data,
++					strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
+ 							CMDSTATUS_LEN);
+ 					conn->asyncStatus = PGASYNC_READY;
+ 					break;
+diff --git a/src/port/exec.c b/src/port/exec.c
+index f751e8e..6d7375f 100644
+--- a/src/port/exec.c
++++ b/src/port/exec.c
+@@ -88,7 +88,7 @@ validate_exec(const char *path)
+ 	if (strlen(path) >= strlen(".exe") &&
+ 		pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
+ 	{
+-		strcpy(path_exe, path);
++		strlcpy(path_exe, path, sizeof(path_exe) - 4);
+ 		strcat(path_exe, ".exe");
+ 		path = path_exe;
+ 	}
+@@ -345,7 +345,7 @@ resolve_symlinks(char *path)
+ 	}
+ 
+ 	/* must copy final component out of 'path' temporarily */
+-	strcpy(link_buf, fname);
++	strlcpy(link_buf, fname, sizeof(link_buf));
+ 
+ 	if (!getcwd(path, MAXPGPATH))
+ 	{
+diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c
+index ae3c8d3..83d7116 100644
+--- a/src/test/regress/pg_regress.c
++++ b/src/test/regress/pg_regress.c
+@@ -1211,7 +1211,7 @@ results_differ(const char *testname, const char *resultsfile, const char *defaul
+ 	 */
+ 	platform_expectfile = get_expectfile(testname, resultsfile);
+ 
+-	strcpy(expectfile, default_expectfile);
++	strlcpy(expectfile, default_expectfile, sizeof(expectfile));
+ 	if (platform_expectfile)
+ 	{
+ 		/*
+@@ -1266,7 +1266,7 @@ results_differ(const char *testname, const char *resultsfile, const char *defaul
+ 		{
+ 			/* This diff was a better match than the last one */
+ 			best_line_count = l;
+-			strcpy(best_expect_file, alt_expectfile);
++			strlcpy(best_expect_file, alt_expectfile, sizeof(best_expect_file));
+ 		}
+ 		free(alt_expectfile);
+ 	}
+@@ -1294,7 +1294,7 @@ results_differ(const char *testname, const char *resultsfile, const char *defaul
+ 		{
+ 			/* This diff was a better match than the last one */
+ 			best_line_count = l;
+-			strcpy(best_expect_file, default_expectfile);
++			strlcpy(best_expect_file, default_expectfile, sizeof(best_expect_file));
+ 		}
+ 	}
+ 
+diff --git a/src/timezone/pgtz.c b/src/timezone/pgtz.c
+index 05c6e80..9dbf196 100644
+--- a/src/timezone/pgtz.c
++++ b/src/timezone/pgtz.c
+@@ -94,7 +94,7 @@ pg_open_tzfile(const char *name, char *canonname)
+ 	 * Loop to split the given name into directory levels; for each level,
+ 	 * search using scan_directory_ci().
+ 	 */
+-	strcpy(fullname, pg_TZDIR());
++	strlcpy(fullname, pg_TZDIR(), sizeof(fullname));
+ 	orignamelen = fullnamelen = strlen(fullname);
+ 	fname = name;
+ 	for (;;)
+@@ -427,7 +427,7 @@ identify_system_timezone(void)
+ 	}
+ 
+ 	/* Search for the best-matching timezone file */
+-	strcpy(tmptzdir, pg_TZDIR());
++	strlcpy(tmptzdir, pg_TZDIR(), sizeof(tmptzdir));
+ 	bestscore = -1;
+ 	resultbuf[0] = '\0';
+ 	scan_available_timezones(tmptzdir, tmptzdir + strlen(tmptzdir) + 1,
diff --git a/postgresql-CVE-2015-0241.patch b/postgresql-CVE-2015-0241.patch
new file mode 100644
index 0000000..30fe27a
--- /dev/null
+++ b/postgresql-CVE-2015-0241.patch
@@ -0,0 +1,19 @@
+to_char(): prevent accesses beyond the allocated buffer (part 2 is n/a:
+8.3 takes localized names from its own catalog).
+Source: CentOS 6 postgresql-CVE-2015-0241.patch
+
+diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
+index 875b9bd..5ba955f 100644
+--- a/src/backend/utils/adt/formatting.c
++++ b/src/backend/utils/adt/formatting.c
+@@ -4380,7 +4380,9 @@ NUM_numpart_to_char(NUMProc *Np, int id)
+ 					Np->num_in = TRUE;
+ 				}
+ 			}
+-			++Np->number_p;
++			/* do no exceed string length */
++			if (*Np->number_p)
++				++Np->number_p;
+ 		}
+ 
+ 		end = Np->num_count + (Np->num_pre ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0);
diff --git a/postgresql-CVE-2015-0243.patch b/postgresql-CVE-2015-0243.patch
new file mode 100644
index 0000000..870f4b3
--- /dev/null
+++ b/postgresql-CVE-2015-0243.patch
@@ -0,0 +1,173 @@
+pgcrypto: fix buffer overrun in pullf_read_max() and cherry-pick imath
+fixes.
+Source: CentOS 6 postgresql-CVE-2015-0243.patch (8.4 LTS dae430aa7c +
+3c68cc60d2)
+
+diff --git a/contrib/pgcrypto/expected/pgp-info.out b/contrib/pgcrypto/expected/pgp-info.out
+index 1fe0088..9064838 100644
+--- a/contrib/pgcrypto/expected/pgp-info.out
++++ b/contrib/pgcrypto/expected/pgp-info.out
+@@ -74,5 +74,6 @@ from encdata order by id;
+  2C226E1FFE5CC7D4
+  B68504FD128E1FF9
+  FD0206C409B74875
+-(4 rows)
++ FD0206C409B74875
++(5 rows)
+ 
+diff --git a/contrib/pgcrypto/expected/pgp-pubkey-decrypt.out b/contrib/pgcrypto/expected/pgp-pubkey-decrypt.out
+index 7fbbd83..7a75f26 100644
+--- a/contrib/pgcrypto/expected/pgp-pubkey-decrypt.out
++++ b/contrib/pgcrypto/expected/pgp-pubkey-decrypt.out
+@@ -500,6 +500,27 @@ GQ==
+ =XHkF
+ -----END PGP MESSAGE-----
+ ');
++-- rsaenc2048 / aes128 (not from gnupg)
++insert into encdata (id, data) values (5, '
++-----BEGIN PGP MESSAGE-----
++
++wcBMA/0CBsQJt0h1AQgAzxZ8j+OTeZ8IlLxfZ/mVd28/gUsCY+xigWBk/anZlK3T
++p2tNU2idHzKdAttH2Hu/PWbZp4kwjl9spezYxMqCeBZqtfGED88Y+rqK0n/ul30A
++7jjFHaw0XUOqFNlST1v6H2i7UXndnp+kcLfHPhnO5BIYWxB2CYBehItqtrn75eqr
++C7trGzU/cr74efcWagbCDSNjiAV7GlEptlzmgVMmNikyI6w0ojEUx8lCLc/OsFz9
++pJUAX8xuwjxDVv+W7xk6c96grQiQlm+FLDYGiGNXoAzx3Wi/howu3uV40dXfY+jx
++3WBrhEew5Pkpt1SsWoFnJWOfJ8GLd0ec8vfRCqAIVdLgAeS7NyawQYtd6wuVrEAj
++5SMg4Thb4d+g45RksuGLHUUr4qO9tiXglODa4InhmJfgNuLk+RGz4LXjq8wepEmW
++vRbgFOG54+Cf4C/gC+HkreDm5JKSKjvvw4B/jC6CDxq+JoziEe2Z1uEjCuEcr+Es
++/eGzeOi36BejXPMHeKxXejj5qBBHKV0pHVhZSgffR0TtlXdB967Yl/5agV0R89hI
++7Gw52emfnH4Z0Y4V0au2H0k1dR/2IxXdJEWSTG7Be1JHT59p9ei2gSEOrdBMIOjP
++tbYYUlmmbvD49bHfThkDiC+oc9947LgQsk3kOOLbNHcjkbrjH8R5kjII4m/SEZA1
++g09T+338SzevBcVXh/cFrQ6/Et+lyyO2LJRUMs69g/HyzJOVWT2Iu8E0eS9MWevY
++Qtrkrhrpkl3Y02qEp/j6M03Yu2t6ZF7dp51aJ5VhO2mmmtHaTnCyCc8Fcf72LmD8
++blH2nKZC9d6fi4YzSYMepZpMOFR65M80MCMiDUGnZBB8sEADu2/iVtqDUeG8mAA=
++=PHJ1
++-----END PGP MESSAGE-----
++');
+ -- successful decrypt
+ select pgp_pub_decrypt(dearmor(data), dearmor(seckey))
+ from keytbl, encdata where keytbl.id=1 and encdata.id=1;
+@@ -553,3 +574,7 @@ from keytbl, encdata where keytbl.id=5 and encdata.id=1;
+  Secret msg
+ (1 row)
+ 
++-- test for a short read from prefix_init
++select pgp_pub_decrypt(dearmor(data), dearmor(seckey))
++from keytbl, encdata where keytbl.id=6 and encdata.id=5;
++ERROR:  Wrong key or corrupt data
+diff --git a/contrib/pgcrypto/imath.c b/contrib/pgcrypto/imath.c
+index 63b294a..de608bd 100644
+--- a/contrib/pgcrypto/imath.c
++++ b/contrib/pgcrypto/imath.c
+@@ -818,7 +818,8 @@ mp_int_mul(mp_int a, mp_int b, mp_int c)
+ 	 */
+ 	ua = MP_USED(a);
+ 	ub = MP_USED(b);
+-	osize = ua + ub;
++	osize = MAX(ua, ub);
++	osize = 4 * ((osize + 1) / 2);
+ 
+ 	if (c == a || c == b)
+ 	{
+@@ -907,7 +908,7 @@ mp_int_sqr(mp_int a, mp_int c)
+ 	CHECK(a != NULL && c != NULL);
+ 
+ 	/* Get a temporary buffer big enough to hold the result */
+-	osize = (mp_size) 2 *MP_USED(a);
++	osize = (mp_size) 4 *((MP_USED(a) + 1) / 2);
+ 
+ 	if (a == c)
+ 	{
+@@ -2605,8 +2606,8 @@ s_kmul(mp_digit * da, mp_digit * db, mp_digit * dc,
+ 		 * Now we'll get t1 = a0b0 and t2 = a1b1, and subtract them out so
+ 		 * that we're left with only the pieces we want:  t3 = a1b0 + a0b1
+ 		 */
+-		ZERO(t1, bot_size + 1);
+-		ZERO(t2, bot_size + 1);
++		ZERO(t1, buf_size);
++		ZERO(t2, buf_size);
+ 		(void) s_kmul(da, db, t1, bot_size, bot_size);	/* t1 = a0 * b0 */
+ 		(void) s_kmul(a_top, b_top, t2, at_size, bt_size);		/* t2 = a1 * b1 */
+ 
+@@ -2616,11 +2617,13 @@ s_kmul(mp_digit * da, mp_digit * db, mp_digit * dc,
+ 
+ 		/* Assemble the output value */
+ 		COPY(t1, dc, buf_size);
+-		(void) s_uadd(t3, dc + bot_size, dc + bot_size,
+-					  buf_size + 1, buf_size + 1);
++		carry = s_uadd(t3, dc + bot_size, dc + bot_size,
++					   buf_size + 1, buf_size);
++		assert(carry == 0);
+ 
+-		(void) s_uadd(t2, dc + 2 * bot_size, dc + 2 * bot_size,
+-					  buf_size, buf_size);
++		carry = s_uadd(t2, dc + 2 * bot_size, dc + 2 * bot_size,
++					   buf_size, buf_size);
++		assert(carry == 0);
+ 
+ 		s_free(t1);				/* note t2 and t3 are just internal pointers
+ 								 * to t1 */
+@@ -3307,7 +3310,10 @@ s_embar(mp_int a, mp_int b, mp_int m, mp_int mu, mp_int c)
+ 	dbt = db + MP_USED(b) - 1;
+ 
+ 	while (last < 3)
+-		SETUP(mp_int_init_size(TEMP(last), 2 * umu), last);
++	{
++		SETUP(mp_int_init_size(TEMP(last), 4 * umu), last);
++		ZERO(MP_DIGITS(TEMP(last - 1)), MP_ALLOC(TEMP(last - 1)));
++	}
+ 
+ 	(void) mp_int_set_value(c, 1);
+ 
+diff --git a/contrib/pgcrypto/mbuf.c b/contrib/pgcrypto/mbuf.c
+index 920e10f..3ada923 100644
+--- a/contrib/pgcrypto/mbuf.c
++++ b/contrib/pgcrypto/mbuf.c
+@@ -305,6 +305,7 @@ pullf_read_max(PullFilter * pf, int len, uint8 **data_p, uint8 *tmpbuf)
+ 			break;
+ 		memcpy(tmpbuf + total, tmp, res);
+ 		total += res;
++		len -= res;
+ 	}
+ 	return total;
+ }
+diff --git a/contrib/pgcrypto/sql/pgp-pubkey-decrypt.sql b/contrib/pgcrypto/sql/pgp-pubkey-decrypt.sql
+index a7cb880..65b32e8 100644
+--- a/contrib/pgcrypto/sql/pgp-pubkey-decrypt.sql
++++ b/contrib/pgcrypto/sql/pgp-pubkey-decrypt.sql
+@@ -514,6 +514,28 @@ GQ==
+ -----END PGP MESSAGE-----
+ ');
+ 
++-- rsaenc2048 / aes128 (not from gnupg)
++insert into encdata (id, data) values (5, '
++-----BEGIN PGP MESSAGE-----
++
++wcBMA/0CBsQJt0h1AQgAzxZ8j+OTeZ8IlLxfZ/mVd28/gUsCY+xigWBk/anZlK3T
++p2tNU2idHzKdAttH2Hu/PWbZp4kwjl9spezYxMqCeBZqtfGED88Y+rqK0n/ul30A
++7jjFHaw0XUOqFNlST1v6H2i7UXndnp+kcLfHPhnO5BIYWxB2CYBehItqtrn75eqr
++C7trGzU/cr74efcWagbCDSNjiAV7GlEptlzmgVMmNikyI6w0ojEUx8lCLc/OsFz9
++pJUAX8xuwjxDVv+W7xk6c96grQiQlm+FLDYGiGNXoAzx3Wi/howu3uV40dXfY+jx
++3WBrhEew5Pkpt1SsWoFnJWOfJ8GLd0ec8vfRCqAIVdLgAeS7NyawQYtd6wuVrEAj
++5SMg4Thb4d+g45RksuGLHUUr4qO9tiXglODa4InhmJfgNuLk+RGz4LXjq8wepEmW
++vRbgFOG54+Cf4C/gC+HkreDm5JKSKjvvw4B/jC6CDxq+JoziEe2Z1uEjCuEcr+Es
++/eGzeOi36BejXPMHeKxXejj5qBBHKV0pHVhZSgffR0TtlXdB967Yl/5agV0R89hI
++7Gw52emfnH4Z0Y4V0au2H0k1dR/2IxXdJEWSTG7Be1JHT59p9ei2gSEOrdBMIOjP
++tbYYUlmmbvD49bHfThkDiC+oc9947LgQsk3kOOLbNHcjkbrjH8R5kjII4m/SEZA1
++g09T+338SzevBcVXh/cFrQ6/Et+lyyO2LJRUMs69g/HyzJOVWT2Iu8E0eS9MWevY
++Qtrkrhrpkl3Y02qEp/j6M03Yu2t6ZF7dp51aJ5VhO2mmmtHaTnCyCc8Fcf72LmD8
++blH2nKZC9d6fi4YzSYMepZpMOFR65M80MCMiDUGnZBB8sEADu2/iVtqDUeG8mAA=
++=PHJ1
++-----END PGP MESSAGE-----
++');
++
+ -- successful decrypt
+ select pgp_pub_decrypt(dearmor(data), dearmor(seckey))
+ from keytbl, encdata where keytbl.id=1 and encdata.id=1;
+@@ -547,3 +569,6 @@ from keytbl, encdata where keytbl.id=5 and encdata.id=1;
+ select pgp_pub_decrypt(dearmor(data), dearmor(seckey), 'parool')
+ from keytbl, encdata where keytbl.id=5 and encdata.id=1;
+ 
++-- test for a short read from prefix_init
++select pgp_pub_decrypt(dearmor(data), dearmor(seckey))
++from keytbl, encdata where keytbl.id=6 and encdata.id=5;
diff --git a/postgresql-CVE-2015-0244.patch b/postgresql-CVE-2015-0244.patch
new file mode 100644
index 0000000..b6752fa
--- /dev/null
+++ b/postgresql-CVE-2015-0244.patch
@@ -0,0 +1,579 @@
+Do not lose sync in the FE/BE protocol after an error inside a message
+(GSS/SSPI loops placed by hand).
+Source: CentOS 6 postgresql-CVE-2015-0244.patch (8.4 LTS 2665304ac0)
+
+diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c
+index 2fb2a31..79d8f49 100644
+--- a/src/backend/commands/copy.c
++++ b/src/backend/commands/copy.c
+@@ -355,6 +355,8 @@ ReceiveCopyBegin(CopyState cstate)
+ 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ 			errmsg("COPY BINARY is not supported to stdout or from stdin")));
+ 		pq_putemptymessage('G');
++		/* any error in old protocol will make us lose sync */
++		pq_startmsgread();
+ 		cstate->copy_dest = COPY_OLD_FE;
+ 	}
+ 	else
+@@ -365,6 +367,8 @@ ReceiveCopyBegin(CopyState cstate)
+ 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ 			errmsg("COPY BINARY is not supported to stdout or from stdin")));
+ 		pq_putemptymessage('D');
++		/* any error in old protocol will make us lose sync */
++		pq_startmsgread();
+ 		cstate->copy_dest = COPY_OLD_FE;
+ 	}
+ 	/* We *must* flush here to ensure FE knows it can send. */
+@@ -525,6 +529,8 @@ CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
+ 					int			mtype;
+ 
+ 			readmessage:
++					HOLD_CANCEL_INTERRUPTS();
++					pq_startmsgread();
+ 					mtype = pq_getbyte();
+ 					if (mtype == EOF)
+ 						ereport(ERROR,
+@@ -534,6 +540,7 @@ CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
+ 						ereport(ERROR,
+ 								(errcode(ERRCODE_CONNECTION_FAILURE),
+ 							 errmsg("unexpected EOF on client connection")));
++					RESUME_CANCEL_INTERRUPTS();
+ 					switch (mtype)
+ 					{
+ 						case 'd':		/* CopyData */
+@@ -2134,6 +2141,13 @@ CopyFrom(CopyState cstate)
+ 
+ 	MemoryContextSwitchTo(oldcontext);
+ 
++	/*
++	 * In the old protocol, tell pqcomm that we can process normal protocol
++	 * messages again.
++	 */
++	if (cstate->copy_dest == COPY_OLD_FE)
++		pq_endmsgread();
++
+ 	/* Execute AFTER STATEMENT insertion triggers */
+ 	ExecASInsertTriggers(estate, resultRelInfo);
+ 
+diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c
+index 88d809f..597962b 100644
+--- a/src/backend/libpq/auth.c
++++ b/src/backend/libpq/auth.c
+@@ -463,6 +463,7 @@ pg_GSS_recvauth(Port *port)
+ 	 */
+ 	do
+ 	{
++		pq_startmsgread();
+ 		mtype = pq_getbyte();
+ 		if (mtype != 'p')
+ 		{
+@@ -725,6 +726,7 @@ pg_SSPI_recvauth(Port *port)
+ 	 */
+ 	do
+ 	{
++		pq_startmsgread();
+ 		mtype = pq_getbyte();
+ 		if (mtype != 'p')
+ 		{
+@@ -1622,6 +1624,7 @@ recv_password_packet(Port *port)
+ {
+ 	StringInfoData buf;
+ 
++	pq_startmsgread();
+ 	if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
+ 	{
+ 		/* Expect 'p' message type */
+diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
+index d38bec4..aa74bad 100644
+--- a/src/backend/libpq/pqcomm.c
++++ b/src/backend/libpq/pqcomm.c
+@@ -116,8 +116,9 @@ static int	PqRecvLength;		/* End of data available in PqRecvBuffer */
+ /*
+  * Message status
+  */
+-static bool PqCommBusy;
+-static bool DoingCopyOut;
++static bool PqCommBusy;			/* busy sending data to the client */
++static bool PqCommReadingMsg;	/* in the middle of reading a message */
++static bool DoingCopyOut;		/* in old-protocol COPY OUT processing */
+ 
+ 
+ /* Internal functions */
+@@ -140,6 +141,7 @@ pq_init(void)
+ {
+ 	PqSendPointer = PqRecvPointer = PqRecvLength = 0;
+ 	PqCommBusy = false;
++	PqCommReadingMsg = false;
+ 	DoingCopyOut = false;
+ 	on_proc_exit(pq_close, 0);
+ }
+@@ -798,6 +800,8 @@ pq_recvbuf(void)
+ int
+ pq_getbyte(void)
+ {
++	Assert(PqCommReadingMsg);
++
+ 	while (PqRecvPointer >= PqRecvLength)
+ 	{
+ 		if (pq_recvbuf())		/* If nothing in buffer, then recv some */
+@@ -846,6 +850,8 @@ pq_getbytes(char *s, size_t len)
+ {
+ 	size_t		amount;
+ 
++	Assert(PqCommReadingMsg);
++
+ 	while (len > 0)
+ 	{
+ 		while (PqRecvPointer >= PqRecvLength)
+@@ -878,6 +884,8 @@ pq_discardbytes(size_t len)
+ {
+ 	size_t		amount;
+ 
++	Assert(PqCommReadingMsg);
++
+ 	while (len > 0)
+ 	{
+ 		while (PqRecvPointer >= PqRecvLength)
+@@ -914,6 +922,8 @@ pq_getstring(StringInfo s)
+ {
+ 	int			i;
+ 
++	Assert(PqCommReadingMsg);
++
+ 	resetStringInfo(s);
+ 
+ 	/* Read until we get the terminating '\0' */
+@@ -945,6 +955,58 @@ pq_getstring(StringInfo s)
+ }
+ 
+ 
++/* --------------------------------
++ *		pq_startmsgread	- begin reading a message from the client.
++ *
++ *		This must be called before any of the pq_get* functions.
++ * --------------------------------
++ */
++void
++pq_startmsgread(void)
++{
++	/*
++	 * There shouldn't be a read active already, but let's check just to be
++	 * sure.
++	 */
++	if (PqCommReadingMsg)
++		ereport(FATAL,
++				(errcode(ERRCODE_PROTOCOL_VIOLATION),
++				 errmsg("terminating connection because protocol sync was lost")));
++
++	PqCommReadingMsg = true;
++}
++
++
++/* --------------------------------
++ *		pq_endmsgread	- finish reading message.
++ *
++ *		This must be called after reading a V2 protocol message with
++ *		pq_getstring() and friends, to indicate that we have read the whole
++ *		message. In V3 protocol, pq_getmessage() does this implicitly.
++ * --------------------------------
++ */
++void
++pq_endmsgread(void)
++{
++	Assert(PqCommReadingMsg);
++
++	PqCommReadingMsg = false;
++}
++
++/* --------------------------------
++ *		pq_is_reading_msg - are we currently reading a message?
++ *
++ * This is used in error recovery at the outer idle loop to detect if we have
++ * lost protocol sync, and need to terminate the connection. pq_startmsgread()
++ * will check for that too, but it's nicer to detect it earlier.
++ * --------------------------------
++ */
++bool
++pq_is_reading_msg(void)
++{
++	return PqCommReadingMsg;
++}
++
+ /* --------------------------------
+  *		pq_getmessage	- get a message with length word from connection
+  *
+@@ -966,6 +1028,8 @@ pq_getmessage(StringInfo s, int maxlen)
+ {
+ 	int32		len;
+ 
++	Assert(PqCommReadingMsg);
++
+ 	resetStringInfo(s);
+ 
+ 	/* Read message length word */
+@@ -1007,6 +1071,9 @@ pq_getmessage(StringInfo s, int maxlen)
+ 				ereport(COMMERROR,
+ 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
+ 						 errmsg("incomplete message from client")));
++
++			/* we discarded the rest of the message so we're back in sync. */
++			PqCommReadingMsg = false;
+ 			PG_RE_THROW();
+ 		}
+ 		PG_END_TRY();
+@@ -1024,6 +1091,9 @@ pq_getmessage(StringInfo s, int maxlen)
+ 		s->data[len] = '\0';
+ 	}
+ 
++	/* finished reading the message. */
++	PqCommReadingMsg = false;
++
+ 	return 0;
+ }
+ 
+diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
+index 90688b7..f4be3ba 100644
+--- a/src/backend/postmaster/postmaster.c
++++ b/src/backend/postmaster/postmaster.c
+@@ -1401,6 +1401,7 @@ ProcessStartupPacket(Port *port, bool SSLdone)
+ 	ProtocolVersion proto;
+ 	MemoryContext oldcontext;
+ 
++	pq_startmsgread();
+ 	if (pq_getbytes((char *) &len, 4) == EOF)
+ 	{
+ 		/*
+@@ -1445,6 +1446,7 @@ ProcessStartupPacket(Port *port, bool SSLdone)
+ 				 errmsg("incomplete startup packet")));
+ 		return STATUS_ERROR;
+ 	}
++	pq_endmsgread();
+ 
+ 	/*
+ 	 * The first field is either a protocol version number or a special
+diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
+index f41f6cb..acb878e 100644
+--- a/src/backend/storage/lmgr/proc.c
++++ b/src/backend/storage/lmgr/proc.c
+@@ -495,9 +495,14 @@ LockWaitCancel(void)
+ {
+ 	LWLockId	partitionLock;
+ 
++	HOLD_INTERRUPTS();
++
+ 	/* Nothing to do if we weren't waiting for a lock */
+ 	if (lockAwaited == NULL)
++	{
++		RESUME_INTERRUPTS();
+ 		return;
++	}
+ 
+ 	/* Turn off the deadlock timer, if it's still running (see ProcSleep) */
+ 	disable_sig_alarm(false);
+@@ -536,6 +541,8 @@ LockWaitCancel(void)
+ 	 * wakeup signal isn't harmful, and it seems not worth expending cycles to
+ 	 * get rid of a signal that most likely isn't there.
+ 	 */
++
++	RESUME_INTERRUPTS();
+ }
+ 
+ 
+diff --git a/src/backend/tcop/fastpath.c b/src/backend/tcop/fastpath.c
+index d1e2913..768cb4a 100644
+--- a/src/backend/tcop/fastpath.c
++++ b/src/backend/tcop/fastpath.c
+@@ -73,7 +73,7 @@ static int16 parse_fcall_arguments_20(StringInfo msgBuf, struct fp_info * fip,
+  * The caller should already have initialized buf to empty.
+  * ----------------
+  */
+-static int
++int
+ GetOldFunctionMessage(StringInfo buf)
+ {
+ 	int32		ibuf;
+@@ -280,20 +280,6 @@ HandleFunctionRequest(StringInfo msgBuf)
+ 	bool		was_logged = false;
+ 	char		msec_str[32];
+ 
+-	/*
+-	 * Read message contents if not already done.
+-	 */
+-	if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
+-	{
+-		if (GetOldFunctionMessage(msgBuf))
+-		{
+-			ereport(COMMERROR,
+-					(errcode(ERRCODE_PROTOCOL_VIOLATION),
+-					 errmsg("unexpected EOF on client connection")));
+-			return EOF;
+-		}
+-	}
+-
+ 	/*
+ 	 * Now that we've eaten the input message, check to see if we actually
+ 	 * want to do the function call or not.  It's now safe to ereport(); we
+diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
+index cc26211..936ea37 100644
+--- a/src/backend/tcop/postgres.c
++++ b/src/backend/tcop/postgres.c
+@@ -322,6 +322,8 @@ SocketBackend(StringInfo inBuf)
+ 	/*
+ 	 * Get message type code from the frontend.
+ 	 */
++	HOLD_CANCEL_INTERRUPTS();
++	pq_startmsgread();
+ 	qtype = pq_getbyte();
+ 
+ 	if (qtype == EOF)			/* frontend disconnected */
+@@ -358,8 +360,17 @@ SocketBackend(StringInfo inBuf)
+ 			break;
+ 
+ 		case 'F':				/* fastpath function call */
+-			/* we let fastpath.c cope with old-style input of this */
+ 			doing_extended_query_message = false;
++			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
++			{
++				if (GetOldFunctionMessage(inBuf))
++				{
++					ereport(COMMERROR,
++							(errcode(ERRCODE_PROTOCOL_VIOLATION),
++							 errmsg("unexpected EOF on client connection")));
++					return EOF;
++				}
++			}
+ 			break;
+ 
+ 		case 'X':				/* terminate */
+@@ -427,6 +438,9 @@ SocketBackend(StringInfo inBuf)
+ 		if (pq_getmessage(inBuf, 0))
+ 			return EOF;			/* suitable message already logged */
+ 	}
++	else
++		pq_endmsgread();
++	RESUME_CANCEL_INTERRUPTS();
+ 
+ 	return qtype;
+ }
+@@ -2546,21 +2560,11 @@ die(SIGNAL_ARGS)
+ 		ProcDiePending = true;
+ 
+ 		/*
+-		 * If it's safe to interrupt, and we're waiting for input or a lock,
+-		 * service the interrupt immediately
++		 * If we're waiting for input or a lock so that it's safe to
++		 * interrupt, service the interrupt immediately
+ 		 */
+-		if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
+-			CritSectionCount == 0)
+-		{
+-			/* bump holdoff count to make ProcessInterrupts() a no-op */
+-			/* until we are done getting ready for it */
+-			InterruptHoldoffCount++;
+-			LockWaitCancel();	/* prevent CheckDeadLock from running */
+-			DisableNotifyInterrupt();
+-			DisableCatchupInterrupt();
+-			InterruptHoldoffCount--;
++		if (ImmediateInterruptOK)
+ 			ProcessInterrupts();
+-		}
+ 	}
+ 
+ 	errno = save_errno;
+@@ -2598,22 +2602,11 @@ StatementCancelHandler(SIGNAL_ARGS)
+ 		QueryCancelPending = true;
+ 
+ 		/*
+-		 * If it's safe to interrupt, and we're waiting for a lock, service
+-		 * the interrupt immediately.  No point in interrupting if we're
+-		 * waiting for input, however.
++		 * If we're waiting for input or a lock so that it's safe to
++		 * interrupt, service the interrupt immediately
+ 		 */
+-		if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
+-			CritSectionCount == 0 && !DoingCommandRead)
+-		{
+-			/* bump holdoff count to make ProcessInterrupts() a no-op */
+-			/* until we are done getting ready for it */
+-			InterruptHoldoffCount++;
+-			LockWaitCancel();	/* prevent CheckDeadLock from running */
+-			DisableNotifyInterrupt();
+-			DisableCatchupInterrupt();
+-			InterruptHoldoffCount--;
++		if (ImmediateInterruptOK)
+ 			ProcessInterrupts();
+-		}
+ 	}
+ 
+ 	errno = save_errno;
+@@ -2649,15 +2642,17 @@ SigHupHandler(SIGNAL_ARGS)
+ void
+ ProcessInterrupts(void)
+ {
+-	/* OK to accept interrupt now? */
++	/* OK to accept any interrupts now? */
+ 	if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
+ 		return;
+ 	InterruptPending = false;
++
+ 	if (ProcDiePending)
+ 	{
+ 		ProcDiePending = false;
+ 		QueryCancelPending = false;		/* ProcDie trumps QueryCancel */
+ 		ImmediateInterruptOK = false;	/* not idle anymore */
++		LockWaitCancel();
+ 		DisableNotifyInterrupt();
+ 		DisableCatchupInterrupt();
+ 		if (IsAutoVacuumWorkerProcess())
+@@ -2669,10 +2664,28 @@ ProcessInterrupts(void)
+ 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
+ 			 errmsg("terminating connection due to administrator command")));
+ 	}
++
+ 	if (QueryCancelPending)
+ 	{
++		/*
++		 * Don't allow query cancel interrupts while reading input from the
++		 * client, because we might lose sync in the FE/BE protocol.  (Die
++		 * interrupts are OK, because we won't read any further messages from
++		 * the client in that case.)
++		 */
++		if (QueryCancelHoldoffCount != 0)
++		{
++			/*
++			 * Re-arm InterruptPending so that we process the cancel request
++			 * as soon as we're done reading the message.
++			 */
++			InterruptPending = true;
++			return;
++		}
++
+ 		QueryCancelPending = false;
+ 		ImmediateInterruptOK = false;	/* not idle anymore */
++		LockWaitCancel();
+ 		DisableNotifyInterrupt();
+ 		DisableCatchupInterrupt();
+ 		if (cancel_from_timeout)
+@@ -3625,6 +3638,19 @@ PostgresMain(int argc, char *argv[], const char *username)
+ 		/* We don't have a transaction command open anymore */
+ 		xact_started = false;
+ 
++		/*
++		 * If an error occurred while we were reading a message from the
++		 * client, we have potentially lost track of where the previous
++		 * message ends and the next one begins.  Even though we have
++		 * otherwise recovered from the error, we cannot safely read any more
++		 * messages from the client, so there isn't much we can do with the
++		 * connection anymore.
++		 */
++		if (pq_is_reading_msg())
++			ereport(FATAL,
++					(errcode(ERRCODE_PROTOCOL_VIOLATION),
++					 errmsg("terminating connection because protocol sync was lost")));
++
+ 		/* Now we can allow interrupts again */
+ 		RESUME_INTERRUPTS();
+ 	}
+@@ -3705,7 +3731,14 @@ PostgresMain(int argc, char *argv[], const char *username)
+ 
+ 		/*
+ 		 * (4) disable async signal conditions again.
++		 *
++		 * Query cancel is supposed to be a no-op when there is no query in
++		 * progress, so if a query cancel arrived while we were idle, just
++		 * reset QueryCancelPending. ProcessInterrupts() has that effect when
++		 * it's called when DoingCommandRead is set, so check for interrupts
++		 * before resetting DoingCommandRead.
+ 		 */
++		CHECK_FOR_INTERRUPTS();
+ 		DoingCommandRead = false;
+ 
+ 		/*
+diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
+index 7e60fd4..e29c256 100644
+--- a/src/backend/utils/error/elog.c
++++ b/src/backend/utils/error/elog.c
+@@ -396,6 +396,7 @@ errfinish(int dummy,...)
+ 		 * should make life easier for most.)
+ 		 */
+ 		InterruptHoldoffCount = 0;
++		QueryCancelHoldoffCount = 0;
+ 
+ 		CritSectionCount = 0;	/* should be unnecessary, but... */
+ 
+diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
+index 3cc443b..b320bdd 100644
+--- a/src/backend/utils/init/globals.c
++++ b/src/backend/utils/init/globals.c
+@@ -30,6 +30,7 @@ volatile bool QueryCancelPending = false;
+ volatile bool ProcDiePending = false;
+ volatile bool ImmediateInterruptOK = false;
+ volatile uint32 InterruptHoldoffCount = 0;
++volatile uint32 QueryCancelHoldoffCount = 0;
+ volatile uint32 CritSectionCount = 0;
+ 
+ int			MyProcPid;
+diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
+index d03f13a..76f3300 100644
+--- a/src/include/libpq/libpq.h
++++ b/src/include/libpq/libpq.h
+@@ -54,6 +54,9 @@ extern void pq_init(void);
+ extern void pq_comm_reset(void);
+ extern int	pq_getbytes(char *s, size_t len);
+ extern int	pq_getstring(StringInfo s);
++extern void pq_startmsgread(void);
++extern void pq_endmsgread(void);
++extern bool pq_is_reading_msg(void);
+ extern int	pq_getmessage(StringInfo s, int maxlen);
+ extern int	pq_getbyte(void);
+ extern int	pq_peekbyte(void);
+diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
+index 34bc154..01912fe 100644
+--- a/src/include/miscadmin.h
++++ b/src/include/miscadmin.h
+@@ -50,6 +50,10 @@
+  * will be held off until CHECK_FOR_INTERRUPTS() is done outside any
+  * HOLD_INTERRUPTS() ... RESUME_INTERRUPTS() section.
+  *
++ * There is also a mechanism to prevent query cancel interrupts, while still
++ * allowing die interrupts: HOLD_CANCEL_INTERRUPTS() and
++ * RESUME_CANCEL_INTERRUPTS().
++ *
+  * Special mechanisms are used to let an interrupt be accepted when we are
+  * waiting for a lock or when we are waiting for command input (but, of
+  * course, only if the interrupt holdoff counter is zero).	See the
+@@ -73,6 +77,7 @@ extern volatile bool ProcDiePending;
+ /* these are marked volatile because they are examined by signal handlers: */
+ extern volatile bool ImmediateInterruptOK;
+ extern PGDLLIMPORT volatile uint32 InterruptHoldoffCount;
++extern PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount;
+ extern PGDLLIMPORT volatile uint32 CritSectionCount;
+ 
+ /* in tcop/postgres.c */
+@@ -105,6 +110,14 @@ do { \
+ 	InterruptHoldoffCount--; \
+ } while(0)
+ 
++#define HOLD_CANCEL_INTERRUPTS()  (QueryCancelHoldoffCount++)
++
++#define RESUME_CANCEL_INTERRUPTS() \
++do { \
++	Assert(QueryCancelHoldoffCount > 0); \
++	QueryCancelHoldoffCount--; \
++} while(0)
++
+ #define START_CRIT_SECTION()  (CritSectionCount++)
+ 
+ #define END_CRIT_SECTION() \
+diff --git a/src/include/tcop/fastpath.h b/src/include/tcop/fastpath.h
+index 4673ea3..36edd91 100644
+--- a/src/include/tcop/fastpath.h
++++ b/src/include/tcop/fastpath.h
+@@ -15,6 +15,7 @@
+ 
+ #include "lib/stringinfo.h"
+ 
++extern int GetOldFunctionMessage(StringInfo buf);
+ extern int	HandleFunctionRequest(StringInfo msgBuf);
+ 
+ #endif   /* FASTPATH_H */
diff --git a/postgresql-CVE-2015-3165.patch b/postgresql-CVE-2015-3165.patch
new file mode 100644
index 0000000..1f52e20
--- /dev/null
+++ b/postgresql-CVE-2015-3165.patch
@@ -0,0 +1,116 @@
+Avoid double free after an authentication timeout with SSL.
+Source: CentOS 6 postgresql-CVE-2015-3165.patch (8.4 LTS 48aa2f1903)
+
+diff --git a/src/backend/libpq/be-secure.c b/src/backend/libpq/be-secure.c
+index 14f31af..6c15fc0 100644
+--- a/src/backend/libpq/be-secure.c
++++ b/src/backend/libpq/be-secure.c
+@@ -982,7 +982,6 @@ open_server_SSL(Port *port)
+ 				(errcode(ERRCODE_PROTOCOL_VIOLATION),
+ 				 errmsg("could not initialize SSL connection: %s",
+ 						SSLerrmessage())));
+-		close_SSL(port);
+ 		return -1;
+ 	}
+ 	if (!my_SSL_set_fd(port->ssl, port->sock))
+@@ -991,7 +990,6 @@ open_server_SSL(Port *port)
+ 				(errcode(ERRCODE_PROTOCOL_VIOLATION),
+ 				 errmsg("could not set SSL socket: %s",
+ 						SSLerrmessage())));
+-		close_SSL(port);
+ 		return -1;
+ 	}
+ 
+@@ -1039,7 +1037,6 @@ aloop:
+ 								err)));
+ 				break;
+ 		}
+-		close_SSL(port);
+ 		return -1;
+ 	}
+ 
+@@ -1076,7 +1073,6 @@ aloop:
+ 				ereport(COMMERROR,
+ 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
+ 						 errmsg("SSL certificate's common name contains embedded null")));
+-				close_SSL(port);
+ 				return -1;
+ 			}
+ 		}
+diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
+index aa74bad..a84252c 100644
+--- a/src/backend/libpq/pqcomm.c
++++ b/src/backend/libpq/pqcomm.c
+@@ -166,32 +166,45 @@ pq_comm_reset(void)
+ /* --------------------------------
+  *		pq_close - shutdown libpq at backend exit
+  *
+- * Note: in a standalone backend MyProcPort will be null,
+- * don't crash during exit...
++ * This is the one pg_on_exit_callback in place during BackendInitialize().
++ * That function's unusual signal handling constrains that this callback be
++ * safe to run at any instant.
+  * --------------------------------
+  */
+ static void
+ pq_close(int code, Datum arg)
+ {
++	/* Nothing to do in a standalone backend, where MyProcPort is NULL. */
+ 	if (MyProcPort != NULL)
+ 	{
+ #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
+ #ifdef ENABLE_GSS
+ 		OM_uint32	min_s;
+ 
+-		/* Shutdown GSSAPI layer */
++		/*
++		 * Shutdown GSSAPI layer.  This section does nothing when interrupting
++		 * BackendInitialize(), because pg_GSS_recvauth() makes first use of
++		 * "ctx" and "cred".
++		 */
+ 		if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
+ 			gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
+ 
+ 		if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
+ 			gss_release_cred(&min_s, &MyProcPort->gss->cred);
+ #endif   /* ENABLE_GSS */
+-		/* GSS and SSPI share the port->gss struct */
+ 
++		/*
++		 * GSS and SSPI share the port->gss struct.  Since nowhere else does a
++		 * postmaster child free this, doing so is safe when interrupting
++		 * BackendInitialize().
++		 */
+ 		free(MyProcPort->gss);
+ #endif   /* ENABLE_GSS || ENABLE_SSPI */
+ 
+-		/* Cleanly shut down SSL layer */
++		/*
++		 * Cleanly shut down SSL layer.  Nowhere else does a postmaster child
++		 * call this, so this is safe when interrupting BackendInitialize().
++		 */
+ 		secure_close(MyProcPort);
+ 
+ 		/*
+diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
+index f4be3ba..5e53aec 100644
+--- a/src/backend/postmaster/postmaster.c
++++ b/src/backend/postmaster/postmaster.c
+@@ -3038,7 +3038,16 @@ BackendInitialize(Port *port)
+ 	 * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
+ 	 * any client authentication related communication. Otherwise the
+ 	 * postmaster cannot shutdown the database FAST or IMMED cleanly if a
+-	 * buggy client blocks a backend during authentication.
++	 * buggy client fails to send the packet promptly.  XXX it follows that
++	 * the remainder of this function must tolerate losing control at any
++	 * instant.  Likewise, any pg_on_exit_callback registered before or during
++	 * this function must be prepared to execute at any instant between here
++	 * and the end of this function.  Furthermore, affected callbacks execute
++	 * partially or not at all when a second exit-inducing signal arrives
++	 * after proc_exit_prepare() decrements on_proc_exit_index.  (Thanks to
++	 * that mechanic, callbacks need not anticipate more than one call.)  This
++	 * is fragile; it ought to instead follow the norm of handling interrupts
++	 * at selected, safe opportunities.
+ 	 */
+ 	pqsignal(SIGTERM, authdie);
+ 	pqsignal(SIGQUIT, authdie);
diff --git a/postgresql-CVE-2016-0773.patch b/postgresql-CVE-2016-0773.patch
new file mode 100644
index 0000000..7ecb377
--- /dev/null
+++ b/postgresql-CVE-2016-0773.patch
@@ -0,0 +1,153 @@
+regex: fix infinite loops and buffer overruns with large chr values
+(range()/dovec() adapted to the 8.3 MCCE-aware cvec API).
+Source: CentOS 6 postgresql-CVE-2016-0773.patch
+
+diff --git a/src/backend/regex/regc_lex.c b/src/backend/regex/regc_lex.c
+index fc86ca3..9afb1f3 100644
+--- a/src/backend/regex/regc_lex.c
++++ b/src/backend/regex/regc_lex.c
+@@ -792,13 +792,13 @@ lexescape(struct vars * v)
+ 			break;
+ 		case CHR('u'):
+ 			c = lexdigits(v, 16, 4, 4);
+-			if (ISERR())
++			if (ISERR() || c < CHR_MIN || c > CHR_MAX)
+ 				FAILW(REG_EESCAPE);
+ 			RETV(PLAIN, c);
+ 			break;
+ 		case CHR('U'):
+ 			c = lexdigits(v, 16, 8, 8);
+-			if (ISERR())
++			if (ISERR() || c < CHR_MIN || c > CHR_MAX)
+ 				FAILW(REG_EESCAPE);
+ 			RETV(PLAIN, c);
+ 			break;
+@@ -816,7 +816,7 @@ lexescape(struct vars * v)
+ 		case CHR('x'):
+ 			NOTE(REG_UUNPORT);
+ 			c = lexdigits(v, 16, 1, 255);		/* REs >255 long outside spec */
+-			if (ISERR())
++			if (ISERR() || c < CHR_MIN || c > CHR_MAX)
+ 				FAILW(REG_EESCAPE);
+ 			RETV(PLAIN, c);
+ 			break;
+@@ -872,6 +872,9 @@ lexescape(struct vars * v)
+ 
+ /*
+  * lexdigits - slurp up digits and return chr value
++ *
++ * This does not account for overflow; callers should range-check the result
++ * if maxlen is large enough to make that possible.
+  */
+ static chr						/* chr value; errors signalled via ERR */
+ lexdigits(struct vars * v,
+diff --git a/src/backend/regex/regc_locale.c b/src/backend/regex/regc_locale.c
+index 09c1bd1..9207136 100644
+--- a/src/backend/regex/regc_locale.c
++++ b/src/backend/regex/regc_locale.c
+@@ -502,8 +502,7 @@ range(struct vars * v,			/* context */
+ 	int			nchrs;
+ 	struct cvec *cv;
+ 	celt		c,
+-				lc,
+-				uc;
++				cc;
+ 
+ 	if (a != b && !before(a, b))
+ 	{
+@@ -521,24 +520,46 @@ range(struct vars * v,			/* context */
+ 
+ 	/*
+ 	 * When case-independent, it's hard to decide when cvec ranges are usable,
+-	 * so for now at least, we won't try.  We allocate enough space for two
+-	 * case variants plus a little extra for the two title case variants.
++	 * so for now at least, we won't try.  We use a range for the originally
++	 * specified chrs and then add on any case-equivalents that are outside
++	 * that range as individual chrs.
++	 *
++	 * To ensure sane behavior if someone specifies a very large range, limit
++	 * the allocation size to 100000 chrs (arbitrary) and check for overrun
++	 * inside the loop below.
+ 	 */
++	nchrs = b - a + 1;
++	if (nchrs <= 0 || nchrs > 100000)
++		nchrs = 100000;
+ 
+-	nchrs = (b - a + 1) * 2 + 4;
+-
+-	cv = getcvec(v, nchrs, 0, 0);
++	cv = getcvec(v, nchrs, 1, 0);
+ 	NOERRN();
++	addrange(cv, a, b);
+ 
+ 	for (c = a; c <= b; c++)
+ 	{
+-		addchr(cv, c);
+-		lc = pg_wc_tolower((chr) c);
+-		if (c != lc)
+-			addchr(cv, lc);
+-		uc = pg_wc_toupper((chr) c);
+-		if (c != uc)
+-			addchr(cv, uc);
++		cc = pg_wc_tolower((chr) c);
++		if (cc != c &&
++			(before(cc, a) || before(b, cc)))
++		{
++			if (cv->nchrs >= cv->chrspace)
++			{
++				ERR(REG_ETOOBIG);
++				return NULL;
++			}
++			addchr(cv, cc);
++		}
++		cc = pg_wc_toupper((chr) c);
++		if (cc != c &&
++			(before(cc, a) || before(b, cc)))
++		{
++			if (cv->nchrs >= cv->chrspace)
++			{
++				ERR(REG_ETOOBIG);
++				return NULL;
++			}
++			addchr(cv, cc);
++		}
+ 	}
+ 
+ 	return cv;
+diff --git a/src/backend/regex/regcomp.c b/src/backend/regex/regcomp.c
+index c67141b..c3dad7d 100644
+--- a/src/backend/regex/regcomp.c
++++ b/src/backend/regex/regcomp.c
+@@ -1673,7 +1673,10 @@ dovec(struct vars * v,
+ 	{
+ 		ch = *p;
+ 		if (!ISCELEADER(v, ch))
++		{
+ 			newarc(v->nfa, PLAIN, subcolor(v->cm, ch), lp, rp);
++			NOERR();
++		}
+ 		else
+ 		{
+ 			assert(singleton(v->cm, ch));
+@@ -1700,6 +1703,7 @@ dovec(struct vars * v,
+ 		}
+ 		if (from <= to)
+ 			subrange(v, from, to, lp, rp);
++		NOERR();
+ 	}
+ 
+ 	if ((leads == NULL || leads->nchrs == 0) && cv->nmcces == 0)
+diff --git a/src/include/regex/regcustom.h b/src/include/regex/regcustom.h
+index 8471fb0..ede9200 100644
+--- a/src/include/regex/regcustom.h
++++ b/src/include/regex/regcustom.h
+@@ -54,7 +54,8 @@ typedef int celt;				/* type to hold chr, MCCE number, or NOCELT */
+ #define DIGITVAL(c) ((c)-'0')	/* turn chr digit into its value */
+ #define CHRBITS 32				/* bits in a chr; must not use sizeof */
+ #define CHR_MIN 0x00000000		/* smallest and largest chr; the value */
+-#define CHR_MAX 0xfffffffe		/* CHR_MAX-CHR_MIN+1 should fit in uchr */
++#define CHR_MAX 0x7ffffffe		/* CHR_MAX-CHR_MIN+1 must fit in an int, and
++								 * CHR_MAX+1 must fit in both chr and celt */
+ 
+ /* functions operating on chr */
+ #define iscalnum(x) pg_wc_isalnum(x)
diff --git a/postgresql-CVE-2016-5423.patch b/postgresql-CVE-2016-5423.patch
new file mode 100644
index 0000000..010dd3d
--- /dev/null
+++ b/postgresql-CVE-2016-5423.patch
@@ -0,0 +1,291 @@
+Fix two errors with nested CASE/WHEN constructs.
+Source: upstream 5327b764a5 (REL9_1)
+
+diff --git a/src/backend/executor/execQual.c b/src/backend/executor/execQual.c
+index 99e04ae..94739df 100644
+--- a/src/backend/executor/execQual.c
++++ b/src/backend/executor/execQual.c
+@@ -2523,19 +2523,30 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
+ 
+ 	/*
+ 	 * If there's a test expression, we have to evaluate it and save the value
+-	 * where the CaseTestExpr placeholders can find it. We must save and
++	 * where the CaseTestExpr placeholders can find it.  We must save and
+ 	 * restore prior setting of econtext's caseValue fields, in case this node
+-	 * is itself within a larger CASE.
++	 * is itself within a larger CASE.  Furthermore, don't assign to the
++	 * econtext fields until after returning from evaluation of the test
++	 * expression.  We used to pass &econtext->caseValue_isNull to the
++	 * recursive call, but that leads to aliasing that variable within said
++	 * call, which can (and did) produce bugs when the test expression itself
++	 * contains a CASE.
++	 *
++	 * If there's no test expression, we don't actually need to save and
++	 * restore these fields; but it's less code to just do so unconditionally.
+ 	 */
+ 	save_datum = econtext->caseValue_datum;
+ 	save_isNull = econtext->caseValue_isNull;
+ 
+ 	if (caseExpr->arg)
+ 	{
++		bool		arg_isNull;
++
+ 		econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
+ 												 econtext,
+-												 &econtext->caseValue_isNull,
++												 &arg_isNull,
+ 												 NULL);
++		econtext->caseValue_isNull = arg_isNull;
+ 	}
+ 
+ 	/*
+@@ -2547,10 +2558,11 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
+ 	{
+ 		CaseWhenState *wclause = lfirst(clause);
+ 		Datum		clause_value;
++		bool		clause_isNull;
+ 
+ 		clause_value = ExecEvalExpr(wclause->expr,
+ 									econtext,
+-									isNull,
++									&clause_isNull,
+ 									NULL);
+ 
+ 		/*
+@@ -2558,7 +2570,7 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
+ 		 * statement is satisfied.	A NULL result from the test is not
+ 		 * considered true.
+ 		 */
+-		if (DatumGetBool(clause_value) && !*isNull)
++		if (DatumGetBool(clause_value) && !clause_isNull)
+ 		{
+ 			econtext->caseValue_datum = save_datum;
+ 			econtext->caseValue_isNull = save_isNull;
+diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
+index 5f5d970..d872c92 100644
+--- a/src/backend/optimizer/util/clauses.c
++++ b/src/backend/optimizer/util/clauses.c
+@@ -71,6 +71,8 @@ static bool contain_subplans_walker(Node *node, void *context);
+ static bool contain_mutable_functions_walker(Node *node, void *context);
+ static bool contain_volatile_functions_walker(Node *node, void *context);
+ static bool contain_nonstrict_functions_walker(Node *node, void *context);
++static bool contain_context_dependent_node(Node *clause);
++static bool contain_context_dependent_node_walker(Node *node, int *flags);
+ static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
+ static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
+ static bool set_coercionform_dontcare_walker(Node *node, void *context);
+@@ -1026,6 +1028,76 @@ contain_nonstrict_functions_walker(Node *node, void *context)
+ 								  context);
+ }
+ 
++/*****************************************************************************
++ *		Check clauses for context-dependent nodes
++ *****************************************************************************/
++
++/*
++ * contain_context_dependent_node
++ *	  Recursively search for context-dependent nodes within a clause.
++ *
++ * CaseTestExpr nodes must appear directly within the corresponding CaseExpr,
++ * not nested within another one, or they'll see the wrong test value.  If one
++ * appears "bare" in the arguments of a SQL function, then we can't inline the
++ * SQL function for fear of creating such a situation.
++ *
++ * CoerceToDomainValue would have the same issue if domain CHECK expressions
++ * could get inlined into larger expressions, but presently that's impossible.
++ * Still, it might be allowed in future, or other node types with similar
++ * issues might get invented.  So give this function a generic name, and set
++ * up the recursion state to allow multiple flag bits.
++ */
++static bool
++contain_context_dependent_node(Node *clause)
++{
++	int			flags = 0;
++
++	return contain_context_dependent_node_walker(clause, &flags);
++}
++
++#define CCDN_IN_CASEEXPR	0x0001		/* CaseTestExpr okay here? */
++
++static bool
++contain_context_dependent_node_walker(Node *node, int *flags)
++{
++	if (node == NULL)
++		return false;
++	if (IsA(node, CaseTestExpr))
++		return !(*flags & CCDN_IN_CASEEXPR);
++	if (IsA(node, CaseExpr))
++	{
++		CaseExpr   *caseexpr = (CaseExpr *) node;
++
++		/*
++		 * If this CASE doesn't have a test expression, then it doesn't create
++		 * a context in which CaseTestExprs should appear, so just fall
++		 * through and treat it as a generic expression node.
++		 */
++		if (caseexpr->arg)
++		{
++			int			save_flags = *flags;
++			bool		res;
++
++			/*
++			 * Note: in principle, we could distinguish the various sub-parts
++			 * of a CASE construct and set the flag bit only for some of them,
++			 * since we are only expecting CaseTestExprs to appear in the
++			 * "expr" subtree of the CaseWhen nodes.  But it doesn't really
++			 * seem worth any extra code.  If there are any bare CaseTestExprs
++			 * elsewhere in the CASE, something's wrong already.
++			 */
++			*flags |= CCDN_IN_CASEEXPR;
++			res = expression_tree_walker(node,
++									   contain_context_dependent_node_walker,
++										 (void *) flags);
++			*flags = save_flags;
++			return res;
++		}
++	}
++	return expression_tree_walker(node, contain_context_dependent_node_walker,
++								  (void *) flags);
++}
++
+ 
+ /*
+  * find_nonnullable_rels
+@@ -3037,6 +3109,8 @@ evaluate_function(Oid funcid, Oid result_type, int32 result_typmod, List *args,
+  * doesn't work in the general case because it discards information such
+  * as OUT-parameter declarations.
+  *
++ * Also, context-dependent expression nodes in the argument list are trouble.
++ *
+  * Returns a simplified expression if successful, or NULL if cannot
+  * simplify the function.
+  */
+@@ -3191,6 +3265,13 @@ inline_function(Oid funcid, Oid result_type, List *args,
+ 		contain_nonstrict_functions(newexpr))
+ 		goto fail;
+ 
++	/*
++	 * If any parameter expression contains a context-dependent node, we can't
++	 * inline, for fear of putting such a node into the wrong context.
++	 */
++	if (contain_context_dependent_node((Node *) args))
++		goto fail;
++
+ 	/*
+ 	 * We may be able to do it; there are still checks on parameter usage to
+ 	 * make, but those are most easily done in combination with the actual
+diff --git a/src/test/regress/expected/case.out b/src/test/regress/expected/case.out
+index 9ec32b8..5c34af2 100644
+--- a/src/test/regress/expected/case.out
++++ b/src/test/regress/expected/case.out
+@@ -296,8 +296,52 @@ SELECT * FROM CASE_TBL;
+   -8 |  10.1
+ (4 rows)
+ 
++--
++-- Nested CASE expressions
++--
++-- This test exercises a bug caused by aliasing econtext->caseValue_isNull
++-- with the isNull argument of the inner CASE's ExecEvalCase() call.  After
++-- evaluating the vol(null) expression in the inner CASE's second WHEN-clause,
++-- the isNull flag for the case test value incorrectly became true, causing
++-- the third WHEN-clause not to match.  The volatile function calls are needed
++-- to prevent constant-folding in the planner, which would hide the bug.
++CREATE FUNCTION vol(text) returns text as
++  'begin return $1; end' language plpgsql volatile;
++SELECT CASE
++  (CASE vol('bar')
++    WHEN 'foo' THEN 'it was foo!'
++    WHEN vol(null) THEN 'null input'
++    WHEN 'bar' THEN 'it was bar!' END
++  )
++  WHEN 'it was foo!' THEN 'foo recognized'
++  WHEN 'it was bar!' THEN 'bar recognized'
++  ELSE 'unrecognized' END;
++      case      
++----------------
++ bar recognized
++(1 row)
++
++-- In this case, we can't inline the SQL function without confusing things.
++CREATE DOMAIN foodomain AS text;
++CREATE FUNCTION volfoo(text) returns foodomain as
++  'begin return $1::foodomain; end' language plpgsql volatile;
++CREATE FUNCTION inline_eq(foodomain, foodomain) returns boolean as
++  'SELECT CASE $2::text WHEN $1::text THEN true ELSE false END' language sql;
++CREATE OPERATOR = (procedure = inline_eq,
++                   leftarg = foodomain, rightarg = foodomain);
++SELECT CASE volfoo('bar') WHEN 'foo'::foodomain THEN 'is foo' ELSE 'is not foo' END;
++    case    
++------------
++ is not foo
++(1 row)
++
+ --
+ -- Clean up
+ --
+ DROP TABLE CASE_TBL;
<Skipped 5640 lines>
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/packages/postgresql.git/commitdiff/f47a9a58475d9ccc1942668cfc13f29fb19cfda3



More information about the pld-cvs-commit mailing list