]> granicus.if.org Git - postgresql/log
postgresql
9 years agoStamp 8.4.22. REL8_4_STABLE github/REL8_4_STABLE REL8_4_22
Tom Lane [Mon, 21 Jul 2014 19:18:03 +0000 (15:18 -0400)]
Stamp 8.4.22.

9 years agoRelease notes for 9.3.5, 9.2.9, 9.1.14, 9.0.18, 8.4.22.
Tom Lane [Mon, 21 Jul 2014 18:59:41 +0000 (14:59 -0400)]
Release notes for 9.3.5, 9.2.9, 9.1.14, 9.0.18, 8.4.22.

9 years agoTranslation updates
Peter Eisentraut [Mon, 21 Jul 2014 04:53:43 +0000 (00:53 -0400)]
Translation updates

9 years agoUpdate time zone data files to tzdata release 2014e.
Tom Lane [Sat, 19 Jul 2014 19:00:50 +0000 (15:00 -0400)]
Update time zone data files to tzdata release 2014e.

DST law changes in Crimea, Egypt, Morocco.  New zone Antarctica/Troll
for Norwegian base in Queen Maud Land.

9 years agoFix two low-probability memory leaks in regular expression parsing.
Tom Lane [Fri, 18 Jul 2014 17:00:27 +0000 (13:00 -0400)]
Fix two low-probability memory leaks in regular expression parsing.

If pg_regcomp failed after having invoked markst/cleanst, it would leak any
"struct subre" nodes it had created.  (We've already detected all regex
syntax errors at that point, so the only likely causes of later failure
would be query cancel or out-of-memory.)  To fix, make sure freesrnode
knows the difference between the pre-cleanst and post-cleanst cleanup
procedures.  Add some documentation of this less-than-obvious point.

Also, newlacon did the wrong thing with an out-of-memory failure from
realloc(), so that the previously allocated array would be leaked.

Both of these are pretty low-probability scenarios, but a bug is a bug,
so patch all the way back.

Per bug #10976 from Arthur O'Dwyer.

9 years agoFix REASSIGN OWNED for text search objects
Alvaro Herrera [Tue, 15 Jul 2014 17:24:07 +0000 (13:24 -0400)]
Fix REASSIGN OWNED for text search objects

Trying to reassign objects owned by a user that had text search
dictionaries or configurations used to fail with:
ERROR:  unexpected classid 3600
or
ERROR:  unexpected classid 3602

Fix by adding cases for those object types in a switch in pg_shdepend.c.

Both REASSIGN OWNED and text search objects go back all the way to 8.1,
so backpatch to all supported branches.  In 9.3 the alter-owner code was
made generic, so the required change in recent branches is pretty
simple; however, for 9.2 and older ones we need some additional
reshuffling to enable specifying objects by OID rather than name.

Text search templates and parsers are not owned objects, so there's no
change required for them.

Per bug #9749 reported by Michal Novotný

9 years agodoc: small fixes for REINDEX reference page
Peter Eisentraut [Tue, 15 Jul 2014 00:37:00 +0000 (20:37 -0400)]
doc: small fixes for REINDEX reference page

From: Josh Kupershmidt <schmiddy@gmail.com>

9 years agoAdd autocompletion of locale keywords for CREATE DATABASE
Magnus Hagander [Sat, 12 Jul 2014 12:19:57 +0000 (14:19 +0200)]
Add autocompletion of locale keywords for CREATE DATABASE

Adds support for autocomplete of LC_COLLATE and LC_CTYPE to
the CREATE DATABASE command in psql.

9 years agoFix bug with whole-row references to append subplans.
Tom Lane [Fri, 11 Jul 2014 23:12:56 +0000 (19:12 -0400)]
Fix bug with whole-row references to append subplans.

ExecEvalWholeRowVar incorrectly supposed that it could "bless" the source
TupleTableSlot just once per query.  But if the input is coming from an
Append (or, perhaps, other cases?) more than one slot might be returned
over the query run.  This led to "record type has not been registered"
errors when a composite datum was extracted from a non-blessed slot.

This bug has been there a long time; I guess it escaped notice because when
dealing with subqueries the planner tends to expand whole-row Vars into
RowExprs, which don't have the same problem.  It is possible to trigger
the problem in all active branches, though, as illustrated by the added
regression test.

9 years agoDon't assume a subquery's output is unique if there's a SRF in its tlist.
Tom Lane [Tue, 8 Jul 2014 18:03:32 +0000 (14:03 -0400)]
Don't assume a subquery's output is unique if there's a SRF in its tlist.

