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

Generated by: LCOV version 1.13