Skip to content

Commit 8b10746

Browse files
committed
Avoid calling strerror[_r] in PQcancel().
PQcancel() is supposed to be safe to call from a signal handler, and indeed psql uses it that way. All of the library functions it uses are specified to be async-signal-safe by POSIX ... except for strerror. Neither plain strerror nor strerror_r are considered safe. When this code was written, back in the dark ages, we probably figured "oh, strerror will just index into a constant array of strings" ... but in any locale except C, that's unlikely to be true. Probably the reason we've not heard complaints is that (a) this error-handling code is unlikely to be reached in normal use, and (b) in many scenarios, localized error strings would already have been loaded, after which maybe it's safe to call strerror here. Still, this is clearly unacceptable. The best we can do without relying on strerror is to print the decimal value of errno, so make it do that instead. (This is probably not much loss of user-friendliness, given that it is hard to get a failure here.) Back-patch to all supported branches. Discussion: https://postgr.es/m/2937814.1641960929@sss.pgh.pa.us
1 parent 491182e commit 8b10746

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/interfaces/libpq/fe-connect.c

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3902,7 +3902,6 @@ internal_cancel(SockAddr *raddr, int be_pid, int be_key,
39023902
{
39033903
int save_errno = SOCK_ERRNO;
39043904
pgsocket tmpsock = PGINVALID_SOCKET;
3905-
char sebuf[256];
39063905
int maxlen;
39073906
struct
39083907
{
@@ -3981,8 +3980,25 @@ internal_cancel(SockAddr *raddr, int be_pid, int be_key,
39813980
maxlen = errbufsize - strlen(errbuf) - 2;
39823981
if (maxlen >= 0)
39833982
{
3984-
strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
3985-
maxlen);
3983+
/*
3984+
* We can't invoke strerror here, since it's not signal-safe. Settle
3985+
* for printing the decimal value of errno. Even that has to be done
3986+
* the hard way.
3987+
*/
3988+
int val = SOCK_ERRNO;
3989+
char buf[32];
3990+
char *bufp;
3991+
3992+
bufp = buf + sizeof(buf) - 1;
3993+
*bufp = '\0';
3994+
do
3995+
{
3996+
*(--bufp) = (val % 10) + '0';
3997+
val /= 10;
3998+
} while (val > 0);
3999+
bufp -= 6;
4000+
memcpy(bufp, "error ", 6);
4001+
strncat(errbuf, bufp, maxlen);
39864002
strcat(errbuf, "\n");
39874003
}
39884004
if (tmpsock != PGINVALID_SOCKET)

0 commit comments

Comments
 (0)