While the x output of "select x from t group by x" can be presumed unique,
this does not hold for "select x, generate_series(1,10) from t group by x",
because we may expand the set-returning function after the grouping step.
(Perhaps that should be re-thought; but considering all the other oddities
involved with SRFs in targetlists, it seems unlikely we'll change it.)
Put a check in query_is_distinct_for() so it's not fooled by such cases.

Back-patch to all supported branches.

David Rowley

9 years agoAdd some errdetail to checkRuleResultList().
Tom Lane [Wed, 2 Jul 2014 18:20:50 +0000 (14:20 -0400)]
Add some errdetail to checkRuleResultList().

This function wasn't originally thought to be really user-facing,
because converting a table to a view isn't something we expect people
to do manually.  So not all that much effort was spent on the error
messages; in particular, while the code will complain that you got
the column types wrong it won't say exactly what they are.  But since
we repurposed the code to also check compatibility of rule RETURNING
lists, it's definitely user-facing.  It now seems worthwhile to add
errdetail messages showing exactly what the conflict is when there's
a mismatch of column names or types.  This is prompted by bug #10836
from Matthias Raffelsieper, which might have been forestalled if the
error message had reported the wrong column type as being "record".

Per Alvaro's advice, back-patch to branches before 9.4, but resist
the temptation to rephrase any existing strings there.  Adding new
strings is not really a translation degradation; anyway having the
info presented in English is better than not having it at all.

9 years agoRemove obsolete example of CSV log file name from log_filename document.
Fujii Masao [Thu, 26 Jun 2014 05:27:27 +0000 (14:27 +0900)]
Remove obsolete example of CSV log file name from log_filename document.

7380b63 changed log_filename so that epoch was not appended to it
when no format specifier is given. But the example of CSV log file name
with epoch still left in log_filename document. This commit removes
such obsolete example.

This commit also documents the defaults of log_directory and
log_filename.

Backpatch to all supported versions.

Christoph Berg

9 years agoAvoid leaking memory while evaluating arguments for a table function.
Tom Lane [Fri, 20 Jun 2014 02:14:00 +0000 (22:14 -0400)]
Avoid leaking memory while evaluating arguments for a table function.

ExecMakeTableFunctionResult evaluated the arguments for a function-in-FROM
in the query-lifespan memory context.  This is insignificant in simple
cases where the function relation is scanned only once; but if the function
is in a sub-SELECT or is on the inside of a nested loop, any memory
consumed during argument evaluation can add up quickly.  (The potential for
trouble here had been foreseen long ago, per existing comments; but we'd
not previously seen a complaint from the field about it.)  To fix, create
an additional temporary context just for this purpose.

Per an example from MauMau.  Back-patch to all active branches.

9 years agoMake pqsignal() available to pg_regress of ECPG and isolation suites.
Noah Misch [Sat, 14 Jun 2014 14:52:25 +0000 (10:52 -0400)]
Make pqsignal() available to pg_regress of ECPG and isolation suites.

Commit 453a5d91d49e4d35054f92785d830df4067e10c1 made it available to the
src/test/regress build of pg_regress, but all pg_regress builds need the
same treatment.  Patch 9.2 through 8.4; in 9.3 and later, pg_regress
gets pqsignal() via libpgport.

9 years agoSecure Unix-domain sockets of "make check" temporary clusters.
Noah Misch [Sat, 14 Jun 2014 13:41:13 +0000 (09:41 -0400)]
Secure Unix-domain sockets of "make check" temporary clusters.

Any OS user able to access the socket can connect as the bootstrap
superuser and proceed to execute arbitrary code as the OS user running
the test.  Protect against that by placing the socket in a temporary,
mode-0700 subdirectory of /tmp.  The pg_regress-based test suites and
the pg_upgrade test suite were vulnerable; the $(prove_check)-based test
suites were already secure.  Back-patch to 8.4 (all supported versions).
The hazard remains wherever the temporary cluster accepts TCP
connections, notably on Windows.

As a convenient side effect, this lets testing proceed smoothly in
builds that override DEFAULT_PGSOCKET_DIR.  Popular non-default values
like /var/run/postgresql are often unwritable to the build user.

Security: CVE-2014-0067

9 years agoAdd mkdtemp() to libpgport.
Noah Misch [Sat, 14 Jun 2014 13:41:13 +0000 (09:41 -0400)]
Add mkdtemp() to libpgport.

This function is pervasive on free software operating systems; import
NetBSD's implementation.  Back-patch to 8.4, like the commit that will
harness it.

9 years agoFix pg_restore's processing of old-style BLOB COMMENTS data.
Tom Lane [Fri, 13 Jun 2014 00:14:55 +0000 (20:14 -0400)]
Fix pg_restore's processing of old-style BLOB COMMENTS data.

Prior to 9.0, pg_dump handled comments on large objects by dumping a bunch
of COMMENT commands into a single BLOB COMMENTS archive object.  With
sufficiently many such comments, some of the commands would likely get
split across bufferloads when restoring, causing failures in
direct-to-database restores (though no problem would be evident in text
output).  This is the same type of issue we have with table data dumped as
INSERT commands, and it can be fixed in the same way, by using a mini SQL
lexer to figure out where the command boundaries are.  Fortunately, the
COMMENT commands are no more complex to lex than INSERTs, so we can just
re-use the existing lexer for INSERTs.

Per bug #10611 from Jacek Zalewski.  Back-patch to all active branches.

9 years agoRemove inadvertent copyright violation in largeobject regression test.
Tom Lane [Thu, 12 Jun 2014 20:51:24 +0000 (16:51 -0400)]
Remove inadvertent copyright violation in largeobject regression test.

Robert Frost is no longer with us, but his copyrights still are, so
let's stop using "Stopping by Woods on a Snowy Evening" as test data
before somebody decides to sue us.  Wordsworth is more safely dead.

9 years agoFix ancient encoding error in hungarian.stop.
Tom Lane [Wed, 11 Jun 2014 02:48:16 +0000 (22:48 -0400)]
Fix ancient encoding error in hungarian.stop.

When we grabbed this file off the Snowball project's website, we mistakenly
supposed that it was in LATIN1 encoding, but evidently it was actually in
LATIN2.  This resulted in ő (o-double-acute, U+0151, which is code 0xF5 in
LATIN2) being misconverted into õ (o-tilde, U+00F5), as complained of in
bug #10589 from Zoltán Sörös.  We'd have messed up u-double-acute too,
but there aren't any of those in the file.  Other characters used in the
file have the same codes in LATIN1 and LATIN2, which no doubt helped hide
the problem for so long.

The error is not only ours: the Snowball project also was confused about
which encoding is required for Hungarian.  But dealing with that will
require source-code changes that I'm not at all sure we'll wish to
back-patch.  Fixing the stopword file seems reasonably safe to back-patch
however.

9 years agoAdd defenses against running with a wrong selection of LOBLKSIZE.
Tom Lane [Thu, 5 Jun 2014 15:31:26 +0000 (11:31 -0400)]
Add defenses against running with a wrong selection of LOBLKSIZE.

It's critical that the backend's idea of LOBLKSIZE match the way data has
actually been divided up in pg_largeobject.  While we don't provide any
direct way to adjust that value, doing so is a one-line source code change
and various people have expressed interest recently in changing it.  So,
just as with TOAST_MAX_CHUNK_SIZE, it seems prudent to record the value in
pg_control and cross-check that the backend's compiled-in setting matches
the on-disk data.

Also tweak the code in inv_api.c so that fetches from pg_largeobject
explicitly verify that the length of the data field is not more than
LOBLKSIZE.  Formerly we just had Asserts() for that, which is no protection
at all in production builds.  In some of the call sites an overlength data
value would translate directly to a security-relevant stack clobber, so it
seems worth one extra runtime comparison to be sure.

In the back branches, we can't change the contents of pg_control; but we
can still make the extra checks in inv_api.c, which will offer some amount
of protection against running with the wrong value of LOBLKSIZE.

9 years agoFix longstanding bug in HeapTupleSatisfiesVacuum().
Andres Freund [Wed, 4 Jun 2014 21:27:38 +0000 (23:27 +0200)]
Fix longstanding bug in HeapTupleSatisfiesVacuum().

HeapTupleSatisfiesVacuum() didn't properly discern between
DELETE_IN_PROGRESS and INSERT_IN_PROGRESS for rows that have been
inserted in the current transaction and deleted in a aborted
subtransaction of the current backend. At the very least that caused
problems for CLUSTER and CREATE INDEX in transactions that had
aborting subtransactions producing rows, leading to warnings like:
WARNING:  concurrent delete in progress within table "..."
possibly in an endless, uninterruptible, loop.

Instead of treating *InProgress xmins the same as *IsCurrent ones,
treat them as being distinct like the other visibility routines. As
implemented this separatation can cause a behaviour change for rows
that have been inserted and deleted in another, still running,
transaction. HTSV will now return INSERT_IN_PROGRESS instead of
DELETE_IN_PROGRESS for those. That's both, more in line with the other
visibility routines and arguably more correct. The latter because a
INSERT_IN_PROGRESS will make callers look at/wait for xmin, instead of
xmax.
The only current caller where that's possibly worse than the old
behaviour is heap_prune_chain() which now won't mark the page as
prunable if a row has concurrently been inserted and deleted. That's
harmless enough.

As a cautionary measure also insert a interrupt check before the gotos
in IndexBuildHeapScan() that lead to the uninterruptible loop. There
are other possible causes, like a row that several sessions try to
update and all fail, for repeated loops and the cost of doing so in
the retry case is low.

As this bug goes back all the way to the introduction of
subtransactions in 573a71a5da backpatch to all supported releases.

Reported-By: Sandro Santilli
9 years agoOn OS X, link libpython normally, ignoring the "framework" framework.
Tom Lane [Fri, 30 May 2014 22:18:32 +0000 (18:18 -0400)]
On OS X, link libpython normally, ignoring the "framework" framework.

As of Xcode 5.0, Apple isn't including the Python framework as part of the
SDK-level files, which means that linking to it might fail depending on
whether Xcode thinks you've selected a specific SDK version.  According to
their Tech Note 2328, they've basically deprecated the framework method of
linking to libpython and are telling people to link to the shared library
normally.  (I'm pretty sure this is in direct contradiction to the advice
they were giving a few years ago, but whatever.)  Testing says that this
approach works fine at least as far back as OS X 10.4.11, so let's just
rip out the framework special case entirely.  We do still need a special
case to decide that OS X provides a shared library at all, unfortunately
(I wonder why the distutils check doesn't work ...).  But this is still
less of a special case than before, so it's fine.

Back-patch to all supported branches, since we'll doubtless be hearing
about this more as more people update to recent Xcode.

9 years agoWhen using the OSSP UUID library, cache its uuid_t state object.
Tom Lane [Thu, 29 May 2014 17:51:18 +0000 (13:51 -0400)]
When using the OSSP UUID library, cache its uuid_t state object.

The original coding in contrib/uuid-ossp created and destroyed a uuid_t
object (or, in some cases, even two of them) each time it was called.
This is not the intended usage: you're supposed to keep the uuid_t object
around so that the library can cache its state across uses.  (Other UUID
libraries seem to keep equivalent state behind-the-scenes in static
variables, but OSSP chose differently.)  Aside from being quite inefficient,
creating a new uuid_t loses knowledge of the previously generated UUID,
which in theory could result in duplicate V1-style UUIDs being created
on sufficiently fast machines.

On at least some platforms, creating a new uuid_t also draws some entropy
from /dev/urandom, leaving less for the rest of the system.  This seems
sufficiently unpleasant to justify back-patching this change.

9 years agoRevert "Fix bogus %name-prefix option syntax in all our Bison files."
Tom Lane [Wed, 28 May 2014 23:30:15 +0000 (19:30 -0400)]
Revert "Fix bogus %name-prefix option syntax in all our Bison files."

This reverts commit ddf317fe0d1ce4d1189d276a776ab18f985d1ab6.

It turns out that the %name-prefix syntax without "=" does not work
at all in pre-2.4 Bison.  We are not prepared to make such a large
jump in minimum required Bison version just to suppress a warning
message in a version hardly any developers are using yet.
When 3.0 gets more popular, we'll figure out a way to deal with this.
In the meantime, BISONFLAGS=-Wno-deprecated is recommendable for
anyone using 3.0 who doesn't want to see the warning.

9 years agoFix bogus %name-prefix option syntax in all our Bison files.
Tom Lane [Wed, 28 May 2014 19:42:08 +0000 (15:42 -0400)]
Fix bogus %name-prefix option syntax in all our Bison files.

%name-prefix doesn't use an "=" sign according to the Bison docs, but it
silently accepted one anyway, until Bison 3.0.  This was originally a
typo of mine in commit 012abebab1bc72043f3f670bf32e91ae4ee04bd2, and we
seem to have slavishly copied the error into all the other grammar files.

Per report from Vik Fearing; analysis by Peter Eisentraut.

Back-patch to all active branches, since somebody might try to build
a back branch with up-to-date tools.

10 years agoFix unportable setvbuf() usage in initdb.
Tom Lane [Thu, 15 May 2014 19:58:11 +0000 (15:58 -0400)]
Fix unportable setvbuf() usage in initdb.

In yesterday's commit 2dc4f011fd61501cce507be78c39a2677690d44b, I tried
to force buffering of stdout/stderr in initdb to be what it is by
default when the program is run interactively on Unix (since that's how
most manual testing is done).  This tripped over the fact that Windows
doesn't support _IOLBF mode.  We dealt with that a long time ago in
syslogger.c by falling back to unbuffered mode on Windows.  Export that
solution in port.h and use it in initdb.

Back-patch to 8.4, like the previous commit.

10 years agoHandle duplicate XIDs in txid_snapshot.
Heikki Linnakangas [Thu, 15 May 2014 15:29:20 +0000 (18:29 +0300)]
Handle duplicate XIDs in txid_snapshot.

The proc array can contain duplicate XIDs, when a transaction is just being
prepared for two-phase commit. To cope, remove any duplicates in
txid_current_snapshot(). Also ignore duplicates in the input functions, so
that if e.g. you have an old pg_dump file that already contains duplicates,
it will be accepted.

Report and fix by Jan Wieck. Backpatch to all supported versions.

10 years agoFix race condition in preparing a transaction for two-phase commit.
Heikki Linnakangas [Thu, 15 May 2014 13:37:50 +0000 (16:37 +0300)]
Fix race condition in preparing a transaction for two-phase commit.

To lock a prepared transaction's shared memory entry, we used to mark it
with the XID of the backend. When the XID was no longer active according
to the proc array, the entry was implicitly considered as not locked
anymore. However, when preparing a transaction, the backend's proc array
entry was cleared before transfering the locks (and some other state) to
the prepared transaction's dummy PGPROC entry, so there was a window where
another backend could finish the transaction before it was in fact fully
prepared.

To fix, rewrite the locking mechanism of global transaction entries. Instead
of an XID, just have simple locked-or-not flag in each entry (we store the
locking backend's backend id rather than a simple boolean, but that's just
for debugging purposes). The backend is responsible for explicitly unlocking
the entry, and to make sure that that happens, install a callback to unlock
it on abort or process exit.

Backpatch to all supported versions.

10 years agoIn initdb, ensure stdout/stderr buffering behavior is what we expect.
Tom Lane [Thu, 15 May 2014 01:14:09 +0000 (21:14 -0400)]
In initdb, ensure stdout/stderr buffering behavior is what we expect.

Since this program may print to either stdout or stderr, the relative
ordering of its messages depends on the buffering behavior of those files.
Force stdout to be line-buffered and stderr to be unbuffered, ensuring
that the behavior will match standard Unix interactive behavior, even
when stdout and stderr are rerouted to a file.

Per complaint from Tomas Vondra.  The particular case he pointed out is
new in HEAD, but issues of the same sort could arise in any branch with
other error messages, so back-patch to all branches.

I'm unsure whether we might not want to do this in other client programs
as well.  For the moment, just fix initdb.

10 years agoInitialize padding bytes in btree_gist varbit support.
Heikki Linnakangas [Tue, 13 May 2014 11:16:28 +0000 (14:16 +0300)]
Initialize padding bytes in btree_gist varbit support.

The code expands a varbit gist leaf key to a node key by copying the bit
data twice in a varlen datum, as both the lower and upper key. The lower key
was expanded to INTALIGN size, but the padding bytes were not initialized.
That's a problem because when the lower/upper keys are compared, the padding
bytes are used compared too, when the values are otherwise equal. That could
lead to incorrect query results.

REINDEX is advised for any btree_gist indexes on bit or bit varying data
type, to fix any garbage padding bytes on disk.

Per Valgrind, reported by Andres Freund. Backpatch to all supported
versions.

10 years agoAccept tcl 8.6 in configure's probe for tclsh.
Tom Lane [Sat, 10 May 2014 14:48:17 +0000 (10:48 -0400)]
Accept tcl 8.6 in configure's probe for tclsh.

Usually the search would find plain "tclsh" without any trouble,
but some installations might only have the version-numbered flavor
of that program.

No compatibility problems have been reported with 8.6, so we might
as well back-patch this to all active branches.

Christoph Berg

10 years agoDocument permissions needed for pg_database_size and pg_tablespace_size.
Tom Lane [Fri, 9 May 2014 01:45:02 +0000 (21:45 -0400)]
Document permissions needed for pg_database_size and pg_tablespace_size.

Back in 8.3, we installed permissions checks in these functions (see
commits 8bc225e7990a and cc26599b7206).  But we forgot to document that
anywhere in the user-facing docs; it did get mentioned in the 8.3 release
notes, but nobody's looking at that any more.  Per gripe from Suya Huang.

10 years agoUn-break ecpg test suite under --disable-integer-datetimes.
Noah Misch [Thu, 8 May 2014 23:29:02 +0000 (19:29 -0400)]
Un-break ecpg test suite under --disable-integer-datetimes.

Commit 4318daecc959886d001a6e79c6ea853e8b1dfb4b broke it.  The change in
sub-second precision at extreme dates is normal.  The inconsistent
truncation vs. rounding is essentially a bug, albeit a longstanding one.
Back-patch to 8.4, like the causative commit.

10 years agoProtect against torn pages when deleting GIN list pages.
Heikki Linnakangas [Thu, 8 May 2014 11:43:04 +0000 (14:43 +0300)]
Protect against torn pages when deleting GIN list pages.

To-be-deleted list pages contain no useful information, as they are being
deleted, but we must still protect the writes from being torn by a crash
after a partial write. To do that, re-initialize the pages on WAL replay.

Jeff Janes caught this with a test program to test partial writes.
Backpatch to all supported versions.

10 years agoAvoid buffer bloat in libpq when server is consistently faster than client.
Tom Lane [Thu, 8 May 2014 01:38:50 +0000 (21:38 -0400)]
Avoid buffer bloat in libpq when server is consistently faster than client.

If the server sends a long stream of data, and the server + network are
consistently fast enough to force the recv() loop in pqReadData() to
iterate until libpq's input buffer is full, then upon processing the last
incomplete message in each bufferload we'd usually double the buffer size,
due to supposing that we didn't have enough room in the buffer to finish
collecting that message.  After filling the newly-enlarged buffer, the
cycle repeats, eventually resulting in an out-of-memory situation (which
would be reported misleadingly as "lost synchronization with server").
Of course, we should not enlarge the buffer unless we still need room
after discarding already-processed messages.

This bug dates back quite a long time: pqParseInput3 has had the behavior
since perhaps 2003, getCopyDataMessage at least since commit 70066eb1a1ad
in 2008.  Probably the reason it's not been isolated before is that in
common environments the recv() loop would always be faster than the server
(if on the same machine) or faster than the network (if not); or at least
it wouldn't be slower consistently enough to let the buffer ramp up to a
problematic size.  The reported cases involve Windows, which perhaps has
different timing behavior than other platforms.

Per bug #7914 from Shin-ichi Morita, though this is different from his
proposed solution.  Back-patch to all supported branches.

10 years agoFix failure to set ActiveSnapshot while rewinding a cursor.
Tom Lane [Wed, 7 May 2014 18:25:28 +0000 (14:25 -0400)]
Fix failure to set ActiveSnapshot while rewinding a cursor.

ActiveSnapshot needs to be set when we call ExecutorRewind because some
plan node types may execute user-defined functions during their ReScan
calls (nodeLimit.c does so, at least).  The wisdom of that is somewhat
debatable, perhaps, but for now the simplest fix is to make sure the
required context is valid.  Failure to do this typically led to a
null-pointer-dereference core dump, though it's possible that in more
complex cases a function could be executed with the wrong snapshot
leading to very subtle misbehavior.

Per report from Leif Jensen.  It's been broken for a long time, so
back-patch to all active branches.

10 years agoFix interval test, which was broken for floating-point timestamps.
Jeff Davis [Wed, 7 May 2014 02:35:24 +0000 (19:35 -0700)]
Fix interval test, which was broken for floating-point timestamps.

Commit 4318daecc959886d001a6e79c6ea853e8b1dfb4b introduced a test that
couldn't be made consistent between integer and floating-point
timestamps.

It was designed to test the longest possible interval output length,
so removing four zeros from the number of hours, as this patch does,
is not ideal. But the test still has some utility for its original
purpose, and there aren't a lot of other good options.

Noah Misch suggested a different approach where we test that the
output either matches what we expect from integer timestamps or what
we expect from floating-point timestamps. That seemed to obscure an
otherwise simple test, however.

Reviewed by Tom Lane and Noah Misch.

10 years agoRemove tabs after spaces in C comments
Bruce Momjian [Tue, 6 May 2014 15:26:24 +0000 (11:26 -0400)]
Remove tabs after spaces in C comments

This was not changed in HEAD, but will be done later as part of a
pgindent run.  Future pgindent runs will also do this.

Report by Tom Lane

Backpatch through all supported branches, but not HEAD

10 years agoFix possible cache invalidation failure in ReceiveSharedInvalidMessages.
Tom Lane [Mon, 5 May 2014 18:43:55 +0000 (14:43 -0400)]
Fix possible cache invalidation failure in ReceiveSharedInvalidMessages.

Commit fad153ec45299bd4d4f29dec8d9e04e2f1c08148 modified sinval.c to reduce
the number of calls into sinvaladt.c (which require taking a shared lock)
by keeping a local buffer of collected-but-not-yet-processed messages.
However, if processing of the last message in a batch resulted in a
recursive call to ReceiveSharedInvalidMessages, we could overwrite that
message with a new one while the outer invalidation function was still
working on it.  This would be likely to lead to invalidation of the wrong
cache entry, allowing subsequent processing to use stale cache data.
The fix is just to make a local copy of each message while we're processing
it.

Spotted by Andres Freund.  Back-patch to 8.4 where the bug was introduced.

10 years agoFix failure to detoast fields in composite elements of structured types.
Tom Lane [Thu, 1 May 2014 19:19:23 +0000 (15:19 -0400)]
Fix failure to detoast fields in composite elements of structured types.

If we have an array of records stored on disk, the individual record fields
cannot contain out-of-line TOAST pointers: the tuptoaster.c mechanisms are
only prepared to deal with TOAST pointers appearing in top-level fields of
a stored row.  The same applies for ranges over composite types, nested
composites, etc.  However, the existing code only took care of expanding
sub-field TOAST pointers for the case of nested composites, not for other
structured types containing composites.  For example, given a command such
as

UPDATE tab SET arraycol = ARRAY[(ROW(x,42)::mycompositetype] ...

where x is a direct reference to a field of an on-disk tuple, if that field
is long enough to be toasted out-of-line then the TOAST pointer would be
inserted as-is into the array column.  If the source record for x is later
deleted, the array field value would become a dangling pointer, leading
to errors along the line of "missing chunk number 0 for toast value ..."
when the value is referenced.  A reproducible test case for this was
provided by Jan Pecek, but it seems likely that some of the "missing chunk
number" reports we've heard in the past were caused by similar issues.

Code-wise, the problem is that PG_DETOAST_DATUM() is not adequate to
produce a self-contained Datum value if the Datum is of composite type.
Seen in this light, the problem is not just confined to arrays and ranges,
but could also affect some other places where detoasting is done in that
way, for example form_index_tuple().

I tried teaching the array code to apply toast_flatten_tuple_attribute()
along with PG_DETOAST_DATUM() when the array element type is composite,
but this was messy and imposed extra cache lookup costs whether or not any
TOAST pointers were present, indeed sometimes when the array element type
isn't even composite (since sometimes it takes a typcache lookup to find
that out).  The idea of extending that approach to all the places that
currently use PG_DETOAST_DATUM() wasn't attractive at all.

This patch instead solves the problem by decreeing that composite Datum
values must not contain any out-of-line TOAST pointers in the first place;
that is, we expand out-of-line fields at the point of constructing a
composite Datum, not at the point where we're about to insert it into a
larger tuple.  This rule is applied only to true composite Datums, not
to tuples that are being passed around the system as tuples, so it's not
as invasive as it might sound at first.  With this approach, the amount
of code that has to be touched for a full solution is greatly reduced,
and added cache lookup costs are avoided except when there actually is
a TOAST pointer that needs to be inlined.

The main drawback of this approach is that we might sometimes dereference
a TOAST pointer that will never actually be used by the query, imposing a
rather large cost that wasn't there before.  On the other side of the coin,
if the field value is used multiple times then we'll come out ahead by
avoiding repeat detoastings.  Experimentation suggests that common SQL
coding patterns are unaffected either way, though.  Applications that are
very negatively affected could be advised to modify their code to not fetch
columns they won't be using.

In future, we might consider reverting this solution in favor of detoasting
only at the point where data is about to be stored to disk, using some
method that can drill down into multiple levels of nested structured types.
That will require defining new APIs for structured types, though, so it
doesn't seem feasible as a back-patchable fix.

Note that this patch changes HeapTupleGetDatum() from a macro to a function
call; this means that any third-party code using that macro will not get
protection against creating TOAST-pointer-containing Datums until it's
recompiled.  The same applies to any uses of PG_RETURN_HEAPTUPLEHEADER().
It seems likely that this is not a big problem in practice: most of the
tuple-returning functions in core and contrib produce outputs that could
not possibly be toasted anyway, and the same probably holds for third-party
extensions.

This bug has existed since TOAST was invented, so back-patch to all
supported branches.

10 years agoCheck for interrupts and stack overflow during rule/view dumps.
Tom Lane [Wed, 30 Apr 2014 17:46:29 +0000 (13:46 -0400)]
Check for interrupts and stack overflow during rule/view dumps.

Since ruleutils.c recurses, it could be driven to stack overflow by
deeply nested constructs.  Very large queries might also take long
enough to deparse that a check for interrupts seems like a good idea.
Stick appropriate tests into a couple of key places.

Noted by Greg Stark.  Back-patch to all supported branches.

10 years agoAdd missing SYSTEMQUOTEs
Heikki Linnakangas [Wed, 30 Apr 2014 07:34:15 +0000 (10:34 +0300)]
Add missing SYSTEMQUOTEs

Some popen() calls were missing SYSTEMQUOTEs, which caused initdb and
pg_upgrade to fail on Windows, if the installation path contained both
spaces and @ signs.

Patch by Nikhil Deshpande. Backpatch to all supported versions.

10 years agoFix two bugs in WAL-logging of GIN pending-list pages.
Heikki Linnakangas [Mon, 28 Apr 2014 13:12:45 +0000 (16:12 +0300)]
Fix two bugs in WAL-logging of GIN pending-list pages.

In writeListPage, never take a full-page image of the page, because we
have all the information required to re-initialize in the WAL record
anyway. Before this fix, a full-page image was always generated, unless
full_page_writes=off, because when the page is initialized its LSN is
always 0. In stable-branches, keep the code to restore the backup blocks
if they exist, in case that the WAL is generated with an older minor
version, but in master Assert that there are no full-page images.

In the redo routine, add missing "off++". Otherwise the tuples are added
to the page in reverse order. That happens to be harmless because we
always scan and remove all the tuples together, but it was clearly wrong.
Also, it was masked by the first bug unless full_page_writes=off, because
the page was always restored from a full-page image.

Backpatch to all supported versions.

10 years agoReset pg_stat_activity.xact_start during PREPARE TRANSACTION.
Tom Lane [Thu, 24 Apr 2014 17:29:48 +0000 (13:29 -0400)]
Reset pg_stat_activity.xact_start during PREPARE TRANSACTION.

Once we've completed a PREPARE, our session is not running a transaction,
so its entry in pg_stat_activity should show xact_start as null, rather
than leaving the value as the start time of the now-prepared transaction.

I think possibly this oversight was triggered by faulty extrapolation
from the adjacent comment that says PrepareTransaction should not call
AtEOXact_PgStat, so tweak the wording of that comment.

Noted by Andres Freund while considering bug #10123 from Maxim Boguk,
although this error doesn't seem to explain that report.

Back-patch to all active branches.

10 years agoFix unused-variable warning on Windows.
Tom Lane [Thu, 17 Apr 2014 20:12:24 +0000 (16:12 -0400)]
Fix unused-variable warning on Windows.

Introduced in 585bca39: msgid is not used in the Windows code path.

Also adjust comments a tad (mostly to keep pgindent from messing it up).

David Rowley

10 years agopgcrypto: fix memset() calls that might be optimized away
Bruce Momjian [Thu, 17 Apr 2014 16:37:53 +0000 (12:37 -0400)]
pgcrypto:  fix memset() calls that might be optimized away

Specifically, on-stack memset() might be removed, so:

* Replace memset() with px_memset()
* Add px_memset to copy_crlf()
* Add px_memset to pgp-s2k.c

Patch by Marko Kreen

Report by PVS-Studio

Backpatch through 8.4.

10 years agoUse AF_UNSPEC not PF_UNSPEC in getaddrinfo calls.
Tom Lane [Wed, 16 Apr 2014 17:21:09 +0000 (13:21 -0400)]
Use AF_UNSPEC not PF_UNSPEC in getaddrinfo calls.

According to the Single Unix Spec and assorted man pages, you're supposed
to use the constants named AF_xxx when setting ai_family for a getaddrinfo
call.  In a few places we were using PF_xxx instead.  Use of PF_xxx
appears to be an ancient BSD convention that was not adopted by later
standardization.  On BSD and most later Unixen, it doesn't matter much
because those constants have equivalent values anyway; but nonetheless
this code is not per spec.

In the same vein, replace PF_INET by AF_INET in one socket() call, which
wasn't even consistent with the other socket() call in the same function
let alone the remainder of our code.

Per investigation of a Cygwin trouble report from Marco Atzeri.  It's
probably a long shot that this will fix his issue, but it's wrong in
any case.

10 years agoFix timeout in LDAP lookup of libpq connection parameters
Magnus Hagander [Wed, 16 Apr 2014 15:18:02 +0000 (17:18 +0200)]
Fix timeout in LDAP lookup of libpq connection parameters

Bind attempts to an LDAP server should time out after two seconds,
allowing additional lines in the service control file to be parsed
(which provide a fall back to a secondary LDAP server or default options).
The existing code failed to enforce that timeout during TCP connect,
resulting in a hang far longer than two seconds if the LDAP server
does not respond.

Laurenz Albe

10 years agoUse correctly-sized buffer when zero-filling a WAL file.
Heikki Linnakangas [Wed, 16 Apr 2014 07:21:09 +0000 (10:21 +0300)]
Use correctly-sized buffer when zero-filling a WAL file.

I mixed up BLCKSZ and XLOG_BLCKSZ when I changed the way the buffer is
allocated a couple of weeks ago. With the default settings, they are both
8k, but they can be changed at compile-time.

10 years agoBlock signals earlier during postmaster startup.
Tom Lane [Sat, 5 Apr 2014 22:16:24 +0000 (18:16 -0400)]
Block signals earlier during postmaster startup.

Formerly, we set up the postmaster's signal handling only when we were
about to start launching subprocesses.  This is a bad idea though, as
it means that for example a SIGINT arriving before that will kill the
postmaster instantly, perhaps leaving lockfiles, socket files, shared
memory, etc laying about.  We'd rather that such a signal caused orderly
postmaster termination including releasing of those resources.  A simple
fix is to move the PostmasterMain stanza that initializes signal handling
to an earlier point, before we've created any such resources.  Then, an
early-arriving signal will be blocked until we're ready to deal with it
in the usual way.  (The only part that really needs to be moved up is
blocking of signals, but it seems best to keep the signal handler
installation calls together with that; for one thing this ensures the
kernel won't drop any signals we wished to get.  The handlers won't get
invoked in any case until we unblock signals in ServerLoop.)

Per a report from MauMau.  He proposed changing the way "pg_ctl stop"
works to deal with this, but that'd just be masking one symptom not
fixing the core issue.

It's been like this since forever, so back-patch to all supported branches.

10 years agoFix processing of PGC_BACKEND GUC parameters on Windows.
Tom Lane [Sat, 5 Apr 2014 16:41:40 +0000 (12:41 -0400)]
Fix processing of PGC_BACKEND GUC parameters on Windows.

EXEC_BACKEND builds (i.e., Windows) failed to absorb values of PGC_BACKEND
parameters if they'd been changed post-startup via the config file.  This
for example prevented log_connections from working if it were turned on
post-startup.  The mechanism for handling this case has always been a bit
of a kluge, and it wasn't revisited when we implemented EXEC_BACKEND.
While in a normal forking environment new backends will inherit the
postmaster's value of such settings, EXEC_BACKEND backends have to read
the settings from the CONFIG_EXEC_PARAMS file, and they were mistakenly
rejecting them.  So this case has always been broken in the Windows port;
so back-patch to all supported branches.

Amit Kapila

10 years agoAvoid allocations in critical sections.
Heikki Linnakangas [Fri, 4 Apr 2014 10:12:38 +0000 (13:12 +0300)]
Avoid allocations in critical sections.

If a palloc in a critical section fails, it becomes a PANIC.

10 years agoFix documentation about joining pg_locks to other views.
Tom Lane [Thu, 3 Apr 2014 18:18:48 +0000 (14:18 -0400)]
Fix documentation about joining pg_locks to other views.

The advice to join to pg_prepared_xacts via the transaction column was not
updated when the transaction column was replaced by virtualtransaction.
Since it's not quite obvious how to do that join, give an explicit example.
For consistency also give an example for the adjacent case of joining to
pg_stat_activity.  And link-ify the view references too, just because we
can.  Per bug #9840 from Alexey Bashtanov.

Michael Paquier and Tom Lane

10 years agoFix documentation about size of interval type.
Tom Lane [Thu, 3 Apr 2014 15:05:55 +0000 (11:05 -0400)]
Fix documentation about size of interval type.

It's been 16 bytes, not 12, for ages.  This was fixed in passing in HEAD
(commit 146604ec), but as a factual error it should have been back-patched.
Per gripe from Tatsuhito Kasahara.

10 years agoRevert "Secure Unix-domain sockets of "make check" temporary clusters."
Noah Misch [Sat, 29 Mar 2014 07:12:00 +0000 (03:12 -0400)]
Revert "Secure Unix-domain sockets of "make check" temporary clusters."

About half of the buildfarm members use too-long directory names,
strongly suggesting that this approach is a dead end.

10 years agoSecure Unix-domain sockets of "make check" temporary clusters.
Noah Misch [Sat, 29 Mar 2014 04:52:56 +0000 (00:52 -0400)]
Secure Unix-domain sockets of "make check" temporary clusters.

Any OS user able to access the socket can connect as the bootstrap
superuser and in turn execute arbitrary code as the OS user running the
test.  Protect against that by placing the socket in the temporary data
directory, which has mode 0700 thanks to initdb.  Back-patch to 8.4 (all
supported versions).  The hazard remains wherever the temporary cluster
accepts TCP connections, notably on Windows.

Attempts to run "make check" from a directory with a long name will now
fail.  An alternative not sharing that problem was to place the socket
in a subdirectory of /tmp, but that is only secure if /tmp is sticky.
The PG_REGRESS_SOCK_DIR environment variable is available as a
workaround when testing from long directory paths.

As a convenient side effect, this lets testing proceed smoothly in
builds that override DEFAULT_PGSOCKET_DIR.  Popular non-default values
like /var/run/postgresql are often unwritable to the build user.

Security: CVE-2014-0067

10 years agoDocument platform-specificity of unix_socket_permissions.
Noah Misch [Sat, 29 Mar 2014 04:52:31 +0000 (00:52 -0400)]
Document platform-specificity of unix_socket_permissions.

Back-patch to 8.4 (all supported versions).

10 years agoFix refcounting bug in PLy_modify_tuple().
Tom Lane [Wed, 26 Mar 2014 20:41:47 +0000 (16:41 -0400)]
Fix refcounting bug in PLy_modify_tuple().

We must increment the refcount on "plntup" as soon as we have the
reference, not sometime later.  Otherwise, if an error is thrown in
between, the Py_XDECREF(plntup) call in the PG_CATCH block removes a
refcount we didn't add, allowing the object to be freed even though
it's still part of the plpython function's parsetree.

This appears to be the cause of crashes seen on buildfarm member
prairiedog.  It's a bit surprising that we've not seen it fail repeatably
before, considering that the regression tests have been exercising the
faulty code path since 2009.

The real-world impact is probably minimal, since it's unlikely anyone would
be provoking the "TD["new"] is not a dictionary" error in production, and
that's the only case that is actually wrong.  Still, it's a bug affecting
the regression tests, so patch all supported branches.

In passing, remove dead variable "plstr", and demote "platt" to a local
variable inside the PG_TRY block, since we don't need to clean it up
in the PG_CATCH path.

10 years agoProperly check for readdir/closedir() failures
Bruce Momjian [Fri, 21 Mar 2014 17:45:11 +0000 (13:45 -0400)]
Properly check for readdir/closedir() failures

Clear errno before calling readdir() and handle old MinGW errno bug
while adding full test coverage for readdir/closedir failures.

Backpatch through 8.4.

10 years agoStamp 8.4.21. REL8_4_21
Tom Lane [Mon, 17 Mar 2014 19:39:12 +0000 (15:39 -0400)]
Stamp 8.4.21.

10 years agoRelease notes for 9.3.4, 9.2.8, 9.1.13, 9.0.17, 8.4.21.
Tom Lane [Mon, 17 Mar 2014 19:28:38 +0000 (15:28 -0400)]
Release notes for 9.3.4, 9.2.8, 9.1.13, 9.0.17, 8.4.21.

10 years agoTranslation updates
Peter Eisentraut [Mon, 17 Mar 2014 01:30:16 +0000 (21:30 -0400)]
Translation updates

10 years agoFix advertised dispsize for libpq's sslmode connection parameter.
Tom Lane [Mon, 17 Mar 2014 01:43:57 +0000 (21:43 -0400)]
Fix advertised dispsize for libpq's sslmode connection parameter.

"8" was correct back when "disable" was the longest allowed value, but
since "verify-full" was added, it should be "12".  Given the lack of
complaints, I wouldn't be surprised if nobody is actually using these
values ... but still, if they're in the API, they should be right.

Noticed while pursuing a different problem.  It's been wrong for quite
a long time, so back-patch to all supported branches.

10 years agoUpdate time zone data files to tzdata release 2014a.
Tom Lane [Sat, 15 Mar 2014 17:36:07 +0000 (13:36 -0400)]
Update time zone data files to tzdata release 2014a.

DST law changes in Fiji, Turkey; historical changes in Israel, Ukraine.

10 years agoAdd missing #include.
Tom Lane [Fri, 14 Mar 2014 15:47:03 +0000 (11:47 -0400)]
Add missing #include.

Commit 31400a673 and siblings added a check_stack_depth() call in
contrib/intarray/_int_bool.c, but neglected to note that in our oldest
branches that file didn't have the #include that defines that function.
This results in a fortunately-harmless compiler warning.  Per buildfarm.

10 years agoPrevent interrupts while reporting non-ERROR elog messages.
Tom Lane [Fri, 14 Mar 2014 00:59:57 +0000 (20:59 -0400)]
Prevent interrupts while reporting non-ERROR elog messages.

This should eliminate the risk of recursive entry to syslog(3), which
appears to be the cause of the hang reported in bug #9551 from James
Morton.

Arguably, the real problem here is auth.c's willingness to turn on
ImmediateInterruptOK while executing fairly wide swaths of backend code.
We may well need to work at narrowing the code ranges in which the
authentication_timeout interrupt is enabled.  For the moment, though,
this is a cheap and reasonably noninvasive fix for a field-reported
failure; the other approach would be complex and not necessarily
bug-free itself.

Back-patch to all supported branches.

10 years agoIn WAL replay, restore GIN metapage unconditionally to avoid torn page.
Heikki Linnakangas [Wed, 12 Mar 2014 07:59:49 +0000 (09:59 +0200)]
In WAL replay, restore GIN metapage unconditionally to avoid torn page.

We don't take a full-page image of the GIN metapage; instead, the WAL record
contains all the information required to reconstruct it from scratch. But
to avoid torn page hazards, we must re-initialize it from the WAL record
every time, even if it already has a greater LSN, similar to how normal full
page images are restored.

This was highly unlikely to cause any problems in practice, because the GIN
metapage is small. We rely on an update smaller than a 512 byte disk sector
to be atomic elsewhere, at least in pg_control. But better safe than sorry,
and this would be easy to overlook if more fields are added to the metapage
so that it's no longer small.

Reported by Noah Misch. Backpatch to all supported versions.

10 years agoFix dangling smgr_owner pointer when a fake relcache entry is freed.
Heikki Linnakangas [Fri, 7 Mar 2014 11:25:11 +0000 (13:25 +0200)]
Fix dangling smgr_owner pointer when a fake relcache entry is freed.

A fake relcache entry can "own" a SmgrRelation object, like a regular
relcache entry. But when it was free'd, the owner field in SmgrRelation
was not cleared, so it was left pointing to free'd memory.

Amazingly this apparently hasn't caused crashes in practice, or we would've
heard about it earlier. Andres found this with Valgrind.

Report and fix by Andres Freund, with minor modifications by me. Backpatch
to all supported versions.

10 years agoAvoid memcpy() with same source and destination address.
Heikki Linnakangas [Fri, 7 Mar 2014 11:13:33 +0000 (13:13 +0200)]
Avoid memcpy() with same source and destination address.

The behavior of that is undefined, although unlikely to lead to problems in
practice.

Found by running regression tests with Valgrind.

10 years agoFix name of syslog_ident GUC in docs.
Heikki Linnakangas [Fri, 7 Mar 2014 08:35:37 +0000 (10:35 +0200)]
Fix name of syslog_ident GUC in docs.

Michael Paquier

10 years agoAvoid getting more than AccessShareLock when deparsing a query.
Tom Lane [Fri, 7 Mar 2014 00:31:22 +0000 (19:31 -0500)]
Avoid getting more than AccessShareLock when deparsing a query.

In make_ruledef and get_query_def, we have long used AcquireRewriteLocks
to ensure that the querytree we are about to deparse is up-to-date and
the schemas of the underlying relations aren't changing.  Howwever, that
function thinks the query is about to be executed, so it acquires locks
that are stronger than necessary for the purpose of deparsing.  Thus for
example, if pg_dump asks to deparse a rule that includes "INSERT INTO t",
we'd acquire RowExclusiveLock on t.  That results in interference with
concurrent transactions that might for example ask for ShareLock on t.
Since pg_dump is documented as being purely read-only, this is unexpected.
(Worse, it used to actually be read-only; this behavior dates back only
to 8.1, cf commit ba4200246.)

Fix this by adding a parameter to AcquireRewriteLocks to tell it whether
we want the "real" execution locks or only AccessShareLock.

Report, diagnosis, and patch by Dean Rasheed.  Back-patch to all supported
branches.

10 years agoAllow regex operations to be terminated early by query cancel requests.
Tom Lane [Sat, 1 Mar 2014 20:21:13 +0000 (15:21 -0500)]
Allow regex operations to be terminated early by query cancel requests.

The regex code didn't have any provision for query cancel; which is
unsurprising given its non-Postgres origin, but still problematic since
some operations can take a long time.  Introduce a callback function to
check for a pending query cancel or session termination request, and
call it in a couple of strategic spots where we can make the regex code
exit with an error indicator.

If we ever actually split out the regex code as a standalone library,
some additional work will be needed to let the cancel callback function
be specified externally to the library.  But that's straightforward
(certainly so by comparison to putting the locale-dependent character
classification logic on a similar arms-length basis), and there seems
no need to do it right now.

A bigger issue is that there may be more places than these two where
we need to check for cancels.  We can always add more checks later,
now that the infrastructure is in place.

Since there are known examples of not-terribly-long regexes that can
lock up a backend for a long time, back-patch to all supported branches.
I have hopes of fixing the known performance problems later, but adding
query cancel ability seems like a good idea even if they were all fixed.

10 years agoRemove broken code that tried to handle OVERLAPS with a single argument.
Tom Lane [Tue, 18 Feb 2014 17:44:36 +0000 (12:44 -0500)]
Remove broken code that tried to handle OVERLAPS with a single argument.

The SQL standard says that OVERLAPS should have a two-element row
constructor on each side.  The original coding of OVERLAPS support in
our grammar attempted to extend that by allowing a single-element row
constructor, which it internally duplicated ... or tried to, anyway.
But that code has certainly not worked since our List infrastructure was
rewritten in 2004, and I'm none too sure it worked before that.  As it
stands, it ends up building a List that includes itself, leading to
assorted undesirable behaviors later in the parser.

Even if it worked as intended, it'd be a bit evil because of the
possibility of duplicate evaluation of a volatile function that the user
had written only once.  Given the lack of documentation, test cases, or
complaints, let's just get rid of the idea and only support the standard
syntax.

While we're at it, improve the error cursor positioning for the
wrong-number-of-arguments errors, and inline the makeOverlaps() function
since it's only called in one place anyway.

Per bug #9227 from Joshua Yanovski.  Initial patch by Joshua Yanovski,
extended a bit by me.

10 years agoTranslation updates
Peter Eisentraut [Mon, 17 Feb 2014 22:00:49 +0000 (17:00 -0500)]
Translation updates

10 years agoStamp 8.4.20. REL8_4_20
Tom Lane [Mon, 17 Feb 2014 19:44:07 +0000 (14:44 -0500)]
Stamp 8.4.20.

10 years agoLast-minute updates for release notes.
Tom Lane [Mon, 17 Feb 2014 19:25:54 +0000 (14:25 -0500)]
Last-minute updates for release notes.

Add entries for security issues.

Security: CVE-2014-0060 through CVE-2014-0067

10 years agoDocument risks of "make check" in the regression testing instructions.
Tom Lane [Mon, 17 Feb 2014 16:24:51 +0000 (11:24 -0500)]
Document risks of "make check" in the regression testing instructions.

Since the temporary server started by "make check" uses "trust"
authentication, another user on the same machine could connect to it
as database superuser, and then potentially exploit the privileges of
the operating-system user who started the tests.  We should change
the testing procedures to prevent this risk; but discussion is required
about the best way to do that, as well as more testing than is practical
for an undisclosed security problem.  Besides, the same issue probably
affects some user-written test harnesses.  So for the moment, we'll just
warn people against using "make check" when there are untrusted users on
the same machine.

In passing, remove some ancient advice that suggested making the
regression testing subtree world-writable if you'd built as root.
That looks dangerously insecure in modern contexts, and anyway we
should not be encouraging people to build Postgres as root.

Security: CVE-2014-0067

10 years agoPrevent potential overruns of fixed-size buffers.
Tom Lane [Mon, 17 Feb 2014 16:20:38 +0000 (11:20 -0500)]
Prevent potential overruns of fixed-size buffers.

Coverity identified a number of places in which it couldn't prove that a
string being copied into a fixed-size buffer would fit.  We believe that
most, perhaps all of these are in fact safe, or are copying data that is
coming from a trusted source so that any overrun is not really a security
issue.  Nonetheless it seems prudent to forestall any risk by using
strlcpy() and similar functions.

Fixes by Peter Eisentraut and Jozef Mlich based on Coverity reports.

In addition, fix a potential null-pointer-dereference crash in
contrib/chkpass.  The crypt(3) function is defined to return NULL on
failure, but chkpass.c didn't check for that before using the result.
The main practical case in which this could be an issue is if libc is
configured to refuse to execute unapproved hashing algorithms (e.g.,
"FIPS mode").  This ideally should've been a separate commit, but
since it touches code adjacent to one of the buffer overrun changes,
I included it in this commit to avoid last-minute merge issues.
This issue was reported by Honza Horak.

Security: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()

10 years agoPredict integer overflow to avoid buffer overruns.
Noah Misch [Mon, 17 Feb 2014 14:33:31 +0000 (09:33 -0500)]
Predict integer overflow to avoid buffer overruns.

Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement.  Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest.  In passing, add check_stack_depth() to prevent stack overflow
in related functions.

Back-patch to 8.4 (all supported versions).  The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.

Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.

Security: CVE-2014-0064

10 years agoFix handling of wide datetime input/output.
Noah Misch [Mon, 17 Feb 2014 14:33:31 +0000 (09:33 -0500)]
Fix handling of wide datetime input/output.

Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value.  It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer.  ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own.  In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly.  Back-patch to 8.4
(all supported versions).

Reported by Daniel Schüssler, reviewed by Tom Lane.

Security: CVE-2014-0063

10 years agoAvoid repeated name lookups during table and index DDL.
Robert Haas [Mon, 17 Feb 2014 14:33:31 +0000 (09:33 -0500)]
Avoid repeated name lookups during table and index DDL.

If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts.  At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.

This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older).  In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches.  A field has also been added
to the Constraint node (FkConstraint in 8.4).  Third-party code calling
these functions or using the Constraint node will require updating.

Report by Andres Freund.  Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.

Security: CVE-2014-0062

10 years agoDocument security implications of check_function_bodies.
Noah Misch [Mon, 17 Feb 2014 14:33:31 +0000 (09:33 -0500)]
Document security implications of check_function_bodies.

Back-patch to 8.4 (all supported versions).

10 years agoPrevent privilege escalation in explicit calls to PL validators.
Noah Misch [Mon, 17 Feb 2014 14:33:31 +0000 (09:33 -0500)]
Prevent privilege escalation in explicit calls to PL validators.

The primary role of PL validators is to be called implicitly during
CREATE FUNCTION, but they are also normal functions that a user can call
explicitly.  Add a permissions check to each validator to ensure that a
user cannot use explicit validator calls to achieve things he could not
otherwise achieve.  Back-patch to 8.4 (all supported versions).
Non-core procedural language extensions ought to make the same two-line
change to their own validators.

Andres Freund, reviewed by Tom Lane and Noah Misch.

Security: CVE-2014-0061

10 years agoShore up ADMIN OPTION restrictions.
Noah Misch [Mon, 17 Feb 2014 14:33:31 +0000 (09:33 -0500)]
Shore up ADMIN OPTION restrictions.

Granting a role without ADMIN OPTION is supposed to prevent the grantee
from adding or removing members from the granted role.  Issuing SET ROLE
before the GRANT bypassed that, because the role itself had an implicit
right to add or remove members.  Plug that hole by recognizing that
implicit right only when the session user matches the current role.
Additionally, do not recognize it during a security-restricted operation
or during execution of a SECURITY DEFINER function.  The restriction on
SECURITY DEFINER is not security-critical.  However, it seems best for a
user testing his own SECURITY DEFINER function to see the same behavior
others will see.  Back-patch to 8.4 (all supported versions).

The SQL standards do not conflate roles and users as PostgreSQL does;
only SQL roles have members, and only SQL users initiate sessions.  An
application using PostgreSQL users and roles as SQL users and roles will
never attempt to grant membership in the role that is the session user,
so the implicit right to add or remove members will never arise.

The security impact was mostly that a role member could revoke access
from others, contrary to the wishes of his own grantor.  Unapproved role
member additions are less notable, because the member can still largely
achieve that by creating a view or a SECURITY DEFINER function.

Reviewed by Andres Freund and Tom Lane.  Reported, independently, by
Jonas Sundman and Noah Misch.

Security: CVE-2014-0060

10 years agoRelease notes for 9.3.3, 9.2.7, 9.1.12, 9.0.16, 8.4.20.
Tom Lane [Mon, 17 Feb 2014 03:08:45 +0000 (22:08 -0500)]
Release notes for 9.3.3, 9.2.7, 9.1.12, 9.0.16, 8.4.20.

10 years agoOoops, forgot to remove solar87 and friends from src/timezone/Makefile.
Tom Lane [Sat, 15 Feb 2014 04:20:08 +0000 (23:20 -0500)]
Ooops, forgot to remove solar87 and friends from src/timezone/Makefile.

Per buildfarm.

10 years agoUpdate time zone data files to tzdata release 2013i.
Tom Lane [Sat, 15 Feb 2014 02:59:13 +0000 (21:59 -0500)]
Update time zone data files to tzdata release 2013i.

DST law changes in Jordan; historical changes in Cuba.

Also, remove the zones Asia/Riyadh87, Asia/Riyadh88, and Asia/Riyadh89.
Per the upstream announcement:
    The files solar87, solar88, and solar89 are no longer distributed.
    They were a negative experiment -- that is, a demonstration that
    tz data can represent solar time only with some difficulty and error.
    Their presence in the distribution caused confusion, as Riyadh
    civil time was generally not solar time in those years.

10 years agoSuggest shell here-documents instead of psql -c for multiple commands.
Tom Lane [Fri, 14 Feb 2014 17:54:58 +0000 (12:54 -0500)]
Suggest shell here-documents instead of psql -c for multiple commands.

The documentation suggested using "echo | psql", but not the often-superior
alternative of a here-document.  Also, be more direct about suggesting
that people avoid -c for multiple commands.  Per discussion.

10 years agoClean up error cases in psql's COPY TO STDOUT/FROM STDIN code.
Tom Lane [Thu, 13 Feb 2014 23:45:32 +0000 (18:45 -0500)]
Clean up error cases in psql's COPY TO STDOUT/FROM STDIN code.

Adjust handleCopyOut() to stop trying to write data once it's failed
one time.  For typical cases such as out-of-disk-space or broken-pipe,
additional attempts aren't going to do anything but waste time, and
in any case clean truncation of the output seems like a better behavior
than randomly dropping blocks in the middle.

Also remove dubious (and misleadingly documented) attempt to force our way
out of COPY_OUT state if libpq didn't do that.  If we did have a situation
like that, it'd be a bug in libpq and would be better fixed there, IMO.
We can hope that commit fa4440f51628d692f077d54b8313aea31af087ea took care
of any such problems, anyway.

Also fix longstanding bug in handleCopyIn(): PQputCopyEnd() only supports
a non-null errormsg parameter in protocol version 3, and will actively
fail if one is passed in version 2.  This would've made our attempts
to get out of COPY_IN state after a failure into infinite loops when
talking to pre-7.4 servers.

Back-patch the COPY_OUT state change business back to 9.2 where it was
introduced, and the other two fixes into all supported branches.

10 years agoFix length checking for Unicode identifiers containing escapes (U&"...").
Tom Lane [Thu, 13 Feb 2014 19:24:58 +0000 (14:24 -0500)]
Fix length checking for Unicode identifiers containing escapes (U&"...").

We used the length of the input string, not the de-escaped string, as
the trigger for NAMEDATALEN truncation.  AFAICS this would only result
in sometimes printing a phony truncation warning; but it's just luck
that there was no worse problem, since we were violating the API spec
for truncate_identifier().  Per bug #9204 from Joshua Yanovski.

This has been wrong since the Unicode-identifier support was added,
so back-patch to all supported branches.

10 years agoImprove cross-references between minor version release notes.
Tom Lane [Thu, 13 Feb 2014 00:09:32 +0000 (19:09 -0500)]
Improve cross-references between minor version release notes.

We have a practice of providing a "bread crumb" trail between the minor
versions where the migration section actually tells you to do something.
Historically that was just plain text, eg, "see the release notes for
9.2.4"; but if you're using a browser or PDF reader, it's a lot nicer
if it's a live hyperlink.  So use "<xref>" instead.  Any argument against
doing this vanished with the recent decommissioning of plain-text release
notes.

Vik Fearing

10 years agoImprove text of stub HISTORY file.
Tom Lane [Wed, 12 Feb 2014 23:16:50 +0000 (18:16 -0500)]
Improve text of stub HISTORY file.

Per Peter Eisentraut.

10 years agoImprove libpq's error recovery for connection loss during COPY.
Tom Lane [Wed, 12 Feb 2014 22:50:23 +0000 (17:50 -0500)]
Improve libpq's error recovery for connection loss during COPY.

In pqSendSome, if the connection is already closed at entry, discard any
queued output data before returning.  There is no possibility of ever
sending the data, and anyway this corresponds to what we'd do if we'd
detected a hard error while trying to send().  This avoids possible
indefinite bloat of the output buffer if the application keeps trying
to send data (or even just keeps trying to do PQputCopyEnd, as psql
indeed will).

Because PQputCopyEnd won't transition out of PGASYNC_COPY_IN state
until it's successfully queued the COPY END message, and pqPutMsgEnd
doesn't distinguish a queuing failure from a pqSendSome failure,
this omission allowed an infinite loop in psql if the connection closure
occurred when we had at least 8K queued to send.  It might be worth
refactoring so that we can make that distinction, but for the moment
the other changes made here seem to offer adequate defenses.

To guard against other variants of this scenario, do not allow
PQgetResult to return a PGRES_COPY_XXX result if the connection is
already known dead.  Make sure it returns PGRES_FATAL_ERROR instead.

Per report from Stephen Frost.  Back-patch to all active branches.

10 years agoIn XLogReadBufferExtended, don't assume P_NEW yields consecutive pages.
Tom Lane [Wed, 12 Feb 2014 19:52:32 +0000 (14:52 -0500)]
In XLogReadBufferExtended, don't assume P_NEW yields consecutive pages.

In a database that's not yet reached consistency, it's possible that some
segments of a relation are not full-size but are not the last ones either.
Because of the way smgrnblocks() works, asking for a new page with P_NEW
will fill in the last not-full-size segment --- and if that makes it full
size, the apparent EOF of the relation will increase by more than one page,
so that the next P_NEW request will yield a page past the next consecutive
one.  This breaks the relation-extension logic in XLogReadBufferExtended,
possibly allowing a page update to be applied to some page far past where
it was intended to go.  This appears to be the explanation for reports of
table bloat on replication slaves compared to their masters, and probably
explains some corrupted-slave reports as well.

Fix the loop to check the page number it actually got, rather than merely
Assert()'ing that dead reckoning got it to the desired place.  AFAICT,
there are no other places that make assumptions about exactly which page
they'll get from P_NEW.

Problem identified by Greg Stark, though this is not the same as his
proposed patch.

It's been like this for a long time, so back-patch to all supported
branches.

10 years agoDon't generate plain-text HISTORY and src/test/regress/README anymore.
Tom Lane [Tue, 11 Feb 2014 01:48:30 +0000 (20:48 -0500)]
Don't generate plain-text HISTORY and src/test/regress/README anymore.

Providing this information as plain text was doubtless worth the trouble
ten years ago, but it seems likely that hardly anyone reads it in this
format anymore.  And the effort required to maintain these files (in the
form of extra-complex markup rules in the relevant parts of the SGML
documentation) is significant.  So, let's stop doing that and rely solely
on the other documentation formats.

Per discussion, the plain-text INSTALL instructions might still be worth
their keep, so we continue to generate that file.

Rather than remove HISTORY and src/test/regress/README from distribution
tarballs entirely, replace them with simple stub files that tell the reader
where to find the relevant documentation.  This is mainly to avoid possibly
breaking packaging recipes that expect these files to exist.

Back-patch to all supported branches, because simplifying the markup
requirements for release notes won't help much unless we do it in all
branches.

10 years agoUse memmove() instead of memcpy() for copying overlapping regions.
Heikki Linnakangas [Mon, 10 Feb 2014 07:55:14 +0000 (09:55 +0200)]
Use memmove() instead of memcpy() for copying overlapping regions.

In commit d2495f272cd164ff075bee5c4ce95aed11338a36, I fixed this bug in
to_tsquery(), but missed the fact that plainto_tsquery() has the same bug.

10 years agoFix makefile syntax.
Andrew Dunstan [Sun, 2 Feb 2014 00:51:37 +0000 (19:51 -0500)]
Fix makefile syntax.

10 years agoFix some wide-character bugs in the text-search parser.
Tom Lane [Sat, 1 Feb 2014 23:27:12 +0000 (18:27 -0500)]
Fix some wide-character bugs in the text-search parser.

In p_isdigit and other character class test functions generated by the
p_iswhat macro, the code path for non-C locales with multibyte encodings
contained a bogus pointer cast that would accidentally fail to malfunction
if types wchar_t and wint_t have the same width.  Apparently that is true
on most platforms, but not on recent Cygwin releases.  Remove the cast,
as it seems completely unnecessary (I think it arose from a false analogy
to the need to cast to unsigned char when dealing with the <ctype.h>
functions).  Per bug #8970 from Marco Atzeri.

In the same functions, the code path for C locale with a multibyte encoding
simply ANDed each wide character with 0xFF before passing it to the
corresponding <ctype.h> function.  This could result in false positive
answers for some non-ASCII characters, so use a range test instead.
Noted by me while investigating Marco's complaint.

Also, remove some useless though not actually buggy maskings and casts
in the hand-coded p_isalnum and p_isalpha functions, which evidently
got tested a bit more carefully than the macro-generated functions.

10 years agoCopy the libpq DLL to the bin directory on Mingw and Cygwin.
Andrew Dunstan [Sat, 1 Feb 2014 20:16:52 +0000 (15:16 -0500)]
Copy the libpq DLL to the bin directory on Mingw and Cygwin.

This has long been done by the MSVC build system, and has caused
confusion in the past when programs like psql have failed to start
because they can't find the DLL. If it's in the same directory as it now
will be they will find it.

Backpatch to all live branches.

10 years agoClear MyProc and MyProcSignalState before they become invalid.
Robert Haas [Sat, 1 Feb 2014 02:31:08 +0000 (21:31 -0500)]
Clear MyProc and MyProcSignalState before they become invalid.

Evidence from buildfarm member crake suggests that the new test_shm_mq
module is routinely crashing the server due to the arrival of a SIGUSR1
after the shared memory segment has been unmapped.  Although processes
using the new dynamic background worker facilities are more likely to
receive a SIGUSR1 around this time, the problem is also possible on older
branches, so I'm back-patching the parts of this change that apply to
older branches as far as they apply.

It's already generally the case that code checks whether these pointers
are NULL before deferencing them, so the important thing is mostly to
make sure that they do get set to NULL before they become invalid.  But
in master, there's one case in procsignal_sigusr1_handler that lacks a
NULL guard, so add that.

Patch by me; review by Tom Lane.