Re: BUG #16330: psql accesses null pointer in connect.c:do_connect

From: Michael Paquier <michael(at)paquier(dot)xyz>
To: hghwng(at)gmail(dot)com, pgsql-bugs(at)lists(dot)postgresql(dot)org
Cc: Alvaro Herrera <alvherre(at)2ndquadrant(dot)com>
Subject: Re: BUG #16330: psql accesses null pointer in connect.c:do_connect
Date: 2020-03-30 07:19:37
Message-ID: 20200330071937.GC43995@paquier.xyz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On Mon, Mar 30, 2020 at 02:20:48AM +0000, PG Bug reporting form wrote:
> If the connection to postmaster is closed, then trying to re-connect to
> another one leads to SIGSEGV.
>
> REPRODUCE:
> $ psql
> -> \conninfo
> You are connected to database "hugh" as user "hugh" via socket in
> "/run/postgresql" at port "5432".
> *shut down server with commands like "systemctl stop postgresql"*
> -> \conninfo
> You are currently not connected to a database.
> -> \c a b c d
> [1] 984978 segmentation fault (core dumped) psql

Indeed. Reproduced the problem here on HEAD and REL_12_STABLE, though
you need to execute a command after stopping the server to let psql
know that you are not connected to a database.

> ANALYSIS:
> PQhost(o_conn) returns NULL, and strcmp(host, NULL) raises SIGSEGV.

Yes, the problem comes from this commit (added Alvaro in CC):
commit: 6e5f8d489acccdc50a35a1b7db8e72b5ad579253
author: Alvaro Herrera <alvherre(at)alvh(dot)no-ip(dot)org>
date: Mon, 19 Nov 2018 14:34:12 -0300
psql: Show IP address in \conninfo

And more particularly this bit that ignores the possibility of
PQhost() being NULL:
- if (!user && reuse_previous)
- user = PQuser(o_conn);
- if (!host && reuse_previous)
- host = PQhost(o_conn);
- if (!port && reuse_previous)
- port = PQport(o_conn);
+ if (reuse_previous)
+ {
+ if (!user)
+ user = PQuser(o_conn);
+ if (host && strcmp(host, PQhost(o_conn)) == 0)
+ {
+ /*
+ * if we are targetting the same host, reuse its hostaddr for
+ * consistency
+ */
+ hostaddr = PQhostaddr(o_conn);

A fix like the attached should be sufficient as if we know that
PQhost() is NULL for the old connection we cannot use the old
hostaddr. Alvaro, what do you think?
--
Michael

Attachment Content-Type Size
psql-crash-fix.patch text/x-diff 469 bytes

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Francisco Olarte 2020-03-30 11:13:58 Re: BUG #16321: Memory leaks in PostmasterMain
Previous Message Alexander Lakhin 2020-03-30 05:00:00 Re: BUG #16329: Valgrind detects an invalid read when building a gist index with buffering