LCOV - code coverage report
Current view: top level - src/interfaces/libpq - fe-connect.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 36.8 % 3074 1132
Test Date: 2026-01-26 10:56:24 Functions: 57.8 % 109 63
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 25.6 % 1994 511

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * fe-connect.c
       4                 :             :  *        functions related to setting up a connection to the backend
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *        src/interfaces/libpq/fe-connect.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : 
      16                 :             : #include "postgres_fe.h"
      17                 :             : 
      18                 :             : #include <sys/stat.h>
      19                 :             : #include <fcntl.h>
      20                 :             : #include <ctype.h>
      21                 :             : #include <limits.h>
      22                 :             : #include <netdb.h>
      23                 :             : #include <time.h>
      24                 :             : #include <unistd.h>
      25                 :             : 
      26                 :             : #include "common/base64.h"
      27                 :             : #include "common/ip.h"
      28                 :             : #include "common/link-canary.h"
      29                 :             : #include "common/scram-common.h"
      30                 :             : #include "common/string.h"
      31                 :             : #include "fe-auth.h"
      32                 :             : #include "fe-auth-oauth.h"
      33                 :             : #include "libpq-fe.h"
      34                 :             : #include "libpq-int.h"
      35                 :             : #include "mb/pg_wchar.h"
      36                 :             : #include "pg_config_paths.h"
      37                 :             : #include "port/pg_bswap.h"
      38                 :             : 
      39                 :             : #ifdef WIN32
      40                 :             : #include "win32.h"
      41                 :             : #ifdef _WIN32_IE
      42                 :             : #undef _WIN32_IE
      43                 :             : #endif
      44                 :             : #define _WIN32_IE 0x0500
      45                 :             : #ifdef near
      46                 :             : #undef near
      47                 :             : #endif
      48                 :             : #define near
      49                 :             : #include <shlobj.h>
      50                 :             : #include <mstcpip.h>
      51                 :             : #else
      52                 :             : #include <sys/socket.h>
      53                 :             : #include <netdb.h>
      54                 :             : #include <netinet/in.h>
      55                 :             : #include <netinet/tcp.h>
      56                 :             : #include <pwd.h>
      57                 :             : #endif
      58                 :             : 
      59                 :             : #ifdef WIN32
      60                 :             : #include "pthread-win32.h"
      61                 :             : #else
      62                 :             : #include <pthread.h>
      63                 :             : #endif
      64                 :             : 
      65                 :             : #ifdef USE_LDAP
      66                 :             : #ifdef WIN32
      67                 :             : #include <winldap.h>
      68                 :             : #else
      69                 :             : /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
      70                 :             : #define LDAP_DEPRECATED 1
      71                 :             : #include <ldap.h>
      72                 :             : typedef struct timeval LDAP_TIMEVAL;
      73                 :             : #endif
      74                 :             : static int      ldapServiceLookup(const char *purl, PQconninfoOption *options,
      75                 :             :                                                           PQExpBuffer errorMessage);
      76                 :             : #endif
      77                 :             : 
      78                 :             : #ifndef WIN32
      79                 :             : #define PGPASSFILE ".pgpass"
      80                 :             : #else
      81                 :             : #define PGPASSFILE "pgpass.conf"
      82                 :             : #endif
      83                 :             : 
      84                 :             : /*
      85                 :             :  * Pre-9.0 servers will return this SQLSTATE if asked to set
      86                 :             :  * application_name in a startup packet.  We hard-wire the value rather
      87                 :             :  * than looking into errcodes.h since it reflects historical behavior
      88                 :             :  * rather than that of the current code.
      89                 :             :  */
      90                 :             : #define ERRCODE_APPNAME_UNKNOWN "42704"
      91                 :             : 
      92                 :             : /* This is part of the protocol so just define it */
      93                 :             : #define ERRCODE_INVALID_PASSWORD "28P01"
      94                 :             : /* This too */
      95                 :             : #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
      96                 :             : 
      97                 :             : /*
      98                 :             :  * Cope with the various platform-specific ways to spell TCP keepalive socket
      99                 :             :  * options.  This doesn't cover Windows, which as usual does its own thing.
     100                 :             :  */
     101                 :             : #if defined(TCP_KEEPIDLE)
     102                 :             : /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
     103                 :             : #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
     104                 :             : #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
     105                 :             : #elif defined(TCP_KEEPALIVE_THRESHOLD)
     106                 :             : /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
     107                 :             : #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
     108                 :             : #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
     109                 :             : #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
     110                 :             : /* TCP_KEEPALIVE is the name of this option on macOS */
     111                 :             : /* Caution: Solaris has this symbol but it means something different */
     112                 :             : #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
     113                 :             : #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
     114                 :             : #endif
     115                 :             : 
     116                 :             : /*
     117                 :             :  * fall back options if they are not specified by arguments or defined
     118                 :             :  * by environment variables
     119                 :             :  */
     120                 :             : #define DefaultHost             "localhost"
     121                 :             : #define DefaultOption   ""
     122                 :             : #ifdef USE_SSL
     123                 :             : #define DefaultChannelBinding   "prefer"
     124                 :             : #else
     125                 :             : #define DefaultChannelBinding   "disable"
     126                 :             : #endif
     127                 :             : #define DefaultTargetSessionAttrs       "any"
     128                 :             : #define DefaultLoadBalanceHosts "disable"
     129                 :             : #ifdef USE_SSL
     130                 :             : #define DefaultSSLMode "prefer"
     131                 :             : #define DefaultSSLCertMode "allow"
     132                 :             : #else
     133                 :             : #define DefaultSSLMode  "disable"
     134                 :             : #define DefaultSSLCertMode "disable"
     135                 :             : #endif
     136                 :             : #define DefaultSSLNegotiation   "postgres"
     137                 :             : #ifdef ENABLE_GSS
     138                 :             : #include "fe-gssapi-common.h"
     139                 :             : #define DefaultGSSMode "prefer"
     140                 :             : #else
     141                 :             : #define DefaultGSSMode "disable"
     142                 :             : #endif
     143                 :             : 
     144                 :             : /* ----------
     145                 :             :  * Definition of the conninfo parameters and their fallback resources.
     146                 :             :  *
     147                 :             :  * If Environment-Var and Compiled-in are specified as NULL, no
     148                 :             :  * fallback is available. If after all no value can be determined
     149                 :             :  * for an option, an error is returned.
     150                 :             :  *
     151                 :             :  * The value for the username is treated specially in conninfo_add_defaults.
     152                 :             :  * If the value is not obtained any other way, the username is determined
     153                 :             :  * by pg_fe_getauthname().
     154                 :             :  *
     155                 :             :  * The Label and Disp-Char entries are provided for applications that
     156                 :             :  * want to use PQconndefaults() to create a generic database connection
     157                 :             :  * dialog. Disp-Char is defined as follows:
     158                 :             :  *              ""            Normal input field
     159                 :             :  *              "*"           Password field - hide value
     160                 :             :  *              "D"           Debug option - don't show by default
     161                 :             :  *
     162                 :             :  * NB: Server-side clients -- dblink, postgres_fdw, libpqrcv -- use dispchar to
     163                 :             :  * determine which options to expose to end users, and how. Changing dispchar
     164                 :             :  * has compatibility and security implications for those clients. For example,
     165                 :             :  * postgres_fdw will attach a "*" option to USER MAPPING instead of the default
     166                 :             :  * SERVER, and it disallows setting "D" options entirely.
     167                 :             :  *
     168                 :             :  * PQconninfoOptions[] is a constant static array that we use to initialize
     169                 :             :  * a dynamically allocated working copy.  All the "val" fields in
     170                 :             :  * PQconninfoOptions[] *must* be NULL.  In a working copy, non-null "val"
     171                 :             :  * fields point to malloc'd strings that should be freed when the working
     172                 :             :  * array is freed (see PQconninfoFree).
     173                 :             :  *
     174                 :             :  * The first part of each struct is identical to the one in libpq-fe.h,
     175                 :             :  * which is required since we memcpy() data between the two!
     176                 :             :  * ----------
     177                 :             :  */
     178                 :             : typedef struct _internalPQconninfoOption
     179                 :             : {
     180                 :             :         char       *keyword;            /* The keyword of the option                    */
     181                 :             :         char       *envvar;                     /* Fallback environment variable name   */
     182                 :             :         char       *compiled;           /* Fallback compiled in default value   */
     183                 :             :         char       *val;                        /* Option's current value, or NULL              */
     184                 :             :         char       *label;                      /* Label for field in connect dialog    */
     185                 :             :         char       *dispchar;           /* Indicates how to display this field in a
     186                 :             :                                                                  * connect dialog. Values are: "" Display
     187                 :             :                                                                  * entered value as is "*" Password field -
     188                 :             :                                                                  * hide value "D"  Debug option - don't show
     189                 :             :                                                                  * by default */
     190                 :             :         int                     dispsize;               /* Field size in characters for dialog  */
     191                 :             :         /* ---
     192                 :             :          * Anything above this comment must be synchronized with
     193                 :             :          * PQconninfoOption in libpq-fe.h, since we memcpy() data
     194                 :             :          * between them!
     195                 :             :          * ---
     196                 :             :          */
     197                 :             :         off_t           connofs;                /* Offset into PGconn struct, -1 if not there */
     198                 :             : } internalPQconninfoOption;
     199                 :             : 
     200                 :             : static const internalPQconninfoOption PQconninfoOptions[] = {
     201                 :             :         {"service", "PGSERVICE", NULL, NULL,
     202                 :             :                 "Database-Service", "", 20,
     203                 :             :         offsetof(struct pg_conn, pgservice)},
     204                 :             : 
     205                 :             :         {"servicefile", "PGSERVICEFILE", NULL, NULL,
     206                 :             :                 "Database-Service-File", "", 64,
     207                 :             :         offsetof(struct pg_conn, pgservicefile)},
     208                 :             : 
     209                 :             :         {"user", "PGUSER", NULL, NULL,
     210                 :             :                 "Database-User", "", 20,
     211                 :             :         offsetof(struct pg_conn, pguser)},
     212                 :             : 
     213                 :             :         {"password", "PGPASSWORD", NULL, NULL,
     214                 :             :                 "Database-Password", "*", 20,
     215                 :             :         offsetof(struct pg_conn, pgpass)},
     216                 :             : 
     217                 :             :         {"passfile", "PGPASSFILE", NULL, NULL,
     218                 :             :                 "Database-Password-File", "", 64,
     219                 :             :         offsetof(struct pg_conn, pgpassfile)},
     220                 :             : 
     221                 :             :         {"channel_binding", "PGCHANNELBINDING", DefaultChannelBinding, NULL,
     222                 :             :                 "Channel-Binding", "", 8,   /* sizeof("require") == 8 */
     223                 :             :         offsetof(struct pg_conn, channel_binding)},
     224                 :             : 
     225                 :             :         {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
     226                 :             :                 "Connect-timeout", "", 10,  /* strlen(INT32_MAX) == 10 */
     227                 :             :         offsetof(struct pg_conn, connect_timeout)},
     228                 :             : 
     229                 :             :         {"dbname", "PGDATABASE", NULL, NULL,
     230                 :             :                 "Database-Name", "", 20,
     231                 :             :         offsetof(struct pg_conn, dbName)},
     232                 :             : 
     233                 :             :         {"host", "PGHOST", NULL, NULL,
     234                 :             :                 "Database-Host", "", 40,
     235                 :             :         offsetof(struct pg_conn, pghost)},
     236                 :             : 
     237                 :             :         {"hostaddr", "PGHOSTADDR", NULL, NULL,
     238                 :             :                 "Database-Host-IP-Address", "", 45,
     239                 :             :         offsetof(struct pg_conn, pghostaddr)},
     240                 :             : 
     241                 :             :         {"port", "PGPORT", DEF_PGPORT_STR, NULL,
     242                 :             :                 "Database-Port", "", 6,
     243                 :             :         offsetof(struct pg_conn, pgport)},
     244                 :             : 
     245                 :             :         {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
     246                 :             :                 "Client-Encoding", "", 10,
     247                 :             :         offsetof(struct pg_conn, client_encoding_initial)},
     248                 :             : 
     249                 :             :         {"options", "PGOPTIONS", DefaultOption, NULL,
     250                 :             :                 "Backend-Options", "", 40,
     251                 :             :         offsetof(struct pg_conn, pgoptions)},
     252                 :             : 
     253                 :             :         {"application_name", "PGAPPNAME", NULL, NULL,
     254                 :             :                 "Application-Name", "", 64,
     255                 :             :         offsetof(struct pg_conn, appname)},
     256                 :             : 
     257                 :             :         {"fallback_application_name", NULL, NULL, NULL,
     258                 :             :                 "Fallback-Application-Name", "", 64,
     259                 :             :         offsetof(struct pg_conn, fbappname)},
     260                 :             : 
     261                 :             :         {"keepalives", NULL, NULL, NULL,
     262                 :             :                 "TCP-Keepalives", "", 1,    /* should be just '0' or '1' */
     263                 :             :         offsetof(struct pg_conn, keepalives)},
     264                 :             : 
     265                 :             :         {"keepalives_idle", NULL, NULL, NULL,
     266                 :             :                 "TCP-Keepalives-Idle", "", 10,      /* strlen(INT32_MAX) == 10 */
     267                 :             :         offsetof(struct pg_conn, keepalives_idle)},
     268                 :             : 
     269                 :             :         {"keepalives_interval", NULL, NULL, NULL,
     270                 :             :                 "TCP-Keepalives-Interval", "", 10,  /* strlen(INT32_MAX) == 10 */
     271                 :             :         offsetof(struct pg_conn, keepalives_interval)},
     272                 :             : 
     273                 :             :         {"keepalives_count", NULL, NULL, NULL,
     274                 :             :                 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
     275                 :             :         offsetof(struct pg_conn, keepalives_count)},
     276                 :             : 
     277                 :             :         {"tcp_user_timeout", NULL, NULL, NULL,
     278                 :             :                 "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
     279                 :             :         offsetof(struct pg_conn, pgtcp_user_timeout)},
     280                 :             : 
     281                 :             :         /*
     282                 :             :          * ssl options are allowed even without client SSL support because the
     283                 :             :          * client can still handle SSL modes "disable" and "allow". Other
     284                 :             :          * parameters have no effect on non-SSL connections, so there is no reason
     285                 :             :          * to exclude them since none of them are mandatory.
     286                 :             :          */
     287                 :             :         {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
     288                 :             :                 "SSL-Mode", "", 12,         /* sizeof("verify-full") == 12 */
     289                 :             :         offsetof(struct pg_conn, sslmode)},
     290                 :             : 
     291                 :             :         {"sslnegotiation", "PGSSLNEGOTIATION", DefaultSSLNegotiation, NULL,
     292                 :             :                 "SSL-Negotiation", "", 9,   /* sizeof("postgres") == 9  */
     293                 :             :         offsetof(struct pg_conn, sslnegotiation)},
     294                 :             : 
     295                 :             :         {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
     296                 :             :                 "SSL-Compression", "", 1,
     297                 :             :         offsetof(struct pg_conn, sslcompression)},
     298                 :             : 
     299                 :             :         {"sslcert", "PGSSLCERT", NULL, NULL,
     300                 :             :                 "SSL-Client-Cert", "", 64,
     301                 :             :         offsetof(struct pg_conn, sslcert)},
     302                 :             : 
     303                 :             :         {"sslkey", "PGSSLKEY", NULL, NULL,
     304                 :             :                 "SSL-Client-Key", "", 64,
     305                 :             :         offsetof(struct pg_conn, sslkey)},
     306                 :             : 
     307                 :             :         {"sslcertmode", "PGSSLCERTMODE", NULL, NULL,
     308                 :             :                 "SSL-Client-Cert-Mode", "", 8,      /* sizeof("disable") == 8 */
     309                 :             :         offsetof(struct pg_conn, sslcertmode)},
     310                 :             : 
     311                 :             :         {"sslpassword", NULL, NULL, NULL,
     312                 :             :                 "SSL-Client-Key-Password", "*", 20,
     313                 :             :         offsetof(struct pg_conn, sslpassword)},
     314                 :             : 
     315                 :             :         {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
     316                 :             :                 "SSL-Root-Certificate", "", 64,
     317                 :             :         offsetof(struct pg_conn, sslrootcert)},
     318                 :             : 
     319                 :             :         {"sslcrl", "PGSSLCRL", NULL, NULL,
     320                 :             :                 "SSL-Revocation-List", "", 64,
     321                 :             :         offsetof(struct pg_conn, sslcrl)},
     322                 :             : 
     323                 :             :         {"sslcrldir", "PGSSLCRLDIR", NULL, NULL,
     324                 :             :                 "SSL-Revocation-List-Dir", "", 64,
     325                 :             :         offsetof(struct pg_conn, sslcrldir)},
     326                 :             : 
     327                 :             :         {"sslsni", "PGSSLSNI", "1", NULL,
     328                 :             :                 "SSL-SNI", "", 1,
     329                 :             :         offsetof(struct pg_conn, sslsni)},
     330                 :             : 
     331                 :             :         {"requirepeer", "PGREQUIREPEER", NULL, NULL,
     332                 :             :                 "Require-Peer", "", 10,
     333                 :             :         offsetof(struct pg_conn, requirepeer)},
     334                 :             : 
     335                 :             :         {"require_auth", "PGREQUIREAUTH", NULL, NULL,
     336                 :             :                 "Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */
     337                 :             :         offsetof(struct pg_conn, require_auth)},
     338                 :             : 
     339                 :             :         {"min_protocol_version", "PGMINPROTOCOLVERSION",
     340                 :             :                 NULL, NULL,
     341                 :             :                 "Min-Protocol-Version", "", 6,      /* sizeof("latest") = 6 */
     342                 :             :         offsetof(struct pg_conn, min_protocol_version)},
     343                 :             : 
     344                 :             :         {"max_protocol_version", "PGMAXPROTOCOLVERSION",
     345                 :             :                 NULL, NULL,
     346                 :             :                 "Max-Protocol-Version", "", 6,      /* sizeof("latest") = 6 */
     347                 :             :         offsetof(struct pg_conn, max_protocol_version)},
     348                 :             : 
     349                 :             :         {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL,
     350                 :             :                 "SSL-Minimum-Protocol-Version", "", 8,      /* sizeof("TLSv1.x") == 8 */
     351                 :             :         offsetof(struct pg_conn, ssl_min_protocol_version)},
     352                 :             : 
     353                 :             :         {"ssl_max_protocol_version", "PGSSLMAXPROTOCOLVERSION", NULL, NULL,
     354                 :             :                 "SSL-Maximum-Protocol-Version", "", 8,      /* sizeof("TLSv1.x") == 8 */
     355                 :             :         offsetof(struct pg_conn, ssl_max_protocol_version)},
     356                 :             : 
     357                 :             :         /*
     358                 :             :          * As with SSL, all GSS options are exposed even in builds that don't have
     359                 :             :          * support.
     360                 :             :          */
     361                 :             :         {"gssencmode", "PGGSSENCMODE", DefaultGSSMode, NULL,
     362                 :             :                 "GSSENC-Mode", "", 8,       /* sizeof("disable") == 8 */
     363                 :             :         offsetof(struct pg_conn, gssencmode)},
     364                 :             : 
     365                 :             :         /* Kerberos and GSSAPI authentication support specifying the service name */
     366                 :             :         {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
     367                 :             :                 "Kerberos-service-name", "", 20,
     368                 :             :         offsetof(struct pg_conn, krbsrvname)},
     369                 :             : 
     370                 :             :         {"gsslib", "PGGSSLIB", NULL, NULL,
     371                 :             :                 "GSS-library", "", 7,       /* sizeof("gssapi") == 7 */
     372                 :             :         offsetof(struct pg_conn, gsslib)},
     373                 :             : 
     374                 :             :         {"gssdelegation", "PGGSSDELEGATION", "0", NULL,
     375                 :             :                 "GSS-delegation", "", 1,
     376                 :             :         offsetof(struct pg_conn, gssdelegation)},
     377                 :             : 
     378                 :             :         {"replication", NULL, NULL, NULL,
     379                 :             :                 "Replication", "D", 5,
     380                 :             :         offsetof(struct pg_conn, replication)},
     381                 :             : 
     382                 :             :         {"target_session_attrs", "PGTARGETSESSIONATTRS",
     383                 :             :                 DefaultTargetSessionAttrs, NULL,
     384                 :             :                 "Target-Session-Attrs", "", 15, /* sizeof("prefer-standby") = 15 */
     385                 :             :         offsetof(struct pg_conn, target_session_attrs)},
     386                 :             : 
     387                 :             :         {"load_balance_hosts", "PGLOADBALANCEHOSTS",
     388                 :             :                 DefaultLoadBalanceHosts, NULL,
     389                 :             :                 "Load-Balance-Hosts", "", 8,        /* sizeof("disable") = 8 */
     390                 :             :         offsetof(struct pg_conn, load_balance_hosts)},
     391                 :             : 
     392                 :             :         {"scram_client_key", NULL, NULL, NULL, "SCRAM-Client-Key", "D", SCRAM_MAX_KEY_LEN * 2,
     393                 :             :         offsetof(struct pg_conn, scram_client_key)},
     394                 :             : 
     395                 :             :         {"scram_server_key", NULL, NULL, NULL, "SCRAM-Server-Key", "D", SCRAM_MAX_KEY_LEN * 2,
     396                 :             :         offsetof(struct pg_conn, scram_server_key)},
     397                 :             : 
     398                 :             :         /* OAuth v2 */
     399                 :             :         {"oauth_issuer", NULL, NULL, NULL,
     400                 :             :                 "OAuth-Issuer", "", 40,
     401                 :             :         offsetof(struct pg_conn, oauth_issuer)},
     402                 :             : 
     403                 :             :         {"oauth_client_id", NULL, NULL, NULL,
     404                 :             :                 "OAuth-Client-ID", "", 40,
     405                 :             :         offsetof(struct pg_conn, oauth_client_id)},
     406                 :             : 
     407                 :             :         {"oauth_client_secret", NULL, NULL, NULL,
     408                 :             :                 "OAuth-Client-Secret", "*", 40,
     409                 :             :         offsetof(struct pg_conn, oauth_client_secret)},
     410                 :             : 
     411                 :             :         {"oauth_scope", NULL, NULL, NULL,
     412                 :             :                 "OAuth-Scope", "", 15,
     413                 :             :         offsetof(struct pg_conn, oauth_scope)},
     414                 :             : 
     415                 :             :         {"sslkeylogfile", NULL, NULL, NULL,
     416                 :             :                 "SSL-Key-Log-File", "D", 64,
     417                 :             :         offsetof(struct pg_conn, sslkeylogfile)},
     418                 :             : 
     419                 :             :         /* Terminating entry --- MUST BE LAST */
     420                 :             :         {NULL, NULL, NULL, NULL,
     421                 :             :         NULL, NULL, 0}
     422                 :             : };
     423                 :             : 
     424                 :             : static const PQEnvironmentOption EnvironmentOptions[] =
     425                 :             : {
     426                 :             :         /* common user-interface settings */
     427                 :             :         {
     428                 :             :                 "PGDATESTYLE", "datestyle"
     429                 :             :         },
     430                 :             :         {
     431                 :             :                 "PGTZ", "timezone"
     432                 :             :         },
     433                 :             :         /* internal performance-related settings */
     434                 :             :         {
     435                 :             :                 "PGGEQO", "geqo"
     436                 :             :         },
     437                 :             :         {
     438                 :             :                 NULL, NULL
     439                 :             :         }
     440                 :             : };
     441                 :             : 
     442                 :             : static const pg_fe_sasl_mech *supported_sasl_mechs[] =
     443                 :             : {
     444                 :             :         &pg_scram_mech,
     445                 :             :         &pg_oauth_mech,
     446                 :             : };
     447                 :             : #define SASL_MECHANISM_COUNT lengthof(supported_sasl_mechs)
     448                 :             : 
     449                 :             : /* The connection URI must start with either of the following designators: */
     450                 :             : static const char uri_designator[] = "postgresql://";
     451                 :             : static const char short_uri_designator[] = "postgres://";
     452                 :             : 
     453                 :             : static bool connectOptions1(PGconn *conn, const char *conninfo);
     454                 :             : static bool init_allowed_encryption_methods(PGconn *conn);
     455                 :             : #if defined(USE_SSL) || defined(ENABLE_GSS)
     456                 :             : static int      encryption_negotiation_failed(PGconn *conn);
     457                 :             : #endif
     458                 :             : static bool connection_failed(PGconn *conn);
     459                 :             : static bool select_next_encryption_method(PGconn *conn, bool have_valid_connection);
     460                 :             : static PGPing internal_ping(PGconn *conn);
     461                 :             : static void pqFreeCommandQueue(PGcmdQueueEntry *queue);
     462                 :             : static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
     463                 :             : static void freePGconn(PGconn *conn);
     464                 :             : static void release_conn_addrinfo(PGconn *conn);
     465                 :             : static int      store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist);
     466                 :             : static void sendTerminateConn(PGconn *conn);
     467                 :             : static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
     468                 :             : static PQconninfoOption *parse_connection_string(const char *connstr,
     469                 :             :                                                                                                  PQExpBuffer errorMessage, bool use_defaults);
     470                 :             : static int      uri_prefix_length(const char *connstr);
     471                 :             : static bool recognized_connection_string(const char *connstr);
     472                 :             : static PQconninfoOption *conninfo_parse(const char *conninfo,
     473                 :             :                                                                                 PQExpBuffer errorMessage, bool use_defaults);
     474                 :             : static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
     475                 :             :                                                                                           const char *const *values, PQExpBuffer errorMessage,
     476                 :             :                                                                                           bool use_defaults, int expand_dbname);
     477                 :             : static bool conninfo_add_defaults(PQconninfoOption *options,
     478                 :             :                                                                   PQExpBuffer errorMessage);
     479                 :             : static PQconninfoOption *conninfo_uri_parse(const char *uri,
     480                 :             :                                                                                         PQExpBuffer errorMessage, bool use_defaults);
     481                 :             : static bool conninfo_uri_parse_options(PQconninfoOption *options,
     482                 :             :                                                                            const char *uri, PQExpBuffer errorMessage);
     483                 :             : static bool conninfo_uri_parse_params(char *params,
     484                 :             :                                                                           PQconninfoOption *connOptions,
     485                 :             :                                                                           PQExpBuffer errorMessage);
     486                 :             : static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
     487                 :             : static bool get_hexdigit(char digit, int *value);
     488                 :             : static const char *conninfo_getval(PQconninfoOption *connOptions,
     489                 :             :                                                                    const char *keyword);
     490                 :             : static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
     491                 :             :                                                                                    const char *keyword, const char *value,
     492                 :             :                                                                                    PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
     493                 :             : static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
     494                 :             :                                                                            const char *keyword);
     495                 :             : static void defaultNoticeReceiver(void *arg, const PGresult *res);
     496                 :             : static void defaultNoticeProcessor(void *arg, const char *message);
     497                 :             : static int      parseServiceInfo(PQconninfoOption *options,
     498                 :             :                                                          PQExpBuffer errorMessage);
     499                 :             : static int      parseServiceFile(const char *serviceFile,
     500                 :             :                                                          const char *service,
     501                 :             :                                                          PQconninfoOption *options,
     502                 :             :                                                          PQExpBuffer errorMessage,
     503                 :             :                                                          bool *group_found);
     504                 :             : static char *pwdfMatchesString(char *buf, const char *token);
     505                 :             : static char *passwordFromFile(const char *hostname, const char *port,
     506                 :             :                                                           const char *dbname, const char *username,
     507                 :             :                                                           const char *pgpassfile, const char **errmsg);
     508                 :             : static void pgpassfileWarning(PGconn *conn);
     509                 :             : static void default_threadlock(int acquire);
     510                 :             : static bool sslVerifyProtocolVersion(const char *version);
     511                 :             : static bool sslVerifyProtocolRange(const char *min, const char *max);
     512                 :             : static bool pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, const char *context);
     513                 :             : 
     514                 :             : 
     515                 :             : /* global variable because fe-auth.c needs to access it */
     516                 :             : pgthreadlock_t pg_g_threadlock = default_threadlock;
     517                 :             : 
     518                 :             : 
     519                 :             : /*
     520                 :             :  *              pqDropConnection
     521                 :             :  *
     522                 :             :  * Close any physical connection to the server, and reset associated
     523                 :             :  * state inside the connection object.  We don't release state that
     524                 :             :  * would be needed to reconnect, though, nor local state that might still
     525                 :             :  * be useful later.
     526                 :             :  *
     527                 :             :  * We can always flush the output buffer, since there's no longer any hope
     528                 :             :  * of sending that data.  However, unprocessed input data might still be
     529                 :             :  * valuable, so the caller must tell us whether to flush that or not.
     530                 :             :  */
     531                 :             : void
     532                 :         638 : pqDropConnection(PGconn *conn, bool flushInput)
     533                 :             : {
     534                 :             :         /* Drop any SSL state */
     535                 :         638 :         pqsecure_close(conn);
     536                 :             : 
     537                 :             :         /* Close the socket itself */
     538         [ +  + ]:         638 :         if (conn->sock != PGINVALID_SOCKET)
     539                 :         317 :                 closesocket(conn->sock);
     540                 :         638 :         conn->sock = PGINVALID_SOCKET;
     541                 :             : 
     542                 :             :         /* Optionally discard any unread data */
     543         [ -  + ]:         638 :         if (flushInput)
     544                 :         638 :                 conn->inStart = conn->inCursor = conn->inEnd = 0;
     545                 :             : 
     546                 :             :         /* Always discard any unsent data */
     547                 :         638 :         conn->outCount = 0;
     548                 :             : 
     549                 :             :         /* Likewise, discard any pending pipelined commands */
     550                 :         638 :         pqFreeCommandQueue(conn->cmd_queue_head);
     551                 :         638 :         conn->cmd_queue_head = conn->cmd_queue_tail = NULL;
     552                 :         638 :         pqFreeCommandQueue(conn->cmd_queue_recycle);
     553                 :         638 :         conn->cmd_queue_recycle = NULL;
     554                 :             : 
     555                 :             :         /* Free authentication/encryption state */
     556         [ +  - ]:         638 :         if (conn->cleanup_async_auth)
     557                 :             :         {
     558                 :             :                 /*
     559                 :             :                  * Any in-progress async authentication should be torn down first so
     560                 :             :                  * that cleanup_async_auth() can depend on the other authentication
     561                 :             :                  * state if necessary.
     562                 :             :                  */
     563                 :           0 :                 conn->cleanup_async_auth(conn);
     564                 :           0 :                 conn->cleanup_async_auth = NULL;
     565                 :           0 :         }
     566                 :         638 :         conn->async_auth = NULL;
     567                 :             :         /* cleanup_async_auth() should have done this, but make sure */
     568                 :         638 :         conn->altsock = PGINVALID_SOCKET;
     569                 :             : #ifdef ENABLE_GSS
     570                 :             :         {
     571                 :         638 :                 OM_uint32       min_s;
     572                 :             : 
     573         [ +  - ]:         638 :                 if (conn->gcred != GSS_C_NO_CREDENTIAL)
     574                 :             :                 {
     575                 :           0 :                         gss_release_cred(&min_s, &conn->gcred);
     576                 :           0 :                         conn->gcred = GSS_C_NO_CREDENTIAL;
     577                 :           0 :                 }
     578         [ +  - ]:         638 :                 if (conn->gctx)
     579                 :           0 :                         gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
     580         [ +  - ]:         638 :                 if (conn->gtarg_nam)
     581                 :           0 :                         gss_release_name(&min_s, &conn->gtarg_nam);
     582         [ +  - ]:         638 :                 if (conn->gss_SendBuffer)
     583                 :             :                 {
     584                 :           0 :                         free(conn->gss_SendBuffer);
     585                 :           0 :                         conn->gss_SendBuffer = NULL;
     586                 :           0 :                 }
     587         [ +  - ]:         638 :                 if (conn->gss_RecvBuffer)
     588                 :             :                 {
     589                 :           0 :                         free(conn->gss_RecvBuffer);
     590                 :           0 :                         conn->gss_RecvBuffer = NULL;
     591                 :           0 :                 }
     592         [ +  - ]:         638 :                 if (conn->gss_ResultBuffer)
     593                 :             :                 {
     594                 :           0 :                         free(conn->gss_ResultBuffer);
     595                 :           0 :                         conn->gss_ResultBuffer = NULL;
     596                 :           0 :                 }
     597                 :         638 :                 conn->gssenc = false;
     598                 :         638 :         }
     599                 :             : #endif
     600                 :             : #ifdef ENABLE_SSPI
     601                 :             :         if (conn->sspitarget)
     602                 :             :         {
     603                 :             :                 free(conn->sspitarget);
     604                 :             :                 conn->sspitarget = NULL;
     605                 :             :         }
     606                 :             :         if (conn->sspicred)
     607                 :             :         {
     608                 :             :                 FreeCredentialsHandle(conn->sspicred);
     609                 :             :                 free(conn->sspicred);
     610                 :             :                 conn->sspicred = NULL;
     611                 :             :         }
     612                 :             :         if (conn->sspictx)
     613                 :             :         {
     614                 :             :                 DeleteSecurityContext(conn->sspictx);
     615                 :             :                 free(conn->sspictx);
     616                 :             :                 conn->sspictx = NULL;
     617                 :             :         }
     618                 :             :         conn->usesspi = 0;
     619                 :             : #endif
     620         [ +  - ]:         638 :         if (conn->sasl_state)
     621                 :             :         {
     622                 :           0 :                 conn->sasl->free(conn->sasl_state);
     623                 :           0 :                 conn->sasl_state = NULL;
     624                 :           0 :         }
     625                 :         638 : }
     626                 :             : 
     627                 :             : /*
     628                 :             :  * pqFreeCommandQueue
     629                 :             :  * Free all the entries of PGcmdQueueEntry queue passed.
     630                 :             :  */
     631                 :             : static void
     632                 :        1276 : pqFreeCommandQueue(PGcmdQueueEntry *queue)
     633                 :             : {
     634         [ +  + ]:        1602 :         while (queue != NULL)
     635                 :             :         {
     636                 :         326 :                 PGcmdQueueEntry *cur = queue;
     637                 :             : 
     638                 :         326 :                 queue = cur->next;
     639                 :         326 :                 free(cur->query);
     640                 :         326 :                 free(cur);
     641                 :         326 :         }
     642                 :        1276 : }
     643                 :             : 
     644                 :             : /*
     645                 :             :  *              pqDropServerData
     646                 :             :  *
     647                 :             :  * Clear all connection state data that was received from (or deduced about)
     648                 :             :  * the server.  This is essential to do between connection attempts to
     649                 :             :  * different servers, else we may incorrectly hold over some data from the
     650                 :             :  * old server.
     651                 :             :  *
     652                 :             :  * It would be better to merge this into pqDropConnection, perhaps, but
     653                 :             :  * right now we cannot because that function is called immediately on
     654                 :             :  * detection of connection loss (cf. pqReadData, for instance).  This data
     655                 :             :  * should be kept until we are actually starting a new connection.
     656                 :             :  */
     657                 :             : static void
     658                 :         636 : pqDropServerData(PGconn *conn)
     659                 :             : {
     660                 :         636 :         PGnotify   *notify;
     661                 :         636 :         pgParameterStatus *pstatus;
     662                 :             : 
     663                 :             :         /* Forget pending notifies */
     664                 :         636 :         notify = conn->notifyHead;
     665         [ -  + ]:         636 :         while (notify != NULL)
     666                 :             :         {
     667                 :           0 :                 PGnotify   *prev = notify;
     668                 :             : 
     669                 :           0 :                 notify = notify->next;
     670                 :           0 :                 free(prev);
     671                 :           0 :         }
     672                 :         636 :         conn->notifyHead = conn->notifyTail = NULL;
     673                 :             : 
     674                 :             :         /* Reset ParameterStatus data, as well as variables deduced from it */
     675                 :         636 :         pstatus = conn->pstatus;
     676         [ +  + ]:        5376 :         while (pstatus != NULL)
     677                 :             :         {
     678                 :        4740 :                 pgParameterStatus *prev = pstatus;
     679                 :             : 
     680                 :        4740 :                 pstatus = pstatus->next;
     681                 :        4740 :                 free(prev);
     682                 :        4740 :         }
     683                 :         636 :         conn->pstatus = NULL;
     684                 :         636 :         conn->client_encoding = PG_SQL_ASCII;
     685                 :         636 :         conn->std_strings = false;
     686                 :         636 :         conn->default_transaction_read_only = PG_BOOL_UNKNOWN;
     687                 :         636 :         conn->in_hot_standby = PG_BOOL_UNKNOWN;
     688                 :         636 :         conn->scram_sha_256_iterations = SCRAM_SHA_256_DEFAULT_ITERATIONS;
     689                 :         636 :         conn->sversion = 0;
     690                 :             : 
     691                 :             :         /* Drop large-object lookup data */
     692                 :         636 :         free(conn->lobjfuncs);
     693                 :         636 :         conn->lobjfuncs = NULL;
     694                 :             : 
     695                 :             :         /* Reset assorted other per-connection state */
     696                 :         636 :         conn->last_sqlstate[0] = '\0';
     697                 :         636 :         conn->pversion_negotiated = false;
     698                 :         636 :         conn->auth_req_received = false;
     699                 :         636 :         conn->client_finished_auth = false;
     700                 :         636 :         conn->password_needed = false;
     701                 :         636 :         conn->gssapi_used = false;
     702                 :         636 :         conn->write_failed = false;
     703                 :         636 :         free(conn->write_err_msg);
     704                 :         636 :         conn->write_err_msg = NULL;
     705                 :         636 :         conn->oauth_want_retry = false;
     706                 :             : 
     707                 :             :         /*
     708                 :             :          * Cancel connections need to retain their be_pid and be_cancel_key across
     709                 :             :          * PQcancelReset invocations, otherwise they would not have access to the
     710                 :             :          * secret token of the connection they are supposed to cancel.
     711                 :             :          */
     712         [ -  + ]:         636 :         if (!conn->cancelRequest)
     713                 :             :         {
     714                 :         636 :                 conn->be_pid = 0;
     715         [ +  + ]:         636 :                 if (conn->be_cancel_key != NULL)
     716                 :             :                 {
     717                 :         316 :                         free(conn->be_cancel_key);
     718                 :         316 :                         conn->be_cancel_key = NULL;
     719                 :         316 :                 }
     720                 :         636 :                 conn->be_cancel_key_len = 0;
     721                 :         636 :         }
     722                 :         636 : }
     723                 :             : 
     724                 :             : 
     725                 :             : /*
     726                 :             :  *              Connecting to a Database
     727                 :             :  *
     728                 :             :  * There are now six different ways a user of this API can connect to the
     729                 :             :  * database.  Two are not recommended for use in new code, because of their
     730                 :             :  * lack of extensibility with respect to the passing of options to the
     731                 :             :  * backend.  These are PQsetdb and PQsetdbLogin (the former now being a macro
     732                 :             :  * to the latter).
     733                 :             :  *
     734                 :             :  * If it is desired to connect in a synchronous (blocking) manner, use the
     735                 :             :  * function PQconnectdb or PQconnectdbParams. The former accepts a string of
     736                 :             :  * option = value pairs (or a URI) which must be parsed; the latter takes two
     737                 :             :  * NULL terminated arrays instead.
     738                 :             :  *
     739                 :             :  * To connect in an asynchronous (non-blocking) manner, use the functions
     740                 :             :  * PQconnectStart or PQconnectStartParams (which differ in the same way as
     741                 :             :  * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
     742                 :             :  *
     743                 :             :  * The non-exported functions pqConnectDBStart, pqConnectDBComplete are
     744                 :             :  * part of the connection procedure implementation.
     745                 :             :  */
     746                 :             : 
     747                 :             : /*
     748                 :             :  *              PQconnectdbParams
     749                 :             :  *
     750                 :             :  * establishes a connection to a postgres backend through the postmaster
     751                 :             :  * using connection information in two arrays.
     752                 :             :  *
     753                 :             :  * The keywords array is defined as
     754                 :             :  *
     755                 :             :  *         const char *params[] = {"option1", "option2", NULL}
     756                 :             :  *
     757                 :             :  * The values array is defined as
     758                 :             :  *
     759                 :             :  *         const char *values[] = {"value1", "value2", NULL}
     760                 :             :  *
     761                 :             :  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
     762                 :             :  * if a memory allocation failed.
     763                 :             :  * If the status field of the connection returned is CONNECTION_BAD,
     764                 :             :  * then some fields may be null'ed out instead of having valid values.
     765                 :             :  *
     766                 :             :  * You should call PQfinish (if conn is not NULL) regardless of whether this
     767                 :             :  * call succeeded.
     768                 :             :  */
     769                 :             : PGconn *
     770                 :         272 : PQconnectdbParams(const char *const *keywords,
     771                 :             :                                   const char *const *values,
     772                 :             :                                   int expand_dbname)
     773                 :             : {
     774                 :         272 :         PGconn     *conn = PQconnectStartParams(keywords, values, expand_dbname);
     775                 :             : 
     776   [ +  -  -  + ]:         272 :         if (conn && conn->status != CONNECTION_BAD)
     777                 :         272 :                 (void) pqConnectDBComplete(conn);
     778                 :             : 
     779                 :         544 :         return conn;
     780                 :         272 : }
     781                 :             : 
     782                 :             : /*
     783                 :             :  *              PQpingParams
     784                 :             :  *
     785                 :             :  * check server status, accepting parameters identical to PQconnectdbParams
     786                 :             :  */
     787                 :             : PGPing
     788                 :           2 : PQpingParams(const char *const *keywords,
     789                 :             :                          const char *const *values,
     790                 :             :                          int expand_dbname)
     791                 :             : {
     792                 :           2 :         PGconn     *conn = PQconnectStartParams(keywords, values, expand_dbname);
     793                 :           2 :         PGPing          ret;
     794                 :             : 
     795                 :           2 :         ret = internal_ping(conn);
     796                 :           2 :         PQfinish(conn);
     797                 :             : 
     798                 :           4 :         return ret;
     799                 :           2 : }
     800                 :             : 
     801                 :             : /*
     802                 :             :  *              PQconnectdb
     803                 :             :  *
     804                 :             :  * establishes a connection to a postgres backend through the postmaster
     805                 :             :  * using connection information in a string.
     806                 :             :  *
     807                 :             :  * The conninfo string is either a whitespace-separated list of
     808                 :             :  *
     809                 :             :  *         option = value
     810                 :             :  *
     811                 :             :  * definitions or a URI (refer to the documentation for details.) Value
     812                 :             :  * might be a single value containing no whitespaces or a single quoted
     813                 :             :  * string. If a single quote should appear anywhere in the value, it must be
     814                 :             :  * escaped with a backslash like \'
     815                 :             :  *
     816                 :             :  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
     817                 :             :  * if a memory allocation failed.
     818                 :             :  * If the status field of the connection returned is CONNECTION_BAD,
     819                 :             :  * then some fields may be null'ed out instead of having valid values.
     820                 :             :  *
     821                 :             :  * You should call PQfinish (if conn is not NULL) regardless of whether this
     822                 :             :  * call succeeded.
     823                 :             :  */
     824                 :             : PGconn *
     825                 :           0 : PQconnectdb(const char *conninfo)
     826                 :             : {
     827                 :           0 :         PGconn     *conn = PQconnectStart(conninfo);
     828                 :             : 
     829   [ #  #  #  # ]:           0 :         if (conn && conn->status != CONNECTION_BAD)
     830                 :           0 :                 (void) pqConnectDBComplete(conn);
     831                 :             : 
     832                 :           0 :         return conn;
     833                 :           0 : }
     834                 :             : 
     835                 :             : /*
     836                 :             :  *              PQping
     837                 :             :  *
     838                 :             :  * check server status, accepting parameters identical to PQconnectdb
     839                 :             :  */
     840                 :             : PGPing
     841                 :           0 : PQping(const char *conninfo)
     842                 :             : {
     843                 :           0 :         PGconn     *conn = PQconnectStart(conninfo);
     844                 :           0 :         PGPing          ret;
     845                 :             : 
     846                 :           0 :         ret = internal_ping(conn);
     847                 :           0 :         PQfinish(conn);
     848                 :             : 
     849                 :           0 :         return ret;
     850                 :           0 : }
     851                 :             : 
     852                 :             : /*
     853                 :             :  *              PQconnectStartParams
     854                 :             :  *
     855                 :             :  * Begins the establishment of a connection to a postgres backend through the
     856                 :             :  * postmaster using connection information in a struct.
     857                 :             :  *
     858                 :             :  * See comment for PQconnectdbParams for the definition of the string format.
     859                 :             :  *
     860                 :             :  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
     861                 :             :  * you should not attempt to proceed with this connection.  If the status
     862                 :             :  * field of the connection returned is CONNECTION_BAD, an error has
     863                 :             :  * occurred. In this case you should call PQfinish on the result, (perhaps
     864                 :             :  * inspecting the error message first).  Other fields of the structure may not
     865                 :             :  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
     866                 :             :  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
     867                 :             :  * this is necessary.
     868                 :             :  *
     869                 :             :  * See PQconnectPoll for more info.
     870                 :             :  */
     871                 :             : PGconn *
     872                 :         318 : PQconnectStartParams(const char *const *keywords,
     873                 :             :                                          const char *const *values,
     874                 :             :                                          int expand_dbname)
     875                 :             : {
     876                 :         318 :         PGconn     *conn;
     877                 :         318 :         PQconninfoOption *connOptions;
     878                 :             : 
     879                 :             :         /*
     880                 :             :          * Allocate memory for the conn structure.  Note that we also expect this
     881                 :             :          * to initialize conn->errorMessage to empty.  All subsequent steps during
     882                 :             :          * connection initialization will only append to that buffer.
     883                 :             :          */
     884                 :         318 :         conn = pqMakeEmptyPGconn();
     885         [ +  - ]:         318 :         if (conn == NULL)
     886                 :           0 :                 return NULL;
     887                 :             : 
     888                 :             :         /*
     889                 :             :          * Parse the conninfo arrays
     890                 :             :          */
     891                 :         636 :         connOptions = conninfo_array_parse(keywords, values,
     892                 :         318 :                                                                            &conn->errorMessage,
     893                 :         318 :                                                                            true, expand_dbname);
     894         [ +  - ]:         318 :         if (connOptions == NULL)
     895                 :             :         {
     896                 :           0 :                 conn->status = CONNECTION_BAD;
     897                 :             :                 /* errorMessage is already set */
     898                 :           0 :                 return conn;
     899                 :             :         }
     900                 :             : 
     901                 :             :         /*
     902                 :             :          * Move option values into conn structure
     903                 :             :          */
     904         [ +  - ]:         318 :         if (!fillPGconn(conn, connOptions))
     905                 :             :         {
     906                 :           0 :                 PQconninfoFree(connOptions);
     907                 :           0 :                 return conn;
     908                 :             :         }
     909                 :             : 
     910                 :             :         /*
     911                 :             :          * Free the option info - all is in conn now
     912                 :             :          */
     913                 :         318 :         PQconninfoFree(connOptions);
     914                 :             : 
     915                 :             :         /*
     916                 :             :          * Compute derived options
     917                 :             :          */
     918         [ +  - ]:         318 :         if (!pqConnectOptions2(conn))
     919                 :           0 :                 return conn;
     920                 :             : 
     921                 :             :         /*
     922                 :             :          * Connect to the database
     923                 :             :          */
     924         [ +  + ]:         318 :         if (!pqConnectDBStart(conn))
     925                 :             :         {
     926                 :             :                 /* Just in case we failed to set it in pqConnectDBStart */
     927                 :           2 :                 conn->status = CONNECTION_BAD;
     928                 :           2 :         }
     929                 :             : 
     930                 :         318 :         return conn;
     931                 :         318 : }
     932                 :             : 
     933                 :             : /*
     934                 :             :  *              PQconnectStart
     935                 :             :  *
     936                 :             :  * Begins the establishment of a connection to a postgres backend through the
     937                 :             :  * postmaster using connection information in a string.
     938                 :             :  *
     939                 :             :  * See comment for PQconnectdb for the definition of the string format.
     940                 :             :  *
     941                 :             :  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
     942                 :             :  * you should not attempt to proceed with this connection.  If the status
     943                 :             :  * field of the connection returned is CONNECTION_BAD, an error has
     944                 :             :  * occurred. In this case you should call PQfinish on the result, (perhaps
     945                 :             :  * inspecting the error message first).  Other fields of the structure may not
     946                 :             :  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
     947                 :             :  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
     948                 :             :  * this is necessary.
     949                 :             :  *
     950                 :             :  * See PQconnectPoll for more info.
     951                 :             :  */
     952                 :             : PGconn *
     953                 :           0 : PQconnectStart(const char *conninfo)
     954                 :             : {
     955                 :           0 :         PGconn     *conn;
     956                 :             : 
     957                 :             :         /*
     958                 :             :          * Allocate memory for the conn structure.  Note that we also expect this
     959                 :             :          * to initialize conn->errorMessage to empty.  All subsequent steps during
     960                 :             :          * connection initialization will only append to that buffer.
     961                 :             :          */
     962                 :           0 :         conn = pqMakeEmptyPGconn();
     963         [ #  # ]:           0 :         if (conn == NULL)
     964                 :           0 :                 return NULL;
     965                 :             : 
     966                 :             :         /*
     967                 :             :          * Parse the conninfo string
     968                 :             :          */
     969         [ #  # ]:           0 :         if (!connectOptions1(conn, conninfo))
     970                 :           0 :                 return conn;
     971                 :             : 
     972                 :             :         /*
     973                 :             :          * Compute derived options
     974                 :             :          */
     975         [ #  # ]:           0 :         if (!pqConnectOptions2(conn))
     976                 :           0 :                 return conn;
     977                 :             : 
     978                 :             :         /*
     979                 :             :          * Connect to the database
     980                 :             :          */
     981         [ #  # ]:           0 :         if (!pqConnectDBStart(conn))
     982                 :             :         {
     983                 :             :                 /* Just in case we failed to set it in pqConnectDBStart */
     984                 :           0 :                 conn->status = CONNECTION_BAD;
     985                 :           0 :         }
     986                 :             : 
     987                 :           0 :         return conn;
     988                 :           0 : }
     989                 :             : 
     990                 :             : /*
     991                 :             :  * Move option values into conn structure
     992                 :             :  *
     993                 :             :  * Don't put anything cute here --- intelligence should be in
     994                 :             :  * pqConnectOptions2 ...
     995                 :             :  *
     996                 :             :  * Returns true on success. On failure, returns false and sets error message.
     997                 :             :  */
     998                 :             : static bool
     999                 :         318 : fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
    1000                 :             : {
    1001                 :         318 :         const internalPQconninfoOption *option;
    1002                 :             : 
    1003         [ +  + ]:       16536 :         for (option = PQconninfoOptions; option->keyword; option++)
    1004                 :             :         {
    1005         [ -  + ]:       16218 :                 if (option->connofs >= 0)
    1006                 :             :                 {
    1007                 :       16218 :                         const char *tmp = conninfo_getval(connOptions, option->keyword);
    1008                 :             : 
    1009         [ +  + ]:       16218 :                         if (tmp)
    1010                 :             :                         {
    1011                 :        5809 :                                 char      **connmember = (char **) ((char *) conn + option->connofs);
    1012                 :             : 
    1013                 :        5809 :                                 free(*connmember);
    1014                 :        5809 :                                 *connmember = strdup(tmp);
    1015         [ +  - ]:        5809 :                                 if (*connmember == NULL)
    1016                 :             :                                 {
    1017                 :           0 :                                         libpq_append_conn_error(conn, "out of memory");
    1018                 :           0 :                                         return false;
    1019                 :             :                                 }
    1020         [ -  + ]:        5809 :                         }
    1021         [ -  + ]:       16218 :                 }
    1022                 :       16218 :         }
    1023                 :             : 
    1024                 :         318 :         return true;
    1025                 :         318 : }
    1026                 :             : 
    1027                 :             : /*
    1028                 :             :  * Copy over option values from srcConn to dstConn
    1029                 :             :  *
    1030                 :             :  * Don't put anything cute here --- intelligence should be in
    1031                 :             :  * pqConnectOptions2 ...
    1032                 :             :  *
    1033                 :             :  * Returns true on success. On failure, returns false and sets error message of
    1034                 :             :  * dstConn.
    1035                 :             :  */
    1036                 :             : bool
    1037                 :           0 : pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
    1038                 :             : {
    1039                 :           0 :         const internalPQconninfoOption *option;
    1040                 :             : 
    1041                 :             :         /* copy over connection options */
    1042         [ #  # ]:           0 :         for (option = PQconninfoOptions; option->keyword; option++)
    1043                 :             :         {
    1044         [ #  # ]:           0 :                 if (option->connofs >= 0)
    1045                 :             :                 {
    1046                 :           0 :                         const char **tmp = (const char **) ((char *) srcConn + option->connofs);
    1047                 :             : 
    1048         [ #  # ]:           0 :                         if (*tmp)
    1049                 :             :                         {
    1050                 :           0 :                                 char      **dstConnmember = (char **) ((char *) dstConn + option->connofs);
    1051                 :             : 
    1052         [ #  # ]:           0 :                                 if (*dstConnmember)
    1053                 :           0 :                                         free(*dstConnmember);
    1054                 :           0 :                                 *dstConnmember = strdup(*tmp);
    1055         [ #  # ]:           0 :                                 if (*dstConnmember == NULL)
    1056                 :             :                                 {
    1057                 :           0 :                                         libpq_append_conn_error(dstConn, "out of memory");
    1058                 :           0 :                                         return false;
    1059                 :             :                                 }
    1060         [ #  # ]:           0 :                         }
    1061         [ #  # ]:           0 :                 }
    1062                 :           0 :         }
    1063                 :           0 :         return true;
    1064                 :           0 : }
    1065                 :             : 
    1066                 :             : /*
    1067                 :             :  *              connectOptions1
    1068                 :             :  *
    1069                 :             :  * Internal subroutine to set up connection parameters given an already-
    1070                 :             :  * created PGconn and a conninfo string.  Derived settings should be
    1071                 :             :  * processed by calling pqConnectOptions2 next.  (We split them because
    1072                 :             :  * PQsetdbLogin overrides defaults in between.)
    1073                 :             :  *
    1074                 :             :  * Returns true if OK, false if trouble (in which case errorMessage is set
    1075                 :             :  * and so is conn->status).
    1076                 :             :  */
    1077                 :             : static bool
    1078                 :           0 : connectOptions1(PGconn *conn, const char *conninfo)
    1079                 :             : {
    1080                 :           0 :         PQconninfoOption *connOptions;
    1081                 :             : 
    1082                 :             :         /*
    1083                 :             :          * Parse the conninfo string
    1084                 :             :          */
    1085                 :           0 :         connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
    1086         [ #  # ]:           0 :         if (connOptions == NULL)
    1087                 :             :         {
    1088                 :           0 :                 conn->status = CONNECTION_BAD;
    1089                 :             :                 /* errorMessage is already set */
    1090                 :           0 :                 return false;
    1091                 :             :         }
    1092                 :             : 
    1093                 :             :         /*
    1094                 :             :          * Move option values into conn structure
    1095                 :             :          */
    1096         [ #  # ]:           0 :         if (!fillPGconn(conn, connOptions))
    1097                 :             :         {
    1098                 :           0 :                 conn->status = CONNECTION_BAD;
    1099                 :           0 :                 PQconninfoFree(connOptions);
    1100                 :           0 :                 return false;
    1101                 :             :         }
    1102                 :             : 
    1103                 :             :         /*
    1104                 :             :          * Free the option info - all is in conn now
    1105                 :             :          */
    1106                 :           0 :         PQconninfoFree(connOptions);
    1107                 :             : 
    1108                 :           0 :         return true;
    1109                 :           0 : }
    1110                 :             : 
    1111                 :             : /*
    1112                 :             :  * Count the number of elements in a simple comma-separated list.
    1113                 :             :  */
    1114                 :             : static int
    1115                 :         318 : count_comma_separated_elems(const char *input)
    1116                 :             : {
    1117                 :         318 :         int                     n;
    1118                 :             : 
    1119                 :         318 :         n = 1;
    1120         [ +  + ]:       19176 :         for (; *input != '\0'; input++)
    1121                 :             :         {
    1122         [ +  - ]:       18858 :                 if (*input == ',')
    1123                 :           0 :                         n++;
    1124                 :       18858 :         }
    1125                 :             : 
    1126                 :         636 :         return n;
    1127                 :         318 : }
    1128                 :             : 
    1129                 :             : /*
    1130                 :             :  * Parse a simple comma-separated list.
    1131                 :             :  *
    1132                 :             :  * On each call, returns a malloc'd copy of the next element, and sets *more
    1133                 :             :  * to indicate whether there are any more elements in the list after this,
    1134                 :             :  * and updates *startptr to point to the next element, if any.
    1135                 :             :  *
    1136                 :             :  * On out of memory, returns NULL.
    1137                 :             :  */
    1138                 :             : static char *
    1139                 :         636 : parse_comma_separated_list(char **startptr, bool *more)
    1140                 :             : {
    1141                 :         636 :         char       *p;
    1142                 :         636 :         char       *s = *startptr;
    1143                 :         636 :         char       *e;
    1144                 :         636 :         size_t          len;
    1145                 :             : 
    1146                 :             :         /*
    1147                 :             :          * Search for the end of the current element; a comma or end-of-string
    1148                 :             :          * acts as a terminator.
    1149                 :             :          */
    1150                 :         636 :         e = s;
    1151   [ +  +  +  + ]:       21081 :         while (*e != '\0' && *e != ',')
    1152                 :       20445 :                 ++e;
    1153                 :         636 :         *more = (*e == ',');
    1154                 :             : 
    1155                 :         636 :         len = e - s;
    1156                 :         636 :         p = (char *) malloc(sizeof(char) * (len + 1));
    1157         [ -  + ]:         636 :         if (p)
    1158                 :             :         {
    1159                 :         636 :                 memcpy(p, s, len);
    1160                 :         636 :                 p[len] = '\0';
    1161                 :         636 :         }
    1162                 :         636 :         *startptr = e + 1;
    1163                 :             : 
    1164                 :        1272 :         return p;
    1165                 :         636 : }
    1166                 :             : 
    1167                 :             : /*
    1168                 :             :  * Initializes the prng_state field of the connection. We want something
    1169                 :             :  * unpredictable, so if possible, use high-quality random bits for the
    1170                 :             :  * seed. Otherwise, fall back to a seed based on the connection address,
    1171                 :             :  * timestamp and PID.
    1172                 :             :  */
    1173                 :             : static void
    1174                 :           0 : libpq_prng_init(PGconn *conn)
    1175                 :             : {
    1176                 :           0 :         uint64          rseed;
    1177                 :           0 :         struct timeval tval = {0};
    1178                 :             : 
    1179   [ #  #  #  # ]:           0 :         if (pg_prng_strong_seed(&conn->prng_state))
    1180                 :           0 :                 return;
    1181                 :             : 
    1182                 :           0 :         gettimeofday(&tval, NULL);
    1183                 :             : 
    1184                 :           0 :         rseed = ((uintptr_t) conn) ^
    1185                 :           0 :                 ((uint64) getpid()) ^
    1186                 :           0 :                 ((uint64) tval.tv_usec) ^
    1187                 :           0 :                 ((uint64) tval.tv_sec);
    1188                 :             : 
    1189                 :           0 :         pg_prng_seed(&conn->prng_state, rseed);
    1190         [ #  # ]:           0 : }
    1191                 :             : 
    1192                 :             : /*
    1193                 :             :  * Fills the connection's allowed_sasl_mechs list with all supported SASL
    1194                 :             :  * mechanisms.
    1195                 :             :  */
    1196                 :             : static inline void
    1197                 :           0 : fill_allowed_sasl_mechs(PGconn *conn)
    1198                 :             : {
    1199                 :             :         /*---
    1200                 :             :          * We only support two mechanisms at the moment, so rather than deal with a
    1201                 :             :          * linked list, conn->allowed_sasl_mechs is an array of static length. We
    1202                 :             :          * rely on the compile-time assertion here to keep us honest.
    1203                 :             :          *
    1204                 :             :          * To add a new mechanism to require_auth,
    1205                 :             :          * - add it to supported_sasl_mechs,
    1206                 :             :          * - update the length of conn->allowed_sasl_mechs,
    1207                 :             :          * - handle the new mechanism name in the require_auth portion of
    1208                 :             :          *   pqConnectOptions2(), below.
    1209                 :             :          */
    1210                 :             :         StaticAssertDecl(lengthof(conn->allowed_sasl_mechs) == SASL_MECHANISM_COUNT,
    1211                 :             :                                          "conn->allowed_sasl_mechs[] is not sufficiently large for holding all supported SASL mechanisms");
    1212                 :             : 
    1213         [ #  # ]:           0 :         for (int i = 0; i < SASL_MECHANISM_COUNT; i++)
    1214                 :           0 :                 conn->allowed_sasl_mechs[i] = supported_sasl_mechs[i];
    1215                 :           0 : }
    1216                 :             : 
    1217                 :             : /*
    1218                 :             :  * Clears the connection's allowed_sasl_mechs list.
    1219                 :             :  */
    1220                 :             : static inline void
    1221                 :           0 : clear_allowed_sasl_mechs(PGconn *conn)
    1222                 :             : {
    1223         [ #  # ]:           0 :         for (int i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
    1224                 :           0 :                 conn->allowed_sasl_mechs[i] = NULL;
    1225                 :           0 : }
    1226                 :             : 
    1227                 :             : /*
    1228                 :             :  * Helper routine that searches the static allowed_sasl_mechs list for a
    1229                 :             :  * specific mechanism.
    1230                 :             :  */
    1231                 :             : static inline int
    1232                 :           0 : index_of_allowed_sasl_mech(PGconn *conn, const pg_fe_sasl_mech *mech)
    1233                 :             : {
    1234   [ #  #  #  #  :           0 :         for (int i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
                      # ]
    1235                 :             :         {
    1236         [ #  # ]:           0 :                 if (conn->allowed_sasl_mechs[i] == mech)
    1237                 :           0 :                         return i;
    1238                 :           0 :         }
    1239                 :             : 
    1240                 :           0 :         return -1;
    1241                 :           0 : }
    1242                 :             : 
    1243                 :             : /*
    1244                 :             :  *              pqConnectOptions2
    1245                 :             :  *
    1246                 :             :  * Compute derived connection options after absorbing all user-supplied info.
    1247                 :             :  *
    1248                 :             :  * Returns true if OK, false if trouble (in which case errorMessage is set
    1249                 :             :  * and so is conn->status).
    1250                 :             :  */
    1251                 :             : bool
    1252                 :         318 : pqConnectOptions2(PGconn *conn)
    1253                 :             : {
    1254                 :         318 :         int                     i;
    1255                 :             : 
    1256                 :             :         /*
    1257                 :             :          * Allocate memory for details about each host to which we might possibly
    1258                 :             :          * try to connect.  For that, count the number of elements in the hostaddr
    1259                 :             :          * or host options.  If neither is given, assume one host.
    1260                 :             :          */
    1261                 :         318 :         conn->whichhost = 0;
    1262   [ -  +  #  # ]:         318 :         if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
    1263                 :           0 :                 conn->nconnhost = count_comma_separated_elems(conn->pghostaddr);
    1264   [ +  -  -  + ]:         318 :         else if (conn->pghost && conn->pghost[0] != '\0')
    1265                 :         318 :                 conn->nconnhost = count_comma_separated_elems(conn->pghost);
    1266                 :             :         else
    1267                 :           0 :                 conn->nconnhost = 1;
    1268                 :         318 :         conn->connhost = (pg_conn_host *)
    1269                 :         318 :                 calloc(conn->nconnhost, sizeof(pg_conn_host));
    1270         [ +  - ]:         318 :         if (conn->connhost == NULL)
    1271                 :           0 :                 goto oom_error;
    1272                 :             : 
    1273                 :             :         /*
    1274                 :             :          * We now have one pg_conn_host structure per possible host.  Fill in the
    1275                 :             :          * host and hostaddr fields for each, by splitting the parameter strings.
    1276                 :             :          */
    1277   [ -  +  #  # ]:         318 :         if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
    1278                 :             :         {
    1279                 :           0 :                 char       *s = conn->pghostaddr;
    1280                 :           0 :                 bool            more = true;
    1281                 :             : 
    1282   [ #  #  #  # ]:           0 :                 for (i = 0; i < conn->nconnhost && more; i++)
    1283                 :             :                 {
    1284                 :           0 :                         conn->connhost[i].hostaddr = parse_comma_separated_list(&s, &more);
    1285         [ #  # ]:           0 :                         if (conn->connhost[i].hostaddr == NULL)
    1286                 :           0 :                                 goto oom_error;
    1287                 :           0 :                 }
    1288                 :             : 
    1289                 :             :                 /*
    1290                 :             :                  * If hostaddr was given, the array was allocated according to the
    1291                 :             :                  * number of elements in the hostaddr list, so it really should be the
    1292                 :             :                  * right size.
    1293                 :             :                  */
    1294         [ #  # ]:           0 :                 Assert(!more);
    1295         [ #  # ]:           0 :                 Assert(i == conn->nconnhost);
    1296         [ #  # ]:           0 :         }
    1297                 :             : 
    1298   [ +  -  -  + ]:         318 :         if (conn->pghost != NULL && conn->pghost[0] != '\0')
    1299                 :             :         {
    1300                 :         318 :                 char       *s = conn->pghost;
    1301                 :         318 :                 bool            more = true;
    1302                 :             : 
    1303   [ +  +  +  + ]:         636 :                 for (i = 0; i < conn->nconnhost && more; i++)
    1304                 :             :                 {
    1305                 :         318 :                         conn->connhost[i].host = parse_comma_separated_list(&s, &more);
    1306         [ -  + ]:         318 :                         if (conn->connhost[i].host == NULL)
    1307                 :           0 :                                 goto oom_error;
    1308                 :         318 :                 }
    1309                 :             : 
    1310                 :             :                 /* Check for wrong number of host items. */
    1311   [ +  -  -  + ]:         318 :                 if (more || i != conn->nconnhost)
    1312                 :             :                 {
    1313                 :           0 :                         conn->status = CONNECTION_BAD;
    1314                 :           0 :                         libpq_append_conn_error(conn, "could not match %d host names to %d hostaddr values",
    1315                 :           0 :                                                                         count_comma_separated_elems(conn->pghost), conn->nconnhost);
    1316                 :           0 :                         return false;
    1317                 :             :                 }
    1318         [ -  + ]:         318 :         }
    1319                 :             : 
    1320                 :             :         /*
    1321                 :             :          * Now, for each host slot, identify the type of address spec, and fill in
    1322                 :             :          * the default address if nothing was given.
    1323                 :             :          */
    1324         [ +  + ]:         636 :         for (i = 0; i < conn->nconnhost; i++)
    1325                 :             :         {
    1326                 :         318 :                 pg_conn_host *ch = &conn->connhost[i];
    1327                 :             : 
    1328   [ -  +  #  # ]:         318 :                 if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
    1329                 :           0 :                         ch->type = CHT_HOST_ADDRESS;
    1330   [ +  -  -  + ]:         318 :                 else if (ch->host != NULL && ch->host[0] != '\0')
    1331                 :             :                 {
    1332                 :         318 :                         ch->type = CHT_HOST_NAME;
    1333         [ -  + ]:         318 :                         if (is_unixsock_path(ch->host))
    1334                 :         318 :                                 ch->type = CHT_UNIX_SOCKET;
    1335                 :         318 :                 }
    1336                 :             :                 else
    1337                 :             :                 {
    1338                 :           0 :                         free(ch->host);
    1339                 :             : 
    1340                 :             :                         /*
    1341                 :             :                          * This bit selects the default host location.  If you change
    1342                 :             :                          * this, see also pg_regress.
    1343                 :             :                          */
    1344                 :             :                         if (DEFAULT_PGSOCKET_DIR[0])
    1345                 :             :                         {
    1346                 :           0 :                                 ch->host = strdup(DEFAULT_PGSOCKET_DIR);
    1347                 :           0 :                                 ch->type = CHT_UNIX_SOCKET;
    1348                 :             :                         }
    1349                 :             :                         else
    1350                 :             :                         {
    1351                 :             :                                 ch->host = strdup(DefaultHost);
    1352                 :             :                                 ch->type = CHT_HOST_NAME;
    1353                 :             :                         }
    1354         [ #  # ]:           0 :                         if (ch->host == NULL)
    1355                 :           0 :                                 goto oom_error;
    1356                 :             :                 }
    1357      [ -  -  + ]:         318 :         }
    1358                 :             : 
    1359                 :             :         /*
    1360                 :             :          * Next, work out the port number corresponding to each host name.
    1361                 :             :          *
    1362                 :             :          * Note: unlike the above for host names, this could leave the port fields
    1363                 :             :          * as null or empty strings.  We will substitute DEF_PGPORT whenever we
    1364                 :             :          * read such a port field.
    1365                 :             :          */
    1366   [ +  -  -  + ]:         318 :         if (conn->pgport != NULL && conn->pgport[0] != '\0')
    1367                 :             :         {
    1368                 :         318 :                 char       *s = conn->pgport;
    1369                 :         318 :                 bool            more = true;
    1370                 :             : 
    1371   [ +  +  +  + ]:         636 :                 for (i = 0; i < conn->nconnhost && more; i++)
    1372                 :             :                 {
    1373                 :         318 :                         conn->connhost[i].port = parse_comma_separated_list(&s, &more);
    1374         [ -  + ]:         318 :                         if (conn->connhost[i].port == NULL)
    1375                 :           0 :                                 goto oom_error;
    1376                 :         318 :                 }
    1377                 :             : 
    1378                 :             :                 /*
    1379                 :             :                  * If exactly one port was given, use it for every host.  Otherwise,
    1380                 :             :                  * there must be exactly as many ports as there were hosts.
    1381                 :             :                  */
    1382   [ +  -  -  + ]:         318 :                 if (i == 1 && !more)
    1383                 :             :                 {
    1384         [ -  + ]:         318 :                         for (i = 1; i < conn->nconnhost; i++)
    1385                 :             :                         {
    1386                 :           0 :                                 conn->connhost[i].port = strdup(conn->connhost[0].port);
    1387         [ #  # ]:           0 :                                 if (conn->connhost[i].port == NULL)
    1388                 :           0 :                                         goto oom_error;
    1389                 :           0 :                         }
    1390                 :         318 :                 }
    1391   [ #  #  #  # ]:           0 :                 else if (more || i != conn->nconnhost)
    1392                 :             :                 {
    1393                 :           0 :                         conn->status = CONNECTION_BAD;
    1394                 :           0 :                         libpq_append_conn_error(conn, "could not match %d port numbers to %d hosts",
    1395                 :           0 :                                                                         count_comma_separated_elems(conn->pgport), conn->nconnhost);
    1396                 :           0 :                         return false;
    1397                 :             :                 }
    1398         [ +  - ]:         318 :         }
    1399                 :             : 
    1400                 :             :         /*
    1401                 :             :          * If user name was not given, fetch it.  (Most likely, the fetch will
    1402                 :             :          * fail, since the only way we get here is if pg_fe_getauthname() failed
    1403                 :             :          * during conninfo_add_defaults().  But now we want an error message.)
    1404                 :             :          */
    1405   [ +  -  +  - ]:         318 :         if (conn->pguser == NULL || conn->pguser[0] == '\0')
    1406                 :             :         {
    1407                 :           0 :                 free(conn->pguser);
    1408                 :           0 :                 conn->pguser = pg_fe_getauthname(&conn->errorMessage);
    1409         [ #  # ]:           0 :                 if (!conn->pguser)
    1410                 :             :                 {
    1411                 :           0 :                         conn->status = CONNECTION_BAD;
    1412                 :           0 :                         return false;
    1413                 :             :                 }
    1414                 :           0 :         }
    1415                 :             : 
    1416                 :             :         /*
    1417                 :             :          * If database name was not given, default it to equal user name
    1418                 :             :          */
    1419   [ +  -  +  - ]:         318 :         if (conn->dbName == NULL || conn->dbName[0] == '\0')
    1420                 :             :         {
    1421                 :           0 :                 free(conn->dbName);
    1422                 :           0 :                 conn->dbName = strdup(conn->pguser);
    1423         [ #  # ]:           0 :                 if (!conn->dbName)
    1424                 :           0 :                         goto oom_error;
    1425                 :           0 :         }
    1426                 :             : 
    1427                 :             :         /*
    1428                 :             :          * If password was not given, try to look it up in password file.  Note
    1429                 :             :          * that the result might be different for each host/port pair.
    1430                 :             :          */
    1431   [ -  +  #  # ]:         318 :         if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
    1432                 :             :         {
    1433                 :             :                 /* If password file wasn't specified, use ~/PGPASSFILE */
    1434   [ +  +  +  - ]:         318 :                 if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
    1435                 :             :                 {
    1436                 :         275 :                         char            homedir[MAXPGPATH];
    1437                 :             : 
    1438         [ -  + ]:         275 :                         if (pqGetHomeDirectory(homedir, sizeof(homedir)))
    1439                 :             :                         {
    1440                 :         275 :                                 free(conn->pgpassfile);
    1441                 :         275 :                                 conn->pgpassfile = malloc(MAXPGPATH);
    1442         [ +  - ]:         275 :                                 if (!conn->pgpassfile)
    1443                 :           0 :                                         goto oom_error;
    1444                 :         550 :                                 snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
    1445                 :         275 :                                                  homedir, PGPASSFILE);
    1446                 :         275 :                         }
    1447         [ -  + ]:         275 :                 }
    1448                 :             : 
    1449   [ +  -  -  + ]:         318 :                 if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
    1450                 :             :                 {
    1451         [ +  + ]:         636 :                         for (i = 0; i < conn->nconnhost; i++)
    1452                 :             :                         {
    1453                 :             :                                 /*
    1454                 :             :                                  * Try to get a password for this host from file.  We use host
    1455                 :             :                                  * for the hostname search key if given, else hostaddr (at
    1456                 :             :                                  * least one of them is guaranteed nonempty by now).
    1457                 :             :                                  */
    1458                 :         318 :                                 const char *pwhost = conn->connhost[i].host;
    1459                 :         318 :                                 const char *password_errmsg = NULL;
    1460                 :             : 
    1461   [ +  -  +  - ]:         318 :                                 if (pwhost == NULL || pwhost[0] == '\0')
    1462                 :           0 :                                         pwhost = conn->connhost[i].hostaddr;
    1463                 :             : 
    1464                 :         318 :                                 conn->connhost[i].password =
    1465                 :         636 :                                         passwordFromFile(pwhost,
    1466                 :         318 :                                                                          conn->connhost[i].port,
    1467                 :         318 :                                                                          conn->dbName,
    1468                 :         318 :                                                                          conn->pguser,
    1469                 :         318 :                                                                          conn->pgpassfile,
    1470                 :             :                                                                          &password_errmsg);
    1471                 :             : 
    1472         [ -  + ]:         318 :                                 if (password_errmsg != NULL)
    1473                 :             :                                 {
    1474                 :           0 :                                         conn->status = CONNECTION_BAD;
    1475                 :           0 :                                         libpq_append_conn_error(conn, "%s", password_errmsg);
    1476                 :           0 :                                         return false;
    1477                 :             :                                 }
    1478         [ -  + ]:         318 :                         }
    1479                 :         318 :                 }
    1480                 :         318 :         }
    1481                 :             : 
    1482                 :             :         /*
    1483                 :             :          * parse and validate require_auth option
    1484                 :             :          */
    1485   [ -  +  #  # ]:         318 :         if (conn->require_auth && conn->require_auth[0])
    1486                 :             :         {
    1487                 :           0 :                 char       *s = conn->require_auth;
    1488                 :           0 :                 bool            first,
    1489                 :             :                                         more;
    1490                 :           0 :                 bool            negated = false;
    1491                 :             : 
    1492                 :             :                 /*
    1493                 :             :                  * By default, start from an empty set of allowed methods and
    1494                 :             :                  * mechanisms, and add to it.
    1495                 :             :                  */
    1496                 :           0 :                 conn->auth_required = true;
    1497                 :           0 :                 conn->allowed_auth_methods = 0;
    1498                 :           0 :                 clear_allowed_sasl_mechs(conn);
    1499                 :             : 
    1500         [ #  # ]:           0 :                 for (first = true, more = true; more; first = false)
    1501                 :             :                 {
    1502                 :           0 :                         char       *method,
    1503                 :             :                                            *part;
    1504                 :           0 :                         uint32          bits = 0;
    1505                 :           0 :                         const pg_fe_sasl_mech *mech = NULL;
    1506                 :             : 
    1507                 :           0 :                         part = parse_comma_separated_list(&s, &more);
    1508         [ #  # ]:           0 :                         if (part == NULL)
    1509                 :           0 :                                 goto oom_error;
    1510                 :             : 
    1511                 :             :                         /*
    1512                 :             :                          * Check for negation, e.g. '!password'. If one element is
    1513                 :             :                          * negated, they all have to be.
    1514                 :             :                          */
    1515                 :           0 :                         method = part;
    1516         [ #  # ]:           0 :                         if (*method == '!')
    1517                 :             :                         {
    1518         [ #  # ]:           0 :                                 if (first)
    1519                 :             :                                 {
    1520                 :             :                                         /*
    1521                 :             :                                          * Switch to a permissive set of allowed methods and
    1522                 :             :                                          * mechanisms, and subtract from it.
    1523                 :             :                                          */
    1524                 :           0 :                                         conn->auth_required = false;
    1525                 :           0 :                                         conn->allowed_auth_methods = -1;
    1526                 :           0 :                                         fill_allowed_sasl_mechs(conn);
    1527                 :           0 :                                 }
    1528         [ #  # ]:           0 :                                 else if (!negated)
    1529                 :             :                                 {
    1530                 :           0 :                                         conn->status = CONNECTION_BAD;
    1531                 :           0 :                                         libpq_append_conn_error(conn, "negative require_auth method \"%s\" cannot be mixed with non-negative methods",
    1532                 :           0 :                                                                                         method);
    1533                 :             : 
    1534                 :           0 :                                         free(part);
    1535                 :           0 :                                         return false;
    1536                 :             :                                 }
    1537                 :             : 
    1538                 :           0 :                                 negated = true;
    1539                 :           0 :                                 method++;
    1540                 :           0 :                         }
    1541         [ #  # ]:           0 :                         else if (negated)
    1542                 :             :                         {
    1543                 :           0 :                                 conn->status = CONNECTION_BAD;
    1544                 :           0 :                                 libpq_append_conn_error(conn, "require_auth method \"%s\" cannot be mixed with negative methods",
    1545                 :           0 :                                                                                 method);
    1546                 :             : 
    1547                 :           0 :                                 free(part);
    1548                 :           0 :                                 return false;
    1549                 :             :                         }
    1550                 :             : 
    1551                 :             :                         /*
    1552                 :             :                          * First group: methods that can be handled solely with the
    1553                 :             :                          * authentication request codes.
    1554                 :             :                          */
    1555         [ #  # ]:           0 :                         if (strcmp(method, "password") == 0)
    1556                 :             :                         {
    1557                 :           0 :                                 bits = (1 << AUTH_REQ_PASSWORD);
    1558                 :           0 :                         }
    1559         [ #  # ]:           0 :                         else if (strcmp(method, "md5") == 0)
    1560                 :             :                         {
    1561                 :           0 :                                 bits = (1 << AUTH_REQ_MD5);
    1562                 :           0 :                         }
    1563         [ #  # ]:           0 :                         else if (strcmp(method, "gss") == 0)
    1564                 :             :                         {
    1565                 :           0 :                                 bits = (1 << AUTH_REQ_GSS);
    1566                 :           0 :                                 bits |= (1 << AUTH_REQ_GSS_CONT);
    1567                 :           0 :                         }
    1568         [ #  # ]:           0 :                         else if (strcmp(method, "sspi") == 0)
    1569                 :             :                         {
    1570                 :           0 :                                 bits = (1 << AUTH_REQ_SSPI);
    1571                 :           0 :                                 bits |= (1 << AUTH_REQ_GSS_CONT);
    1572                 :           0 :                         }
    1573                 :             : 
    1574                 :             :                         /*
    1575                 :             :                          * Next group: SASL mechanisms. All of these use the same request
    1576                 :             :                          * codes, so the list of allowed mechanisms is tracked separately.
    1577                 :             :                          *
    1578                 :             :                          * supported_sasl_mechs must contain all mechanisms handled here.
    1579                 :             :                          */
    1580         [ #  # ]:           0 :                         else if (strcmp(method, "scram-sha-256") == 0)
    1581                 :             :                         {
    1582                 :           0 :                                 mech = &pg_scram_mech;
    1583                 :           0 :                         }
    1584         [ #  # ]:           0 :                         else if (strcmp(method, "oauth") == 0)
    1585                 :             :                         {
    1586                 :           0 :                                 mech = &pg_oauth_mech;
    1587                 :           0 :                         }
    1588                 :             : 
    1589                 :             :                         /*
    1590                 :             :                          * Final group: meta-options.
    1591                 :             :                          */
    1592         [ #  # ]:           0 :                         else if (strcmp(method, "none") == 0)
    1593                 :             :                         {
    1594                 :             :                                 /*
    1595                 :             :                                  * Special case: let the user explicitly allow (or disallow)
    1596                 :             :                                  * connections where the server does not send an explicit
    1597                 :             :                                  * authentication challenge, such as "trust" and "cert" auth.
    1598                 :             :                                  */
    1599         [ #  # ]:           0 :                                 if (negated)    /* "!none" */
    1600                 :             :                                 {
    1601         [ #  # ]:           0 :                                         if (conn->auth_required)
    1602                 :           0 :                                                 goto duplicate;
    1603                 :             : 
    1604                 :           0 :                                         conn->auth_required = true;
    1605                 :           0 :                                 }
    1606                 :             :                                 else                    /* "none" */
    1607                 :             :                                 {
    1608         [ #  # ]:           0 :                                         if (!conn->auth_required)
    1609                 :           0 :                                                 goto duplicate;
    1610                 :             : 
    1611                 :           0 :                                         conn->auth_required = false;
    1612                 :             :                                 }
    1613                 :             : 
    1614                 :           0 :                                 free(part);
    1615                 :           0 :                                 continue;               /* avoid the bitmask manipulation below */
    1616                 :             :                         }
    1617                 :             :                         else
    1618                 :             :                         {
    1619                 :           0 :                                 conn->status = CONNECTION_BAD;
    1620                 :           0 :                                 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    1621                 :           0 :                                                                                 "require_auth", method);
    1622                 :             : 
    1623                 :           0 :                                 free(part);
    1624                 :           0 :                                 return false;
    1625                 :             :                         }
    1626                 :             : 
    1627         [ #  # ]:           0 :                         if (mech)
    1628                 :             :                         {
    1629                 :             :                                 /*
    1630                 :             :                                  * Update the mechanism set only. The method bitmask will be
    1631                 :             :                                  * updated for SASL further down.
    1632                 :             :                                  */
    1633         [ #  # ]:           0 :                                 Assert(!bits);
    1634                 :             : 
    1635         [ #  # ]:           0 :                                 if (negated)
    1636                 :             :                                 {
    1637                 :             :                                         /* Remove the existing mechanism from the list. */
    1638                 :           0 :                                         i = index_of_allowed_sasl_mech(conn, mech);
    1639         [ #  # ]:           0 :                                         if (i < 0)
    1640                 :           0 :                                                 goto duplicate;
    1641                 :             : 
    1642                 :           0 :                                         conn->allowed_sasl_mechs[i] = NULL;
    1643                 :           0 :                                 }
    1644                 :             :                                 else
    1645                 :             :                                 {
    1646                 :             :                                         /*
    1647                 :             :                                          * Find a space to put the new mechanism (after making
    1648                 :             :                                          * sure it's not already there).
    1649                 :             :                                          */
    1650                 :           0 :                                         i = index_of_allowed_sasl_mech(conn, mech);
    1651         [ #  # ]:           0 :                                         if (i >= 0)
    1652                 :           0 :                                                 goto duplicate;
    1653                 :             : 
    1654                 :           0 :                                         i = index_of_allowed_sasl_mech(conn, NULL);
    1655         [ #  # ]:           0 :                                         if (i < 0)
    1656                 :             :                                         {
    1657                 :             :                                                 /* Should not happen; the pointer list is corrupted. */
    1658                 :           0 :                                                 Assert(false);
    1659                 :             : 
    1660                 :             :                                                 conn->status = CONNECTION_BAD;
    1661                 :             :                                                 libpq_append_conn_error(conn,
    1662                 :             :                                                                                                 "internal error: no space in allowed_sasl_mechs");
    1663                 :             :                                                 free(part);
    1664                 :             :                                                 return false;
    1665                 :             :                                         }
    1666                 :             : 
    1667                 :           0 :                                         conn->allowed_sasl_mechs[i] = mech;
    1668                 :             :                                 }
    1669                 :           0 :                         }
    1670                 :             :                         else
    1671                 :             :                         {
    1672                 :             :                                 /* Update the method bitmask. */
    1673         [ #  # ]:           0 :                                 Assert(bits);
    1674                 :             : 
    1675         [ #  # ]:           0 :                                 if (negated)
    1676                 :             :                                 {
    1677         [ #  # ]:           0 :                                         if ((conn->allowed_auth_methods & bits) == 0)
    1678                 :           0 :                                                 goto duplicate;
    1679                 :             : 
    1680                 :           0 :                                         conn->allowed_auth_methods &= ~bits;
    1681                 :           0 :                                 }
    1682                 :             :                                 else
    1683                 :             :                                 {
    1684         [ #  # ]:           0 :                                         if ((conn->allowed_auth_methods & bits) == bits)
    1685                 :           0 :                                                 goto duplicate;
    1686                 :             : 
    1687                 :           0 :                                         conn->allowed_auth_methods |= bits;
    1688                 :             :                                 }
    1689                 :             :                         }
    1690                 :             : 
    1691                 :           0 :                         free(part);
    1692                 :           0 :                         continue;
    1693                 :             : 
    1694                 :             :         duplicate:
    1695                 :             : 
    1696                 :             :                         /*
    1697                 :             :                          * A duplicated method probably indicates a typo in a setting
    1698                 :             :                          * where typos are extremely risky.
    1699                 :             :                          */
    1700                 :           0 :                         conn->status = CONNECTION_BAD;
    1701                 :           0 :                         libpq_append_conn_error(conn, "require_auth method \"%s\" is specified more than once",
    1702                 :           0 :                                                                         part);
    1703                 :             : 
    1704                 :           0 :                         free(part);
    1705                 :           0 :                         return false;
    1706         [ #  # ]:           0 :                 }
    1707                 :             : 
    1708                 :             :                 /*
    1709                 :             :                  * Finally, allow SASL authentication requests if (and only if) we've
    1710                 :             :                  * allowed any mechanisms.
    1711                 :             :                  */
    1712                 :             :                 {
    1713                 :           0 :                         bool            allowed = false;
    1714                 :           0 :                         const uint32 sasl_bits =
    1715                 :             :                                 (1 << AUTH_REQ_SASL)
    1716                 :             :                                 | (1 << AUTH_REQ_SASL_CONT)
    1717                 :             :                                 | (1 << AUTH_REQ_SASL_FIN);
    1718                 :             : 
    1719         [ #  # ]:           0 :                         for (i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
    1720                 :             :                         {
    1721         [ #  # ]:           0 :                                 if (conn->allowed_sasl_mechs[i])
    1722                 :             :                                 {
    1723                 :           0 :                                         allowed = true;
    1724                 :           0 :                                         break;
    1725                 :             :                                 }
    1726                 :           0 :                         }
    1727                 :             : 
    1728                 :             :                         /*
    1729                 :             :                          * For the standard case, add the SASL bits to the (default-empty)
    1730                 :             :                          * set if needed. For the negated case, remove them.
    1731                 :             :                          */
    1732   [ #  #  #  # ]:           0 :                         if (!negated && allowed)
    1733                 :           0 :                                 conn->allowed_auth_methods |= sasl_bits;
    1734   [ #  #  #  # ]:           0 :                         else if (negated && !allowed)
    1735                 :           0 :                                 conn->allowed_auth_methods &= ~sasl_bits;
    1736                 :           0 :                 }
    1737         [ #  # ]:           0 :         }
    1738                 :             : 
    1739                 :             :         /*
    1740                 :             :          * validate channel_binding option
    1741                 :             :          */
    1742         [ +  - ]:         318 :         if (conn->channel_binding)
    1743                 :             :         {
    1744                 :         318 :                 if (strcmp(conn->channel_binding, "disable") != 0
    1745         [ +  - ]:         318 :                         && strcmp(conn->channel_binding, "prefer") != 0
    1746   [ -  +  #  # ]:         318 :                         && strcmp(conn->channel_binding, "require") != 0)
    1747                 :             :                 {
    1748                 :           0 :                         conn->status = CONNECTION_BAD;
    1749                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    1750                 :           0 :                                                                         "channel_binding", conn->channel_binding);
    1751                 :           0 :                         return false;
    1752                 :             :                 }
    1753                 :         318 :         }
    1754                 :             :         else
    1755                 :             :         {
    1756                 :           0 :                 conn->channel_binding = strdup(DefaultChannelBinding);
    1757         [ #  # ]:           0 :                 if (!conn->channel_binding)
    1758                 :           0 :                         goto oom_error;
    1759                 :             :         }
    1760                 :             : 
    1761                 :             : #ifndef USE_SSL
    1762                 :             : 
    1763                 :             :         /*
    1764                 :             :          * sslrootcert=system is not supported. Since setting this changes the
    1765                 :             :          * default sslmode, check this _before_ we validate sslmode, to avoid
    1766                 :             :          * confusing the user with errors for an option they may not have set.
    1767                 :             :          */
    1768                 :             :         if (conn->sslrootcert
    1769                 :             :                 && strcmp(conn->sslrootcert, "system") == 0)
    1770                 :             :         {
    1771                 :             :                 conn->status = CONNECTION_BAD;
    1772                 :             :                 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
    1773                 :             :                                                                 "sslrootcert", conn->sslrootcert);
    1774                 :             :                 return false;
    1775                 :             :         }
    1776                 :             : #endif
    1777                 :             : 
    1778                 :             :         /*
    1779                 :             :          * validate sslmode option
    1780                 :             :          */
    1781         [ +  - ]:         318 :         if (conn->sslmode)
    1782                 :             :         {
    1783                 :         318 :                 if (strcmp(conn->sslmode, "disable") != 0
    1784         [ +  - ]:         318 :                         && strcmp(conn->sslmode, "allow") != 0
    1785         [ +  - ]:         318 :                         && strcmp(conn->sslmode, "prefer") != 0
    1786         [ -  + ]:         318 :                         && strcmp(conn->sslmode, "require") != 0
    1787         [ #  # ]:           0 :                         && strcmp(conn->sslmode, "verify-ca") != 0
    1788   [ #  #  #  # ]:           0 :                         && strcmp(conn->sslmode, "verify-full") != 0)
    1789                 :             :                 {
    1790                 :           0 :                         conn->status = CONNECTION_BAD;
    1791                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    1792                 :           0 :                                                                         "sslmode", conn->sslmode);
    1793                 :           0 :                         return false;
    1794                 :             :                 }
    1795                 :             : 
    1796                 :             : #ifndef USE_SSL
    1797                 :             :                 switch (conn->sslmode[0])
    1798                 :             :                 {
    1799                 :             :                         case 'a':                       /* "allow" */
    1800                 :             :                         case 'p':                       /* "prefer" */
    1801                 :             : 
    1802                 :             :                                 /*
    1803                 :             :                                  * warn user that an SSL connection will never be negotiated
    1804                 :             :                                  * since SSL was not compiled in?
    1805                 :             :                                  */
    1806                 :             :                                 break;
    1807                 :             : 
    1808                 :             :                         case 'r':                       /* "require" */
    1809                 :             :                         case 'v':                       /* "verify-ca" or "verify-full" */
    1810                 :             :                                 conn->status = CONNECTION_BAD;
    1811                 :             :                                 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
    1812                 :             :                                                                                 "sslmode", conn->sslmode);
    1813                 :             :                                 return false;
    1814                 :             :                 }
    1815                 :             : #endif
    1816                 :         318 :         }
    1817                 :             :         else
    1818                 :             :         {
    1819                 :           0 :                 conn->sslmode = strdup(DefaultSSLMode);
    1820         [ #  # ]:           0 :                 if (!conn->sslmode)
    1821                 :           0 :                         goto oom_error;
    1822                 :             :         }
    1823                 :             : 
    1824                 :             :         /*
    1825                 :             :          * validate sslnegotiation option, default is "postgres" for the postgres
    1826                 :             :          * style negotiated connection with an extra round trip but more options.
    1827                 :             :          */
    1828         [ +  - ]:         318 :         if (conn->sslnegotiation)
    1829                 :             :         {
    1830                 :         318 :                 if (strcmp(conn->sslnegotiation, "postgres") != 0
    1831   [ -  +  #  # ]:         318 :                         && strcmp(conn->sslnegotiation, "direct") != 0)
    1832                 :             :                 {
    1833                 :           0 :                         conn->status = CONNECTION_BAD;
    1834                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    1835                 :           0 :                                                                         "sslnegotiation", conn->sslnegotiation);
    1836                 :           0 :                         return false;
    1837                 :             :                 }
    1838                 :             : 
    1839                 :             : #ifndef USE_SSL
    1840                 :             :                 if (conn->sslnegotiation[0] != 'p')
    1841                 :             :                 {
    1842                 :             :                         conn->status = CONNECTION_BAD;
    1843                 :             :                         libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
    1844                 :             :                                                                         "sslnegotiation", conn->sslnegotiation);
    1845                 :             :                         return false;
    1846                 :             :                 }
    1847                 :             : #endif
    1848                 :             : 
    1849                 :             :                 /*
    1850                 :             :                  * Don't allow direct SSL negotiation with sslmode='prefer', because
    1851                 :             :                  * that poses a risk of unintentional fallback to plaintext connection
    1852                 :             :                  * when connecting to a pre-v17 server that does not support direct
    1853                 :             :                  * SSL connections. To keep things simple, don't allow it with
    1854                 :             :                  * sslmode='allow' or sslmode='disable' either. If a user goes through
    1855                 :             :                  * the trouble of setting sslnegotiation='direct', they probably
    1856                 :             :                  * intend to use SSL, and sslmode=disable or allow is probably a user
    1857                 :             :                  * mistake anyway.
    1858                 :             :                  */
    1859         [ -  + ]:         318 :                 if (conn->sslnegotiation[0] == 'd' &&
    1860   [ #  #  #  # ]:           0 :                         conn->sslmode[0] != 'r' && conn->sslmode[0] != 'v')
    1861                 :             :                 {
    1862                 :           0 :                         conn->status = CONNECTION_BAD;
    1863                 :           0 :                         libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslnegotiation=direct (use \"require\", \"verify-ca\", or \"verify-full\")",
    1864                 :           0 :                                                                         conn->sslmode);
    1865                 :           0 :                         return false;
    1866                 :             :                 }
    1867                 :         318 :         }
    1868                 :             :         else
    1869                 :             :         {
    1870                 :           0 :                 conn->sslnegotiation = strdup(DefaultSSLNegotiation);
    1871         [ #  # ]:           0 :                 if (!conn->sslnegotiation)
    1872                 :           0 :                         goto oom_error;
    1873                 :             :         }
    1874                 :             : 
    1875                 :             : #ifdef USE_SSL
    1876                 :             : 
    1877                 :             :         /*
    1878                 :             :          * If sslrootcert=system, make sure our chosen sslmode is compatible.
    1879                 :             :          */
    1880                 :         318 :         if (conn->sslrootcert
    1881         [ -  + ]:         318 :                 && strcmp(conn->sslrootcert, "system") == 0
    1882   [ #  #  #  # ]:           0 :                 && strcmp(conn->sslmode, "verify-full") != 0)
    1883                 :             :         {
    1884                 :           0 :                 conn->status = CONNECTION_BAD;
    1885                 :           0 :                 libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslrootcert=system (use \"verify-full\")",
    1886                 :           0 :                                                                 conn->sslmode);
    1887                 :           0 :                 return false;
    1888                 :             :         }
    1889                 :             : #endif
    1890                 :             : 
    1891                 :             :         /*
    1892                 :             :          * Validate TLS protocol versions for ssl_min_protocol_version and
    1893                 :             :          * ssl_max_protocol_version.
    1894                 :             :          */
    1895         [ +  - ]:         318 :         if (!sslVerifyProtocolVersion(conn->ssl_min_protocol_version))
    1896                 :             :         {
    1897                 :           0 :                 conn->status = CONNECTION_BAD;
    1898                 :           0 :                 libpq_append_conn_error(conn, "invalid \"%s\" value: \"%s\"",
    1899                 :             :                                                                 "ssl_min_protocol_version",
    1900                 :           0 :                                                                 conn->ssl_min_protocol_version);
    1901                 :           0 :                 return false;
    1902                 :             :         }
    1903         [ +  - ]:         318 :         if (!sslVerifyProtocolVersion(conn->ssl_max_protocol_version))
    1904                 :             :         {
    1905                 :           0 :                 conn->status = CONNECTION_BAD;
    1906                 :           0 :                 libpq_append_conn_error(conn, "invalid \"%s\" value: \"%s\"",
    1907                 :             :                                                                 "ssl_max_protocol_version",
    1908                 :           0 :                                                                 conn->ssl_max_protocol_version);
    1909                 :           0 :                 return false;
    1910                 :             :         }
    1911                 :             : 
    1912                 :             :         /*
    1913                 :             :          * Check if the range of SSL protocols defined is correct.  This is done
    1914                 :             :          * at this early step because this is independent of the SSL
    1915                 :             :          * implementation used, and this avoids unnecessary cycles with an
    1916                 :             :          * already-built SSL context when the connection is being established, as
    1917                 :             :          * it would be doomed anyway.
    1918                 :             :          */
    1919   [ +  -  +  - ]:         636 :         if (!sslVerifyProtocolRange(conn->ssl_min_protocol_version,
    1920                 :         318 :                                                                 conn->ssl_max_protocol_version))
    1921                 :             :         {
    1922                 :           0 :                 conn->status = CONNECTION_BAD;
    1923                 :           0 :                 libpq_append_conn_error(conn, "invalid SSL protocol version range");
    1924                 :           0 :                 return false;
    1925                 :             :         }
    1926                 :             : 
    1927                 :             :         /*
    1928                 :             :          * validate sslcertmode option
    1929                 :             :          */
    1930         [ +  + ]:         318 :         if (conn->sslcertmode)
    1931                 :             :         {
    1932         [ +  - ]:          43 :                 if (strcmp(conn->sslcertmode, "disable") != 0 &&
    1933   [ -  +  #  # ]:          43 :                         strcmp(conn->sslcertmode, "allow") != 0 &&
    1934                 :           0 :                         strcmp(conn->sslcertmode, "require") != 0)
    1935                 :             :                 {
    1936                 :           0 :                         conn->status = CONNECTION_BAD;
    1937                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    1938                 :           0 :                                                                         "sslcertmode", conn->sslcertmode);
    1939                 :           0 :                         return false;
    1940                 :             :                 }
    1941                 :             : #ifndef USE_SSL
    1942                 :             :                 if (strcmp(conn->sslcertmode, "require") == 0)
    1943                 :             :                 {
    1944                 :             :                         conn->status = CONNECTION_BAD;
    1945                 :             :                         libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
    1946                 :             :                                                                         "sslcertmode", conn->sslcertmode);
    1947                 :             :                         return false;
    1948                 :             :                 }
    1949                 :             : #endif
    1950                 :             : #ifndef HAVE_SSL_CTX_SET_CERT_CB
    1951                 :             : 
    1952                 :             :                 /*
    1953                 :             :                  * Without a certificate callback, the current implementation can't
    1954                 :             :                  * figure out if a certificate was actually requested, so "require" is
    1955                 :             :                  * useless.
    1956                 :             :                  */
    1957                 :             :                 if (strcmp(conn->sslcertmode, "require") == 0)
    1958                 :             :                 {
    1959                 :             :                         conn->status = CONNECTION_BAD;
    1960                 :             :                         libpq_append_conn_error(conn, "%s value \"%s\" is not supported (check OpenSSL version)",
    1961                 :             :                                                                         "sslcertmode", conn->sslcertmode);
    1962                 :             :                         return false;
    1963                 :             :                 }
    1964                 :             : #endif
    1965                 :          43 :         }
    1966                 :             :         else
    1967                 :             :         {
    1968                 :         275 :                 conn->sslcertmode = strdup(DefaultSSLCertMode);
    1969         [ +  - ]:         275 :                 if (!conn->sslcertmode)
    1970                 :           0 :                         goto oom_error;
    1971                 :             :         }
    1972                 :             : 
    1973                 :             :         /*
    1974                 :             :          * validate gssencmode option
    1975                 :             :          */
    1976         [ +  - ]:         318 :         if (conn->gssencmode)
    1977                 :             :         {
    1978         [ +  - ]:         318 :                 if (strcmp(conn->gssencmode, "disable") != 0 &&
    1979   [ -  +  #  # ]:         318 :                         strcmp(conn->gssencmode, "prefer") != 0 &&
    1980                 :           0 :                         strcmp(conn->gssencmode, "require") != 0)
    1981                 :             :                 {
    1982                 :           0 :                         conn->status = CONNECTION_BAD;
    1983                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"", "gssencmode", conn->gssencmode);
    1984                 :           0 :                         return false;
    1985                 :             :                 }
    1986                 :             : #ifndef ENABLE_GSS
    1987                 :             :                 if (strcmp(conn->gssencmode, "require") == 0)
    1988                 :             :                 {
    1989                 :             :                         conn->status = CONNECTION_BAD;
    1990                 :             :                         libpq_append_conn_error(conn, "gssencmode value \"%s\" invalid when GSSAPI support is not compiled in",
    1991                 :             :                                                                         conn->gssencmode);
    1992                 :             :                         return false;
    1993                 :             :                 }
    1994                 :             : #endif
    1995                 :         318 :         }
    1996                 :             :         else
    1997                 :             :         {
    1998                 :           0 :                 conn->gssencmode = strdup(DefaultGSSMode);
    1999         [ #  # ]:           0 :                 if (!conn->gssencmode)
    2000                 :           0 :                         goto oom_error;
    2001                 :             :         }
    2002                 :             : 
    2003                 :             :         /*
    2004                 :             :          * validate target_session_attrs option, and set target_server_type
    2005                 :             :          */
    2006         [ +  - ]:         318 :         if (conn->target_session_attrs)
    2007                 :             :         {
    2008         [ -  + ]:         318 :                 if (strcmp(conn->target_session_attrs, "any") == 0)
    2009                 :         318 :                         conn->target_server_type = SERVER_TYPE_ANY;
    2010         [ #  # ]:           0 :                 else if (strcmp(conn->target_session_attrs, "read-write") == 0)
    2011                 :           0 :                         conn->target_server_type = SERVER_TYPE_READ_WRITE;
    2012         [ #  # ]:           0 :                 else if (strcmp(conn->target_session_attrs, "read-only") == 0)
    2013                 :           0 :                         conn->target_server_type = SERVER_TYPE_READ_ONLY;
    2014         [ #  # ]:           0 :                 else if (strcmp(conn->target_session_attrs, "primary") == 0)
    2015                 :           0 :                         conn->target_server_type = SERVER_TYPE_PRIMARY;
    2016         [ #  # ]:           0 :                 else if (strcmp(conn->target_session_attrs, "standby") == 0)
    2017                 :           0 :                         conn->target_server_type = SERVER_TYPE_STANDBY;
    2018         [ #  # ]:           0 :                 else if (strcmp(conn->target_session_attrs, "prefer-standby") == 0)
    2019                 :           0 :                         conn->target_server_type = SERVER_TYPE_PREFER_STANDBY;
    2020                 :             :                 else
    2021                 :             :                 {
    2022                 :           0 :                         conn->status = CONNECTION_BAD;
    2023                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    2024                 :             :                                                                         "target_session_attrs",
    2025                 :           0 :                                                                         conn->target_session_attrs);
    2026                 :           0 :                         return false;
    2027                 :             :                 }
    2028                 :         318 :         }
    2029                 :             :         else
    2030                 :           0 :                 conn->target_server_type = SERVER_TYPE_ANY;
    2031                 :             : 
    2032         [ +  - ]:         318 :         if (conn->scram_client_key)
    2033                 :             :         {
    2034                 :           0 :                 int                     len;
    2035                 :             : 
    2036                 :           0 :                 len = pg_b64_dec_len(strlen(conn->scram_client_key));
    2037                 :           0 :                 conn->scram_client_key_binary = malloc(len);
    2038         [ #  # ]:           0 :                 if (!conn->scram_client_key_binary)
    2039                 :           0 :                         goto oom_error;
    2040                 :           0 :                 len = pg_b64_decode(conn->scram_client_key, strlen(conn->scram_client_key),
    2041                 :           0 :                                                         conn->scram_client_key_binary, len);
    2042         [ #  # ]:           0 :                 if (len < 0)
    2043                 :             :                 {
    2044                 :           0 :                         libpq_append_conn_error(conn, "invalid SCRAM client key");
    2045                 :           0 :                         return false;
    2046                 :             :                 }
    2047         [ #  # ]:           0 :                 if (len != SCRAM_MAX_KEY_LEN)
    2048                 :             :                 {
    2049                 :           0 :                         libpq_append_conn_error(conn, "invalid SCRAM client key length: %d", len);
    2050                 :           0 :                         return false;
    2051                 :             :                 }
    2052                 :           0 :                 conn->scram_client_key_len = len;
    2053         [ #  # ]:           0 :         }
    2054                 :             : 
    2055         [ +  - ]:         318 :         if (conn->scram_server_key)
    2056                 :             :         {
    2057                 :           0 :                 int                     len;
    2058                 :             : 
    2059                 :           0 :                 len = pg_b64_dec_len(strlen(conn->scram_server_key));
    2060                 :           0 :                 conn->scram_server_key_binary = malloc(len);
    2061         [ #  # ]:           0 :                 if (!conn->scram_server_key_binary)
    2062                 :           0 :                         goto oom_error;
    2063                 :           0 :                 len = pg_b64_decode(conn->scram_server_key, strlen(conn->scram_server_key),
    2064                 :           0 :                                                         conn->scram_server_key_binary, len);
    2065         [ #  # ]:           0 :                 if (len < 0)
    2066                 :             :                 {
    2067                 :           0 :                         libpq_append_conn_error(conn, "invalid SCRAM server key");
    2068                 :           0 :                         return false;
    2069                 :             :                 }
    2070         [ #  # ]:           0 :                 if (len != SCRAM_MAX_KEY_LEN)
    2071                 :             :                 {
    2072                 :           0 :                         libpq_append_conn_error(conn, "invalid SCRAM server key length: %d", len);
    2073                 :           0 :                         return false;
    2074                 :             :                 }
    2075                 :           0 :                 conn->scram_server_key_len = len;
    2076         [ #  # ]:           0 :         }
    2077                 :             : 
    2078                 :             :         /*
    2079                 :             :          * validate load_balance_hosts option, and set load_balance_type
    2080                 :             :          */
    2081         [ +  - ]:         318 :         if (conn->load_balance_hosts)
    2082                 :             :         {
    2083         [ -  + ]:         318 :                 if (strcmp(conn->load_balance_hosts, "disable") == 0)
    2084                 :         318 :                         conn->load_balance_type = LOAD_BALANCE_DISABLE;
    2085         [ #  # ]:           0 :                 else if (strcmp(conn->load_balance_hosts, "random") == 0)
    2086                 :           0 :                         conn->load_balance_type = LOAD_BALANCE_RANDOM;
    2087                 :             :                 else
    2088                 :             :                 {
    2089                 :           0 :                         conn->status = CONNECTION_BAD;
    2090                 :           0 :                         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    2091                 :             :                                                                         "load_balance_hosts",
    2092                 :           0 :                                                                         conn->load_balance_hosts);
    2093                 :           0 :                         return false;
    2094                 :             :                 }
    2095                 :         318 :         }
    2096                 :             :         else
    2097                 :           0 :                 conn->load_balance_type = LOAD_BALANCE_DISABLE;
    2098                 :             : 
    2099         [ +  - ]:         318 :         if (conn->load_balance_type == LOAD_BALANCE_RANDOM)
    2100                 :             :         {
    2101                 :           0 :                 libpq_prng_init(conn);
    2102                 :             : 
    2103                 :             :                 /*
    2104                 :             :                  * This is the "inside-out" variant of the Fisher-Yates shuffle
    2105                 :             :                  * algorithm. Notionally, we append each new value to the array and
    2106                 :             :                  * then swap it with a randomly-chosen array element (possibly
    2107                 :             :                  * including itself, else we fail to generate permutations with the
    2108                 :             :                  * last integer last).  The swap step can be optimized by combining it
    2109                 :             :                  * with the insertion.
    2110                 :             :                  */
    2111         [ #  # ]:           0 :                 for (i = 1; i < conn->nconnhost; i++)
    2112                 :             :                 {
    2113                 :           0 :                         int                     j = pg_prng_uint64_range(&conn->prng_state, 0, i);
    2114                 :           0 :                         pg_conn_host temp = conn->connhost[j];
    2115                 :             : 
    2116                 :           0 :                         conn->connhost[j] = conn->connhost[i];
    2117                 :           0 :                         conn->connhost[i] = temp;
    2118                 :           0 :                 }
    2119                 :           0 :         }
    2120                 :             : 
    2121         [ -  + ]:         318 :         if (conn->min_protocol_version)
    2122                 :             :         {
    2123         [ #  # ]:           0 :                 if (!pqParseProtocolVersion(conn->min_protocol_version, &conn->min_pversion, conn, "min_protocol_version"))
    2124                 :             :                 {
    2125                 :           0 :                         conn->status = CONNECTION_BAD;
    2126                 :           0 :                         return false;
    2127                 :             :                 }
    2128                 :           0 :         }
    2129                 :             :         else
    2130                 :             :         {
    2131                 :         318 :                 conn->min_pversion = PG_PROTOCOL_EARLIEST;
    2132                 :             :         }
    2133                 :             : 
    2134         [ -  + ]:         318 :         if (conn->max_protocol_version)
    2135                 :             :         {
    2136         [ #  # ]:           0 :                 if (!pqParseProtocolVersion(conn->max_protocol_version, &conn->max_pversion, conn, "max_protocol_version"))
    2137                 :             :                 {
    2138                 :           0 :                         conn->status = CONNECTION_BAD;
    2139                 :           0 :                         return false;
    2140                 :             :                 }
    2141                 :           0 :         }
    2142                 :             :         else
    2143                 :             :         {
    2144                 :             :                 /*
    2145                 :             :                  * To not break connecting to older servers/poolers that do not yet
    2146                 :             :                  * support NegotiateProtocolVersion, default to the 3.0 protocol at
    2147                 :             :                  * least for a while longer. Except when min_protocol_version is set
    2148                 :             :                  * to something larger, then we might as well default to the latest.
    2149                 :             :                  */
    2150         [ -  + ]:         318 :                 if (conn->min_pversion > PG_PROTOCOL(3, 0))
    2151                 :           0 :                         conn->max_pversion = PG_PROTOCOL_LATEST;
    2152                 :             :                 else
    2153                 :         318 :                         conn->max_pversion = PG_PROTOCOL(3, 0);
    2154                 :             :         }
    2155                 :             : 
    2156         [ -  + ]:         318 :         if (conn->min_pversion > conn->max_pversion)
    2157                 :             :         {
    2158                 :           0 :                 conn->status = CONNECTION_BAD;
    2159                 :           0 :                 libpq_append_conn_error(conn, "\"%s\" is greater than \"%s\"", "min_protocol_version", "max_protocol_version");
    2160                 :           0 :                 return false;
    2161                 :             :         }
    2162                 :             : 
    2163                 :             :         /*
    2164                 :             :          * Resolve special "auto" client_encoding from the locale
    2165                 :             :          */
    2166   [ +  +  +  - ]:         318 :         if (conn->client_encoding_initial &&
    2167                 :           1 :                 strcmp(conn->client_encoding_initial, "auto") == 0)
    2168                 :             :         {
    2169                 :           0 :                 free(conn->client_encoding_initial);
    2170                 :           0 :                 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
    2171         [ #  # ]:           0 :                 if (!conn->client_encoding_initial)
    2172                 :           0 :                         goto oom_error;
    2173                 :           0 :         }
    2174                 :             : 
    2175                 :             :         /*
    2176                 :             :          * Only if we get this far is it appropriate to try to connect. (We need a
    2177                 :             :          * state flag, rather than just the boolean result of this function, in
    2178                 :             :          * case someone tries to PQreset() the PGconn.)
    2179                 :             :          */
    2180                 :         318 :         conn->options_valid = true;
    2181                 :             : 
    2182                 :         318 :         return true;
    2183                 :             : 
    2184                 :             : oom_error:
    2185                 :           0 :         conn->status = CONNECTION_BAD;
    2186                 :           0 :         libpq_append_conn_error(conn, "out of memory");
    2187                 :           0 :         return false;
    2188                 :         318 : }
    2189                 :             : 
    2190                 :             : /*
    2191                 :             :  *              PQconndefaults
    2192                 :             :  *
    2193                 :             :  * Construct a default connection options array, which identifies all the
    2194                 :             :  * available options and shows any default values that are available from the
    2195                 :             :  * environment etc.  On error (eg out of memory), NULL is returned.
    2196                 :             :  *
    2197                 :             :  * Using this function, an application may determine all possible options
    2198                 :             :  * and their current default values.
    2199                 :             :  *
    2200                 :             :  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
    2201                 :             :  * and should be freed when no longer needed via PQconninfoFree().  (In prior
    2202                 :             :  * versions, the returned array was static, but that's not thread-safe.)
    2203                 :             :  * Pre-7.0 applications that use this function will see a small memory leak
    2204                 :             :  * until they are updated to call PQconninfoFree.
    2205                 :             :  */
    2206                 :             : PQconninfoOption *
    2207                 :           0 : PQconndefaults(void)
    2208                 :             : {
    2209                 :           0 :         PQExpBufferData errorBuf;
    2210                 :           0 :         PQconninfoOption *connOptions;
    2211                 :             : 
    2212                 :             :         /* We don't actually report any errors here, but callees want a buffer */
    2213                 :           0 :         initPQExpBuffer(&errorBuf);
    2214         [ #  # ]:           0 :         if (PQExpBufferDataBroken(errorBuf))
    2215                 :           0 :                 return NULL;                    /* out of memory already :-( */
    2216                 :             : 
    2217                 :           0 :         connOptions = conninfo_init(&errorBuf);
    2218         [ #  # ]:           0 :         if (connOptions != NULL)
    2219                 :             :         {
    2220                 :             :                 /* pass NULL errorBuf to ignore errors */
    2221         [ #  # ]:           0 :                 if (!conninfo_add_defaults(connOptions, NULL))
    2222                 :             :                 {
    2223                 :           0 :                         PQconninfoFree(connOptions);
    2224                 :           0 :                         connOptions = NULL;
    2225                 :           0 :                 }
    2226                 :           0 :         }
    2227                 :             : 
    2228                 :           0 :         termPQExpBuffer(&errorBuf);
    2229                 :           0 :         return connOptions;
    2230                 :           0 : }
    2231                 :             : 
    2232                 :             : /* ----------------
    2233                 :             :  *              PQsetdbLogin
    2234                 :             :  *
    2235                 :             :  * establishes a connection to a postgres backend through the postmaster
    2236                 :             :  * at the specified host and port.
    2237                 :             :  *
    2238                 :             :  * returns a PGconn* which is needed for all subsequent libpq calls
    2239                 :             :  *
    2240                 :             :  * if the status field of the connection returned is CONNECTION_BAD,
    2241                 :             :  * then only the errorMessage is likely to be useful.
    2242                 :             :  * ----------------
    2243                 :             :  */
    2244                 :             : PGconn *
    2245                 :           0 : PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
    2246                 :             :                          const char *pgtty, const char *dbName, const char *login,
    2247                 :             :                          const char *pwd)
    2248                 :             : {
    2249                 :           0 :         PGconn     *conn;
    2250                 :             : 
    2251                 :             :         /*
    2252                 :             :          * Allocate memory for the conn structure.  Note that we also expect this
    2253                 :             :          * to initialize conn->errorMessage to empty.  All subsequent steps during
    2254                 :             :          * connection initialization will only append to that buffer.
    2255                 :             :          */
    2256                 :           0 :         conn = pqMakeEmptyPGconn();
    2257         [ #  # ]:           0 :         if (conn == NULL)
    2258                 :           0 :                 return NULL;
    2259                 :             : 
    2260                 :             :         /*
    2261                 :             :          * If the dbName parameter contains what looks like a connection string,
    2262                 :             :          * parse it into conn struct using connectOptions1.
    2263                 :             :          */
    2264   [ #  #  #  # ]:           0 :         if (dbName && recognized_connection_string(dbName))
    2265                 :             :         {
    2266         [ #  # ]:           0 :                 if (!connectOptions1(conn, dbName))
    2267                 :           0 :                         return conn;
    2268                 :           0 :         }
    2269                 :             :         else
    2270                 :             :         {
    2271                 :             :                 /*
    2272                 :             :                  * Old-style path: first, parse an empty conninfo string in order to
    2273                 :             :                  * set up the same defaults that PQconnectdb() would use.
    2274                 :             :                  */
    2275         [ #  # ]:           0 :                 if (!connectOptions1(conn, ""))
    2276                 :           0 :                         return conn;
    2277                 :             : 
    2278                 :             :                 /* Insert dbName parameter value into struct */
    2279   [ #  #  #  # ]:           0 :                 if (dbName && dbName[0] != '\0')
    2280                 :             :                 {
    2281                 :           0 :                         free(conn->dbName);
    2282                 :           0 :                         conn->dbName = strdup(dbName);
    2283         [ #  # ]:           0 :                         if (!conn->dbName)
    2284                 :           0 :                                 goto oom_error;
    2285                 :           0 :                 }
    2286                 :             :         }
    2287                 :             : 
    2288                 :             :         /*
    2289                 :             :          * Insert remaining parameters into struct, overriding defaults (as well
    2290                 :             :          * as any conflicting data from dbName taken as a conninfo).
    2291                 :             :          */
    2292   [ #  #  #  # ]:           0 :         if (pghost && pghost[0] != '\0')
    2293                 :             :         {
    2294                 :           0 :                 free(conn->pghost);
    2295                 :           0 :                 conn->pghost = strdup(pghost);
    2296         [ #  # ]:           0 :                 if (!conn->pghost)
    2297                 :           0 :                         goto oom_error;
    2298                 :           0 :         }
    2299                 :             : 
    2300   [ #  #  #  # ]:           0 :         if (pgport && pgport[0] != '\0')
    2301                 :             :         {
    2302                 :           0 :                 free(conn->pgport);
    2303                 :           0 :                 conn->pgport = strdup(pgport);
    2304         [ #  # ]:           0 :                 if (!conn->pgport)
    2305                 :           0 :                         goto oom_error;
    2306                 :           0 :         }
    2307                 :             : 
    2308   [ #  #  #  # ]:           0 :         if (pgoptions && pgoptions[0] != '\0')
    2309                 :             :         {
    2310                 :           0 :                 free(conn->pgoptions);
    2311                 :           0 :                 conn->pgoptions = strdup(pgoptions);
    2312         [ #  # ]:           0 :                 if (!conn->pgoptions)
    2313                 :           0 :                         goto oom_error;
    2314                 :           0 :         }
    2315                 :             : 
    2316   [ #  #  #  # ]:           0 :         if (login && login[0] != '\0')
    2317                 :             :         {
    2318                 :           0 :                 free(conn->pguser);
    2319                 :           0 :                 conn->pguser = strdup(login);
    2320         [ #  # ]:           0 :                 if (!conn->pguser)
    2321                 :           0 :                         goto oom_error;
    2322                 :           0 :         }
    2323                 :             : 
    2324   [ #  #  #  # ]:           0 :         if (pwd && pwd[0] != '\0')
    2325                 :             :         {
    2326                 :           0 :                 free(conn->pgpass);
    2327                 :           0 :                 conn->pgpass = strdup(pwd);
    2328         [ #  # ]:           0 :                 if (!conn->pgpass)
    2329                 :           0 :                         goto oom_error;
    2330                 :           0 :         }
    2331                 :             : 
    2332                 :             :         /*
    2333                 :             :          * Compute derived options
    2334                 :             :          */
    2335         [ #  # ]:           0 :         if (!pqConnectOptions2(conn))
    2336                 :           0 :                 return conn;
    2337                 :             : 
    2338                 :             :         /*
    2339                 :             :          * Connect to the database
    2340                 :             :          */
    2341         [ #  # ]:           0 :         if (pqConnectDBStart(conn))
    2342                 :           0 :                 (void) pqConnectDBComplete(conn);
    2343                 :             : 
    2344                 :           0 :         return conn;
    2345                 :             : 
    2346                 :             : oom_error:
    2347                 :           0 :         conn->status = CONNECTION_BAD;
    2348                 :           0 :         libpq_append_conn_error(conn, "out of memory");
    2349                 :           0 :         return conn;
    2350                 :           0 : }
    2351                 :             : 
    2352                 :             : 
    2353                 :             : /* ----------
    2354                 :             :  * connectNoDelay -
    2355                 :             :  * Sets the TCP_NODELAY socket option.
    2356                 :             :  * Returns 1 if successful, 0 if not.
    2357                 :             :  * ----------
    2358                 :             :  */
    2359                 :             : static int
    2360                 :           0 : connectNoDelay(PGconn *conn)
    2361                 :             : {
    2362                 :             : #ifdef  TCP_NODELAY
    2363                 :           0 :         int                     on = 1;
    2364                 :             : 
    2365                 :           0 :         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
    2366                 :             :                                    (char *) &on,
    2367         [ #  # ]:           0 :                                    sizeof(on)) < 0)
    2368                 :             :         {
    2369                 :           0 :                 char            sebuf[PG_STRERROR_R_BUFLEN];
    2370                 :             : 
    2371                 :           0 :                 libpq_append_conn_error(conn, "could not set socket to TCP no delay mode: %s",
    2372                 :           0 :                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    2373                 :           0 :                 return 0;
    2374                 :           0 :         }
    2375                 :             : #endif
    2376                 :             : 
    2377                 :           0 :         return 1;
    2378                 :           0 : }
    2379                 :             : 
    2380                 :             : /* ----------
    2381                 :             :  * Write currently connected IP address into host_addr (of len host_addr_len).
    2382                 :             :  * If unable to, set it to the empty string.
    2383                 :             :  * ----------
    2384                 :             :  */
    2385                 :             : static void
    2386                 :         317 : getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
    2387                 :             : {
    2388                 :         317 :         struct sockaddr_storage *addr = &conn->raddr.addr;
    2389                 :             : 
    2390         [ -  + ]:         317 :         if (addr->ss_family == AF_INET)
    2391                 :             :         {
    2392                 :           0 :                 if (pg_inet_net_ntop(AF_INET,
    2393                 :           0 :                                                          &((struct sockaddr_in *) addr)->sin_addr.s_addr,
    2394                 :             :                                                          32,
    2395   [ #  #  #  # ]:           0 :                                                          host_addr, host_addr_len) == NULL)
    2396                 :           0 :                         host_addr[0] = '\0';
    2397                 :           0 :         }
    2398         [ -  + ]:         317 :         else if (addr->ss_family == AF_INET6)
    2399                 :             :         {
    2400                 :           0 :                 if (pg_inet_net_ntop(AF_INET6,
    2401                 :           0 :                                                          &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
    2402                 :             :                                                          128,
    2403   [ #  #  #  # ]:           0 :                                                          host_addr, host_addr_len) == NULL)
    2404                 :           0 :                         host_addr[0] = '\0';
    2405                 :           0 :         }
    2406                 :             :         else
    2407                 :         317 :                 host_addr[0] = '\0';
    2408                 :         317 : }
    2409                 :             : 
    2410                 :             : /*
    2411                 :             :  * emitHostIdentityInfo -
    2412                 :             :  * Speculatively append "connection to server so-and-so failed: " to
    2413                 :             :  * conn->errorMessage once we've identified the current connection target
    2414                 :             :  * address.  This ensures that any subsequent error message will be properly
    2415                 :             :  * attributed to the server we couldn't connect to.  conn->raddr must be
    2416                 :             :  * valid, and the result of getHostaddr() must be supplied.
    2417                 :             :  */
    2418                 :             : static void
    2419                 :         317 : emitHostIdentityInfo(PGconn *conn, const char *host_addr)
    2420                 :             : {
    2421         [ +  - ]:         317 :         if (conn->raddr.addr.ss_family == AF_UNIX)
    2422                 :             :         {
    2423                 :         317 :                 char            service[NI_MAXHOST];
    2424                 :             : 
    2425                 :         634 :                 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
    2426                 :             :                                                    NULL, 0,
    2427                 :         317 :                                                    service, sizeof(service),
    2428                 :             :                                                    NI_NUMERICSERV);
    2429                 :         634 :                 appendPQExpBuffer(&conn->errorMessage,
    2430                 :         317 :                                                   libpq_gettext("connection to server on socket \"%s\" failed: "),
    2431                 :         317 :                                                   service);
    2432                 :         317 :         }
    2433                 :             :         else
    2434                 :             :         {
    2435                 :           0 :                 const char *displayed_host;
    2436                 :           0 :                 const char *displayed_port;
    2437                 :             : 
    2438                 :             :                 /* To which host and port were we actually connecting? */
    2439         [ #  # ]:           0 :                 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
    2440                 :           0 :                         displayed_host = conn->connhost[conn->whichhost].hostaddr;
    2441                 :             :                 else
    2442                 :           0 :                         displayed_host = conn->connhost[conn->whichhost].host;
    2443                 :           0 :                 displayed_port = conn->connhost[conn->whichhost].port;
    2444   [ #  #  #  # ]:           0 :                 if (displayed_port == NULL || displayed_port[0] == '\0')
    2445                 :           0 :                         displayed_port = DEF_PGPORT_STR;
    2446                 :             : 
    2447                 :             :                 /*
    2448                 :             :                  * If the user did not supply an IP address using 'hostaddr', and
    2449                 :             :                  * 'host' was missing or does not match our lookup, display the
    2450                 :             :                  * looked-up IP address.
    2451                 :             :                  */
    2452         [ #  # ]:           0 :                 if (conn->connhost[conn->whichhost].type != CHT_HOST_ADDRESS &&
    2453   [ #  #  #  # ]:           0 :                         host_addr[0] &&
    2454                 :           0 :                         strcmp(displayed_host, host_addr) != 0)
    2455                 :           0 :                         appendPQExpBuffer(&conn->errorMessage,
    2456                 :           0 :                                                           libpq_gettext("connection to server at \"%s\" (%s), port %s failed: "),
    2457                 :           0 :                                                           displayed_host, host_addr,
    2458                 :           0 :                                                           displayed_port);
    2459                 :             :                 else
    2460                 :           0 :                         appendPQExpBuffer(&conn->errorMessage,
    2461                 :           0 :                                                           libpq_gettext("connection to server at \"%s\", port %s failed: "),
    2462                 :           0 :                                                           displayed_host,
    2463                 :           0 :                                                           displayed_port);
    2464                 :           0 :         }
    2465                 :         317 : }
    2466                 :             : 
    2467                 :             : /* ----------
    2468                 :             :  * connectFailureMessage -
    2469                 :             :  * create a friendly error message on connection failure,
    2470                 :             :  * using the given errno value.  Use this for error cases that
    2471                 :             :  * imply that there's no server there.
    2472                 :             :  * ----------
    2473                 :             :  */
    2474                 :             : static void
    2475                 :           1 : connectFailureMessage(PGconn *conn, int errorno)
    2476                 :             : {
    2477                 :           1 :         char            sebuf[PG_STRERROR_R_BUFLEN];
    2478                 :             : 
    2479                 :           2 :         appendPQExpBuffer(&conn->errorMessage,
    2480                 :             :                                           "%s\n",
    2481                 :           1 :                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
    2482                 :             : 
    2483         [ +  - ]:           1 :         if (conn->raddr.addr.ss_family == AF_UNIX)
    2484                 :           1 :                 libpq_append_conn_error(conn, "\tIs the server running locally and accepting connections on that socket?");
    2485                 :             :         else
    2486                 :           0 :                 libpq_append_conn_error(conn, "\tIs the server running on that host and accepting TCP/IP connections?");
    2487                 :           1 : }
    2488                 :             : 
    2489                 :             : /*
    2490                 :             :  * Should we use keepalives?  Returns 1 if yes, 0 if no, and -1 if
    2491                 :             :  * conn->keepalives is set to a value which is not parseable as an
    2492                 :             :  * integer.
    2493                 :             :  */
    2494                 :             : static int
    2495                 :           0 : useKeepalives(PGconn *conn)
    2496                 :             : {
    2497                 :           0 :         int                     val;
    2498                 :             : 
    2499         [ #  # ]:           0 :         if (conn->keepalives == NULL)
    2500                 :           0 :                 return 1;
    2501                 :             : 
    2502         [ #  # ]:           0 :         if (!pqParseIntParam(conn->keepalives, &val, conn, "keepalives"))
    2503                 :           0 :                 return -1;
    2504                 :             : 
    2505                 :           0 :         return val != 0 ? 1 : 0;
    2506                 :           0 : }
    2507                 :             : 
    2508                 :             : #ifndef WIN32
    2509                 :             : /*
    2510                 :             :  * Set the keepalive idle timer.
    2511                 :             :  */
    2512                 :             : static int
    2513                 :           0 : setKeepalivesIdle(PGconn *conn)
    2514                 :             : {
    2515                 :           0 :         int                     idle;
    2516                 :             : 
    2517         [ #  # ]:           0 :         if (conn->keepalives_idle == NULL)
    2518                 :           0 :                 return 1;
    2519                 :             : 
    2520         [ #  # ]:           0 :         if (!pqParseIntParam(conn->keepalives_idle, &idle, conn,
    2521                 :             :                                                  "keepalives_idle"))
    2522                 :           0 :                 return 0;
    2523         [ #  # ]:           0 :         if (idle < 0)
    2524                 :           0 :                 idle = 0;
    2525                 :             : 
    2526                 :             : #ifdef PG_TCP_KEEPALIVE_IDLE
    2527                 :           0 :         if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
    2528         [ #  # ]:           0 :                                    (char *) &idle, sizeof(idle)) < 0)
    2529                 :             :         {
    2530                 :           0 :                 char            sebuf[PG_STRERROR_R_BUFLEN];
    2531                 :             : 
    2532                 :           0 :                 libpq_append_conn_error(conn, "%s(%s) failed: %s",
    2533                 :             :                                                                 "setsockopt",
    2534                 :             :                                                                 PG_TCP_KEEPALIVE_IDLE_STR,
    2535                 :           0 :                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    2536                 :           0 :                 return 0;
    2537                 :           0 :         }
    2538                 :             : #endif
    2539                 :             : 
    2540                 :           0 :         return 1;
    2541                 :           0 : }
    2542                 :             : 
    2543                 :             : /*
    2544                 :             :  * Set the keepalive interval.
    2545                 :             :  */
    2546                 :             : static int
    2547                 :           0 : setKeepalivesInterval(PGconn *conn)
    2548                 :             : {
    2549                 :           0 :         int                     interval;
    2550                 :             : 
    2551         [ #  # ]:           0 :         if (conn->keepalives_interval == NULL)
    2552                 :           0 :                 return 1;
    2553                 :             : 
    2554         [ #  # ]:           0 :         if (!pqParseIntParam(conn->keepalives_interval, &interval, conn,
    2555                 :             :                                                  "keepalives_interval"))
    2556                 :           0 :                 return 0;
    2557         [ #  # ]:           0 :         if (interval < 0)
    2558                 :           0 :                 interval = 0;
    2559                 :             : 
    2560                 :             : #ifdef TCP_KEEPINTVL
    2561                 :           0 :         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
    2562         [ #  # ]:           0 :                                    (char *) &interval, sizeof(interval)) < 0)
    2563                 :             :         {
    2564                 :           0 :                 char            sebuf[PG_STRERROR_R_BUFLEN];
    2565                 :             : 
    2566                 :           0 :                 libpq_append_conn_error(conn, "%s(%s) failed: %s",
    2567                 :             :                                                                 "setsockopt",
    2568                 :             :                                                                 "TCP_KEEPINTVL",
    2569                 :           0 :                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    2570                 :           0 :                 return 0;
    2571                 :           0 :         }
    2572                 :             : #endif
    2573                 :             : 
    2574                 :           0 :         return 1;
    2575                 :           0 : }
    2576                 :             : 
    2577                 :             : /*
    2578                 :             :  * Set the count of lost keepalive packets that will trigger a connection
    2579                 :             :  * break.
    2580                 :             :  */
    2581                 :             : static int
    2582                 :           0 : setKeepalivesCount(PGconn *conn)
    2583                 :             : {
    2584                 :           0 :         int                     count;
    2585                 :             : 
    2586         [ #  # ]:           0 :         if (conn->keepalives_count == NULL)
    2587                 :           0 :                 return 1;
    2588                 :             : 
    2589         [ #  # ]:           0 :         if (!pqParseIntParam(conn->keepalives_count, &count, conn,
    2590                 :             :                                                  "keepalives_count"))
    2591                 :           0 :                 return 0;
    2592         [ #  # ]:           0 :         if (count < 0)
    2593                 :           0 :                 count = 0;
    2594                 :             : 
    2595                 :             : #ifdef TCP_KEEPCNT
    2596                 :           0 :         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
    2597         [ #  # ]:           0 :                                    (char *) &count, sizeof(count)) < 0)
    2598                 :             :         {
    2599                 :           0 :                 char            sebuf[PG_STRERROR_R_BUFLEN];
    2600                 :             : 
    2601                 :           0 :                 libpq_append_conn_error(conn, "%s(%s) failed: %s",
    2602                 :             :                                                                 "setsockopt",
    2603                 :             :                                                                 "TCP_KEEPCNT",
    2604                 :           0 :                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    2605                 :           0 :                 return 0;
    2606                 :           0 :         }
    2607                 :             : #endif
    2608                 :             : 
    2609                 :           0 :         return 1;
    2610                 :           0 : }
    2611                 :             : #else                                                   /* WIN32 */
    2612                 :             : #ifdef SIO_KEEPALIVE_VALS
    2613                 :             : /*
    2614                 :             :  * Enable keepalives and set the keepalive values on Win32,
    2615                 :             :  * where they are always set in one batch.
    2616                 :             :  *
    2617                 :             :  * CAUTION: This needs to be signal safe, since it's used by PQcancel.
    2618                 :             :  */
    2619                 :             : int
    2620                 :             : pqSetKeepalivesWin32(pgsocket sock, int idle, int interval)
    2621                 :             : {
    2622                 :             :         struct tcp_keepalive ka;
    2623                 :             :         DWORD           retsize;
    2624                 :             : 
    2625                 :             :         if (idle <= 0)
    2626                 :             :                 idle = 2 * 60 * 60;             /* 2 hours = default */
    2627                 :             :         if (interval <= 0)
    2628                 :             :                 interval = 1;                   /* 1 second = default */
    2629                 :             : 
    2630                 :             :         ka.onoff = 1;
    2631                 :             :         ka.keepalivetime = idle * 1000;
    2632                 :             :         ka.keepaliveinterval = interval * 1000;
    2633                 :             : 
    2634                 :             :         if (WSAIoctl(sock,
    2635                 :             :                                  SIO_KEEPALIVE_VALS,
    2636                 :             :                                  (LPVOID) &ka,
    2637                 :             :                                  sizeof(ka),
    2638                 :             :                                  NULL,
    2639                 :             :                                  0,
    2640                 :             :                                  &retsize,
    2641                 :             :                                  NULL,
    2642                 :             :                                  NULL)
    2643                 :             :                 != 0)
    2644                 :             :                 return 0;
    2645                 :             :         return 1;
    2646                 :             : }
    2647                 :             : 
    2648                 :             : static int
    2649                 :             : prepKeepalivesWin32(PGconn *conn)
    2650                 :             : {
    2651                 :             :         int                     idle = -1;
    2652                 :             :         int                     interval = -1;
    2653                 :             : 
    2654                 :             :         if (conn->keepalives_idle &&
    2655                 :             :                 !pqParseIntParam(conn->keepalives_idle, &idle, conn,
    2656                 :             :                                                  "keepalives_idle"))
    2657                 :             :                 return 0;
    2658                 :             :         if (conn->keepalives_interval &&
    2659                 :             :                 !pqParseIntParam(conn->keepalives_interval, &interval, conn,
    2660                 :             :                                                  "keepalives_interval"))
    2661                 :             :                 return 0;
    2662                 :             : 
    2663                 :             :         if (!pqSetKeepalivesWin32(conn->sock, idle, interval))
    2664                 :             :         {
    2665                 :             :                 libpq_append_conn_error(conn, "%s(%s) failed: error code %d",
    2666                 :             :                                                                 "WSAIoctl", "SIO_KEEPALIVE_VALS",
    2667                 :             :                                                                 WSAGetLastError());
    2668                 :             :                 return 0;
    2669                 :             :         }
    2670                 :             :         return 1;
    2671                 :             : }
    2672                 :             : #endif                                                  /* SIO_KEEPALIVE_VALS */
    2673                 :             : #endif                                                  /* WIN32 */
    2674                 :             : 
    2675                 :             : /*
    2676                 :             :  * Set the TCP user timeout.
    2677                 :             :  */
    2678                 :             : static int
    2679                 :           0 : setTCPUserTimeout(PGconn *conn)
    2680                 :             : {
    2681                 :           0 :         int                     timeout;
    2682                 :             : 
    2683         [ #  # ]:           0 :         if (conn->pgtcp_user_timeout == NULL)
    2684                 :           0 :                 return 1;
    2685                 :             : 
    2686         [ #  # ]:           0 :         if (!pqParseIntParam(conn->pgtcp_user_timeout, &timeout, conn,
    2687                 :             :                                                  "tcp_user_timeout"))
    2688                 :           0 :                 return 0;
    2689                 :             : 
    2690         [ #  # ]:           0 :         if (timeout < 0)
    2691                 :           0 :                 timeout = 0;
    2692                 :             : 
    2693                 :             : #ifdef TCP_USER_TIMEOUT
    2694                 :             :         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
    2695                 :             :                                    (char *) &timeout, sizeof(timeout)) < 0)
    2696                 :             :         {
    2697                 :             :                 char            sebuf[256];
    2698                 :             : 
    2699                 :             :                 libpq_append_conn_error(conn, "%s(%s) failed: %s",
    2700                 :             :                                                                 "setsockopt",
    2701                 :             :                                                                 "TCP_USER_TIMEOUT",
    2702                 :             :                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    2703                 :             :                 return 0;
    2704                 :             :         }
    2705                 :             : #endif
    2706                 :             : 
    2707                 :           0 :         return 1;
    2708                 :           0 : }
    2709                 :             : 
    2710                 :             : /* ----------
    2711                 :             :  * pqConnectDBStart -
    2712                 :             :  *              Begin the process of making a connection to the backend.
    2713                 :             :  *
    2714                 :             :  * Returns 1 if successful, 0 if not.
    2715                 :             :  * ----------
    2716                 :             :  */
    2717                 :             : int
    2718                 :         318 : pqConnectDBStart(PGconn *conn)
    2719                 :             : {
    2720         [ +  - ]:         318 :         if (!conn)
    2721                 :           0 :                 return 0;
    2722                 :             : 
    2723         [ +  - ]:         318 :         if (!conn->options_valid)
    2724                 :           0 :                 goto connect_errReturn;
    2725                 :             : 
    2726                 :             :         /*
    2727                 :             :          * Check for bad linking to backend-internal versions of src/common
    2728                 :             :          * functions (see comments in link-canary.c for the reason we need this).
    2729                 :             :          * Nobody but developers should see this message, so we don't bother
    2730                 :             :          * translating it.
    2731                 :             :          */
    2732         [ +  - ]:         318 :         if (!pg_link_canary_is_frontend())
    2733                 :             :         {
    2734                 :           0 :                 appendPQExpBufferStr(&conn->errorMessage,
    2735                 :             :                                                          "libpq is incorrectly linked to backend functions\n");
    2736                 :           0 :                 goto connect_errReturn;
    2737                 :             :         }
    2738                 :             : 
    2739                 :             :         /* Ensure our buffers are empty */
    2740                 :         318 :         conn->inStart = conn->inCursor = conn->inEnd = 0;
    2741                 :         318 :         conn->outCount = 0;
    2742                 :             : 
    2743                 :             :         /*
    2744                 :             :          * Set up to try to connect to the first host.  (Setting whichhost = -1 is
    2745                 :             :          * a bit of a cheat, but PQconnectPoll will advance it to 0 before
    2746                 :             :          * anything else looks at it.)
    2747                 :             :          *
    2748                 :             :          * Cancel requests are special though, they should only try one host and
    2749                 :             :          * address, and these fields have already been set up in PQcancelCreate,
    2750                 :             :          * so leave these fields alone for cancel requests.
    2751                 :             :          */
    2752         [ -  + ]:         318 :         if (!conn->cancelRequest)
    2753                 :             :         {
    2754                 :         318 :                 conn->whichhost = -1;
    2755                 :         318 :                 conn->try_next_host = true;
    2756                 :         318 :                 conn->try_next_addr = false;
    2757                 :         318 :         }
    2758                 :             : 
    2759                 :         318 :         conn->status = CONNECTION_NEEDED;
    2760                 :             : 
    2761                 :             :         /* Also reset the target_server_type state if needed */
    2762         [ +  - ]:         318 :         if (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY_PASS2)
    2763                 :           0 :                 conn->target_server_type = SERVER_TYPE_PREFER_STANDBY;
    2764                 :             : 
    2765                 :             :         /*
    2766                 :             :          * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
    2767                 :             :          * so that it can easily be re-executed if needed again during the
    2768                 :             :          * asynchronous startup process.  However, we must run it once here,
    2769                 :             :          * because callers expect a success return from this routine to mean that
    2770                 :             :          * we are in PGRES_POLLING_WRITING connection state.
    2771                 :             :          */
    2772         [ +  + ]:         318 :         if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
    2773                 :         316 :                 return 1;
    2774                 :             : 
    2775                 :             : connect_errReturn:
    2776                 :             : 
    2777                 :             :         /*
    2778                 :             :          * If we managed to open a socket, close it immediately rather than
    2779                 :             :          * waiting till PQfinish.  (The application cannot have gotten the socket
    2780                 :             :          * from PQsocket yet, so this doesn't risk breaking anything.)
    2781                 :             :          */
    2782                 :           2 :         pqDropConnection(conn, true);
    2783                 :           2 :         conn->status = CONNECTION_BAD;
    2784                 :           2 :         return 0;
    2785                 :         318 : }
    2786                 :             : 
    2787                 :             : 
    2788                 :             : /*
    2789                 :             :  *              pqConnectDBComplete
    2790                 :             :  *
    2791                 :             :  * Block and complete a connection.
    2792                 :             :  *
    2793                 :             :  * Returns 1 on success, 0 on failure.
    2794                 :             :  */
    2795                 :             : int
    2796                 :         273 : pqConnectDBComplete(PGconn *conn)
    2797                 :             : {
    2798                 :         273 :         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
    2799                 :         273 :         pg_usec_time_t end_time = -1;
    2800                 :         273 :         int                     timeout = 0;
    2801                 :         273 :         int                     last_whichhost = -2;    /* certainly different from whichhost */
    2802                 :         273 :         int                     last_whichaddr = -2;    /* certainly different from whichaddr */
    2803                 :             : 
    2804   [ +  -  -  + ]:         273 :         if (conn == NULL || conn->status == CONNECTION_BAD)
    2805                 :           0 :                 return 0;
    2806                 :             : 
    2807                 :             :         /*
    2808                 :             :          * Set up a time limit, if connect_timeout is greater than zero.
    2809                 :             :          */
    2810         [ +  - ]:         273 :         if (conn->connect_timeout != NULL)
    2811                 :             :         {
    2812         [ #  # ]:           0 :                 if (!pqParseIntParam(conn->connect_timeout, &timeout, conn,
    2813                 :             :                                                          "connect_timeout"))
    2814                 :             :                 {
    2815                 :             :                         /* mark the connection as bad to report the parsing failure */
    2816                 :           0 :                         conn->status = CONNECTION_BAD;
    2817                 :           0 :                         return 0;
    2818                 :             :                 }
    2819                 :           0 :         }
    2820                 :             : 
    2821                 :         819 :         for (;;)
    2822                 :             :         {
    2823                 :         819 :                 int                     ret = 0;
    2824                 :             : 
    2825                 :             :                 /*
    2826                 :             :                  * (Re)start the connect_timeout timer if it's active and we are
    2827                 :             :                  * considering a different host than we were last time through.  If
    2828                 :             :                  * we've already succeeded, though, needn't recalculate.
    2829                 :             :                  */
    2830         [ +  + ]:         819 :                 if (flag != PGRES_POLLING_OK &&
    2831   [ -  +  #  # ]:         546 :                         timeout > 0 &&
    2832         [ #  # ]:           0 :                         (conn->whichhost != last_whichhost ||
    2833                 :           0 :                          conn->whichaddr != last_whichaddr))
    2834                 :             :                 {
    2835                 :           0 :                         end_time = PQgetCurrentTimeUSec() + (pg_usec_time_t) timeout * 1000000;
    2836                 :           0 :                         last_whichhost = conn->whichhost;
    2837                 :           0 :                         last_whichaddr = conn->whichaddr;
    2838                 :           0 :                 }
    2839                 :             : 
    2840                 :             :                 /*
    2841                 :             :                  * Wait, if necessary.  Note that the initial state (just after
    2842                 :             :                  * PQconnectStart) is to wait for the socket to select for writing.
    2843                 :             :                  */
    2844   [ -  +  +  + ]:         819 :                 switch (flag)
    2845                 :             :                 {
    2846                 :             :                         case PGRES_POLLING_OK:
    2847                 :         273 :                                 return 1;               /* success! */
    2848                 :             : 
    2849                 :             :                         case PGRES_POLLING_READING:
    2850                 :         273 :                                 ret = pqWaitTimed(1, 0, conn, end_time);
    2851         [ +  - ]:         273 :                                 if (ret == -1)
    2852                 :             :                                 {
    2853                 :             :                                         /* hard failure, eg select() problem, aborts everything */
    2854                 :           0 :                                         conn->status = CONNECTION_BAD;
    2855                 :           0 :                                         return 0;
    2856                 :             :                                 }
    2857                 :         273 :                                 break;
    2858                 :             : 
    2859                 :             :                         case PGRES_POLLING_WRITING:
    2860                 :         273 :                                 ret = pqWaitTimed(0, 1, conn, end_time);
    2861         [ +  - ]:         273 :                                 if (ret == -1)
    2862                 :             :                                 {
    2863                 :             :                                         /* hard failure, eg select() problem, aborts everything */
    2864                 :           0 :                                         conn->status = CONNECTION_BAD;
    2865                 :           0 :                                         return 0;
    2866                 :             :                                 }
    2867                 :         273 :                                 break;
    2868                 :             : 
    2869                 :             :                         default:
    2870                 :             :                                 /* Just in case we failed to set it in PQconnectPoll */
    2871                 :           0 :                                 conn->status = CONNECTION_BAD;
    2872                 :           0 :                                 return 0;
    2873                 :             :                 }
    2874                 :             : 
    2875         [ +  - ]:         546 :                 if (ret == 1)                   /* connect_timeout elapsed */
    2876                 :             :                 {
    2877                 :             :                         /*
    2878                 :             :                          * Give up on current server/address, try the next one.
    2879                 :             :                          */
    2880                 :           0 :                         conn->try_next_addr = true;
    2881                 :           0 :                         conn->status = CONNECTION_NEEDED;
    2882                 :           0 :                 }
    2883                 :             : 
    2884                 :             :                 /*
    2885                 :             :                  * Now try to advance the state machine.
    2886                 :             :                  */
    2887         [ -  + ]:         546 :                 if (conn->cancelRequest)
    2888                 :           0 :                         flag = PQcancelPoll((PGcancelConn *) conn);
    2889                 :             :                 else
    2890                 :         546 :                         flag = PQconnectPoll(conn);
    2891         [ +  + ]:         819 :         }
    2892                 :         273 : }
    2893                 :             : 
    2894                 :             : /* ----------------
    2895                 :             :  *              PQconnectPoll
    2896                 :             :  *
    2897                 :             :  * Poll an asynchronous connection.
    2898                 :             :  *
    2899                 :             :  * Returns a PostgresPollingStatusType.
    2900                 :             :  * Before calling this function, use select(2) to determine when data
    2901                 :             :  * has arrived..
    2902                 :             :  *
    2903                 :             :  * You must call PQfinish whether or not this fails.
    2904                 :             :  *
    2905                 :             :  * This function and PQconnectStart are intended to allow connections to be
    2906                 :             :  * made without blocking the execution of your program on remote I/O. However,
    2907                 :             :  * there are a number of caveats:
    2908                 :             :  *
    2909                 :             :  *       o      If you call PQtrace, ensure that the stream object into which you trace
    2910                 :             :  *              will not block.
    2911                 :             :  *       o      If you do not supply an IP address for the remote host (i.e. you
    2912                 :             :  *              supply a host name instead) then PQconnectStart will block on
    2913                 :             :  *              getaddrinfo.  You will be fine if using Unix sockets (i.e. by
    2914                 :             :  *              supplying neither a host name nor a host address).
    2915                 :             :  *       o      If your backend wants to use Kerberos authentication then you must
    2916                 :             :  *              supply both a host name and a host address, otherwise this function
    2917                 :             :  *              may block on gethostname.
    2918                 :             :  *
    2919                 :             :  * ----------------
    2920                 :             :  */
    2921                 :             : PostgresPollingStatusType
    2922                 :         952 : PQconnectPoll(PGconn *conn)
    2923                 :             : {
    2924                 :         952 :         bool            reset_connection_state_machine = false;
    2925                 :         952 :         bool            need_new_connection = false;
    2926                 :         952 :         PGresult   *res;
    2927                 :         952 :         char            sebuf[PG_STRERROR_R_BUFLEN];
    2928                 :         952 :         int                     optval;
    2929                 :             : 
    2930         [ +  - ]:         952 :         if (conn == NULL)
    2931                 :           0 :                 return PGRES_POLLING_FAILED;
    2932                 :             : 
    2933                 :             :         /* Get the new data */
    2934   [ +  +  +  -  :         952 :         switch (conn->status)
                   -  - ]
    2935                 :             :         {
    2936                 :             :                         /*
    2937                 :             :                          * We really shouldn't have been polled in these two cases, but we
    2938                 :             :                          * can handle it.
    2939                 :             :                          */
    2940                 :             :                 case CONNECTION_BAD:
    2941                 :           0 :                         return PGRES_POLLING_FAILED;
    2942                 :             :                 case CONNECTION_OK:
    2943                 :           0 :                         return PGRES_POLLING_OK;
    2944                 :             : 
    2945                 :             :                         /* These are reading states */
    2946                 :             :                 case CONNECTION_AWAITING_RESPONSE:
    2947                 :             :                 case CONNECTION_AUTH_OK:
    2948                 :             :                 case CONNECTION_CHECK_WRITABLE:
    2949                 :             :                 case CONNECTION_CONSUME:
    2950                 :             :                 case CONNECTION_CHECK_STANDBY:
    2951                 :             :                         {
    2952                 :             :                                 /* Load waiting data */
    2953                 :         318 :                                 int                     n = pqReadData(conn);
    2954                 :             : 
    2955         [ +  - ]:         318 :                                 if (n < 0)
    2956                 :           0 :                                         goto error_return;
    2957         [ +  - ]:         318 :                                 if (n == 0)
    2958                 :           0 :                                         return PGRES_POLLING_READING;
    2959                 :             : 
    2960                 :         318 :                                 break;
    2961      [ +  +  + ]:         318 :                         }
    2962                 :             : 
    2963                 :             :                         /* These are writing states, so we just proceed. */
    2964                 :             :                 case CONNECTION_STARTED:
    2965                 :             :                 case CONNECTION_MADE:
    2966                 :         316 :                         break;
    2967                 :             : 
    2968                 :             :                         /* Special cases: proceed without waiting. */
    2969                 :             :                 case CONNECTION_SSL_STARTUP:
    2970                 :             :                 case CONNECTION_NEEDED:
    2971                 :             :                 case CONNECTION_GSS_STARTUP:
    2972                 :             :                 case CONNECTION_CHECK_TARGET:
    2973                 :             :                 case CONNECTION_AUTHENTICATING:
    2974                 :         318 :                         break;
    2975                 :             : 
    2976                 :             :                 default:
    2977                 :           0 :                         libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
    2978                 :           0 :                         goto error_return;
    2979                 :         952 :         }
    2980                 :             : 
    2981                 :             : 
    2982                 :             : keep_going:                                             /* We will come back to here until there is
    2983                 :             :                                                                  * nothing left to do. */
    2984                 :             : 
    2985                 :             :         /* Time to advance to next address, or next host if no more addresses? */
    2986         [ +  + ]:        2533 :         if (conn->try_next_addr)
    2987                 :             :         {
    2988         [ +  - ]:           1 :                 if (conn->whichaddr < conn->naddr)
    2989                 :             :                 {
    2990                 :           1 :                         conn->whichaddr++;
    2991                 :           1 :                         reset_connection_state_machine = true;
    2992                 :           1 :                 }
    2993                 :             :                 else
    2994                 :           0 :                         conn->try_next_host = true;
    2995                 :           1 :                 conn->try_next_addr = false;
    2996                 :           1 :         }
    2997                 :             : 
    2998                 :             :         /* Time to advance to next connhost[] entry? */
    2999         [ +  + ]:        1903 :         if (conn->try_next_host)
    3000                 :             :         {
    3001                 :         320 :                 pg_conn_host *ch;
    3002                 :         320 :                 struct addrinfo hint;
    3003                 :         320 :                 struct addrinfo *addrlist;
    3004                 :         320 :                 int                     thisport;
    3005                 :         320 :                 int                     ret;
    3006                 :         320 :                 char            portstr[MAXPGPATH];
    3007                 :             : 
    3008         [ +  + ]:         320 :                 if (conn->whichhost + 1 < conn->nconnhost)
    3009                 :         318 :                         conn->whichhost++;
    3010                 :             :                 else
    3011                 :             :                 {
    3012                 :             :                         /*
    3013                 :             :                          * Oops, no more hosts.
    3014                 :             :                          *
    3015                 :             :                          * If we are trying to connect in "prefer-standby" mode, then drop
    3016                 :             :                          * the standby requirement and start over. Don't do this for
    3017                 :             :                          * cancel requests though, since we are certain the list of
    3018                 :             :                          * servers won't change as the target_server_type option is not
    3019                 :             :                          * applicable to those connections.
    3020                 :             :                          *
    3021                 :             :                          * Otherwise, an appropriate error message is already set up, so
    3022                 :             :                          * we just need to set the right status.
    3023                 :             :                          */
    3024         [ -  + ]:           2 :                         if (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY &&
    3025   [ #  #  #  # ]:           0 :                                 conn->nconnhost > 0 &&
    3026                 :           0 :                                 !conn->cancelRequest)
    3027                 :             :                         {
    3028                 :           0 :                                 conn->target_server_type = SERVER_TYPE_PREFER_STANDBY_PASS2;
    3029                 :           0 :                                 conn->whichhost = 0;
    3030                 :           0 :                         }
    3031                 :             :                         else
    3032                 :           2 :                                 goto error_return;
    3033                 :             :                 }
    3034                 :             : 
    3035                 :             :                 /* Drop any address info for previous host */
    3036                 :         318 :                 release_conn_addrinfo(conn);
    3037                 :             : 
    3038                 :             :                 /*
    3039                 :             :                  * Look up info for the new host.  On failure, log the problem in
    3040                 :             :                  * conn->errorMessage, then loop around to try the next host.  (Note
    3041                 :             :                  * we don't clear try_next_host until we've succeeded.)
    3042                 :             :                  */
    3043                 :         318 :                 ch = &conn->connhost[conn->whichhost];
    3044                 :             : 
    3045                 :             :                 /* Initialize hint structure */
    3046   [ +  -  +  -  :        2226 :                 MemSet(&hint, 0, sizeof(hint));
          +  -  -  +  +  
                      + ]
    3047                 :         318 :                 hint.ai_socktype = SOCK_STREAM;
    3048                 :         318 :                 hint.ai_family = AF_UNSPEC;
    3049                 :             : 
    3050                 :             :                 /* Figure out the port number we're going to use. */
    3051   [ +  -  -  + ]:         318 :                 if (ch->port == NULL || ch->port[0] == '\0')
    3052                 :           0 :                         thisport = DEF_PGPORT;
    3053                 :             :                 else
    3054                 :             :                 {
    3055         [ +  - ]:         318 :                         if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
    3056                 :           0 :                                 goto error_return;
    3057                 :             : 
    3058   [ +  +  -  + ]:         318 :                         if (thisport < 1 || thisport > 65535)
    3059                 :             :                         {
    3060                 :           1 :                                 libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
    3061                 :           1 :                                 goto keep_going;
    3062                 :             :                         }
    3063                 :             :                 }
    3064                 :         317 :                 snprintf(portstr, sizeof(portstr), "%d", thisport);
    3065                 :             : 
    3066                 :             :                 /* Use pg_getaddrinfo_all() to resolve the address */
    3067   [ -  -  -  + ]:         317 :                 switch (ch->type)
    3068                 :             :                 {
    3069                 :             :                         case CHT_HOST_NAME:
    3070                 :           0 :                                 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
    3071                 :             :                                                                                  &addrlist);
    3072   [ #  #  #  # ]:           0 :                                 if (ret || !addrlist)
    3073                 :             :                                 {
    3074                 :           0 :                                         libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
    3075                 :           0 :                                                                                         ch->host, gai_strerror(ret));
    3076                 :           0 :                                         goto keep_going;
    3077                 :             :                                 }
    3078                 :           0 :                                 break;
    3079                 :             : 
    3080                 :             :                         case CHT_HOST_ADDRESS:
    3081                 :           0 :                                 hint.ai_flags = AI_NUMERICHOST;
    3082                 :           0 :                                 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
    3083                 :             :                                                                                  &addrlist);
    3084   [ #  #  #  # ]:           0 :                                 if (ret || !addrlist)
    3085                 :             :                                 {
    3086                 :           0 :                                         libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
    3087                 :           0 :                                                                                         ch->hostaddr, gai_strerror(ret));
    3088                 :           0 :                                         goto keep_going;
    3089                 :             :                                 }
    3090                 :           0 :                                 break;
    3091                 :             : 
    3092                 :             :                         case CHT_UNIX_SOCKET:
    3093                 :         317 :                                 hint.ai_family = AF_UNIX;
    3094   [ -  +  -  + ]:         317 :                                 UNIXSOCK_PATH(portstr, thisport, ch->host);
    3095         [ -  + ]:         317 :                                 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
    3096                 :             :                                 {
    3097                 :           0 :                                         libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %zu bytes)",
    3098                 :           0 :                                                                                         portstr,
    3099                 :             :                                                                                         (UNIXSOCK_PATH_BUFLEN - 1));
    3100                 :           0 :                                         goto keep_going;
    3101                 :             :                                 }
    3102                 :             : 
    3103                 :             :                                 /*
    3104                 :             :                                  * NULL hostname tells pg_getaddrinfo_all to parse the service
    3105                 :             :                                  * name as a Unix-domain socket path.
    3106                 :             :                                  */
    3107                 :         317 :                                 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
    3108                 :             :                                                                                  &addrlist);
    3109   [ +  -  +  - ]:         317 :                                 if (ret || !addrlist)
    3110                 :             :                                 {
    3111                 :           0 :                                         libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
    3112                 :           0 :                                                                                         portstr, gai_strerror(ret));
    3113                 :           0 :                                         goto keep_going;
    3114                 :             :                                 }
    3115                 :         317 :                                 break;
    3116                 :             :                 }
    3117                 :             : 
    3118                 :             :                 /*
    3119                 :             :                  * Store a copy of the addrlist in private memory so we can perform
    3120                 :             :                  * randomization for load balancing.
    3121                 :             :                  */
    3122                 :         317 :                 ret = store_conn_addrinfo(conn, addrlist);
    3123                 :         317 :                 pg_freeaddrinfo_all(hint.ai_family, addrlist);
    3124         [ +  - ]:         317 :                 if (ret)
    3125                 :           0 :                         goto error_return;      /* message already logged */
    3126                 :             : 
    3127                 :             :                 /*
    3128                 :             :                  * If random load balancing is enabled we shuffle the addresses.
    3129                 :             :                  */
    3130         [ +  - ]:         317 :                 if (conn->load_balance_type == LOAD_BALANCE_RANDOM)
    3131                 :             :                 {
    3132                 :             :                         /*
    3133                 :             :                          * This is the "inside-out" variant of the Fisher-Yates shuffle
    3134                 :             :                          * algorithm. Notionally, we append each new value to the array
    3135                 :             :                          * and then swap it with a randomly-chosen array element (possibly
    3136                 :             :                          * including itself, else we fail to generate permutations with
    3137                 :             :                          * the last integer last).  The swap step can be optimized by
    3138                 :             :                          * combining it with the insertion.
    3139                 :             :                          *
    3140                 :             :                          * We don't need to initialize conn->prng_state here, because that
    3141                 :             :                          * already happened in pqConnectOptions2.
    3142                 :             :                          */
    3143         [ #  # ]:           0 :                         for (int i = 1; i < conn->naddr; i++)
    3144                 :             :                         {
    3145                 :           0 :                                 int                     j = pg_prng_uint64_range(&conn->prng_state, 0, i);
    3146                 :           0 :                                 AddrInfo        temp = conn->addr[j];
    3147                 :             : 
    3148                 :           0 :                                 conn->addr[j] = conn->addr[i];
    3149                 :           0 :                                 conn->addr[i] = temp;
    3150                 :           0 :                         }
    3151                 :           0 :                 }
    3152                 :             : 
    3153                 :         317 :                 reset_connection_state_machine = true;
    3154                 :         317 :                 conn->try_next_host = false;
    3155      [ +  +  + ]:         320 :         }
    3156                 :             : 
    3157                 :             :         /* Reset connection state machine? */
    3158         [ +  + ]:        1900 :         if (reset_connection_state_machine)
    3159                 :             :         {
    3160                 :             :                 /*
    3161                 :             :                  * (Re) initialize our connection control variables for a set of
    3162                 :             :                  * connection attempts to a single server address.  These variables
    3163                 :             :                  * must persist across individual connection attempts, but we must
    3164                 :             :                  * reset them when we start to consider a new server.
    3165                 :             :                  */
    3166                 :         318 :                 conn->pversion = conn->max_pversion;
    3167                 :         318 :                 conn->send_appname = true;
    3168                 :         318 :                 conn->failed_enc_methods = 0;
    3169                 :         318 :                 conn->current_enc_method = 0;
    3170                 :         318 :                 conn->allowed_enc_methods = 0;
    3171                 :         318 :                 reset_connection_state_machine = false;
    3172                 :         318 :                 need_new_connection = true;
    3173                 :         318 :         }
    3174                 :             : 
    3175                 :             :         /* Force a new connection (perhaps to the same server as before)? */
    3176         [ +  + ]:        1900 :         if (need_new_connection)
    3177                 :             :         {
    3178                 :             :                 /* Drop any existing connection */
    3179                 :         318 :                 pqDropConnection(conn, true);
    3180                 :             : 
    3181                 :             :                 /* Reset all state obtained from old server */
    3182                 :         318 :                 pqDropServerData(conn);
    3183                 :             : 
    3184                 :             :                 /* Drop any PGresult we might have, too */
    3185                 :         318 :                 conn->asyncStatus = PGASYNC_IDLE;
    3186                 :         318 :                 conn->xactStatus = PQTRANS_IDLE;
    3187                 :         318 :                 conn->pipelineStatus = PQ_PIPELINE_OFF;
    3188                 :         318 :                 pqClearAsyncResult(conn);
    3189                 :             : 
    3190                 :             :                 /* Reset conn->status to put the state machine in the right state */
    3191                 :         318 :                 conn->status = CONNECTION_NEEDED;
    3192                 :             : 
    3193                 :         318 :                 need_new_connection = false;
    3194                 :         318 :         }
    3195                 :             : 
    3196                 :             :         /*
    3197                 :             :          * Decide what to do next, if server rejects SSL or GSS negotiation, but
    3198                 :             :          * the connection is still valid.  If there are no options left, error out
    3199                 :             :          * with 'msg'.
    3200                 :             :          */
    3201                 :             : #define ENCRYPTION_NEGOTIATION_FAILED(msg) \
    3202                 :             :         do { \
    3203                 :             :                 switch (encryption_negotiation_failed(conn)) \
    3204                 :             :                 { \
    3205                 :             :                         case 0: \
    3206                 :             :                                 libpq_append_conn_error(conn, (msg)); \
    3207                 :             :                                 goto error_return; \
    3208                 :             :                         case 1: \
    3209                 :             :                                 conn->status = CONNECTION_MADE; \
    3210                 :             :                                 return PGRES_POLLING_WRITING; \
    3211                 :             :                         case 2: \
    3212                 :             :                                 need_new_connection = true; \
    3213                 :             :                                 goto keep_going; \
    3214                 :             :                 } \
    3215                 :             :         } while(0);
    3216                 :             : 
    3217                 :             :         /*
    3218                 :             :          * Decide what to do next, if connection fails.  If there are no options
    3219                 :             :          * left, return with an error.  The error message has already been written
    3220                 :             :          * to the connection's error buffer.
    3221                 :             :          */
    3222                 :             : #define CONNECTION_FAILED() \
    3223                 :             :         do { \
    3224                 :             :                 if (connection_failed(conn)) \
    3225                 :             :                 { \
    3226                 :             :                         need_new_connection = true; \
    3227                 :             :                         goto keep_going; \
    3228                 :             :                 } \
    3229                 :             :                 else \
    3230                 :             :                         goto error_return; \
    3231                 :             :         } while(0);
    3232                 :             : 
    3233                 :             :         /* Now try to advance the state machine for this connection */
    3234   [ +  +  -  -  :        1900 :         switch (conn->status)
          +  -  +  +  -  
             -  -  -  + ]
    3235                 :             :         {
    3236                 :             :                 case CONNECTION_NEEDED:
    3237                 :             :                         {
    3238                 :             :                                 /*
    3239                 :             :                                  * Try to initiate a connection to one of the addresses
    3240                 :             :                                  * returned by pg_getaddrinfo_all().  conn->whichaddr is the
    3241                 :             :                                  * next one to try.
    3242                 :             :                                  *
    3243                 :             :                                  * The extra level of braces here is historical.  It's not
    3244                 :             :                                  * worth reindenting this whole switch case to remove 'em.
    3245                 :             :                                  */
    3246                 :             :                                 {
    3247                 :         318 :                                         char            host_addr[NI_MAXHOST];
    3248                 :         318 :                                         int                     sock_type;
    3249                 :         318 :                                         AddrInfo   *addr_cur;
    3250                 :             : 
    3251                 :             :                                         /*
    3252                 :             :                                          * Advance to next possible host, if we've tried all of
    3253                 :             :                                          * the addresses for the current host.
    3254                 :             :                                          */
    3255         [ +  + ]:         318 :                                         if (conn->whichaddr == conn->naddr)
    3256                 :             :                                         {
    3257                 :           1 :                                                 conn->try_next_host = true;
    3258                 :           1 :                                                 goto keep_going;
    3259                 :             :                                         }
    3260                 :         317 :                                         addr_cur = &conn->addr[conn->whichaddr];
    3261                 :             : 
    3262                 :             :                                         /* Remember current address for possible use later */
    3263                 :         317 :                                         memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
    3264                 :             : 
    3265                 :             : #ifdef ENABLE_GSS
    3266                 :             : 
    3267                 :             :                                         /*
    3268                 :             :                                          * Before establishing the connection, check if it's
    3269                 :             :                                          * doomed to fail because gssencmode='require' but GSSAPI
    3270                 :             :                                          * is not available.
    3271                 :             :                                          */
    3272         [ +  - ]:         317 :                                         if (conn->gssencmode[0] == 'r')
    3273                 :             :                                         {
    3274         [ #  # ]:           0 :                                                 if (conn->raddr.addr.ss_family == AF_UNIX)
    3275                 :             :                                                 {
    3276                 :           0 :                                                         libpq_append_conn_error(conn,
    3277                 :             :                                                                                                         "GSSAPI encryption required but it is not supported over a local socket");
    3278                 :           0 :                                                         goto error_return;
    3279                 :             :                                                 }
    3280         [ #  # ]:           0 :                                                 if (conn->gcred == GSS_C_NO_CREDENTIAL)
    3281                 :             :                                                 {
    3282         [ #  # ]:           0 :                                                         if (!pg_GSS_have_cred_cache(&conn->gcred))
    3283                 :             :                                                         {
    3284                 :           0 :                                                                 libpq_append_conn_error(conn,
    3285                 :             :                                                                                                                 "GSSAPI encryption required but no credential cache");
    3286                 :           0 :                                                                 goto error_return;
    3287                 :             :                                                         }
    3288                 :           0 :                                                 }
    3289                 :           0 :                                         }
    3290                 :             : #endif
    3291                 :             : 
    3292                 :             :                                         /*
    3293                 :             :                                          * Choose the encryption method to try first.  Do this
    3294                 :             :                                          * before establishing the connection, so that if none of
    3295                 :             :                                          * the modes allowed by the connections options are
    3296                 :             :                                          * available, we can error out before establishing the
    3297                 :             :                                          * connection.
    3298                 :             :                                          */
    3299         [ +  - ]:         317 :                                         if (!init_allowed_encryption_methods(conn))
    3300                 :           0 :                                                 goto error_return;
    3301                 :             : 
    3302                 :             :                                         /*
    3303                 :             :                                          * Set connip, too.  Note we purposely ignore strdup
    3304                 :             :                                          * failure; not a big problem if it fails.
    3305                 :             :                                          */
    3306         [ +  - ]:         317 :                                         if (conn->connip != NULL)
    3307                 :             :                                         {
    3308                 :           0 :                                                 free(conn->connip);
    3309                 :           0 :                                                 conn->connip = NULL;
    3310                 :           0 :                                         }
    3311                 :         317 :                                         getHostaddr(conn, host_addr, NI_MAXHOST);
    3312         [ +  - ]:         317 :                                         if (host_addr[0])
    3313                 :           0 :                                                 conn->connip = strdup(host_addr);
    3314                 :             : 
    3315                 :             :                                         /* Try to create the socket */
    3316                 :         317 :                                         sock_type = SOCK_STREAM;
    3317                 :             : #ifdef SOCK_CLOEXEC
    3318                 :             : 
    3319                 :             :                                         /*
    3320                 :             :                                          * Atomically mark close-on-exec, if possible on this
    3321                 :             :                                          * platform, so that there isn't a window where a
    3322                 :             :                                          * subprogram executed by another thread inherits the
    3323                 :             :                                          * socket.  See fallback code below.
    3324                 :             :                                          */
    3325                 :             :                                         sock_type |= SOCK_CLOEXEC;
    3326                 :             : #endif
    3327                 :             : #ifdef SOCK_NONBLOCK
    3328                 :             : 
    3329                 :             :                                         /*
    3330                 :             :                                          * We might as well skip a system call for nonblocking
    3331                 :             :                                          * mode too, if we can.
    3332                 :             :                                          */
    3333                 :             :                                         sock_type |= SOCK_NONBLOCK;
    3334                 :             : #endif
    3335                 :         317 :                                         conn->sock = socket(addr_cur->family, sock_type, 0);
    3336         [ +  - ]:         317 :                                         if (conn->sock == PGINVALID_SOCKET)
    3337                 :             :                                         {
    3338                 :           0 :                                                 int                     errorno = SOCK_ERRNO;
    3339                 :             : 
    3340                 :             :                                                 /*
    3341                 :             :                                                  * Silently ignore socket() failure if we have more
    3342                 :             :                                                  * addresses to try; this reduces useless chatter in
    3343                 :             :                                                  * cases where the address list includes both IPv4 and
    3344                 :             :                                                  * IPv6 but kernel only accepts one family.
    3345                 :             :                                                  */
    3346   [ #  #  #  # ]:           0 :                                                 if (conn->whichaddr < conn->naddr ||
    3347                 :           0 :                                                         conn->whichhost + 1 < conn->nconnhost)
    3348                 :             :                                                 {
    3349                 :           0 :                                                         conn->try_next_addr = true;
    3350                 :           0 :                                                         goto keep_going;
    3351                 :             :                                                 }
    3352                 :           0 :                                                 emitHostIdentityInfo(conn, host_addr);
    3353                 :           0 :                                                 libpq_append_conn_error(conn, "could not create socket: %s",
    3354                 :           0 :                                                                                                 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
    3355                 :           0 :                                                 goto error_return;
    3356                 :           0 :                                         }
    3357                 :             : 
    3358                 :             :                                         /*
    3359                 :             :                                          * Once we've identified a target address, all errors
    3360                 :             :                                          * except the preceding socket()-failure case should be
    3361                 :             :                                          * prefixed with host-identity information.  (If the
    3362                 :             :                                          * connection succeeds, the contents of conn->errorMessage
    3363                 :             :                                          * won't matter, so this is harmless.)
    3364                 :             :                                          */
    3365                 :         317 :                                         emitHostIdentityInfo(conn, host_addr);
    3366                 :             : 
    3367                 :             :                                         /*
    3368                 :             :                                          * Select socket options: no delay of outgoing data for
    3369                 :             :                                          * TCP sockets, nonblock mode, close-on-exec.  Try the
    3370                 :             :                                          * next address if any of this fails.
    3371                 :             :                                          */
    3372         [ +  - ]:         317 :                                         if (addr_cur->family != AF_UNIX)
    3373                 :             :                                         {
    3374         [ #  # ]:           0 :                                                 if (!connectNoDelay(conn))
    3375                 :             :                                                 {
    3376                 :             :                                                         /* error message already created */
    3377                 :           0 :                                                         conn->try_next_addr = true;
    3378                 :           0 :                                                         goto keep_going;
    3379                 :             :                                                 }
    3380                 :           0 :                                         }
    3381                 :             : #ifndef SOCK_NONBLOCK
    3382         [ +  - ]:         317 :                                         if (!pg_set_noblock(conn->sock))
    3383                 :             :                                         {
    3384                 :           0 :                                                 libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
    3385                 :           0 :                                                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3386                 :           0 :                                                 conn->try_next_addr = true;
    3387                 :           0 :                                                 goto keep_going;
    3388                 :             :                                         }
    3389                 :             : #endif
    3390                 :             : 
    3391                 :             : #ifndef SOCK_CLOEXEC
    3392                 :             : #ifdef F_SETFD
    3393         [ +  - ]:         317 :                                         if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
    3394                 :             :                                         {
    3395                 :           0 :                                                 libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
    3396                 :           0 :                                                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3397                 :           0 :                                                 conn->try_next_addr = true;
    3398                 :           0 :                                                 goto keep_going;
    3399                 :             :                                         }
    3400                 :             : #endif                                                  /* F_SETFD */
    3401                 :             : #endif
    3402                 :             : 
    3403         [ +  - ]:         317 :                                         if (addr_cur->family != AF_UNIX)
    3404                 :             :                                         {
    3405                 :             : #ifndef WIN32
    3406                 :           0 :                                                 int                     on = 1;
    3407                 :             : #endif
    3408                 :           0 :                                                 int                     usekeepalives = useKeepalives(conn);
    3409                 :           0 :                                                 int                     err = 0;
    3410                 :             : 
    3411         [ #  # ]:           0 :                                                 if (usekeepalives < 0)
    3412                 :             :                                                 {
    3413                 :             :                                                         /* error is already reported */
    3414                 :           0 :                                                         err = 1;
    3415                 :           0 :                                                 }
    3416         [ #  # ]:           0 :                                                 else if (usekeepalives == 0)
    3417                 :             :                                                 {
    3418                 :             :                                                         /* Do nothing */
    3419                 :           0 :                                                 }
    3420                 :             : #ifndef WIN32
    3421                 :           0 :                                                 else if (setsockopt(conn->sock,
    3422                 :             :                                                                                         SOL_SOCKET, SO_KEEPALIVE,
    3423         [ #  # ]:           0 :                                                                                         (char *) &on, sizeof(on)) < 0)
    3424                 :             :                                                 {
    3425                 :           0 :                                                         libpq_append_conn_error(conn, "%s(%s) failed: %s",
    3426                 :             :                                                                                                         "setsockopt",
    3427                 :             :                                                                                                         "SO_KEEPALIVE",
    3428                 :           0 :                                                                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3429                 :           0 :                                                         err = 1;
    3430                 :           0 :                                                 }
    3431                 :           0 :                                                 else if (!setKeepalivesIdle(conn)
    3432         [ #  # ]:           0 :                                                                  || !setKeepalivesInterval(conn)
    3433   [ #  #  #  # ]:           0 :                                                                  || !setKeepalivesCount(conn))
    3434                 :           0 :                                                         err = 1;
    3435                 :             : #else                                                   /* WIN32 */
    3436                 :             : #ifdef SIO_KEEPALIVE_VALS
    3437                 :             :                                                 else if (!prepKeepalivesWin32(conn))
    3438                 :             :                                                         err = 1;
    3439                 :             : #endif                                                  /* SIO_KEEPALIVE_VALS */
    3440                 :             : #endif                                                  /* WIN32 */
    3441         [ #  # ]:           0 :                                                 else if (!setTCPUserTimeout(conn))
    3442                 :           0 :                                                         err = 1;
    3443                 :             : 
    3444         [ #  # ]:           0 :                                                 if (err)
    3445                 :             :                                                 {
    3446                 :           0 :                                                         conn->try_next_addr = true;
    3447                 :           0 :                                                         goto keep_going;
    3448                 :             :                                                 }
    3449         [ #  # ]:           0 :                                         }
    3450                 :             : 
    3451                 :             :                                         /*----------
    3452                 :             :                                          * We have three methods of blocking SIGPIPE during
    3453                 :             :                                          * send() calls to this socket:
    3454                 :             :                                          *
    3455                 :             :                                          *      - setsockopt(sock, SO_NOSIGPIPE)
    3456                 :             :                                          *      - send(sock, ..., MSG_NOSIGNAL)
    3457                 :             :                                          *      - setting the signal mask to SIG_IGN during send()
    3458                 :             :                                          *
    3459                 :             :                                          * The third method requires three syscalls per send,
    3460                 :             :                                          * so we prefer either of the first two, but they are
    3461                 :             :                                          * less portable.  The state is tracked in the following
    3462                 :             :                                          * members of PGconn:
    3463                 :             :                                          *
    3464                 :             :                                          * conn->sigpipe_so          - we have set up SO_NOSIGPIPE
    3465                 :             :                                          * conn->sigpipe_flag        - we're specifying MSG_NOSIGNAL
    3466                 :             :                                          *
    3467                 :             :                                          * If we can use SO_NOSIGPIPE, then set sigpipe_so here
    3468                 :             :                                          * and we're done.  Otherwise, set sigpipe_flag so that
    3469                 :             :                                          * we will try MSG_NOSIGNAL on sends.  If we get an error
    3470                 :             :                                          * with MSG_NOSIGNAL, we'll clear that flag and revert to
    3471                 :             :                                          * signal masking.
    3472                 :             :                                          *----------
    3473                 :             :                                          */
    3474                 :         317 :                                         conn->sigpipe_so = false;
    3475                 :             : #ifdef MSG_NOSIGNAL
    3476                 :         317 :                                         conn->sigpipe_flag = true;
    3477                 :             : #else
    3478                 :             :                                         conn->sigpipe_flag = false;
    3479                 :             : #endif                                                  /* MSG_NOSIGNAL */
    3480                 :             : 
    3481                 :             : #ifdef SO_NOSIGPIPE
    3482                 :         317 :                                         optval = 1;
    3483                 :         317 :                                         if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
    3484         [ -  + ]:         317 :                                                                    (char *) &optval, sizeof(optval)) == 0)
    3485                 :             :                                         {
    3486                 :         317 :                                                 conn->sigpipe_so = true;
    3487                 :         317 :                                                 conn->sigpipe_flag = false;
    3488                 :         317 :                                         }
    3489                 :             : #endif                                                  /* SO_NOSIGPIPE */
    3490                 :             : 
    3491                 :             :                                         /*
    3492                 :             :                                          * Start/make connection.  This should not block, since we
    3493                 :             :                                          * are in nonblock mode.  If it does, well, too bad.
    3494                 :             :                                          */
    3495                 :         634 :                                         if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
    3496   [ +  +  +  + ]:         634 :                                                                 addr_cur->addr.salen) < 0)
    3497                 :             :                                         {
    3498   [ +  -  -  + ]:           1 :                                                 if (SOCK_ERRNO == EINPROGRESS ||
    3499                 :             : #ifdef WIN32
    3500                 :             :                                                         SOCK_ERRNO == EWOULDBLOCK ||
    3501                 :             : #endif
    3502                 :           1 :                                                         SOCK_ERRNO == EINTR)
    3503                 :             :                                                 {
    3504                 :             :                                                         /*
    3505                 :             :                                                          * This is fine - we're in non-blocking mode, and
    3506                 :             :                                                          * the connection is in progress.  Tell caller to
    3507                 :             :                                                          * wait for write-ready on socket.
    3508                 :             :                                                          */
    3509                 :           0 :                                                         conn->status = CONNECTION_STARTED;
    3510                 :           0 :                                                         return PGRES_POLLING_WRITING;
    3511                 :             :                                                 }
    3512                 :             :                                                 /* otherwise, trouble */
    3513                 :           1 :                                         }
    3514                 :             :                                         else
    3515                 :             :                                         {
    3516                 :             :                                                 /*
    3517                 :             :                                                  * Hm, we're connected already --- seems the "nonblock
    3518                 :             :                                                  * connection" wasn't.  Advance the state machine and
    3519                 :             :                                                  * go do the next stuff.
    3520                 :             :                                                  */
    3521                 :         316 :                                                 conn->status = CONNECTION_STARTED;
    3522                 :         316 :                                                 goto keep_going;
    3523                 :             :                                         }
    3524                 :             : 
    3525                 :             :                                         /*
    3526                 :             :                                          * This connection failed.  Add the error report to
    3527                 :             :                                          * conn->errorMessage, then try the next address if any.
    3528                 :             :                                          */
    3529                 :           1 :                                         connectFailureMessage(conn, SOCK_ERRNO);
    3530                 :           1 :                                         conn->try_next_addr = true;
    3531                 :           1 :                                         goto keep_going;
    3532                 :         318 :                                 }
    3533                 :             :                         }
    3534                 :             : 
    3535                 :             :                 case CONNECTION_STARTED:
    3536                 :             :                         {
    3537                 :         316 :                                 socklen_t       optlen = sizeof(optval);
    3538                 :             : 
    3539                 :             :                                 /*
    3540                 :             :                                  * Write ready, since we've made it here, so the connection
    3541                 :             :                                  * has been made ... or has failed.
    3542                 :             :                                  */
    3543                 :             : 
    3544                 :             :                                 /*
    3545                 :             :                                  * Now check (using getsockopt) that there is not an error
    3546                 :             :                                  * state waiting for us on the socket.
    3547                 :             :                                  */
    3548                 :             : 
    3549                 :         316 :                                 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
    3550         [ +  - ]:         316 :                                                            (char *) &optval, &optlen) == -1)
    3551                 :             :                                 {
    3552                 :           0 :                                         libpq_append_conn_error(conn, "could not get socket error status: %s",
    3553                 :           0 :                                                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3554                 :           0 :                                         goto error_return;
    3555                 :             :                                 }
    3556         [ -  + ]:         316 :                                 else if (optval != 0)
    3557                 :             :                                 {
    3558                 :             :                                         /*
    3559                 :             :                                          * When using a nonblocking connect, we will typically see
    3560                 :             :                                          * connect failures at this point, so provide a friendly
    3561                 :             :                                          * error message.
    3562                 :             :                                          */
    3563                 :           0 :                                         connectFailureMessage(conn, optval);
    3564                 :             : 
    3565                 :             :                                         /*
    3566                 :             :                                          * Try the next address if any, just as in the case where
    3567                 :             :                                          * connect() returned failure immediately.
    3568                 :             :                                          */
    3569                 :           0 :                                         conn->try_next_addr = true;
    3570                 :           0 :                                         goto keep_going;
    3571                 :             :                                 }
    3572                 :             : 
    3573                 :             :                                 /* Fill in the client address */
    3574                 :         316 :                                 conn->laddr.salen = sizeof(conn->laddr.addr);
    3575                 :         632 :                                 if (getsockname(conn->sock,
    3576                 :         316 :                                                                 (struct sockaddr *) &conn->laddr.addr,
    3577   [ +  -  +  - ]:         632 :                                                                 &conn->laddr.salen) < 0)
    3578                 :             :                                 {
    3579                 :           0 :                                         libpq_append_conn_error(conn, "could not get client address from socket: %s",
    3580                 :           0 :                                                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3581                 :           0 :                                         goto error_return;
    3582                 :             :                                 }
    3583                 :             : 
    3584                 :             :                                 /*
    3585                 :             :                                  * Implement requirepeer check, if requested and it's a
    3586                 :             :                                  * Unix-domain socket.
    3587                 :             :                                  */
    3588   [ -  +  #  #  :         316 :                                 if (conn->requirepeer && conn->requirepeer[0] &&
                   #  # ]
    3589                 :           0 :                                         conn->raddr.addr.ss_family == AF_UNIX)
    3590                 :             :                                 {
    3591                 :             : #ifndef WIN32
    3592                 :           0 :                                         char       *remote_username;
    3593                 :             : #endif
    3594                 :           0 :                                         uid_t           uid;
    3595                 :           0 :                                         gid_t           gid;
    3596                 :             : 
    3597                 :           0 :                                         errno = 0;
    3598         [ #  # ]:           0 :                                         if (getpeereid(conn->sock, &uid, &gid) != 0)
    3599                 :             :                                         {
    3600                 :             :                                                 /*
    3601                 :             :                                                  * Provide special error message if getpeereid is a
    3602                 :             :                                                  * stub
    3603                 :             :                                                  */
    3604         [ #  # ]:           0 :                                                 if (errno == ENOSYS)
    3605                 :           0 :                                                         libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
    3606                 :             :                                                 else
    3607                 :           0 :                                                         libpq_append_conn_error(conn, "could not get peer credentials: %s",
    3608                 :           0 :                                                                                                         strerror_r(errno, sebuf, sizeof(sebuf)));
    3609                 :           0 :                                                 goto error_return;
    3610                 :             :                                         }
    3611                 :             : 
    3612                 :             : #ifndef WIN32
    3613                 :           0 :                                         remote_username = pg_fe_getusername(uid,
    3614                 :           0 :                                                                                                                 &conn->errorMessage);
    3615         [ #  # ]:           0 :                                         if (remote_username == NULL)
    3616                 :           0 :                                                 goto error_return;      /* message already logged */
    3617                 :             : 
    3618         [ #  # ]:           0 :                                         if (strcmp(remote_username, conn->requirepeer) != 0)
    3619                 :             :                                         {
    3620                 :           0 :                                                 libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
    3621                 :           0 :                                                                                                 conn->requirepeer, remote_username);
    3622                 :           0 :                                                 free(remote_username);
    3623                 :           0 :                                                 goto error_return;
    3624                 :             :                                         }
    3625                 :           0 :                                         free(remote_username);
    3626                 :             : #else                                                   /* WIN32 */
    3627                 :             :                                         /* should have failed with ENOSYS above */
    3628                 :             :                                         Assert(false);
    3629                 :             : #endif                                                  /* WIN32 */
    3630         [ #  # ]:           0 :                                 }
    3631                 :             : 
    3632                 :             :                                 /*
    3633                 :             :                                  * Make sure we can write before advancing to next step.
    3634                 :             :                                  */
    3635                 :         316 :                                 conn->status = CONNECTION_MADE;
    3636                 :         316 :                                 return PGRES_POLLING_WRITING;
    3637                 :         316 :                         }
    3638                 :             : 
    3639                 :             :                 case CONNECTION_MADE:
    3640                 :             :                         {
    3641                 :         316 :                                 char       *startpacket;
    3642                 :         316 :                                 int                     packetlen;
    3643                 :             : 
    3644                 :             : #ifdef ENABLE_GSS
    3645                 :             : 
    3646                 :             :                                 /*
    3647                 :             :                                  * If GSSAPI encryption is enabled, send a packet to the
    3648                 :             :                                  * server asking for GSSAPI Encryption and proceed with GSSAPI
    3649                 :             :                                  * handshake.  We will come back here after GSSAPI encryption
    3650                 :             :                                  * has been established, with conn->gctx set.
    3651                 :             :                                  */
    3652   [ -  +  #  # ]:         316 :                                 if (conn->current_enc_method == ENC_GSSAPI && !conn->gctx)
    3653                 :             :                                 {
    3654                 :           0 :                                         ProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);
    3655                 :             : 
    3656         [ #  # ]:           0 :                                         if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
    3657                 :             :                                         {
    3658                 :           0 :                                                 libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
    3659                 :           0 :                                                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3660                 :           0 :                                                 goto error_return;
    3661                 :             :                                         }
    3662                 :             : 
    3663                 :             :                                         /* Ok, wait for response */
    3664                 :           0 :                                         conn->status = CONNECTION_GSS_STARTUP;
    3665                 :           0 :                                         return PGRES_POLLING_READING;
    3666                 :           0 :                                 }
    3667                 :             : #endif
    3668                 :             : 
    3669                 :             : #ifdef USE_SSL
    3670                 :             : 
    3671                 :             :                                 /*
    3672                 :             :                                  * If SSL is enabled, start the SSL negotiation. We will come
    3673                 :             :                                  * back here after SSL encryption has been established, with
    3674                 :             :                                  * ssl_in_use set.
    3675                 :             :                                  */
    3676   [ -  +  #  # ]:         316 :                                 if (conn->current_enc_method == ENC_SSL && !conn->ssl_in_use)
    3677                 :             :                                 {
    3678                 :             :                                         /*
    3679                 :             :                                          * If traditional postgres SSL negotiation is used, send
    3680                 :             :                                          * the SSL request.  In direct negotiation, jump straight
    3681                 :             :                                          * into the SSL handshake.
    3682                 :             :                                          */
    3683         [ #  # ]:           0 :                                         if (conn->sslnegotiation[0] == 'p')
    3684                 :             :                                         {
    3685                 :           0 :                                                 ProtocolVersion pv;
    3686                 :             : 
    3687                 :             :                                                 /*
    3688                 :             :                                                  * Send the SSL request packet.
    3689                 :             :                                                  *
    3690                 :             :                                                  * Theoretically, this could block, but it really
    3691                 :             :                                                  * shouldn't since we only got here if the socket is
    3692                 :             :                                                  * write-ready.
    3693                 :             :                                                  */
    3694                 :           0 :                                                 pv = pg_hton32(NEGOTIATE_SSL_CODE);
    3695         [ #  # ]:           0 :                                                 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
    3696                 :             :                                                 {
    3697                 :           0 :                                                         libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
    3698                 :           0 :                                                                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3699                 :           0 :                                                         goto error_return;
    3700                 :             :                                                 }
    3701                 :             :                                                 /* Ok, wait for response */
    3702                 :           0 :                                                 conn->status = CONNECTION_SSL_STARTUP;
    3703                 :           0 :                                                 return PGRES_POLLING_READING;
    3704                 :           0 :                                         }
    3705                 :             :                                         else
    3706                 :             :                                         {
    3707         [ #  # ]:           0 :                                                 Assert(conn->sslnegotiation[0] == 'd');
    3708                 :           0 :                                                 conn->status = CONNECTION_SSL_STARTUP;
    3709                 :           0 :                                                 return PGRES_POLLING_WRITING;
    3710                 :             :                                         }
    3711                 :             :                                 }
    3712                 :             : #endif                                                  /* USE_SSL */
    3713                 :             : 
    3714                 :             :                                 /*
    3715                 :             :                                  * For cancel requests this is as far as we need to go in the
    3716                 :             :                                  * connection establishment. Now we can actually send our
    3717                 :             :                                  * cancellation request.
    3718                 :             :                                  */
    3719         [ -  + ]:         316 :                                 if (conn->cancelRequest)
    3720                 :             :                                 {
    3721         [ #  # ]:           0 :                                         if (PQsendCancelRequest(conn) != STATUS_OK)
    3722                 :             :                                         {
    3723                 :           0 :                                                 libpq_append_conn_error(conn, "could not send cancel packet: %s",
    3724                 :           0 :                                                                                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3725                 :           0 :                                                 goto error_return;
    3726                 :             :                                         }
    3727                 :           0 :                                         conn->status = CONNECTION_AWAITING_RESPONSE;
    3728                 :           0 :                                         return PGRES_POLLING_READING;
    3729                 :             :                                 }
    3730                 :             : 
    3731                 :             :                                 /*
    3732                 :             :                                  * We have now established encryption, or we are happy to
    3733                 :             :                                  * proceed without.
    3734                 :             :                                  */
    3735                 :             : 
    3736                 :             :                                 /* Build the startup packet. */
    3737                 :         316 :                                 startpacket = pqBuildStartupPacket3(conn, &packetlen,
    3738                 :             :                                                                                                         EnvironmentOptions);
    3739         [ -  + ]:         316 :                                 if (!startpacket)
    3740                 :             :                                 {
    3741                 :           0 :                                         libpq_append_conn_error(conn, "out of memory");
    3742                 :           0 :                                         goto error_return;
    3743                 :             :                                 }
    3744                 :             : 
    3745                 :             :                                 /*
    3746                 :             :                                  * Send the startup packet.
    3747                 :             :                                  *
    3748                 :             :                                  * Theoretically, this could block, but it really shouldn't
    3749                 :             :                                  * since we only got here if the socket is write-ready.
    3750                 :             :                                  */
    3751         [ -  + ]:         316 :                                 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
    3752                 :             :                                 {
    3753                 :           0 :                                         libpq_append_conn_error(conn, "could not send startup packet: %s",
    3754                 :           0 :                                                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    3755                 :           0 :                                         free(startpacket);
    3756                 :           0 :                                         goto error_return;
    3757                 :             :                                 }
    3758                 :             : 
    3759                 :         316 :                                 free(startpacket);
    3760                 :             : 
    3761                 :         316 :                                 conn->status = CONNECTION_AWAITING_RESPONSE;
    3762                 :         316 :                                 return PGRES_POLLING_READING;
    3763                 :         316 :                         }
    3764                 :             : 
    3765                 :             :                         /*
    3766                 :             :                          * Handle SSL negotiation: wait for postmaster messages and
    3767                 :             :                          * respond as necessary.
    3768                 :             :                          */
    3769                 :             :                 case CONNECTION_SSL_STARTUP:
    3770                 :             :                         {
    3771                 :             : #ifdef USE_SSL
    3772                 :           0 :                                 PostgresPollingStatusType pollres;
    3773                 :             : 
    3774                 :             :                                 /*
    3775                 :             :                                  * On first time through with traditional SSL negotiation, get
    3776                 :             :                                  * the postmaster's response to our SSLRequest packet. With
    3777                 :             :                                  * sslnegotiation='direct', go straight to initiating SSL.
    3778                 :             :                                  */
    3779   [ #  #  #  # ]:           0 :                                 if (!conn->ssl_in_use && conn->sslnegotiation[0] == 'p')
    3780                 :             :                                 {
    3781                 :             :                                         /*
    3782                 :             :                                          * We use pqReadData here since it has the logic to
    3783                 :             :                                          * distinguish no-data-yet from connection closure. Since
    3784                 :             :                                          * conn->ssl isn't set, a plain recv() will occur.
    3785                 :             :                                          */
    3786                 :           0 :                                         char            SSLok;
    3787                 :           0 :                                         int                     rdresult;
    3788                 :             : 
    3789                 :           0 :                                         rdresult = pqReadData(conn);
    3790         [ #  # ]:           0 :                                         if (rdresult < 0)
    3791                 :             :                                         {
    3792                 :             :                                                 /* errorMessage is already filled in */
    3793                 :           0 :                                                 goto error_return;
    3794                 :             :                                         }
    3795         [ #  # ]:           0 :                                         if (rdresult == 0)
    3796                 :             :                                         {
    3797                 :             :                                                 /* caller failed to wait for data */
    3798                 :           0 :                                                 return PGRES_POLLING_READING;
    3799                 :             :                                         }
    3800         [ #  # ]:           0 :                                         if (pqGetc(&SSLok, conn) < 0)
    3801                 :             :                                         {
    3802                 :             :                                                 /* should not happen really */
    3803                 :           0 :                                                 return PGRES_POLLING_READING;
    3804                 :             :                                         }
    3805         [ #  # ]:           0 :                                         if (SSLok == 'S')
    3806                 :             :                                         {
    3807         [ #  # ]:           0 :                                                 if (conn->Pfdebug)
    3808                 :           0 :                                                         pqTraceOutputCharResponse(conn, "SSLResponse",
    3809                 :           0 :                                                                                                           SSLok);
    3810                 :             :                                                 /* mark byte consumed */
    3811                 :           0 :                                                 conn->inStart = conn->inCursor;
    3812                 :           0 :                                         }
    3813         [ #  # ]:           0 :                                         else if (SSLok == 'N')
    3814                 :             :                                         {
    3815         [ #  # ]:           0 :                                                 if (conn->Pfdebug)
    3816                 :           0 :                                                         pqTraceOutputCharResponse(conn, "SSLResponse",
    3817                 :           0 :                                                                                                           SSLok);
    3818                 :             :                                                 /* mark byte consumed */
    3819                 :           0 :                                                 conn->inStart = conn->inCursor;
    3820                 :             : 
    3821                 :             :                                                 /*
    3822                 :             :                                                  * The connection is still valid, so if it's OK to
    3823                 :             :                                                  * continue without SSL, we can proceed using this
    3824                 :             :                                                  * connection.  Otherwise return with an error.
    3825                 :             :                                                  */
    3826   [ #  #  #  # ]:           0 :                                                 ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server does not support SSL, but SSL was required"));
    3827                 :           0 :                                         }
    3828         [ #  # ]:           0 :                                         else if (SSLok == 'E')
    3829                 :             :                                         {
    3830                 :             :                                                 /*
    3831                 :             :                                                  * Server failure of some sort, such as failure to
    3832                 :             :                                                  * fork a backend process.  Don't bother retrieving
    3833                 :             :                                                  * the error message; we should not trust it as the
    3834                 :             :                                                  * server has not been authenticated yet.
    3835                 :             :                                                  */
    3836                 :           0 :                                                 libpq_append_conn_error(conn, "server sent an error response during SSL exchange");
    3837                 :           0 :                                                 goto error_return;
    3838                 :             :                                         }
    3839                 :             :                                         else
    3840                 :             :                                         {
    3841                 :           0 :                                                 libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
    3842                 :           0 :                                                                                                 SSLok);
    3843                 :           0 :                                                 goto error_return;
    3844                 :             :                                         }
    3845         [ #  # ]:           0 :                                 }
    3846                 :             : 
    3847                 :             :                                 /*
    3848                 :             :                                  * Begin or continue the SSL negotiation process.
    3849                 :             :                                  */
    3850                 :           0 :                                 pollres = pqsecure_open_client(conn);
    3851         [ #  # ]:           0 :                                 if (pollres == PGRES_POLLING_OK)
    3852                 :             :                                 {
    3853                 :             :                                         /*
    3854                 :             :                                          * At this point we should have no data already buffered.
    3855                 :             :                                          * If we do, it was received before we performed the SSL
    3856                 :             :                                          * handshake, so it wasn't encrypted and indeed may have
    3857                 :             :                                          * been injected by a man-in-the-middle.
    3858                 :             :                                          */
    3859         [ #  # ]:           0 :                                         if (conn->inCursor != conn->inEnd)
    3860                 :             :                                         {
    3861                 :           0 :                                                 libpq_append_conn_error(conn, "received unencrypted data after SSL response");
    3862                 :           0 :                                                 goto error_return;
    3863                 :             :                                         }
    3864                 :             : 
    3865                 :             :                                         /* SSL handshake done, ready to send startup packet */
    3866                 :           0 :                                         conn->status = CONNECTION_MADE;
    3867                 :           0 :                                         return PGRES_POLLING_WRITING;
    3868                 :             :                                 }
    3869         [ #  # ]:           0 :                                 if (pollres == PGRES_POLLING_FAILED)
    3870                 :             :                                 {
    3871                 :             :                                         /*
    3872                 :             :                                          * SSL handshake failed.  We will retry with a plaintext
    3873                 :             :                                          * connection, if permitted by sslmode.
    3874                 :             :                                          */
    3875         [ #  # ]:           0 :                                         CONNECTION_FAILED();
    3876                 :           0 :                                 }
    3877                 :             :                                 /* Else, return POLLING_READING or POLLING_WRITING status */
    3878                 :           0 :                                 return pollres;
    3879                 :             : #else                                                   /* !USE_SSL */
    3880                 :             :                                 /* can't get here */
    3881                 :             :                                 goto error_return;
    3882                 :             : #endif                                                  /* USE_SSL */
    3883                 :           0 :                         }
    3884                 :             : 
    3885                 :             :                 case CONNECTION_GSS_STARTUP:
    3886                 :             :                         {
    3887                 :             : #ifdef ENABLE_GSS
    3888                 :           0 :                                 PostgresPollingStatusType pollres;
    3889                 :             : 
    3890                 :             :                                 /*
    3891                 :             :                                  * If we haven't yet, get the postmaster's response to our
    3892                 :             :                                  * negotiation packet
    3893                 :             :                                  */
    3894         [ #  # ]:           0 :                                 if (!conn->gctx)
    3895                 :             :                                 {
    3896                 :           0 :                                         char            gss_ok;
    3897                 :           0 :                                         int                     rdresult = pqReadData(conn);
    3898                 :             : 
    3899         [ #  # ]:           0 :                                         if (rdresult < 0)
    3900                 :             :                                                 /* pqReadData fills in error message */
    3901                 :           0 :                                                 goto error_return;
    3902         [ #  # ]:           0 :                                         else if (rdresult == 0)
    3903                 :             :                                                 /* caller failed to wait for data */
    3904                 :           0 :                                                 return PGRES_POLLING_READING;
    3905         [ #  # ]:           0 :                                         if (pqGetc(&gss_ok, conn) < 0)
    3906                 :             :                                                 /* shouldn't happen... */
    3907                 :           0 :                                                 return PGRES_POLLING_READING;
    3908                 :             : 
    3909         [ #  # ]:           0 :                                         if (gss_ok == 'E')
    3910                 :             :                                         {
    3911                 :             :                                                 /*
    3912                 :             :                                                  * Server failure of some sort, possibly protocol
    3913                 :             :                                                  * version support failure.  Don't bother retrieving
    3914                 :             :                                                  * the error message; we should not trust it anyway as
    3915                 :             :                                                  * the server has not authenticated yet.
    3916                 :             :                                                  *
    3917                 :             :                                                  * Note that unlike on an error response to
    3918                 :             :                                                  * SSLRequest, we allow falling back to SSL or
    3919                 :             :                                                  * plaintext connection here.  GSS support was
    3920                 :             :                                                  * introduced in PostgreSQL version 12, so an error
    3921                 :             :                                                  * response might mean that we are connecting to a
    3922                 :             :                                                  * pre-v12 server.
    3923                 :             :                                                  */
    3924                 :           0 :                                                 libpq_append_conn_error(conn, "server sent an error response during GSS encryption exchange");
    3925         [ #  # ]:           0 :                                                 CONNECTION_FAILED();
    3926                 :           0 :                                         }
    3927                 :             : 
    3928                 :             :                                         /* mark byte consumed */
    3929                 :           0 :                                         conn->inStart = conn->inCursor;
    3930                 :             : 
    3931         [ #  # ]:           0 :                                         if (gss_ok == 'N')
    3932                 :             :                                         {
    3933         [ #  # ]:           0 :                                                 if (conn->Pfdebug)
    3934                 :           0 :                                                         pqTraceOutputCharResponse(conn, "GSSENCResponse",
    3935                 :           0 :                                                                                                           gss_ok);
    3936                 :             : 
    3937                 :             :                                                 /*
    3938                 :             :                                                  * The connection is still valid, so if it's OK to
    3939                 :             :                                                  * continue without GSS, we can proceed using this
    3940                 :             :                                                  * connection.  Otherwise return with an error.
    3941                 :             :                                                  */
    3942   [ #  #  #  # ]:           0 :                                                 ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server doesn't support GSSAPI encryption, but it was required"));
    3943                 :           0 :                                         }
    3944         [ #  # ]:           0 :                                         else if (gss_ok != 'G')
    3945                 :             :                                         {
    3946                 :           0 :                                                 libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
    3947                 :           0 :                                                                                                 gss_ok);
    3948                 :           0 :                                                 goto error_return;
    3949                 :             :                                         }
    3950                 :             : 
    3951         [ #  # ]:           0 :                                         if (conn->Pfdebug)
    3952                 :           0 :                                                 pqTraceOutputCharResponse(conn, "GSSENCResponse",
    3953                 :           0 :                                                                                                   gss_ok);
    3954         [ #  # ]:           0 :                                 }
    3955                 :             : 
    3956                 :             :                                 /* Begin or continue GSSAPI negotiation */
    3957                 :           0 :                                 pollres = pqsecure_open_gss(conn);
    3958         [ #  # ]:           0 :                                 if (pollres == PGRES_POLLING_OK)
    3959                 :             :                                 {
    3960                 :             :                                         /*
    3961                 :             :                                          * At this point we should have no data already buffered.
    3962                 :             :                                          * If we do, it was received before we performed the GSS
    3963                 :             :                                          * handshake, so it wasn't encrypted and indeed may have
    3964                 :             :                                          * been injected by a man-in-the-middle.
    3965                 :             :                                          */
    3966         [ #  # ]:           0 :                                         if (conn->inCursor != conn->inEnd)
    3967                 :             :                                         {
    3968                 :           0 :                                                 libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
    3969                 :           0 :                                                 goto error_return;
    3970                 :             :                                         }
    3971                 :             : 
    3972                 :             :                                         /* All set for startup packet */
    3973                 :           0 :                                         conn->status = CONNECTION_MADE;
    3974                 :           0 :                                         return PGRES_POLLING_WRITING;
    3975                 :             :                                 }
    3976         [ #  # ]:           0 :                                 else if (pollres == PGRES_POLLING_FAILED)
    3977                 :             :                                 {
    3978                 :             :                                         /*
    3979                 :             :                                          * GSS handshake failed.  We will retry with an SSL or
    3980                 :             :                                          * plaintext connection, if permitted by the options.
    3981                 :             :                                          */
    3982         [ #  # ]:           0 :                                         CONNECTION_FAILED();
    3983                 :           0 :                                 }
    3984                 :             :                                 /* Else, return POLLING_READING or POLLING_WRITING status */
    3985                 :           0 :                                 return pollres;
    3986                 :             : #else                                                   /* !ENABLE_GSS */
    3987                 :             :                                 /* unreachable */
    3988                 :             :                                 goto error_return;
    3989                 :             : #endif                                                  /* ENABLE_GSS */
    3990                 :           0 :                         }
    3991                 :             : 
    3992                 :             :                         /*
    3993                 :             :                          * Handle authentication exchange: wait for postmaster messages
    3994                 :             :                          * and respond as necessary.
    3995                 :             :                          */
    3996                 :             :                 case CONNECTION_AWAITING_RESPONSE:
    3997                 :             :                         {
    3998                 :         316 :                                 char            beresp;
    3999                 :         316 :                                 int                     msgLength;
    4000                 :         316 :                                 int                     avail;
    4001                 :         316 :                                 AuthRequest areq;
    4002                 :         316 :                                 int                     res;
    4003                 :         316 :                                 bool            async;
    4004                 :             : 
    4005                 :             :                                 /*
    4006                 :             :                                  * Scan the message from current point (note that if we find
    4007                 :             :                                  * the message is incomplete, we will return without advancing
    4008                 :             :                                  * inStart, and resume here next time).
    4009                 :             :                                  */
    4010                 :         316 :                                 conn->inCursor = conn->inStart;
    4011                 :             : 
    4012                 :             :                                 /* Read type byte */
    4013         [ -  + ]:         316 :                                 if (pqGetc(&beresp, conn))
    4014                 :             :                                 {
    4015                 :             :                                         /* We'll come back when there is more data */
    4016                 :           0 :                                         return PGRES_POLLING_READING;
    4017                 :             :                                 }
    4018                 :             : 
    4019                 :             :                                 /*
    4020                 :             :                                  * Validate message type: we expect only an authentication
    4021                 :             :                                  * request, NegotiateProtocolVersion, or an error here.
    4022                 :             :                                  * Anything else probably means it's not Postgres on the other
    4023                 :             :                                  * end at all.
    4024                 :             :                                  */
    4025         [ -  + ]:         316 :                                 if (beresp != PqMsg_AuthenticationRequest &&
    4026   [ #  #  #  # ]:           0 :                                         beresp != PqMsg_ErrorResponse &&
    4027                 :           0 :                                         beresp != PqMsg_NegotiateProtocolVersion)
    4028                 :             :                                 {
    4029                 :           0 :                                         libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
    4030                 :           0 :                                                                                         beresp);
    4031                 :           0 :                                         goto error_return;
    4032                 :             :                                 }
    4033                 :             : 
    4034                 :             :                                 /* Read message length word */
    4035         [ -  + ]:         316 :                                 if (pqGetInt(&msgLength, 4, conn))
    4036                 :             :                                 {
    4037                 :             :                                         /* We'll come back when there is more data */
    4038                 :           0 :                                         return PGRES_POLLING_READING;
    4039                 :             :                                 }
    4040                 :             : 
    4041                 :             :                                 /*
    4042                 :             :                                  * Try to validate message length before using it.
    4043                 :             :                                  *
    4044                 :             :                                  * Authentication requests can't be very large, although GSS
    4045                 :             :                                  * auth requests may not be that small.  Same for
    4046                 :             :                                  * NegotiateProtocolVersion.
    4047                 :             :                                  *
    4048                 :             :                                  * Errors can be a little larger, but not huge.  If we see a
    4049                 :             :                                  * large apparent length in an error, it means we're really
    4050                 :             :                                  * talking to a pre-3.0-protocol server; cope.  (Before
    4051                 :             :                                  * version 14, the server also used the old protocol for
    4052                 :             :                                  * errors that happened before processing the startup packet.)
    4053                 :             :                                  */
    4054   [ +  -  -  + ]:         632 :                                 if (beresp == PqMsg_AuthenticationRequest &&
    4055         [ +  - ]:         316 :                                         (msgLength < 8 || msgLength > 2000))
    4056                 :             :                                 {
    4057                 :           0 :                                         libpq_append_conn_error(conn, "received invalid authentication request");
    4058                 :           0 :                                         goto error_return;
    4059                 :             :                                 }
    4060   [ -  +  #  # ]:         316 :                                 if (beresp == PqMsg_NegotiateProtocolVersion &&
    4061         [ #  # ]:           0 :                                         (msgLength < 8 || msgLength > 2000))
    4062                 :             :                                 {
    4063                 :           0 :                                         libpq_append_conn_error(conn, "received invalid protocol negotiation message");
    4064                 :           0 :                                         goto error_return;
    4065                 :             :                                 }
    4066                 :             : 
    4067                 :             : #define MAX_ERRLEN 30000
    4068   [ -  +  #  # ]:         316 :                                 if (beresp == PqMsg_ErrorResponse &&
    4069         [ #  # ]:           0 :                                         (msgLength < 8 || msgLength > MAX_ERRLEN))
    4070                 :             :                                 {
    4071                 :             :                                         /* Handle error from a pre-3.0 server */
    4072                 :           0 :                                         conn->inCursor = conn->inStart + 1; /* reread data */
    4073         [ #  # ]:           0 :                                         if (pqGets_append(&conn->errorMessage, conn))
    4074                 :             :                                         {
    4075                 :             :                                                 /*
    4076                 :             :                                                  * We may not have authenticated the server yet, so
    4077                 :             :                                                  * don't let the buffer grow forever.
    4078                 :             :                                                  */
    4079                 :           0 :                                                 avail = conn->inEnd - conn->inCursor;
    4080         [ #  # ]:           0 :                                                 if (avail > MAX_ERRLEN)
    4081                 :             :                                                 {
    4082                 :           0 :                                                         libpq_append_conn_error(conn, "received invalid error message");
    4083                 :           0 :                                                         goto error_return;
    4084                 :             :                                                 }
    4085                 :             : 
    4086                 :             :                                                 /* We'll come back when there is more data */
    4087                 :           0 :                                                 return PGRES_POLLING_READING;
    4088                 :             :                                         }
    4089                 :             :                                         /* OK, we read the message; mark data consumed */
    4090                 :           0 :                                         pqParseDone(conn, conn->inCursor);
    4091                 :             : 
    4092                 :             :                                         /*
    4093                 :             :                                          * Before 7.2, the postmaster didn't always end its
    4094                 :             :                                          * messages with a newline, so add one if needed to
    4095                 :             :                                          * conform to libpq conventions.
    4096                 :             :                                          */
    4097   [ #  #  #  # ]:           0 :                                         if (conn->errorMessage.len == 0 ||
    4098                 :           0 :                                                 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
    4099                 :             :                                         {
    4100                 :           0 :                                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
    4101                 :           0 :                                         }
    4102                 :             : 
    4103                 :           0 :                                         goto error_return;
    4104                 :             :                                 }
    4105                 :             : #undef MAX_ERRLEN
    4106                 :             : 
    4107                 :             :                                 /*
    4108                 :             :                                  * Can't process if message body isn't all here yet.
    4109                 :             :                                  *
    4110                 :             :                                  * After this check passes, any further EOF during parsing
    4111                 :             :                                  * implies that the server sent a bad/truncated message.
    4112                 :             :                                  * Reading more bytes won't help in that case, so don't return
    4113                 :             :                                  * PGRES_POLLING_READING after this point.
    4114                 :             :                                  */
    4115                 :         316 :                                 msgLength -= 4;
    4116                 :         316 :                                 avail = conn->inEnd - conn->inCursor;
    4117         [ -  + ]:         316 :                                 if (avail < msgLength)
    4118                 :             :                                 {
    4119                 :             :                                         /*
    4120                 :             :                                          * Before returning, try to enlarge the input buffer if
    4121                 :             :                                          * needed to hold the whole message; see notes in
    4122                 :             :                                          * pqParseInput3.
    4123                 :             :                                          */
    4124   [ #  #  #  # ]:           0 :                                         if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
    4125                 :           0 :                                                                                          conn))
    4126                 :           0 :                                                 goto error_return;
    4127                 :             :                                         /* We'll come back when there is more data */
    4128                 :           0 :                                         return PGRES_POLLING_READING;
    4129                 :             :                                 }
    4130                 :             : 
    4131                 :             :                                 /* Handle errors. */
    4132         [ -  + ]:         316 :                                 if (beresp == PqMsg_ErrorResponse)
    4133                 :             :                                 {
    4134         [ #  # ]:           0 :                                         if (pqGetErrorNotice3(conn, true))
    4135                 :             :                                         {
    4136                 :           0 :                                                 libpq_append_conn_error(conn, "received invalid error message");
    4137                 :           0 :                                                 goto error_return;
    4138                 :             :                                         }
    4139                 :             :                                         /* OK, we read the message; mark data consumed */
    4140                 :           0 :                                         pqParseDone(conn, conn->inCursor);
    4141                 :             : 
    4142                 :             :                                         /*
    4143                 :             :                                          * If error is "cannot connect now", try the next host if
    4144                 :             :                                          * any (but we don't want to consider additional addresses
    4145                 :             :                                          * for this host, nor is there much point in changing SSL
    4146                 :             :                                          * or GSS mode).  This is helpful when dealing with
    4147                 :             :                                          * standby servers that might not be in hot-standby state.
    4148                 :             :                                          */
    4149                 :           0 :                                         if (strcmp(conn->last_sqlstate,
    4150         [ #  # ]:           0 :                                                            ERRCODE_CANNOT_CONNECT_NOW) == 0)
    4151                 :             :                                         {
    4152                 :           0 :                                                 conn->try_next_host = true;
    4153                 :           0 :                                                 goto keep_going;
    4154                 :             :                                         }
    4155                 :             : 
    4156                 :             :                                         /* Check to see if we should mention pgpassfile */
    4157                 :           0 :                                         pgpassfileWarning(conn);
    4158                 :             : 
    4159         [ #  # ]:           0 :                                         CONNECTION_FAILED();
    4160                 :           0 :                                 }
    4161                 :             :                                 /* Handle NegotiateProtocolVersion */
    4162         [ -  + ]:         316 :                                 else if (beresp == PqMsg_NegotiateProtocolVersion)
    4163                 :             :                                 {
    4164         [ #  # ]:           0 :                                         if (conn->pversion_negotiated)
    4165                 :             :                                         {
    4166                 :           0 :                                                 libpq_append_conn_error(conn, "received duplicate protocol negotiation message");
    4167                 :           0 :                                                 goto error_return;
    4168                 :             :                                         }
    4169         [ #  # ]:           0 :                                         if (pqGetNegotiateProtocolVersion3(conn))
    4170                 :             :                                         {
    4171                 :             :                                                 /* pqGetNegotiateProtocolVersion3 set error already */
    4172                 :           0 :                                                 goto error_return;
    4173                 :             :                                         }
    4174                 :           0 :                                         conn->pversion_negotiated = true;
    4175                 :             : 
    4176                 :             :                                         /* OK, we read the message; mark data consumed */
    4177                 :           0 :                                         pqParseDone(conn, conn->inCursor);
    4178                 :             : 
    4179                 :           0 :                                         goto keep_going;
    4180                 :             :                                 }
    4181                 :             : 
    4182                 :             :                                 /* It is an authentication request. */
    4183                 :         316 :                                 conn->auth_req_received = true;
    4184                 :             : 
    4185                 :             :                                 /* Get the type of request. */
    4186         [ -  + ]:         316 :                                 if (pqGetInt((int *) &areq, 4, conn))
    4187                 :             :                                 {
    4188                 :             :                                         /* can't happen because we checked the length already */
    4189                 :           0 :                                         libpq_append_conn_error(conn, "received invalid authentication request");
    4190                 :           0 :                                         goto error_return;
    4191                 :             :                                 }
    4192                 :         316 :                                 msgLength -= 4;
    4193                 :             : 
    4194                 :             :                                 /*
    4195                 :             :                                  * Process the rest of the authentication request message, and
    4196                 :             :                                  * respond to it if necessary.
    4197                 :             :                                  *
    4198                 :             :                                  * Note that conn->pghost must be non-NULL if we are going to
    4199                 :             :                                  * avoid the Kerberos code doing a hostname look-up.
    4200                 :             :                                  */
    4201                 :         316 :                                 res = pg_fe_sendauth(areq, msgLength, conn, &async);
    4202                 :             : 
    4203   [ -  +  #  # ]:         316 :                                 if (async && (res == STATUS_OK))
    4204                 :             :                                 {
    4205                 :             :                                         /*
    4206                 :             :                                          * We'll come back later once we're ready to respond.
    4207                 :             :                                          * Don't consume the request yet.
    4208                 :             :                                          */
    4209                 :           0 :                                         conn->status = CONNECTION_AUTHENTICATING;
    4210                 :           0 :                                         goto keep_going;
    4211                 :             :                                 }
    4212                 :             : 
    4213                 :             :                                 /*
    4214                 :             :                                  * OK, we have processed the message; mark data consumed.  We
    4215                 :             :                                  * don't call pqParseDone here because we already traced this
    4216                 :             :                                  * message inside pg_fe_sendauth.
    4217                 :             :                                  */
    4218                 :         316 :                                 conn->inStart = conn->inCursor;
    4219                 :             : 
    4220         [ -  + ]:         316 :                                 if (res != STATUS_OK)
    4221                 :             :                                 {
    4222                 :             :                                         /*
    4223                 :             :                                          * OAuth connections may perform two-step discovery, where
    4224                 :             :                                          * the first connection is a dummy.
    4225                 :             :                                          */
    4226   [ #  #  #  # ]:           0 :                                         if (conn->sasl == &pg_oauth_mech && conn->oauth_want_retry)
    4227                 :             :                                         {
    4228                 :           0 :                                                 need_new_connection = true;
    4229                 :           0 :                                                 goto keep_going;
    4230                 :             :                                         }
    4231                 :             : 
    4232                 :           0 :                                         goto error_return;
    4233                 :             :                                 }
    4234                 :             : 
    4235                 :             :                                 /*
    4236                 :             :                                  * Just make sure that any data sent by pg_fe_sendauth is
    4237                 :             :                                  * flushed out.  Although this theoretically could block, it
    4238                 :             :                                  * really shouldn't since we don't send large auth responses.
    4239                 :             :                                  */
    4240         [ -  + ]:         316 :                                 if (pqFlush(conn))
    4241                 :           0 :                                         goto error_return;
    4242                 :             : 
    4243         [ +  - ]:         316 :                                 if (areq == AUTH_REQ_OK)
    4244                 :             :                                 {
    4245                 :             :                                         /* We are done with authentication exchange */
    4246                 :         316 :                                         conn->status = CONNECTION_AUTH_OK;
    4247                 :             : 
    4248                 :             :                                         /*
    4249                 :             :                                          * Set asyncStatus so that PQgetResult will think that
    4250                 :             :                                          * what comes back next is the result of a query.  See
    4251                 :             :                                          * below.
    4252                 :             :                                          */
    4253                 :         316 :                                         conn->asyncStatus = PGASYNC_BUSY;
    4254                 :         316 :                                 }
    4255                 :             : 
    4256                 :             :                                 /* Look to see if we have more data yet. */
    4257                 :         316 :                                 goto keep_going;
    4258                 :         316 :                         }
    4259                 :             : 
    4260                 :             :                 case CONNECTION_AUTHENTICATING:
    4261                 :             :                         {
    4262                 :           0 :                                 PostgresPollingStatusType status;
    4263                 :             : 
    4264   [ #  #  #  # ]:           0 :                                 if (!conn->async_auth || !conn->cleanup_async_auth)
    4265                 :             :                                 {
    4266                 :             :                                         /* programmer error; should not happen */
    4267                 :           0 :                                         libpq_append_conn_error(conn,
    4268                 :             :                                                                                         "internal error: async authentication has no handler");
    4269                 :           0 :                                         goto error_return;
    4270                 :             :                                 }
    4271                 :             : 
    4272                 :             :                                 /* Drive some external authentication work. */
    4273                 :           0 :                                 status = conn->async_auth(conn);
    4274                 :             : 
    4275         [ #  # ]:           0 :                                 if (status == PGRES_POLLING_FAILED)
    4276                 :           0 :                                         goto error_return;
    4277                 :             : 
    4278         [ #  # ]:           0 :                                 if (status == PGRES_POLLING_OK)
    4279                 :             :                                 {
    4280                 :             :                                         /* Done. Tear down the async implementation. */
    4281                 :           0 :                                         conn->cleanup_async_auth(conn);
    4282                 :           0 :                                         conn->cleanup_async_auth = NULL;
    4283                 :             : 
    4284                 :             :                                         /*
    4285                 :             :                                          * Cleanup must unset altsock, both as an indication that
    4286                 :             :                                          * it's been released, and to stop pqSocketCheck from
    4287                 :             :                                          * looking at the wrong socket after async auth is done.
    4288                 :             :                                          */
    4289         [ #  # ]:           0 :                                         if (conn->altsock != PGINVALID_SOCKET)
    4290                 :             :                                         {
    4291                 :           0 :                                                 Assert(false);
    4292                 :             :                                                 libpq_append_conn_error(conn,
    4293                 :             :                                                                                                 "internal error: async cleanup did not release polling socket");
    4294                 :             :                                                 goto error_return;
    4295                 :             :                                         }
    4296                 :             : 
    4297                 :             :                                         /*
    4298                 :             :                                          * Reenter the authentication exchange with the server. We
    4299                 :             :                                          * didn't consume the message that started external
    4300                 :             :                                          * authentication, so it'll be reprocessed as if we just
    4301                 :             :                                          * received it.
    4302                 :             :                                          */
    4303                 :           0 :                                         conn->status = CONNECTION_AWAITING_RESPONSE;
    4304                 :             : 
    4305                 :           0 :                                         goto keep_going;
    4306                 :             :                                 }
    4307                 :             : 
    4308                 :             :                                 /*
    4309                 :             :                                  * Caller needs to poll some more. conn->async_auth() should
    4310                 :             :                                  * have assigned an altsock to poll on.
    4311                 :             :                                  */
    4312         [ #  # ]:           0 :                                 if (conn->altsock == PGINVALID_SOCKET)
    4313                 :             :                                 {
    4314                 :           0 :                                         Assert(false);
    4315                 :             :                                         libpq_append_conn_error(conn,
    4316                 :             :                                                                                         "internal error: async authentication did not set a socket for polling");
    4317                 :             :                                         goto error_return;
    4318                 :             :                                 }
    4319                 :             : 
    4320                 :           0 :                                 return status;
    4321                 :           0 :                         }
    4322                 :             : 
    4323                 :             :                 case CONNECTION_AUTH_OK:
    4324                 :             :                         {
    4325                 :             :                                 /*
    4326                 :             :                                  * Now we expect to hear from the backend. A ReadyForQuery
    4327                 :             :                                  * message indicates that startup is successful, but we might
    4328                 :             :                                  * also get an Error message indicating failure. (Notice
    4329                 :             :                                  * messages indicating nonfatal warnings are also allowed by
    4330                 :             :                                  * the protocol, as are ParameterStatus and BackendKeyData
    4331                 :             :                                  * messages.) Easiest way to handle this is to let
    4332                 :             :                                  * PQgetResult() read the messages. We just have to fake it
    4333                 :             :                                  * out about the state of the connection, by setting
    4334                 :             :                                  * asyncStatus = PGASYNC_BUSY (done above).
    4335                 :             :                                  */
    4336                 :             : 
    4337         [ +  + ]:         318 :                                 if (PQisBusy(conn))
    4338                 :           2 :                                         return PGRES_POLLING_READING;
    4339                 :             : 
    4340                 :         316 :                                 res = PQgetResult(conn);
    4341                 :             : 
    4342                 :             :                                 /*
    4343                 :             :                                  * NULL return indicating we have gone to IDLE state is
    4344                 :             :                                  * expected
    4345                 :             :                                  */
    4346         [ -  + ]:         316 :                                 if (res)
    4347                 :             :                                 {
    4348         [ #  # ]:           0 :                                         if (res->resultStatus != PGRES_FATAL_ERROR)
    4349                 :           0 :                                                 libpq_append_conn_error(conn, "unexpected message from server during startup");
    4350   [ #  #  #  # ]:           0 :                                         else if (conn->send_appname &&
    4351         [ #  # ]:           0 :                                                          (conn->appname || conn->fbappname))
    4352                 :             :                                         {
    4353                 :             :                                                 /*
    4354                 :             :                                                  * If we tried to send application_name, check to see
    4355                 :             :                                                  * if the error is about that --- pre-9.0 servers will
    4356                 :             :                                                  * reject it at this stage of the process.  If so,
    4357                 :             :                                                  * close the connection and retry without sending
    4358                 :             :                                                  * application_name.  We could possibly get a false
    4359                 :             :                                                  * SQLSTATE match here and retry uselessly, but there
    4360                 :             :                                                  * seems no great harm in that; we'll just get the
    4361                 :             :                                                  * same error again if it's unrelated.
    4362                 :             :                                                  */
    4363                 :           0 :                                                 const char *sqlstate;
    4364                 :             : 
    4365                 :           0 :                                                 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
    4366   [ #  #  #  # ]:           0 :                                                 if (sqlstate &&
    4367                 :           0 :                                                         strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
    4368                 :             :                                                 {
    4369                 :           0 :                                                         PQclear(res);
    4370                 :           0 :                                                         conn->send_appname = false;
    4371                 :           0 :                                                         need_new_connection = true;
    4372                 :           0 :                                                         goto keep_going;
    4373                 :             :                                                 }
    4374      [ #  #  # ]:           0 :                                         }
    4375                 :             : 
    4376                 :             :                                         /*
    4377                 :             :                                          * if the resultStatus is FATAL, then conn->errorMessage
    4378                 :             :                                          * already has a copy of the error; needn't copy it back.
    4379                 :             :                                          * But add a newline if it's not there already, since
    4380                 :             :                                          * postmaster error messages may not have one.
    4381                 :             :                                          */
    4382   [ #  #  #  # ]:           0 :                                         if (conn->errorMessage.len <= 0 ||
    4383                 :           0 :                                                 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
    4384                 :           0 :                                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
    4385                 :           0 :                                         PQclear(res);
    4386                 :           0 :                                         goto error_return;
    4387                 :             :                                 }
    4388                 :             : 
    4389                 :             :                                 /* Almost there now ... */
    4390                 :         316 :                                 conn->status = CONNECTION_CHECK_TARGET;
    4391                 :         316 :                                 goto keep_going;
    4392                 :             :                         }
    4393                 :             : 
    4394                 :             :                 case CONNECTION_CHECK_TARGET:
    4395                 :             :                         {
    4396                 :             :                                 /*
    4397                 :             :                                  * If a read-write, read-only, primary, or standby connection
    4398                 :             :                                  * is required, see if we have one.
    4399                 :             :                                  */
    4400   [ +  -  -  + ]:         316 :                                 if (conn->target_server_type == SERVER_TYPE_READ_WRITE ||
    4401                 :         316 :                                         conn->target_server_type == SERVER_TYPE_READ_ONLY)
    4402                 :             :                                 {
    4403                 :           0 :                                         bool            read_only_server;
    4404                 :             : 
    4405                 :             :                                         /*
    4406                 :             :                                          * If the server didn't report
    4407                 :             :                                          * "default_transaction_read_only" or "in_hot_standby" at
    4408                 :             :                                          * startup, we must determine its state by sending the
    4409                 :             :                                          * query "SHOW transaction_read_only".  This GUC exists in
    4410                 :             :                                          * all server versions that support 3.0 protocol.
    4411                 :             :                                          */
    4412   [ #  #  #  # ]:           0 :                                         if (conn->default_transaction_read_only == PG_BOOL_UNKNOWN ||
    4413                 :           0 :                                                 conn->in_hot_standby == PG_BOOL_UNKNOWN)
    4414                 :             :                                         {
    4415                 :             :                                                 /*
    4416                 :             :                                                  * We use PQsendQueryContinue so that
    4417                 :             :                                                  * conn->errorMessage does not get cleared.  We need
    4418                 :             :                                                  * to preserve any error messages related to previous
    4419                 :             :                                                  * hosts we have tried and failed to connect to.
    4420                 :             :                                                  */
    4421                 :           0 :                                                 conn->status = CONNECTION_OK;
    4422         [ #  # ]:           0 :                                                 if (!PQsendQueryContinue(conn,
    4423                 :             :                                                                                                  "SHOW transaction_read_only"))
    4424                 :           0 :                                                         goto error_return;
    4425                 :             :                                                 /* We'll return to this state when we have the answer */
    4426                 :           0 :                                                 conn->status = CONNECTION_CHECK_WRITABLE;
    4427                 :           0 :                                                 return PGRES_POLLING_READING;
    4428                 :             :                                         }
    4429                 :             : 
    4430                 :             :                                         /* OK, we can make the test */
    4431                 :           0 :                                         read_only_server =
    4432         [ #  # ]:           0 :                                                 (conn->default_transaction_read_only == PG_BOOL_YES ||
    4433                 :           0 :                                                  conn->in_hot_standby == PG_BOOL_YES);
    4434                 :             : 
    4435   [ #  #  #  # ]:           0 :                                         if ((conn->target_server_type == SERVER_TYPE_READ_WRITE) ?
    4436                 :           0 :                                                 read_only_server : !read_only_server)
    4437                 :             :                                         {
    4438                 :             :                                                 /* Wrong server state, reject and try the next host */
    4439         [ #  # ]:           0 :                                                 if (conn->target_server_type == SERVER_TYPE_READ_WRITE)
    4440                 :           0 :                                                         libpq_append_conn_error(conn, "session is read-only");
    4441                 :             :                                                 else
    4442                 :           0 :                                                         libpq_append_conn_error(conn, "session is not read-only");
    4443                 :             : 
    4444                 :             :                                                 /* Close connection politely. */
    4445                 :           0 :                                                 conn->status = CONNECTION_OK;
    4446                 :           0 :                                                 sendTerminateConn(conn);
    4447                 :             : 
    4448                 :             :                                                 /*
    4449                 :             :                                                  * Try next host if any, but we don't want to consider
    4450                 :             :                                                  * additional addresses for this host.
    4451                 :             :                                                  */
    4452                 :           0 :                                                 conn->try_next_host = true;
    4453                 :           0 :                                                 goto keep_going;
    4454                 :             :                                         }
    4455         [ #  # ]:           0 :                                 }
    4456         [ +  - ]:         316 :                                 else if (conn->target_server_type == SERVER_TYPE_PRIMARY ||
    4457   [ +  -  -  + ]:         316 :                                                  conn->target_server_type == SERVER_TYPE_STANDBY ||
    4458                 :         316 :                                                  conn->target_server_type == SERVER_TYPE_PREFER_STANDBY)
    4459                 :             :                                 {
    4460                 :             :                                         /*
    4461                 :             :                                          * If the server didn't report "in_hot_standby" at
    4462                 :             :                                          * startup, we must determine its state by sending the
    4463                 :             :                                          * query "SELECT pg_catalog.pg_is_in_recovery()".  Servers
    4464                 :             :                                          * before 9.0 don't have that function, but by the same
    4465                 :             :                                          * token they don't have any standby mode, so we may just
    4466                 :             :                                          * assume the result.
    4467                 :             :                                          */
    4468         [ #  # ]:           0 :                                         if (conn->sversion < 90000)
    4469                 :           0 :                                                 conn->in_hot_standby = PG_BOOL_NO;
    4470                 :             : 
    4471         [ #  # ]:           0 :                                         if (conn->in_hot_standby == PG_BOOL_UNKNOWN)
    4472                 :             :                                         {
    4473                 :             :                                                 /*
    4474                 :             :                                                  * We use PQsendQueryContinue so that
    4475                 :             :                                                  * conn->errorMessage does not get cleared.  We need
    4476                 :             :                                                  * to preserve any error messages related to previous
    4477                 :             :                                                  * hosts we have tried and failed to connect to.
    4478                 :             :                                                  */
    4479                 :           0 :                                                 conn->status = CONNECTION_OK;
    4480         [ #  # ]:           0 :                                                 if (!PQsendQueryContinue(conn,
    4481                 :             :                                                                                                  "SELECT pg_catalog.pg_is_in_recovery()"))
    4482                 :           0 :                                                         goto error_return;
    4483                 :             :                                                 /* We'll return to this state when we have the answer */
    4484                 :           0 :                                                 conn->status = CONNECTION_CHECK_STANDBY;
    4485                 :           0 :                                                 return PGRES_POLLING_READING;
    4486                 :             :                                         }
    4487                 :             : 
    4488                 :             :                                         /* OK, we can make the test */
    4489   [ #  #  #  # ]:           0 :                                         if ((conn->target_server_type == SERVER_TYPE_PRIMARY) ?
    4490                 :           0 :                                                 (conn->in_hot_standby == PG_BOOL_YES) :
    4491                 :           0 :                                                 (conn->in_hot_standby == PG_BOOL_NO))
    4492                 :             :                                         {
    4493                 :             :                                                 /* Wrong server state, reject and try the next host */
    4494         [ #  # ]:           0 :                                                 if (conn->target_server_type == SERVER_TYPE_PRIMARY)
    4495                 :           0 :                                                         libpq_append_conn_error(conn, "server is in hot standby mode");
    4496                 :             :                                                 else
    4497                 :           0 :                                                         libpq_append_conn_error(conn, "server is not in hot standby mode");
    4498                 :             : 
    4499                 :             :                                                 /* Close connection politely. */
    4500                 :           0 :                                                 conn->status = CONNECTION_OK;
    4501                 :           0 :                                                 sendTerminateConn(conn);
    4502                 :             : 
    4503                 :             :                                                 /*
    4504                 :             :                                                  * Try next host if any, but we don't want to consider
    4505                 :             :                                                  * additional addresses for this host.
    4506                 :             :                                                  */
    4507                 :           0 :                                                 conn->try_next_host = true;
    4508                 :           0 :                                                 goto keep_going;
    4509                 :             :                                         }
    4510                 :           0 :                                 }
    4511                 :             : 
    4512                 :             :                                 /* Don't hold onto any OAuth tokens longer than necessary. */
    4513                 :         316 :                                 pqClearOAuthToken(conn);
    4514                 :             : 
    4515                 :             :                                 /*
    4516                 :             :                                  * For non cancel requests we can release the address list
    4517                 :             :                                  * now. For cancel requests we never actually resolve
    4518                 :             :                                  * addresses and instead the addrinfo exists for the lifetime
    4519                 :             :                                  * of the connection.
    4520                 :             :                                  */
    4521         [ -  + ]:         316 :                                 if (!conn->cancelRequest)
    4522                 :         316 :                                         release_conn_addrinfo(conn);
    4523                 :             : 
    4524                 :             :                                 /*
    4525                 :             :                                  * Contents of conn->errorMessage are no longer interesting
    4526                 :             :                                  * (and it seems some clients expect it to be empty after a
    4527                 :             :                                  * successful connection).
    4528                 :             :                                  */
    4529                 :         316 :                                 pqClearConnErrorState(conn);
    4530                 :             : 
    4531                 :             :                                 /* We are open for business! */
    4532                 :         316 :                                 conn->status = CONNECTION_OK;
    4533                 :         316 :                                 return PGRES_POLLING_OK;
    4534                 :             :                         }
    4535                 :             : 
    4536                 :             :                 case CONNECTION_CONSUME:
    4537                 :             :                         {
    4538                 :             :                                 /*
    4539                 :             :                                  * This state just makes sure the connection is idle after
    4540                 :             :                                  * we've obtained the result of a SHOW or SELECT query.  Once
    4541                 :             :                                  * we're clear, return to CONNECTION_CHECK_TARGET state to
    4542                 :             :                                  * decide what to do next.  We must transiently set status =
    4543                 :             :                                  * CONNECTION_OK in order to use the result-consuming
    4544                 :             :                                  * subroutines.
    4545                 :             :                                  */
    4546                 :           0 :                                 conn->status = CONNECTION_OK;
    4547         [ #  # ]:           0 :                                 if (!PQconsumeInput(conn))
    4548                 :           0 :                                         goto error_return;
    4549                 :             : 
    4550         [ #  # ]:           0 :                                 if (PQisBusy(conn))
    4551                 :             :                                 {
    4552                 :           0 :                                         conn->status = CONNECTION_CONSUME;
    4553                 :           0 :                                         return PGRES_POLLING_READING;
    4554                 :             :                                 }
    4555                 :             : 
    4556                 :             :                                 /* Call PQgetResult() again until we get a NULL result */
    4557                 :           0 :                                 res = PQgetResult(conn);
    4558         [ #  # ]:           0 :                                 if (res != NULL)
    4559                 :             :                                 {
    4560                 :           0 :                                         PQclear(res);
    4561                 :           0 :                                         conn->status = CONNECTION_CONSUME;
    4562                 :           0 :                                         return PGRES_POLLING_READING;
    4563                 :             :                                 }
    4564                 :             : 
    4565                 :           0 :                                 conn->status = CONNECTION_CHECK_TARGET;
    4566                 :           0 :                                 goto keep_going;
    4567                 :             :                         }
    4568                 :             : 
    4569                 :             :                 case CONNECTION_CHECK_WRITABLE:
    4570                 :             :                         {
    4571                 :             :                                 /*
    4572                 :             :                                  * Waiting for result of "SHOW transaction_read_only".  We
    4573                 :             :                                  * must transiently set status = CONNECTION_OK in order to use
    4574                 :             :                                  * the result-consuming subroutines.
    4575                 :             :                                  */
    4576                 :           0 :                                 conn->status = CONNECTION_OK;
    4577         [ #  # ]:           0 :                                 if (!PQconsumeInput(conn))
    4578                 :           0 :                                         goto error_return;
    4579                 :             : 
    4580         [ #  # ]:           0 :                                 if (PQisBusy(conn))
    4581                 :             :                                 {
    4582                 :           0 :                                         conn->status = CONNECTION_CHECK_WRITABLE;
    4583                 :           0 :                                         return PGRES_POLLING_READING;
    4584                 :             :                                 }
    4585                 :             : 
    4586                 :           0 :                                 res = PQgetResult(conn);
    4587   [ #  #  #  #  :           0 :                                 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
                   #  # ]
    4588                 :           0 :                                         PQntuples(res) == 1)
    4589                 :             :                                 {
    4590                 :           0 :                                         char       *val = PQgetvalue(res, 0, 0);
    4591                 :             : 
    4592                 :             :                                         /*
    4593                 :             :                                          * "transaction_read_only = on" proves that at least one
    4594                 :             :                                          * of default_transaction_read_only and in_hot_standby is
    4595                 :             :                                          * on, but we don't actually know which.  We don't care
    4596                 :             :                                          * though for the purpose of identifying a read-only
    4597                 :             :                                          * session, so satisfy the CONNECTION_CHECK_TARGET code by
    4598                 :             :                                          * claiming they are both on.  On the other hand, if it's
    4599                 :             :                                          * a read-write session, they are certainly both off.
    4600                 :             :                                          */
    4601         [ #  # ]:           0 :                                         if (strncmp(val, "on", 2) == 0)
    4602                 :             :                                         {
    4603                 :           0 :                                                 conn->default_transaction_read_only = PG_BOOL_YES;
    4604                 :           0 :                                                 conn->in_hot_standby = PG_BOOL_YES;
    4605                 :           0 :                                         }
    4606                 :             :                                         else
    4607                 :             :                                         {
    4608                 :           0 :                                                 conn->default_transaction_read_only = PG_BOOL_NO;
    4609                 :           0 :                                                 conn->in_hot_standby = PG_BOOL_NO;
    4610                 :             :                                         }
    4611                 :           0 :                                         PQclear(res);
    4612                 :             : 
    4613                 :             :                                         /* Finish reading messages before continuing */
    4614                 :           0 :                                         conn->status = CONNECTION_CONSUME;
    4615                 :             :                                         goto keep_going;
    4616                 :           0 :                                 }
    4617                 :             : 
    4618                 :             :                                 /* Something went wrong with "SHOW transaction_read_only". */
    4619                 :           0 :                                 PQclear(res);
    4620                 :             : 
    4621                 :             :                                 /* Append error report to conn->errorMessage. */
    4622                 :           0 :                                 libpq_append_conn_error(conn, "\"%s\" failed",
    4623                 :             :                                                                                 "SHOW transaction_read_only");
    4624                 :             : 
    4625                 :             :                                 /* Close connection politely. */
    4626                 :           0 :                                 conn->status = CONNECTION_OK;
    4627                 :           0 :                                 sendTerminateConn(conn);
    4628                 :             : 
    4629                 :             :                                 /* Try next host. */
    4630                 :           0 :                                 conn->try_next_host = true;
    4631                 :           0 :                                 goto keep_going;
    4632                 :             :                         }
    4633                 :             : 
    4634                 :             :                 case CONNECTION_CHECK_STANDBY:
    4635                 :             :                         {
    4636                 :             :                                 /*
    4637                 :             :                                  * Waiting for result of "SELECT pg_is_in_recovery()".  We
    4638                 :             :                                  * must transiently set status = CONNECTION_OK in order to use
    4639                 :             :                                  * the result-consuming subroutines.
    4640                 :             :                                  */
    4641                 :           0 :                                 conn->status = CONNECTION_OK;
    4642         [ #  # ]:           0 :                                 if (!PQconsumeInput(conn))
    4643                 :           0 :                                         goto error_return;
    4644                 :             : 
    4645         [ #  # ]:           0 :                                 if (PQisBusy(conn))
    4646                 :             :                                 {
    4647                 :           0 :                                         conn->status = CONNECTION_CHECK_STANDBY;
    4648                 :           0 :                                         return PGRES_POLLING_READING;
    4649                 :             :                                 }
    4650                 :             : 
    4651                 :           0 :                                 res = PQgetResult(conn);
    4652   [ #  #  #  #  :           0 :                                 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
                   #  # ]
    4653                 :           0 :                                         PQntuples(res) == 1)
    4654                 :             :                                 {
    4655                 :           0 :                                         char       *val = PQgetvalue(res, 0, 0);
    4656                 :             : 
    4657         [ #  # ]:           0 :                                         if (strncmp(val, "t", 1) == 0)
    4658                 :           0 :                                                 conn->in_hot_standby = PG_BOOL_YES;
    4659                 :             :                                         else
    4660                 :           0 :                                                 conn->in_hot_standby = PG_BOOL_NO;
    4661                 :           0 :                                         PQclear(res);
    4662                 :             : 
    4663                 :             :                                         /* Finish reading messages before continuing */
    4664                 :           0 :                                         conn->status = CONNECTION_CONSUME;
    4665                 :             :                                         goto keep_going;
    4666                 :           0 :                                 }
    4667                 :             : 
    4668                 :             :                                 /* Something went wrong with "SELECT pg_is_in_recovery()". */
    4669                 :           0 :                                 PQclear(res);
    4670                 :             : 
    4671                 :             :                                 /* Append error report to conn->errorMessage. */
    4672                 :           0 :                                 libpq_append_conn_error(conn, "\"%s\" failed",
    4673                 :             :                                                                                 "SELECT pg_is_in_recovery()");
    4674                 :             : 
    4675                 :             :                                 /* Close connection politely. */
    4676                 :           0 :                                 conn->status = CONNECTION_OK;
    4677                 :           0 :                                 sendTerminateConn(conn);
    4678                 :             : 
    4679                 :             :                                 /* Try next host. */
    4680                 :           0 :                                 conn->try_next_host = true;
    4681                 :           0 :                                 goto keep_going;
    4682                 :             :                         }
    4683                 :             : 
    4684                 :             :                 default:
    4685                 :           0 :                         libpq_append_conn_error(conn,
    4686                 :             :                                                                         "invalid connection state %d, probably indicative of memory corruption",
    4687                 :           0 :                                                                         conn->status);
    4688                 :           0 :                         goto error_return;
    4689                 :             :         }
    4690                 :             : 
    4691                 :             :         /* Unreachable */
    4692                 :             : 
    4693                 :             : error_return:
    4694                 :             : 
    4695                 :             :         /*
    4696                 :             :          * We used to close the socket at this point, but that makes it awkward
    4697                 :             :          * for those above us if they wish to remove this socket from their own
    4698                 :             :          * records (an fd_set for example).  We'll just have this socket closed
    4699                 :             :          * when PQfinish is called (which is compulsory even after an error, since
    4700                 :             :          * the connection structure must be freed).
    4701                 :             :          */
    4702                 :           2 :         conn->status = CONNECTION_BAD;
    4703                 :           2 :         return PGRES_POLLING_FAILED;
    4704                 :         950 : }
    4705                 :             : 
    4706                 :             : /*
    4707                 :             :  * Initialize the state machine for negotiating encryption
    4708                 :             :  */
    4709                 :             : static bool
    4710                 :         317 : init_allowed_encryption_methods(PGconn *conn)
    4711                 :             : {
    4712         [ -  + ]:         317 :         if (conn->raddr.addr.ss_family == AF_UNIX)
    4713                 :             :         {
    4714                 :             :                 /* Don't request SSL or GSSAPI over Unix sockets */
    4715                 :         317 :                 conn->allowed_enc_methods &= ~(ENC_SSL | ENC_GSSAPI);
    4716                 :             : 
    4717                 :             :                 /*
    4718                 :             :                  * XXX: we probably should not do this. sslmode=require works
    4719                 :             :                  * differently
    4720                 :             :                  */
    4721         [ -  + ]:         317 :                 if (conn->gssencmode[0] == 'r')
    4722                 :             :                 {
    4723                 :           0 :                         libpq_append_conn_error(conn,
    4724                 :             :                                                                         "GSSAPI encryption required but it is not supported over a local socket");
    4725                 :           0 :                         conn->allowed_enc_methods = 0;
    4726                 :           0 :                         conn->current_enc_method = ENC_ERROR;
    4727                 :           0 :                         return false;
    4728                 :             :                 }
    4729                 :             : 
    4730                 :         317 :                 conn->allowed_enc_methods = ENC_PLAINTEXT;
    4731                 :         317 :                 conn->current_enc_method = ENC_PLAINTEXT;
    4732                 :         317 :                 return true;
    4733                 :             :         }
    4734                 :             : 
    4735                 :             :         /* initialize based on sslmode and gssencmode */
    4736                 :           0 :         conn->allowed_enc_methods = 0;
    4737                 :             : 
    4738                 :             : #ifdef USE_SSL
    4739                 :             :         /* sslmode anything but 'disable', and GSSAPI not required */
    4740   [ #  #  #  # ]:           0 :         if (conn->sslmode[0] != 'd' && conn->gssencmode[0] != 'r')
    4741                 :             :         {
    4742                 :           0 :                 conn->allowed_enc_methods |= ENC_SSL;
    4743                 :           0 :         }
    4744                 :             : #endif
    4745                 :             : 
    4746                 :             : #ifdef ENABLE_GSS
    4747         [ #  # ]:           0 :         if (conn->gssencmode[0] != 'd')
    4748                 :           0 :                 conn->allowed_enc_methods |= ENC_GSSAPI;
    4749                 :             : #endif
    4750                 :             : 
    4751   [ #  #  #  #  :           0 :         if ((conn->sslmode[0] == 'd' || conn->sslmode[0] == 'p' || conn->sslmode[0] == 'a') &&
                   #  # ]
    4752         [ #  # ]:           0 :                 (conn->gssencmode[0] == 'd' || conn->gssencmode[0] == 'p'))
    4753                 :             :         {
    4754                 :           0 :                 conn->allowed_enc_methods |= ENC_PLAINTEXT;
    4755                 :           0 :         }
    4756                 :             : 
    4757                 :           0 :         return select_next_encryption_method(conn, false);
    4758                 :         317 : }
    4759                 :             : 
    4760                 :             : /*
    4761                 :             :  * Out-of-line portion of the ENCRYPTION_NEGOTIATION_FAILED() macro in the
    4762                 :             :  * PQconnectPoll state machine.
    4763                 :             :  *
    4764                 :             :  * Return value:
    4765                 :             :  *  0: connection failed and we are out of encryption methods to try. return an error
    4766                 :             :  *  1: Retry with next connection method. The TCP connection is still valid and in
    4767                 :             :  *     known state, so we can proceed with the negotiating next method without
    4768                 :             :  *     reconnecting.
    4769                 :             :  *  2: Disconnect, and retry with next connection method.
    4770                 :             :  *
    4771                 :             :  * conn->current_enc_method is updated to the next method to try.
    4772                 :             :  */
    4773                 :             : #if defined(USE_SSL) || defined(ENABLE_GSS)
    4774                 :             : static int
    4775                 :           0 : encryption_negotiation_failed(PGconn *conn)
    4776                 :             : {
    4777         [ #  # ]:           0 :         Assert((conn->failed_enc_methods & conn->current_enc_method) == 0);
    4778                 :           0 :         conn->failed_enc_methods |= conn->current_enc_method;
    4779                 :             : 
    4780         [ #  # ]:           0 :         if (select_next_encryption_method(conn, true))
    4781                 :             :         {
    4782                 :             :                 /* An existing connection cannot be reused for direct SSL */
    4783   [ #  #  #  # ]:           0 :                 if (conn->current_enc_method == ENC_SSL && conn->sslnegotiation[0] == 'd')
    4784                 :           0 :                         return 2;
    4785                 :             :                 else
    4786                 :           0 :                         return 1;
    4787                 :             :         }
    4788                 :             :         else
    4789                 :           0 :                 return 0;
    4790                 :           0 : }
    4791                 :             : #endif
    4792                 :             : 
    4793                 :             : /*
    4794                 :             :  * Out-of-line portion of the CONNECTION_FAILED() macro
    4795                 :             :  *
    4796                 :             :  * Returns true, if we should reconnect and retry with a different encryption
    4797                 :             :  * method.  conn->current_enc_method is updated to the next method to try.
    4798                 :             :  */
    4799                 :             : static bool
    4800                 :           0 : connection_failed(PGconn *conn)
    4801                 :             : {
    4802         [ #  # ]:           0 :         Assert((conn->failed_enc_methods & conn->current_enc_method) == 0);
    4803                 :           0 :         conn->failed_enc_methods |= conn->current_enc_method;
    4804                 :             : 
    4805                 :           0 :         return select_next_encryption_method(conn, false);
    4806                 :             : }
    4807                 :             : 
    4808                 :             : /*
    4809                 :             :  * Choose the next encryption method to try. If this is a retry,
    4810                 :             :  * conn->failed_enc_methods has already been updated. The function sets
    4811                 :             :  * conn->current_enc_method to the next method to try. Returns false if no
    4812                 :             :  * encryption methods remain.
    4813                 :             :  */
    4814                 :             : static bool
    4815                 :           0 : select_next_encryption_method(PGconn *conn, bool have_valid_connection)
    4816                 :             : {
    4817                 :           0 :         int                     remaining_methods;
    4818                 :             : 
    4819                 :             : #define SELECT_NEXT_METHOD(method) \
    4820                 :             :         do { \
    4821                 :             :                 if ((remaining_methods & method) != 0) \
    4822                 :             :                 { \
    4823                 :             :                         conn->current_enc_method = method; \
    4824                 :             :                         return true; \
    4825                 :             :                 } \
    4826                 :             :         } while (false)
    4827                 :             : 
    4828                 :           0 :         remaining_methods = conn->allowed_enc_methods & ~conn->failed_enc_methods;
    4829                 :             : 
    4830                 :             :         /*
    4831                 :             :          * Try GSSAPI before SSL
    4832                 :             :          */
    4833                 :             : #ifdef ENABLE_GSS
    4834         [ #  # ]:           0 :         if ((remaining_methods & ENC_GSSAPI) != 0)
    4835                 :             :         {
    4836                 :             :                 /*
    4837                 :             :                  * If GSSAPI encryption is enabled, then call pg_GSS_have_cred_cache()
    4838                 :             :                  * which will return true if we can acquire credentials (and give us a
    4839                 :             :                  * handle to use in conn->gcred), and then send a packet to the server
    4840                 :             :                  * asking for GSSAPI Encryption (and skip past SSL negotiation and
    4841                 :             :                  * regular startup below).
    4842                 :             :                  */
    4843         [ #  # ]:           0 :                 if (!conn->gctx)
    4844                 :             :                 {
    4845         [ #  # ]:           0 :                         if (!pg_GSS_have_cred_cache(&conn->gcred))
    4846                 :             :                         {
    4847                 :           0 :                                 conn->allowed_enc_methods &= ~ENC_GSSAPI;
    4848                 :           0 :                                 remaining_methods &= ~ENC_GSSAPI;
    4849                 :             : 
    4850         [ #  # ]:           0 :                                 if (conn->gssencmode[0] == 'r')
    4851                 :             :                                 {
    4852                 :           0 :                                         libpq_append_conn_error(conn,
    4853                 :             :                                                                                         "GSSAPI encryption required but no credential cache");
    4854                 :           0 :                                 }
    4855                 :           0 :                         }
    4856                 :           0 :                 }
    4857                 :           0 :         }
    4858                 :             : 
    4859         [ #  # ]:           0 :         SELECT_NEXT_METHOD(ENC_GSSAPI);
    4860                 :             : #endif
    4861                 :             : 
    4862                 :             :         /*
    4863                 :             :          * The order between SSL encryption and plaintext depends on sslmode. With
    4864                 :             :          * sslmode=allow, try plaintext connection before SSL. With
    4865                 :             :          * sslmode=prefer, it's the other way round. With other modes, we only try
    4866                 :             :          * plaintext or SSL connections so the order they're listed here doesn't
    4867                 :             :          * matter.
    4868                 :             :          */
    4869         [ #  # ]:           0 :         if (conn->sslmode[0] == 'a')
    4870         [ #  # ]:           0 :                 SELECT_NEXT_METHOD(ENC_PLAINTEXT);
    4871                 :             : 
    4872         [ #  # ]:           0 :         SELECT_NEXT_METHOD(ENC_SSL);
    4873                 :             : 
    4874         [ #  # ]:           0 :         if (conn->sslmode[0] != 'a')
    4875         [ #  # ]:           0 :                 SELECT_NEXT_METHOD(ENC_PLAINTEXT);
    4876                 :             : 
    4877                 :             :         /* No more options */
    4878                 :           0 :         conn->current_enc_method = ENC_ERROR;
    4879                 :           0 :         return false;
    4880                 :             : #undef SELECT_NEXT_METHOD
    4881                 :           0 : }
    4882                 :             : 
    4883                 :             : /*
    4884                 :             :  * internal_ping
    4885                 :             :  *              Determine if a server is running and if we can connect to it.
    4886                 :             :  *
    4887                 :             :  * The argument is a connection that's been started, but not completed.
    4888                 :             :  */
    4889                 :             : static PGPing
    4890                 :           2 : internal_ping(PGconn *conn)
    4891                 :             : {
    4892                 :             :         /* Say "no attempt" if we never got to PQconnectPoll */
    4893   [ +  -  -  + ]:           2 :         if (!conn || !conn->options_valid)
    4894                 :           0 :                 return PQPING_NO_ATTEMPT;
    4895                 :             : 
    4896                 :             :         /* Attempt to complete the connection */
    4897         [ +  + ]:           2 :         if (conn->status != CONNECTION_BAD)
    4898                 :           1 :                 (void) pqConnectDBComplete(conn);
    4899                 :             : 
    4900                 :             :         /* Definitely OK if we succeeded */
    4901         [ +  + ]:           2 :         if (conn->status != CONNECTION_BAD)
    4902                 :           1 :                 return PQPING_OK;
    4903                 :             : 
    4904                 :             :         /*
    4905                 :             :          * Here begins the interesting part of "ping": determine the cause of the
    4906                 :             :          * failure in sufficient detail to decide what to return.  We do not want
    4907                 :             :          * to report that the server is not up just because we didn't have a valid
    4908                 :             :          * password, for example.  In fact, any sort of authentication request
    4909                 :             :          * implies the server is up.  (We need this check since the libpq side of
    4910                 :             :          * things might have pulled the plug on the connection before getting an
    4911                 :             :          * error as such from the postmaster.)
    4912                 :             :          */
    4913         [ -  + ]:           1 :         if (conn->auth_req_received)
    4914                 :           0 :                 return PQPING_OK;
    4915                 :             : 
    4916                 :             :         /*
    4917                 :             :          * If we failed to get any ERROR response from the postmaster, report
    4918                 :             :          * PQPING_NO_RESPONSE.  This result could be somewhat misleading for a
    4919                 :             :          * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
    4920                 :             :          * out of support.  Another corner case where the server could return a
    4921                 :             :          * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
    4922                 :             :          * isn't totally unreasonable for that anyway.  We expect that every other
    4923                 :             :          * failure case in a modern server will produce a report with a SQLSTATE.
    4924                 :             :          *
    4925                 :             :          * NOTE: whenever we get around to making libpq generate SQLSTATEs for
    4926                 :             :          * client-side errors, we should either not store those into
    4927                 :             :          * last_sqlstate, or add an extra flag so we can tell client-side errors
    4928                 :             :          * apart from server-side ones.
    4929                 :             :          */
    4930         [ +  - ]:           1 :         if (strlen(conn->last_sqlstate) != 5)
    4931                 :           1 :                 return PQPING_NO_RESPONSE;
    4932                 :             : 
    4933                 :             :         /*
    4934                 :             :          * Report PQPING_REJECT if server says it's not accepting connections.
    4935                 :             :          */
    4936         [ #  # ]:           0 :         if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
    4937                 :           0 :                 return PQPING_REJECT;
    4938                 :             : 
    4939                 :             :         /*
    4940                 :             :          * Any other SQLSTATE can be taken to indicate that the server is up.
    4941                 :             :          * Presumably it didn't like our username, password, or database name; or
    4942                 :             :          * perhaps it had some transient failure, but that should not be taken as
    4943                 :             :          * meaning "it's down".
    4944                 :             :          */
    4945                 :           0 :         return PQPING_OK;
    4946                 :           2 : }
    4947                 :             : 
    4948                 :             : 
    4949                 :             : /*
    4950                 :             :  * pqMakeEmptyPGconn
    4951                 :             :  *       - create a PGconn data structure with (as yet) no interesting data
    4952                 :             :  */
    4953                 :             : PGconn *
    4954                 :         318 : pqMakeEmptyPGconn(void)
    4955                 :             : {
    4956                 :         318 :         PGconn     *conn;
    4957                 :             : 
    4958                 :             : #ifdef WIN32
    4959                 :             : 
    4960                 :             :         /*
    4961                 :             :          * Make sure socket support is up and running in this process.
    4962                 :             :          *
    4963                 :             :          * Note: the Windows documentation says that we should eventually do a
    4964                 :             :          * matching WSACleanup() call, but experience suggests that that is at
    4965                 :             :          * least as likely to cause problems as fix them.  So we don't.
    4966                 :             :          */
    4967                 :             :         static bool wsastartup_done = false;
    4968                 :             : 
    4969                 :             :         if (!wsastartup_done)
    4970                 :             :         {
    4971                 :             :                 WSADATA         wsaData;
    4972                 :             : 
    4973                 :             :                 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    4974                 :             :                         return NULL;
    4975                 :             :                 wsastartup_done = true;
    4976                 :             :         }
    4977                 :             : 
    4978                 :             :         /* Forget any earlier error */
    4979                 :             :         WSASetLastError(0);
    4980                 :             : #endif                                                  /* WIN32 */
    4981                 :             : 
    4982                 :         318 :         conn = (PGconn *) malloc(sizeof(PGconn));
    4983         [ +  - ]:         318 :         if (conn == NULL)
    4984                 :           0 :                 return conn;
    4985                 :             : 
    4986                 :             :         /* Zero all pointers and booleans */
    4987   [ +  -  +  -  :         318 :         MemSet(conn, 0, sizeof(PGconn));
          +  -  +  -  #  
                      # ]
    4988                 :             : 
    4989                 :             :         /* install default notice hooks */
    4990                 :         318 :         conn->noticeHooks.noticeRec = defaultNoticeReceiver;
    4991                 :         318 :         conn->noticeHooks.noticeProc = defaultNoticeProcessor;
    4992                 :             : 
    4993                 :         318 :         conn->status = CONNECTION_BAD;
    4994                 :         318 :         conn->asyncStatus = PGASYNC_IDLE;
    4995                 :         318 :         conn->pipelineStatus = PQ_PIPELINE_OFF;
    4996                 :         318 :         conn->xactStatus = PQTRANS_IDLE;
    4997                 :         318 :         conn->options_valid = false;
    4998                 :         318 :         conn->nonblocking = false;
    4999                 :         318 :         conn->client_encoding = PG_SQL_ASCII;
    5000                 :         318 :         conn->std_strings = false;   /* unless server says differently */
    5001                 :         318 :         conn->default_transaction_read_only = PG_BOOL_UNKNOWN;
    5002                 :         318 :         conn->in_hot_standby = PG_BOOL_UNKNOWN;
    5003                 :         318 :         conn->scram_sha_256_iterations = SCRAM_SHA_256_DEFAULT_ITERATIONS;
    5004                 :         318 :         conn->verbosity = PQERRORS_DEFAULT;
    5005                 :         318 :         conn->show_context = PQSHOW_CONTEXT_ERRORS;
    5006                 :         318 :         conn->sock = PGINVALID_SOCKET;
    5007                 :         318 :         conn->altsock = PGINVALID_SOCKET;
    5008                 :         318 :         conn->Pfdebug = NULL;
    5009                 :             : 
    5010                 :             :         /*
    5011                 :             :          * We try to send at least 8K at a time, which is the usual size of pipe
    5012                 :             :          * buffers on Unix systems.  That way, when we are sending a large amount
    5013                 :             :          * of data, we avoid incurring extra kernel context swaps for partial
    5014                 :             :          * bufferloads.  The output buffer is initially made 16K in size, and we
    5015                 :             :          * try to dump it after accumulating 8K.
    5016                 :             :          *
    5017                 :             :          * With the same goal of minimizing context swaps, the input buffer will
    5018                 :             :          * be enlarged anytime it has less than 8K free, so we initially allocate
    5019                 :             :          * twice that.
    5020                 :             :          */
    5021                 :         318 :         conn->inBufSize = 16 * 1024;
    5022                 :         318 :         conn->inBuffer = (char *) malloc(conn->inBufSize);
    5023                 :         318 :         conn->outBufSize = 16 * 1024;
    5024                 :         318 :         conn->outBuffer = (char *) malloc(conn->outBufSize);
    5025                 :         318 :         conn->rowBufLen = 32;
    5026                 :         318 :         conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
    5027                 :         318 :         initPQExpBuffer(&conn->errorMessage);
    5028                 :         318 :         initPQExpBuffer(&conn->workBuffer);
    5029                 :             : 
    5030         [ +  - ]:         318 :         if (conn->inBuffer == NULL ||
    5031         [ +  - ]:         318 :                 conn->outBuffer == NULL ||
    5032         [ +  - ]:         318 :                 conn->rowBuf == NULL ||
    5033   [ +  -  +  -  :         636 :                 PQExpBufferBroken(&conn->errorMessage) ||
                   +  - ]
    5034         [ +  - ]:         318 :                 PQExpBufferBroken(&conn->workBuffer))
    5035                 :             :         {
    5036                 :             :                 /* out of memory already :-( */
    5037                 :           0 :                 freePGconn(conn);
    5038                 :           0 :                 conn = NULL;
    5039                 :           0 :         }
    5040                 :             : 
    5041                 :         318 :         return conn;
    5042                 :         318 : }
    5043                 :             : 
    5044                 :             : /*
    5045                 :             :  * freePGconn
    5046                 :             :  *       - free an idle (closed) PGconn data structure
    5047                 :             :  *
    5048                 :             :  * NOTE: this should not overlap any functionality with pqClosePGconn().
    5049                 :             :  * Clearing/resetting of transient state belongs there; what we do here is
    5050                 :             :  * release data that is to be held for the life of the PGconn structure.
    5051                 :             :  * If a value ought to be cleared/freed during PQreset(), do it there not here.
    5052                 :             :  */
    5053                 :             : static void
    5054                 :         318 : freePGconn(PGconn *conn)
    5055                 :             : {
    5056                 :             :         /* let any event procs clean up their state data */
    5057         [ -  + ]:         318 :         for (int i = 0; i < conn->nEvents; i++)
    5058                 :             :         {
    5059                 :           0 :                 PGEventConnDestroy evt;
    5060                 :             : 
    5061                 :           0 :                 evt.conn = conn;
    5062                 :           0 :                 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
    5063                 :           0 :                                                                         conn->events[i].passThrough);
    5064                 :           0 :                 free(conn->events[i].name);
    5065                 :           0 :         }
    5066                 :             : 
    5067                 :             :         /* free everything not freed in pqClosePGconn */
    5068                 :         318 :         free(conn->pghost);
    5069                 :         318 :         free(conn->pghostaddr);
    5070                 :         318 :         free(conn->pgport);
    5071                 :         318 :         free(conn->connect_timeout);
    5072                 :         318 :         free(conn->pgtcp_user_timeout);
    5073                 :         318 :         free(conn->client_encoding_initial);
    5074                 :         318 :         free(conn->pgoptions);
    5075                 :         318 :         free(conn->appname);
    5076                 :         318 :         free(conn->fbappname);
    5077                 :         318 :         free(conn->dbName);
    5078                 :         318 :         free(conn->replication);
    5079                 :         318 :         free(conn->pgservice);
    5080                 :         318 :         free(conn->pgservicefile);
    5081                 :         318 :         free(conn->pguser);
    5082         [ +  - ]:         318 :         if (conn->pgpass)
    5083                 :             :         {
    5084                 :           0 :                 explicit_bzero(conn->pgpass, strlen(conn->pgpass));
    5085                 :           0 :                 free(conn->pgpass);
    5086                 :           0 :         }
    5087                 :         318 :         free(conn->pgpassfile);
    5088                 :         318 :         free(conn->channel_binding);
    5089                 :         318 :         free(conn->keepalives);
    5090                 :         318 :         free(conn->keepalives_idle);
    5091                 :         318 :         free(conn->keepalives_interval);
    5092                 :         318 :         free(conn->keepalives_count);
    5093                 :         318 :         free(conn->sslmode);
    5094                 :         318 :         free(conn->sslnegotiation);
    5095                 :         318 :         free(conn->sslcompression);
    5096                 :         318 :         free(conn->sslkey);
    5097                 :         318 :         free(conn->sslcert);
    5098         [ +  - ]:         318 :         if (conn->sslpassword)
    5099                 :             :         {
    5100                 :           0 :                 explicit_bzero(conn->sslpassword, strlen(conn->sslpassword));
    5101                 :           0 :                 free(conn->sslpassword);
    5102                 :           0 :         }
    5103                 :         318 :         free(conn->sslcertmode);
    5104                 :         318 :         free(conn->sslrootcert);
    5105                 :         318 :         free(conn->sslcrl);
    5106                 :         318 :         free(conn->sslcrldir);
    5107                 :         318 :         free(conn->sslsni);
    5108                 :         318 :         free(conn->requirepeer);
    5109                 :         318 :         free(conn->gssencmode);
    5110                 :         318 :         free(conn->krbsrvname);
    5111                 :         318 :         free(conn->gsslib);
    5112                 :         318 :         free(conn->gssdelegation);
    5113                 :         318 :         free(conn->min_protocol_version);
    5114                 :         318 :         free(conn->max_protocol_version);
    5115                 :         318 :         free(conn->ssl_min_protocol_version);
    5116                 :         318 :         free(conn->ssl_max_protocol_version);
    5117                 :         318 :         free(conn->target_session_attrs);
    5118                 :         318 :         free(conn->require_auth);
    5119                 :         318 :         free(conn->load_balance_hosts);
    5120                 :         318 :         free(conn->scram_client_key);
    5121                 :         318 :         free(conn->scram_server_key);
    5122                 :         318 :         free(conn->sslkeylogfile);
    5123                 :         318 :         free(conn->oauth_issuer);
    5124                 :         318 :         free(conn->oauth_issuer_id);
    5125                 :         318 :         free(conn->oauth_discovery_uri);
    5126                 :         318 :         free(conn->oauth_client_id);
    5127                 :         318 :         free(conn->oauth_client_secret);
    5128                 :         318 :         free(conn->oauth_scope);
    5129                 :             :         /* Note that conn->Pfdebug is not ours to close or free */
    5130                 :         318 :         free(conn->events);
    5131                 :         318 :         pqReleaseConnHosts(conn);
    5132                 :         318 :         free(conn->connip);
    5133                 :         318 :         release_conn_addrinfo(conn);
    5134                 :         318 :         free(conn->scram_client_key_binary);
    5135                 :         318 :         free(conn->scram_server_key_binary);
    5136                 :             :         /* if this is a cancel connection, be_cancel_key may still be allocated */
    5137                 :         318 :         free(conn->be_cancel_key);
    5138                 :         318 :         free(conn->inBuffer);
    5139                 :         318 :         free(conn->outBuffer);
    5140                 :         318 :         free(conn->rowBuf);
    5141                 :         318 :         termPQExpBuffer(&conn->errorMessage);
    5142                 :         318 :         termPQExpBuffer(&conn->workBuffer);
    5143                 :             : 
    5144                 :         318 :         free(conn);
    5145                 :         318 : }
    5146                 :             : 
    5147                 :             : /*
    5148                 :             :  * pqReleaseConnHosts
    5149                 :             :  *       - Free the host list in the PGconn.
    5150                 :             :  */
    5151                 :             : void
    5152                 :         318 : pqReleaseConnHosts(PGconn *conn)
    5153                 :             : {
    5154         [ +  - ]:         318 :         if (conn->connhost)
    5155                 :             :         {
    5156         [ +  + ]:         636 :                 for (int i = 0; i < conn->nconnhost; ++i)
    5157                 :             :                 {
    5158                 :         318 :                         free(conn->connhost[i].host);
    5159                 :         318 :                         free(conn->connhost[i].hostaddr);
    5160                 :         318 :                         free(conn->connhost[i].port);
    5161         [ +  - ]:         318 :                         if (conn->connhost[i].password != NULL)
    5162                 :             :                         {
    5163                 :           0 :                                 explicit_bzero(conn->connhost[i].password,
    5164                 :           0 :                                                            strlen(conn->connhost[i].password));
    5165                 :           0 :                                 free(conn->connhost[i].password);
    5166                 :           0 :                         }
    5167                 :         318 :                 }
    5168                 :         318 :                 free(conn->connhost);
    5169                 :         318 :                 conn->connhost = NULL;
    5170                 :         318 :         }
    5171                 :         318 : }
    5172                 :             : 
    5173                 :             : /*
    5174                 :             :  * store_conn_addrinfo
    5175                 :             :  *       - copy addrinfo to PGconn object
    5176                 :             :  *
    5177                 :             :  * Copies the addrinfos from addrlist to the PGconn object such that the
    5178                 :             :  * addrinfos can be manipulated by libpq. Returns a positive integer on
    5179                 :             :  * failure, otherwise zero.
    5180                 :             :  */
    5181                 :             : static int
    5182                 :         317 : store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
    5183                 :             : {
    5184                 :         317 :         struct addrinfo *ai = addrlist;
    5185                 :             : 
    5186                 :         317 :         conn->whichaddr = 0;
    5187                 :             : 
    5188                 :         317 :         conn->naddr = 0;
    5189         [ +  + ]:         634 :         while (ai)
    5190                 :             :         {
    5191                 :         317 :                 ai = ai->ai_next;
    5192                 :         317 :                 conn->naddr++;
    5193                 :             :         }
    5194                 :             : 
    5195                 :         317 :         conn->addr = calloc(conn->naddr, sizeof(AddrInfo));
    5196         [ +  - ]:         317 :         if (conn->addr == NULL)
    5197                 :             :         {
    5198                 :           0 :                 libpq_append_conn_error(conn, "out of memory");
    5199                 :           0 :                 return 1;
    5200                 :             :         }
    5201                 :             : 
    5202                 :         317 :         ai = addrlist;
    5203         [ +  + ]:         634 :         for (int i = 0; i < conn->naddr; i++)
    5204                 :             :         {
    5205                 :         317 :                 conn->addr[i].family = ai->ai_family;
    5206                 :             : 
    5207                 :         317 :                 memcpy(&conn->addr[i].addr.addr, ai->ai_addr,
    5208                 :             :                            ai->ai_addrlen);
    5209                 :         317 :                 conn->addr[i].addr.salen = ai->ai_addrlen;
    5210                 :         317 :                 ai = ai->ai_next;
    5211                 :         317 :         }
    5212                 :             : 
    5213                 :         317 :         return 0;
    5214                 :         317 : }
    5215                 :             : 
    5216                 :             : /*
    5217                 :             :  * release_conn_addrinfo
    5218                 :             :  *       - Free any addrinfo list in the PGconn.
    5219                 :             :  */
    5220                 :             : static void
    5221                 :        1270 : release_conn_addrinfo(PGconn *conn)
    5222                 :             : {
    5223         [ +  + ]:        1270 :         if (conn->addr)
    5224                 :             :         {
    5225                 :         317 :                 free(conn->addr);
    5226                 :         317 :                 conn->addr = NULL;
    5227                 :         317 :         }
    5228                 :        1270 : }
    5229                 :             : 
    5230                 :             : /*
    5231                 :             :  * sendTerminateConn
    5232                 :             :  *       - Send a terminate message to backend.
    5233                 :             :  */
    5234                 :             : static void
    5235                 :         318 : sendTerminateConn(PGconn *conn)
    5236                 :             : {
    5237                 :             :         /*
    5238                 :             :          * The Postgres cancellation protocol does not have a notion of a
    5239                 :             :          * Terminate message, so don't send one.
    5240                 :             :          */
    5241         [ +  - ]:         318 :         if (conn->cancelRequest)
    5242                 :           0 :                 return;
    5243                 :             : 
    5244                 :             :         /*
    5245                 :             :          * Note that the protocol doesn't allow us to send Terminate messages
    5246                 :             :          * during the startup phase.
    5247                 :             :          */
    5248   [ +  +  -  + ]:         318 :         if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
    5249                 :             :         {
    5250                 :             :                 /*
    5251                 :             :                  * Try to send "close connection" message to backend. Ignore any
    5252                 :             :                  * error.
    5253                 :             :                  */
    5254                 :         316 :                 pqPutMsgStart(PqMsg_Terminate, conn);
    5255                 :         316 :                 pqPutMsgEnd(conn);
    5256                 :         316 :                 (void) pqFlush(conn);
    5257                 :         316 :         }
    5258                 :         318 : }
    5259                 :             : 
    5260                 :             : /*
    5261                 :             :  * pqClosePGconn
    5262                 :             :  *       - properly close a connection to the backend
    5263                 :             :  *
    5264                 :             :  * This should reset or release all transient state, but NOT the connection
    5265                 :             :  * parameters.  On exit, the PGconn should be in condition to start a fresh
    5266                 :             :  * connection with the same parameters (see PQreset()).
    5267                 :             :  */
    5268                 :             : void
    5269                 :         318 : pqClosePGconn(PGconn *conn)
    5270                 :             : {
    5271                 :             :         /*
    5272                 :             :          * If possible, send Terminate message to close the connection politely.
    5273                 :             :          */
    5274                 :         318 :         sendTerminateConn(conn);
    5275                 :             : 
    5276                 :             :         /*
    5277                 :             :          * Must reset the blocking status so a possible reconnect will work.
    5278                 :             :          *
    5279                 :             :          * Don't call PQsetnonblocking() because it will fail if it's unable to
    5280                 :             :          * flush the connection.
    5281                 :             :          */
    5282                 :         318 :         conn->nonblocking = false;
    5283                 :             : 
    5284                 :             :         /*
    5285                 :             :          * Close the connection, reset all transient state, flush I/O buffers.
    5286                 :             :          * Note that this includes clearing conn's error state; we're no longer
    5287                 :             :          * interested in any failures associated with the old connection, and we
    5288                 :             :          * want a clean slate for any new connection attempt.
    5289                 :             :          */
    5290                 :         318 :         pqDropConnection(conn, true);
    5291                 :         318 :         conn->status = CONNECTION_BAD;       /* Well, not really _bad_ - just absent */
    5292                 :         318 :         conn->asyncStatus = PGASYNC_IDLE;
    5293                 :         318 :         conn->xactStatus = PQTRANS_IDLE;
    5294                 :         318 :         conn->pipelineStatus = PQ_PIPELINE_OFF;
    5295                 :         318 :         pqClearOAuthToken(conn);
    5296                 :         318 :         pqClearAsyncResult(conn);       /* deallocate result */
    5297                 :         318 :         pqClearConnErrorState(conn);
    5298                 :             : 
    5299                 :             :         /*
    5300                 :             :          * Release addrinfo, but since cancel requests never change their addrinfo
    5301                 :             :          * we don't do that. Otherwise we would have to rebuild it during a
    5302                 :             :          * PQcancelReset.
    5303                 :             :          */
    5304         [ -  + ]:         318 :         if (!conn->cancelRequest)
    5305                 :         318 :                 release_conn_addrinfo(conn);
    5306                 :             : 
    5307                 :             :         /* Reset all state obtained from server, too */
    5308                 :         318 :         pqDropServerData(conn);
    5309                 :         318 : }
    5310                 :             : 
    5311                 :             : /*
    5312                 :             :  * PQfinish: properly close a connection to the backend. Also frees
    5313                 :             :  * the PGconn data structure so it shouldn't be re-used after this.
    5314                 :             :  */
    5315                 :             : void
    5316                 :         318 : PQfinish(PGconn *conn)
    5317                 :             : {
    5318         [ -  + ]:         318 :         if (conn)
    5319                 :             :         {
    5320                 :         318 :                 pqClosePGconn(conn);
    5321                 :         318 :                 freePGconn(conn);
    5322                 :         318 :         }
    5323                 :         318 : }
    5324                 :             : 
    5325                 :             : /*
    5326                 :             :  * PQreset: resets the connection to the backend by closing the
    5327                 :             :  * existing connection and creating a new one.
    5328                 :             :  */
    5329                 :             : void
    5330                 :           0 : PQreset(PGconn *conn)
    5331                 :             : {
    5332         [ #  # ]:           0 :         if (conn)
    5333                 :             :         {
    5334                 :           0 :                 pqClosePGconn(conn);
    5335                 :             : 
    5336   [ #  #  #  # ]:           0 :                 if (pqConnectDBStart(conn) && pqConnectDBComplete(conn))
    5337                 :             :                 {
    5338                 :             :                         /*
    5339                 :             :                          * Notify event procs of successful reset.
    5340                 :             :                          */
    5341                 :           0 :                         int                     i;
    5342                 :             : 
    5343         [ #  # ]:           0 :                         for (i = 0; i < conn->nEvents; i++)
    5344                 :             :                         {
    5345                 :           0 :                                 PGEventConnReset evt;
    5346                 :             : 
    5347                 :           0 :                                 evt.conn = conn;
    5348                 :           0 :                                 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
    5349                 :           0 :                                                                                         conn->events[i].passThrough);
    5350                 :           0 :                         }
    5351                 :           0 :                 }
    5352                 :           0 :         }
    5353                 :           0 : }
    5354                 :             : 
    5355                 :             : 
    5356                 :             : /*
    5357                 :             :  * PQresetStart:
    5358                 :             :  * resets the connection to the backend
    5359                 :             :  * closes the existing connection and makes a new one
    5360                 :             :  * Returns 1 on success, 0 on failure.
    5361                 :             :  */
    5362                 :             : int
    5363                 :           0 : PQresetStart(PGconn *conn)
    5364                 :             : {
    5365         [ #  # ]:           0 :         if (conn)
    5366                 :             :         {
    5367                 :           0 :                 pqClosePGconn(conn);
    5368                 :             : 
    5369                 :           0 :                 return pqConnectDBStart(conn);
    5370                 :             :         }
    5371                 :             : 
    5372                 :           0 :         return 0;
    5373                 :           0 : }
    5374                 :             : 
    5375                 :             : 
    5376                 :             : /*
    5377                 :             :  * PQresetPoll:
    5378                 :             :  * resets the connection to the backend
    5379                 :             :  * closes the existing connection and makes a new one
    5380                 :             :  */
    5381                 :             : PostgresPollingStatusType
    5382                 :           0 : PQresetPoll(PGconn *conn)
    5383                 :             : {
    5384         [ #  # ]:           0 :         if (conn)
    5385                 :             :         {
    5386                 :           0 :                 PostgresPollingStatusType status = PQconnectPoll(conn);
    5387                 :             : 
    5388         [ #  # ]:           0 :                 if (status == PGRES_POLLING_OK)
    5389                 :             :                 {
    5390                 :             :                         /*
    5391                 :             :                          * Notify event procs of successful reset.
    5392                 :             :                          */
    5393                 :           0 :                         int                     i;
    5394                 :             : 
    5395         [ #  # ]:           0 :                         for (i = 0; i < conn->nEvents; i++)
    5396                 :             :                         {
    5397                 :           0 :                                 PGEventConnReset evt;
    5398                 :             : 
    5399                 :           0 :                                 evt.conn = conn;
    5400                 :           0 :                                 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
    5401                 :           0 :                                                                                         conn->events[i].passThrough);
    5402                 :           0 :                         }
    5403                 :           0 :                 }
    5404                 :             : 
    5405                 :           0 :                 return status;
    5406                 :           0 :         }
    5407                 :             : 
    5408                 :           0 :         return PGRES_POLLING_FAILED;
    5409                 :           0 : }
    5410                 :             : 
    5411                 :             : /*
    5412                 :             :  * pqPacketSend() -- convenience routine to send a message to server.
    5413                 :             :  *
    5414                 :             :  * pack_type: the single-byte message type code.  (Pass zero for startup
    5415                 :             :  * packets, which have no message type code.)
    5416                 :             :  *
    5417                 :             :  * buf, buf_len: contents of message.  The given length includes only what
    5418                 :             :  * is in buf; the message type and message length fields are added here.
    5419                 :             :  *
    5420                 :             :  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
    5421                 :             :  * SIDE_EFFECTS: may block.
    5422                 :             :  */
    5423                 :             : int
    5424                 :         316 : pqPacketSend(PGconn *conn, char pack_type,
    5425                 :             :                          const void *buf, size_t buf_len)
    5426                 :             : {
    5427                 :             :         /* Start the message. */
    5428         [ -  + ]:         316 :         if (pqPutMsgStart(pack_type, conn))
    5429                 :           0 :                 return STATUS_ERROR;
    5430                 :             : 
    5431                 :             :         /* Send the message body. */
    5432         [ -  + ]:         316 :         if (pqPutnchar(buf, buf_len, conn))
    5433                 :           0 :                 return STATUS_ERROR;
    5434                 :             : 
    5435                 :             :         /* Finish the message. */
    5436         [ -  + ]:         316 :         if (pqPutMsgEnd(conn))
    5437                 :           0 :                 return STATUS_ERROR;
    5438                 :             : 
    5439                 :             :         /* Flush to ensure backend gets it. */
    5440         [ -  + ]:         316 :         if (pqFlush(conn))
    5441                 :           0 :                 return STATUS_ERROR;
    5442                 :             : 
    5443                 :         316 :         return STATUS_OK;
    5444                 :         316 : }
    5445                 :             : 
    5446                 :             : #ifdef USE_LDAP
    5447                 :             : 
    5448                 :             : #define LDAP_URL        "ldap://"
    5449                 :             : #define LDAP_DEF_PORT   389
    5450                 :             : #define PGLDAP_TIMEOUT 2
    5451                 :             : 
    5452                 :             : #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
    5453                 :             : #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
    5454                 :             : 
    5455                 :             : 
    5456                 :             : /*
    5457                 :             :  *              ldapServiceLookup
    5458                 :             :  *
    5459                 :             :  * Search the LDAP URL passed as first argument, treat the result as a
    5460                 :             :  * string of connection options that are parsed and added to the array of
    5461                 :             :  * options passed as second argument.
    5462                 :             :  *
    5463                 :             :  * LDAP URLs must conform to RFC 1959 without escape sequences.
    5464                 :             :  *      ldap://host:port/dn?attributes?scope?filter?extensions
    5465                 :             :  *
    5466                 :             :  * Returns
    5467                 :             :  *      0 if the lookup was successful,
    5468                 :             :  *      1 if the connection to the LDAP server could be established but
    5469                 :             :  *        the search was unsuccessful,
    5470                 :             :  *      2 if a connection could not be established, and
    5471                 :             :  *      3 if a fatal error occurred.
    5472                 :             :  *
    5473                 :             :  * An error message is appended to *errorMessage for return codes 1 and 3.
    5474                 :             :  */
    5475                 :             : static int
    5476                 :             : ldapServiceLookup(const char *purl, PQconninfoOption *options,
    5477                 :             :                                   PQExpBuffer errorMessage)
    5478                 :             : {
    5479                 :             :         int                     port = LDAP_DEF_PORT,
    5480                 :             :                                 scope,
    5481                 :             :                                 rc,
    5482                 :             :                                 size,
    5483                 :             :                                 state,
    5484                 :             :                                 oldstate,
    5485                 :             :                                 i;
    5486                 :             : #ifndef WIN32
    5487                 :             :         int                     msgid;
    5488                 :             : #endif
    5489                 :             :         bool            found_keyword;
    5490                 :             :         char       *url,
    5491                 :             :                            *hostname,
    5492                 :             :                            *portstr,
    5493                 :             :                            *endptr,
    5494                 :             :                            *dn,
    5495                 :             :                            *scopestr,
    5496                 :             :                            *filter,
    5497                 :             :                            *result,
    5498                 :             :                            *p,
    5499                 :             :                            *p1 = NULL,
    5500                 :             :                            *optname = NULL,
    5501                 :             :                            *optval = NULL;
    5502                 :             :         char       *attrs[2] = {NULL, NULL};
    5503                 :             :         LDAP       *ld = NULL;
    5504                 :             :         LDAPMessage *res,
    5505                 :             :                            *entry;
    5506                 :             :         struct berval **values;
    5507                 :             :         LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
    5508                 :             :         int                     ldapversion = LDAP_VERSION3;
    5509                 :             : 
    5510                 :             :         if ((url = strdup(purl)) == NULL)
    5511                 :             :         {
    5512                 :             :                 libpq_append_error(errorMessage, "out of memory");
    5513                 :             :                 return 3;
    5514                 :             :         }
    5515                 :             : 
    5516                 :             :         /*
    5517                 :             :          * Parse URL components, check for correctness.  Basically, url has '\0'
    5518                 :             :          * placed at component boundaries and variables are pointed at each
    5519                 :             :          * component.
    5520                 :             :          */
    5521                 :             : 
    5522                 :             :         if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
    5523                 :             :         {
    5524                 :             :                 libpq_append_error(errorMessage,
    5525                 :             :                                                    "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
    5526                 :             :                 free(url);
    5527                 :             :                 return 3;
    5528                 :             :         }
    5529                 :             : 
    5530                 :             :         /* hostname */
    5531                 :             :         hostname = url + strlen(LDAP_URL);
    5532                 :             :         if (*hostname == '/')           /* no hostname? */
    5533                 :             :                 hostname = DefaultHost; /* the default */
    5534                 :             : 
    5535                 :             :         /* dn, "distinguished name" */
    5536                 :             :         p = strchr(url + strlen(LDAP_URL), '/');
    5537                 :             :         if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
    5538                 :             :         {
    5539                 :             :                 libpq_append_error(errorMessage,
    5540                 :             :                                                    "invalid LDAP URL \"%s\": missing distinguished name",
    5541                 :             :                                                    purl);
    5542                 :             :                 free(url);
    5543                 :             :                 return 3;
    5544                 :             :         }
    5545                 :             :         *p = '\0';                                      /* terminate hostname */
    5546                 :             :         dn = p + 1;
    5547                 :             : 
    5548                 :             :         /* attribute */
    5549                 :             :         if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
    5550                 :             :         {
    5551                 :             :                 libpq_append_error(errorMessage,
    5552                 :             :                                                    "invalid LDAP URL \"%s\": must have exactly one attribute",
    5553                 :             :                                                    purl);
    5554                 :             :                 free(url);
    5555                 :             :                 return 3;
    5556                 :             :         }
    5557                 :             :         *p = '\0';
    5558                 :             :         attrs[0] = p + 1;
    5559                 :             : 
    5560                 :             :         /* scope */
    5561                 :             :         if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
    5562                 :             :         {
    5563                 :             :                 libpq_append_error(errorMessage,
    5564                 :             :                                                    "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
    5565                 :             :                                                    purl);
    5566                 :             :                 free(url);
    5567                 :             :                 return 3;
    5568                 :             :         }
    5569                 :             :         *p = '\0';
    5570                 :             :         scopestr = p + 1;
    5571                 :             : 
    5572                 :             :         /* filter */
    5573                 :             :         if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
    5574                 :             :         {
    5575                 :             :                 libpq_append_error(errorMessage,
    5576                 :             :                                                    "invalid LDAP URL \"%s\": no filter",
    5577                 :             :                                                    purl);
    5578                 :             :                 free(url);
    5579                 :             :                 return 3;
    5580                 :             :         }
    5581                 :             :         *p = '\0';
    5582                 :             :         filter = p + 1;
    5583                 :             :         if ((p = strchr(filter, '?')) != NULL)
    5584                 :             :                 *p = '\0';
    5585                 :             : 
    5586                 :             :         /* port number? */
    5587                 :             :         if ((p1 = strchr(hostname, ':')) != NULL)
    5588                 :             :         {
    5589                 :             :                 long            lport;
    5590                 :             : 
    5591                 :             :                 *p1 = '\0';
    5592                 :             :                 portstr = p1 + 1;
    5593                 :             :                 errno = 0;
    5594                 :             :                 lport = strtol(portstr, &endptr, 10);
    5595                 :             :                 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
    5596                 :             :                 {
    5597                 :             :                         libpq_append_error(errorMessage,
    5598                 :             :                                                            "invalid LDAP URL \"%s\": invalid port number",
    5599                 :             :                                                            purl);
    5600                 :             :                         free(url);
    5601                 :             :                         return 3;
    5602                 :             :                 }
    5603                 :             :                 port = (int) lport;
    5604                 :             :         }
    5605                 :             : 
    5606                 :             :         /* Allow only one attribute */
    5607                 :             :         if (strchr(attrs[0], ',') != NULL)
    5608                 :             :         {
    5609                 :             :                 libpq_append_error(errorMessage,
    5610                 :             :                                                    "invalid LDAP URL \"%s\": must have exactly one attribute",
    5611                 :             :                                                    purl);
    5612                 :             :                 free(url);
    5613                 :             :                 return 3;
    5614                 :             :         }
    5615                 :             : 
    5616                 :             :         /* set scope */
    5617                 :             :         if (pg_strcasecmp(scopestr, "base") == 0)
    5618                 :             :                 scope = LDAP_SCOPE_BASE;
    5619                 :             :         else if (pg_strcasecmp(scopestr, "one") == 0)
    5620                 :             :                 scope = LDAP_SCOPE_ONELEVEL;
    5621                 :             :         else if (pg_strcasecmp(scopestr, "sub") == 0)
    5622                 :             :                 scope = LDAP_SCOPE_SUBTREE;
    5623                 :             :         else
    5624                 :             :         {
    5625                 :             :                 libpq_append_error(errorMessage,
    5626                 :             :                                                    "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
    5627                 :             :                                                    purl);
    5628                 :             :                 free(url);
    5629                 :             :                 return 3;
    5630                 :             :         }
    5631                 :             : 
    5632                 :             :         /* initialize LDAP structure */
    5633                 :             :         if ((ld = ldap_init(hostname, port)) == NULL)
    5634                 :             :         {
    5635                 :             :                 libpq_append_error(errorMessage, "could not create LDAP structure");
    5636                 :             :                 free(url);
    5637                 :             :                 return 3;
    5638                 :             :         }
    5639                 :             : 
    5640                 :             :         if ((rc = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
    5641                 :             :         {
    5642                 :             :                 libpq_append_error(errorMessage, "could not set LDAP protocol version: %s",
    5643                 :             :                                                    ldap_err2string(rc));
    5644                 :             :                 free(url);
    5645                 :             :                 ldap_unbind(ld);
    5646                 :             :                 return 3;
    5647                 :             :         }
    5648                 :             : 
    5649                 :             :         /*
    5650                 :             :          * Perform an explicit anonymous bind.
    5651                 :             :          *
    5652                 :             :          * LDAP does not require that an anonymous bind is performed explicitly,
    5653                 :             :          * but we want to distinguish between the case where LDAP bind does not
    5654                 :             :          * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
    5655                 :             :          * service control file) and the case where querying the LDAP server fails
    5656                 :             :          * (return 1 to end parsing).
    5657                 :             :          *
    5658                 :             :          * Unfortunately there is no way of setting a timeout that works for both
    5659                 :             :          * Windows and OpenLDAP.
    5660                 :             :          */
    5661                 :             : #ifdef WIN32
    5662                 :             :         /* the nonstandard ldap_connect function performs an anonymous bind */
    5663                 :             :         if (ldap_connect(ld, &time) != LDAP_SUCCESS)
    5664                 :             :         {
    5665                 :             :                 /* error or timeout in ldap_connect */
    5666                 :             :                 free(url);
    5667                 :             :                 ldap_unbind(ld);
    5668                 :             :                 return 2;
    5669                 :             :         }
    5670                 :             : #else                                                   /* !WIN32 */
    5671                 :             :         /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
    5672                 :             :         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
    5673                 :             :         {
    5674                 :             :                 free(url);
    5675                 :             :                 ldap_unbind(ld);
    5676                 :             :                 return 3;
    5677                 :             :         }
    5678                 :             : 
    5679                 :             :         /* anonymous bind */
    5680                 :             :         if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
    5681                 :             :         {
    5682                 :             :                 /* error or network timeout */
    5683                 :             :                 free(url);
    5684                 :             :                 ldap_unbind(ld);
    5685                 :             :                 return 2;
    5686                 :             :         }
    5687                 :             : 
    5688                 :             :         /* wait some time for the connection to succeed */
    5689                 :             :         res = NULL;
    5690                 :             :         if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
    5691                 :             :                 res == NULL)
    5692                 :             :         {
    5693                 :             :                 /* error or timeout */
    5694                 :             :                 if (res != NULL)
    5695                 :             :                         ldap_msgfree(res);
    5696                 :             :                 free(url);
    5697                 :             :                 ldap_unbind(ld);
    5698                 :             :                 return 2;
    5699                 :             :         }
    5700                 :             :         ldap_msgfree(res);
    5701                 :             : 
    5702                 :             :         /* reset timeout */
    5703                 :             :         time.tv_sec = -1;
    5704                 :             :         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
    5705                 :             :         {
    5706                 :             :                 free(url);
    5707                 :             :                 ldap_unbind(ld);
    5708                 :             :                 return 3;
    5709                 :             :         }
    5710                 :             : #endif                                                  /* WIN32 */
    5711                 :             : 
    5712                 :             :         /* search */
    5713                 :             :         res = NULL;
    5714                 :             :         if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
    5715                 :             :                 != LDAP_SUCCESS)
    5716                 :             :         {
    5717                 :             :                 if (res != NULL)
    5718                 :             :                         ldap_msgfree(res);
    5719                 :             :                 libpq_append_error(errorMessage, "lookup on LDAP server failed: %s", ldap_err2string(rc));
    5720                 :             :                 ldap_unbind(ld);
    5721                 :             :                 free(url);
    5722                 :             :                 return 1;
    5723                 :             :         }
    5724                 :             : 
    5725                 :             :         /* complain if there was not exactly one result */
    5726                 :             :         if ((rc = ldap_count_entries(ld, res)) != 1)
    5727                 :             :         {
    5728                 :             :                 if (rc > 1)
    5729                 :             :                         libpq_append_error(errorMessage, "more than one entry found on LDAP lookup");
    5730                 :             :                 else
    5731                 :             :                         libpq_append_error(errorMessage, "no entry found on LDAP lookup");
    5732                 :             :                 ldap_msgfree(res);
    5733                 :             :                 ldap_unbind(ld);
    5734                 :             :                 free(url);
    5735                 :             :                 return 1;
    5736                 :             :         }
    5737                 :             : 
    5738                 :             :         /* get entry */
    5739                 :             :         if ((entry = ldap_first_entry(ld, res)) == NULL)
    5740                 :             :         {
    5741                 :             :                 /* should never happen */
    5742                 :             :                 libpq_append_error(errorMessage, "no entry found on LDAP lookup");
    5743                 :             :                 ldap_msgfree(res);
    5744                 :             :                 ldap_unbind(ld);
    5745                 :             :                 free(url);
    5746                 :             :                 return 1;
    5747                 :             :         }
    5748                 :             : 
    5749                 :             :         /* get values */
    5750                 :             :         if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
    5751                 :             :         {
    5752                 :             :                 libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
    5753                 :             :                 ldap_msgfree(res);
    5754                 :             :                 ldap_unbind(ld);
    5755                 :             :                 free(url);
    5756                 :             :                 return 1;
    5757                 :             :         }
    5758                 :             : 
    5759                 :             :         ldap_msgfree(res);
    5760                 :             :         free(url);
    5761                 :             : 
    5762                 :             :         if (values[0] == NULL)
    5763                 :             :         {
    5764                 :             :                 libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
    5765                 :             :                 ldap_value_free_len(values);
    5766                 :             :                 ldap_unbind(ld);
    5767                 :             :                 return 1;
    5768                 :             :         }
    5769                 :             : 
    5770                 :             :         /* concatenate values into a single string with newline terminators */
    5771                 :             :         size = 1;                                       /* for the trailing null */
    5772                 :             :         for (i = 0; values[i] != NULL; i++)
    5773                 :             :         {
    5774                 :             :                 if (values[i]->bv_len >= INT_MAX ||
    5775                 :             :                         size > (INT_MAX - (values[i]->bv_len + 1)))
    5776                 :             :                 {
    5777                 :             :                         libpq_append_error(errorMessage,
    5778                 :             :                                                            "connection info string size exceeds the maximum allowed (%d)",
    5779                 :             :                                                            INT_MAX);
    5780                 :             :                         ldap_value_free_len(values);
    5781                 :             :                         ldap_unbind(ld);
    5782                 :             :                         return 3;
    5783                 :             :                 }
    5784                 :             : 
    5785                 :             :                 size += values[i]->bv_len + 1;
    5786                 :             :         }
    5787                 :             : 
    5788                 :             :         if ((result = malloc(size)) == NULL)
    5789                 :             :         {
    5790                 :             :                 libpq_append_error(errorMessage, "out of memory");
    5791                 :             :                 ldap_value_free_len(values);
    5792                 :             :                 ldap_unbind(ld);
    5793                 :             :                 return 3;
    5794                 :             :         }
    5795                 :             :         p = result;
    5796                 :             :         for (i = 0; values[i] != NULL; i++)
    5797                 :             :         {
    5798                 :             :                 memcpy(p, values[i]->bv_val, values[i]->bv_len);
    5799                 :             :                 p += values[i]->bv_len;
    5800                 :             :                 *(p++) = '\n';
    5801                 :             :         }
    5802                 :             :         *p = '\0';
    5803                 :             : 
    5804                 :             :         ldap_value_free_len(values);
    5805                 :             :         ldap_unbind(ld);
    5806                 :             : 
    5807                 :             :         /* parse result string */
    5808                 :             :         oldstate = state = 0;
    5809                 :             :         for (p = result; *p != '\0'; ++p)
    5810                 :             :         {
    5811                 :             :                 switch (state)
    5812                 :             :                 {
    5813                 :             :                         case 0:                         /* between entries */
    5814                 :             :                                 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
    5815                 :             :                                 {
    5816                 :             :                                         optname = p;
    5817                 :             :                                         state = 1;
    5818                 :             :                                 }
    5819                 :             :                                 break;
    5820                 :             :                         case 1:                         /* in option name */
    5821                 :             :                                 if (ld_is_sp_tab(*p))
    5822                 :             :                                 {
    5823                 :             :                                         *p = '\0';
    5824                 :             :                                         state = 2;
    5825                 :             :                                 }
    5826                 :             :                                 else if (ld_is_nl_cr(*p))
    5827                 :             :                                 {
    5828                 :             :                                         libpq_append_error(errorMessage,
    5829                 :             :                                                                            "missing \"=\" after \"%s\" in connection info string",
    5830                 :             :                                                                            optname);
    5831                 :             :                                         free(result);
    5832                 :             :                                         return 3;
    5833                 :             :                                 }
    5834                 :             :                                 else if (*p == '=')
    5835                 :             :                                 {
    5836                 :             :                                         *p = '\0';
    5837                 :             :                                         state = 3;
    5838                 :             :                                 }
    5839                 :             :                                 break;
    5840                 :             :                         case 2:                         /* after option name */
    5841                 :             :                                 if (*p == '=')
    5842                 :             :                                 {
    5843                 :             :                                         state = 3;
    5844                 :             :                                 }
    5845                 :             :                                 else if (!ld_is_sp_tab(*p))
    5846                 :             :                                 {
    5847                 :             :                                         libpq_append_error(errorMessage,
    5848                 :             :                                                                            "missing \"=\" after \"%s\" in connection info string",
    5849                 :             :                                                                            optname);
    5850                 :             :                                         free(result);
    5851                 :             :                                         return 3;
    5852                 :             :                                 }
    5853                 :             :                                 break;
    5854                 :             :                         case 3:                         /* before option value */
    5855                 :             :                                 if (*p == '\'')
    5856                 :             :                                 {
    5857                 :             :                                         optval = p + 1;
    5858                 :             :                                         p1 = p + 1;
    5859                 :             :                                         state = 5;
    5860                 :             :                                 }
    5861                 :             :                                 else if (ld_is_nl_cr(*p))
    5862                 :             :                                 {
    5863                 :             :                                         optval = optname + strlen(optname); /* empty */
    5864                 :             :                                         state = 0;
    5865                 :             :                                 }
    5866                 :             :                                 else if (!ld_is_sp_tab(*p))
    5867                 :             :                                 {
    5868                 :             :                                         optval = p;
    5869                 :             :                                         state = 4;
    5870                 :             :                                 }
    5871                 :             :                                 break;
    5872                 :             :                         case 4:                         /* in unquoted option value */
    5873                 :             :                                 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
    5874                 :             :                                 {
    5875                 :             :                                         *p = '\0';
    5876                 :             :                                         state = 0;
    5877                 :             :                                 }
    5878                 :             :                                 break;
    5879                 :             :                         case 5:                         /* in quoted option value */
    5880                 :             :                                 if (*p == '\'')
    5881                 :             :                                 {
    5882                 :             :                                         *p1 = '\0';
    5883                 :             :                                         state = 0;
    5884                 :             :                                 }
    5885                 :             :                                 else if (*p == '\\')
    5886                 :             :                                         state = 6;
    5887                 :             :                                 else
    5888                 :             :                                         *(p1++) = *p;
    5889                 :             :                                 break;
    5890                 :             :                         case 6:                         /* in quoted option value after escape */
    5891                 :             :                                 *(p1++) = *p;
    5892                 :             :                                 state = 5;
    5893                 :             :                                 break;
    5894                 :             :                 }
    5895                 :             : 
    5896                 :             :                 if (state == 0 && oldstate != 0)
    5897                 :             :                 {
    5898                 :             :                         found_keyword = false;
    5899                 :             :                         for (i = 0; options[i].keyword; i++)
    5900                 :             :                         {
    5901                 :             :                                 if (strcmp(options[i].keyword, optname) == 0)
    5902                 :             :                                 {
    5903                 :             :                                         if (options[i].val == NULL)
    5904                 :             :                                         {
    5905                 :             :                                                 options[i].val = strdup(optval);
    5906                 :             :                                                 if (!options[i].val)
    5907                 :             :                                                 {
    5908                 :             :                                                         libpq_append_error(errorMessage, "out of memory");
    5909                 :             :                                                         free(result);
    5910                 :             :                                                         return 3;
    5911                 :             :                                                 }
    5912                 :             :                                         }
    5913                 :             :                                         found_keyword = true;
    5914                 :             :                                         break;
    5915                 :             :                                 }
    5916                 :             :                         }
    5917                 :             :                         if (!found_keyword)
    5918                 :             :                         {
    5919                 :             :                                 libpq_append_error(errorMessage, "invalid connection option \"%s\"", optname);
    5920                 :             :                                 free(result);
    5921                 :             :                                 return 1;
    5922                 :             :                         }
    5923                 :             :                         optname = NULL;
    5924                 :             :                         optval = NULL;
    5925                 :             :                 }
    5926                 :             :                 oldstate = state;
    5927                 :             :         }
    5928                 :             : 
    5929                 :             :         free(result);
    5930                 :             : 
    5931                 :             :         if (state == 5 || state == 6)
    5932                 :             :         {
    5933                 :             :                 libpq_append_error(errorMessage,
    5934                 :             :                                                    "unterminated quoted string in connection info string");
    5935                 :             :                 return 3;
    5936                 :             :         }
    5937                 :             : 
    5938                 :             :         return 0;
    5939                 :             : }
    5940                 :             : 
    5941                 :             : #endif                                                  /* USE_LDAP */
    5942                 :             : 
    5943                 :             : /*
    5944                 :             :  * parseServiceInfo: if a service name has been given, look it up and absorb
    5945                 :             :  * connection options from it into *options.
    5946                 :             :  *
    5947                 :             :  * Returns 0 on success, nonzero on failure.  On failure, if errorMessage
    5948                 :             :  * isn't null, also store an error message there.  (Note: the only reason
    5949                 :             :  * this function and related ones don't dump core on errorMessage == NULL
    5950                 :             :  * is the undocumented fact that appendPQExpBuffer does nothing when passed
    5951                 :             :  * a null PQExpBuffer pointer.)
    5952                 :             :  */
    5953                 :             : static int
    5954                 :         318 : parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
    5955                 :             : {
    5956                 :         318 :         const char *service = conninfo_getval(options, "service");
    5957                 :         318 :         const char *service_fname = conninfo_getval(options, "servicefile");
    5958                 :         318 :         char            serviceFile[MAXPGPATH];
    5959                 :         318 :         char       *env;
    5960                 :         318 :         bool            group_found = false;
    5961                 :         318 :         int                     status;
    5962                 :         318 :         struct stat stat_buf;
    5963                 :             : 
    5964                 :             :         /*
    5965                 :             :          * We have to special-case the environment variable PGSERVICE here, since
    5966                 :             :          * this is and should be called before inserting environment defaults for
    5967                 :             :          * other connection options.
    5968                 :             :          */
    5969         [ -  + ]:         318 :         if (service == NULL)
    5970                 :         318 :                 service = getenv("PGSERVICE");
    5971                 :             : 
    5972                 :             :         /* If no service name given, nothing to do */
    5973         [ -  + ]:         318 :         if (service == NULL)
    5974                 :         318 :                 return 0;
    5975                 :             : 
    5976                 :             :         /*
    5977                 :             :          * First, try the "servicefile" option in connection string.  Then, try
    5978                 :             :          * the PGSERVICEFILE environment variable.  Finally, check
    5979                 :             :          * ~/.pg_service.conf (if that exists).
    5980                 :             :          */
    5981         [ #  # ]:           0 :         if (service_fname != NULL)
    5982                 :           0 :                 strlcpy(serviceFile, service_fname, sizeof(serviceFile));
    5983         [ #  # ]:           0 :         else if ((env = getenv("PGSERVICEFILE")) != NULL)
    5984                 :           0 :                 strlcpy(serviceFile, env, sizeof(serviceFile));
    5985                 :             :         else
    5986                 :             :         {
    5987                 :           0 :                 char            homedir[MAXPGPATH];
    5988                 :             : 
    5989         [ #  # ]:           0 :                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
    5990                 :           0 :                         goto next_file;
    5991                 :           0 :                 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
    5992         [ #  # ]:           0 :                 if (stat(serviceFile, &stat_buf) != 0)
    5993                 :           0 :                         goto next_file;
    5994      [ #  #  # ]:           0 :         }
    5995                 :             : 
    5996                 :           0 :         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
    5997   [ #  #  #  # ]:           0 :         if (group_found || status != 0)
    5998                 :           0 :                 return status;
    5999                 :             : 
    6000                 :             : next_file:
    6001                 :             : 
    6002                 :             :         /*
    6003                 :             :          * This could be used by any application so we can't use the binary
    6004                 :             :          * location to find our config files.
    6005                 :             :          */
    6006                 :           0 :         snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
    6007         [ #  # ]:           0 :                          getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
    6008         [ #  # ]:           0 :         if (stat(serviceFile, &stat_buf) != 0)
    6009                 :           0 :                 goto last_file;
    6010                 :             : 
    6011                 :           0 :         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
    6012         [ #  # ]:           0 :         if (status != 0)
    6013                 :           0 :                 return status;
    6014                 :             : 
    6015                 :             : last_file:
    6016         [ #  # ]:           0 :         if (!group_found)
    6017                 :             :         {
    6018                 :           0 :                 libpq_append_error(errorMessage, "definition of service \"%s\" not found", service);
    6019                 :           0 :                 return 3;
    6020                 :             :         }
    6021                 :             : 
    6022                 :           0 :         return 0;
    6023                 :         318 : }
    6024                 :             : 
    6025                 :             : static int
    6026                 :           0 : parseServiceFile(const char *serviceFile,
    6027                 :             :                                  const char *service,
    6028                 :             :                                  PQconninfoOption *options,
    6029                 :             :                                  PQExpBuffer errorMessage,
    6030                 :             :                                  bool *group_found)
    6031                 :             : {
    6032                 :           0 :         int                     result = 0,
    6033                 :           0 :                                 linenr = 0,
    6034                 :             :                                 i;
    6035                 :           0 :         FILE       *f;
    6036                 :           0 :         char       *line;
    6037                 :           0 :         char            buf[1024];
    6038                 :             : 
    6039                 :           0 :         *group_found = false;
    6040                 :             : 
    6041                 :           0 :         f = fopen(serviceFile, "r");
    6042         [ #  # ]:           0 :         if (f == NULL)
    6043                 :             :         {
    6044                 :           0 :                 libpq_append_error(errorMessage, "service file \"%s\" not found", serviceFile);
    6045                 :           0 :                 return 1;
    6046                 :             :         }
    6047                 :             : 
    6048         [ #  # ]:           0 :         while ((line = fgets(buf, sizeof(buf), f)) != NULL)
    6049                 :             :         {
    6050                 :           0 :                 int                     len;
    6051                 :             : 
    6052                 :           0 :                 linenr++;
    6053                 :             : 
    6054         [ #  # ]:           0 :                 if (strlen(line) >= sizeof(buf) - 1)
    6055                 :             :                 {
    6056                 :           0 :                         libpq_append_error(errorMessage,
    6057                 :             :                                                            "line %d too long in service file \"%s\"",
    6058                 :           0 :                                                            linenr,
    6059                 :           0 :                                                            serviceFile);
    6060                 :           0 :                         result = 2;
    6061                 :           0 :                         goto exit;
    6062                 :             :                 }
    6063                 :             : 
    6064                 :             :                 /* ignore whitespace at end of line, especially the newline */
    6065                 :           0 :                 len = strlen(line);
    6066   [ #  #  #  # ]:           0 :                 while (len > 0 && isspace((unsigned char) line[len - 1]))
    6067                 :           0 :                         line[--len] = '\0';
    6068                 :             : 
    6069                 :             :                 /* ignore leading whitespace too */
    6070   [ #  #  #  # ]:           0 :                 while (*line && isspace((unsigned char) line[0]))
    6071                 :           0 :                         line++;
    6072                 :             : 
    6073                 :             :                 /* ignore comments and empty lines */
    6074   [ #  #  #  # ]:           0 :                 if (line[0] == '\0' || line[0] == '#')
    6075                 :           0 :                         continue;
    6076                 :             : 
    6077                 :             :                 /* Check for right groupname */
    6078         [ #  # ]:           0 :                 if (line[0] == '[')
    6079                 :             :                 {
    6080         [ #  # ]:           0 :                         if (*group_found)
    6081                 :             :                         {
    6082                 :             :                                 /* end of desired group reached; return success */
    6083                 :           0 :                                 goto exit;
    6084                 :             :                         }
    6085                 :             : 
    6086   [ #  #  #  # ]:           0 :                         if (strncmp(line + 1, service, strlen(service)) == 0 &&
    6087                 :           0 :                                 line[strlen(service) + 1] == ']')
    6088                 :           0 :                                 *group_found = true;
    6089                 :             :                         else
    6090                 :           0 :                                 *group_found = false;
    6091                 :           0 :                 }
    6092                 :             :                 else
    6093                 :             :                 {
    6094         [ #  # ]:           0 :                         if (*group_found)
    6095                 :             :                         {
    6096                 :             :                                 /*
    6097                 :             :                                  * Finally, we are in the right group and can parse the line
    6098                 :             :                                  */
    6099                 :           0 :                                 char       *key,
    6100                 :             :                                                    *val;
    6101                 :           0 :                                 bool            found_keyword;
    6102                 :             : 
    6103                 :             : #ifdef USE_LDAP
    6104                 :             :                                 if (strncmp(line, "ldap", 4) == 0)
    6105                 :             :                                 {
    6106                 :             :                                         int                     rc = ldapServiceLookup(line, options, errorMessage);
    6107                 :             : 
    6108                 :             :                                         /* if rc = 2, go on reading for fallback */
    6109                 :             :                                         switch (rc)
    6110                 :             :                                         {
    6111                 :             :                                                 case 0:
    6112                 :             :                                                         goto exit;
    6113                 :             :                                                 case 1:
    6114                 :             :                                                 case 3:
    6115                 :             :                                                         result = 3;
    6116                 :             :                                                         goto exit;
    6117                 :             :                                                 case 2:
    6118                 :             :                                                         continue;
    6119                 :             :                                         }
    6120                 :             :                                 }
    6121                 :             : #endif
    6122                 :             : 
    6123                 :           0 :                                 key = line;
    6124                 :           0 :                                 val = strchr(line, '=');
    6125         [ #  # ]:           0 :                                 if (val == NULL)
    6126                 :             :                                 {
    6127                 :           0 :                                         libpq_append_error(errorMessage,
    6128                 :             :                                                                            "syntax error in service file \"%s\", line %d",
    6129                 :           0 :                                                                            serviceFile,
    6130                 :           0 :                                                                            linenr);
    6131                 :           0 :                                         result = 3;
    6132                 :           0 :                                         goto exit;
    6133                 :             :                                 }
    6134                 :           0 :                                 *val++ = '\0';
    6135                 :             : 
    6136         [ #  # ]:           0 :                                 if (strcmp(key, "service") == 0)
    6137                 :             :                                 {
    6138                 :           0 :                                         libpq_append_error(errorMessage,
    6139                 :             :                                                                            "nested \"service\" specifications not supported in service file \"%s\", line %d",
    6140                 :           0 :                                                                            serviceFile,
    6141                 :           0 :                                                                            linenr);
    6142                 :           0 :                                         result = 3;
    6143                 :           0 :                                         goto exit;
    6144                 :             :                                 }
    6145                 :             : 
    6146         [ #  # ]:           0 :                                 if (strcmp(key, "servicefile") == 0)
    6147                 :             :                                 {
    6148                 :           0 :                                         libpq_append_error(errorMessage,
    6149                 :             :                                                                            "nested \"servicefile\" specifications not supported in service file \"%s\", line %d",
    6150                 :           0 :                                                                            serviceFile,
    6151                 :           0 :                                                                            linenr);
    6152                 :           0 :                                         result = 3;
    6153                 :           0 :                                         goto exit;
    6154                 :             :                                 }
    6155                 :             : 
    6156                 :             :                                 /*
    6157                 :             :                                  * Set the parameter --- but don't override any previous
    6158                 :             :                                  * explicit setting.
    6159                 :             :                                  */
    6160                 :           0 :                                 found_keyword = false;
    6161         [ #  # ]:           0 :                                 for (i = 0; options[i].keyword; i++)
    6162                 :             :                                 {
    6163         [ #  # ]:           0 :                                         if (strcmp(options[i].keyword, key) == 0)
    6164                 :             :                                         {
    6165         [ #  # ]:           0 :                                                 if (options[i].val == NULL)
    6166                 :           0 :                                                         options[i].val = strdup(val);
    6167         [ #  # ]:           0 :                                                 if (!options[i].val)
    6168                 :             :                                                 {
    6169                 :           0 :                                                         libpq_append_error(errorMessage, "out of memory");
    6170                 :           0 :                                                         result = 3;
    6171                 :           0 :                                                         goto exit;
    6172                 :             :                                                 }
    6173                 :           0 :                                                 found_keyword = true;
    6174                 :           0 :                                                 break;
    6175                 :             :                                         }
    6176                 :           0 :                                 }
    6177                 :             : 
    6178         [ #  # ]:           0 :                                 if (!found_keyword)
    6179                 :             :                                 {
    6180                 :           0 :                                         libpq_append_error(errorMessage,
    6181                 :             :                                                                            "syntax error in service file \"%s\", line %d",
    6182                 :           0 :                                                                            serviceFile,
    6183                 :           0 :                                                                            linenr);
    6184                 :           0 :                                         result = 3;
    6185                 :           0 :                                         goto exit;
    6186                 :             :                                 }
    6187         [ #  # ]:           0 :                         }
    6188                 :             :                 }
    6189   [ #  #  #  # ]:           0 :         }
    6190                 :             : 
    6191                 :             : exit:
    6192                 :             : 
    6193                 :             :         /*
    6194                 :             :          * If a service has been successfully found, set the "servicefile" option
    6195                 :             :          * if not already set.  This matters when we use a default service file or
    6196                 :             :          * PGSERVICEFILE, where we want to be able track the value.
    6197                 :             :          */
    6198   [ #  #  #  # ]:           0 :         if (*group_found && result == 0)
    6199                 :             :         {
    6200         [ #  # ]:           0 :                 for (i = 0; options[i].keyword; i++)
    6201                 :             :                 {
    6202         [ #  # ]:           0 :                         if (strcmp(options[i].keyword, "servicefile") != 0)
    6203                 :           0 :                                 continue;
    6204                 :             : 
    6205                 :             :                         /* If value is already set, nothing to do */
    6206         [ #  # ]:           0 :                         if (options[i].val != NULL)
    6207                 :           0 :                                 break;
    6208                 :             : 
    6209                 :           0 :                         options[i].val = strdup(serviceFile);
    6210         [ #  # ]:           0 :                         if (options[i].val == NULL)
    6211                 :             :                         {
    6212                 :           0 :                                 libpq_append_error(errorMessage, "out of memory");
    6213                 :           0 :                                 result = 3;
    6214                 :           0 :                         }
    6215                 :           0 :                         break;
    6216                 :             :                 }
    6217                 :           0 :         }
    6218                 :             : 
    6219                 :           0 :         fclose(f);
    6220                 :             : 
    6221                 :           0 :         return result;
    6222                 :           0 : }
    6223                 :             : 
    6224                 :             : 
    6225                 :             : /*
    6226                 :             :  *              PQconninfoParse
    6227                 :             :  *
    6228                 :             :  * Parse a string like PQconnectdb() would do and return the
    6229                 :             :  * resulting connection options array.  NULL is returned on failure.
    6230                 :             :  * The result contains only options specified directly in the string,
    6231                 :             :  * not any possible default values.
    6232                 :             :  *
    6233                 :             :  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
    6234                 :             :  * string on failure (use PQfreemem to free it).  In out-of-memory conditions
    6235                 :             :  * both *errmsg and the result could be NULL.
    6236                 :             :  *
    6237                 :             :  * NOTE: the returned array is dynamically allocated and should
    6238                 :             :  * be freed when no longer needed via PQconninfoFree().
    6239                 :             :  */
    6240                 :             : PQconninfoOption *
    6241                 :          22 : PQconninfoParse(const char *conninfo, char **errmsg)
    6242                 :             : {
    6243                 :          22 :         PQExpBufferData errorBuf;
    6244                 :          22 :         PQconninfoOption *connOptions;
    6245                 :             : 
    6246         [ -  + ]:          22 :         if (errmsg)
    6247                 :          22 :                 *errmsg = NULL;                 /* default */
    6248                 :          22 :         initPQExpBuffer(&errorBuf);
    6249         [ +  - ]:          22 :         if (PQExpBufferDataBroken(errorBuf))
    6250                 :           0 :                 return NULL;                    /* out of memory already :-( */
    6251                 :          22 :         connOptions = parse_connection_string(conninfo, &errorBuf, false);
    6252   [ +  +  -  + ]:          22 :         if (connOptions == NULL && errmsg)
    6253                 :           3 :                 *errmsg = errorBuf.data;
    6254                 :             :         else
    6255                 :          19 :                 termPQExpBuffer(&errorBuf);
    6256                 :          22 :         return connOptions;
    6257                 :          22 : }
    6258                 :             : 
    6259                 :             : /*
    6260                 :             :  * Build a working copy of the constant PQconninfoOptions array.
    6261                 :             :  */
    6262                 :             : static PQconninfoOption *
    6263                 :        1037 : conninfo_init(PQExpBuffer errorMessage)
    6264                 :             : {
    6265                 :        1037 :         PQconninfoOption *options;
    6266                 :        1037 :         PQconninfoOption *opt_dest;
    6267                 :        1037 :         const internalPQconninfoOption *cur_opt;
    6268                 :             : 
    6269                 :             :         /*
    6270                 :             :          * Get enough memory for all options in PQconninfoOptions, even if some
    6271                 :             :          * end up being filtered out.
    6272                 :             :          */
    6273                 :        1037 :         options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
    6274         [ +  - ]:        1037 :         if (options == NULL)
    6275                 :             :         {
    6276                 :           0 :                 libpq_append_error(errorMessage, "out of memory");
    6277                 :           0 :                 return NULL;
    6278                 :             :         }
    6279                 :        1037 :         opt_dest = options;
    6280                 :             : 
    6281         [ +  + ]:       53924 :         for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
    6282                 :             :         {
    6283                 :             :                 /* Only copy the public part of the struct, not the full internal */
    6284                 :       52887 :                 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
    6285                 :       52887 :                 opt_dest++;
    6286                 :       52887 :         }
    6287   [ +  -  +  -  :        8296 :         MemSet(opt_dest, 0, sizeof(PQconninfoOption));
          +  -  -  +  +  
                      + ]
    6288                 :             : 
    6289                 :        1037 :         return options;
    6290                 :        1037 : }
    6291                 :             : 
    6292                 :             : /*
    6293                 :             :  * Connection string parser
    6294                 :             :  *
    6295                 :             :  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
    6296                 :             :  * Otherwise, NULL is returned and an error message is added to errorMessage.
    6297                 :             :  *
    6298                 :             :  * If use_defaults is true, default values are filled in (from a service file,
    6299                 :             :  * environment variables, etc).
    6300                 :             :  */
    6301                 :             : static PQconninfoOption *
    6302                 :          46 : parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
    6303                 :             :                                                 bool use_defaults)
    6304                 :             : {
    6305                 :             :         /* Parse as URI if connection string matches URI prefix */
    6306         [ -  + ]:          46 :         if (uri_prefix_length(connstr) != 0)
    6307                 :           0 :                 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
    6308                 :             : 
    6309                 :             :         /* Parse as default otherwise */
    6310                 :          46 :         return conninfo_parse(connstr, errorMessage, use_defaults);
    6311                 :          46 : }
    6312                 :             : 
    6313                 :             : /*
    6314                 :             :  * Checks if connection string starts with either of the valid URI prefix
    6315                 :             :  * designators.
    6316                 :             :  *
    6317                 :             :  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
    6318                 :             :  *
    6319                 :             :  * XXX this is duplicated in psql/common.c.
    6320                 :             :  */
    6321                 :             : static int
    6322                 :         321 : uri_prefix_length(const char *connstr)
    6323                 :             : {
    6324                 :         321 :         if (strncmp(connstr, uri_designator,
    6325         [ +  - ]:         321 :                                 sizeof(uri_designator) - 1) == 0)
    6326                 :           0 :                 return sizeof(uri_designator) - 1;
    6327                 :             : 
    6328                 :         321 :         if (strncmp(connstr, short_uri_designator,
    6329         [ +  - ]:         321 :                                 sizeof(short_uri_designator) - 1) == 0)
    6330                 :           0 :                 return sizeof(short_uri_designator) - 1;
    6331                 :             : 
    6332                 :         321 :         return 0;
    6333                 :         321 : }
    6334                 :             : 
    6335                 :             : /*
    6336                 :             :  * Recognized connection string either starts with a valid URI prefix or
    6337                 :             :  * contains a "=" in it.
    6338                 :             :  *
    6339                 :             :  * Must be consistent with parse_connection_string: anything for which this
    6340                 :             :  * returns true should at least look like it's parseable by that routine.
    6341                 :             :  *
    6342                 :             :  * XXX this is duplicated in psql/common.c
    6343                 :             :  */
    6344                 :             : static bool
    6345                 :         275 : recognized_connection_string(const char *connstr)
    6346                 :             : {
    6347         [ -  + ]:         275 :         return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
    6348                 :             : }
    6349                 :             : 
    6350                 :             : /*
    6351                 :             :  * Subroutine for parse_connection_string
    6352                 :             :  *
    6353                 :             :  * Deal with a string containing key=value pairs.
    6354                 :             :  */
    6355                 :             : static PQconninfoOption *
    6356                 :          46 : conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
    6357                 :             :                            bool use_defaults)
    6358                 :             : {
    6359                 :          46 :         char       *pname;
    6360                 :          46 :         char       *pval;
    6361                 :          46 :         char       *buf;
    6362                 :          46 :         char       *cp;
    6363                 :          46 :         char       *cp2;
    6364                 :          46 :         PQconninfoOption *options;
    6365                 :             : 
    6366                 :             :         /* Make a working copy of PQconninfoOptions */
    6367                 :          46 :         options = conninfo_init(errorMessage);
    6368         [ +  - ]:          46 :         if (options == NULL)
    6369                 :           0 :                 return NULL;
    6370                 :             : 
    6371                 :             :         /* Need a modifiable copy of the input string */
    6372         [ +  - ]:          46 :         if ((buf = strdup(conninfo)) == NULL)
    6373                 :             :         {
    6374                 :           0 :                 libpq_append_error(errorMessage, "out of memory");
    6375                 :           0 :                 PQconninfoFree(options);
    6376                 :           0 :                 return NULL;
    6377                 :             :         }
    6378                 :          46 :         cp = buf;
    6379                 :             : 
    6380         [ +  + ]:         135 :         while (*cp)
    6381                 :             :         {
    6382                 :             :                 /* Skip blanks before the parameter name */
    6383         [ -  + ]:          92 :                 if (isspace((unsigned char) *cp))
    6384                 :             :                 {
    6385                 :           0 :                         cp++;
    6386                 :           0 :                         continue;
    6387                 :             :                 }
    6388                 :             : 
    6389                 :             :                 /* Get the parameter name */
    6390                 :          92 :                 pname = cp;
    6391         [ +  + ]:         554 :                 while (*cp)
    6392                 :             :                 {
    6393         [ +  + ]:         552 :                         if (*cp == '=')
    6394                 :          90 :                                 break;
    6395         [ -  + ]:         462 :                         if (isspace((unsigned char) *cp))
    6396                 :             :                         {
    6397                 :           0 :                                 *cp++ = '\0';
    6398         [ #  # ]:           0 :                                 while (*cp)
    6399                 :             :                                 {
    6400         [ #  # ]:           0 :                                         if (!isspace((unsigned char) *cp))
    6401                 :           0 :                                                 break;
    6402                 :           0 :                                         cp++;
    6403                 :             :                                 }
    6404                 :           0 :                                 break;
    6405                 :             :                         }
    6406                 :         462 :                         cp++;
    6407                 :             :                 }
    6408                 :             : 
    6409                 :             :                 /* Check that there is a following '=' */
    6410         [ +  + ]:          92 :                 if (*cp != '=')
    6411                 :             :                 {
    6412                 :           4 :                         libpq_append_error(errorMessage,
    6413                 :             :                                                            "missing \"=\" after \"%s\" in connection info string",
    6414                 :           2 :                                                            pname);
    6415                 :           2 :                         PQconninfoFree(options);
    6416                 :           2 :                         free(buf);
    6417                 :           2 :                         return NULL;
    6418                 :             :                 }
    6419                 :          90 :                 *cp++ = '\0';
    6420                 :             : 
    6421                 :             :                 /* Skip blanks after the '=' */
    6422         [ -  + ]:          90 :                 while (*cp)
    6423                 :             :                 {
    6424         [ +  - ]:          90 :                         if (!isspace((unsigned char) *cp))
    6425                 :          90 :                                 break;
    6426                 :           0 :                         cp++;
    6427                 :             :                 }
    6428                 :             : 
    6429                 :             :                 /* Get the parameter value */
    6430                 :          90 :                 pval = cp;
    6431                 :             : 
    6432         [ +  + ]:          90 :                 if (*cp != '\'')
    6433                 :             :                 {
    6434                 :          67 :                         cp2 = pval;
    6435         [ +  + ]:        1873 :                         while (*cp)
    6436                 :             :                         {
    6437         [ +  + ]:        1853 :                                 if (isspace((unsigned char) *cp))
    6438                 :             :                                 {
    6439                 :          47 :                                         *cp++ = '\0';
    6440                 :          47 :                                         break;
    6441                 :             :                                 }
    6442         [ -  + ]:        1806 :                                 if (*cp == '\\')
    6443                 :             :                                 {
    6444                 :           0 :                                         cp++;
    6445         [ #  # ]:           0 :                                         if (*cp != '\0')
    6446                 :           0 :                                                 *cp2++ = *cp++;
    6447                 :           0 :                                 }
    6448                 :             :                                 else
    6449                 :        1806 :                                         *cp2++ = *cp++;
    6450                 :             :                         }
    6451                 :          67 :                         *cp2 = '\0';
    6452                 :          67 :                 }
    6453                 :             :                 else
    6454                 :             :                 {
    6455                 :          23 :                         cp2 = pval;
    6456                 :          23 :                         cp++;
    6457                 :         207 :                         for (;;)
    6458                 :             :                         {
    6459         [ +  - ]:         207 :                                 if (*cp == '\0')
    6460                 :             :                                 {
    6461                 :           0 :                                         libpq_append_error(errorMessage, "unterminated quoted string in connection info string");
    6462                 :           0 :                                         PQconninfoFree(options);
    6463                 :           0 :                                         free(buf);
    6464                 :           0 :                                         return NULL;
    6465                 :             :                                 }
    6466         [ -  + ]:         207 :                                 if (*cp == '\\')
    6467                 :             :                                 {
    6468                 :           0 :                                         cp++;
    6469         [ #  # ]:           0 :                                         if (*cp != '\0')
    6470                 :           0 :                                                 *cp2++ = *cp++;
    6471                 :           0 :                                         continue;
    6472                 :             :                                 }
    6473         [ +  + ]:         207 :                                 if (*cp == '\'')
    6474                 :             :                                 {
    6475                 :          23 :                                         *cp2 = '\0';
    6476                 :          23 :                                         cp++;
    6477                 :          23 :                                         break;
    6478                 :             :                                 }
    6479                 :         184 :                                 *cp2++ = *cp++;
    6480                 :             :                         }
    6481                 :             :                 }
    6482                 :             : 
    6483                 :             :                 /*
    6484                 :             :                  * Now that we have the name and the value, store the record.
    6485                 :             :                  */
    6486         [ +  + ]:          90 :                 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
    6487                 :             :                 {
    6488                 :           1 :                         PQconninfoFree(options);
    6489                 :           1 :                         free(buf);
    6490                 :           1 :                         return NULL;
    6491                 :             :                 }
    6492                 :             :         }
    6493                 :             : 
    6494                 :             :         /* Done with the modifiable input string */
    6495                 :          43 :         free(buf);
    6496                 :             : 
    6497                 :             :         /*
    6498                 :             :          * Add in defaults if the caller wants that.
    6499                 :             :          */
    6500         [ +  - ]:          43 :         if (use_defaults)
    6501                 :             :         {
    6502         [ #  # ]:           0 :                 if (!conninfo_add_defaults(options, errorMessage))
    6503                 :             :                 {
    6504                 :           0 :                         PQconninfoFree(options);
    6505                 :           0 :                         return NULL;
    6506                 :             :                 }
    6507                 :           0 :         }
    6508                 :             : 
    6509                 :          43 :         return options;
    6510                 :          46 : }
    6511                 :             : 
    6512                 :             : /*
    6513                 :             :  * Conninfo array parser routine
    6514                 :             :  *
    6515                 :             :  * If successful, a malloc'd PQconninfoOption array is returned.
    6516                 :             :  * If not successful, NULL is returned and an error message is
    6517                 :             :  * appended to errorMessage.
    6518                 :             :  * Defaults are supplied (from a service file, environment variables, etc)
    6519                 :             :  * for unspecified options, but only if use_defaults is true.
    6520                 :             :  *
    6521                 :             :  * If expand_dbname is non-zero, and the value passed for the first occurrence
    6522                 :             :  * of "dbname" keyword is a connection string (as indicated by
    6523                 :             :  * recognized_connection_string) then parse and process it, overriding any
    6524                 :             :  * previously processed conflicting keywords. Subsequent keywords will take
    6525                 :             :  * precedence, however. In-tree programs generally specify expand_dbname=true,
    6526                 :             :  * so command-line arguments naming a database can use a connection string.
    6527                 :             :  * Some code acquires arbitrary database names from known-literal sources like
    6528                 :             :  * PQdb(), PQconninfoParse() and pg_database.datname.  When connecting to such
    6529                 :             :  * a database, in-tree code first wraps the name in a connection string.
    6530                 :             :  */
    6531                 :             : static PQconninfoOption *
    6532                 :         318 : conninfo_array_parse(const char *const *keywords, const char *const *values,
    6533                 :             :                                          PQExpBuffer errorMessage, bool use_defaults,
    6534                 :             :                                          int expand_dbname)
    6535                 :             : {
    6536                 :         318 :         PQconninfoOption *options;
    6537                 :         318 :         PQconninfoOption *dbname_options = NULL;
    6538                 :         318 :         PQconninfoOption *option;
    6539                 :         318 :         int                     i = 0;
    6540                 :             : 
    6541                 :             :         /*
    6542                 :             :          * If expand_dbname is non-zero, check keyword "dbname" to see if val is
    6543                 :             :          * actually a recognized connection string.
    6544                 :             :          */
    6545   [ +  +  +  + ]:        1406 :         while (expand_dbname && keywords[i])
    6546                 :             :         {
    6547                 :        1363 :                 const char *pname = keywords[i];
    6548                 :        1363 :                 const char *pvalue = values[i];
    6549                 :             : 
    6550                 :             :                 /* first find "dbname" if any */
    6551   [ +  +  -  + ]:        1363 :                 if (strcmp(pname, "dbname") == 0 && pvalue)
    6552                 :             :                 {
    6553                 :             :                         /*
    6554                 :             :                          * If value is a connection string, parse it, but do not use
    6555                 :             :                          * defaults here -- those get picked up later. We only want to
    6556                 :             :                          * override for those parameters actually passed.
    6557                 :             :                          */
    6558         [ +  + ]:         275 :                         if (recognized_connection_string(pvalue))
    6559                 :             :                         {
    6560                 :          24 :                                 dbname_options = parse_connection_string(pvalue, errorMessage, false);
    6561         [ +  - ]:          24 :                                 if (dbname_options == NULL)
    6562                 :           0 :                                         return NULL;
    6563                 :          24 :                         }
    6564                 :         275 :                         break;
    6565                 :             :                 }
    6566                 :        1088 :                 ++i;
    6567      [ -  +  + ]:        1363 :         }
    6568                 :             : 
    6569                 :             :         /* Make a working copy of PQconninfoOptions */
    6570                 :         318 :         options = conninfo_init(errorMessage);
    6571         [ +  - ]:         318 :         if (options == NULL)
    6572                 :             :         {
    6573                 :           0 :                 PQconninfoFree(dbname_options);
    6574                 :           0 :                 return NULL;
    6575                 :             :         }
    6576                 :             : 
    6577                 :             :         /* Parse the keywords/values arrays */
    6578                 :         318 :         i = 0;
    6579         [ +  + ]:        3093 :         while (keywords[i])
    6580                 :             :         {
    6581                 :        2775 :                 const char *pname = keywords[i];
    6582                 :        2775 :                 const char *pvalue = values[i];
    6583                 :             : 
    6584   [ +  +  -  + ]:        2775 :                 if (pvalue != NULL && pvalue[0] != '\0')
    6585                 :             :                 {
    6586                 :             :                         /* Search for the param record */
    6587         [ -  + ]:       25666 :                         for (option = options; option->keyword != NULL; option++)
    6588                 :             :                         {
    6589         [ +  + ]:       25666 :                                 if (strcmp(option->keyword, pname) == 0)
    6590                 :        1415 :                                         break;
    6591                 :       24251 :                         }
    6592                 :             : 
    6593                 :             :                         /* Check for invalid connection option */
    6594         [ -  + ]:        1415 :                         if (option->keyword == NULL)
    6595                 :             :                         {
    6596                 :           0 :                                 libpq_append_error(errorMessage, "invalid connection option \"%s\"", pname);
    6597                 :           0 :                                 PQconninfoFree(options);
    6598                 :           0 :                                 PQconninfoFree(dbname_options);
    6599                 :           0 :                                 return NULL;
    6600                 :             :                         }
    6601                 :             : 
    6602                 :             :                         /*
    6603                 :             :                          * If we are on the first dbname parameter, and we have a parsed
    6604                 :             :                          * connection string, copy those parameters across, overriding any
    6605                 :             :                          * existing previous settings.
    6606                 :             :                          */
    6607   [ +  +  +  + ]:        1415 :                         if (strcmp(pname, "dbname") == 0 && dbname_options)
    6608                 :             :                         {
    6609                 :          24 :                                 PQconninfoOption *str_option;
    6610                 :             : 
    6611         [ +  + ]:        1248 :                                 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
    6612                 :             :                                 {
    6613         [ +  + ]:        1224 :                                         if (str_option->val != NULL)
    6614                 :             :                                         {
    6615                 :          70 :                                                 int                     k;
    6616                 :             : 
    6617         [ -  + ]:         655 :                                                 for (k = 0; options[k].keyword; k++)
    6618                 :             :                                                 {
    6619         [ +  + ]:         655 :                                                         if (strcmp(options[k].keyword, str_option->keyword) == 0)
    6620                 :             :                                                         {
    6621                 :          70 :                                                                 free(options[k].val);
    6622                 :          70 :                                                                 options[k].val = strdup(str_option->val);
    6623         [ +  - ]:          70 :                                                                 if (!options[k].val)
    6624                 :             :                                                                 {
    6625                 :           0 :                                                                         libpq_append_error(errorMessage, "out of memory");
    6626                 :           0 :                                                                         PQconninfoFree(options);
    6627                 :           0 :                                                                         PQconninfoFree(dbname_options);
    6628                 :           0 :                                                                         return NULL;
    6629                 :             :                                                                 }
    6630                 :          70 :                                                                 break;
    6631                 :             :                                                         }
    6632                 :         585 :                                                 }
    6633         [ -  + ]:          70 :                                         }
    6634                 :        1224 :                                 }
    6635                 :             : 
    6636                 :             :                                 /*
    6637                 :             :                                  * Forget the parsed connection string, so that any subsequent
    6638                 :             :                                  * dbname parameters will not be expanded.
    6639                 :             :                                  */
    6640                 :          24 :                                 PQconninfoFree(dbname_options);
    6641                 :          24 :                                 dbname_options = NULL;
    6642         [ -  + ]:          24 :                         }
    6643                 :             :                         else
    6644                 :             :                         {
    6645                 :             :                                 /*
    6646                 :             :                                  * Store the value, overriding previous settings
    6647                 :             :                                  */
    6648                 :        1391 :                                 free(option->val);
    6649                 :        1391 :                                 option->val = strdup(pvalue);
    6650         [ +  - ]:        1391 :                                 if (!option->val)
    6651                 :             :                                 {
    6652                 :           0 :                                         libpq_append_error(errorMessage, "out of memory");
    6653                 :           0 :                                         PQconninfoFree(options);
    6654                 :           0 :                                         PQconninfoFree(dbname_options);
    6655                 :           0 :                                         return NULL;
    6656                 :             :                                 }
    6657                 :             :                         }
    6658                 :        1415 :                 }
    6659                 :        2775 :                 ++i;
    6660         [ -  + ]:        2775 :         }
    6661                 :         318 :         PQconninfoFree(dbname_options);
    6662                 :             : 
    6663                 :             :         /*
    6664                 :             :          * Add in defaults if the caller wants that.
    6665                 :             :          */
    6666         [ -  + ]:         318 :         if (use_defaults)
    6667                 :             :         {
    6668         [ +  - ]:         318 :                 if (!conninfo_add_defaults(options, errorMessage))
    6669                 :             :                 {
    6670                 :           0 :                         PQconninfoFree(options);
    6671                 :           0 :                         return NULL;
    6672                 :             :                 }
    6673                 :         318 :         }
    6674                 :             : 
    6675                 :         318 :         return options;
    6676                 :         318 : }
    6677                 :             : 
    6678                 :             : /*
    6679                 :             :  * Add the default values for any unspecified options to the connection
    6680                 :             :  * options array.
    6681                 :             :  *
    6682                 :             :  * Defaults are obtained from a service file, environment variables, etc.
    6683                 :             :  *
    6684                 :             :  * Returns true if successful, otherwise false; errorMessage, if supplied,
    6685                 :             :  * is filled in upon failure.  Note that failure to locate a default value
    6686                 :             :  * is not an error condition here --- we just leave the option's value as
    6687                 :             :  * NULL.
    6688                 :             :  */
    6689                 :             : static bool
    6690                 :         318 : conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
    6691                 :             : {
    6692                 :         318 :         PQconninfoOption *option;
    6693                 :         318 :         PQconninfoOption *sslmode_default = NULL,
    6694                 :         318 :                            *sslrootcert = NULL;
    6695                 :         318 :         char       *tmp;
    6696                 :             : 
    6697                 :             :         /*
    6698                 :             :          * If there's a service spec, use it to obtain any not-explicitly-given
    6699                 :             :          * parameters.  Ignore error if no error message buffer is passed because
    6700                 :             :          * there is no way to pass back the failure message.
    6701                 :             :          */
    6702   [ -  +  #  # ]:         318 :         if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
    6703                 :           0 :                 return false;
    6704                 :             : 
    6705                 :             :         /*
    6706                 :             :          * Get the fallback resources for parameters not specified in the conninfo
    6707                 :             :          * string nor the service.
    6708                 :             :          */
    6709         [ +  + ]:       16536 :         for (option = options; option->keyword != NULL; option++)
    6710                 :             :         {
    6711         [ +  + ]:       16218 :                 if (strcmp(option->keyword, "sslrootcert") == 0)
    6712                 :         318 :                         sslrootcert = option;   /* save for later */
    6713                 :             : 
    6714         [ +  + ]:       16218 :                 if (option->val != NULL)
    6715                 :        1461 :                         continue;                       /* Value was in conninfo or service */
    6716                 :             : 
    6717                 :             :                 /*
    6718                 :             :                  * Try to get the environment variable fallback
    6719                 :             :                  */
    6720         [ +  + ]:       14757 :                 if (option->envvar != NULL)
    6721                 :             :                 {
    6722         [ +  + ]:       10304 :                         if ((tmp = getenv(option->envvar)) != NULL)
    6723                 :             :                         {
    6724                 :        1025 :                                 option->val = strdup(tmp);
    6725         [ -  + ]:        1025 :                                 if (!option->val)
    6726                 :             :                                 {
    6727         [ #  # ]:           0 :                                         if (errorMessage)
    6728                 :           0 :                                                 libpq_append_error(errorMessage, "out of memory");
    6729                 :           0 :                                         return false;
    6730                 :             :                                 }
    6731                 :        1025 :                                 continue;
    6732                 :             :                         }
    6733                 :        9279 :                 }
    6734                 :             : 
    6735                 :             :                 /*
    6736                 :             :                  * Interpret the deprecated PGREQUIRESSL environment variable.  Per
    6737                 :             :                  * tradition, translate values starting with "1" to sslmode=require,
    6738                 :             :                  * and ignore other values.  Given both PGREQUIRESSL=1 and PGSSLMODE,
    6739                 :             :                  * PGSSLMODE takes precedence; the opposite was true before v9.3.
    6740                 :             :                  */
    6741         [ +  + ]:       13732 :                 if (strcmp(option->keyword, "sslmode") == 0)
    6742                 :             :                 {
    6743                 :         275 :                         const char *requiresslenv = getenv("PGREQUIRESSL");
    6744                 :             : 
    6745   [ -  +  #  # ]:         275 :                         if (requiresslenv != NULL && requiresslenv[0] == '1')
    6746                 :             :                         {
    6747                 :           0 :                                 option->val = strdup("require");
    6748         [ #  # ]:           0 :                                 if (!option->val)
    6749                 :             :                                 {
    6750         [ #  # ]:           0 :                                         if (errorMessage)
    6751                 :           0 :                                                 libpq_append_error(errorMessage, "out of memory");
    6752                 :           0 :                                         return false;
    6753                 :             :                                 }
    6754                 :           0 :                                 continue;
    6755                 :             :                         }
    6756                 :             : 
    6757                 :             :                         /*
    6758                 :             :                          * sslmode is not specified. Let it be filled in with the compiled
    6759                 :             :                          * default for now, but if sslrootcert=system, we'll override the
    6760                 :             :                          * default later before returning.
    6761                 :             :                          */
    6762                 :         275 :                         sslmode_default = option;
    6763      [ -  -  + ]:         275 :                 }
    6764                 :             : 
    6765                 :             :                 /*
    6766                 :             :                  * No environment variable specified or the variable isn't set - try
    6767                 :             :                  * compiled-in default
    6768                 :             :                  */
    6769         [ +  + ]:       13732 :                 if (option->compiled != NULL)
    6770                 :             :                 {
    6771                 :        3048 :                         option->val = strdup(option->compiled);
    6772         [ +  - ]:        3048 :                         if (!option->val)
    6773                 :             :                         {
    6774         [ #  # ]:           0 :                                 if (errorMessage)
    6775                 :           0 :                                         libpq_append_error(errorMessage, "out of memory");
    6776                 :           0 :                                 return false;
    6777                 :             :                         }
    6778                 :        3048 :                         continue;
    6779                 :             :                 }
    6780                 :             : 
    6781                 :             :                 /*
    6782                 :             :                  * Special handling for "user" option.  Note that if pg_fe_getauthname
    6783                 :             :                  * fails, we just leave the value as NULL; there's no need for this to
    6784                 :             :                  * be an error condition if the caller provides a user name.  The only
    6785                 :             :                  * reason we do this now at all is so that callers of PQconndefaults
    6786                 :             :                  * will see a correct default (barring error, of course).
    6787                 :             :                  */
    6788         [ +  + ]:       10684 :                 if (strcmp(option->keyword, "user") == 0)
    6789                 :             :                 {
    6790                 :         275 :                         option->val = pg_fe_getauthname(NULL);
    6791                 :         275 :                         continue;
    6792                 :             :                 }
    6793                 :       10409 :         }
    6794                 :             : 
    6795                 :             :         /*
    6796                 :             :          * Special handling for sslrootcert=system with no sslmode explicitly
    6797                 :             :          * defined. In this case we want to strengthen the default sslmode to
    6798                 :             :          * verify-full.
    6799                 :             :          */
    6800   [ +  +  -  + ]:         318 :         if (sslmode_default && sslrootcert)
    6801                 :             :         {
    6802   [ -  +  #  # ]:         275 :                 if (sslrootcert->val && strcmp(sslrootcert->val, "system") == 0)
    6803                 :             :                 {
    6804                 :           0 :                         free(sslmode_default->val);
    6805                 :             : 
    6806                 :           0 :                         sslmode_default->val = strdup("verify-full");
    6807         [ #  # ]:           0 :                         if (!sslmode_default->val)
    6808                 :             :                         {
    6809         [ #  # ]:           0 :                                 if (errorMessage)
    6810                 :           0 :                                         libpq_append_error(errorMessage, "out of memory");
    6811                 :           0 :                                 return false;
    6812                 :             :                         }
    6813                 :           0 :                 }
    6814                 :         275 :         }
    6815                 :             : 
    6816                 :         318 :         return true;
    6817                 :         318 : }
    6818                 :             : 
    6819                 :             : /*
    6820                 :             :  * Subroutine for parse_connection_string
    6821                 :             :  *
    6822                 :             :  * Deal with a URI connection string.
    6823                 :             :  */
    6824                 :             : static PQconninfoOption *
    6825                 :           0 : conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
    6826                 :             :                                    bool use_defaults)
    6827                 :             : {
    6828                 :           0 :         PQconninfoOption *options;
    6829                 :             : 
    6830                 :             :         /* Make a working copy of PQconninfoOptions */
    6831                 :           0 :         options = conninfo_init(errorMessage);
    6832         [ #  # ]:           0 :         if (options == NULL)
    6833                 :           0 :                 return NULL;
    6834                 :             : 
    6835         [ #  # ]:           0 :         if (!conninfo_uri_parse_options(options, uri, errorMessage))
    6836                 :             :         {
    6837                 :           0 :                 PQconninfoFree(options);
    6838                 :           0 :                 return NULL;
    6839                 :             :         }
    6840                 :             : 
    6841                 :             :         /*
    6842                 :             :          * Add in defaults if the caller wants that.
    6843                 :             :          */
    6844         [ #  # ]:           0 :         if (use_defaults)
    6845                 :             :         {
    6846         [ #  # ]:           0 :                 if (!conninfo_add_defaults(options, errorMessage))
    6847                 :             :                 {
    6848                 :           0 :                         PQconninfoFree(options);
    6849                 :           0 :                         return NULL;
    6850                 :             :                 }
    6851                 :           0 :         }
    6852                 :             : 
    6853                 :           0 :         return options;
    6854                 :           0 : }
    6855                 :             : 
    6856                 :             : /*
    6857                 :             :  * conninfo_uri_parse_options
    6858                 :             :  *              Actual URI parser.
    6859                 :             :  *
    6860                 :             :  * If successful, returns true while the options array is filled with parsed
    6861                 :             :  * options from the URI.
    6862                 :             :  * If not successful, returns false and fills errorMessage accordingly.
    6863                 :             :  *
    6864                 :             :  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
    6865                 :             :  * 3986):
    6866                 :             :  *
    6867                 :             :  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
    6868                 :             :  *
    6869                 :             :  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
    6870                 :             :  * by literal square brackets.  As an extension, we also allow multiple
    6871                 :             :  * netloc[:port] specifications, separated by commas:
    6872                 :             :  *
    6873                 :             :  * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
    6874                 :             :  *
    6875                 :             :  * Any of the URI parts might use percent-encoding (%xy).
    6876                 :             :  */
    6877                 :             : static bool
    6878                 :           0 : conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
    6879                 :             :                                                    PQExpBuffer errorMessage)
    6880                 :             : {
    6881                 :           0 :         int                     prefix_len;
    6882                 :           0 :         char       *p;
    6883                 :           0 :         char       *buf = NULL;
    6884                 :           0 :         char       *start;
    6885                 :           0 :         char            prevchar = '\0';
    6886                 :           0 :         char       *user = NULL;
    6887                 :           0 :         char       *host = NULL;
    6888                 :           0 :         bool            retval = false;
    6889                 :           0 :         PQExpBufferData hostbuf;
    6890                 :           0 :         PQExpBufferData portbuf;
    6891                 :             : 
    6892                 :           0 :         initPQExpBuffer(&hostbuf);
    6893                 :           0 :         initPQExpBuffer(&portbuf);
    6894   [ #  #  #  # ]:           0 :         if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
    6895                 :             :         {
    6896                 :           0 :                 libpq_append_error(errorMessage, "out of memory");
    6897                 :           0 :                 goto cleanup;
    6898                 :             :         }
    6899                 :             : 
    6900                 :             :         /* need a modifiable copy of the input URI */
    6901                 :           0 :         buf = strdup(uri);
    6902         [ #  # ]:           0 :         if (buf == NULL)
    6903                 :             :         {
    6904                 :           0 :                 libpq_append_error(errorMessage, "out of memory");
    6905                 :           0 :                 goto cleanup;
    6906                 :             :         }
    6907                 :           0 :         start = buf;
    6908                 :             : 
    6909                 :             :         /* Skip the URI prefix */
    6910                 :           0 :         prefix_len = uri_prefix_length(uri);
    6911         [ #  # ]:           0 :         if (prefix_len == 0)
    6912                 :             :         {
    6913                 :             :                 /* Should never happen */
    6914                 :           0 :                 libpq_append_error(errorMessage,
    6915                 :             :                                                    "invalid URI propagated to internal parser routine: \"%s\"",
    6916                 :           0 :                                                    uri);
    6917                 :           0 :                 goto cleanup;
    6918                 :             :         }
    6919                 :           0 :         start += prefix_len;
    6920                 :           0 :         p = start;
    6921                 :             : 
    6922                 :             :         /* Look ahead for possible user credentials designator */
    6923   [ #  #  #  #  :           0 :         while (*p && *p != '@' && *p != '/')
                   #  # ]
    6924                 :           0 :                 ++p;
    6925         [ #  # ]:           0 :         if (*p == '@')
    6926                 :             :         {
    6927                 :             :                 /*
    6928                 :             :                  * Found username/password designator, so URI should be of the form
    6929                 :             :                  * "scheme://user[:password]@[netloc]".
    6930                 :             :                  */
    6931                 :           0 :                 user = start;
    6932                 :             : 
    6933                 :           0 :                 p = user;
    6934   [ #  #  #  # ]:           0 :                 while (*p != ':' && *p != '@')
    6935                 :           0 :                         ++p;
    6936                 :             : 
    6937                 :             :                 /* Save last char and cut off at end of user name */
    6938                 :           0 :                 prevchar = *p;
    6939                 :           0 :                 *p = '\0';
    6940                 :             : 
    6941   [ #  #  #  # ]:           0 :                 if (*user &&
    6942                 :           0 :                         !conninfo_storeval(options, "user", user,
    6943                 :           0 :                                                            errorMessage, false, true))
    6944                 :           0 :                         goto cleanup;
    6945                 :             : 
    6946         [ #  # ]:           0 :                 if (prevchar == ':')
    6947                 :             :                 {
    6948                 :           0 :                         const char *password = p + 1;
    6949                 :             : 
    6950         [ #  # ]:           0 :                         while (*p != '@')
    6951                 :           0 :                                 ++p;
    6952                 :           0 :                         *p = '\0';
    6953                 :             : 
    6954   [ #  #  #  # ]:           0 :                         if (*password &&
    6955                 :           0 :                                 !conninfo_storeval(options, "password", password,
    6956                 :           0 :                                                                    errorMessage, false, true))
    6957                 :           0 :                                 goto cleanup;
    6958      [ #  #  # ]:           0 :                 }
    6959                 :             : 
    6960                 :             :                 /* Advance past end of parsed user name or password token */
    6961                 :           0 :                 ++p;
    6962                 :           0 :         }
    6963                 :             :         else
    6964                 :             :         {
    6965                 :             :                 /*
    6966                 :             :                  * No username/password designator found.  Reset to start of URI.
    6967                 :             :                  */
    6968                 :           0 :                 p = start;
    6969                 :             :         }
    6970                 :             : 
    6971                 :             :         /*
    6972                 :             :          * There may be multiple netloc[:port] pairs, each separated from the next
    6973                 :             :          * by a comma.  When we initially enter this loop, "p" has been
    6974                 :             :          * incremented past optional URI credential information at this point and
    6975                 :             :          * now points at the "netloc" part of the URI.  On subsequent loop
    6976                 :             :          * iterations, "p" has been incremented past the comma separator and now
    6977                 :             :          * points at the start of the next "netloc".
    6978                 :             :          */
    6979                 :           0 :         for (;;)
    6980                 :             :         {
    6981                 :             :                 /*
    6982                 :             :                  * Look for IPv6 address.
    6983                 :             :                  */
    6984         [ #  # ]:           0 :                 if (*p == '[')
    6985                 :             :                 {
    6986                 :           0 :                         host = ++p;
    6987   [ #  #  #  # ]:           0 :                         while (*p && *p != ']')
    6988                 :           0 :                                 ++p;
    6989         [ #  # ]:           0 :                         if (!*p)
    6990                 :             :                         {
    6991                 :           0 :                                 libpq_append_error(errorMessage,
    6992                 :             :                                                                    "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
    6993                 :           0 :                                                                    uri);
    6994                 :           0 :                                 goto cleanup;
    6995                 :             :                         }
    6996         [ #  # ]:           0 :                         if (p == host)
    6997                 :             :                         {
    6998                 :           0 :                                 libpq_append_error(errorMessage,
    6999                 :             :                                                                    "IPv6 host address may not be empty in URI: \"%s\"",
    7000                 :           0 :                                                                    uri);
    7001                 :           0 :                                 goto cleanup;
    7002                 :             :                         }
    7003                 :             : 
    7004                 :             :                         /* Cut off the bracket and advance */
    7005                 :           0 :                         *(p++) = '\0';
    7006                 :             : 
    7007                 :             :                         /*
    7008                 :             :                          * The address may be followed by a port specifier or a slash or a
    7009                 :             :                          * query or a separator comma.
    7010                 :             :                          */
    7011   [ #  #  #  #  :           0 :                         if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
          #  #  #  #  #  
                      # ]
    7012                 :             :                         {
    7013                 :           0 :                                 libpq_append_error(errorMessage,
    7014                 :             :                                                                    "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
    7015                 :           0 :                                                                    *p, (int) (p - buf + 1), uri);
    7016                 :           0 :                                 goto cleanup;
    7017                 :             :                         }
    7018                 :           0 :                 }
    7019                 :             :                 else
    7020                 :             :                 {
    7021                 :             :                         /* not an IPv6 address: DNS-named or IPv4 netloc */
    7022                 :           0 :                         host = p;
    7023                 :             : 
    7024                 :             :                         /*
    7025                 :             :                          * Look for port specifier (colon) or end of host specifier
    7026                 :             :                          * (slash) or query (question mark) or host separator (comma).
    7027                 :             :                          */
    7028   [ #  #  #  #  :           0 :                         while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
          #  #  #  #  #  
                      # ]
    7029                 :           0 :                                 ++p;
    7030                 :             :                 }
    7031                 :             : 
    7032                 :             :                 /* Save the hostname terminator before we null it */
    7033                 :           0 :                 prevchar = *p;
    7034                 :           0 :                 *p = '\0';
    7035                 :             : 
    7036                 :           0 :                 appendPQExpBufferStr(&hostbuf, host);
    7037                 :             : 
    7038         [ #  # ]:           0 :                 if (prevchar == ':')
    7039                 :             :                 {
    7040                 :           0 :                         const char *port = ++p; /* advance past host terminator */
    7041                 :             : 
    7042   [ #  #  #  #  :           0 :                         while (*p && *p != '/' && *p != '?' && *p != ',')
             #  #  #  # ]
    7043                 :           0 :                                 ++p;
    7044                 :             : 
    7045                 :           0 :                         prevchar = *p;
    7046                 :           0 :                         *p = '\0';
    7047                 :             : 
    7048                 :           0 :                         appendPQExpBufferStr(&portbuf, port);
    7049                 :           0 :                 }
    7050                 :             : 
    7051         [ #  # ]:           0 :                 if (prevchar != ',')
    7052                 :           0 :                         break;
    7053                 :           0 :                 ++p;                                    /* advance past comma separator */
    7054                 :           0 :                 appendPQExpBufferChar(&hostbuf, ',');
    7055                 :           0 :                 appendPQExpBufferChar(&portbuf, ',');
    7056                 :             :         }
    7057                 :             : 
    7058                 :             :         /* Save final values for host and port. */
    7059   [ #  #  #  # ]:           0 :         if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
    7060                 :           0 :                 goto cleanup;
    7061   [ #  #  #  # ]:           0 :         if (hostbuf.data[0] &&
    7062                 :           0 :                 !conninfo_storeval(options, "host", hostbuf.data,
    7063                 :           0 :                                                    errorMessage, false, true))
    7064                 :           0 :                 goto cleanup;
    7065   [ #  #  #  # ]:           0 :         if (portbuf.data[0] &&
    7066                 :           0 :                 !conninfo_storeval(options, "port", portbuf.data,
    7067                 :           0 :                                                    errorMessage, false, true))
    7068                 :           0 :                 goto cleanup;
    7069                 :             : 
    7070   [ #  #  #  # ]:           0 :         if (prevchar && prevchar != '?')
    7071                 :             :         {
    7072                 :           0 :                 const char *dbname = ++p;       /* advance past host terminator */
    7073                 :             : 
    7074                 :             :                 /* Look for query parameters */
    7075   [ #  #  #  # ]:           0 :                 while (*p && *p != '?')
    7076                 :           0 :                         ++p;
    7077                 :             : 
    7078                 :           0 :                 prevchar = *p;
    7079                 :           0 :                 *p = '\0';
    7080                 :             : 
    7081                 :             :                 /*
    7082                 :             :                  * Avoid setting dbname to an empty string, as it forces the default
    7083                 :             :                  * value (username) and ignores $PGDATABASE, as opposed to not setting
    7084                 :             :                  * it at all.
    7085                 :             :                  */
    7086   [ #  #  #  # ]:           0 :                 if (*dbname &&
    7087                 :           0 :                         !conninfo_storeval(options, "dbname", dbname,
    7088                 :           0 :                                                            errorMessage, false, true))
    7089                 :           0 :                         goto cleanup;
    7090         [ #  # ]:           0 :         }
    7091                 :             : 
    7092         [ #  # ]:           0 :         if (prevchar)
    7093                 :             :         {
    7094                 :           0 :                 ++p;                                    /* advance past terminator */
    7095                 :             : 
    7096         [ #  # ]:           0 :                 if (!conninfo_uri_parse_params(p, options, errorMessage))
    7097                 :           0 :                         goto cleanup;
    7098                 :           0 :         }
    7099                 :             : 
    7100                 :             :         /* everything parsed okay */
    7101                 :           0 :         retval = true;
    7102                 :             : 
    7103                 :             : cleanup:
    7104                 :           0 :         termPQExpBuffer(&hostbuf);
    7105                 :           0 :         termPQExpBuffer(&portbuf);
    7106                 :           0 :         free(buf);
    7107                 :           0 :         return retval;
    7108                 :           0 : }
    7109                 :             : 
    7110                 :             : /*
    7111                 :             :  * Connection URI parameters parser routine
    7112                 :             :  *
    7113                 :             :  * If successful, returns true while connOptions is filled with parsed
    7114                 :             :  * parameters.  Otherwise, returns false and fills errorMessage appropriately.
    7115                 :             :  *
    7116                 :             :  * Destructively modifies 'params' buffer.
    7117                 :             :  */
    7118                 :             : static bool
    7119                 :           0 : conninfo_uri_parse_params(char *params,
    7120                 :             :                                                   PQconninfoOption *connOptions,
    7121                 :             :                                                   PQExpBuffer errorMessage)
    7122                 :             : {
    7123         [ #  # ]:           0 :         while (*params)
    7124                 :             :         {
    7125                 :           0 :                 char       *keyword = params;
    7126                 :           0 :                 char       *value = NULL;
    7127                 :           0 :                 char       *p = params;
    7128                 :           0 :                 bool            malloced = false;
    7129                 :           0 :                 int                     oldmsglen;
    7130                 :             : 
    7131                 :             :                 /*
    7132                 :             :                  * Scan the params string for '=' and '&', marking the end of keyword
    7133                 :             :                  * and value respectively.
    7134                 :             :                  */
    7135                 :           0 :                 for (;;)
    7136                 :             :                 {
    7137         [ #  # ]:           0 :                         if (*p == '=')
    7138                 :             :                         {
    7139                 :             :                                 /* Was there '=' already? */
    7140         [ #  # ]:           0 :                                 if (value != NULL)
    7141                 :             :                                 {
    7142                 :           0 :                                         libpq_append_error(errorMessage,
    7143                 :             :                                                                            "extra key/value separator \"=\" in URI query parameter: \"%s\"",
    7144                 :           0 :                                                                            keyword);
    7145                 :           0 :                                         return false;
    7146                 :             :                                 }
    7147                 :             :                                 /* Cut off keyword, advance to value */
    7148                 :           0 :                                 *p++ = '\0';
    7149                 :           0 :                                 value = p;
    7150                 :           0 :                         }
    7151   [ #  #  #  # ]:           0 :                         else if (*p == '&' || *p == '\0')
    7152                 :             :                         {
    7153                 :             :                                 /*
    7154                 :             :                                  * If not at the end, cut off value and advance; leave p
    7155                 :             :                                  * pointing to start of the next parameter, if any.
    7156                 :             :                                  */
    7157         [ #  # ]:           0 :                                 if (*p != '\0')
    7158                 :           0 :                                         *p++ = '\0';
    7159                 :             :                                 /* Was there '=' at all? */
    7160         [ #  # ]:           0 :                                 if (value == NULL)
    7161                 :             :                                 {
    7162                 :           0 :                                         libpq_append_error(errorMessage,
    7163                 :             :                                                                            "missing key/value separator \"=\" in URI query parameter: \"%s\"",
    7164                 :           0 :                                                                            keyword);
    7165                 :           0 :                                         return false;
    7166                 :             :                                 }
    7167                 :             :                                 /* Got keyword and value, go process them. */
    7168                 :           0 :                                 break;
    7169                 :             :                         }
    7170                 :             :                         else
    7171                 :           0 :                                 ++p;                    /* Advance over all other bytes. */
    7172                 :             :                 }
    7173                 :             : 
    7174                 :           0 :                 keyword = conninfo_uri_decode(keyword, errorMessage);
    7175         [ #  # ]:           0 :                 if (keyword == NULL)
    7176                 :             :                 {
    7177                 :             :                         /* conninfo_uri_decode already set an error message */
    7178                 :           0 :                         return false;
    7179                 :             :                 }
    7180                 :           0 :                 value = conninfo_uri_decode(value, errorMessage);
    7181         [ #  # ]:           0 :                 if (value == NULL)
    7182                 :             :                 {
    7183                 :             :                         /* conninfo_uri_decode already set an error message */
    7184                 :           0 :                         free(keyword);
    7185                 :           0 :                         return false;
    7186                 :             :                 }
    7187                 :           0 :                 malloced = true;
    7188                 :             : 
    7189                 :             :                 /*
    7190                 :             :                  * Special keyword handling for improved JDBC compatibility.
    7191                 :             :                  */
    7192   [ #  #  #  # ]:           0 :                 if (strcmp(keyword, "ssl") == 0 &&
    7193                 :           0 :                         strcmp(value, "true") == 0)
    7194                 :             :                 {
    7195                 :           0 :                         free(keyword);
    7196                 :           0 :                         free(value);
    7197                 :           0 :                         malloced = false;
    7198                 :             : 
    7199                 :           0 :                         keyword = "sslmode";
    7200                 :           0 :                         value = "require";
    7201                 :           0 :                 }
    7202                 :             : 
    7203                 :             :                 /*
    7204                 :             :                  * Store the value if the corresponding option exists; ignore
    7205                 :             :                  * otherwise.  At this point both keyword and value are not
    7206                 :             :                  * URI-encoded.
    7207                 :             :                  */
    7208                 :           0 :                 oldmsglen = errorMessage->len;
    7209   [ #  #  #  # ]:           0 :                 if (!conninfo_storeval(connOptions, keyword, value,
    7210                 :           0 :                                                            errorMessage, true, false))
    7211                 :             :                 {
    7212                 :             :                         /* Insert generic message if conninfo_storeval didn't give one. */
    7213         [ #  # ]:           0 :                         if (errorMessage->len == oldmsglen)
    7214                 :           0 :                                 libpq_append_error(errorMessage,
    7215                 :             :                                                                    "invalid URI query parameter: \"%s\"",
    7216                 :           0 :                                                                    keyword);
    7217                 :             :                         /* And fail. */
    7218         [ #  # ]:           0 :                         if (malloced)
    7219                 :             :                         {
    7220                 :           0 :                                 free(keyword);
    7221                 :           0 :                                 free(value);
    7222                 :           0 :                         }
    7223                 :           0 :                         return false;
    7224                 :             :                 }
    7225                 :             : 
    7226         [ #  # ]:           0 :                 if (malloced)
    7227                 :             :                 {
    7228                 :           0 :                         free(keyword);
    7229                 :           0 :                         free(value);
    7230                 :           0 :                 }
    7231                 :             : 
    7232                 :             :                 /* Proceed to next key=value pair, if any */
    7233                 :           0 :                 params = p;
    7234      [ #  #  # ]:           0 :         }
    7235                 :             : 
    7236                 :           0 :         return true;
    7237                 :           0 : }
    7238                 :             : 
    7239                 :             : /*
    7240                 :             :  * Connection URI decoder routine
    7241                 :             :  *
    7242                 :             :  * If successful, returns the malloc'd decoded string.
    7243                 :             :  * If not successful, returns NULL and fills errorMessage accordingly.
    7244                 :             :  *
    7245                 :             :  * The string is decoded by replacing any percent-encoded tokens with
    7246                 :             :  * corresponding characters, while preserving any non-encoded characters.  A
    7247                 :             :  * percent-encoded token is a character triplet: a percent sign, followed by a
    7248                 :             :  * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
    7249                 :             :  * treated identically.
    7250                 :             :  */
    7251                 :             : static char *
    7252                 :           0 : conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
    7253                 :             : {
    7254                 :           0 :         char       *buf;                        /* result */
    7255                 :           0 :         char       *p;                          /* output location */
    7256                 :           0 :         const char *q = str;            /* input location */
    7257                 :             : 
    7258                 :           0 :         buf = malloc(strlen(str) + 1);
    7259         [ #  # ]:           0 :         if (buf == NULL)
    7260                 :             :         {
    7261                 :           0 :                 libpq_append_error(errorMessage, "out of memory");
    7262                 :           0 :                 return NULL;
    7263                 :             :         }
    7264                 :           0 :         p = buf;
    7265                 :             : 
    7266                 :             :         /* skip leading whitespaces */
    7267         [ #  # ]:           0 :         for (const char *s = q; *s == ' '; s++)
    7268                 :             :         {
    7269                 :           0 :                 q++;
    7270                 :           0 :                 continue;
    7271                 :             :         }
    7272                 :             : 
    7273                 :           0 :         for (;;)
    7274                 :             :         {
    7275         [ #  # ]:           0 :                 if (*q != '%')
    7276                 :             :                 {
    7277                 :             :                         /* if found a whitespace or NUL, the string ends */
    7278   [ #  #  #  # ]:           0 :                         if (*q == ' ' || *q == '\0')
    7279                 :           0 :                                 goto end;
    7280                 :             : 
    7281                 :             :                         /* copy character */
    7282                 :           0 :                         *(p++) = *(q++);
    7283                 :           0 :                 }
    7284                 :             :                 else
    7285                 :             :                 {
    7286                 :           0 :                         int                     hi;
    7287                 :           0 :                         int                     lo;
    7288                 :           0 :                         int                     c;
    7289                 :             : 
    7290                 :           0 :                         ++q;                            /* skip the percent sign itself */
    7291                 :             : 
    7292                 :             :                         /*
    7293                 :             :                          * Possible EOL will be caught by the first call to
    7294                 :             :                          * get_hexdigit(), so we never dereference an invalid q pointer.
    7295                 :             :                          */
    7296   [ #  #  #  # ]:           0 :                         if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
    7297                 :             :                         {
    7298                 :           0 :                                 libpq_append_error(errorMessage,
    7299                 :             :                                                                    "invalid percent-encoded token: \"%s\"",
    7300                 :           0 :                                                                    str);
    7301                 :           0 :                                 free(buf);
    7302                 :           0 :                                 return NULL;
    7303                 :             :                         }
    7304                 :             : 
    7305                 :           0 :                         c = (hi << 4) | lo;
    7306         [ #  # ]:           0 :                         if (c == 0)
    7307                 :             :                         {
    7308                 :           0 :                                 libpq_append_error(errorMessage,
    7309                 :             :                                                                    "forbidden value %%00 in percent-encoded value: \"%s\"",
    7310                 :           0 :                                                                    str);
    7311                 :           0 :                                 free(buf);
    7312                 :           0 :                                 return NULL;
    7313                 :             :                         }
    7314                 :           0 :                         *(p++) = c;
    7315         [ #  # ]:           0 :                 }
    7316                 :             :         }
    7317                 :             : 
    7318                 :             : end:
    7319                 :             : 
    7320                 :             :         /* skip trailing whitespaces */
    7321         [ #  # ]:           0 :         for (const char *s = q; *s == ' '; s++)
    7322                 :             :         {
    7323                 :           0 :                 q++;
    7324                 :           0 :                 continue;
    7325                 :             :         }
    7326                 :             : 
    7327                 :             :         /* Not at the end of the string yet?  Fail. */
    7328         [ #  # ]:           0 :         if (*q != '\0')
    7329                 :             :         {
    7330                 :           0 :                 libpq_append_error(errorMessage,
    7331                 :             :                                                    "unexpected spaces found in \"%s\", use percent-encoded spaces (%%20) instead",
    7332                 :           0 :                                                    str);
    7333                 :           0 :                 free(buf);
    7334                 :           0 :                 return NULL;
    7335                 :             :         }
    7336                 :             : 
    7337                 :             :         /* Copy NUL terminator */
    7338                 :           0 :         *p = '\0';
    7339                 :             : 
    7340                 :           0 :         return buf;
    7341                 :           0 : }
    7342                 :             : 
    7343                 :             : /*
    7344                 :             :  * Convert hexadecimal digit character to its integer value.
    7345                 :             :  *
    7346                 :             :  * If successful, returns true and value is filled with digit's base 16 value.
    7347                 :             :  * If not successful, returns false.
    7348                 :             :  *
    7349                 :             :  * Lower- and upper-case letters in the range A-F are treated identically.
    7350                 :             :  */
    7351                 :             : static bool
    7352                 :           0 : get_hexdigit(char digit, int *value)
    7353                 :             : {
    7354   [ #  #  #  # ]:           0 :         if ('0' <= digit && digit <= '9')
    7355                 :           0 :                 *value = digit - '0';
    7356   [ #  #  #  # ]:           0 :         else if ('A' <= digit && digit <= 'F')
    7357                 :           0 :                 *value = digit - 'A' + 10;
    7358   [ #  #  #  # ]:           0 :         else if ('a' <= digit && digit <= 'f')
    7359                 :           0 :                 *value = digit - 'a' + 10;
    7360                 :             :         else
    7361                 :           0 :                 return false;
    7362                 :             : 
    7363                 :           0 :         return true;
    7364                 :           0 : }
    7365                 :             : 
    7366                 :             : /*
    7367                 :             :  * Find an option value corresponding to the keyword in the connOptions array.
    7368                 :             :  *
    7369                 :             :  * If successful, returns a pointer to the corresponding option's value.
    7370                 :             :  * If not successful, returns NULL.
    7371                 :             :  */
    7372                 :             : static const char *
    7373                 :       16854 : conninfo_getval(PQconninfoOption *connOptions,
    7374                 :             :                                 const char *keyword)
    7375                 :             : {
    7376                 :       16854 :         PQconninfoOption *option;
    7377                 :             : 
    7378                 :       16854 :         option = conninfo_find(connOptions, keyword);
    7379                 :             : 
    7380         [ +  - ]:       16854 :         return option ? option->val : NULL;
    7381                 :       16854 : }
    7382                 :             : 
    7383                 :             : /*
    7384                 :             :  * Store a (new) value for an option corresponding to the keyword in
    7385                 :             :  * connOptions array.
    7386                 :             :  *
    7387                 :             :  * If uri_decode is true, the value is URI-decoded.  The keyword is always
    7388                 :             :  * assumed to be non URI-encoded.
    7389                 :             :  *
    7390                 :             :  * If successful, returns a pointer to the corresponding PQconninfoOption,
    7391                 :             :  * which value is replaced with a strdup'd copy of the passed value string.
    7392                 :             :  * The existing value for the option is free'd before replacing, if any.
    7393                 :             :  *
    7394                 :             :  * If not successful, returns NULL and fills errorMessage accordingly.
    7395                 :             :  * However, if the reason of failure is an invalid keyword being passed and
    7396                 :             :  * ignoreMissing is true, errorMessage will be left untouched.
    7397                 :             :  */
    7398                 :             : static PQconninfoOption *
    7399                 :       13550 : conninfo_storeval(PQconninfoOption *connOptions,
    7400                 :             :                                   const char *keyword, const char *value,
    7401                 :             :                                   PQExpBuffer errorMessage, bool ignoreMissing,
    7402                 :             :                                   bool uri_decode)
    7403                 :             : {
    7404                 :       13550 :         PQconninfoOption *option;
    7405                 :       13550 :         char       *value_copy;
    7406                 :             : 
    7407                 :             :         /*
    7408                 :             :          * For backwards compatibility, requiressl=1 gets translated to
    7409                 :             :          * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
    7410                 :             :          * (which is the default for sslmode).
    7411                 :             :          */
    7412         [ +  - ]:       13550 :         if (strcmp(keyword, "requiressl") == 0)
    7413                 :             :         {
    7414                 :           0 :                 keyword = "sslmode";
    7415         [ #  # ]:           0 :                 if (value[0] == '1')
    7416                 :           0 :                         value = "require";
    7417                 :             :                 else
    7418                 :           0 :                         value = "prefer";
    7419                 :           0 :         }
    7420                 :             : 
    7421                 :       13550 :         option = conninfo_find(connOptions, keyword);
    7422         [ +  + ]:       13550 :         if (option == NULL)
    7423                 :             :         {
    7424         [ -  + ]:           1 :                 if (!ignoreMissing)
    7425                 :           2 :                         libpq_append_error(errorMessage,
    7426                 :             :                                                            "invalid connection option \"%s\"",
    7427                 :           1 :                                                            keyword);
    7428                 :           1 :                 return NULL;
    7429                 :             :         }
    7430                 :             : 
    7431         [ -  + ]:       13549 :         if (uri_decode)
    7432                 :             :         {
    7433                 :           0 :                 value_copy = conninfo_uri_decode(value, errorMessage);
    7434         [ #  # ]:           0 :                 if (value_copy == NULL)
    7435                 :             :                         /* conninfo_uri_decode already set an error message */
    7436                 :           0 :                         return NULL;
    7437                 :           0 :         }
    7438                 :             :         else
    7439                 :             :         {
    7440                 :       13549 :                 value_copy = strdup(value);
    7441         [ +  - ]:       13549 :                 if (value_copy == NULL)
    7442                 :             :                 {
    7443                 :           0 :                         libpq_append_error(errorMessage, "out of memory");
    7444                 :           0 :                         return NULL;
    7445                 :             :                 }
    7446                 :             :         }
    7447                 :             : 
    7448                 :       13549 :         free(option->val);
    7449                 :       13549 :         option->val = value_copy;
    7450                 :             : 
    7451                 :       13549 :         return option;
    7452                 :       13550 : }
    7453                 :             : 
    7454                 :             : /*
    7455                 :             :  * Find a PQconninfoOption option corresponding to the keyword in the
    7456                 :             :  * connOptions array.
    7457                 :             :  *
    7458                 :             :  * If successful, returns a pointer to the corresponding PQconninfoOption
    7459                 :             :  * structure.
    7460                 :             :  * If not successful, returns NULL.
    7461                 :             :  */
    7462                 :             : static PQconninfoOption *
    7463                 :       30404 : conninfo_find(PQconninfoOption *connOptions, const char *keyword)
    7464                 :             : {
    7465                 :       30404 :         PQconninfoOption *option;
    7466                 :             : 
    7467         [ +  + ]:      724990 :         for (option = connOptions; option->keyword != NULL; option++)
    7468                 :             :         {
    7469         [ +  + ]:      724989 :                 if (strcmp(option->keyword, keyword) == 0)
    7470                 :       30403 :                         return option;
    7471                 :      694586 :         }
    7472                 :             : 
    7473                 :           1 :         return NULL;
    7474                 :       30404 : }
    7475                 :             : 
    7476                 :             : 
    7477                 :             : /*
    7478                 :             :  * Return the connection options used for the connection
    7479                 :             :  */
    7480                 :             : PQconninfoOption *
    7481                 :         673 : PQconninfo(PGconn *conn)
    7482                 :             : {
    7483                 :         673 :         PQExpBufferData errorBuf;
    7484                 :         673 :         PQconninfoOption *connOptions;
    7485                 :             : 
    7486         [ +  - ]:         673 :         if (conn == NULL)
    7487                 :           0 :                 return NULL;
    7488                 :             : 
    7489                 :             :         /*
    7490                 :             :          * We don't actually report any errors here, but callees want a buffer,
    7491                 :             :          * and we prefer not to trash the conn's errorMessage.
    7492                 :             :          */
    7493                 :         673 :         initPQExpBuffer(&errorBuf);
    7494         [ +  - ]:         673 :         if (PQExpBufferDataBroken(errorBuf))
    7495                 :           0 :                 return NULL;                    /* out of memory already :-( */
    7496                 :             : 
    7497                 :         673 :         connOptions = conninfo_init(&errorBuf);
    7498                 :             : 
    7499         [ -  + ]:         673 :         if (connOptions != NULL)
    7500                 :             :         {
    7501                 :         673 :                 const internalPQconninfoOption *option;
    7502                 :             : 
    7503         [ +  + ]:       34996 :                 for (option = PQconninfoOptions; option->keyword; option++)
    7504                 :             :                 {
    7505                 :       34323 :                         char      **connmember;
    7506                 :             : 
    7507         [ +  - ]:       34323 :                         if (option->connofs < 0)
    7508                 :           0 :                                 continue;
    7509                 :             : 
    7510                 :       34323 :                         connmember = (char **) ((char *) conn + option->connofs);
    7511                 :             : 
    7512         [ +  + ]:       34323 :                         if (*connmember)
    7513                 :       13460 :                                 conninfo_storeval(connOptions, option->keyword, *connmember,
    7514                 :             :                                                                   &errorBuf, true, false);
    7515      [ -  -  + ]:       34323 :                 }
    7516                 :         673 :         }
    7517                 :             : 
    7518                 :         673 :         termPQExpBuffer(&errorBuf);
    7519                 :             : 
    7520                 :         673 :         return connOptions;
    7521                 :         673 : }
    7522                 :             : 
    7523                 :             : 
    7524                 :             : void
    7525                 :        1355 : PQconninfoFree(PQconninfoOption *connOptions)
    7526                 :             : {
    7527         [ +  + ]:        1355 :         if (connOptions == NULL)
    7528                 :         318 :                 return;
    7529                 :             : 
    7530         [ +  + ]:       53924 :         for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
    7531                 :       52887 :                 free(option->val);
    7532                 :        1037 :         free(connOptions);
    7533                 :        1355 : }
    7534                 :             : 
    7535                 :             : 
    7536                 :             : /* =========== accessor functions for PGconn ========= */
    7537                 :             : char *
    7538                 :         521 : PQdb(const PGconn *conn)
    7539                 :             : {
    7540         [ +  - ]:         521 :         if (!conn)
    7541                 :           0 :                 return NULL;
    7542                 :         521 :         return conn->dbName;
    7543                 :         521 : }
    7544                 :             : 
    7545                 :             : char *
    7546                 :         315 : PQuser(const PGconn *conn)
    7547                 :             : {
    7548         [ +  - ]:         315 :         if (!conn)
    7549                 :           0 :                 return NULL;
    7550                 :         315 :         return conn->pguser;
    7551                 :         315 : }
    7552                 :             : 
    7553                 :             : char *
    7554                 :           0 : PQpass(const PGconn *conn)
    7555                 :             : {
    7556                 :           0 :         char       *password = NULL;
    7557                 :             : 
    7558         [ #  # ]:           0 :         if (!conn)
    7559                 :           0 :                 return NULL;
    7560         [ #  # ]:           0 :         if (conn->connhost != NULL)
    7561                 :           0 :                 password = conn->connhost[conn->whichhost].password;
    7562         [ #  # ]:           0 :         if (password == NULL)
    7563                 :           0 :                 password = conn->pgpass;
    7564                 :             :         /* Historically we've returned "" not NULL for no password specified */
    7565         [ #  # ]:           0 :         if (password == NULL)
    7566                 :           0 :                 password = "";
    7567                 :           0 :         return password;
    7568                 :           0 : }
    7569                 :             : 
    7570                 :             : char *
    7571                 :         315 : PQhost(const PGconn *conn)
    7572                 :             : {
    7573         [ +  - ]:         315 :         if (!conn)
    7574                 :           0 :                 return NULL;
    7575                 :             : 
    7576         [ -  + ]:         315 :         if (conn->connhost != NULL)
    7577                 :             :         {
    7578                 :             :                 /*
    7579                 :             :                  * Return the verbatim host value provided by user, or hostaddr in its
    7580                 :             :                  * lack.
    7581                 :             :                  */
    7582   [ +  -  -  + ]:         315 :                 if (conn->connhost[conn->whichhost].host != NULL &&
    7583                 :         315 :                         conn->connhost[conn->whichhost].host[0] != '\0')
    7584                 :         315 :                         return conn->connhost[conn->whichhost].host;
    7585   [ #  #  #  # ]:           0 :                 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
    7586                 :           0 :                                  conn->connhost[conn->whichhost].hostaddr[0] != '\0')
    7587                 :           0 :                         return conn->connhost[conn->whichhost].hostaddr;
    7588                 :           0 :         }
    7589                 :             : 
    7590                 :           0 :         return "";
    7591                 :         315 : }
    7592                 :             : 
    7593                 :             : char *
    7594                 :           0 : PQhostaddr(const PGconn *conn)
    7595                 :             : {
    7596         [ #  # ]:           0 :         if (!conn)
    7597                 :           0 :                 return NULL;
    7598                 :             : 
    7599                 :             :         /* Return the parsed IP address */
    7600   [ #  #  #  # ]:           0 :         if (conn->connhost != NULL && conn->connip != NULL)
    7601                 :           0 :                 return conn->connip;
    7602                 :             : 
    7603                 :           0 :         return "";
    7604                 :           0 : }
    7605                 :             : 
    7606                 :             : char *
    7607                 :         315 : PQport(const PGconn *conn)
    7608                 :             : {
    7609         [ +  - ]:         315 :         if (!conn)
    7610                 :           0 :                 return NULL;
    7611                 :             : 
    7612         [ +  - ]:         315 :         if (conn->connhost != NULL &&
    7613   [ +  -  -  + ]:         315 :                 conn->connhost[conn->whichhost].port != NULL &&
    7614                 :         315 :                 conn->connhost[conn->whichhost].port[0] != '\0')
    7615                 :         315 :                 return conn->connhost[conn->whichhost].port;
    7616                 :             : 
    7617                 :           0 :         return DEF_PGPORT_STR;
    7618                 :         315 : }
    7619                 :             : 
    7620                 :             : /*
    7621                 :             :  * No longer does anything, but the function remains for API backwards
    7622                 :             :  * compatibility.
    7623                 :             :  */
    7624                 :             : char *
    7625                 :           0 : PQtty(const PGconn *conn)
    7626                 :             : {
    7627         [ #  # ]:           0 :         if (!conn)
    7628                 :           0 :                 return NULL;
    7629                 :           0 :         return "";
    7630                 :           0 : }
    7631                 :             : 
    7632                 :             : char *
    7633                 :           0 : PQoptions(const PGconn *conn)
    7634                 :             : {
    7635         [ #  # ]:           0 :         if (!conn)
    7636                 :           0 :                 return NULL;
    7637                 :           0 :         return conn->pgoptions;
    7638                 :           0 : }
    7639                 :             : 
    7640                 :             : ConnStatusType
    7641                 :       58151 : PQstatus(const PGconn *conn)
    7642                 :             : {
    7643         [ +  - ]:       58151 :         if (!conn)
    7644                 :           0 :                 return CONNECTION_BAD;
    7645                 :       58151 :         return conn->status;
    7646                 :       58151 : }
    7647                 :             : 
    7648                 :             : PGTransactionStatusType
    7649                 :       51084 : PQtransactionStatus(const PGconn *conn)
    7650                 :             : {
    7651   [ +  -  -  + ]:       51084 :         if (!conn || conn->status != CONNECTION_OK)
    7652                 :           0 :                 return PQTRANS_UNKNOWN;
    7653         [ +  + ]:       51084 :         if (conn->asyncStatus != PGASYNC_IDLE)
    7654                 :         163 :                 return PQTRANS_ACTIVE;
    7655                 :       50921 :         return conn->xactStatus;
    7656                 :       51084 : }
    7657                 :             : 
    7658                 :             : const char *
    7659                 :       99490 : PQparameterStatus(const PGconn *conn, const char *paramName)
    7660                 :             : {
    7661                 :       99490 :         const pgParameterStatus *pstatus;
    7662                 :             : 
    7663   [ +  -  -  + ]:       99490 :         if (!conn || !paramName)
    7664                 :           0 :                 return NULL;
    7665         [ +  - ]:     1225294 :         for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
    7666                 :             :         {
    7667         [ +  + ]:     1225294 :                 if (strcmp(pstatus->name, paramName) == 0)
    7668                 :       99490 :                         return pstatus->value;
    7669                 :     1125804 :         }
    7670                 :           0 :         return NULL;
    7671                 :       99490 : }
    7672                 :             : 
    7673                 :             : int
    7674                 :           0 : PQprotocolVersion(const PGconn *conn)
    7675                 :             : {
    7676         [ #  # ]:           0 :         if (!conn)
    7677                 :           0 :                 return 0;
    7678         [ #  # ]:           0 :         if (conn->status == CONNECTION_BAD)
    7679                 :           0 :                 return 0;
    7680                 :           0 :         return PG_PROTOCOL_MAJOR(conn->pversion);
    7681                 :           0 : }
    7682                 :             : 
    7683                 :             : int
    7684                 :           0 : PQfullProtocolVersion(const PGconn *conn)
    7685                 :             : {
    7686         [ #  # ]:           0 :         if (!conn)
    7687                 :           0 :                 return 0;
    7688         [ #  # ]:           0 :         if (conn->status == CONNECTION_BAD)
    7689                 :           0 :                 return 0;
    7690                 :           0 :         return PG_PROTOCOL_FULL(conn->pversion);
    7691                 :           0 : }
    7692                 :             : 
    7693                 :             : int
    7694                 :        1901 : PQserverVersion(const PGconn *conn)
    7695                 :             : {
    7696         [ +  - ]:        1901 :         if (!conn)
    7697                 :           0 :                 return 0;
    7698         [ -  + ]:        1901 :         if (conn->status == CONNECTION_BAD)
    7699                 :           0 :                 return 0;
    7700                 :        1901 :         return conn->sversion;
    7701                 :        1901 : }
    7702                 :             : 
    7703                 :             : char *
    7704                 :          48 : PQerrorMessage(const PGconn *conn)
    7705                 :             : {
    7706         [ +  - ]:          48 :         if (!conn)
    7707                 :           0 :                 return libpq_gettext("connection pointer is NULL\n");
    7708                 :             : 
    7709                 :             :         /*
    7710                 :             :          * The errorMessage buffer might be marked "broken" due to having
    7711                 :             :          * previously failed to allocate enough memory for the message.  In that
    7712                 :             :          * case, tell the application we ran out of memory.
    7713                 :             :          */
    7714   [ +  -  -  + ]:          48 :         if (PQExpBufferBroken(&conn->errorMessage))
    7715                 :           0 :                 return libpq_gettext("out of memory\n");
    7716                 :             : 
    7717                 :          48 :         return conn->errorMessage.data;
    7718                 :          48 : }
    7719                 :             : 
    7720                 :             : /*
    7721                 :             :  * In Windows, socket values are unsigned, and an invalid socket value
    7722                 :             :  * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
    7723                 :             :  * warning). Ideally we would return an unsigned value for PQsocket() on
    7724                 :             :  * Windows, but that would cause the function's return value to differ from
    7725                 :             :  * Unix, so we just return -1 for invalid sockets.
    7726                 :             :  * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
    7727                 :             :  * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
    7728                 :             :  */
    7729                 :             : int
    7730                 :          88 : PQsocket(const PGconn *conn)
    7731                 :             : {
    7732         [ +  - ]:          88 :         if (!conn)
    7733                 :           0 :                 return -1;
    7734         [ -  + ]:          88 :         if (conn->altsock != PGINVALID_SOCKET)
    7735                 :           0 :                 return conn->altsock;
    7736         [ +  - ]:          88 :         return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
    7737                 :          88 : }
    7738                 :             : 
    7739                 :             : int
    7740                 :           0 : PQbackendPID(const PGconn *conn)
    7741                 :             : {
    7742   [ #  #  #  # ]:           0 :         if (!conn || conn->status != CONNECTION_OK)
    7743                 :           0 :                 return 0;
    7744                 :           0 :         return conn->be_pid;
    7745                 :           0 : }
    7746                 :             : 
    7747                 :             : PGpipelineStatus
    7748                 :      190952 : PQpipelineStatus(const PGconn *conn)
    7749                 :             : {
    7750         [ +  - ]:      190952 :         if (!conn)
    7751                 :           0 :                 return PQ_PIPELINE_OFF;
    7752                 :             : 
    7753                 :      190952 :         return conn->pipelineStatus;
    7754                 :      190952 : }
    7755                 :             : 
    7756                 :             : int
    7757                 :           0 : PQconnectionNeedsPassword(const PGconn *conn)
    7758                 :             : {
    7759                 :           0 :         char       *password;
    7760                 :             : 
    7761         [ #  # ]:           0 :         if (!conn)
    7762                 :           0 :                 return false;
    7763                 :           0 :         password = PQpass(conn);
    7764   [ #  #  #  # ]:           0 :         if (conn->password_needed &&
    7765         [ #  # ]:           0 :                 (password == NULL || password[0] == '\0'))
    7766                 :           0 :                 return true;
    7767                 :             :         else
    7768                 :           0 :                 return false;
    7769                 :           0 : }
    7770                 :             : 
    7771                 :             : int
    7772                 :           0 : PQconnectionUsedPassword(const PGconn *conn)
    7773                 :             : {
    7774         [ #  # ]:           0 :         if (!conn)
    7775                 :           0 :                 return false;
    7776         [ #  # ]:           0 :         if (conn->password_needed)
    7777                 :           0 :                 return true;
    7778                 :             :         else
    7779                 :           0 :                 return false;
    7780                 :           0 : }
    7781                 :             : 
    7782                 :             : int
    7783                 :           0 : PQconnectionUsedGSSAPI(const PGconn *conn)
    7784                 :             : {
    7785         [ #  # ]:           0 :         if (!conn)
    7786                 :           0 :                 return false;
    7787         [ #  # ]:           0 :         if (conn->gssapi_used)
    7788                 :           0 :                 return true;
    7789                 :             :         else
    7790                 :           0 :                 return false;
    7791                 :           0 : }
    7792                 :             : 
    7793                 :             : int
    7794                 :       52456 : PQclientEncoding(const PGconn *conn)
    7795                 :             : {
    7796   [ +  -  -  + ]:       52456 :         if (!conn || conn->status != CONNECTION_OK)
    7797                 :           0 :                 return -1;
    7798                 :       52456 :         return conn->client_encoding;
    7799                 :       52456 : }
    7800                 :             : 
    7801                 :             : int
    7802                 :           0 : PQsetClientEncoding(PGconn *conn, const char *encoding)
    7803                 :             : {
    7804                 :           0 :         char            qbuf[128];
    7805                 :             :         static const char query[] = "set client_encoding to '%s'";
    7806                 :           0 :         PGresult   *res;
    7807                 :           0 :         int                     status;
    7808                 :             : 
    7809   [ #  #  #  # ]:           0 :         if (!conn || conn->status != CONNECTION_OK)
    7810                 :           0 :                 return -1;
    7811                 :             : 
    7812         [ #  # ]:           0 :         if (!encoding)
    7813                 :           0 :                 return -1;
    7814                 :             : 
    7815                 :             :         /* Resolve special "auto" value from the locale */
    7816         [ #  # ]:           0 :         if (strcmp(encoding, "auto") == 0)
    7817                 :           0 :                 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
    7818                 :             : 
    7819                 :             :         /* check query buffer overflow */
    7820         [ #  # ]:           0 :         if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
    7821                 :           0 :                 return -1;
    7822                 :             : 
    7823                 :             :         /* ok, now send a query */
    7824                 :           0 :         sprintf(qbuf, query, encoding);
    7825                 :           0 :         res = PQexec(conn, qbuf);
    7826                 :             : 
    7827         [ #  # ]:           0 :         if (res == NULL)
    7828                 :           0 :                 return -1;
    7829         [ #  # ]:           0 :         if (res->resultStatus != PGRES_COMMAND_OK)
    7830                 :           0 :                 status = -1;
    7831                 :             :         else
    7832                 :             :         {
    7833                 :             :                 /*
    7834                 :             :                  * We rely on the backend to report the parameter value, and we'll
    7835                 :             :                  * change state at that time.
    7836                 :             :                  */
    7837                 :           0 :                 status = 0;                             /* everything is ok */
    7838                 :             :         }
    7839                 :           0 :         PQclear(res);
    7840                 :           0 :         return status;
    7841                 :           0 : }
    7842                 :             : 
    7843                 :             : PGVerbosity
    7844                 :         334 : PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
    7845                 :             : {
    7846                 :         334 :         PGVerbosity old;
    7847                 :             : 
    7848         [ +  - ]:         334 :         if (!conn)
    7849                 :           0 :                 return PQERRORS_DEFAULT;
    7850                 :         334 :         old = conn->verbosity;
    7851                 :         334 :         conn->verbosity = verbosity;
    7852                 :         334 :         return old;
    7853                 :         334 : }
    7854                 :             : 
    7855                 :             : PGContextVisibility
    7856                 :         320 : PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
    7857                 :             : {
    7858                 :         320 :         PGContextVisibility old;
    7859                 :             : 
    7860         [ +  - ]:         320 :         if (!conn)
    7861                 :           0 :                 return PQSHOW_CONTEXT_ERRORS;
    7862                 :         320 :         old = conn->show_context;
    7863                 :         320 :         conn->show_context = show_context;
    7864                 :         320 :         return old;
    7865                 :         320 : }
    7866                 :             : 
    7867                 :             : PQnoticeReceiver
    7868                 :           0 : PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
    7869                 :             : {
    7870                 :           0 :         PQnoticeReceiver old;
    7871                 :             : 
    7872         [ #  # ]:           0 :         if (conn == NULL)
    7873                 :           0 :                 return NULL;
    7874                 :             : 
    7875                 :           0 :         old = conn->noticeHooks.noticeRec;
    7876         [ #  # ]:           0 :         if (proc)
    7877                 :             :         {
    7878                 :           0 :                 conn->noticeHooks.noticeRec = proc;
    7879                 :           0 :                 conn->noticeHooks.noticeRecArg = arg;
    7880                 :           0 :         }
    7881                 :           0 :         return old;
    7882                 :           0 : }
    7883                 :             : 
    7884                 :             : PQnoticeProcessor
    7885                 :         315 : PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
    7886                 :             : {
    7887                 :         315 :         PQnoticeProcessor old;
    7888                 :             : 
    7889         [ +  - ]:         315 :         if (conn == NULL)
    7890                 :           0 :                 return NULL;
    7891                 :             : 
    7892                 :         315 :         old = conn->noticeHooks.noticeProc;
    7893         [ -  + ]:         315 :         if (proc)
    7894                 :             :         {
    7895                 :         315 :                 conn->noticeHooks.noticeProc = proc;
    7896                 :         315 :                 conn->noticeHooks.noticeProcArg = arg;
    7897                 :         315 :         }
    7898                 :         315 :         return old;
    7899                 :         315 : }
    7900                 :             : 
    7901                 :             : /*
    7902                 :             :  * The default notice message receiver just gets the standard notice text
    7903                 :             :  * and sends it to the notice processor.  This two-level setup exists
    7904                 :             :  * mostly for backwards compatibility; perhaps we should deprecate use of
    7905                 :             :  * PQsetNoticeProcessor?
    7906                 :             :  */
    7907                 :             : static void
    7908                 :        2868 : defaultNoticeReceiver(void *arg, const PGresult *res)
    7909                 :             : {
    7910                 :        2868 :         (void) arg;                                     /* not used */
    7911         [ -  + ]:        2868 :         if (res->noticeHooks.noticeProc != NULL)
    7912                 :        5736 :                 res->noticeHooks.noticeProc(res->noticeHooks.noticeProcArg,
    7913                 :        2868 :                                                                         PQresultErrorMessage(res));
    7914                 :        2868 : }
    7915                 :             : 
    7916                 :             : /*
    7917                 :             :  * The default notice message processor just prints the
    7918                 :             :  * message on stderr.  Applications can override this if they
    7919                 :             :  * want the messages to go elsewhere (a window, for example).
    7920                 :             :  * Note that simply discarding notices is probably a bad idea.
    7921                 :             :  */
    7922                 :             : static void
    7923                 :           2 : defaultNoticeProcessor(void *arg, const char *message)
    7924                 :             : {
    7925                 :           2 :         (void) arg;                                     /* not used */
    7926                 :             :         /* Note: we expect the supplied string to end with a newline already. */
    7927                 :           2 :         fprintf(stderr, "%s", message);
    7928                 :           2 : }
    7929                 :             : 
    7930                 :             : /*
    7931                 :             :  * returns a pointer to the next token or NULL if the current
    7932                 :             :  * token doesn't match
    7933                 :             :  */
    7934                 :             : static char *
    7935                 :           0 : pwdfMatchesString(char *buf, const char *token)
    7936                 :             : {
    7937                 :           0 :         char       *tbuf;
    7938                 :           0 :         const char *ttok;
    7939                 :           0 :         bool            bslash = false;
    7940                 :             : 
    7941   [ #  #  #  # ]:           0 :         if (buf == NULL || token == NULL)
    7942                 :           0 :                 return NULL;
    7943                 :           0 :         tbuf = buf;
    7944                 :           0 :         ttok = token;
    7945   [ #  #  #  # ]:           0 :         if (tbuf[0] == '*' && tbuf[1] == ':')
    7946                 :           0 :                 return tbuf + 2;
    7947         [ #  # ]:           0 :         while (*tbuf != 0)
    7948                 :             :         {
    7949   [ #  #  #  # ]:           0 :                 if (*tbuf == '\\' && !bslash)
    7950                 :             :                 {
    7951                 :           0 :                         tbuf++;
    7952                 :           0 :                         bslash = true;
    7953                 :           0 :                 }
    7954   [ #  #  #  #  :           0 :                 if (*tbuf == ':' && *ttok == 0 && !bslash)
                   #  # ]
    7955                 :           0 :                         return tbuf + 1;
    7956                 :           0 :                 bslash = false;
    7957         [ #  # ]:           0 :                 if (*ttok == 0)
    7958                 :           0 :                         return NULL;
    7959         [ #  # ]:           0 :                 if (*tbuf == *ttok)
    7960                 :             :                 {
    7961                 :           0 :                         tbuf++;
    7962                 :           0 :                         ttok++;
    7963                 :           0 :                 }
    7964                 :             :                 else
    7965                 :           0 :                         return NULL;
    7966                 :             :         }
    7967                 :           0 :         return NULL;
    7968                 :           0 : }
    7969                 :             : 
    7970                 :             : /*
    7971                 :             :  * Get a password from the password file. Return value is malloc'd.
    7972                 :             :  *
    7973                 :             :  * On failure, *errmsg is set to an error to be returned.  It is
    7974                 :             :  * left NULL on success, or if no password could be found.
    7975                 :             :  */
    7976                 :             : static char *
    7977                 :         318 : passwordFromFile(const char *hostname, const char *port,
    7978                 :             :                                  const char *dbname, const char *username,
    7979                 :             :                                  const char *pgpassfile, const char **errmsg)
    7980                 :             : {
    7981                 :         318 :         FILE       *fp;
    7982                 :             : #ifndef WIN32
    7983                 :         318 :         struct stat stat_buf;
    7984                 :             : #endif
    7985                 :         318 :         PQExpBufferData buf;
    7986                 :             : 
    7987                 :         318 :         *errmsg = NULL;
    7988                 :             : 
    7989   [ +  -  -  + ]:         318 :         if (dbname == NULL || dbname[0] == '\0')
    7990                 :           0 :                 return NULL;
    7991                 :             : 
    7992   [ +  -  -  + ]:         318 :         if (username == NULL || username[0] == '\0')
    7993                 :           0 :                 return NULL;
    7994                 :             : 
    7995                 :             :         /* 'localhost' matches pghost of '' or the default socket directory */
    7996   [ +  -  -  + ]:         318 :         if (hostname == NULL || hostname[0] == '\0')
    7997                 :           0 :                 hostname = DefaultHost;
    7998         [ -  + ]:         318 :         else if (is_unixsock_path(hostname))
    7999                 :             : 
    8000                 :             :                 /*
    8001                 :             :                  * We should probably use canonicalize_path(), but then we have to
    8002                 :             :                  * bring path.c into libpq, and it doesn't seem worth it.
    8003                 :             :                  */
    8004         [ +  - ]:         318 :                 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
    8005                 :           0 :                         hostname = DefaultHost;
    8006                 :             : 
    8007   [ +  -  +  - ]:         318 :         if (port == NULL || port[0] == '\0')
    8008                 :           0 :                 port = DEF_PGPORT_STR;
    8009                 :             : 
    8010                 :             :         /* If password file cannot be opened, ignore it. */
    8011                 :         318 :         fp = fopen(pgpassfile, "r");
    8012         [ -  + ]:         318 :         if (fp == NULL)
    8013                 :         318 :                 return NULL;
    8014                 :             : 
    8015                 :             : #ifndef WIN32
    8016         [ #  # ]:           0 :         if (fstat(fileno(fp), &stat_buf) != 0)
    8017                 :             :         {
    8018                 :           0 :                 fclose(fp);
    8019                 :           0 :                 return NULL;
    8020                 :             :         }
    8021                 :             : 
    8022         [ #  # ]:           0 :         if (!S_ISREG(stat_buf.st_mode))
    8023                 :             :         {
    8024                 :           0 :                 fprintf(stderr,
    8025                 :           0 :                                 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
    8026                 :           0 :                                 pgpassfile);
    8027                 :           0 :                 fclose(fp);
    8028                 :           0 :                 return NULL;
    8029                 :             :         }
    8030                 :             : 
    8031                 :             :         /* If password file is insecure, alert the user and ignore it. */
    8032         [ #  # ]:           0 :         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
    8033                 :             :         {
    8034                 :           0 :                 fprintf(stderr,
    8035                 :           0 :                                 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
    8036                 :           0 :                                 pgpassfile);
    8037                 :           0 :                 fclose(fp);
    8038                 :           0 :                 return NULL;
    8039                 :             :         }
    8040                 :             : #else
    8041                 :             : 
    8042                 :             :         /*
    8043                 :             :          * On Win32, the directory is protected, so we don't have to check the
    8044                 :             :          * file.
    8045                 :             :          */
    8046                 :             : #endif
    8047                 :             : 
    8048                 :             :         /* Use an expansible buffer to accommodate any reasonable line length */
    8049                 :           0 :         initPQExpBuffer(&buf);
    8050                 :             : 
    8051   [ #  #  #  # ]:           0 :         while (!feof(fp) && !ferror(fp))
    8052                 :             :         {
    8053                 :             :                 /* Make sure there's a reasonable amount of room in the buffer */
    8054         [ #  # ]:           0 :                 if (!enlargePQExpBuffer(&buf, 128))
    8055                 :             :                 {
    8056                 :           0 :                         *errmsg = libpq_gettext("out of memory");
    8057                 :           0 :                         break;
    8058                 :             :                 }
    8059                 :             : 
    8060                 :             :                 /* Read some data, appending it to what we already have */
    8061         [ #  # ]:           0 :                 if (fgets(buf.data + buf.len, buf.maxlen - buf.len, fp) == NULL)
    8062                 :           0 :                         break;
    8063                 :           0 :                 buf.len += strlen(buf.data + buf.len);
    8064                 :             : 
    8065                 :             :                 /* If we don't yet have a whole line, loop around to read more */
    8066   [ #  #  #  # ]:           0 :                 if (!(buf.len > 0 && buf.data[buf.len - 1] == '\n') && !feof(fp))
    8067                 :           0 :                         continue;
    8068                 :             : 
    8069                 :             :                 /* ignore comments */
    8070         [ #  # ]:           0 :                 if (buf.data[0] != '#')
    8071                 :             :                 {
    8072                 :           0 :                         char       *t = buf.data;
    8073                 :           0 :                         int                     len;
    8074                 :             : 
    8075                 :             :                         /* strip trailing newline and carriage return */
    8076                 :           0 :                         len = pg_strip_crlf(t);
    8077                 :             : 
    8078         [ #  # ]:           0 :                         if (len > 0 &&
    8079         [ #  # ]:           0 :                                 (t = pwdfMatchesString(t, hostname)) != NULL &&
    8080         [ #  # ]:           0 :                                 (t = pwdfMatchesString(t, port)) != NULL &&
    8081   [ #  #  #  # ]:           0 :                                 (t = pwdfMatchesString(t, dbname)) != NULL &&
    8082                 :           0 :                                 (t = pwdfMatchesString(t, username)) != NULL)
    8083                 :             :                         {
    8084                 :             :                                 /* Found a match. */
    8085                 :           0 :                                 char       *ret,
    8086                 :             :                                                    *p1,
    8087                 :             :                                                    *p2;
    8088                 :             : 
    8089                 :           0 :                                 ret = strdup(t);
    8090                 :             : 
    8091                 :           0 :                                 fclose(fp);
    8092                 :           0 :                                 explicit_bzero(buf.data, buf.maxlen);
    8093                 :           0 :                                 termPQExpBuffer(&buf);
    8094                 :             : 
    8095         [ #  # ]:           0 :                                 if (!ret)
    8096                 :             :                                 {
    8097                 :           0 :                                         *errmsg = libpq_gettext("out of memory");
    8098                 :           0 :                                         return NULL;
    8099                 :             :                                 }
    8100                 :             : 
    8101                 :             :                                 /* De-escape password. */
    8102   [ #  #  #  # ]:           0 :                                 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
    8103                 :             :                                 {
    8104   [ #  #  #  # ]:           0 :                                         if (*p1 == '\\' && p1[1] != '\0')
    8105                 :           0 :                                                 ++p1;
    8106                 :           0 :                                         *p2 = *p1;
    8107                 :           0 :                                 }
    8108                 :           0 :                                 *p2 = '\0';
    8109                 :             : 
    8110                 :           0 :                                 return ret;
    8111                 :           0 :                         }
    8112         [ #  # ]:           0 :                 }
    8113                 :             : 
    8114                 :             :                 /* No match, reset buffer to prepare for next line. */
    8115                 :           0 :                 buf.len = 0;
    8116                 :             :         }
    8117                 :             : 
    8118                 :           0 :         fclose(fp);
    8119                 :           0 :         explicit_bzero(buf.data, buf.maxlen);
    8120                 :           0 :         termPQExpBuffer(&buf);
    8121                 :           0 :         return NULL;
    8122                 :         318 : }
    8123                 :             : 
    8124                 :             : 
    8125                 :             : /*
    8126                 :             :  *      If the connection failed due to bad password, we should mention
    8127                 :             :  *      if we got the password from the pgpassfile.
    8128                 :             :  */
    8129                 :             : static void
    8130                 :           0 : pgpassfileWarning(PGconn *conn)
    8131                 :             : {
    8132                 :             :         /* If it was 'invalid authorization', add pgpassfile mention */
    8133                 :             :         /* only works with >= 9.0 servers */
    8134         [ #  # ]:           0 :         if (conn->password_needed &&
    8135   [ #  #  #  # ]:           0 :                 conn->connhost[conn->whichhost].password != NULL &&
    8136                 :           0 :                 conn->result)
    8137                 :             :         {
    8138                 :           0 :                 const char *sqlstate = PQresultErrorField(conn->result,
    8139                 :             :                                                                                                   PG_DIAG_SQLSTATE);
    8140                 :             : 
    8141   [ #  #  #  # ]:           0 :                 if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
    8142                 :           0 :                         libpq_append_conn_error(conn, "password retrieved from file \"%s\"",
    8143                 :           0 :                                                                         conn->pgpassfile);
    8144                 :           0 :         }
    8145                 :           0 : }
    8146                 :             : 
    8147                 :             : /*
    8148                 :             :  * Check if the SSL protocol value given in input is valid or not.
    8149                 :             :  * This is used as a sanity check routine for the connection parameters
    8150                 :             :  * ssl_min_protocol_version and ssl_max_protocol_version.
    8151                 :             :  */
    8152                 :             : static bool
    8153                 :        1272 : sslVerifyProtocolVersion(const char *version)
    8154                 :             : {
    8155                 :             :         /*
    8156                 :             :          * An empty string and a NULL value are considered valid as it is
    8157                 :             :          * equivalent to ignoring the parameter.
    8158                 :             :          */
    8159   [ +  +  -  + ]:        1272 :         if (!version || strlen(version) == 0)
    8160                 :         636 :                 return true;
    8161                 :             : 
    8162         [ +  - ]:         636 :         if (pg_strcasecmp(version, "TLSv1") == 0 ||
    8163         [ +  - ]:         636 :                 pg_strcasecmp(version, "TLSv1.1") == 0 ||
    8164   [ -  +  #  # ]:         636 :                 pg_strcasecmp(version, "TLSv1.2") == 0 ||
    8165                 :           0 :                 pg_strcasecmp(version, "TLSv1.3") == 0)
    8166                 :         636 :                 return true;
    8167                 :             : 
    8168                 :             :         /* anything else is wrong */
    8169                 :           0 :         return false;
    8170                 :        1272 : }
    8171                 :             : 
    8172                 :             : 
    8173                 :             : /*
    8174                 :             :  * Ensure that the SSL protocol range given in input is correct.  The check
    8175                 :             :  * is performed on the input string to keep it TLS backend agnostic.  Input
    8176                 :             :  * to this function is expected verified with sslVerifyProtocolVersion().
    8177                 :             :  */
    8178                 :             : static bool
    8179                 :         318 : sslVerifyProtocolRange(const char *min, const char *max)
    8180                 :             : {
    8181   [ -  +  +  - ]:         318 :         Assert(sslVerifyProtocolVersion(min) &&
    8182                 :             :                    sslVerifyProtocolVersion(max));
    8183                 :             : 
    8184                 :             :         /* If at least one of the bounds is not set, the range is valid */
    8185   [ +  -  -  +  :         318 :         if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
             #  #  #  # ]
    8186                 :         318 :                 return true;
    8187                 :             : 
    8188                 :             :         /*
    8189                 :             :          * If the minimum version is the lowest one we accept, then all options
    8190                 :             :          * for the maximum are valid.
    8191                 :             :          */
    8192         [ #  # ]:           0 :         if (pg_strcasecmp(min, "TLSv1") == 0)
    8193                 :           0 :                 return true;
    8194                 :             : 
    8195                 :             :         /*
    8196                 :             :          * The minimum bound is valid, and cannot be TLSv1, so using TLSv1 for the
    8197                 :             :          * maximum is incorrect.
    8198                 :             :          */
    8199         [ #  # ]:           0 :         if (pg_strcasecmp(max, "TLSv1") == 0)
    8200                 :           0 :                 return false;
    8201                 :             : 
    8202                 :             :         /*
    8203                 :             :          * At this point we know that we have a mix of TLSv1.1 through 1.3
    8204                 :             :          * versions.
    8205                 :             :          */
    8206         [ #  # ]:           0 :         if (pg_strcasecmp(min, max) > 0)
    8207                 :           0 :                 return false;
    8208                 :             : 
    8209                 :           0 :         return true;
    8210                 :         318 : }
    8211                 :             : 
    8212                 :             : 
    8213                 :             : /*
    8214                 :             :  * Obtain user's home directory, return in given buffer
    8215                 :             :  *
    8216                 :             :  * On Unix, this actually returns the user's home directory.  On Windows
    8217                 :             :  * it returns the PostgreSQL-specific application data folder.
    8218                 :             :  *
    8219                 :             :  * This is essentially the same as get_home_path(), but we don't use that
    8220                 :             :  * because we don't want to pull path.c into libpq (it pollutes application
    8221                 :             :  * namespace).
    8222                 :             :  *
    8223                 :             :  * Returns true on success, false on failure to obtain the directory name.
    8224                 :             :  *
    8225                 :             :  * CAUTION: although in most situations failure is unexpected, there are users
    8226                 :             :  * who like to run applications in a home-directory-less environment.  On
    8227                 :             :  * failure, you almost certainly DO NOT want to report an error.  Just act as
    8228                 :             :  * though whatever file you were hoping to find in the home directory isn't
    8229                 :             :  * there (which it isn't).
    8230                 :             :  */
    8231                 :             : bool
    8232                 :         275 : pqGetHomeDirectory(char *buf, int bufsize)
    8233                 :             : {
    8234                 :             : #ifndef WIN32
    8235                 :         275 :         const char *home;
    8236                 :             : 
    8237                 :         275 :         home = getenv("HOME");
    8238   [ +  -  -  + ]:         275 :         if (home && home[0])
    8239                 :             :         {
    8240                 :         275 :                 strlcpy(buf, home, bufsize);
    8241                 :         275 :                 return true;
    8242                 :             :         }
    8243                 :             :         else
    8244                 :             :         {
    8245                 :           0 :                 struct passwd pwbuf;
    8246                 :           0 :                 struct passwd *pw;
    8247                 :           0 :                 char            tmpbuf[1024];
    8248                 :           0 :                 int                     rc;
    8249                 :             : 
    8250                 :           0 :                 rc = getpwuid_r(geteuid(), &pwbuf, tmpbuf, sizeof tmpbuf, &pw);
    8251   [ #  #  #  # ]:           0 :                 if (rc != 0 || !pw)
    8252                 :           0 :                         return false;
    8253                 :           0 :                 strlcpy(buf, pw->pw_dir, bufsize);
    8254                 :           0 :                 return true;
    8255                 :           0 :         }
    8256                 :             : #else
    8257                 :             :         char            tmppath[MAX_PATH];
    8258                 :             : 
    8259                 :             :         ZeroMemory(tmppath, sizeof(tmppath));
    8260                 :             :         if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
    8261                 :             :                 return false;
    8262                 :             :         snprintf(buf, bufsize, "%s/postgresql", tmppath);
    8263                 :             :         return true;
    8264                 :             : #endif
    8265                 :         275 : }
    8266                 :             : 
    8267                 :             : /*
    8268                 :             :  * Parse and try to interpret "value" as an integer value, and if successful,
    8269                 :             :  * store it in *result, complaining if there is any trailing garbage or an
    8270                 :             :  * overflow.  This allows any number of leading and trailing whitespaces.
    8271                 :             :  */
    8272                 :             : bool
    8273                 :         318 : pqParseIntParam(const char *value, int *result, PGconn *conn,
    8274                 :             :                                 const char *context)
    8275                 :             : {
    8276                 :         318 :         char       *end;
    8277                 :         318 :         long            numval;
    8278                 :             : 
    8279         [ +  - ]:         318 :         Assert(value != NULL);
    8280                 :             : 
    8281                 :         318 :         *result = 0;
    8282                 :             : 
    8283                 :             :         /* strtol(3) skips leading whitespaces */
    8284                 :         318 :         errno = 0;
    8285                 :         318 :         numval = strtol(value, &end, 10);
    8286                 :             : 
    8287                 :             :         /*
    8288                 :             :          * If no progress was done during the parsing or an error happened, fail.
    8289                 :             :          * This tests properly for overflows of the result.
    8290                 :             :          */
    8291   [ +  -  +  -  :         318 :         if (value == end || errno != 0 || numval != (int) numval)
                   -  + ]
    8292                 :           0 :                 goto error;
    8293                 :             : 
    8294                 :             :         /*
    8295                 :             :          * Skip any trailing whitespace; if anything but whitespace remains before
    8296                 :             :          * the terminating character, fail
    8297                 :             :          */
    8298   [ +  -  -  + ]:         318 :         while (*end != '\0' && isspace((unsigned char) *end))
    8299                 :           0 :                 end++;
    8300                 :             : 
    8301         [ -  + ]:         318 :         if (*end != '\0')
    8302                 :           0 :                 goto error;
    8303                 :             : 
    8304                 :         318 :         *result = numval;
    8305                 :         318 :         return true;
    8306                 :             : 
    8307                 :             : error:
    8308                 :           0 :         libpq_append_conn_error(conn, "invalid integer value \"%s\" for connection option \"%s\"",
    8309                 :           0 :                                                         value, context);
    8310                 :           0 :         return false;
    8311                 :         318 : }
    8312                 :             : 
    8313                 :             : /*
    8314                 :             :  * Parse and try to interpret "value" as a ProtocolVersion value, and if
    8315                 :             :  * successful, store it in *result.
    8316                 :             :  */
    8317                 :             : static bool
    8318                 :           0 : pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn,
    8319                 :             :                                            const char *context)
    8320                 :             : {
    8321         [ #  # ]:           0 :         if (strcmp(value, "latest") == 0)
    8322                 :             :         {
    8323                 :           0 :                 *result = PG_PROTOCOL_LATEST;
    8324                 :           0 :                 return true;
    8325                 :             :         }
    8326         [ #  # ]:           0 :         if (strcmp(value, "3.0") == 0)
    8327                 :             :         {
    8328                 :           0 :                 *result = PG_PROTOCOL(3, 0);
    8329                 :           0 :                 return true;
    8330                 :             :         }
    8331                 :             : 
    8332                 :             :         /* 3.1 never existed, we went straight from 3.0 to 3.2 */
    8333                 :             : 
    8334         [ #  # ]:           0 :         if (strcmp(value, "3.2") == 0)
    8335                 :             :         {
    8336                 :           0 :                 *result = PG_PROTOCOL(3, 2);
    8337                 :           0 :                 return true;
    8338                 :             :         }
    8339                 :             : 
    8340                 :           0 :         libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
    8341                 :           0 :                                                         context, value);
    8342                 :           0 :         return false;
    8343                 :           0 : }
    8344                 :             : 
    8345                 :             : /*
    8346                 :             :  * To keep the API consistent, the locking stubs are always provided, even
    8347                 :             :  * if they are not required.
    8348                 :             :  *
    8349                 :             :  * Since we neglected to provide any error-return convention in the
    8350                 :             :  * pgthreadlock_t API, we can't do much except Assert upon failure of any
    8351                 :             :  * mutex primitive.  Fortunately, such failures appear to be nonexistent in
    8352                 :             :  * the field.
    8353                 :             :  */
    8354                 :             : 
    8355                 :             : static void
    8356                 :           0 : default_threadlock(int acquire)
    8357                 :             : {
    8358                 :             :         static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
    8359                 :             : 
    8360         [ #  # ]:           0 :         if (acquire)
    8361                 :             :         {
    8362         [ #  # ]:           0 :                 if (pthread_mutex_lock(&singlethread_lock))
    8363                 :           0 :                         Assert(false);
    8364                 :           0 :         }
    8365                 :             :         else
    8366                 :             :         {
    8367         [ #  # ]:           0 :                 if (pthread_mutex_unlock(&singlethread_lock))
    8368                 :           0 :                         Assert(false);
    8369                 :             :         }
    8370                 :           0 : }
    8371                 :             : 
    8372                 :             : pgthreadlock_t
    8373                 :           0 : PQregisterThreadLock(pgthreadlock_t newhandler)
    8374                 :             : {
    8375                 :           0 :         pgthreadlock_t prev = pg_g_threadlock;
    8376                 :             : 
    8377         [ #  # ]:           0 :         if (newhandler)
    8378                 :           0 :                 pg_g_threadlock = newhandler;
    8379                 :             :         else
    8380                 :           0 :                 pg_g_threadlock = default_threadlock;
    8381                 :             : 
    8382                 :           0 :         return prev;
    8383                 :           0 : }
        

Generated by: LCOV version 2.3.2-1