LCOV - code coverage report
Current view: top level - src/interfaces/libpq - fe-connect.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18beta1 Lines: 1777 2694 66.0 %
Date: 2025-05-15 20:16:04 Functions: 99 111 89.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14