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

Generated by: LCOV version 1.14