PostgreSQL Source Code  git master
fe-connect.c File Reference
#include "postgres_fe.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <netdb.h>
#include <time.h>
#include <unistd.h>
#include "common/ip.h"
#include "common/link-canary.h"
#include "common/scram-common.h"
#include "common/string.h"
#include "fe-auth.h"
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include "pg_config_paths.h"
#include "port/pg_bswap.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
Include dependency graph for fe-connect.c:

Go to the source code of this file.

Data Structures

struct  _internalPQconninfoOption
 

Macros

#define PGPASSFILE   ".pgpass"
 
#define ERRCODE_APPNAME_UNKNOWN   "42704"
 
#define ERRCODE_INVALID_PASSWORD   "28P01"
 
#define ERRCODE_CANNOT_CONNECT_NOW   "57P03"
 
#define DefaultHost   "localhost"
 
#define DefaultOption   ""
 
#define DefaultChannelBinding   "disable"
 
#define DefaultTargetSessionAttrs   "any"
 
#define DefaultLoadBalanceHosts   "disable"
 
#define DefaultSSLMode   "disable"
 
#define DefaultSSLCertMode   "disable"
 
#define DefaultSSLNegotiation   "postgres"
 
#define DefaultGSSMode   "disable"
 
#define ENCRYPTION_NEGOTIATION_FAILED()
 
#define CONNECTION_FAILED()
 
#define MAX_ERRLEN   30000
 
#define SELECT_NEXT_METHOD(method)
 

Typedefs

typedef struct _internalPQconninfoOption internalPQconninfoOption
 

Functions

static bool connectOptions1 (PGconn *conn, const char *conninfo)
 
static bool init_allowed_encryption_methods (PGconn *conn)
 
static bool connection_failed (PGconn *conn)
 
static bool select_next_encryption_method (PGconn *conn, bool have_valid_connection)
 
static PGPing internal_ping (PGconn *conn)
 
static void pqFreeCommandQueue (PGcmdQueueEntry *queue)
 
static bool fillPGconn (PGconn *conn, PQconninfoOption *connOptions)
 
static void freePGconn (PGconn *conn)
 
static void release_conn_addrinfo (PGconn *conn)
 
static int store_conn_addrinfo (PGconn *conn, struct addrinfo *addrlist)
 
static void sendTerminateConn (PGconn *conn)
 
static PQconninfoOptionconninfo_init (PQExpBuffer errorMessage)
 
static PQconninfoOptionparse_connection_string (const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
 
static int uri_prefix_length (const char *connstr)
 
static bool recognized_connection_string (const char *connstr)
 
static PQconninfoOptionconninfo_parse (const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
 
static PQconninfoOptionconninfo_array_parse (const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
 
static bool conninfo_add_defaults (PQconninfoOption *options, PQExpBuffer errorMessage)
 
static PQconninfoOptionconninfo_uri_parse (const char *uri, PQExpBuffer errorMessage, bool use_defaults)
 
static bool conninfo_uri_parse_options (PQconninfoOption *options, const char *uri, PQExpBuffer errorMessage)
 
static bool conninfo_uri_parse_params (char *params, PQconninfoOption *connOptions, PQExpBuffer errorMessage)
 
static char * conninfo_uri_decode (const char *str, PQExpBuffer errorMessage)
 
static bool get_hexdigit (char digit, int *value)
 
static const char * conninfo_getval (PQconninfoOption *connOptions, const char *keyword)
 
static PQconninfoOptionconninfo_storeval (PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
 
static PQconninfoOptionconninfo_find (PQconninfoOption *connOptions, const char *keyword)
 
static void defaultNoticeReceiver (void *arg, const PGresult *res)
 
static void defaultNoticeProcessor (void *arg, const char *message)
 
static int parseServiceInfo (PQconninfoOption *options, PQExpBuffer errorMessage)
 
static int parseServiceFile (const char *serviceFile, const char *service, PQconninfoOption *options, PQExpBuffer errorMessage, bool *group_found)
 
static char * pwdfMatchesString (char *buf, const char *token)
 
static char * passwordFromFile (const char *hostname, const char *port, const char *dbname, const char *username, const char *pgpassfile)
 
static void pgpassfileWarning (PGconn *conn)
 
static void default_threadlock (int acquire)
 
static bool sslVerifyProtocolVersion (const char *version)
 
static bool sslVerifyProtocolRange (const char *min, const char *max)
 
void pqDropConnection (PGconn *conn, bool flushInput)
 
static void pqDropServerData (PGconn *conn)
 
PGconnPQconnectdbParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGPing PQpingParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGconnPQconnectdb (const char *conninfo)
 
PGPing PQping (const char *conninfo)
 
PGconnPQconnectStartParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGconnPQconnectStart (const char *conninfo)
 
bool pqCopyPGconn (PGconn *srcConn, PGconn *dstConn)
 
static int count_comma_separated_elems (const char *input)
 
static char * parse_comma_separated_list (char **startptr, bool *more)
 
static void libpq_prng_init (PGconn *conn)
 
bool pqConnectOptions2 (PGconn *conn)
 
PQconninfoOptionPQconndefaults (void)
 
PGconnPQsetdbLogin (const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
 
static int connectNoDelay (PGconn *conn)
 
static void getHostaddr (PGconn *conn, char *host_addr, int host_addr_len)
 
static void emitHostIdentityInfo (PGconn *conn, const char *host_addr)
 
static void connectFailureMessage (PGconn *conn, int errorno)
 
static int useKeepalives (PGconn *conn)
 
static int setKeepalivesIdle (PGconn *conn)
 
static int setKeepalivesInterval (PGconn *conn)
 
static int setKeepalivesCount (PGconn *conn)
 
static int setTCPUserTimeout (PGconn *conn)
 
int pqConnectDBStart (PGconn *conn)
 
int pqConnectDBComplete (PGconn *conn)
 
PostgresPollingStatusType PQconnectPoll (PGconn *conn)
 
PGconnpqMakeEmptyPGconn (void)
 
void pqReleaseConnHosts (PGconn *conn)
 
void pqClosePGconn (PGconn *conn)
 
void PQfinish (PGconn *conn)
 
void PQreset (PGconn *conn)
 
int PQresetStart (PGconn *conn)
 
PostgresPollingStatusType PQresetPoll (PGconn *conn)
 
int pqPacketSend (PGconn *conn, char pack_type, const void *buf, size_t buf_len)
 
PQconninfoOptionPQconninfoParse (const char *conninfo, char **errmsg)
 
PQconninfoOptionPQconninfo (PGconn *conn)
 
void PQconninfoFree (PQconninfoOption *connOptions)
 
char * PQdb (const PGconn *conn)
 
char * PQuser (const PGconn *conn)
 
char * PQpass (const PGconn *conn)
 
char * PQhost (const PGconn *conn)
 
char * PQhostaddr (const PGconn *conn)
 
char * PQport (const PGconn *conn)
 
char * PQtty (const PGconn *conn)
 
char * PQoptions (const PGconn *conn)
 
ConnStatusType PQstatus (const PGconn *conn)
 
PGTransactionStatusType PQtransactionStatus (const PGconn *conn)
 
const char * PQparameterStatus (const PGconn *conn, const char *paramName)
 
int PQprotocolVersion (const PGconn *conn)
 
int PQserverVersion (const PGconn *conn)
 
char * PQerrorMessage (const PGconn *conn)
 
int PQsocket (const PGconn *conn)
 
int PQbackendPID (const PGconn *conn)
 
PGpipelineStatus PQpipelineStatus (const PGconn *conn)
 
int PQconnectionNeedsPassword (const PGconn *conn)
 
int PQconnectionUsedPassword (const PGconn *conn)
 
int PQconnectionUsedGSSAPI (const PGconn *conn)
 
int PQclientEncoding (const PGconn *conn)
 
int PQsetClientEncoding (PGconn *conn, const char *encoding)
 
PGVerbosity PQsetErrorVerbosity (PGconn *conn, PGVerbosity verbosity)
 
PGContextVisibility PQsetErrorContextVisibility (PGconn *conn, PGContextVisibility show_context)
 
PQnoticeReceiver PQsetNoticeReceiver (PGconn *conn, PQnoticeReceiver proc, void *arg)
 
PQnoticeProcessor PQsetNoticeProcessor (PGconn *conn, PQnoticeProcessor proc, void *arg)
 
bool pqGetHomeDirectory (char *buf, int bufsize)
 
bool pqParseIntParam (const char *value, int *result, PGconn *conn, const char *context)
 
pgthreadlock_t PQregisterThreadLock (pgthreadlock_t newhandler)
 

Variables

static const internalPQconninfoOption PQconninfoOptions []
 
static const PQEnvironmentOption EnvironmentOptions []
 
static const char uri_designator [] = "postgresql://"
 
static const char short_uri_designator [] = "postgres://"
 
pgthreadlock_t pg_g_threadlock = default_threadlock
 

Macro Definition Documentation

◆ CONNECTION_FAILED

#define CONNECTION_FAILED ( )
Value:
do { \
{ \
need_new_connection = true; \
goto keep_going; \
} \
else \
goto error_return; \
} while(0);
static bool connection_failed(PGconn *conn)
Definition: fe-connect.c:4353
PGconn * conn
Definition: streamutil.c:55

◆ DefaultChannelBinding

#define DefaultChannelBinding   "disable"

Definition at line 121 of file fe-connect.c.

◆ DefaultGSSMode

#define DefaultGSSMode   "disable"

Definition at line 137 of file fe-connect.c.

◆ DefaultHost

#define DefaultHost   "localhost"

Definition at line 116 of file fe-connect.c.

◆ DefaultLoadBalanceHosts

#define DefaultLoadBalanceHosts   "disable"

Definition at line 124 of file fe-connect.c.

◆ DefaultOption

#define DefaultOption   ""

Definition at line 117 of file fe-connect.c.

◆ DefaultSSLCertMode

#define DefaultSSLCertMode   "disable"

Definition at line 130 of file fe-connect.c.

◆ DefaultSSLMode

#define DefaultSSLMode   "disable"

Definition at line 129 of file fe-connect.c.

◆ DefaultSSLNegotiation

#define DefaultSSLNegotiation   "postgres"

Definition at line 132 of file fe-connect.c.

◆ DefaultTargetSessionAttrs

#define DefaultTargetSessionAttrs   "any"

Definition at line 123 of file fe-connect.c.

◆ ENCRYPTION_NEGOTIATION_FAILED

#define ENCRYPTION_NEGOTIATION_FAILED ( )
Value:
do { \
switch (encryption_negotiation_failed(conn)) \
{ \
case 0: \
goto error_return; \
case 1: \
conn->status = CONNECTION_MADE; \
case 2: \
need_new_connection = true; \
goto keep_going; \
} \
} while(0);
@ CONNECTION_MADE
Definition: libpq-fe.h:70
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:92

◆ ERRCODE_APPNAME_UNKNOWN

#define ERRCODE_APPNAME_UNKNOWN   "42704"

Definition at line 86 of file fe-connect.c.

◆ ERRCODE_CANNOT_CONNECT_NOW

#define ERRCODE_CANNOT_CONNECT_NOW   "57P03"

Definition at line 91 of file fe-connect.c.

◆ ERRCODE_INVALID_PASSWORD

#define ERRCODE_INVALID_PASSWORD   "28P01"

Definition at line 89 of file fe-connect.c.

◆ MAX_ERRLEN

#define MAX_ERRLEN   30000

◆ PGPASSFILE

#define PGPASSFILE   ".pgpass"

Definition at line 75 of file fe-connect.c.

◆ SELECT_NEXT_METHOD

#define SELECT_NEXT_METHOD (   method)
Value:
do { \
if ((remaining_methods & method) != 0) \
{ \
conn->current_enc_method = method; \
return true; \
} \
} while (false)

Typedef Documentation

◆ internalPQconninfoOption

Function Documentation

◆ connectFailureMessage()

static void connectFailureMessage ( PGconn conn,
int  errorno 
)
static

Definition at line 2131 of file fe-connect.c.

2132 {
2133  char sebuf[PG_STRERROR_R_BUFLEN];
2134 
2136  "%s\n",
2137  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2138 
2139  if (conn->raddr.addr.ss_family == AF_UNIX)
2140  libpq_append_conn_error(conn, "\tIs the server running locally and accepting connections on that socket?");
2141  else
2142  libpq_append_conn_error(conn, "\tIs the server running on that host and accepting TCP/IP connections?");
2143 }
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1324
#define SOCK_STRERROR
Definition: libpq-int.h:935
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
struct sockaddr_storage addr
Definition: pqcomm.h:32
PQExpBufferData errorMessage
Definition: libpq-int.h:635
SockAddr raddr
Definition: libpq-int.h:478

References SockAddr::addr, appendPQExpBuffer(), conn, pg_conn::errorMessage, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, pg_conn::raddr, and SOCK_STRERROR.

Referenced by PQconnectPoll().

◆ connection_failed()

static bool connection_failed ( PGconn conn)
static

Definition at line 4353 of file fe-connect.c.

4354 {
4357 
4358  /*
4359  * If the server reported an error after the SSL handshake, no point in
4360  * retrying with negotiated vs direct SSL.
4361  */
4364  {
4366  }
4367  else
4369 
4370  return select_next_encryption_method(conn, false);
4371 }
#define Assert(condition)
Definition: c.h:858
static bool select_next_encryption_method(PGconn *conn, bool have_valid_connection)
Definition: fe-connect.c:4380
#define ENC_DIRECT_SSL
Definition: libpq-int.h:238
#define ENC_NEGOTIATED_SSL
Definition: libpq-int.h:239
uint8 failed_enc_methods
Definition: libpq-int.h:564
uint8 current_enc_method
Definition: libpq-int.h:565
uint8 allowed_enc_methods
Definition: libpq-int.h:563
bool ssl_handshake_started
Definition: libpq-int.h:569

References pg_conn::allowed_enc_methods, Assert, conn, pg_conn::current_enc_method, ENC_DIRECT_SSL, ENC_NEGOTIATED_SSL, pg_conn::failed_enc_methods, select_next_encryption_method(), and pg_conn::ssl_handshake_started.

◆ connectNoDelay()

static int connectNoDelay ( PGconn conn)
static

Definition at line 2016 of file fe-connect.c.

2017 {
2018 #ifdef TCP_NODELAY
2019  int on = 1;
2020 
2021  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
2022  (char *) &on,
2023  sizeof(on)) < 0)
2024  {
2025  char sebuf[PG_STRERROR_R_BUFLEN];
2026 
2027  libpq_append_conn_error(conn, "could not set socket to TCP no delay mode: %s",
2028  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2029  return 0;
2030  }
2031 #endif
2032 
2033  return 1;
2034 }
#define SOCK_ERRNO
Definition: libpq-int.h:934
pgsocket sock
Definition: libpq-int.h:475

References conn, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, pg_conn::sock, SOCK_ERRNO, and SOCK_STRERROR.

Referenced by PQconnectPoll().

◆ connectOptions1()

static bool connectOptions1 ( PGconn conn,
const char *  conninfo 
)
static

Definition at line 997 of file fe-connect.c.

998 {
999  PQconninfoOption *connOptions;
1000 
1001  /*
1002  * Parse the conninfo string
1003  */
1004  connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
1005  if (connOptions == NULL)
1006  {
1008  /* errorMessage is already set */
1009  return false;
1010  }
1011 
1012  /*
1013  * Move option values into conn structure
1014  */
1015  if (!fillPGconn(conn, connOptions))
1016  {
1018  PQconninfoFree(connOptions);
1019  return false;
1020  }
1021 
1022  /*
1023  * Free the option info - all is in conn now
1024  */
1025  PQconninfoFree(connOptions);
1026 
1027  return true;
1028 }
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5789
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6980
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:918
@ CONNECTION_BAD
Definition: libpq-fe.h:62
ConnStatusType status
Definition: libpq-int.h:438

References conn, CONNECTION_BAD, pg_conn::errorMessage, fillPGconn(), parse_connection_string(), PQconninfoFree(), and pg_conn::status.

Referenced by PQconnectStart(), and PQsetdbLogin().

◆ conninfo_add_defaults()

static bool conninfo_add_defaults ( PQconninfoOption options,
PQExpBuffer  errorMessage 
)
static

Definition at line 6177 of file fe-connect.c.

6178 {
6180  PQconninfoOption *sslmode_default = NULL,
6181  *sslrootcert = NULL;
6182  char *tmp;
6183 
6184  /*
6185  * If there's a service spec, use it to obtain any not-explicitly-given
6186  * parameters. Ignore error if no error message buffer is passed because
6187  * there is no way to pass back the failure message.
6188  */
6189  if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
6190  return false;
6191 
6192  /*
6193  * Get the fallback resources for parameters not specified in the conninfo
6194  * string nor the service.
6195  */
6196  for (option = options; option->keyword != NULL; option++)
6197  {
6198  if (strcmp(option->keyword, "sslrootcert") == 0)
6199  sslrootcert = option; /* save for later */
6200 
6201  if (option->val != NULL)
6202  continue; /* Value was in conninfo or service */
6203 
6204  /*
6205  * Try to get the environment variable fallback
6206  */
6207  if (option->envvar != NULL)
6208  {
6209  if ((tmp = getenv(option->envvar)) != NULL)
6210  {
6211  option->val = strdup(tmp);
6212  if (!option->val)
6213  {
6214  if (errorMessage)
6215  libpq_append_error(errorMessage, "out of memory");
6216  return false;
6217  }
6218  continue;
6219  }
6220  }
6221 
6222  /*
6223  * Interpret the deprecated PGREQUIRESSL environment variable. Per
6224  * tradition, translate values starting with "1" to sslmode=require,
6225  * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
6226  * PGSSLMODE takes precedence; the opposite was true before v9.3.
6227  */
6228  if (strcmp(option->keyword, "sslmode") == 0)
6229  {
6230  const char *requiresslenv = getenv("PGREQUIRESSL");
6231 
6232  if (requiresslenv != NULL && requiresslenv[0] == '1')
6233  {
6234  option->val = strdup("require");
6235  if (!option->val)
6236  {
6237  if (errorMessage)
6238  libpq_append_error(errorMessage, "out of memory");
6239  return false;
6240  }
6241  continue;
6242  }
6243 
6244  /*
6245  * sslmode is not specified. Let it be filled in with the compiled
6246  * default for now, but if sslrootcert=system, we'll override the
6247  * default later before returning.
6248  */
6249  sslmode_default = option;
6250  }
6251 
6252  /*
6253  * No environment variable specified or the variable isn't set - try
6254  * compiled-in default
6255  */
6256  if (option->compiled != NULL)
6257  {
6258  option->val = strdup(option->compiled);
6259  if (!option->val)
6260  {
6261  if (errorMessage)
6262  libpq_append_error(errorMessage, "out of memory");
6263  return false;
6264  }
6265  continue;
6266  }
6267 
6268  /*
6269  * Special handling for "user" option. Note that if pg_fe_getauthname
6270  * fails, we just leave the value as NULL; there's no need for this to
6271  * be an error condition if the caller provides a user name. The only
6272  * reason we do this now at all is so that callers of PQconndefaults
6273  * will see a correct default (barring error, of course).
6274  */
6275  if (strcmp(option->keyword, "user") == 0)
6276  {
6277  option->val = pg_fe_getauthname(NULL);
6278  continue;
6279  }
6280  }
6281 
6282  /*
6283  * Special handling for sslrootcert=system with no sslmode explicitly
6284  * defined. In this case we want to strengthen the default sslmode to
6285  * verify-full.
6286  */
6287  if (sslmode_default && sslrootcert)
6288  {
6289  if (sslrootcert->val && strcmp(sslrootcert->val, "system") == 0)
6290  {
6291  free(sslmode_default->val);
6292 
6293  sslmode_default->val = strdup("verify-full");
6294  if (!sslmode_default->val)
6295  {
6296  if (errorMessage)
6297  libpq_append_error(errorMessage, "out of memory");
6298  return false;
6299  }
6300  }
6301  }
6302 
6303  return true;
6304 }
char * pg_fe_getauthname(PQExpBuffer errorMessage)
Definition: fe-auth.c:1213
static int parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5482
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1295
#define free(a)
Definition: header.h:65
int val
Definition: getopt_long.h:21

References free, libpq_append_error(), parseServiceInfo(), pg_fe_getauthname(), option::val, and _PQconninfoOption::val.

Referenced by conninfo_array_parse(), conninfo_parse(), conninfo_uri_parse(), and PQconndefaults().

◆ conninfo_array_parse()

static PQconninfoOption * conninfo_array_parse ( const char *const *  keywords,
const char *const *  values,
PQExpBuffer  errorMessage,
bool  use_defaults,
int  expand_dbname 
)
static

Definition at line 6019 of file fe-connect.c.

6022 {
6024  PQconninfoOption *dbname_options = NULL;
6026  int i = 0;
6027 
6028  /*
6029  * If expand_dbname is non-zero, check keyword "dbname" to see if val is
6030  * actually a recognized connection string.
6031  */
6032  while (expand_dbname && keywords[i])
6033  {
6034  const char *pname = keywords[i];
6035  const char *pvalue = values[i];
6036 
6037  /* first find "dbname" if any */
6038  if (strcmp(pname, "dbname") == 0 && pvalue)
6039  {
6040  /*
6041  * If value is a connection string, parse it, but do not use
6042  * defaults here -- those get picked up later. We only want to
6043  * override for those parameters actually passed.
6044  */
6045  if (recognized_connection_string(pvalue))
6046  {
6047  dbname_options = parse_connection_string(pvalue, errorMessage, false);
6048  if (dbname_options == NULL)
6049  return NULL;
6050  }
6051  break;
6052  }
6053  ++i;
6054  }
6055 
6056  /* Make a working copy of PQconninfoOptions */
6057  options = conninfo_init(errorMessage);
6058  if (options == NULL)
6059  {
6060  PQconninfoFree(dbname_options);
6061  return NULL;
6062  }
6063 
6064  /* Parse the keywords/values arrays */
6065  i = 0;
6066  while (keywords[i])
6067  {
6068  const char *pname = keywords[i];
6069  const char *pvalue = values[i];
6070 
6071  if (pvalue != NULL && pvalue[0] != '\0')
6072  {
6073  /* Search for the param record */
6074  for (option = options; option->keyword != NULL; option++)
6075  {
6076  if (strcmp(option->keyword, pname) == 0)
6077  break;
6078  }
6079 
6080  /* Check for invalid connection option */
6081  if (option->keyword == NULL)
6082  {
6083  libpq_append_error(errorMessage, "invalid connection option \"%s\"", pname);
6085  PQconninfoFree(dbname_options);
6086  return NULL;
6087  }
6088 
6089  /*
6090  * If we are on the first dbname parameter, and we have a parsed
6091  * connection string, copy those parameters across, overriding any
6092  * existing previous settings.
6093  */
6094  if (strcmp(pname, "dbname") == 0 && dbname_options)
6095  {
6096  PQconninfoOption *str_option;
6097 
6098  for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
6099  {
6100  if (str_option->val != NULL)
6101  {
6102  int k;
6103 
6104  for (k = 0; options[k].keyword; k++)
6105  {
6106  if (strcmp(options[k].keyword, str_option->keyword) == 0)
6107  {
6108  free(options[k].val);
6109  options[k].val = strdup(str_option->val);
6110  if (!options[k].val)
6111  {
6112  libpq_append_error(errorMessage, "out of memory");
6114  PQconninfoFree(dbname_options);
6115  return NULL;
6116  }
6117  break;
6118  }
6119  }
6120  }
6121  }
6122 
6123  /*
6124  * Forget the parsed connection string, so that any subsequent
6125  * dbname parameters will not be expanded.
6126  */
6127  PQconninfoFree(dbname_options);
6128  dbname_options = NULL;
6129  }
6130  else
6131  {
6132  /*
6133  * Store the value, overriding previous settings
6134  */
6135  free(option->val);
6136  option->val = strdup(pvalue);
6137  if (!option->val)
6138  {
6139  libpq_append_error(errorMessage, "out of memory");
6141  PQconninfoFree(dbname_options);
6142  return NULL;
6143  }
6144  }
6145  }
6146  ++i;
6147  }
6148  PQconninfoFree(dbname_options);
6149 
6150  /*
6151  * Add in defaults if the caller wants that.
6152  */
6153  if (use_defaults)
6154  {
6155  if (!conninfo_add_defaults(options, errorMessage))
6156  {
6158  return NULL;
6159  }
6160  }
6161 
6162  return options;
6163 }
static Datum values[MAXATTR]
Definition: bootstrap.c:152
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5750
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6177
static bool recognized_connection_string(const char *connstr)
Definition: fe-connect.c:5832
long val
Definition: informix.c:670
int i
Definition: isn.c:73
static char ** options

References conninfo_add_defaults(), conninfo_init(), free, i, _PQconninfoOption::keyword, libpq_append_error(), options, parse_connection_string(), PQconninfoFree(), recognized_connection_string(), option::val, val, _PQconninfoOption::val, and values.

Referenced by PQconnectStartParams().

◆ conninfo_find()

static PQconninfoOption * conninfo_find ( PQconninfoOption connOptions,
const char *  keyword 
)
static

Definition at line 6918 of file fe-connect.c.

6919 {
6921 
6922  for (option = connOptions; option->keyword != NULL; option++)
6923  {
6924  if (strcmp(option->keyword, keyword) == 0)
6925  return option;
6926  }
6927 
6928  return NULL;
6929 }

Referenced by conninfo_getval(), and conninfo_storeval().

◆ conninfo_getval()

static const char * conninfo_getval ( PQconninfoOption connOptions,
const char *  keyword 
)
static

Definition at line 6828 of file fe-connect.c.

6830 {
6832 
6833  option = conninfo_find(connOptions, keyword);
6834 
6835  return option ? option->val : NULL;
6836 }
static PQconninfoOption * conninfo_find(PQconninfoOption *connOptions, const char *keyword)
Definition: fe-connect.c:6918

References conninfo_find(), and option::val.

Referenced by fillPGconn(), and parseServiceInfo().

◆ conninfo_init()

static PQconninfoOption * conninfo_init ( PQExpBuffer  errorMessage)
static

Definition at line 5750 of file fe-connect.c.

5751 {
5753  PQconninfoOption *opt_dest;
5754  const internalPQconninfoOption *cur_opt;
5755 
5756  /*
5757  * Get enough memory for all options in PQconninfoOptions, even if some
5758  * end up being filtered out.
5759  */
5761  if (options == NULL)
5762  {
5763  libpq_append_error(errorMessage, "out of memory");
5764  return NULL;
5765  }
5766  opt_dest = options;
5767 
5768  for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
5769  {
5770  /* Only copy the public part of the struct, not the full internal */
5771  memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
5772  opt_dest++;
5773  }
5774  MemSet(opt_dest, 0, sizeof(PQconninfoOption));
5775 
5776  return options;
5777 }
#define MemSet(start, val, len)
Definition: c.h:1020
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:190
#define malloc(a)
Definition: header.h:50

References _internalPQconninfoOption::keyword, libpq_append_error(), malloc, MemSet, options, and PQconninfoOptions.

Referenced by conninfo_array_parse(), conninfo_parse(), conninfo_uri_parse(), PQconndefaults(), and PQconninfo().

◆ conninfo_parse()

static PQconninfoOption * conninfo_parse ( const char *  conninfo,
PQExpBuffer  errorMessage,
bool  use_defaults 
)
static

Definition at line 5843 of file fe-connect.c.

5845 {
5846  char *pname;
5847  char *pval;
5848  char *buf;
5849  char *cp;
5850  char *cp2;
5852 
5853  /* Make a working copy of PQconninfoOptions */
5854  options = conninfo_init(errorMessage);
5855  if (options == NULL)
5856  return NULL;
5857 
5858  /* Need a modifiable copy of the input string */
5859  if ((buf = strdup(conninfo)) == NULL)
5860  {
5861  libpq_append_error(errorMessage, "out of memory");
5863  return NULL;
5864  }
5865  cp = buf;
5866 
5867  while (*cp)
5868  {
5869  /* Skip blanks before the parameter name */
5870  if (isspace((unsigned char) *cp))
5871  {
5872  cp++;
5873  continue;
5874  }
5875 
5876  /* Get the parameter name */
5877  pname = cp;
5878  while (*cp)
5879  {
5880  if (*cp == '=')
5881  break;
5882  if (isspace((unsigned char) *cp))
5883  {
5884  *cp++ = '\0';
5885  while (*cp)
5886  {
5887  if (!isspace((unsigned char) *cp))
5888  break;
5889  cp++;
5890  }
5891  break;
5892  }
5893  cp++;
5894  }
5895 
5896  /* Check that there is a following '=' */
5897  if (*cp != '=')
5898  {
5899  libpq_append_error(errorMessage,
5900  "missing \"=\" after \"%s\" in connection info string",
5901  pname);
5903  free(buf);
5904  return NULL;
5905  }
5906  *cp++ = '\0';
5907 
5908  /* Skip blanks after the '=' */
5909  while (*cp)
5910  {
5911  if (!isspace((unsigned char) *cp))
5912  break;
5913  cp++;
5914  }
5915 
5916  /* Get the parameter value */
5917  pval = cp;
5918 
5919  if (*cp != '\'')
5920  {
5921  cp2 = pval;
5922  while (*cp)
5923  {
5924  if (isspace((unsigned char) *cp))
5925  {
5926  *cp++ = '\0';
5927  break;
5928  }
5929  if (*cp == '\\')
5930  {
5931  cp++;
5932  if (*cp != '\0')
5933  *cp2++ = *cp++;
5934  }
5935  else
5936  *cp2++ = *cp++;
5937  }
5938  *cp2 = '\0';
5939  }
5940  else
5941  {
5942  cp2 = pval;
5943  cp++;
5944  for (;;)
5945  {
5946  if (*cp == '\0')
5947  {
5948  libpq_append_error(errorMessage, "unterminated quoted string in connection info string");
5950  free(buf);
5951  return NULL;
5952  }
5953  if (*cp == '\\')
5954  {
5955  cp++;
5956  if (*cp != '\0')
5957  *cp2++ = *cp++;
5958  continue;
5959  }
5960  if (*cp == '\'')
5961  {
5962  *cp2 = '\0';
5963  cp++;
5964  break;
5965  }
5966  *cp2++ = *cp++;
5967  }
5968  }
5969 
5970  /*
5971  * Now that we have the name and the value, store the record.
5972  */
5973  if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5974  {
5976  free(buf);
5977  return NULL;
5978  }
5979  }
5980 
5981  /* Done with the modifiable input string */
5982  free(buf);
5983 
5984  /*
5985  * Add in defaults if the caller wants that.
5986  */
5987  if (use_defaults)
5988  {
5989  if (!conninfo_add_defaults(options, errorMessage))
5990  {
5992  return NULL;
5993  }
5994  }
5995 
5996  return options;
5997 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6854
static char * buf
Definition: pg_test_fsync.c:73

References buf, conninfo_add_defaults(), conninfo_init(), conninfo_storeval(), free, libpq_append_error(), options, and PQconninfoFree().

Referenced by parse_connection_string().

◆ conninfo_storeval()

static PQconninfoOption * conninfo_storeval ( PQconninfoOption connOptions,
const char *  keyword,
const char *  value,
PQExpBuffer  errorMessage,
bool  ignoreMissing,
bool  uri_decode 
)
static

Definition at line 6854 of file fe-connect.c.

6858 {
6860  char *value_copy;
6861 
6862  /*
6863  * For backwards compatibility, requiressl=1 gets translated to
6864  * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
6865  * (which is the default for sslmode).
6866  */
6867  if (strcmp(keyword, "requiressl") == 0)
6868  {
6869  keyword = "sslmode";
6870  if (value[0] == '1')
6871  value = "require";
6872  else
6873  value = "prefer";
6874  }
6875 
6876  option = conninfo_find(connOptions, keyword);
6877  if (option == NULL)
6878  {
6879  if (!ignoreMissing)
6880  libpq_append_error(errorMessage,
6881  "invalid connection option \"%s\"",
6882  keyword);
6883  return NULL;
6884  }
6885 
6886  if (uri_decode)
6887  {
6888  value_copy = conninfo_uri_decode(value, errorMessage);
6889  if (value_copy == NULL)
6890  /* conninfo_uri_decode already set an error message */
6891  return NULL;
6892  }
6893  else
6894  {
6895  value_copy = strdup(value);
6896  if (value_copy == NULL)
6897  {
6898  libpq_append_error(errorMessage, "out of memory");
6899  return NULL;
6900  }
6901  }
6902 
6903  free(option->val);
6904  option->val = value_copy;
6905 
6906  return option;
6907 }
static char * conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
Definition: fe-connect.c:6739
static struct @155 value

References conninfo_find(), conninfo_uri_decode(), free, libpq_append_error(), option::val, and value.

Referenced by conninfo_parse(), conninfo_uri_parse_options(), conninfo_uri_parse_params(), and PQconninfo().

◆ conninfo_uri_decode()

static char * conninfo_uri_decode ( const char *  str,
PQExpBuffer  errorMessage 
)
static

Definition at line 6739 of file fe-connect.c.

6740 {
6741  char *buf;
6742  char *p;
6743  const char *q = str;
6744 
6745  buf = malloc(strlen(str) + 1);
6746  if (buf == NULL)
6747  {
6748  libpq_append_error(errorMessage, "out of memory");
6749  return NULL;
6750  }
6751  p = buf;
6752 
6753  for (;;)
6754  {
6755  if (*q != '%')
6756  {
6757  /* copy and check for NUL terminator */
6758  if (!(*(p++) = *(q++)))
6759  break;
6760  }
6761  else
6762  {
6763  int hi;
6764  int lo;
6765  int c;
6766 
6767  ++q; /* skip the percent sign itself */
6768 
6769  /*
6770  * Possible EOL will be caught by the first call to
6771  * get_hexdigit(), so we never dereference an invalid q pointer.
6772  */
6773  if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
6774  {
6775  libpq_append_error(errorMessage,
6776  "invalid percent-encoded token: \"%s\"",
6777  str);
6778  free(buf);
6779  return NULL;
6780  }
6781 
6782  c = (hi << 4) | lo;
6783  if (c == 0)
6784  {
6785  libpq_append_error(errorMessage,
6786  "forbidden value %%00 in percent-encoded value: \"%s\"",
6787  str);
6788  free(buf);
6789  return NULL;
6790  }
6791  *(p++) = c;
6792  }
6793  }
6794 
6795  return buf;
6796 }
static bool get_hexdigit(char digit, int *value)
Definition: fe-connect.c:6807
const char * str
char * c

References buf, free, get_hexdigit(), libpq_append_error(), malloc, and str.

Referenced by conninfo_storeval(), and conninfo_uri_parse_params().

◆ conninfo_uri_parse()

static PQconninfoOption * conninfo_uri_parse ( const char *  uri,
PQExpBuffer  errorMessage,
bool  use_defaults 
)
static

Definition at line 6312 of file fe-connect.c.

6314 {
6316 
6317  /* Make a working copy of PQconninfoOptions */
6318  options = conninfo_init(errorMessage);
6319  if (options == NULL)
6320  return NULL;
6321 
6322  if (!conninfo_uri_parse_options(options, uri, errorMessage))
6323  {
6325  return NULL;
6326  }
6327 
6328  /*
6329  * Add in defaults if the caller wants that.
6330  */
6331  if (use_defaults)
6332  {
6333  if (!conninfo_add_defaults(options, errorMessage))
6334  {
6336  return NULL;
6337  }
6338  }
6339 
6340  return options;
6341 }
static bool conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, PQExpBuffer errorMessage)
Definition: fe-connect.c:6365

References conninfo_add_defaults(), conninfo_init(), conninfo_uri_parse_options(), options, and PQconninfoFree().

Referenced by parse_connection_string().

◆ conninfo_uri_parse_options()

static bool conninfo_uri_parse_options ( PQconninfoOption options,
const char *  uri,
PQExpBuffer  errorMessage 
)
static

Definition at line 6365 of file fe-connect.c.

6367 {
6368  int prefix_len;
6369  char *p;
6370  char *buf = NULL;
6371  char *start;
6372  char prevchar = '\0';
6373  char *user = NULL;
6374  char *host = NULL;
6375  bool retval = false;
6376  PQExpBufferData hostbuf;
6377  PQExpBufferData portbuf;
6378 
6379  initPQExpBuffer(&hostbuf);
6380  initPQExpBuffer(&portbuf);
6381  if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6382  {
6383  libpq_append_error(errorMessage, "out of memory");
6384  goto cleanup;
6385  }
6386 
6387  /* need a modifiable copy of the input URI */
6388  buf = strdup(uri);
6389  if (buf == NULL)
6390  {
6391  libpq_append_error(errorMessage, "out of memory");
6392  goto cleanup;
6393  }
6394  start = buf;
6395 
6396  /* Skip the URI prefix */
6397  prefix_len = uri_prefix_length(uri);
6398  if (prefix_len == 0)
6399  {
6400  /* Should never happen */
6401  libpq_append_error(errorMessage,
6402  "invalid URI propagated to internal parser routine: \"%s\"",
6403  uri);
6404  goto cleanup;
6405  }
6406  start += prefix_len;
6407  p = start;
6408 
6409  /* Look ahead for possible user credentials designator */
6410  while (*p && *p != '@' && *p != '/')
6411  ++p;
6412  if (*p == '@')
6413  {
6414  /*
6415  * Found username/password designator, so URI should be of the form
6416  * "scheme://user[:password]@[netloc]".
6417  */
6418  user = start;
6419 
6420  p = user;
6421  while (*p != ':' && *p != '@')
6422  ++p;
6423 
6424  /* Save last char and cut off at end of user name */
6425  prevchar = *p;
6426  *p = '\0';
6427 
6428  if (*user &&
6429  !conninfo_storeval(options, "user", user,
6430  errorMessage, false, true))
6431  goto cleanup;
6432 
6433  if (prevchar == ':')
6434  {
6435  const char *password = p + 1;
6436 
6437  while (*p != '@')
6438  ++p;
6439  *p = '\0';
6440 
6441  if (*password &&
6442  !conninfo_storeval(options, "password", password,
6443  errorMessage, false, true))
6444  goto cleanup;
6445  }
6446 
6447  /* Advance past end of parsed user name or password token */
6448  ++p;
6449  }
6450  else
6451  {
6452  /*
6453  * No username/password designator found. Reset to start of URI.
6454  */
6455  p = start;
6456  }
6457 
6458  /*
6459  * There may be multiple netloc[:port] pairs, each separated from the next
6460  * by a comma. When we initially enter this loop, "p" has been
6461  * incremented past optional URI credential information at this point and
6462  * now points at the "netloc" part of the URI. On subsequent loop
6463  * iterations, "p" has been incremented past the comma separator and now
6464  * points at the start of the next "netloc".
6465  */
6466  for (;;)
6467  {
6468  /*
6469  * Look for IPv6 address.
6470  */
6471  if (*p == '[')
6472  {
6473  host = ++p;
6474  while (*p && *p != ']')
6475  ++p;
6476  if (!*p)
6477  {
6478  libpq_append_error(errorMessage,
6479  "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
6480  uri);
6481  goto cleanup;
6482  }
6483  if (p == host)
6484  {
6485  libpq_append_error(errorMessage,
6486  "IPv6 host address may not be empty in URI: \"%s\"",
6487  uri);
6488  goto cleanup;
6489  }
6490 
6491  /* Cut off the bracket and advance */
6492  *(p++) = '\0';
6493 
6494  /*
6495  * The address may be followed by a port specifier or a slash or a
6496  * query or a separator comma.
6497  */
6498  if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6499  {
6500  libpq_append_error(errorMessage,
6501  "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
6502  *p, (int) (p - buf + 1), uri);
6503  goto cleanup;
6504  }
6505  }
6506  else
6507  {
6508  /* not an IPv6 address: DNS-named or IPv4 netloc */
6509  host = p;
6510 
6511  /*
6512  * Look for port specifier (colon) or end of host specifier
6513  * (slash) or query (question mark) or host separator (comma).
6514  */
6515  while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6516  ++p;
6517  }
6518 
6519  /* Save the hostname terminator before we null it */
6520  prevchar = *p;
6521  *p = '\0';
6522 
6523  appendPQExpBufferStr(&hostbuf, host);
6524 
6525  if (prevchar == ':')
6526  {
6527  const char *port = ++p; /* advance past host terminator */
6528 
6529  while (*p && *p != '/' && *p != '?' && *p != ',')
6530  ++p;
6531 
6532  prevchar = *p;
6533  *p = '\0';
6534 
6535  appendPQExpBufferStr(&portbuf, port);
6536  }
6537 
6538  if (prevchar != ',')
6539  break;
6540  ++p; /* advance past comma separator */
6541  appendPQExpBufferChar(&hostbuf, ',');
6542  appendPQExpBufferChar(&portbuf, ',');
6543  }
6544 
6545  /* Save final values for host and port. */
6546  if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6547  goto cleanup;
6548  if (hostbuf.data[0] &&
6549  !conninfo_storeval(options, "host", hostbuf.data,
6550  errorMessage, false, true))
6551  goto cleanup;
6552  if (portbuf.data[0] &&
6553  !conninfo_storeval(options, "port", portbuf.data,
6554  errorMessage, false, true))
6555  goto cleanup;
6556 
6557  if (prevchar && prevchar != '?')
6558  {
6559  const char *dbname = ++p; /* advance past host terminator */
6560 
6561  /* Look for query parameters */
6562  while (*p && *p != '?')
6563  ++p;
6564 
6565  prevchar = *p;
6566  *p = '\0';
6567 
6568  /*
6569  * Avoid setting dbname to an empty string, as it forces the default
6570  * value (username) and ignores $PGDATABASE, as opposed to not setting
6571  * it at all.
6572  */
6573  if (*dbname &&
6574  !conninfo_storeval(options, "dbname", dbname,
6575  errorMessage, false, true))
6576  goto cleanup;
6577  }
6578 
6579  if (prevchar)
6580  {
6581  ++p; /* advance past terminator */
6582 
6583  if (!conninfo_uri_parse_params(p, options, errorMessage))
6584  goto cleanup;
6585  }
6586 
6587  /* everything parsed okay */
6588  retval = true;
6589 
6590 cleanup:
6591  termPQExpBuffer(&hostbuf);
6592  termPQExpBuffer(&portbuf);
6593  free(buf);
6594  return retval;
6595 }
static void cleanup(void)
Definition: bootstrap.c:682
static int uri_prefix_length(const char *connstr)
Definition: fe-connect.c:5809
static bool conninfo_uri_parse_params(char *params, PQconninfoOption *connOptions, PQExpBuffer errorMessage)
Definition: fe-connect.c:6606
return str start
static char * user
Definition: pg_regress.c:120
static int port
Definition: pg_regress.c:116
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
static char * password
Definition: streamutil.c:54
char * dbname
Definition: streamutil.c:52

References appendPQExpBufferChar(), appendPQExpBufferStr(), buf, cleanup(), conninfo_storeval(), conninfo_uri_parse_params(), PQExpBufferData::data, dbname, free, initPQExpBuffer(), libpq_append_error(), password, port, PQExpBufferDataBroken, start, termPQExpBuffer(), uri_prefix_length(), and user.

Referenced by conninfo_uri_parse().

◆ conninfo_uri_parse_params()

static bool conninfo_uri_parse_params ( char *  params,
PQconninfoOption connOptions,
PQExpBuffer  errorMessage 
)
static

Definition at line 6606 of file fe-connect.c.

6609 {
6610  while (*params)
6611  {
6612  char *keyword = params;
6613  char *value = NULL;
6614  char *p = params;
6615  bool malloced = false;
6616  int oldmsglen;
6617 
6618  /*
6619  * Scan the params string for '=' and '&', marking the end of keyword
6620  * and value respectively.
6621  */
6622  for (;;)
6623  {
6624  if (*p == '=')
6625  {
6626  /* Was there '=' already? */
6627  if (value != NULL)
6628  {
6629  libpq_append_error(errorMessage,
6630  "extra key/value separator \"=\" in URI query parameter: \"%s\"",
6631  keyword);
6632  return false;
6633  }
6634  /* Cut off keyword, advance to value */
6635  *p++ = '\0';
6636  value = p;
6637  }
6638  else if (*p == '&' || *p == '\0')
6639  {
6640  /*
6641  * If not at the end, cut off value and advance; leave p
6642  * pointing to start of the next parameter, if any.
6643  */
6644  if (*p != '\0')
6645  *p++ = '\0';
6646  /* Was there '=' at all? */
6647  if (value == NULL)
6648  {
6649  libpq_append_error(errorMessage,
6650  "missing key/value separator \"=\" in URI query parameter: \"%s\"",
6651  keyword);
6652  return false;
6653  }
6654  /* Got keyword and value, go process them. */
6655  break;
6656  }
6657  else
6658  ++p; /* Advance over all other bytes. */
6659  }
6660 
6661  keyword = conninfo_uri_decode(keyword, errorMessage);
6662  if (keyword == NULL)
6663  {
6664  /* conninfo_uri_decode already set an error message */
6665  return false;
6666  }
6667  value = conninfo_uri_decode(value, errorMessage);
6668  if (value == NULL)
6669  {
6670  /* conninfo_uri_decode already set an error message */
6671  free(keyword);
6672  return false;
6673  }
6674  malloced = true;
6675 
6676  /*
6677  * Special keyword handling for improved JDBC compatibility.
6678  */
6679  if (strcmp(keyword, "ssl") == 0 &&
6680  strcmp(value, "true") == 0)
6681  {
6682  free(keyword);
6683  free(value);
6684  malloced = false;
6685 
6686  keyword = "sslmode";
6687  value = "require";
6688  }
6689 
6690  /*
6691  * Store the value if the corresponding option exists; ignore
6692  * otherwise. At this point both keyword and value are not
6693  * URI-encoded.
6694  */
6695  oldmsglen = errorMessage->len;
6696  if (!conninfo_storeval(connOptions, keyword, value,
6697  errorMessage, true, false))
6698  {
6699  /* Insert generic message if conninfo_storeval didn't give one. */
6700  if (errorMessage->len == oldmsglen)
6701  libpq_append_error(errorMessage,
6702  "invalid URI query parameter: \"%s\"",
6703  keyword);
6704  /* And fail. */
6705  if (malloced)
6706  {
6707  free(keyword);
6708  free(value);
6709  }
6710  return false;
6711  }
6712 
6713  if (malloced)
6714  {
6715  free(keyword);
6716  free(value);
6717  }
6718 
6719  /* Proceed to next key=value pair, if any */
6720  params = p;
6721  }
6722 
6723  return true;
6724 }

References conninfo_storeval(), conninfo_uri_decode(), free, PQExpBufferData::len, libpq_append_error(), and value.

Referenced by conninfo_uri_parse_options().

◆ count_comma_separated_elems()

static int count_comma_separated_elems ( const char *  input)
static

Definition at line 1034 of file fe-connect.c.

1035 {
1036  int n;
1037 
1038  n = 1;
1039  for (; *input != '\0'; input++)
1040  {
1041  if (*input == ',')
1042  n++;
1043  }
1044 
1045  return n;
1046 }
FILE * input

References input.

Referenced by pqConnectOptions2().

◆ default_threadlock()

static void default_threadlock ( int  acquire)
static

Definition at line 7733 of file fe-connect.c.

7734 {
7735  static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
7736 
7737  if (acquire)
7738  {
7739  if (pthread_mutex_lock(&singlethread_lock))
7740  Assert(false);
7741  }
7742  else
7743  {
7744  if (pthread_mutex_unlock(&singlethread_lock))
7745  Assert(false);
7746  }
7747 }
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:60
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:42
#define PTHREAD_MUTEX_INITIALIZER
Definition: pthread-win32.h:16

References Assert, PTHREAD_MUTEX_INITIALIZER, pthread_mutex_lock(), and pthread_mutex_unlock().

Referenced by PQregisterThreadLock().

◆ defaultNoticeProcessor()

static void defaultNoticeProcessor ( void *  arg,
const char *  message 
)
static

Definition at line 7364 of file fe-connect.c.

7365 {
7366  (void) arg; /* not used */
7367  /* Note: we expect the supplied string to end with a newline already. */
7368  fprintf(stderr, "%s", message);
7369 }
void * arg
#define fprintf
Definition: port.h:242

References arg, and fprintf.

Referenced by pqMakeEmptyPGconn().

◆ defaultNoticeReceiver()

static void defaultNoticeReceiver ( void *  arg,
const PGresult res 
)
static

Definition at line 7349 of file fe-connect.c.

7350 {
7351  (void) arg; /* not used */
7352  if (res->noticeHooks.noticeProc != NULL)
7355 }
char * PQresultErrorMessage(const PGresult *res)
Definition: fe-exec.c:3427
void * noticeProcArg
Definition: libpq-int.h:158
PQnoticeProcessor noticeProc
Definition: libpq-int.h:157
PGNoticeHooks noticeHooks
Definition: libpq-int.h:189

References arg, pg_result::noticeHooks, PGNoticeHooks::noticeProc, PGNoticeHooks::noticeProcArg, PQresultErrorMessage(), and res.

Referenced by pqMakeEmptyPGconn().

◆ emitHostIdentityInfo()

static void emitHostIdentityInfo ( PGconn conn,
const char *  host_addr 
)
static

Definition at line 2075 of file fe-connect.c.

2076 {
2077  if (conn->raddr.addr.ss_family == AF_UNIX)
2078  {
2079  char service[NI_MAXHOST];
2080 
2082  NULL, 0,
2083  service, sizeof(service),
2084  NI_NUMERICSERV);
2086  libpq_gettext("connection to server on socket \"%s\" failed: "),
2087  service);
2088  }
2089  else
2090  {
2091  const char *displayed_host;
2092  const char *displayed_port;
2093 
2094  /* To which host and port were we actually connecting? */
2096  displayed_host = conn->connhost[conn->whichhost].hostaddr;
2097  else
2098  displayed_host = conn->connhost[conn->whichhost].host;
2099  displayed_port = conn->connhost[conn->whichhost].port;
2100  if (displayed_port == NULL || displayed_port[0] == '\0')
2101  displayed_port = DEF_PGPORT_STR;
2102 
2103  /*
2104  * If the user did not supply an IP address using 'hostaddr', and
2105  * 'host' was missing or does not match our lookup, display the
2106  * looked-up IP address.
2107  */
2109  host_addr[0] &&
2110  strcmp(displayed_host, host_addr) != 0)
2112  libpq_gettext("connection to server at \"%s\" (%s), port %s failed: "),
2113  displayed_host, host_addr,
2114  displayed_port);
2115  else
2117  libpq_gettext("connection to server at \"%s\", port %s failed: "),
2118  displayed_host,
2119  displayed_port);
2120  }
2121 }
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
#define libpq_gettext(x)
Definition: libpq-int.h:913
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:317
socklen_t salen
Definition: pqcomm.h:33
char * host
Definition: libpq-int.h:353
char * port
Definition: libpq-int.h:355
char * hostaddr
Definition: libpq-int.h:354
pg_conn_host_type type
Definition: libpq-int.h:352
int whichhost
Definition: libpq-int.h:457
pg_conn_host * connhost
Definition: libpq-int.h:458

References SockAddr::addr, appendPQExpBuffer(), CHT_HOST_ADDRESS, conn, pg_conn::connhost, pg_conn::errorMessage, pg_conn_host::host, pg_conn_host::hostaddr, libpq_gettext, pg_getnameinfo_all(), pg_conn_host::port, pg_conn::raddr, SockAddr::salen, pg_conn_host::type, and pg_conn::whichhost.

Referenced by PQconnectPoll().

◆ fillPGconn()

static bool fillPGconn ( PGconn conn,
PQconninfoOption connOptions 
)
static

Definition at line 918 of file fe-connect.c.

919 {
921 
922  for (option = PQconninfoOptions; option->keyword; option++)
923  {
924  if (option->connofs >= 0)
925  {
926  const char *tmp = conninfo_getval(connOptions, option->keyword);
927 
928  if (tmp)
929  {
930  char **connmember = (char **) ((char *) conn + option->connofs);
931 
932  free(*connmember);
933  *connmember = strdup(tmp);
934  if (*connmember == NULL)
935  {
936  libpq_append_conn_error(conn, "out of memory");
937  return false;
938  }
939  }
940  }
941  }
942 
943  return true;
944 }
static const char * conninfo_getval(PQconninfoOption *connOptions, const char *keyword)
Definition: fe-connect.c:6828

References conn, conninfo_getval(), free, libpq_append_conn_error(), and PQconninfoOptions.

Referenced by connectOptions1(), and PQconnectStartParams().

◆ freePGconn()

static void freePGconn ( PGconn conn)
static

Definition at line 4624 of file fe-connect.c.

4625 {
4626  /* let any event procs clean up their state data */
4627  for (int i = 0; i < conn->nEvents; i++)
4628  {
4629  PGEventConnDestroy evt;
4630 
4631  evt.conn = conn;
4632  (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
4633  conn->events[i].passThrough);
4634  free(conn->events[i].name);
4635  }
4636 
4639 
4641  free(conn->events);
4642  free(conn->pghost);
4643  free(conn->pghostaddr);
4644  free(conn->pgport);
4647  free(conn->pgoptions);
4648  free(conn->appname);
4649  free(conn->fbappname);
4650  free(conn->dbName);
4651  free(conn->replication);
4652  free(conn->pguser);
4653  if (conn->pgpass)
4654  {
4655  explicit_bzero(conn->pgpass, strlen(conn->pgpass));
4656  free(conn->pgpass);
4657  }
4658  free(conn->pgpassfile);
4660  free(conn->keepalives);
4664  free(conn->sslmode);
4666  free(conn->sslcert);
4667  free(conn->sslkey);
4668  if (conn->sslpassword)
4669  {
4671  free(conn->sslpassword);
4672  }
4673  free(conn->sslcertmode);
4674  free(conn->sslrootcert);
4675  free(conn->sslcrl);
4676  free(conn->sslcrldir);
4678  free(conn->sslsni);
4679  free(conn->requirepeer);
4683  free(conn->gssencmode);
4684  free(conn->krbsrvname);
4685  free(conn->gsslib);
4687  free(conn->connip);
4688  /* Note that conn->Pfdebug is not ours to close or free */
4690  free(conn->inBuffer);
4691  free(conn->outBuffer);
4692  free(conn->rowBuf);
4697 
4698  free(conn);
4699 }
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4774
void pqReleaseConnHosts(PGconn *conn)
Definition: fe-connect.c:4706
@ PGEVT_CONNDESTROY
Definition: libpq-events.h:31
void explicit_bzero(void *buf, size_t len)
void * passThrough
Definition: libpq-int.h:165
char * name
Definition: libpq-int.h:164
PGEventProc proc
Definition: libpq-int.h:163
char * replication
Definition: libpq-int.h:385
char * write_err_msg
Definition: libpq-int.h:487
char * sslrootcert
Definition: libpq-int.h:405
PGdataValue * rowBuf
Definition: libpq-int.h:541
char * sslnegotiation
Definition: libpq-int.h:398
char * sslcompression
Definition: libpq-int.h:400
char * require_auth
Definition: libpq-int.h:418
char * inBuffer
Definition: libpq-int.h:524
char * channel_binding
Definition: libpq-int.h:389
char * sslcrldir
Definition: libpq-int.h:407
char * gssdelegation
Definition: libpq-int.h:414
char * pgoptions
Definition: libpq-int.h:381
char * sslcrl
Definition: libpq-int.h:406
char * pghost
Definition: libpq-int.h:368
char * ssl_max_protocol_version
Definition: libpq-int.h:416
char * pgpass
Definition: libpq-int.h:387
char * dbName
Definition: libpq-int.h:384
char * fbappname
Definition: libpq-int.h:383
char * sslcert
Definition: libpq-int.h:402
char * sslcertmode
Definition: libpq-int.h:404
char * target_session_attrs
Definition: libpq-int.h:417
char * sslpassword
Definition: libpq-int.h:403
PQExpBufferData workBuffer
Definition: libpq-int.h:639
char * keepalives_idle
Definition: libpq-int.h:392
char * connip
Definition: libpq-int.h:459
char * load_balance_hosts
Definition: libpq-int.h:419
char * pguser
Definition: libpq-int.h:386
char * keepalives
Definition: libpq-int.h:391
char * client_encoding_initial
Definition: libpq-int.h:380
char * keepalives_interval
Definition: libpq-int.h:393
char * appname
Definition: libpq-int.h:382
char * sslmode
Definition: libpq-int.h:397
char * pgtcp_user_timeout
Definition: libpq-int.h:379
char * ssl_min_protocol_version
Definition: libpq-int.h:415
char * gssencmode
Definition: libpq-int.h:410
int nEvents
Definition: libpq-int.h:434
char * pghostaddr
Definition: libpq-int.h:372
char * sslkey
Definition: libpq-int.h:401
char * pgpassfile
Definition: libpq-int.h:388
char * connect_timeout
Definition: libpq-int.h:378
char * krbsrvname
Definition: libpq-int.h:411
char * gsslib
Definition: libpq-int.h:412
char * pgport
Definition: libpq-int.h:376
char * keepalives_count
Definition: libpq-int.h:395
char * requirepeer
Definition: libpq-int.h:409
char * sslsni
Definition: libpq-int.h:408
PGEvent * events
Definition: libpq-int.h:433
char * outBuffer
Definition: libpq-int.h:531

References pg_conn::appname, pg_conn::channel_binding, pg_conn::client_encoding_initial, conn, PGEventConnDestroy::conn, pg_conn::connect_timeout, pg_conn::connip, pg_conn::dbName, pg_conn::errorMessage, pg_conn::events, explicit_bzero(), pg_conn::fbappname, free, pg_conn::gssdelegation, pg_conn::gssencmode, pg_conn::gsslib, i, pg_conn::inBuffer, pg_conn::keepalives, pg_conn::keepalives_count, pg_conn::keepalives_idle, pg_conn::keepalives_interval, pg_conn::krbsrvname, pg_conn::load_balance_hosts, PGEvent::name, pg_conn::nEvents, pg_conn::outBuffer, PGEvent::passThrough, PGEVT_CONNDESTROY, pg_conn::pghost, pg_conn::pghostaddr, pg_conn::pgoptions, pg_conn::pgpass, pg_conn::pgpassfile, pg_conn::pgport, pg_conn::pgtcp_user_timeout, pg_conn::pguser, pqReleaseConnHosts(), PGEvent::proc, release_conn_addrinfo(), pg_conn::replication, pg_conn::require_auth, pg_conn::requirepeer, pg_conn::rowBuf, pg_conn::ssl_max_protocol_version, pg_conn::ssl_min_protocol_version, pg_conn::sslcert, pg_conn::sslcertmode, pg_conn::sslcompression, pg_conn::sslcrl, pg_conn::sslcrldir, pg_conn::sslkey, pg_conn::sslmode, pg_conn::sslnegotiation, pg_conn::sslpassword, pg_conn::sslrootcert, pg_conn::sslsni, pg_conn::target_session_attrs, termPQExpBuffer(), pg_conn::workBuffer, and pg_conn::write_err_msg.

Referenced by PQfinish(), and pqMakeEmptyPGconn().

◆ get_hexdigit()

static bool get_hexdigit ( char  digit,
int *  value 
)
static

Definition at line 6807 of file fe-connect.c.

6808 {
6809  if ('0' <= digit && digit <= '9')
6810  *value = digit - '0';
6811  else if ('A' <= digit && digit <= 'F')
6812  *value = digit - 'A' + 10;
6813  else if ('a' <= digit && digit <= 'f')
6814  *value = digit - 'a' + 10;
6815  else
6816  return false;
6817 
6818  return true;
6819 }

References value.

Referenced by conninfo_uri_decode().

◆ getHostaddr()

static void getHostaddr ( PGconn conn,
char *  host_addr,
int  host_addr_len 
)
static

Definition at line 2042 of file fe-connect.c.

2043 {
2044  struct sockaddr_storage *addr = &conn->raddr.addr;
2045 
2046  if (addr->ss_family == AF_INET)
2047  {
2048  if (pg_inet_net_ntop(AF_INET,
2049  &((struct sockaddr_in *) addr)->sin_addr.s_addr,
2050  32,
2051  host_addr, host_addr_len) == NULL)
2052  host_addr[0] = '\0';
2053  }
2054  else if (addr->ss_family == AF_INET6)
2055  {
2056  if (pg_inet_net_ntop(AF_INET6,
2057  &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
2058  128,
2059  host_addr, host_addr_len) == NULL)
2060  host_addr[0] = '\0';
2061  }
2062  else
2063  host_addr[0] = '\0';
2064 }
char * pg_inet_net_ntop(int af, const void *src, int bits, char *dst, size_t size)
Definition: inet_net_ntop.c:77

References SockAddr::addr, conn, pg_inet_net_ntop(), and pg_conn::raddr.

Referenced by PQconnectPoll().

◆ init_allowed_encryption_methods()

static bool init_allowed_encryption_methods ( PGconn conn)
static

Definition at line 4259 of file fe-connect.c.

4260 {
4261  if (conn->raddr.addr.ss_family == AF_UNIX)
4262  {
4263  /* Don't request SSL or GSSAPI over Unix sockets */
4265 
4266  /*
4267  * XXX: we probably should not do this. sslmode=require works
4268  * differently
4269  */
4270  if (conn->gssencmode[0] == 'r')
4271  {
4273  "GSSAPI encryption required but it is not supported over a local socket)");
4276  return false;
4277  }
4278 
4281  return true;
4282  }
4283 
4284  /* initialize based on sslmode and gssencmode */
4286 
4287 #ifdef USE_SSL
4288  /* sslmode anything but 'disable', and GSSAPI not required */
4289  if (conn->sslmode[0] != 'd' && conn->gssencmode[0] != 'r')
4290  {
4291  if (conn->sslnegotiation[0] == 'p')
4293  else if (conn->sslnegotiation[0] == 'd')
4295  else if (conn->sslnegotiation[0] == 'r')
4297  }
4298 #endif
4299 
4300 #ifdef ENABLE_GSS
4301  if (conn->gssencmode[0] != 'd')
4303 #endif
4304 
4305  if ((conn->sslmode[0] == 'd' || conn->sslmode[0] == 'p' || conn->sslmode[0] == 'a') &&
4306  (conn->gssencmode[0] == 'd' || conn->gssencmode[0] == 'p'))
4307  {
4309  }
4310 
4311  return select_next_encryption_method(conn, false);
4312 }
#define ENC_PLAINTEXT
Definition: libpq-int.h:236
#define ENC_GSSAPI
Definition: libpq-int.h:237
#define ENC_ERROR
Definition: libpq-int.h:235

References SockAddr::addr, pg_conn::allowed_enc_methods, conn, pg_conn::current_enc_method, ENC_DIRECT_SSL, ENC_ERROR, ENC_GSSAPI, ENC_NEGOTIATED_SSL, ENC_PLAINTEXT, pg_conn::gssencmode, libpq_append_conn_error(), pg_conn::raddr, select_next_encryption_method(), pg_conn::sslmode, and pg_conn::sslnegotiation.

Referenced by PQconnectPoll().

◆ internal_ping()

static PGPing internal_ping ( PGconn conn)
static

Definition at line 4461 of file fe-connect.c.

4462 {
4463  /* Say "no attempt" if we never got to PQconnectPoll */
4464  if (!conn || !conn->options_valid)
4465  return PQPING_NO_ATTEMPT;
4466 
4467  /* Attempt to complete the connection */
4468  if (conn->status != CONNECTION_BAD)
4469  (void) pqConnectDBComplete(conn);
4470 
4471  /* Definitely OK if we succeeded */
4472  if (conn->status != CONNECTION_BAD)
4473  return PQPING_OK;
4474 
4475  /*
4476  * Here begins the interesting part of "ping": determine the cause of the
4477  * failure in sufficient detail to decide what to return. We do not want
4478  * to report that the server is not up just because we didn't have a valid
4479  * password, for example. In fact, any sort of authentication request
4480  * implies the server is up. (We need this check since the libpq side of
4481  * things might have pulled the plug on the connection before getting an
4482  * error as such from the postmaster.)
4483  */
4484  if (conn->auth_req_received)
4485  return PQPING_OK;
4486 
4487  /*
4488  * If we failed to get any ERROR response from the postmaster, report
4489  * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
4490  * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
4491  * out of support. Another corner case where the server could return a
4492  * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
4493  * isn't totally unreasonable for that anyway. We expect that every other
4494  * failure case in a modern server will produce a report with a SQLSTATE.
4495  *
4496  * NOTE: whenever we get around to making libpq generate SQLSTATEs for
4497  * client-side errors, we should either not store those into
4498  * last_sqlstate, or add an extra flag so we can tell client-side errors
4499  * apart from server-side ones.
4500  */
4501  if (strlen(conn->last_sqlstate) != 5)
4502  return PQPING_NO_RESPONSE;
4503 
4504  /*
4505  * Report PQPING_REJECT if server says it's not accepting connections.
4506  */
4507  if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
4508  return PQPING_REJECT;
4509 
4510  /*
4511  * Any other SQLSTATE can be taken to indicate that the server is up.
4512  * Presumably it didn't like our username, password, or database name; or
4513  * perhaps it had some transient failure, but that should not be taken as
4514  * meaning "it's down".
4515  */
4516  return PQPING_OK;
4517 }
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:91
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2452
@ PQPING_OK
Definition: libpq-fe.h:151
@ PQPING_REJECT
Definition: libpq-fe.h:152
@ PQPING_NO_RESPONSE
Definition: libpq-fe.h:153
@ PQPING_NO_ATTEMPT
Definition: libpq-fe.h:154
bool auth_req_received
Definition: libpq-int.h:481
char last_sqlstate[6]
Definition: libpq-int.h:441
bool options_valid
Definition: libpq-int.h:442

References pg_conn::auth_req_received, conn, CONNECTION_BAD, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::last_sqlstate, pg_conn::options_valid, pqConnectDBComplete(), PQPING_NO_ATTEMPT, PQPING_NO_RESPONSE, PQPING_OK, PQPING_REJECT, and pg_conn::status.

Referenced by PQping(), and PQpingParams().

◆ libpq_prng_init()

static void libpq_prng_init ( PGconn conn)
static

Definition at line 1093 of file fe-connect.c.

1094 {
1095  uint64 rseed;
1096  struct timeval tval = {0};
1097 
1099  return;
1100 
1101  gettimeofday(&tval, NULL);
1102 
1103  rseed = ((uintptr_t) conn) ^
1104  ((uint64) getpid()) ^
1105  ((uint64) tval.tv_usec) ^
1106  ((uint64) tval.tv_sec);
1107 
1108  pg_prng_seed(&conn->prng_state, rseed);
1109 }
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
#define pg_prng_strong_seed(state)
Definition: pg_prng.h:46
pg_prng_state prng_state
Definition: libpq-int.h:520
int gettimeofday(struct timeval *tp, void *tzp)

References conn, gettimeofday(), pg_prng_seed(), pg_prng_strong_seed, and pg_conn::prng_state.

Referenced by pqConnectOptions2().

◆ parse_comma_separated_list()

static char* parse_comma_separated_list ( char **  startptr,
bool more 
)
static

Definition at line 1058 of file fe-connect.c.

1059 {
1060  char *p;
1061  char *s = *startptr;
1062  char *e;
1063  int len;
1064 
1065  /*
1066  * Search for the end of the current element; a comma or end-of-string
1067  * acts as a terminator.
1068  */
1069  e = s;
1070  while (*e != '\0' && *e != ',')
1071  ++e;
1072  *more = (*e == ',');
1073 
1074  len = e - s;
1075  p = (char *) malloc(sizeof(char) * (len + 1));
1076  if (p)
1077  {
1078  memcpy(p, s, len);
1079  p[len] = '\0';
1080  }
1081  *startptr = e + 1;
1082 
1083  return p;
1084 }
const void size_t len
e
Definition: preproc-init.c:82

References len, and malloc.

Referenced by pqConnectOptions2().

◆ parse_connection_string()

static PQconninfoOption * parse_connection_string ( const char *  connstr,
PQExpBuffer  errorMessage,
bool  use_defaults 
)
static

Definition at line 5789 of file fe-connect.c.

5791 {
5792  /* Parse as URI if connection string matches URI prefix */
5793  if (uri_prefix_length(connstr) != 0)
5794  return conninfo_uri_parse(connstr, errorMessage, use_defaults);
5795 
5796  /* Parse as default otherwise */
5797  return conninfo_parse(connstr, errorMessage, use_defaults);
5798 }
static PQconninfoOption * conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:6312
static PQconninfoOption * conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5843
static char * connstr
Definition: pg_dumpall.c:88

References conninfo_parse(), conninfo_uri_parse(), connstr, and uri_prefix_length().

Referenced by connectOptions1(), conninfo_array_parse(), and PQconninfoParse().

◆ parseServiceFile()

static int parseServiceFile ( const char *  serviceFile,
const char *  service,
PQconninfoOption options,
PQExpBuffer  errorMessage,
bool group_found 
)
static

Definition at line 5550 of file fe-connect.c.

5555 {
5556  int result = 0,
5557  linenr = 0,
5558  i;
5559  FILE *f;
5560  char *line;
5561  char buf[1024];
5562 
5563  *group_found = false;
5564 
5565  f = fopen(serviceFile, "r");
5566  if (f == NULL)
5567  {
5568  libpq_append_error(errorMessage, "service file \"%s\" not found", serviceFile);
5569  return 1;
5570  }
5571 
5572  while ((line = fgets(buf, sizeof(buf), f)) != NULL)
5573  {
5574  int len;
5575 
5576  linenr++;
5577 
5578  if (strlen(line) >= sizeof(buf) - 1)
5579  {
5580  libpq_append_error(errorMessage,
5581  "line %d too long in service file \"%s\"",
5582  linenr,
5583  serviceFile);
5584  result = 2;
5585  goto exit;
5586  }
5587 
5588  /* ignore whitespace at end of line, especially the newline */
5589  len = strlen(line);
5590  while (len > 0 && isspace((unsigned char) line[len - 1]))
5591  line[--len] = '\0';
5592 
5593  /* ignore leading whitespace too */
5594  while (*line && isspace((unsigned char) line[0]))
5595  line++;
5596 
5597  /* ignore comments and empty lines */
5598  if (line[0] == '\0' || line[0] == '#')
5599  continue;
5600 
5601  /* Check for right groupname */
5602  if (line[0] == '[')
5603  {
5604  if (*group_found)
5605  {
5606  /* end of desired group reached; return success */
5607  goto exit;
5608  }
5609 
5610  if (strncmp(line + 1, service, strlen(service)) == 0 &&
5611  line[strlen(service) + 1] == ']')
5612  *group_found = true;
5613  else
5614  *group_found = false;
5615  }
5616  else
5617  {
5618  if (*group_found)
5619  {
5620  /*
5621  * Finally, we are in the right group and can parse the line
5622  */
5623  char *key,
5624  *val;
5625  bool found_keyword;
5626 
5627 #ifdef USE_LDAP
5628  if (strncmp(line, "ldap", 4) == 0)
5629  {
5630  int rc = ldapServiceLookup(line, options, errorMessage);
5631 
5632  /* if rc = 2, go on reading for fallback */
5633  switch (rc)
5634  {
5635  case 0:
5636  goto exit;
5637  case 1:
5638  case 3:
5639  result = 3;
5640  goto exit;
5641  case 2:
5642  continue;
5643  }
5644  }
5645 #endif
5646 
5647  key = line;
5648  val = strchr(line, '=');
5649  if (val == NULL)
5650  {
5651  libpq_append_error(errorMessage,
5652  "syntax error in service file \"%s\", line %d",
5653  serviceFile,
5654  linenr);
5655  result = 3;
5656  goto exit;
5657  }
5658  *val++ = '\0';
5659 
5660  if (strcmp(key, "service") == 0)
5661  {
5662  libpq_append_error(errorMessage,
5663  "nested service specifications not supported in service file \"%s\", line %d",
5664  serviceFile,
5665  linenr);
5666  result = 3;
5667  goto exit;
5668  }
5669 
5670  /*
5671  * Set the parameter --- but don't override any previous
5672  * explicit setting.
5673  */
5674  found_keyword = false;
5675  for (i = 0; options[i].keyword; i++)
5676  {
5677  if (strcmp(options[i].keyword, key) == 0)
5678  {
5679  if (options[i].val == NULL)
5680  options[i].val = strdup(val);
5681  if (!options[i].val)
5682  {
5683  libpq_append_error(errorMessage, "out of memory");
5684  result = 3;
5685  goto exit;
5686  }
5687  found_keyword = true;
5688  break;
5689  }
5690  }
5691 
5692  if (!found_keyword)
5693  {
5694  libpq_append_error(errorMessage,
5695  "syntax error in service file \"%s\", line %d",
5696  serviceFile,
5697  linenr);
5698  result = 3;
5699  goto exit;
5700  }
5701  }
5702  }
5703  }
5704 
5705 exit:
5706  fclose(f);
5707 
5708  return result;
5709 }
exit(1)

References buf, exit(), i, sort-test::key, len, libpq_append_error(), and val.

Referenced by parseServiceInfo().

◆ parseServiceInfo()

static int parseServiceInfo ( PQconninfoOption options,
PQExpBuffer  errorMessage 
)
static

Definition at line 5482 of file fe-connect.c.

5483 {
5484  const char *service = conninfo_getval(options, "service");
5485  char serviceFile[MAXPGPATH];
5486  char *env;
5487  bool group_found = false;
5488  int status;
5489  struct stat stat_buf;
5490 
5491  /*
5492  * We have to special-case the environment variable PGSERVICE here, since
5493  * this is and should be called before inserting environment defaults for
5494  * other connection options.
5495  */
5496  if (service == NULL)
5497  service = getenv("PGSERVICE");
5498 
5499  /* If no service name given, nothing to do */
5500  if (service == NULL)
5501  return 0;
5502 
5503  /*
5504  * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
5505  * exists).
5506  */
5507  if ((env = getenv("PGSERVICEFILE")) != NULL)
5508  strlcpy(serviceFile, env, sizeof(serviceFile));
5509  else
5510  {
5511  char homedir[MAXPGPATH];
5512 
5513  if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5514  goto next_file;
5515  snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5516  if (stat(serviceFile, &stat_buf) != 0)
5517  goto next_file;
5518  }
5519 
5520  status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5521  if (group_found || status != 0)
5522  return status;
5523 
5524 next_file:
5525 
5526  /*
5527  * This could be used by any application so we can't use the binary
5528  * location to find our config files.
5529  */
5530  snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5531  getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5532  if (stat(serviceFile, &stat_buf) != 0)
5533  goto last_file;
5534 
5535  status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5536  if (status != 0)
5537  return status;
5538 
5539 last_file:
5540  if (!group_found)
5541  {
5542  libpq_append_error(errorMessage, "definition of service \"%s\" not found", service);
5543  return 3;
5544  }
5545 
5546  return 0;
5547 }
static int parseServiceFile(const char *serviceFile, const char *service, PQconninfoOption *options, PQExpBuffer errorMessage, bool *group_found)
Definition: fe-connect.c:5550
bool pqGetHomeDirectory(char *buf, int bufsize)
Definition: fe-connect.c:7655
#define MAXPGPATH
#define snprintf
Definition: port.h:238
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define stat
Definition: win32_port.h:284

References conninfo_getval(), libpq_append_error(), MAXPGPATH, parseServiceFile(), pqGetHomeDirectory(), snprintf, stat, and strlcpy().

Referenced by conninfo_add_defaults().

◆ passwordFromFile()

static char * passwordFromFile ( const char *  hostname,
const char *  port,
const char *  dbname,
const char *  username,
const char *  pgpassfile 
)
static

Definition at line 7413 of file fe-connect.c.

7415 {
7416  FILE *fp;
7417  struct stat stat_buf;
7419 
7420  if (dbname == NULL || dbname[0] == '\0')
7421  return NULL;
7422 
7423  if (username == NULL || username[0] == '\0')
7424  return NULL;
7425 
7426  /* 'localhost' matches pghost of '' or the default socket directory */
7427  if (hostname == NULL || hostname[0] == '\0')
7429  else if (is_unixsock_path(hostname))
7430 
7431  /*
7432  * We should probably use canonicalize_path(), but then we have to
7433  * bring path.c into libpq, and it doesn't seem worth it.
7434  */
7435  if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
7437 
7438  if (port == NULL || port[0] == '\0')
7439  port = DEF_PGPORT_STR;
7440 
7441  /* If password file cannot be opened, ignore it. */
7442  if (stat(pgpassfile, &stat_buf) != 0)
7443  return NULL;
7444 
7445 #ifndef WIN32
7446  if (!S_ISREG(stat_buf.st_mode))
7447  {
7448  fprintf(stderr,
7449  libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
7450  pgpassfile);
7451  return NULL;
7452  }
7453 
7454  /* If password file is insecure, alert the user and ignore it. */
7455  if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
7456  {
7457  fprintf(stderr,
7458  libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
7459  pgpassfile);
7460  return NULL;
7461  }
7462 #else
7463 
7464  /*
7465  * On Win32, the directory is protected, so we don't have to check the
7466  * file.
7467  */
7468 #endif
7469 
7470  fp = fopen(pgpassfile, "r");
7471  if (fp == NULL)
7472  return NULL;
7473 
7474  /* Use an expansible buffer to accommodate any reasonable line length */
7475  initPQExpBuffer(&buf);
7476 
7477  while (!feof(fp) && !ferror(fp))
7478  {
7479  /* Make sure there's a reasonable amount of room in the buffer */
7480  if (!enlargePQExpBuffer(&buf, 128))
7481  break;
7482 
7483  /* Read some data, appending it to what we already have */
7484  if (fgets(buf.data + buf.len, buf.maxlen - buf.len, fp) == NULL)
7485  break;
7486  buf.len += strlen(buf.data + buf.len);
7487 
7488  /* If we don't yet have a whole line, loop around to read more */
7489  if (!(buf.len > 0 && buf.data[buf.len - 1] == '\n') && !feof(fp))
7490  continue;
7491 
7492  /* ignore comments */
7493  if (buf.data[0] != '#')
7494  {
7495  char *t = buf.data;
7496  int len;
7497 
7498  /* strip trailing newline and carriage return */
7499  len = pg_strip_crlf(t);
7500 
7501  if (len > 0 &&
7502  (t = pwdfMatchesString(t, hostname)) != NULL &&
7503  (t = pwdfMatchesString(t, port)) != NULL &&
7504  (t = pwdfMatchesString(t, dbname)) != NULL &&
7505  (t = pwdfMatchesString(t, username)) != NULL)
7506  {
7507  /* Found a match. */
7508  char *ret,
7509  *p1,
7510  *p2;
7511 
7512  ret = strdup(t);
7513 
7514  fclose(fp);
7515  explicit_bzero(buf.data, buf.maxlen);
7516  termPQExpBuffer(&buf);
7517 
7518  if (!ret)
7519  {
7520  /* Out of memory. XXX: an error message would be nice. */
7521  return NULL;
7522  }
7523 
7524  /* De-escape password. */
7525  for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
7526  {
7527  if (*p1 == '\\' && p1[1] != '\0')
7528  ++p1;
7529  *p2 = *p1;
7530  }
7531  *p2 = '\0';
7532 
7533  return ret;
7534  }
7535  }
7536 
7537  /* No match, reset buffer to prepare for next line. */
7538  buf.len = 0;
7539  }
7540 
7541  fclose(fp);
7542  explicit_bzero(buf.data, buf.maxlen);
7543  termPQExpBuffer(&buf);
7544  return NULL;
7545 }
#define DefaultHost
Definition: fe-connect.c:116
static char * pwdfMatchesString(char *buf, const char *token)
Definition: fe-connect.c:7376
#define DEFAULT_PGSOCKET_DIR
static char * hostname
Definition: pg_regress.c:115
const char * username
Definition: pgbench.c:296
static bool is_unixsock_path(const char *path)
Definition: pqcomm.h:67
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:172
int pg_strip_crlf(char *str)
Definition: string.c:155
#define S_IRWXG
Definition: win32_port.h:310
#define S_IRWXO
Definition: win32_port.h:322
#define S_ISREG(m)
Definition: win32_port.h:328

References buf, dbname, DEFAULT_PGSOCKET_DIR, DefaultHost, enlargePQExpBuffer(), explicit_bzero(), fprintf, hostname, initPQExpBuffer(), is_unixsock_path(), len, libpq_gettext, p2, pg_strip_crlf(), port, pwdfMatchesString(), S_IRWXG, S_IRWXO, S_ISREG, stat::st_mode, stat, termPQExpBuffer(), and username.

Referenced by pqConnectOptions2().

◆ pgpassfileWarning()

static void pgpassfileWarning ( PGconn conn)
static

Definition at line 7553 of file fe-connect.c.

7554 {
7555  /* If it was 'invalid authorization', add pgpassfile mention */
7556  /* only works with >= 9.0 servers */
7557  if (conn->password_needed &&
7558  conn->connhost[conn->whichhost].password != NULL &&
7559  conn->result)
7560  {
7561  const char *sqlstate = PQresultErrorField(conn->result,
7563 
7564  if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
7565  libpq_append_conn_error(conn, "password retrieved from file \"%s\"",
7566  conn->pgpassfile);
7567  }
7568 }
#define ERRCODE_INVALID_PASSWORD
Definition: fe-connect.c:89
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
char * password
Definition: libpq-int.h:356
PGresult * result
Definition: libpq-int.h:554
bool password_needed
Definition: libpq-int.h:482

References conn, pg_conn::connhost, ERRCODE_INVALID_PASSWORD, libpq_append_conn_error(), pg_conn_host::password, pg_conn::password_needed, PG_DIAG_SQLSTATE, pg_conn::pgpassfile, PQresultErrorField(), pg_conn::result, and pg_conn::whichhost.

Referenced by PQconnectPoll().

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

Definition at line 7181 of file fe-connect.c.

7182 {
7183  if (!conn || conn->status != CONNECTION_OK)
7184  return 0;
7185  return conn->be_pid;
7186 }
@ CONNECTION_OK
Definition: libpq-fe.h:61
int be_pid
Definition: libpq-int.h:510

References pg_conn::be_pid, conn, CONNECTION_OK, and pg_conn::status.

Referenced by get_prompt(), libpqrcv_get_backend_pid(), main(), send_cancellable_query_impl(), and StartLogStreamer().

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ pqClosePGconn()

void pqClosePGconn ( PGconn conn)

Definition at line 4822 of file fe-connect.c.

4823 {
4824  /*
4825  * If possible, send Terminate message to close the connection politely.
4826  */
4828 
4829  /*
4830  * Must reset the blocking status so a possible reconnect will work.
4831  *
4832  * Don't call PQsetnonblocking() because it will fail if it's unable to
4833  * flush the connection.
4834  */
4835  conn->nonblocking = false;
4836 
4837  /*
4838  * Close the connection, reset all transient state, flush I/O buffers.
4839  * Note that this includes clearing conn's error state; we're no longer
4840  * interested in any failures associated with the old connection, and we
4841  * want a clean slate for any new connection attempt.
4842  */
4843  pqDropConnection(conn, true);
4844  conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
4848  pqClearAsyncResult(conn); /* deallocate result */
4850 
4851  /*
4852  * Release addrinfo, but since cancel requests never change their addrinfo
4853  * we don't do that. Otherwise we would have to rebuild it during a
4854  * PQcancelReset.
4855  */
4856  if (!conn->cancelRequest)
4858 
4859  /* Reset all state obtained from server, too */
4861 }
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:471
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4788
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:584
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:779
@ PQTRANS_IDLE
Definition: libpq-fe.h:122
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:162
@ PGASYNC_IDLE
Definition: libpq-int.h:221
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:886
PGTransactionStatusType xactStatus
Definition: libpq-int.h:440
bool cancelRequest
Definition: libpq-int.h:421
bool nonblocking
Definition: libpq-int.h:443
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:439
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:445

References pg_conn::asyncStatus, pg_conn::cancelRequest, conn, CONNECTION_BAD, pg_conn::nonblocking, PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqClearAsyncResult(), pqClearConnErrorState, pqDropConnection(), pqDropServerData(), PQTRANS_IDLE, release_conn_addrinfo(), sendTerminateConn(), pg_conn::status, and pg_conn::xactStatus.

Referenced by PQcancelReset(), PQfinish(), PQreset(), and PQresetStart().

◆ PQconndefaults()

PQconninfoOption* PQconndefaults ( void  )

Definition at line 1863 of file fe-connect.c.

1864 {
1865  PQExpBufferData errorBuf;
1866  PQconninfoOption *connOptions;
1867 
1868  /* We don't actually report any errors here, but callees want a buffer */
1869  initPQExpBuffer(&errorBuf);
1870  if (PQExpBufferDataBroken(errorBuf))
1871  return NULL; /* out of memory already :-( */
1872 
1873  connOptions = conninfo_init(&errorBuf);
1874  if (connOptions != NULL)
1875  {
1876  /* pass NULL errorBuf to ignore errors */
1877  if (!conninfo_add_defaults(connOptions, NULL))
1878  {
1879  PQconninfoFree(connOptions);
1880  connOptions = NULL;
1881  }
1882  }
1883 
1884  termPQExpBuffer(&errorBuf);
1885  return connOptions;
1886 }

References conninfo_add_defaults(), conninfo_init(), initPQExpBuffer(), PQconninfoFree(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by check_pghost_envvar(), dblink_fdw_validator(), do_connect(), get_connect_string(), GetDbnameFromConnectionOptions(), InitPgFdwOptions(), and main().

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

Definition at line 744 of file fe-connect.c.

745 {
746  PGconn *conn = PQconnectStart(conninfo);
747 
748  if (conn && conn->status != CONNECTION_BAD)
749  (void) pqConnectDBComplete(conn);
750 
751  return conn;
752 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:872

References conn, CONNECTION_BAD, pqConnectDBComplete(), PQconnectStart(), and pg_conn::status.

Referenced by connect_database(), get_db_conn(), and main().

◆ pqConnectDBComplete()

int pqConnectDBComplete ( PGconn conn)

Definition at line 2452 of file fe-connect.c.

2453 {
2455  time_t finish_time = ((time_t) -1);
2456  int timeout = 0;
2457  int last_whichhost = -2; /* certainly different from whichhost */
2458  int last_whichaddr = -2; /* certainly different from whichaddr */
2459 
2460  if (conn == NULL || conn->status == CONNECTION_BAD)
2461  return 0;
2462 
2463  /*
2464  * Set up a time limit, if connect_timeout isn't zero.
2465  */
2466  if (conn->connect_timeout != NULL)
2467  {
2468  if (!pqParseIntParam(conn->connect_timeout, &timeout, conn,
2469  "connect_timeout"))
2470  {
2471  /* mark the connection as bad to report the parsing failure */
2473  return 0;
2474  }
2475 
2476  if (timeout > 0)
2477  {
2478  /*
2479  * Rounding could cause connection to fail unexpectedly quickly;
2480  * to prevent possibly waiting hardly-at-all, insist on at least
2481  * two seconds.
2482  */
2483  if (timeout < 2)
2484  timeout = 2;
2485  }
2486  else /* negative means 0 */
2487  timeout = 0;
2488  }
2489 
2490  for (;;)
2491  {
2492  int ret = 0;
2493 
2494  /*
2495  * (Re)start the connect_timeout timer if it's active and we are
2496  * considering a different host than we were last time through. If
2497  * we've already succeeded, though, needn't recalculate.
2498  */
2499  if (flag != PGRES_POLLING_OK &&
2500  timeout > 0 &&
2501  (conn->whichhost != last_whichhost ||
2502  conn->whichaddr != last_whichaddr))
2503  {
2504  finish_time = time(NULL) + timeout;
2505  last_whichhost = conn->whichhost;
2506  last_whichaddr = conn->whichaddr;
2507  }
2508 
2509  /*
2510  * Wait, if necessary. Note that the initial state (just after
2511  * PQconnectStart) is to wait for the socket to select for writing.
2512  */
2513  switch (flag)
2514  {
2515  case PGRES_POLLING_OK:
2516  return 1; /* success! */
2517 
2518  case PGRES_POLLING_READING:
2519  ret = pqWaitTimed(1, 0, conn, finish_time);
2520  if (ret == -1)
2521  {
2522  /* hard failure, eg select() problem, aborts everything */
2524  return 0;
2525  }
2526  break;
2527 
2528  case PGRES_POLLING_WRITING:
2529  ret = pqWaitTimed(0, 1, conn, finish_time);
2530  if (ret == -1)
2531  {
2532  /* hard failure, eg select() problem, aborts everything */
2534  return 0;
2535  }
2536  break;
2537 
2538  default:
2539  /* Just in case we failed to set it in PQconnectPoll */
2541  return 0;
2542  }
2543 
2544  if (ret == 1) /* connect_timeout elapsed */
2545  {
2546  /*
2547  * Give up on current server/address, try the next one.
2548  */
2549  conn->try_next_addr = true;
2551  }
2552 
2553  /*
2554  * Now try to advance the state machine.
2555  */
2556  if (conn->cancelRequest)
2558  else
2559  flag = PQconnectPoll(conn);
2560  }
2561 }
PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn)
Definition: fe-cancel.c:207
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2591
bool pqParseIntParam(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:7682
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
Definition: fe-misc.c:991
@ CONNECTION_NEEDED
Definition: libpq-fe.h:77
PostgresPollingStatusType
Definition: libpq-fe.h:89
@ PGRES_POLLING_OK
Definition: libpq-fe.h:93
@ PGRES_POLLING_READING
Definition: libpq-fe.h:91
int whichaddr
Definition: libpq-int.h:504
bool try_next_addr
Definition: libpq-int.h:501
char * flag(int b)
Definition: test-ctype.c:33

References pg_conn::cancelRequest, conn, pg_conn::connect_timeout, CONNECTION_BAD, CONNECTION_NEEDED, flag(), PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PQcancelPoll(), PQconnectPoll(), pqParseIntParam(), pqWaitTimed(), pg_conn::status, pg_conn::try_next_addr, pg_conn::whichaddr, and pg_conn::whichhost.

Referenced by internal_ping(), PQcancelBlocking(), PQconnectdb(), PQconnectdbParams(), PQreset(), and PQsetdbLogin().

◆ PQconnectdbParams()

PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 689 of file fe-connect.c.

692 {
693  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
694 
695  if (conn && conn->status != CONNECTION_BAD)
696  (void) pqConnectDBComplete(conn);
697 
698  return conn;
699 }
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:791

References conn, CONNECTION_BAD, pqConnectDBComplete(), PQconnectStartParams(), pg_conn::status, and values.

Referenced by ConnectDatabase(), connectDatabase(), copy_connection(), doConnect(), ECPGconnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

◆ pqConnectDBStart()

int pqConnectDBStart ( PGconn conn)

Definition at line 2374 of file fe-connect.c.

2375 {
2376  if (!conn)
2377  return 0;
2378 
2379  if (!conn->options_valid)
2380  goto connect_errReturn;
2381 
2382  /*
2383  * Check for bad linking to backend-internal versions of src/common
2384  * functions (see comments in link-canary.c for the reason we need this).
2385  * Nobody but developers should see this message, so we don't bother
2386  * translating it.
2387  */
2389  {
2391  "libpq is incorrectly linked to backend functions\n");
2392  goto connect_errReturn;
2393  }
2394 
2395  /* Ensure our buffers are empty */
2396  conn->inStart = conn->inCursor = conn->inEnd = 0;
2397  conn->outCount = 0;
2398 
2399  /*
2400  * Set up to try to connect to the first host. (Setting whichhost = -1 is
2401  * a bit of a cheat, but PQconnectPoll will advance it to 0 before
2402  * anything else looks at it.)
2403  *
2404  * Cancel requests are special though, they should only try one host and
2405  * address, and these fields have already been set up in PQcancelCreate,
2406  * so leave these fields alone for cancel requests.
2407  */
2408  if (!conn->cancelRequest)
2409  {
2410  conn->whichhost = -1;
2411  conn->try_next_host = true;
2412  conn->try_next_addr = false;
2413  }
2414 
2416 
2417  /* Also reset the target_server_type state if needed */
2420 
2421  /*
2422  * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
2423  * so that it can easily be re-executed if needed again during the
2424  * asynchronous startup process. However, we must run it once here,
2425  * because callers expect a success return from this routine to mean that
2426  * we are in PGRES_POLLING_WRITING connection state.
2427  */
2429  return 1;
2430 
2431 connect_errReturn:
2432 
2433  /*
2434  * If we managed to open a socket, close it immediately rather than
2435  * waiting till PQfinish. (The application cannot have gotten the socket
2436  * from PQsocket yet, so this doesn't risk breaking anything.)
2437  */
2438  pqDropConnection(conn, true);
2440  return 0;
2441 }
@ SERVER_TYPE_PREFER_STANDBY_PASS2
Definition: libpq-int.h:250
@ SERVER_TYPE_PREFER_STANDBY
Definition: libpq-int.h:249
bool try_next_host
Definition: libpq-int.h:502
int inCursor
Definition: libpq-int.h:527
int inEnd
Definition: libpq-int.h:528
int inStart
Definition: libpq-int.h:526
PGTargetServerType target_server_type
Definition: libpq-int.h:498
int outCount
Definition: libpq-int.h:533

References appendPQExpBufferStr(), pg_conn::cancelRequest, conn, CONNECTION_BAD, CONNECTION_NEEDED, pg_conn::errorMessage, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, pg_conn::options_valid, pg_conn::outCount, pg_link_canary_is_frontend(), PGRES_POLLING_WRITING, PQconnectPoll(), pqDropConnection(), SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PREFER_STANDBY_PASS2, pg_conn::status, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, and pg_conn::whichhost.

Referenced by PQcancelStart(), PQconnectStart(), PQconnectStartParams(), PQreset(), PQresetStart(), and PQsetdbLogin().

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

Definition at line 7198 of file fe-connect.c.

7199 {
7200  char *password;
7201 
7202  if (!conn)
7203  return false;
7204  password = PQpass(conn);
7205  if (conn->password_needed &&
7206  (password == NULL || password[0] == '\0'))
7207  return true;
7208  else
7209  return false;
7210 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7009

References conn, password, pg_conn::password_needed, and PQpass().

Referenced by ConnectDatabase(), connectDatabase(), do_connect(), doConnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

◆ PQconnectionUsedGSSAPI()

int PQconnectionUsedGSSAPI ( const PGconn conn)

Definition at line 7224 of file fe-connect.c.

7225 {
7226  if (!conn)
7227  return false;
7228  if (conn->gssapi_used)
7229  return true;
7230  else
7231  return false;
7232 }
bool gssapi_used
Definition: libpq-int.h:483

References conn, and pg_conn::gssapi_used.

Referenced by dblink_security_check(), and pgfdw_security_check().

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

Definition at line 7213 of file fe-connect.c.

7214 {
7215  if (!conn)
7216  return false;
7217  if (conn->password_needed)
7218  return true;
7219  else
7220  return false;
7221 }

References conn, and pg_conn::password_needed.

Referenced by ConnectDatabase(), dblink_security_check(), libpqrcv_connect(), and pgfdw_security_check().

◆ pqConnectOptions2()

bool pqConnectOptions2 ( PGconn conn)

Definition at line 1120 of file fe-connect.c.

1121 {
1122  int i;
1123 
1124  /*
1125  * Allocate memory for details about each host to which we might possibly
1126  * try to connect. For that, count the number of elements in the hostaddr
1127  * or host options. If neither is given, assume one host.
1128  */
1129  conn->whichhost = 0;
1130  if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1132  else if (conn->pghost && conn->pghost[0] != '\0')
1134  else
1135  conn->nconnhost = 1;
1136  conn->connhost = (pg_conn_host *)
1137  calloc(conn->nconnhost, sizeof(pg_conn_host));
1138  if (conn->connhost == NULL)
1139  goto oom_error;
1140 
1141  /*
1142  * We now have one pg_conn_host structure per possible host. Fill in the
1143  * host and hostaddr fields for each, by splitting the parameter strings.
1144  */
1145  if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1146  {
1147  char *s = conn->pghostaddr;
1148  bool more = true;
1149 
1150  for (i = 0; i < conn->nconnhost && more; i++)
1151  {
1153  if (conn->connhost[i].hostaddr == NULL)
1154  goto oom_error;
1155  }
1156 
1157  /*
1158  * If hostaddr was given, the array was allocated according to the
1159  * number of elements in the hostaddr list, so it really should be the
1160  * right size.
1161  */
1162  Assert(!more);
1163  Assert(i == conn->nconnhost);
1164  }
1165 
1166  if (conn->pghost != NULL && conn->pghost[0] != '\0')
1167  {
1168  char *s = conn->pghost;
1169  bool more = true;
1170 
1171  for (i = 0; i < conn->nconnhost && more; i++)
1172  {
1174  if (conn->connhost[i].host == NULL)
1175  goto oom_error;
1176  }
1177 
1178  /* Check for wrong number of host items. */
1179  if (more || i != conn->nconnhost)
1180  {
1182  libpq_append_conn_error(conn, "could not match %d host names to %d hostaddr values",
1184  return false;
1185  }
1186  }
1187 
1188  /*
1189  * Now, for each host slot, identify the type of address spec, and fill in
1190  * the default address if nothing was given.
1191  */
1192  for (i = 0; i < conn->nconnhost; i++)
1193  {
1194  pg_conn_host *ch = &conn->connhost[i];
1195 
1196  if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1197  ch->type = CHT_HOST_ADDRESS;
1198  else if (ch->host != NULL && ch->host[0] != '\0')
1199  {
1200  ch->type = CHT_HOST_NAME;
1201  if (is_unixsock_path(ch->host))
1202  ch->type = CHT_UNIX_SOCKET;
1203  }
1204  else
1205  {
1206  free(ch->host);
1207 
1208  /*
1209  * This bit selects the default host location. If you change
1210  * this, see also pg_regress.
1211  */
1212  if (DEFAULT_PGSOCKET_DIR[0])
1213  {
1214  ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1215  ch->type = CHT_UNIX_SOCKET;
1216  }
1217  else
1218  {
1219  ch->host = strdup(DefaultHost);
1220  ch->type = CHT_HOST_NAME;
1221  }
1222  if (ch->host == NULL)
1223  goto oom_error;
1224  }
1225  }
1226 
1227  /*
1228  * Next, work out the port number corresponding to each host name.
1229  *
1230  * Note: unlike the above for host names, this could leave the port fields
1231  * as null or empty strings. We will substitute DEF_PGPORT whenever we
1232  * read such a port field.
1233  */
1234  if (conn->pgport != NULL && conn->pgport[0] != '\0')
1235  {
1236  char *s = conn->pgport;
1237  bool more = true;
1238 
1239  for (i = 0; i < conn->nconnhost && more; i++)
1240  {
1242  if (conn->connhost[i].port == NULL)
1243  goto oom_error;
1244  }
1245 
1246  /*
1247  * If exactly one port was given, use it for every host. Otherwise,
1248  * there must be exactly as many ports as there were hosts.
1249  */
1250  if (i == 1 && !more)
1251  {
1252  for (i = 1; i < conn->nconnhost; i++)
1253  {
1254  conn->connhost[i].port = strdup(conn->connhost[0].port);
1255  if (conn->connhost[i].port == NULL)
1256  goto oom_error;
1257  }
1258  }
1259  else if (more || i != conn->nconnhost)
1260  {
1262  libpq_append_conn_error(conn, "could not match %d port numbers to %d hosts",
1264  return false;
1265  }
1266  }
1267 
1268  /*
1269  * If user name was not given, fetch it. (Most likely, the fetch will
1270  * fail, since the only way we get here is if pg_fe_getauthname() failed
1271  * during conninfo_add_defaults(). But now we want an error message.)
1272  */
1273  if (conn->pguser == NULL || conn->pguser[0] == '\0')
1274  {
1275  free(conn->pguser);
1277  if (!conn->pguser)
1278  {
1280  return false;
1281  }
1282  }
1283 
1284  /*
1285  * If database name was not given, default it to equal user name
1286  */
1287  if (conn->dbName == NULL || conn->dbName[0] == '\0')
1288  {
1289  free(conn->dbName);
1290  conn->dbName = strdup(conn->pguser);
1291  if (!conn->dbName)
1292  goto oom_error;
1293  }
1294 
1295  /*
1296  * If password was not given, try to look it up in password file. Note
1297  * that the result might be different for each host/port pair.
1298  */
1299  if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1300  {
1301  /* If password file wasn't specified, use ~/PGPASSFILE */
1302  if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1303  {
1304  char homedir[MAXPGPATH];
1305 
1306  if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1307  {
1308  free(conn->pgpassfile);
1310  if (!conn->pgpassfile)
1311  goto oom_error;
1312  snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1313  homedir, PGPASSFILE);
1314  }
1315  }
1316 
1317  if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1318  {
1319  for (i = 0; i < conn->nconnhost; i++)
1320  {
1321  /*
1322  * Try to get a password for this host from file. We use host
1323  * for the hostname search key if given, else hostaddr (at
1324  * least one of them is guaranteed nonempty by now).
1325  */
1326  const char *pwhost = conn->connhost[i].host;
1327 
1328  if (pwhost == NULL || pwhost[0] == '\0')
1329  pwhost = conn->connhost[i].hostaddr;
1330 
1331  conn->connhost[i].password =
1332  passwordFromFile(pwhost,
1333  conn->connhost[i].port,
1334  conn->dbName,
1335  conn->pguser,
1336  conn->pgpassfile);
1337  }
1338  }
1339  }
1340 
1341  /*
1342  * parse and validate require_auth option
1343  */
1344  if (conn->require_auth && conn->require_auth[0])
1345  {
1346  char *s = conn->require_auth;
1347  bool first,
1348  more;
1349  bool negated = false;
1350 
1351  /*
1352  * By default, start from an empty set of allowed options and add to
1353  * it.
1354  */
1355  conn->auth_required = true;
1357 
1358  for (first = true, more = true; more; first = false)
1359  {
1360  char *method,
1361  *part;
1362  uint32 bits;
1363 
1364  part = parse_comma_separated_list(&s, &more);
1365  if (part == NULL)
1366  goto oom_error;
1367 
1368  /*
1369  * Check for negation, e.g. '!password'. If one element is
1370  * negated, they all have to be.
1371  */
1372  method = part;
1373  if (*method == '!')
1374  {
1375  if (first)
1376  {
1377  /*
1378  * Switch to a permissive set of allowed options, and
1379  * subtract from it.
1380  */
1381  conn->auth_required = false;
1382  conn->allowed_auth_methods = -1;
1383  }
1384  else if (!negated)
1385  {
1387  libpq_append_conn_error(conn, "negative require_auth method \"%s\" cannot be mixed with non-negative methods",
1388  method);
1389 
1390  free(part);
1391  return false;
1392  }
1393 
1394  negated = true;
1395  method++;
1396  }
1397  else if (negated)
1398  {
1400  libpq_append_conn_error(conn, "require_auth method \"%s\" cannot be mixed with negative methods",
1401  method);
1402 
1403  free(part);
1404  return false;
1405  }
1406 
1407  if (strcmp(method, "password") == 0)
1408  {
1409  bits = (1 << AUTH_REQ_PASSWORD);
1410  }
1411  else if (strcmp(method, "md5") == 0)
1412  {
1413  bits = (1 << AUTH_REQ_MD5);
1414  }
1415  else if (strcmp(method, "gss") == 0)
1416  {
1417  bits = (1 << AUTH_REQ_GSS);
1418  bits |= (1 << AUTH_REQ_GSS_CONT);
1419  }
1420  else if (strcmp(method, "sspi") == 0)
1421  {
1422  bits = (1 << AUTH_REQ_SSPI);
1423  bits |= (1 << AUTH_REQ_GSS_CONT);
1424  }
1425  else if (strcmp(method, "scram-sha-256") == 0)
1426  {
1427  /* This currently assumes that SCRAM is the only SASL method. */
1428  bits = (1 << AUTH_REQ_SASL);
1429  bits |= (1 << AUTH_REQ_SASL_CONT);
1430  bits |= (1 << AUTH_REQ_SASL_FIN);
1431  }
1432  else if (strcmp(method, "none") == 0)
1433  {
1434  /*
1435  * Special case: let the user explicitly allow (or disallow)
1436  * connections where the server does not send an explicit
1437  * authentication challenge, such as "trust" and "cert" auth.
1438  */
1439  if (negated) /* "!none" */
1440  {
1441  if (conn->auth_required)
1442  goto duplicate;
1443 
1444  conn->auth_required = true;
1445  }
1446  else /* "none" */
1447  {
1448  if (!conn->auth_required)
1449  goto duplicate;
1450 
1451  conn->auth_required = false;
1452  }
1453 
1454  free(part);
1455  continue; /* avoid the bitmask manipulation below */
1456  }
1457  else
1458  {
1460  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1461  "require_auth", method);
1462 
1463  free(part);
1464  return false;
1465  }
1466 
1467  /* Update the bitmask. */
1468  if (negated)
1469  {
1470  if ((conn->allowed_auth_methods & bits) == 0)
1471  goto duplicate;
1472 
1473  conn->allowed_auth_methods &= ~bits;
1474  }
1475  else
1476  {
1477  if ((conn->allowed_auth_methods & bits) == bits)
1478  goto duplicate;
1479 
1480  conn->allowed_auth_methods |= bits;
1481  }
1482 
1483  free(part);
1484  continue;
1485 
1486  duplicate:
1487 
1488  /*
1489  * A duplicated method probably indicates a typo in a setting
1490  * where typos are extremely risky.
1491  */
1493  libpq_append_conn_error(conn, "require_auth method \"%s\" is specified more than once",
1494  part);
1495 
1496  free(part);
1497  return false;
1498  }
1499  }
1500 
1501  /*
1502  * validate channel_binding option
1503  */
1504  if (conn->channel_binding)
1505  {
1506  if (strcmp(conn->channel_binding, "disable") != 0
1507  && strcmp(conn->channel_binding, "prefer") != 0
1508  && strcmp(conn->channel_binding, "require") != 0)
1509  {
1511  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1512  "channel_binding", conn->channel_binding);
1513  return false;
1514  }
1515  }
1516  else
1517  {
1519  if (!conn->channel_binding)
1520  goto oom_error;
1521  }
1522 
1523 #ifndef USE_SSL
1524 
1525  /*
1526  * sslrootcert=system is not supported. Since setting this changes the
1527  * default sslmode, check this _before_ we validate sslmode, to avoid
1528  * confusing the user with errors for an option they may not have set.
1529  */
1530  if (conn->sslrootcert
1531  && strcmp(conn->sslrootcert, "system") == 0)
1532  {
1534  libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1535  "sslrootcert", conn->sslrootcert);
1536  return false;
1537  }
1538 #endif
1539 
1540  /*
1541  * validate sslmode option
1542  */
1543  if (conn->sslmode)
1544  {
1545  if (strcmp(conn->sslmode, "disable") != 0
1546  && strcmp(conn->sslmode, "allow") != 0
1547  && strcmp(conn->sslmode, "prefer") != 0
1548  && strcmp(conn->sslmode, "require") != 0
1549  && strcmp(conn->sslmode, "verify-ca") != 0
1550  && strcmp(conn->sslmode, "verify-full") != 0)
1551  {
1553  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1554  "sslmode", conn->sslmode);
1555  return false;
1556  }
1557 
1558 #ifndef USE_SSL
1559  switch (conn->sslmode[0])
1560  {
1561  case 'a': /* "allow" */
1562  case 'p': /* "prefer" */
1563 
1564  /*
1565  * warn user that an SSL connection will never be negotiated
1566  * since SSL was not compiled in?
1567  */
1568  break;
1569 
1570  case 'r': /* "require" */
1571  case 'v': /* "verify-ca" or "verify-full" */
1573  libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1574  "sslmode", conn->sslmode);
1575  return false;
1576  }
1577 #endif
1578  }
1579  else
1580  {
1581  conn->sslmode = strdup(DefaultSSLMode);
1582  if (!conn->sslmode)
1583  goto oom_error;
1584  }
1585 
1586  /*
1587  * validate sslnegotiation option, default is "postgres" for the postgres
1588  * style negotiated connection with an extra round trip but more options.
1589  */
1590  if (conn->sslnegotiation)
1591  {
1592  if (strcmp(conn->sslnegotiation, "postgres") != 0
1593  && strcmp(conn->sslnegotiation, "direct") != 0
1594  && strcmp(conn->sslnegotiation, "requiredirect") != 0)
1595  {
1597  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1598  "sslnegotiation", conn->sslnegotiation);
1599  return false;
1600  }
1601 
1602 #ifndef USE_SSL
1603  if (conn->sslnegotiation[0] != 'p')
1604  {
1606  libpq_append_conn_error(conn, "sslnegotiation value \"%s\" invalid when SSL support is not compiled in",
1607  conn->sslnegotiation);
1608  return false;
1609  }
1610 #endif
1611  }
1612  else
1613  {
1615  if (!conn->sslnegotiation)
1616  goto oom_error;
1617  }
1618 
1619 #ifdef USE_SSL
1620 
1621  /*
1622  * If sslrootcert=system, make sure our chosen sslmode is compatible.
1623  */
1624  if (conn->sslrootcert
1625  && strcmp(conn->sslrootcert, "system") == 0
1626  && strcmp(conn->sslmode, "verify-full") != 0)
1627  {
1629  libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslrootcert=system (use \"verify-full\")",
1630  conn->sslmode);
1631  return false;
1632  }
1633 #endif
1634 
1635  /*
1636  * Validate TLS protocol versions for ssl_min_protocol_version and
1637  * ssl_max_protocol_version.
1638  */
1640  {
1642  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1643  "ssl_min_protocol_version",
1645  return false;
1646  }
1648  {
1650  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1651  "ssl_max_protocol_version",
1653  return false;
1654  }
1655 
1656  /*
1657  * Check if the range of SSL protocols defined is correct. This is done
1658  * at this early step because this is independent of the SSL
1659  * implementation used, and this avoids unnecessary cycles with an
1660  * already-built SSL context when the connection is being established, as
1661  * it would be doomed anyway.
1662  */
1665  {
1667  libpq_append_conn_error(conn, "invalid SSL protocol version range");
1668  return false;
1669  }
1670 
1671  /*
1672  * validate sslcertmode option
1673  */
1674  if (conn->sslcertmode)
1675  {
1676  if (strcmp(conn->sslcertmode, "disable") != 0 &&
1677  strcmp(conn->sslcertmode, "allow") != 0 &&
1678  strcmp(conn->sslcertmode, "require") != 0)
1679  {
1681  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1682  "sslcertmode", conn->sslcertmode);
1683  return false;
1684  }
1685 #ifndef USE_SSL
1686  if (strcmp(conn->sslcertmode, "require") == 0)
1687  {
1689  libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1690  "sslcertmode", conn->sslcertmode);
1691  return false;
1692  }
1693 #endif
1694 #ifndef HAVE_SSL_CTX_SET_CERT_CB
1695 
1696  /*
1697  * Without a certificate callback, the current implementation can't
1698  * figure out if a certificate was actually requested, so "require" is
1699  * useless.
1700  */
1701  if (strcmp(conn->sslcertmode, "require") == 0)
1702  {
1704  libpq_append_conn_error(conn, "%s value \"%s\" is not supported (check OpenSSL version)",
1705  "sslcertmode", conn->sslcertmode);
1706  return false;
1707  }
1708 #endif
1709  }
1710  else
1711  {
1712  conn->sslcertmode = strdup(DefaultSSLCertMode);
1713  if (!conn->sslcertmode)
1714  goto oom_error;
1715  }
1716 
1717  /*
1718  * validate gssencmode option
1719  */
1720  if (conn->gssencmode)
1721  {
1722  if (strcmp(conn->gssencmode, "disable") != 0 &&
1723  strcmp(conn->gssencmode, "prefer") != 0 &&
1724  strcmp(conn->gssencmode, "require") != 0)
1725  {
1727  libpq_append_conn_error(conn, "invalid %s value: \"%s\"", "gssencmode", conn->gssencmode);
1728  return false;
1729  }
1730 #ifndef ENABLE_GSS
1731  if (strcmp(conn->gssencmode, "require") == 0)
1732  {
1734  libpq_append_conn_error(conn, "gssencmode value \"%s\" invalid when GSSAPI support is not compiled in",
1735  conn->gssencmode);
1736  return false;
1737  }
1738 #endif
1739  }
1740  else
1741  {
1742  conn->gssencmode = strdup(DefaultGSSMode);
1743  if (!conn->gssencmode)
1744  goto oom_error;
1745  }
1746 
1747  /*
1748  * validate target_session_attrs option, and set target_server_type
1749  */
1751  {
1752  if (strcmp(conn->target_session_attrs, "any") == 0)
1754  else if (strcmp(conn->target_session_attrs, "read-write") == 0)
1756  else if (strcmp(conn->target_session_attrs, "read-only") == 0)
1758  else if (strcmp(conn->target_session_attrs, "primary") == 0)
1760  else if (strcmp(conn->target_session_attrs, "standby") == 0)
1762  else if (strcmp(conn->target_session_attrs, "prefer-standby") == 0)
1764  else
1765  {
1767  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1768  "target_session_attrs",
1770  return false;
1771  }
1772  }
1773  else
1775 
1776  /*
1777  * validate load_balance_hosts option, and set load_balance_type
1778  */
1779  if (conn->load_balance_hosts)
1780  {
1781  if (strcmp(conn->load_balance_hosts, "disable") == 0)
1783  else if (strcmp(conn->load_balance_hosts, "random") == 0)
1785  else
1786  {
1788  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1789  "load_balance_hosts",
1791  return false;
1792  }
1793  }
1794  else
1796 
1798  {
1800 
1801  /*
1802  * This is the "inside-out" variant of the Fisher-Yates shuffle
1803  * algorithm. Notionally, we append each new value to the array and
1804  * then swap it with a randomly-chosen array element (possibly
1805  * including itself, else we fail to generate permutations with the
1806  * last integer last). The swap step can be optimized by combining it
1807  * with the insertion.
1808  */
1809  for (i = 1; i < conn->nconnhost; i++)
1810  {
1811  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
1812  pg_conn_host temp = conn->connhost[j];
1813 
1814  conn->connhost[j] = conn->connhost[i];
1815  conn->connhost[i] = temp;
1816  }
1817  }
1818 
1819  /*
1820  * Resolve special "auto" client_encoding from the locale
1821  */
1823  strcmp(conn->client_encoding_initial, "auto") == 0)
1824  {
1828  goto oom_error;
1829  }
1830 
1831  /*
1832  * Only if we get this far is it appropriate to try to connect. (We need a
1833  * state flag, rather than just the boolean result of this function, in
1834  * case someone tries to PQreset() the PGconn.)
1835  */
1836  conn->options_valid = true;
1837 
1838  return true;
1839 
1840 oom_error:
1842  libpq_append_conn_error(conn, "out of memory");
1843  return false;
1844 }
unsigned int uint32
Definition: c.h:506
static char * passwordFromFile(const char *hostname, const char *port, const char *dbname, const char *username, const char *pgpassfile)
Definition: fe-connect.c:7413
static bool sslVerifyProtocolRange(const char *min, const char *max)
Definition: fe-connect.c:7602
static void libpq_prng_init(PGconn *conn)
Definition: fe-connect.c:1093
#define DefaultSSLMode
Definition: fe-connect.c:129
#define DefaultGSSMode
Definition: fe-connect.c:137
static int count_comma_separated_elems(const char *input)
Definition: fe-connect.c:1034
#define DefaultChannelBinding
Definition: fe-connect.c:121
static bool sslVerifyProtocolVersion(const char *version)
Definition: fe-connect.c:7576
static char * parse_comma_separated_list(char **startptr, bool *more)
Definition: fe-connect.c:1058
#define DefaultSSLNegotiation
Definition: fe-connect.c:132
#define PGPASSFILE
Definition: fe-connect.c:75
#define DefaultSSLCertMode
Definition: fe-connect.c:130
#define calloc(a, b)
Definition: header.h:55
int j
Definition: isn.c:74
@ LOAD_BALANCE_DISABLE
Definition: libpq-int.h:256
@ LOAD_BALANCE_RANDOM
Definition: libpq-int.h:257
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:318
@ CHT_HOST_NAME
Definition: libpq-int.h:316
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:248
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:247
@ SERVER_TYPE_ANY
Definition: libpq-int.h:244
@ SERVER_TYPE_READ_WRITE
Definition: libpq-int.h:245
@ SERVER_TYPE_READ_ONLY
Definition: libpq-int.h:246
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition: pg_prng.c:144
#define pg_encoding_to_char
Definition: pg_wchar.h:630
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428
#define AUTH_REQ_SSPI
Definition: protocol.h:79
#define AUTH_REQ_SASL_CONT
Definition: protocol.h:81
#define AUTH_REQ_GSS
Definition: protocol.h:77
#define AUTH_REQ_MD5
Definition: protocol.h:75
#define AUTH_REQ_PASSWORD
Definition: protocol.h:73
#define AUTH_REQ_GSS_CONT
Definition: protocol.h:78
#define AUTH_REQ_SASL
Definition: protocol.h:80
#define AUTH_REQ_SASL_FIN
Definition: protocol.h:82
int nconnhost
Definition: libpq-int.h:456
uint32 allowed_auth_methods
Definition: libpq-int.h:491
bool auth_required
Definition: libpq-int.h:489
PGLoadBalanceType load_balance_type
Definition: libpq-int.h:499

References pg_conn::allowed_auth_methods, Assert, AUTH_REQ_GSS, AUTH_REQ_GSS_CONT, AUTH_REQ_MD5, AUTH_REQ_PASSWORD, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, AUTH_REQ_SSPI, pg_conn::auth_required, calloc, pg_conn::channel_binding, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, pg_conn::client_encoding_initial, conn, CONNECTION_BAD, pg_conn::connhost, count_comma_separated_elems(), pg_conn::dbName, DEFAULT_PGSOCKET_DIR, DefaultChannelBinding, DefaultGSSMode, DefaultHost, DefaultSSLCertMode, DefaultSSLMode, DefaultSSLNegotiation, pg_conn::errorMessage, free, pg_conn::gssencmode, pg_conn_host::host, pg_conn_host::hostaddr, i, is_unixsock_path(), j, libpq_append_conn_error(), libpq_prng_init(), LOAD_BALANCE_DISABLE, pg_conn::load_balance_hosts, LOAD_BALANCE_RANDOM, pg_conn::load_balance_type, malloc, MAXPGPATH, pg_conn::nconnhost, pg_conn::options_valid, parse_comma_separated_list(), pg_conn_host::password, passwordFromFile(), pg_encoding_to_char, pg_fe_getauthname(), pg_get_encoding_from_locale(), pg_prng_uint64_range(), pg_conn::pghost, pg_conn::pghostaddr, pg_conn::pgpass, PGPASSFILE, pg_conn::pgpassfile, pg_conn::pgport, pg_conn::pguser, pg_conn_host::port, pqGetHomeDirectory(), pg_conn::prng_state, pg_conn::require_auth, SERVER_TYPE_ANY, SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PRIMARY, SERVER_TYPE_READ_ONLY, SERVER_TYPE_READ_WRITE, SERVER_TYPE_STANDBY, snprintf, pg_conn::ssl_max_protocol_version, pg_conn::ssl_min_protocol_version, pg_conn::sslcertmode, pg_conn::sslmode, pg_conn::sslnegotiation, pg_conn::sslrootcert, sslVerifyProtocolRange(), sslVerifyProtocolVersion(), pg_conn::status, pg_conn::target_server_type, pg_conn::target_session_attrs, pg_conn_host::type, and pg_conn::whichhost.

Referenced by PQcancelCreate(), PQconnectStart(), PQconnectStartParams(), and PQsetdbLogin().

◆ PQconnectPoll()

PostgresPollingStatusType PQconnectPoll ( PGconn conn)

Definition at line 2591 of file fe-connect.c.

2592 {
2593  bool reset_connection_state_machine = false;
2594  bool need_new_connection = false;
2595  PGresult *res;
2596  char sebuf[PG_STRERROR_R_BUFLEN];
2597  int optval;
2598 
2599  if (conn == NULL)
2600  return PGRES_POLLING_FAILED;
2601 
2602  /* Get the new data */
2603  switch (conn->status)
2604  {
2605  /*
2606  * We really shouldn't have been polled in these two cases, but we
2607  * can handle it.
2608  */
2609  case CONNECTION_BAD:
2610  return PGRES_POLLING_FAILED;
2611  case CONNECTION_OK:
2612  return PGRES_POLLING_OK;
2613 
2614  /* These are reading states */
2616  case CONNECTION_AUTH_OK:
2618  case CONNECTION_CONSUME:
2620  {
2621  /* Load waiting data */
2622  int n = pqReadData(conn);
2623 
2624  if (n < 0)
2625  goto error_return;
2626  if (n == 0)
2627  return PGRES_POLLING_READING;
2628 
2629  break;
2630  }
2631 
2632  /* These are writing states, so we just proceed. */
2633  case CONNECTION_STARTED:
2634  case CONNECTION_MADE:
2635  break;
2636 
2637  /* Special cases: proceed without waiting. */
2639  case CONNECTION_NEEDED:
2642  break;
2643 
2644  default:
2645  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2646  goto error_return;
2647  }
2648 
2649 
2650 keep_going: /* We will come back to here until there is
2651  * nothing left to do. */
2652 
2653  /* Time to advance to next address, or next host if no more addresses? */
2654  if (conn->try_next_addr)
2655  {
2656  if (conn->whichaddr < conn->naddr)
2657  {
2658  conn->whichaddr++;
2659  reset_connection_state_machine = true;
2660  }
2661  else
2662  conn->try_next_host = true;
2663  conn->try_next_addr = false;
2664  }
2665 
2666  /* Time to advance to next connhost[] entry? */
2667  if (conn->try_next_host)
2668  {
2669  pg_conn_host *ch;
2670  struct addrinfo hint;
2671  struct addrinfo *addrlist;
2672  int thisport;
2673  int ret;
2674  char portstr[MAXPGPATH];
2675 
2676  if (conn->whichhost + 1 < conn->nconnhost)
2677  conn->whichhost++;
2678  else
2679  {
2680  /*
2681  * Oops, no more hosts.
2682  *
2683  * If we are trying to connect in "prefer-standby" mode, then drop
2684  * the standby requirement and start over. Don't do this for
2685  * cancel requests though, since we are certain the list of
2686  * servers won't change as the target_server_type option is not
2687  * applicable to those connections.
2688  *
2689  * Otherwise, an appropriate error message is already set up, so
2690  * we just need to set the right status.
2691  */
2693  conn->nconnhost > 0 &&
2694  !conn->cancelRequest)
2695  {
2697  conn->whichhost = 0;
2698  }
2699  else
2700  goto error_return;
2701  }
2702 
2703  /* Drop any address info for previous host */
2705 
2706  /*
2707  * Look up info for the new host. On failure, log the problem in
2708  * conn->errorMessage, then loop around to try the next host. (Note
2709  * we don't clear try_next_host until we've succeeded.)
2710  */
2711  ch = &conn->connhost[conn->whichhost];
2712 
2713  /* Initialize hint structure */
2714  MemSet(&hint, 0, sizeof(hint));
2715  hint.ai_socktype = SOCK_STREAM;
2716  hint.ai_family = AF_UNSPEC;
2717 
2718  /* Figure out the port number we're going to use. */
2719  if (ch->port == NULL || ch->port[0] == '\0')
2720  thisport = DEF_PGPORT;
2721  else
2722  {
2723  if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
2724  goto error_return;
2725 
2726  if (thisport < 1 || thisport > 65535)
2727  {
2728  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2729  goto keep_going;
2730  }
2731  }
2732  snprintf(portstr, sizeof(portstr), "%d", thisport);
2733 
2734  /* Use pg_getaddrinfo_all() to resolve the address */
2735  switch (ch->type)
2736  {
2737  case CHT_HOST_NAME:
2738  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2739  &addrlist);
2740  if (ret || !addrlist)
2741  {
2742  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2743  ch->host, gai_strerror(ret));
2744  goto keep_going;
2745  }
2746  break;
2747 
2748  case CHT_HOST_ADDRESS:
2749  hint.ai_flags = AI_NUMERICHOST;
2750  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2751  &addrlist);
2752  if (ret || !addrlist)
2753  {
2754  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2755  ch->hostaddr, gai_strerror(ret));
2756  goto keep_going;
2757  }
2758  break;
2759 
2760  case CHT_UNIX_SOCKET:
2761  hint.ai_family = AF_UNIX;
2762  UNIXSOCK_PATH(portstr, thisport, ch->host);
2763  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2764  {
2765  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2766  portstr,
2767  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2768  goto keep_going;
2769  }
2770 
2771  /*
2772  * NULL hostname tells pg_getaddrinfo_all to parse the service
2773  * name as a Unix-domain socket path.
2774  */
2775  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2776  &addrlist);
2777  if (ret || !addrlist)
2778  {
2779  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2780  portstr, gai_strerror(ret));
2781  goto keep_going;
2782  }
2783  break;
2784  }
2785 
2786  /*
2787  * Store a copy of the addrlist in private memory so we can perform
2788  * randomization for load balancing.
2789  */
2790  ret = store_conn_addrinfo(conn, addrlist);
2791  pg_freeaddrinfo_all(hint.ai_family, addrlist);
2792  if (ret)
2793  goto error_return; /* message already logged */
2794 
2795  /*
2796  * If random load balancing is enabled we shuffle the addresses.
2797  */
2799  {
2800  /*
2801  * This is the "inside-out" variant of the Fisher-Yates shuffle
2802  * algorithm. Notionally, we append each new value to the array
2803  * and then swap it with a randomly-chosen array element (possibly
2804  * including itself, else we fail to generate permutations with
2805  * the last integer last). The swap step can be optimized by
2806  * combining it with the insertion.
2807  *
2808  * We don't need to initialize conn->prng_state here, because that
2809  * already happened in pqConnectOptions2.
2810  */
2811  for (int i = 1; i < conn->naddr; i++)
2812  {
2813  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2814  AddrInfo temp = conn->addr[j];
2815 
2816  conn->addr[j] = conn->addr[i];
2817  conn->addr[i] = temp;
2818  }
2819  }
2820 
2821  reset_connection_state_machine = true;
2822  conn->try_next_host = false;
2823  }
2824 
2825  /* Reset connection state machine? */
2826  if (reset_connection_state_machine)
2827  {
2828  /*
2829  * (Re) initialize our connection control variables for a set of
2830  * connection attempts to a single server address. These variables
2831  * must persist across individual connection attempts, but we must
2832  * reset them when we start to consider a new server.
2833  */
2834  conn->pversion = PG_PROTOCOL(3, 0);
2835  conn->send_appname = true;
2836  conn->failed_enc_methods = 0;
2837  conn->current_enc_method = 0;
2839  reset_connection_state_machine = false;
2840  need_new_connection = true;
2841  }
2842 
2843  /* Force a new connection (perhaps to the same server as before)? */
2844  if (need_new_connection)
2845  {
2846  /* Drop any existing connection */
2847  pqDropConnection(conn, true);
2848 
2849  /* Reset all state obtained from old server */
2851 
2852  /* Drop any PGresult we might have, too */
2857 
2858  /* Reset conn->status to put the state machine in the right state */
2860 
2861  need_new_connection = false;
2862  }
2863 
2864  /* Decide what to do next, if SSL or GSS negotiation fails */
2865 #define ENCRYPTION_NEGOTIATION_FAILED() \
2866  do { \
2867  switch (encryption_negotiation_failed(conn)) \
2868  { \
2869  case 0: \
2870  goto error_return; \
2871  case 1: \
2872  conn->status = CONNECTION_MADE; \
2873  return PGRES_POLLING_WRITING; \
2874  case 2: \
2875  need_new_connection = true; \
2876  goto keep_going; \
2877  } \
2878  } while(0);
2879 
2880  /* Decide what to do next, if connection fails */
2881 #define CONNECTION_FAILED() \
2882  do { \
2883  if (connection_failed(conn)) \
2884  { \
2885  need_new_connection = true; \
2886  goto keep_going; \
2887  } \
2888  else \
2889  goto error_return; \
2890  } while(0);
2891 
2892  /* Now try to advance the state machine for this connection */
2893  switch (conn->status)
2894  {
2895  case CONNECTION_NEEDED:
2896  {
2897  /*
2898  * Try to initiate a connection to one of the addresses
2899  * returned by pg_getaddrinfo_all(). conn->whichaddr is the
2900  * next one to try.
2901  *
2902  * The extra level of braces here is historical. It's not
2903  * worth reindenting this whole switch case to remove 'em.
2904  */
2905  {
2906  char host_addr[NI_MAXHOST];
2907  int sock_type;
2908  AddrInfo *addr_cur;
2909 
2910  /*
2911  * Advance to next possible host, if we've tried all of
2912  * the addresses for the current host.
2913  */
2914  if (conn->whichaddr == conn->naddr)
2915  {
2916  conn->try_next_host = true;
2917  goto keep_going;
2918  }
2919  addr_cur = &conn->addr[conn->whichaddr];
2920 
2921  /* Remember current address for possible use later */
2922  memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
2923 
2924 #ifdef ENABLE_GSS
2925 
2926  /*
2927  * Before establishing the connection, check if it's
2928  * doomed to fail because gssencmode='require' but GSSAPI
2929  * is not available.
2930  */
2931  if (conn->gssencmode[0] == 'r')
2932  {
2933  if (conn->raddr.addr.ss_family == AF_UNIX)
2934  {
2936  "GSSAPI encryption required but it is not supported over a local socket");
2937  goto error_return;
2938  }
2939  if (conn->gcred == GSS_C_NO_CREDENTIAL)
2940  {
2941  if (!pg_GSS_have_cred_cache(&conn->gcred))
2942  {
2944  "GSSAPI encryption required but no credential cache");
2945  goto error_return;
2946  }
2947  }
2948  }
2949 #endif
2950 
2951  /*
2952  * Choose the encryption method to try first. Do this
2953  * before establishing the connection, so that if none of
2954  * the modes allowed by the connections options are
2955  * available, we can error out before establishing the
2956  * connection.
2957  */
2959  goto error_return;
2960 
2961  /*
2962  * Set connip, too. Note we purposely ignore strdup
2963  * failure; not a big problem if it fails.
2964  */
2965  if (conn->connip != NULL)
2966  {
2967  free(conn->connip);
2968  conn->connip = NULL;
2969  }
2970  getHostaddr(conn, host_addr, NI_MAXHOST);
2971  if (host_addr[0])
2972  conn->connip = strdup(host_addr);
2973 
2974  /* Try to create the socket */
2975  sock_type = SOCK_STREAM;
2976 #ifdef SOCK_CLOEXEC
2977 
2978  /*
2979  * Atomically mark close-on-exec, if possible on this
2980  * platform, so that there isn't a window where a
2981  * subprogram executed by another thread inherits the
2982  * socket. See fallback code below.
2983  */
2984  sock_type |= SOCK_CLOEXEC;
2985 #endif
2986 #ifdef SOCK_NONBLOCK
2987 
2988  /*
2989  * We might as well skip a system call for nonblocking
2990  * mode too, if we can.
2991  */
2992  sock_type |= SOCK_NONBLOCK;
2993 #endif
2994  conn->sock = socket(addr_cur->family, sock_type, 0);
2995  if (conn->sock == PGINVALID_SOCKET)
2996  {
2997  int errorno = SOCK_ERRNO;
2998 
2999  /*
3000  * Silently ignore socket() failure if we have more
3001  * addresses to try; this reduces useless chatter in
3002  * cases where the address list includes both IPv4 and
3003  * IPv6 but kernel only accepts one family.
3004  */
3005  if (conn->whichaddr < conn->naddr ||
3006  conn->whichhost + 1 < conn->nconnhost)
3007  {
3008  conn->try_next_addr = true;
3009  goto keep_going;
3010  }
3011  emitHostIdentityInfo(conn, host_addr);
3012  libpq_append_conn_error(conn, "could not create socket: %s",
3013  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
3014  goto error_return;
3015  }
3016 
3017  /*
3018  * Once we've identified a target address, all errors
3019  * except the preceding socket()-failure case should be
3020  * prefixed with host-identity information. (If the
3021  * connection succeeds, the contents of conn->errorMessage
3022  * won't matter, so this is harmless.)
3023  */
3024  emitHostIdentityInfo(conn, host_addr);
3025 
3026  /*
3027  * Select socket options: no delay of outgoing data for
3028  * TCP sockets, nonblock mode, close-on-exec. Try the
3029  * next address if any of this fails.
3030  */
3031  if (addr_cur->family != AF_UNIX)
3032  {
3033  if (!connectNoDelay(conn))
3034  {
3035  /* error message already created */
3036  conn->try_next_addr = true;
3037  goto keep_going;
3038  }
3039  }
3040 #ifndef SOCK_NONBLOCK
3041  if (!pg_set_noblock(conn->sock))
3042  {
3043  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
3044  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3045  conn->try_next_addr = true;
3046  goto keep_going;
3047  }
3048 #endif
3049 
3050 #ifndef SOCK_CLOEXEC
3051 #ifdef F_SETFD
3052  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
3053  {
3054  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
3055  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3056  conn->try_next_addr = true;
3057  goto keep_going;
3058  }
3059 #endif /* F_SETFD */
3060 #endif
3061 
3062  if (addr_cur->family != AF_UNIX)
3063  {
3064 #ifndef WIN32
3065  int on = 1;
3066 #endif
3067  int usekeepalives = useKeepalives(conn);
3068  int err = 0;
3069 
3070  if (usekeepalives < 0)
3071  {
3072  libpq_append_conn_error(conn, "keepalives parameter must be an integer");
3073  err = 1;
3074  }
3075  else if (usekeepalives == 0)
3076  {
3077  /* Do nothing */
3078  }
3079 #ifndef WIN32
3080  else if (setsockopt(conn->sock,
3081  SOL_SOCKET, SO_KEEPALIVE,
3082  (char *) &on, sizeof(on)) < 0)
3083  {
3084  libpq_append_conn_error(conn, "%s(%s) failed: %s",
3085  "setsockopt",
3086  "SO_KEEPALIVE",
3087  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3088  err = 1;
3089  }
3090  else if (!setKeepalivesIdle(conn)
3092  || !setKeepalivesCount(conn))
3093  err = 1;
3094 #else /* WIN32 */
3095 #ifdef SIO_KEEPALIVE_VALS
3096  else if (!prepKeepalivesWin32(conn))
3097  err = 1;
3098 #endif /* SIO_KEEPALIVE_VALS */
3099 #endif /* WIN32 */
3100  else if (!setTCPUserTimeout(conn))
3101  err = 1;
3102 
3103  if (err)
3104  {
3105  conn->try_next_addr = true;
3106  goto keep_going;
3107  }
3108  }
3109 
3110  /*----------
3111  * We have three methods of blocking SIGPIPE during
3112  * send() calls to this socket:
3113  *
3114  * - setsockopt(sock, SO_NOSIGPIPE)
3115  * - send(sock, ..., MSG_NOSIGNAL)
3116  * - setting the signal mask to SIG_IGN during send()
3117  *
3118  * The third method requires three syscalls per send,
3119  * so we prefer either of the first two, but they are
3120  * less portable. The state is tracked in the following
3121  * members of PGconn:
3122  *
3123  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3124  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3125  *
3126  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3127  * and we're done. Otherwise, set sigpipe_flag so that
3128  * we will try MSG_NOSIGNAL on sends. If we get an error
3129  * with MSG_NOSIGNAL, we'll clear that flag and revert to
3130  * signal masking.
3131  *----------
3132  */
3133  conn->sigpipe_so = false;
3134 #ifdef MSG_NOSIGNAL
3135  conn->sigpipe_flag = true;
3136 #else
3137  conn->sigpipe_flag = false;
3138 #endif /* MSG_NOSIGNAL */
3139 
3140 #ifdef SO_NOSIGPIPE
3141  optval = 1;
3142  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3143  (char *) &optval, sizeof(optval)) == 0)
3144  {
3145  conn->sigpipe_so = true;
3146  conn->sigpipe_flag = false;
3147  }
3148 #endif /* SO_NOSIGPIPE */
3149 
3150  /*
3151  * Start/make connection. This should not block, since we
3152  * are in nonblock mode. If it does, well, too bad.
3153  */
3154  if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3155  addr_cur->addr.salen) < 0)
3156  {
3157  if (SOCK_ERRNO == EINPROGRESS ||
3158 #ifdef WIN32
3159  SOCK_ERRNO == EWOULDBLOCK ||
3160 #endif
3161  SOCK_ERRNO == EINTR)
3162  {
3163  /*
3164  * This is fine - we're in non-blocking mode, and
3165  * the connection is in progress. Tell caller to
3166  * wait for write-ready on socket.
3167  */
3169  return PGRES_POLLING_WRITING;
3170  }
3171  /* otherwise, trouble */
3172  }
3173  else
3174  {
3175  /*
3176  * Hm, we're connected already --- seems the "nonblock
3177  * connection" wasn't. Advance the state machine and
3178  * go do the next stuff.
3179  */
3181  goto keep_going;
3182  }
3183 
3184  /*
3185  * This connection failed. Add the error report to
3186  * conn->errorMessage, then try the next address if any.
3187  */
3189  conn->try_next_addr = true;
3190  goto keep_going;
3191  }
3192  }
3193 
3194  case CONNECTION_STARTED:
3195  {
3196  socklen_t optlen = sizeof(optval);
3197 
3198  /*
3199  * Write ready, since we've made it here, so the connection
3200  * has been made ... or has failed.
3201  */
3202 
3203  /*
3204  * Now check (using getsockopt) that there is not an error
3205  * state waiting for us on the socket.
3206  */
3207 
3208  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3209  (char *) &optval, &optlen) == -1)
3210  {
3211  libpq_append_conn_error(conn, "could not get socket error status: %s",
3212  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3213  goto error_return;
3214  }
3215  else if (optval != 0)
3216  {
3217  /*
3218  * When using a nonblocking connect, we will typically see
3219  * connect failures at this point, so provide a friendly
3220  * error message.
3221  */
3222  connectFailureMessage(conn, optval);
3223 
3224  /*
3225  * Try the next address if any, just as in the case where
3226  * connect() returned failure immediately.
3227  */
3228  conn->try_next_addr = true;
3229  goto keep_going;
3230  }
3231 
3232  /* Fill in the client address */
3233  conn->laddr.salen = sizeof(conn->laddr.addr);
3234  if (getsockname(conn->sock,
3235  (struct sockaddr *) &conn->laddr.addr,
3236  &conn->laddr.salen) < 0)
3237  {
3238  libpq_append_conn_error(conn, "could not get client address from socket: %s",
3239  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3240  goto error_return;
3241  }
3242 
3243  /*
3244  * Implement requirepeer check, if requested and it's a
3245  * Unix-domain socket.
3246  */
3247  if (conn->requirepeer && conn->requirepeer[0] &&
3248  conn->raddr.addr.ss_family == AF_UNIX)
3249  {
3250 #ifndef WIN32
3251  char *remote_username;
3252 #endif
3253  uid_t uid;
3254  gid_t gid;
3255 
3256  errno = 0;
3257  if (getpeereid(conn->sock, &uid, &gid) != 0)
3258  {
3259  /*
3260  * Provide special error message if getpeereid is a
3261  * stub
3262  */
3263  if (errno == ENOSYS)
3264  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3265  else
3266  libpq_append_conn_error(conn, "could not get peer credentials: %s",
3267  strerror_r(errno, sebuf, sizeof(sebuf)));
3268  goto error_return;
3269  }
3270 
3271 #ifndef WIN32
3272  remote_username = pg_fe_getusername(uid,
3273  &conn->errorMessage);
3274  if (remote_username == NULL)
3275  goto error_return; /* message already logged */
3276 
3277  if (strcmp(remote_username, conn->requirepeer) != 0)
3278  {
3279  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3280  conn->requirepeer, remote_username);
3281  free(remote_username);
3282  goto error_return;
3283  }
3284  free(remote_username);
3285 #else /* WIN32 */
3286  /* should have failed with ENOSYS above */
3287  Assert(false);
3288 #endif /* WIN32 */
3289  }
3290 
3291  /*
3292  * Make sure we can write before advancing to next step.
3293  */
3295  return PGRES_POLLING_WRITING;
3296  }
3297 
3298  case CONNECTION_MADE:
3299  {
3300  char *startpacket;
3301  int packetlen;
3302 
3303 #ifdef ENABLE_GSS
3304 
3305  /*
3306  * If GSSAPI encryption is enabled, send a packet to the
3307  * server asking for GSSAPI Encryption and proceed with GSSAPI
3308  * handshake. We will come back here after GSSAPI encryption
3309  * has been established, with conn->gctx set.
3310  */
3311  if (conn->current_enc_method == ENC_GSSAPI && !conn->gctx)
3312  {
3314 
3315  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3316  {
3317  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3318  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3319  goto error_return;
3320  }
3321 
3322  /* Ok, wait for response */
3324  return PGRES_POLLING_READING;
3325  }
3326 #endif
3327 
3328 #ifdef USE_SSL
3329 
3330  /*
3331  * Enable the libcrypto callbacks before checking if SSL needs
3332  * to be done. This is done before sending the startup packet
3333  * as depending on the type of authentication done, like MD5
3334  * or SCRAM that use cryptohashes, the callbacks would be
3335  * required even without a SSL connection
3336  */
3337  if (pqsecure_initialize(conn, false, true) < 0)
3338  goto error_return;
3339 
3340  /*
3341  * If direct SSL is enabled, jump right into SSL handshake. We
3342  * will come back here after SSL encryption has been
3343  * established, with ssl_in_use set.
3344  */
3346  {
3348  return PGRES_POLLING_WRITING;
3349  }
3350 
3351  /*
3352  * If negotiated SSL is enabled, request SSL and proceed with
3353  * SSL handshake. We will come back here after SSL encryption
3354  * has been established, with ssl_in_use set.
3355  */
3357  {
3358  ProtocolVersion pv;
3359 
3360  /*
3361  * Send the SSL request packet.
3362  *
3363  * Theoretically, this could block, but it really
3364  * shouldn't since we only got here if the socket is
3365  * write-ready.
3366  */
3368  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3369  {
3370  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3371  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3372  goto error_return;
3373  }
3374  /* Ok, wait for response */
3376  return PGRES_POLLING_READING;
3377  }
3378 #endif /* USE_SSL */
3379 
3380  /*
3381  * For cancel requests this is as far as we need to go in the
3382  * connection establishment. Now we can actually send our
3383  * cancellation request.
3384  */
3385  if (conn->cancelRequest)
3386  {
3387  CancelRequestPacket cancelpacket;
3388 
3389  packetlen = sizeof(cancelpacket);
3391  cancelpacket.backendPID = pg_hton32(conn->be_pid);
3392  cancelpacket.cancelAuthCode = pg_hton32(conn->be_key);
3393  if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK)
3394  {
3395  libpq_append_conn_error(conn, "could not send cancel packet: %s",
3396  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3397  goto error_return;
3398  }
3400  return PGRES_POLLING_READING;
3401  }
3402 
3403  /*
3404  * We have now established encryption, or we are happy to
3405  * proceed without.
3406  */
3407 
3408  /* Build the startup packet. */
3409  startpacket = pqBuildStartupPacket3(conn, &packetlen,
3411  if (!startpacket)
3412  {
3413  libpq_append_conn_error(conn, "out of memory");
3414  goto error_return;
3415  }
3416 
3417  /*
3418  * Send the startup packet.
3419  *
3420  * Theoretically, this could block, but it really shouldn't
3421  * since we only got here if the socket is write-ready.
3422  */
3423  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3424  {
3425  libpq_append_conn_error(conn, "could not send startup packet: %s",
3426  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3427  free(startpacket);
3428  goto error_return;
3429  }
3430 
3431  free(startpacket);
3432 
3434  return PGRES_POLLING_READING;
3435  }
3436 
3437  /*
3438  * Handle SSL negotiation: wait for postmaster messages and
3439  * respond as necessary.
3440  */
3442  {
3443 #ifdef USE_SSL
3444  PostgresPollingStatusType pollres;
3445 
3446  /*
3447  * On first time through, get the postmaster's response to our
3448  * SSL negotiation packet. If we are trying a direct ssl
3449  * connection, go straight to initiating ssl.
3450  */
3452  {
3453  /*
3454  * We use pqReadData here since it has the logic to
3455  * distinguish no-data-yet from connection closure. Since
3456  * conn->ssl isn't set, a plain recv() will occur.
3457  */
3458  char SSLok;
3459  int rdresult;
3460 
3461  rdresult = pqReadData(conn);
3462  if (rdresult < 0)
3463  {
3464  /* errorMessage is already filled in */
3465  goto error_return;
3466  }
3467  if (rdresult == 0)
3468  {
3469  /* caller failed to wait for data */
3470  return PGRES_POLLING_READING;
3471  }
3472  if (pqGetc(&SSLok, conn) < 0)
3473  {
3474  /* should not happen really */
3475  return PGRES_POLLING_READING;
3476  }
3477  if (SSLok == 'S')
3478  {
3479  /* mark byte consumed */
3480  conn->inStart = conn->inCursor;
3481  }
3482  else if (SSLok == 'N')
3483  {
3484  /* mark byte consumed */
3485  conn->inStart = conn->inCursor;
3486  /* OK to do without SSL? */
3487  /* We can proceed using this connection */
3489  }
3490  else if (SSLok == 'E')
3491  {
3492  /*
3493  * Server failure of some sort, such as failure to
3494  * fork a backend process. We need to process and
3495  * report the error message, which might be formatted
3496  * according to either protocol 2 or protocol 3.
3497  * Rather than duplicate the code for that, we flip
3498  * into AWAITING_RESPONSE state and let the code there
3499  * deal with it. Note we have *not* consumed the "E"
3500  * byte here.
3501  */
3503  goto keep_going;
3504  }
3505  else
3506  {
3507  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3508  SSLok);
3509  goto error_return;
3510  }
3511  }
3512 
3513  /*
3514  * Set up global SSL state if required. The crypto state has
3515  * already been set if libpq took care of doing that, so there
3516  * is no need to make that happen again.
3517  */
3518  if (pqsecure_initialize(conn, true, false) != 0)
3519  goto error_return;
3520 
3521  /*
3522  * Begin or continue the SSL negotiation process.
3523  */
3524  pollres = pqsecure_open_client(conn);
3525  if (pollres == PGRES_POLLING_OK)
3526  {
3527  /*
3528  * At this point we should have no data already buffered.
3529  * If we do, it was received before we performed the SSL
3530  * handshake, so it wasn't encrypted and indeed may have
3531  * been injected by a man-in-the-middle.
3532  */
3533  if (conn->inCursor != conn->inEnd)
3534  {
3535  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3536  goto error_return;
3537  }
3538 
3539  /* SSL handshake done, ready to send startup packet */
3541  return PGRES_POLLING_WRITING;
3542  }
3543  if (pollres == PGRES_POLLING_FAILED)
3544  {
3545  /*
3546  * Failed direct ssl connection, possibly try a new
3547  * connection with postgres negotiation
3548  */
3550  }
3551  /* Else, return POLLING_READING or POLLING_WRITING status */
3552  return pollres;
3553 #else /* !USE_SSL */
3554  /* can't get here */
3555  goto error_return;
3556 #endif /* USE_SSL */
3557  }
3558 
3560  {
3561 #ifdef ENABLE_GSS
3562  PostgresPollingStatusType pollres;
3563 
3564  /*
3565  * If we haven't yet, get the postmaster's response to our
3566  * negotiation packet
3567  */
3568  if (!conn->gctx)
3569  {
3570  char gss_ok;
3571  int rdresult = pqReadData(conn);
3572 
3573  if (rdresult < 0)
3574  /* pqReadData fills in error message */
3575  goto error_return;
3576  else if (rdresult == 0)
3577  /* caller failed to wait for data */
3578  return PGRES_POLLING_READING;
3579  if (pqGetc(&gss_ok, conn) < 0)
3580  /* shouldn't happen... */
3581  return PGRES_POLLING_READING;
3582 
3583  if (gss_ok == 'E')
3584  {
3585  /*
3586  * Server failure of some sort. Assume it's a
3587  * protocol version support failure, and let's see if
3588  * we can't recover (if it's not, we'll get a better
3589  * error message on retry). Server gets fussy if we
3590  * don't hang up the socket, though.
3591  */
3593  }
3594 
3595  /* mark byte consumed */
3596  conn->inStart = conn->inCursor;
3597 
3598  if (gss_ok == 'N')
3599  {
3600  /* We can proceed using this connection */
3602  }
3603  else if (gss_ok != 'G')
3604  {
3605  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3606  gss_ok);
3607  goto error_return;
3608  }
3609  }
3610 
3611  /* Begin or continue GSSAPI negotiation */
3612  pollres = pqsecure_open_gss(conn);
3613  if (pollres == PGRES_POLLING_OK)
3614  {
3615  /*
3616  * At this point we should have no data already buffered.
3617  * If we do, it was received before we performed the GSS
3618  * handshake, so it wasn't encrypted and indeed may have
3619  * been injected by a man-in-the-middle.
3620  */
3621  if (conn->inCursor != conn->inEnd)
3622  {
3623  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3624  goto error_return;
3625  }
3626 
3627  /* All set for startup packet */
3629  return PGRES_POLLING_WRITING;
3630  }
3631  else if (pollres == PGRES_POLLING_FAILED)
3632  {
3634  }
3635  /* Else, return POLLING_READING or POLLING_WRITING status */
3636  return pollres;
3637 #else /* !ENABLE_GSS */
3638  /* unreachable */
3639  goto error_return;
3640 #endif /* ENABLE_GSS */
3641  }
3642 
3643  /*
3644  * Handle authentication exchange: wait for postmaster messages
3645  * and respond as necessary.
3646  */
3648  {
3649  char beresp;
3650  int msgLength;
3651  int avail;
3652  AuthRequest areq;
3653  int res;
3654 
3655  /*
3656  * Scan the message from current point (note that if we find
3657  * the message is incomplete, we will return without advancing
3658  * inStart, and resume here next time).
3659  */
3660  conn->inCursor = conn->inStart;
3661 
3662  /* Read type byte */
3663  if (pqGetc(&beresp, conn))
3664  {
3665  /* We'll come back when there is more data */
3666  return PGRES_POLLING_READING;
3667  }
3668 
3669  /*
3670  * Validate message type: we expect only an authentication
3671  * request, NegotiateProtocolVersion, or an error here.
3672  * Anything else probably means it's not Postgres on the other
3673  * end at all.
3674  */
3675  if (beresp != PqMsg_AuthenticationRequest &&
3676  beresp != PqMsg_ErrorResponse &&
3678  {
3679  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3680  beresp);
3681  goto error_return;
3682  }
3683 
3684  /* Read message length word */
3685  if (pqGetInt(&msgLength, 4, conn))
3686  {
3687  /* We'll come back when there is more data */
3688  return PGRES_POLLING_READING;
3689  }
3690 
3691  /*
3692  * Try to validate message length before using it.
3693  *
3694  * Authentication requests can't be very large, although GSS
3695  * auth requests may not be that small. Same for
3696  * NegotiateProtocolVersion.
3697  *
3698  * Errors can be a little larger, but not huge. If we see a
3699  * large apparent length in an error, it means we're really
3700  * talking to a pre-3.0-protocol server; cope. (Before
3701  * version 14, the server also used the old protocol for
3702  * errors that happened before processing the startup packet.)
3703  */
3704  if (beresp == PqMsg_AuthenticationRequest &&
3705  (msgLength < 8 || msgLength > 2000))
3706  {
3707  libpq_append_conn_error(conn, "received invalid authentication request");
3708  goto error_return;
3709  }
3710  if (beresp == PqMsg_NegotiateProtocolVersion &&
3711  (msgLength < 8 || msgLength > 2000))
3712  {
3713  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3714  goto error_return;
3715  }
3716 
3717 #define MAX_ERRLEN 30000
3718  if (beresp == PqMsg_ErrorResponse &&
3719  (msgLength < 8 || msgLength > MAX_ERRLEN))
3720  {
3721  /* Handle error from a pre-3.0 server */
3722  conn->inCursor = conn->inStart + 1; /* reread data */
3724  {
3725  /*
3726  * We may not have authenticated the server yet, so
3727  * don't let the buffer grow forever.
3728  */
3729  avail = conn->inEnd - conn->inCursor;
3730  if (avail > MAX_ERRLEN)
3731  {
3732  libpq_append_conn_error(conn, "received invalid error message");
3733  goto error_return;
3734  }
3735 
3736  /* We'll come back when there is more data */
3737  return PGRES_POLLING_READING;
3738  }
3739  /* OK, we read the message; mark data consumed */
3740  conn->inStart = conn->inCursor;
3741 
3742  /*
3743  * Before 7.2, the postmaster didn't always end its
3744  * messages with a newline, so add one if needed to
3745  * conform to libpq conventions.
3746  */
3747  if (conn->errorMessage.len == 0 ||
3748  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3749  {
3751  }
3752 
3753  goto error_return;
3754  }
3755 #undef MAX_ERRLEN
3756 
3757  /*
3758  * Can't process if message body isn't all here yet.
3759  *
3760  * After this check passes, any further EOF during parsing
3761  * implies that the server sent a bad/truncated message.
3762  * Reading more bytes won't help in that case, so don't return
3763  * PGRES_POLLING_READING after this point.
3764  */
3765  msgLength -= 4;
3766  avail = conn->inEnd - conn->inCursor;
3767  if (avail < msgLength)
3768  {
3769  /*
3770  * Before returning, try to enlarge the input buffer if
3771  * needed to hold the whole message; see notes in
3772  * pqParseInput3.
3773  */
3774  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3775  conn))
3776  goto error_return;
3777  /* We'll come back when there is more data */
3778  return PGRES_POLLING_READING;
3779  }
3780 
3781  /* Handle errors. */
3782  if (beresp == PqMsg_ErrorResponse)
3783  {
3784  if (pqGetErrorNotice3(conn, true))
3785  {
3786  libpq_append_conn_error(conn, "received invalid error message");
3787  goto error_return;
3788  }
3789  /* OK, we read the message; mark data consumed */
3790  conn->inStart = conn->inCursor;
3791 
3792  /*
3793  * If error is "cannot connect now", try the next host if
3794  * any (but we don't want to consider additional addresses
3795  * for this host, nor is there much point in changing SSL
3796  * or GSS mode). This is helpful when dealing with
3797  * standby servers that might not be in hot-standby state.
3798  */
3799  if (strcmp(conn->last_sqlstate,
3801  {
3802  conn->try_next_host = true;
3803  goto keep_going;
3804  }
3805 
3806  /* Check to see if we should mention pgpassfile */
3808 
3810  }
3811  else if (beresp == PqMsg_NegotiateProtocolVersion)
3812  {
3814  {
3815  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3816  goto error_return;
3817  }
3818  /* OK, we read the message; mark data consumed */
3819  conn->inStart = conn->inCursor;
3820  goto error_return;
3821  }
3822 
3823  /* It is an authentication request. */
3824  conn->auth_req_received = true;
3825 
3826  /* Get the type of request. */
3827  if (pqGetInt((int *) &areq, 4, conn))
3828  {
3829  /* can't happen because we checked the length already */
3830  libpq_append_conn_error(conn, "received invalid authentication request");
3831  goto error_return;
3832  }
3833  msgLength -= 4;
3834 
3835  /*
3836  * Process the rest of the authentication request message, and
3837  * respond to it if necessary.
3838  *
3839  * Note that conn->pghost must be non-NULL if we are going to
3840  * avoid the Kerberos code doing a hostname look-up.
3841  */
3842  res = pg_fe_sendauth(areq, msgLength, conn);
3843 
3844  /* OK, we have processed the message; mark data consumed */
3845  conn->inStart = conn->inCursor;
3846 
3847  if (res != STATUS_OK)
3848  goto error_return;
3849 
3850  /*
3851  * Just make sure that any data sent by pg_fe_sendauth is
3852  * flushed out. Although this theoretically could block, it
3853  * really shouldn't since we don't send large auth responses.
3854  */
3855  if (pqFlush(conn))
3856  goto error_return;
3857 
3858  if (areq == AUTH_REQ_OK)
3859  {
3860  /* We are done with authentication exchange */
3862 
3863  /*
3864  * Set asyncStatus so that PQgetResult will think that
3865  * what comes back next is the result of a query. See
3866  * below.
3867  */
3869  }
3870 
3871  /* Look to see if we have more data yet. */
3872  goto keep_going;
3873  }
3874 
3875  case CONNECTION_AUTH_OK:
3876  {
3877  /*
3878  * Now we expect to hear from the backend. A ReadyForQuery
3879  * message indicates that startup is successful, but we might
3880  * also get an Error message indicating failure. (Notice
3881  * messages indicating nonfatal warnings are also allowed by
3882  * the protocol, as are ParameterStatus and BackendKeyData
3883  * messages.) Easiest way to handle this is to let
3884  * PQgetResult() read the messages. We just have to fake it
3885  * out about the state of the connection, by setting
3886  * asyncStatus = PGASYNC_BUSY (done above).
3887  */
3888 
3889  if (PQisBusy(conn))
3890  return PGRES_POLLING_READING;
3891 
3892  res = PQgetResult(conn);
3893 
3894  /*
3895  * NULL return indicating we have gone to IDLE state is
3896  * expected
3897  */
3898  if (res)
3899  {
3901  libpq_append_conn_error(conn, "unexpected message from server during startup");
3902  else if (conn->send_appname &&
3903  (conn->appname || conn->fbappname))
3904  {
3905  /*
3906  * If we tried to send application_name, check to see
3907  * if the error is about that --- pre-9.0 servers will
3908  * reject it at this stage of the process. If so,
3909  * close the connection and retry without sending
3910  * application_name. We could possibly get a false
3911  * SQLSTATE match here and retry uselessly, but there
3912  * seems no great harm in that; we'll just get the
3913  * same error again if it's unrelated.
3914  */
3915  const char *sqlstate;
3916 
3918  if (sqlstate &&
3919  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3920  {
3921  PQclear(res);
3922  conn->send_appname = false;
3923  need_new_connection = true;
3924  goto keep_going;
3925  }
3926  }
3927 
3928  /*
3929  * if the resultStatus is FATAL, then conn->errorMessage
3930  * already has a copy of the error; needn't copy it back.
3931  * But add a newline if it's not there already, since
3932  * postmaster error messages may not have one.
3933  */
3934  if (conn->errorMessage.len <= 0 ||
3935  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3937  PQclear(res);
3938  goto error_return;
3939  }
3940 
3941  /* Almost there now ... */
3943  goto keep_going;
3944  }
3945 
3947  {
3948  /*
3949  * If a read-write, read-only, primary, or standby connection
3950  * is required, see if we have one.
3951  */
3954  {
3955  bool read_only_server;
3956 
3957  /*
3958  * If the server didn't report
3959  * "default_transaction_read_only" or "in_hot_standby" at
3960  * startup, we must determine its state by sending the
3961  * query "SHOW transaction_read_only". This GUC exists in
3962  * all server versions that support 3.0 protocol.
3963  */
3966  {
3967  /*
3968  * We use PQsendQueryContinue so that
3969  * conn->errorMessage does not get cleared. We need
3970  * to preserve any error messages related to previous
3971  * hosts we have tried and failed to connect to.
3972  */
3975  "SHOW transaction_read_only"))
3976  goto error_return;
3977  /* We'll return to this state when we have the answer */
3979  return PGRES_POLLING_READING;
3980  }
3981 
3982  /* OK, we can make the test */
3983  read_only_server =
3986 
3988  read_only_server : !read_only_server)
3989  {
3990  /* Wrong server state, reject and try the next host */
3992  libpq_append_conn_error(conn, "session is read-only");
3993  else
3994  libpq_append_conn_error(conn, "session is not read-only");
3995 
3996  /* Close connection politely. */
3999 
4000  /*
4001  * Try next host if any, but we don't want to consider
4002  * additional addresses for this host.
4003  */
4004  conn->try_next_host = true;
4005  goto keep_going;
4006  }
4007  }
4011  {
4012  /*
4013  * If the server didn't report "in_hot_standby" at
4014  * startup, we must determine its state by sending the
4015  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
4016  * before 9.0 don't have that function, but by the same
4017  * token they don't have any standby mode, so we may just
4018  * assume the result.
4019  */
4020  if (conn->sversion < 90000)
4022 
4024  {
4025  /*
4026  * We use PQsendQueryContinue so that
4027  * conn->errorMessage does not get cleared. We need
4028  * to preserve any error messages related to previous
4029  * hosts we have tried and failed to connect to.
4030  */
4033  "SELECT pg_catalog.pg_is_in_recovery()"))
4034  goto error_return;
4035  /* We'll return to this state when we have the answer */
4037  return PGRES_POLLING_READING;
4038  }
4039 
4040  /* OK, we can make the test */
4044  {
4045  /* Wrong server state, reject and try the next host */
4047  libpq_append_conn_error(conn, "server is in hot standby mode");
4048  else
4049  libpq_append_conn_error(conn, "server is not in hot standby mode");
4050 
4051  /* Close connection politely. */
4054 
4055  /*
4056  * Try next host if any, but we don't want to consider
4057  * additional addresses for this host.
4058  */
4059  conn->try_next_host = true;
4060  goto keep_going;
4061  }
4062  }
4063 
4064  /*
4065  * For non cancel requests we can release the address list
4066  * now. For cancel requests we never actually resolve
4067  * addresses and instead the addrinfo exists for the lifetime
4068  * of the connection.
4069  */
4070  if (!conn->cancelRequest)
4072 
4073  /*
4074  * Contents of conn->errorMessage are no longer interesting
4075  * (and it seems some clients expect it to be empty after a
4076  * successful connection).
4077  */
4079 
4080  /* We are open for business! */
4082  return PGRES_POLLING_OK;
4083  }
4084 
4085  case CONNECTION_CONSUME:
4086  {
4087  /*
4088  * This state just makes sure the connection is idle after
4089  * we've obtained the result of a SHOW or SELECT query. Once
4090  * we're clear, return to CONNECTION_CHECK_TARGET state to
4091  * decide what to do next. We must transiently set status =
4092  * CONNECTION_OK in order to use the result-consuming
4093  * subroutines.
4094  */
4096  if (!PQconsumeInput(conn))
4097  goto error_return;
4098 
4099  if (PQisBusy(conn))
4100  {
4102  return PGRES_POLLING_READING;
4103  }
4104 
4105  /* Call PQgetResult() again until we get a NULL result */
4106  res = PQgetResult(conn);
4107  if (res != NULL)
4108  {
4109  PQclear(res);
4111  return PGRES_POLLING_READING;
4112  }
4113 
4115  goto keep_going;
4116  }
4117 
4119  {
4120  /*
4121  * Waiting for result of "SHOW transaction_read_only". We
4122  * must transiently set status = CONNECTION_OK in order to use
4123  * the result-consuming subroutines.
4124  */
4126  if (!PQconsumeInput(conn))
4127  goto error_return;
4128 
4129  if (PQisBusy(conn))
4130  {
4132  return PGRES_POLLING_READING;
4133  }
4134 
4135  res = PQgetResult(conn);
4136  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4137  PQntuples(res) == 1)
4138  {
4139  char *val = PQgetvalue(res, 0, 0);
4140 
4141  /*
4142  * "transaction_read_only = on" proves that at least one
4143  * of default_transaction_read_only and in_hot_standby is
4144  * on, but we don't actually know which. We don't care
4145  * though for the purpose of identifying a read-only
4146  * session, so satisfy the CONNECTION_CHECK_TARGET code by
4147  * claiming they are both on. On the other hand, if it's
4148  * a read-write session, they are certainly both off.
4149  */
4150  if (strncmp(val, "on", 2) == 0)
4151  {
4154  }
4155  else
4156  {
4159  }
4160  PQclear(res);
4161 
4162  /* Finish reading messages before continuing */
4164  goto keep_going;
4165  }
4166 
4167  /* Something went wrong with "SHOW transaction_read_only". */
4168  PQclear(res);
4169 
4170  /* Append error report to conn->errorMessage. */
4171  libpq_append_conn_error(conn, "\"%s\" failed",
4172  "SHOW transaction_read_only");
4173 
4174  /* Close connection politely. */
4177 
4178  /* Try next host. */
4179  conn->try_next_host = true;
4180  goto keep_going;
4181  }
4182 
4184  {
4185  /*
4186  * Waiting for result of "SELECT pg_is_in_recovery()". We
4187  * must transiently set status = CONNECTION_OK in order to use
4188  * the result-consuming subroutines.
4189  */
4191  if (!PQconsumeInput(conn))
4192  goto error_return;
4193 
4194  if (PQisBusy(conn))
4195  {
4197  return PGRES_POLLING_READING;
4198  }
4199 
4200  res = PQgetResult(conn);
4201  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4202  PQntuples(res) == 1)
4203  {
4204  char *val = PQgetvalue(res, 0, 0);
4205 
4206  if (strncmp(val, "t", 1) == 0)
4208  else
4210  PQclear(res);
4211 
4212  /* Finish reading messages before continuing */
4214  goto keep_going;
4215  }
4216 
4217  /* Something went wrong with "SELECT pg_is_in_recovery()". */
4218  PQclear(res);
4219 
4220  /* Append error report to conn->errorMessage. */
4221  libpq_append_conn_error(conn, "\"%s\" failed",
4222  "SELECT pg_is_in_recovery()");
4223 
4224  /* Close connection politely. */
4227 
4228  /* Try next host. */
4229  conn->try_next_host = true;
4230  goto keep_going;
4231  }
4232 
4233  default:
4235  "invalid connection state %d, probably indicative of memory corruption",
4236  conn->status);
4237  goto error_return;
4238  }
4239 
4240  /* Unreachable */
4241 
4242 error_return:
4243 
4244  /*
4245  * We used to close the socket at this point, but that makes it awkward
4246  * for those above us if they wish to remove this socket from their own
4247  * records (an fd_set for example). We'll just have this socket closed
4248  * when PQfinish is called (which is compulsory even after an error, since
4249  * the connection structure must be freed).
4250  */
4252  return PGRES_POLLING_FAILED;
4253 }
#define STATUS_OK
Definition: c.h:1169
void err(int eval, const char *fmt,...)
Definition: err.c:43
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:960
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1168
#define MAX_ERRLEN
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:372
#define CONNECTION_FAILED()
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2238
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:2151
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
Definition: fe-connect.c:4735
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:2131
#define ENCRYPTION_NEGOTIATION_FAILED()
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:86
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2203
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2169
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7553
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:2075
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2335
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:2016
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:2042
static bool init_allowed_encryption_methods(PGconn *conn)
Definition: fe-connect.c:4259
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4976
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1422
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1984
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqReadData(PGconn *conn)
Definition: fe-misc.c:565
int pqFlush(PGconn *conn)
Definition: fe-misc.c:953
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:77
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:216
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:351
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:142
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:882
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:153
int pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
Definition: fe-secure.c:138
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
@ CONNECTION_CONSUME
Definition: libpq-fe.h:79
@ CONNECTION_CHECK_STANDBY
Definition: libpq-fe.h:83
@ CONNECTION_STARTED
Definition: libpq-fe.h:69
@ CONNECTION_AWAITING_RESPONSE
Definition: libpq-fe.h:71
@ CONNECTION_CHECK_WRITABLE
Definition: libpq-fe.h:78
@ CONNECTION_GSS_STARTUP
Definition: libpq-fe.h:80
@ CONNECTION_SSL_STARTUP
Definition: libpq-fe.h:76
@ CONNECTION_AUTH_OK
Definition: libpq-fe.h:73
@ CONNECTION_CHECK_TARGET
Definition: libpq-fe.h:81
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:111
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:90
@ PGASYNC_BUSY
Definition: libpq-int.h:222
@ PG_BOOL_YES
Definition: libpq-int.h:264
@ PG_BOOL_NO
Definition: libpq-int.h:265
@ PG_BOOL_UNKNOWN
Definition: libpq-int.h:263
#define pg_hton32(x)
Definition: pg_bswap.h:121
static char portstr[16]
Definition: pg_regress.c:117
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
unsigned int socklen_t
Definition: port.h:40
#define PGINVALID_SOCKET
Definition: port.h:31
#define strerror_r
Definition: port.h:255
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:132
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:44
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:60
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:167
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:166
uint32 ProtocolVersion
Definition: pqcomm.h:99
uint32 AuthRequest
Definition: pqcomm.h:121
ProtocolVersion MsgType
Definition: pqcomm.h:101
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:89
#define AUTH_REQ_OK
Definition: protocol.h:70
#define PqMsg_AuthenticationRequest
Definition: protocol.h:50
#define PqMsg_NegotiateProtocolVersion
Definition: protocol.h:59
#define PqMsg_ErrorResponse
Definition: protocol.h:44
const char * gai_strerror(int ecode)
int family
Definition: pqcomm.h:38
SockAddr addr
Definition: pqcomm.h:39
MsgType cancelRequestCode
Definition: pqcomm.h:137
uint32 backendPID
Definition: pqcomm.h:138
uint32 cancelAuthCode
Definition: pqcomm.h:139
SockAddr laddr
Definition: libpq-int.h:477
AddrInfo * addr
Definition: libpq-int.h:505
bool sigpipe_flag
Definition: libpq-int.h:485
ProtocolVersion pversion
Definition: libpq-int.h:479
bool send_appname
Definition: libpq-int.h:507
PGTernaryBool in_hot_standby
Definition: libpq-int.h:516
int be_key
Definition: libpq-int.h:511
int naddr
Definition: libpq-int.h:503
int sversion
Definition: libpq-int.h:480
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:515
bool sigpipe_so
Definition: libpq-int.h:484
bool ssl_in_use
Definition: libpq-int.h:568
ExecStatusType resultStatus
Definition: libpq-int.h:180
#define EINTR
Definition: win32_port.h:374
#define EWOULDBLOCK
Definition: win32_port.h:380
#define EINPROGRESS
Definition: win32_port.h:386
int gid_t
Definition: win32_port.h:245
#define socket(af, type, protocol)
Definition: win32_port.h:490
#define connect(s, name, namelen)
Definition: win32_port.h:494
int uid_t
Definition: win32_port.h:244

References AddrInfo::addr, SockAddr::addr, pg_conn::addr, pg_conn::allowed_enc_methods, appendPQExpBufferChar(), pg_conn::appname, Assert, pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CancelRequestPacket::backendPID, pg_conn::be_key, pg_conn::be_pid, CANCEL_REQUEST_CODE, CancelRequestPacket::cancelAuthCode, pg_conn::cancelRequest, CancelRequestPacket::cancelRequestCode, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_FAILED, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, pg_conn::current_enc_method, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), ENC_DIRECT_SSL, ENC_GSSAPI, ENC_NEGOTIATED_SSL, ENCRYPTION_NEGOTIATION_FAILED, EnvironmentOptions, err(), ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::failed_enc_methods, AddrInfo::family, pg_conn::fbappname, free, gai_strerror(), getHostaddr(), getpeereid(), pg_conn::gssencmode, pg_conn_host::host, pg_conn_host::hostaddr, i, pg_conn::in_hot_standby, pg_conn::inCursor, pg_conn::inEnd, init_allowed_encryption_methods(), pg_conn::inStart, j, pg_conn::laddr, pg_conn::last_sqlstate, PQExpBufferData::len, libpq_append_conn_error(), LOAD_BALANCE_RANDOM, pg_conn::load_balance_type, MAX_ERRLEN, MAXPGPATH, MemSet, pg_conn::naddr, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, PG_BOOL_NO, PG_BOOL_UNKNOWN, PG_BOOL_YES, PG_DIAG_SQLSTATE, pg_fe_getusername(), pg_fe_sendauth(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_GSS_have_cred_cache(), pg_hton32, pg_prng_uint64_range(), PG_PROTOCOL, pg_set_noblock(), PG_STRERROR_R_BUFLEN, PGASYNC_BUSY, PGASYNC_IDLE, PGINVALID_SOCKET, pgpassfileWarning(), PGRES_FATAL_ERROR, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_TUPLES_OK, pg_conn::pipelineStatus, pg_conn_host::port, portstr, PQ_PIPELINE_OFF, pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), pqClearAsyncResult(), pqClearConnErrorState, PQconsumeInput(), pqDropConnection(), pqDropServerData(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetNegotiateProtocolVersion3(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PqMsg_AuthenticationRequest, PqMsg_ErrorResponse, PqMsg_NegotiateProtocolVersion, PQntuples(), pqPacketSend(), pqParseIntParam(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), pqsecure_open_gss(), PQsendQueryContinue(), PQTRANS_IDLE, pg_conn::prng_state, pg_conn::pversion, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, res, pg_result::resultStatus, SockAddr::salen, pg_conn::send_appname, sendTerminateConn(), SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PREFER_STANDBY_PASS2, SERVER_TYPE_PRIMARY, SERVER_TYPE_READ_ONLY, SERVER_TYPE_READ_WRITE, SERVER_TYPE_STANDBY, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::ssl_in_use, pg_conn::status, STATUS_OK, store_conn_addrinfo(), strerror_r, pg_conn::sversion, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), val, pg_conn::whichaddr, pg_conn::whichhost, and pg_conn::xactStatus.

Referenced by libpqrcv_connect(), libpqsrv_connect_internal(), PQcancelPoll(), pqConnectDBComplete(), pqConnectDBStart(), PQresetPoll(), and wait_until_connected().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

Definition at line 872 of file fe-connect.c.

873 {
874  PGconn *conn;
875 
876  /*
877  * Allocate memory for the conn structure. Note that we also expect this
878  * to initialize conn->errorMessage to empty. All subsequent steps during
879  * connection initialization will only append to that buffer.
880  */
882  if (conn == NULL)
883  return NULL;
884 
885  /*
886  * Parse the conninfo string
887  */
888  if (!connectOptions1(conn, conninfo))
889  return conn;
890 
891  /*
892  * Compute derived options
893  */
894  if (!pqConnectOptions2(conn))
895  return conn;
896 
897  /*
898  * Connect to the database
899  */
900  if (!pqConnectDBStart(conn))
901  {
902  /* Just in case we failed to set it in pqConnectDBStart */
904  }
905 
906  return conn;
907 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:997
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1120
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4525
int pqConnectDBStart(PGconn *conn)
Definition: fe-connect.c:2374

References conn, CONNECTION_BAD, connectOptions1(), pqConnectDBStart(), pqConnectOptions2(), pqMakeEmptyPGconn(), and pg_conn::status.

Referenced by libpqsrv_connect(), PQconnectdb(), and PQping().

◆ PQconnectStartParams()

PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 791 of file fe-connect.c.

794 {
795  PGconn *conn;
796  PQconninfoOption *connOptions;
797 
798  /*
799  * Allocate memory for the conn structure. Note that we also expect this
800  * to initialize conn->errorMessage to empty. All subsequent steps during
801  * connection initialization will only append to that buffer.
802  */
804  if (conn == NULL)
805  return NULL;
806 
807  /*
808  * Parse the conninfo arrays
809  */
810  connOptions = conninfo_array_parse(keywords, values,
811  &conn->errorMessage,
812  true, expand_dbname);
813  if (connOptions == NULL)
814  {
816  /* errorMessage is already set */
817  return conn;
818  }
819 
820  /*
821  * Move option values into conn structure
822  */
823  if (!fillPGconn(conn, connOptions))
824  {
825  PQconninfoFree(connOptions);
826  return conn;
827  }
828 
829  /*
830  * Free the option info - all is in conn now
831  */
832  PQconninfoFree(connOptions);
833 
834  /*
835  * Compute derived options
836  */
837  if (!pqConnectOptions2(conn))
838  return conn;
839 
840  /*
841  * Connect to the database
842  */
843  if (!pqConnectDBStart(conn))
844  {
845  /* Just in case we failed to set it in pqConnectDBStart */
847  }
848 
849  return conn;
850 }
static PQconninfoOption * conninfo_array_parse(const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
Definition: fe-connect.c:6019

References conn, CONNECTION_BAD, conninfo_array_parse(), pg_conn::errorMessage, fillPGconn(), pqConnectDBStart(), pqConnectOptions2(), PQconninfoFree(), pqMakeEmptyPGconn(), pg_conn::status, and values.

Referenced by do_connect(), libpqrcv_connect(), libpqsrv_connect_params(), PQconnectdbParams(), and PQpingParams().

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

Definition at line 6936 of file fe-connect.c.

6937 {
6938  PQExpBufferData errorBuf;
6939  PQconninfoOption *connOptions;
6940 
6941  if (conn == NULL)
6942  return NULL;
6943 
6944  /*
6945  * We don't actually report any errors here, but callees want a buffer,
6946  * and we prefer not to trash the conn's errorMessage.
6947  */
6948  initPQExpBuffer(&errorBuf);
6949  if (PQExpBufferDataBroken(errorBuf))
6950  return NULL; /* out of memory already :-( */
6951 
6952  connOptions = conninfo_init(&errorBuf);
6953 
6954  if (connOptions != NULL)
6955  {
6957 
6958  for (option = PQconninfoOptions; option->keyword; option++)
6959  {
6960  char **connmember;
6961 
6962  if (option->connofs < 0)
6963  continue;
6964 
6965  connmember = (char **) ((char *) conn + option->connofs);
6966 
6967  if (*connmember)
6968  conninfo_storeval(connOptions, option->keyword, *connmember,
6969  &errorBuf, true, false);
6970  }
6971  }
6972 
6973  termPQExpBuffer(&errorBuf);
6974 
6975  return connOptions;
6976 }

References conn, conninfo_init(), conninfo_storeval(), initPQExpBuffer(), PQconninfoOptions, PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by copy_connection(), do_connect(), GenerateRecoveryConfig(), and libpqrcv_get_conninfo().

◆ PQconninfoFree()

◆ PQconninfoParse()

PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

Definition at line 5728 of file fe-connect.c.

5729 {
5730  PQExpBufferData errorBuf;
5731  PQconninfoOption *connOptions;
5732 
5733  if (errmsg)
5734  *errmsg = NULL; /* default */
5735  initPQExpBuffer(&errorBuf);
5736  if (PQExpBufferDataBroken(errorBuf))
5737  return NULL; /* out of memory already :-( */
5738  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5739  if (connOptions == NULL && errmsg)
5740  *errmsg = errorBuf.data;
5741  else
5742  termPQExpBuffer(&errorBuf);
5743  return connOptions;
5744 }
int errmsg(const char *fmt,...)
Definition: elog.c:1072

References PQExpBufferData::data, errmsg(), initPQExpBuffer(), parse_connection_string(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by connectDatabase(), dblink_connstr_has_pw(), do_connect(), get_base_conninfo(), GetConnection(), GetDbnameFromConnectionOptions(), libpqrcv_check_conninfo(), libpqrcv_get_dbname_from_conninfo(), and main().

◆ pqCopyPGconn()

bool pqCopyPGconn ( PGconn srcConn,
PGconn dstConn 
)

Definition at line 956 of file fe-connect.c.

957 {
959 
960  /* copy over connection options */
961  for (option = PQconninfoOptions; option->keyword; option++)
962  {
963  if (option->connofs >= 0)
964  {
965  const char **tmp = (const char **) ((char *) srcConn + option->connofs);
966 
967  if (*tmp)
968  {
969  char **dstConnmember = (char **) ((char *) dstConn + option->connofs);
970 
971  if (*dstConnmember)
972  free(*dstConnmember);
973  *dstConnmember = strdup(*tmp);
974  if (*dstConnmember == NULL)
975  {
976  libpq_append_conn_error(dstConn, "out of memory");
977  return false;
978  }
979  }
980  }
981  }
982  return true;
983 }

References free, libpq_append_conn_error(), and PQconninfoOptions.

Referenced by PQcancelCreate().

◆ PQdb()

◆ pqDropConnection()

void pqDropConnection ( PGconn conn,
bool  flushInput 
)

Definition at line 471 of file fe-connect.c.

472 {
473  /* Drop any SSL state */
475 
476  /* Close the socket itself */
477  if (conn->sock != PGINVALID_SOCKET)
480 
481  /* Optionally discard any unread data */
482  if (flushInput)
483  conn->inStart = conn->inCursor = conn->inEnd = 0;
484 
485  /* Always discard any unsent data */
486  conn->outCount = 0;
487 
488  /* Likewise, discard any pending pipelined commands */
492  conn->cmd_queue_recycle = NULL;
493 
494  /* Free authentication/encryption state */
495 #ifdef ENABLE_GSS
496  {
497  OM_uint32 min_s;
498 
499  if (conn->gcred != GSS_C_NO_CREDENTIAL)
500  {
501  gss_release_cred(&min_s, &conn->gcred);
502  conn->gcred = GSS_C_NO_CREDENTIAL;
503  }
504  if (conn->gctx)
505  gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
506  if (conn->gtarg_nam)
507  gss_release_name(&min_s, &conn->gtarg_nam);
508  if (conn->gss_SendBuffer)
509  {
510  free(conn->gss_SendBuffer);
511  conn->gss_SendBuffer = NULL;
512  }
513  if (conn->gss_RecvBuffer)
514  {
515  free(conn->gss_RecvBuffer);
516  conn->gss_RecvBuffer = NULL;
517  }
518  if (conn->gss_ResultBuffer)
519  {
520  free(conn->gss_ResultBuffer);
521  conn->gss_ResultBuffer = NULL;
522  }
523  conn->gssenc = false;
524  }
525 #endif
526 #ifdef ENABLE_SSPI
527  if (conn->sspitarget)
528  {
529  free(conn->sspitarget);
530  conn->sspitarget = NULL;
531  }
532  if (conn->sspicred)
533  {
534  FreeCredentialsHandle(conn->sspicred);
535  free(conn->sspicred);
536  conn->sspicred = NULL;
537  }
538  if (conn->sspictx)
539  {
540  DeleteSecurityContext(conn->sspictx);
541  free(conn->sspictx);
542  conn->sspictx = NULL;
543  }
544  conn->usesspi = 0;
545 #endif
546  if (conn->sasl_state)
547  {
549  conn->sasl_state = NULL;
550  }
551 }
static void pqFreeCommandQueue(PGcmdQueueEntry *queue)
Definition: fe-connect.c:558
void pqsecure_close(PGconn *conn)
Definition: fe-secure.c:167
#define closesocket
Definition: port.h:349
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:559
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:472
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:466
void * sasl_state
Definition: libpq-int.h:560
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:465
void(* free)(void *state)
Definition: fe-auth-sasl.h:140

References closesocket, pg_conn::cmd_queue_head, pg_conn::cmd_queue_recycle, pg_conn::cmd_queue_tail, conn, free, pg_fe_sasl_mech::free, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, pg_conn::outCount, PGINVALID_SOCKET, pqFreeCommandQueue(), pqsecure_close(), pg_conn::sasl, pg_conn::sasl_state, and pg_conn::sock.

Referenced by handleSyncLoss(), pqClosePGconn(), pqConnectDBStart(), PQconnectPoll(), and pqReadData().

◆ pqDropServerData()

static void pqDropServerData ( PGconn conn)
static

Definition at line 584 of file fe-connect.c.

585 {
586  PGnotify *notify;
587  pgParameterStatus *pstatus;
588 
589  /* Forget pending notifies */
590  notify = conn->notifyHead;
591  while (notify != NULL)
592  {
593  PGnotify *prev = notify;
594 
595  notify = notify->next;
596  free(prev);
597  }
598  conn->notifyHead = conn->notifyTail = NULL;
599 
600  /* Reset ParameterStatus data, as well as variables deduced from it */
601  pstatus = conn->pstatus;
602  while (pstatus != NULL)
603  {
604  pgParameterStatus *prev = pstatus;
605 
606  pstatus = pstatus->next;
607  free(prev);
608  }
609  conn->pstatus = NULL;
611  conn->std_strings = false;
615  conn->sversion = 0;
616 
617  /* Drop large-object lookup data */
618  free(conn->lobjfuncs);
619  conn->lobjfuncs = NULL;
620 
621  /* Reset assorted other per-connection state */
622  conn->last_sqlstate[0] = '\0';
623  conn->auth_req_received = false;
624  conn->client_finished_auth = false;
625  conn->password_needed = false;
626  conn->gssapi_used = false;
627  conn->write_failed = false;
629  conn->write_err_msg = NULL;
630 
631  /*
632  * Cancel connections need to retain their be_pid and be_key across
633  * PQcancelReset invocations, otherwise they would not have access to the
634  * secret token of the connection they are supposed to cancel.
635  */
636  if (!conn->cancelRequest)
637  {
638  conn->be_pid = 0;
639  conn->be_key = 0;
640  }
641 }
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
#define SCRAM_SHA_256_DEFAULT_ITERATIONS
Definition: scram-common.h:50
struct pgNotify * next
Definition: libpq-fe.h:202
struct pgParameterStatus * next
Definition: libpq-int.h:278
PGnotify * notifyHead
Definition: libpq-int.h:452
bool std_strings
Definition: libpq-int.h:514
bool write_failed
Definition: libpq-int.h:486
bool client_finished_auth
Definition: libpq-int.h:493
PGnotify * notifyTail
Definition: libpq-int.h:453
pgParameterStatus * pstatus
Definition: libpq-int.h:512
int scram_sha_256_iterations
Definition: libpq-int.h:561
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:519

References pg_conn::auth_req_received, pg_conn::be_key, pg_conn::be_pid, pg_conn::cancelRequest, pg_conn::client_encoding, pg_conn::client_finished_auth, conn, pg_conn::default_transaction_read_only, free, pg_conn::gssapi_used, pg_conn::in_hot_standby, pg_conn::last_sqlstate, pg_conn::lobjfuncs, pgNotify::next, pgParameterStatus::next, pg_conn::notifyHead, pg_conn::notifyTail, pg_conn::password_needed, PG_BOOL_UNKNOWN, PG_SQL_ASCII, pg_conn::pstatus, SCRAM_SHA_256_DEFAULT_ITERATIONS, pg_conn::scram_sha_256_iterations, pg_conn::std_strings, pg_conn::sversion, pg_conn::write_err_msg, and pg_conn::write_failed.

Referenced by pqClosePGconn(), and PQconnectPoll().

◆ PQerrorMessage()

char* PQerrorMessage ( const PGconn conn)

Definition at line 7147 of file fe-connect.c.

7148 {
7149  if (!conn)
7150  return libpq_gettext("connection pointer is NULL\n");
7151 
7152  /*
7153  * The errorMessage buffer might be marked "broken" due to having
7154  * previously failed to allocate enough memory for the message. In that
7155  * case, tell the application we ran out of memory.
7156  */
7158  return libpq_gettext("out of memory\n");
7159 
7160  return conn->errorMessage.data;
7161 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

References conn, PQExpBufferData::data, pg_conn::errorMessage, libpq_gettext, and PQExpBufferBroken.

Referenced by _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), BaseBackup(), check_loadable_libraries(), check_prepare_conn(), CheckCopyStreamStop(), cluster_one_database(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_database(), connect_pg_server(), ConnectDatabase(), connectDatabase(), connectToServer(), copy_connection(), CopyStreamPoll(), CopyStreamReceive(), CreateReplicationSlot(), dblink_connect(), dblink_error_message(), dblink_get_conn(), dblink_res_error(), dblink_send_query(), DescribeQuery(), die_on_query_failure(), do_connect(), do_lo_export(), do_lo_import(), do_lo_unlink(), doConnect(), DropReplicationSlot(), dump_lo_buf(), dumpLOs(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_raise_backend(), ECPGconnect(), EndDBCopyMode(), exec_command_password(), ExecQueryAndProcessResults(), executeCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlCommandBuf(), executeStatement(), GetConnection(), GetSlotInformation(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), initPopulateTable(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_send(), libpqrcv_startstreaming(), main(), my_truncate(), overwrite(), pgfdw_cancel_query_end(), pgfdw_report_error(), pickout(), PQcancelErrorMessage(), prepareCommand(), process_queued_fetch_requests(), process_result(), ProcessXLogDataMsg(), psql_get_variable(), readCommandResponse(), ReceiveCopyData(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_command(), run_permutation(), run_reindex_command(), run_vacuum_command(), RunIdentifySystem(), send_cancellable_query_impl(), sendFeedback(), SendQuery(), sql_conn(), sql_exec(), start_postmaster(), StartRestoreLO(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_cancel(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), threadRun(), try_complete_step(), tryExecuteStatement(), vacuumlo(), verify_btree_slot_handler(), verify_heap_slot_handler(), and wait_for_connection_state().

◆ PQfinish()

void PQfinish ( PGconn conn)

Definition at line 4868 of file fe-connect.c.

4869 {
4870  if (conn)
4871  {
4873  freePGconn(conn);
4874  }
4875 }
void pqClosePGconn(PGconn *conn)
Definition: fe-connect.c:4822
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:4624

References conn, freePGconn(), and pqClosePGconn().

Referenced by appendQualifiedRelation(), BaseBackup(), check_for_data_types_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_loadable_libraries(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_proper_datallowconn(), CheckConnection(), cluster_all_databases(), cluster_one_database(), connect_database(), ConnectDatabase(), connectDatabase(), connectToServer(), create_logical_replication_slots(), disconnect_atexit(), disconnect_database(), DisconnectDatabase(), disconnectDatabase(), do_connect(), doConnect(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpTablespaces(), ecpg_finish(), executeCommand(), executeQuery(), executeQueryOrDie(), exit_nicely(), expand_dbname_patterns(), finishCon(), get_db_infos(), get_db_subscription_count(), get_loadable_libraries(), get_old_cluster_logical_slot_infos(), get_parallel_object_list(), get_rel_infos(), get_tablespace_paths(), get_template0_info(), GetConnection(), libpqrcv_connect(), libpqrcv_disconnect(), libpqsrv_connect_internal(), libpqsrv_disconnect(), LogStreamerMain(), main(), old_9_6_invalidate_hash_indexes(), PQcancelFinish(), PQping(), PQpingParams(), ReconnectToServer(), reindex_all_databases(), reindex_one_database(), report_extension_updates(), run_reindex_command(), runInitSteps(), set_frozenxids(), set_locale_and_encoding(), sql_conn(), sql_exec(), start_postmaster(), StreamLog(), StreamLogicalLog(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

◆ pqFreeCommandQueue()

static void pqFreeCommandQueue ( PGcmdQueueEntry queue)
static

Definition at line 558 of file fe-connect.c.

559 {
560  while (queue != NULL)
561  {
562  PGcmdQueueEntry *cur = queue;
563 
564  queue = cur->next;
565  free(cur->query);
566  free(cur);
567  }
568 }
struct cursor * cur
Definition: ecpg.c:28
struct cursor * next
Definition: type.h:147

References cur, free, and cursor::next.

Referenced by pqDropConnection().

◆ pqGetHomeDirectory()

bool pqGetHomeDirectory ( char *  buf,
int  bufsize 
)

Definition at line 7655 of file fe-connect.c.

7656 {
7657 #ifndef WIN32
7658  const char *home;
7659 
7660  home = getenv("HOME");
7661  if (home == NULL || home[0] == '\0')
7662  return pg_get_user_home_dir(geteuid(), buf, bufsize);
7663  strlcpy(buf, home, bufsize);
7664  return true;
7665 #else
7666  char tmppath[MAX_PATH];
7667 
7668  ZeroMemory(tmppath, sizeof(tmppath));
7669  if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7670  return false;
7671  snprintf(buf, bufsize, "%s/postgresql", tmppath);
7672  return true;
7673 #endif
7674 }
#define bufsize
Definition: indent_globs.h:36
bool pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
Definition: user.c:64

References buf, bufsize, pg_get_user_home_dir(), snprintf, and strlcpy().

Referenced by initialize_SSL(), parseServiceInfo(), and pqConnectOptions2().

◆ PQhost()

char* PQhost ( const PGconn conn)

Definition at line 7026 of file fe-connect.c.

7027 {
7028  if (!conn)
7029  return NULL;
7030 
7031  if (conn->connhost != NULL)
7032  {
7033  /*
7034  * Return the verbatim host value provided by user, or hostaddr in its
7035  * lack.
7036  */
7037  if (conn->connhost[conn->whichhost].host != NULL &&
7038  conn->connhost[conn->whichhost].host[0] != '\0')
7039  return conn->connhost[conn->whichhost].host;
7040  else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
7041  conn->connhost[conn->whichhost].hostaddr[0] != '\0')
7042  return conn->connhost[conn->whichhost].hostaddr;
7043  }
7044 
7045  return "";
7046 }

References conn, pg_conn::connhost, pg_conn_host::host, pg_conn_host::hostaddr, and pg_conn::whichhost.

Referenced by do_connect(), exec_command_conninfo(), get_prompt(), libpqrcv_get_senderinfo(), main(), pg_GSS_load_servicename(), and SyncVariables().

◆ PQhostaddr()

char* PQhostaddr ( const PGconn conn)

Definition at line 7049 of file fe-connect.c.

7050 {
7051  if (!conn)
7052  return NULL;
7053 
7054  /* Return the parsed IP address */
7055  if (conn->connhost != NULL && conn->connip != NULL)
7056  return conn->connip;
7057 
7058  return "";
7059 }

References conn, pg_conn::connhost, and pg_conn::connip.

Referenced by do_connect(), and exec_command_conninfo().

◆ pqMakeEmptyPGconn()

PGconn* pqMakeEmptyPGconn ( void  )

Definition at line 4525 of file fe-connect.c.

4526 {
4527  PGconn *conn;
4528 
4529 #ifdef WIN32
4530 
4531  /*
4532  * Make sure socket support is up and running in this process.
4533  *
4534  * Note: the Windows documentation says that we should eventually do a
4535  * matching WSACleanup() call, but experience suggests that that is at
4536  * least as likely to cause problems as fix them. So we don't.
4537  */
4538  static bool wsastartup_done = false;
4539 
4540  if (!wsastartup_done)
4541  {
4542  WSADATA wsaData;
4543 
4544  if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4545  return NULL;
4546  wsastartup_done = true;
4547  }
4548 
4549  /* Forget any earlier error */
4550  WSASetLastError(0);
4551 #endif /* WIN32 */
4552 
4553  conn = (PGconn *) malloc(sizeof(PGconn));
4554  if (conn == NULL)
4555  return conn;
4556 
4557  /* Zero all pointers and booleans */
4558  MemSet(conn, 0, sizeof(PGconn));
4559 
4560  /* install default notice hooks */
4563 
4568  conn->options_valid = false;
4569  conn->nonblocking = false;
4571  conn->std_strings = false; /* unless server says differently */
4578  conn->Pfdebug = NULL;
4579 
4580  /*
4581  * We try to send at least 8K at a time, which is the usual size of pipe
4582  * buffers on Unix systems. That way, when we are sending a large amount
4583  * of data, we avoid incurring extra kernel context swaps for partial
4584  * bufferloads. The output buffer is initially made 16K in size, and we
4585  * try to dump it after accumulating 8K.
4586  *
4587  * With the same goal of minimizing context swaps, the input buffer will
4588  * be enlarged anytime it has less than 8K free, so we initially allocate
4589  * twice that.
4590  */
4591  conn->inBufSize = 16 * 1024;
4592  conn->inBuffer = (char *) malloc(conn->inBufSize);
4593  conn->outBufSize = 16 * 1024;
4594  conn->outBuffer = (char *) malloc(conn->outBufSize);
4595  conn->rowBufLen = 32;
4596  conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
4599 
4600  if (conn->inBuffer == NULL ||
4601  conn->outBuffer == NULL ||
4602  conn->rowBuf == NULL ||
4605  {
4606  /* out of memory already :-( */
4607  freePGconn(conn);
4608  conn = NULL;
4609  }
4610 
4611  return conn;
4612 }
static void defaultNoticeReceiver(void *arg, const PGresult *res)
Definition: fe-connect.c:7349
static void defaultNoticeProcessor(void *arg, const char *message)
Definition: fe-connect.c:7364
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:140
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:132
PQnoticeReceiver noticeRec
Definition: libpq-int.h:155
int inBufSize
Definition: libpq-int.h:525
PGVerbosity verbosity
Definition: libpq-int.h:517
int rowBufLen
Definition: libpq-int.h:542
int outBufSize
Definition: libpq-int.h:532
PGNoticeHooks noticeHooks
Definition: libpq-int.h:430
FILE * Pfdebug
Definition: libpq-int.h:426
PGContextVisibility show_context
Definition: libpq-int.h:518

References pg_conn::asyncStatus, pg_conn::client_encoding, conn, CONNECTION_BAD, pg_conn::default_transaction_read_only, defaultNoticeProcessor(), defaultNoticeReceiver(), pg_conn::errorMessage, freePGconn(), pg_conn::in_hot_standby, pg_conn::inBuffer, pg_conn::inBufSize, initPQExpBuffer(), malloc, MemSet, pg_conn::nonblocking, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, PGNoticeHooks::noticeRec, pg_conn::options_valid, pg_conn::outBuffer, pg_conn::outBufSize, pg_conn::Pfdebug, PG_BOOL_UNKNOWN, PG_SQL_ASCII, PGASYNC_IDLE, PGINVALID_SOCKET, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQERRORS_DEFAULT, PQExpBufferBroken, PQSHOW_CONTEXT_ERRORS, PQTRANS_IDLE, pg_conn::rowBuf, pg_conn::rowBufLen, SCRAM_SHA_256_DEFAULT_ITERATIONS, pg_conn::scram_sha_256_iterations, pg_conn::show_context, pg_conn::sock, pg_conn::status, pg_conn::std_strings, pg_conn::verbosity, pg_conn::workBuffer, and pg_conn::xactStatus.

Referenced by PQcancelCreate(), PQconnectStart(), PQconnectStartParams(), and PQsetdbLogin().

◆ PQoptions()

char* PQoptions ( const PGconn conn)

Definition at line 7086 of file fe-connect.c.

7087 {
7088  if (!conn)
7089  return NULL;
7090  return conn->pgoptions;
7091 }

References conn, and pg_conn::pgoptions.

◆ pqPacketSend()

int pqPacketSend ( PGconn conn,
char  pack_type,
const void *  buf,
size_t  buf_len 
)

Definition at line 4976 of file fe-connect.c.

4978 {
4979  /* Start the message. */
4980  if (pqPutMsgStart(pack_type, conn))
4981  return STATUS_ERROR;
4982 
4983  /* Send the message body. */
4984  if (pqPutnchar(buf, buf_len, conn))
4985  return STATUS_ERROR;
4986 
4987  /* Finish the message. */
4988  if (pqPutMsgEnd(conn))
4989  return STATUS_ERROR;
4990 
4991  /* Flush to ensure backend gets it. */
4992  if (pqFlush(conn))
4993  return STATUS_ERROR;
4994 
4995  return STATUS_OK;
4996 }
#define STATUS_ERROR
Definition: c.h:1170
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:458
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:202
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:517

References buf, conn, pqFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), STATUS_ERROR, and STATUS_OK.

Referenced by pg_password_sendauth(), pg_SASL_continue(), and PQconnectPoll().

◆ PQparameterStatus()

const char* PQparameterStatus ( const PGconn conn,
const char *  paramName 
)

Definition at line 7112 of file fe-connect.c.

7113 {
7114  const pgParameterStatus *pstatus;
7115 
7116  if (!conn || !paramName)
7117  return NULL;
7118  for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
7119  {
7120  if (strcmp(pstatus->name, paramName) == 0)
7121  return pstatus->value;
7122  }
7123  return NULL;
7124 }

References conn, pgParameterStatus::name, pgParameterStatus::next, pg_conn::pstatus, and pgParameterStatus::value.

Referenced by _check_database_version(), applyRemoteGucs(), BaseBackup(), CheckServerVersionForStreaming(), connectDatabase(), connection_warnings(), ecpg_build_params(), GetConnection(), is_superuser(), main(), printVersion(), session_username(), setup_connection(), standard_strings(), and SyncVariables().

◆ pqParseIntParam()

bool pqParseIntParam ( const char *  value,
int *  result,
PGconn conn,
const char *  context 
)

Definition at line 7682 of file fe-connect.c.

7684 {
7685  char *end;
7686  long numval;
7687 
7688  Assert(value != NULL);
7689 
7690  *result = 0;
7691 
7692  /* strtol(3) skips leading whitespaces */
7693  errno = 0;
7694  numval = strtol(value, &end, 10);
7695 
7696  /*
7697  * If no progress was done during the parsing or an error happened, fail.
7698  * This tests properly for overflows of the result.
7699  */
7700  if (value == end || errno != 0 || numval != (int) numval)
7701  goto error;
7702 
7703  /*
7704  * Skip any trailing whitespace; if anything but whitespace remains before
7705  * the terminating character, fail
7706  */
7707  while (*end != '\0' && isspace((unsigned char) *end))
7708  end++;
7709 
7710  if (*end != '\0')
7711  goto error;
7712 
7713  *result = numval;
7714  return true;
7715 
7716 error:
7717  libpq_append_conn_error(conn, "invalid integer value \"%s\" for connection option \"%s\"",
7718  value, context);
7719  return false;
7720 }
tree context
Definition: radixtree.h:1833
static void error(void)
Definition: sql-dyntest.c:147

References Assert, conn, context, error(), libpq_append_conn_error(), and value.

Referenced by pqConnectDBComplete(), PQconnectPoll(), PQgetCancel(), setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), and setTCPUserTimeout().

◆ PQpass()

char* PQpass ( const PGconn conn)

Definition at line 7009 of file fe-connect.c.

7010 {
7011  char *password = NULL;
7012 
7013  if (!conn)
7014  return NULL;
7015  if (conn->connhost != NULL)
7017  if (password == NULL)
7018  password = conn->pgpass;
7019  /* Historically we've returned "" not NULL for no password specified */
7020  if (password == NULL)
7021  password = "";
7022  return password;
7023 }

References conn, pg_conn::connhost, password, pg_conn_host::password, pg_conn::pgpass, and pg_conn::whichhost.

Referenced by ConnectDatabase(), and PQconnectionNeedsPassword().

◆ PQping()

PGPing PQping ( const char *  conninfo)

Definition at line 760 of file fe-connect.c.

761 {
762  PGconn *conn = PQconnectStart(conninfo);
763  PGPing ret;
764 
765  ret = internal_ping(conn);
766  PQfinish(conn);
767 
768  return ret;
769 }
static PGPing internal_ping(PGconn *conn)
Definition: fe-connect.c:4461
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4868
PGPing
Definition: libpq-fe.h:150

References conn, internal_ping(), PQconnectStart(), and PQfinish().

◆ PQpingParams()

PGPing PQpingParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 707 of file fe-connect.c.

710 {
711  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
712  PGPing ret;
713 
714  ret = internal_ping(conn);
715  PQfinish(conn);
716 
717  return ret;
718 }

References conn, internal_ping(), PQconnectStartParams(), PQfinish(), and values.

Referenced by main(), and regression_main().

◆ PQpipelineStatus()

PGpipelineStatus PQpipelineStatus ( const PGconn conn)

◆ PQport()

char* PQport ( const PGconn conn)

Definition at line 7062 of file fe-connect.c.

7063 {
7064  if (!conn)
7065  return NULL;
7066 
7067  if (conn->connhost != NULL)
7068  return conn->connhost[conn->whichhost].port;
7069 
7070  return "";
7071 }

References conn, pg_conn::connhost, pg_conn_host::port, and pg_conn::whichhost.

Referenced by do_connect(), exec_command_conninfo(), get_prompt(), libpqrcv_get_senderinfo(), main(), and SyncVariables().

◆ PQprotocolVersion()

int PQprotocolVersion ( const PGconn conn)

Definition at line 7127 of file fe-connect.c.

7128 {
7129  if (!conn)
7130  return 0;
7131  if (conn->status == CONNECTION_BAD)
7132  return 0;
7133  return PG_PROTOCOL_MAJOR(conn->pversion);
7134 }
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:87

References conn, CONNECTION_BAD, PG_PROTOCOL_MAJOR, pg_conn::pversion, and pg_conn::status.

Referenced by handleCopyIn().

◆ PQregisterThreadLock()

pgthreadlock_t PQregisterThreadLock ( pgthreadlock_t  newhandler)

Definition at line 7750 of file fe-connect.c.

7751 {
7753 
7754  if (newhandler)
7755  pg_g_threadlock = newhandler;
7756  else
7758 
7759  return prev;
7760 }
static void default_threadlock(int acquire)
Definition: fe-connect.c:7733
pgthreadlock_t pg_g_threadlock
Definition: fe-connect.c:455
void(* pgthreadlock_t)(int acquire)
Definition: libpq-fe.h:432

References default_threadlock(), and pg_g_threadlock.

◆ pqReleaseConnHosts()

void pqReleaseConnHosts ( PGconn conn)

Definition at line 4706 of file fe-connect.c.

4707 {
4708  if (conn->connhost)
4709  {
4710  for (int i = 0; i < conn->nconnhost; ++i)
4711  {
4712  free(conn->connhost[i].host);
4714  free(conn->connhost[i].port);
4715  if (conn->connhost[i].password != NULL)
4716  {
4718  strlen(conn->connhost[i].password));
4720  }
4721  }
4722  free(conn->connhost);
4723  }
4724 }

References conn, pg_conn::connhost, explicit_bzero(), free, pg_conn_host::host, pg_conn_host::hostaddr, i, pg_conn::nconnhost, pg_conn_host::password, and pg_conn_host::port.

Referenced by freePGconn(), and PQcancelCreate().

◆ PQreset()

void PQreset ( PGconn conn)

Definition at line 4882 of file fe-connect.c.

4883 {
4884  if (conn)
4885  {
4887 
4889  {
4890  /*
4891  * Notify event procs of successful reset.
4892  */
4893  int i;
4894 
4895  for (i = 0; i < conn->nEvents; i++)
4896  {
4897  PGEventConnReset evt;
4898 
4899  evt.conn = conn;
4900  (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4901  conn->events[i].passThrough);
4902  }
4903  }
4904  }
4905 }
@ PGEVT_CONNRESET
Definition: libpq-events.h:30

References conn, PGEventConnReset::conn, pg_conn::events, i, pg_conn::nEvents, PGEvent::passThrough, PGEVT_CONNRESET, pqClosePGconn(), pqConnectDBComplete(), pqConnectDBStart(), and PGEvent::proc.

Referenced by CheckConnection().

◆ PQresetPoll()

PostgresPollingStatusType PQresetPoll ( PGconn conn)

Definition at line 4934 of file fe-connect.c.

4935 {
4936  if (conn)
4937  {
4939 
4940  if (status == PGRES_POLLING_OK)
4941  {
4942  /*
4943  * Notify event procs of successful reset.
4944  */
4945  int i;
4946 
4947  for (i = 0; i < conn->nEvents; i++)
4948  {
4949  PGEventConnReset evt;
4950 
4951  evt.conn = conn;
4952  (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4953  conn->events[i].passThrough);
4954  }
4955  }
4956 
4957  return status;
4958  }
4959 
4960  return PGRES_POLLING_FAILED;
4961 }

References conn, PGEventConnReset::conn, pg_conn::events, i, pg_conn::nEvents, PGEvent::passThrough, PGEVT_CONNRESET, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PQconnectPoll(), and PGEvent::proc.

◆ PQresetStart()

int PQresetStart ( PGconn conn)

Definition at line 4915 of file fe-connect.c.

4916 {
4917  if (conn)
4918  {
4920 
4921  return pqConnectDBStart(conn);
4922  }
4923 
4924  return 0;
4925 }

References conn, pqClosePGconn(), and pqConnectDBStart().

◆ PQserverVersion()

◆ PQsetClientEncoding()

int PQsetClientEncoding ( PGconn conn,
const char *  encoding 
)

Definition at line 7243 of file fe-connect.c.

7244 {
7245  char qbuf[128];
7246  static const char query[] = "set client_encoding to '%s'";
7247  PGresult *res;
7248  int status;
7249 
7250  if (!conn || conn->status != CONNECTION_OK)
7251  return -1;
7252 
7253  if (!encoding)
7254  return -1;
7255 
7256  /* Resolve special "auto" value from the locale */
7257  if (strcmp(encoding, "auto") == 0)
7259 
7260  /* check query buffer overflow */
7261  if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
7262  return -1;
7263 
7264  /* ok, now send a query */
7265  sprintf(qbuf, query, encoding);
7266  res = PQexec(conn, qbuf);
7267 
7268  if (res == NULL)
7269  return -1;
7271  status = -1;
7272  else
7273  {
7274  /*
7275  * We rely on the backend to report the parameter value, and we'll
7276  * change state at that time.
7277  */
7278  status = 0; /* everything is ok */
7279  }
7280  PQclear(res);
7281  return status;
7282 }
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:100
int32 encoding
Definition: pg_database.h:41
#define sprintf
Definition: port.h:240

References conn, CONNECTION_OK, encoding, pg_encoding_to_char, pg_get_encoding_from_locale(), PGRES_COMMAND_OK, PQclear(), PQexec(), res, pg_result::resultStatus, sprintf, and pg_conn::status.

Referenced by dblink_connect(), dblink_get_conn(), exec_command_encoding(), main(), and setup_connection().

◆ PQsetdbLogin()

PGconn* PQsetdbLogin ( const char *  pghost,
const char *  pgport,
const char *  pgoptions,
const char *  pgtty,
const char *  dbName,
const char *  login,
const char *  pwd 
)

Definition at line 1901 of file fe-connect.c.

1904 {
1905  PGconn *conn;
1906 
1907  /*
1908  * Allocate memory for the conn structure. Note that we also expect this
1909  * to initialize conn->errorMessage to empty. All subsequent steps during
1910  * connection initialization will only append to that buffer.
1911  */
1912  conn = pqMakeEmptyPGconn();
1913  if (conn == NULL)
1914  return NULL;
1915 
1916  /*
1917  * If the dbName parameter contains what looks like a connection string,
1918  * parse it into conn struct using connectOptions1.
1919  */
1921  {
1922  if (!connectOptions1(conn, dbName))
1923  return conn;
1924  }
1925  else
1926  {
1927  /*
1928  * Old-style path: first, parse an empty conninfo string in order to
1929  * set up the same defaults that PQconnectdb() would use.
1930  */
1931  if (!connectOptions1(conn, ""))
1932  return conn;
1933 
1934  /* Insert dbName parameter value into struct */
1935  if (dbName && dbName[0] != '\0')
1936  {
1937  free(conn->dbName);
1938  conn->dbName = strdup(dbName);
1939  if (!conn->dbName)
1940  goto oom_error;
1941  }
1942  }
1943 
1944  /*
1945  * Insert remaining parameters into struct, overriding defaults (as well
1946  * as any conflicting data from dbName taken as a conninfo).
1947  */
1948  if (pghost && pghost[0] != '\0')
1949  {
1950  free(conn->pghost);
1951  conn->pghost = strdup(pghost);
1952  if (!conn->pghost)
1953  goto oom_error;
1954  }
1955 
1956  if (pgport && pgport[0] != '\0')
1957  {
1958  free(conn->pgport);
1959  conn->pgport = strdup(pgport);
1960  if (!conn->pgport)
1961  goto oom_error;
1962  }
1963 
1964  if (pgoptions && pgoptions[0] != '\0')
1965  {
1966  free(conn->pgoptions);
1967  conn->pgoptions = strdup(pgoptions);
1968  if (!conn->pgoptions)
1969  goto oom_error;
1970  }
1971 
1972  if (login && login[0] != '\0')
1973  {
1974  free(conn->pguser);
1975  conn->pguser = strdup(login);
1976  if (!conn->pguser)
1977  goto oom_error;
1978  }
1979 
1980  if (pwd && pwd[0] != '\0')
1981  {
1982  free(conn->pgpass);
1983  conn->pgpass = strdup(pwd);
1984  if (!conn->pgpass)
1985  goto oom_error;
1986  }
1987 
1988  /*
1989  * Compute derived options
1990  */
1991  if (!pqConnectOptions2(conn))
1992  return conn;
1993 
1994  /*
1995  * Connect to the database
1996  */
1997  if (pqConnectDBStart(conn))
1998  (void) pqConnectDBComplete(conn);
1999 
2000  return conn;
2001 
2002 oom_error:
2004  libpq_append_conn_error(conn, "out of memory");
2005  return conn;
2006 }
const char * pghost
Definition: pgbench.c:294
const char * pgport
Definition: pgbench.c:295
const char * dbName
Definition: pgbench.c:297

References conn, CONNECTION_BAD, connectOptions1(), dbName, pg_conn::dbName, free, libpq_append_conn_error(), pghost, pg_conn::pghost, pg_conn::pgoptions, pg_conn::pgpass, pgport, pg_conn::pgport, pg_conn::pguser, pqConnectDBComplete(), pqConnectDBStart(), pqConnectOptions2(), pqMakeEmptyPGconn(), recognized_connection_string(), and pg_conn::status.

◆ PQsetErrorContextVisibility()

PGContextVisibility PQsetErrorContextVisibility ( PGconn conn,
PGContextVisibility  show_context 
)

Definition at line 7297 of file fe-connect.c.

7298 {
7299  PGContextVisibility old;
7300 
7301  if (!conn)
7302  return PQSHOW_CONTEXT_ERRORS;
7303  old = conn->show_context;
7304  conn->show_context = show_context;
7305  return old;
7306 }
PGContextVisibility
Definition: libpq-fe.h:138

References conn, PQSHOW_CONTEXT_ERRORS, and pg_conn::show_context.

Referenced by show_context_hook(), and SyncVariables().

◆ PQsetErrorVerbosity()

PGVerbosity PQsetErrorVerbosity ( PGconn conn,
PGVerbosity  verbosity 
)

Definition at line 7285 of file fe-connect.c.

7286 {
7287  PGVerbosity old;
7288 
7289  if (!conn)
7290  return PQERRORS_DEFAULT;
7291  old = conn->verbosity;
7292  conn->verbosity = verbosity;
7293  return old;
7294 }
PGVerbosity
Definition: libpq-fe.h:130

References conn, PQERRORS_DEFAULT, and pg_conn::verbosity.

Referenced by main(), SyncVariables(), and verbosity_hook().

◆ PQsetNoticeProcessor()

PQnoticeProcessor PQsetNoticeProcessor ( PGconn conn,
PQnoticeProcessor  proc,
void *  arg 
)

Definition at line 7326 of file fe-connect.c.

7327 {
7328  PQnoticeProcessor old;
7329 
7330  if (conn == NULL)
7331  return NULL;
7332 
7333  old = conn->noticeHooks.noticeProc;
7334  if (proc)
7335  {
7336  conn->noticeHooks.noticeProc = proc;
7338  }
7339  return old;
7340 }
void(* PQnoticeProcessor)(void *arg, const char *message)
Definition: libpq-fe.h:207

References arg, conn, pg_conn::noticeHooks, PGNoticeHooks::noticeProc, and PGNoticeHooks::noticeProcArg.

Referenced by ConnectDatabase(), do_connect(), main(), and test_pipeline_idle().

◆ PQsetNoticeReceiver()

PQnoticeReceiver PQsetNoticeReceiver ( PGconn conn,
PQnoticeReceiver  proc,
void *  arg 
)

Definition at line 7309 of file fe-connect.c.

7310 {
7311  PQnoticeReceiver old;
7312 
7313  if (conn == NULL)
7314  return NULL;
7315 
7316  old = conn->noticeHooks.noticeRec;
7317  if (proc)
7318  {
7319  conn->noticeHooks.noticeRec = proc;
7321  }
7322  return old;
7323 }
void(* PQnoticeReceiver)(void *arg, const PGresult *res)
Definition: libpq-fe.h:206
void * noticeRecArg
Definition: libpq-int.h:156

References arg, conn, pg_conn::noticeHooks, PGNoticeHooks::noticeRec, and PGNoticeHooks::noticeRecArg.

Referenced by ECPGconnect().

◆ PQsocket()

◆ PQstatus()

◆ PQtransactionStatus()

◆ PQtty()

char* PQtty ( const PGconn conn)

Definition at line 7078 of file fe-connect.c.

7079 {
7080  if (!conn)
7081  return NULL;
7082  return "";
7083 }

References conn.

◆ PQuser()

char* PQuser ( const PGconn conn)

Definition at line 7001 of file fe-connect.c.

7002 {
7003  if (!conn)
7004  return NULL;
7005  return conn->pguser;
7006 }

References conn, and pg_conn::pguser.

Referenced by do_connect(), exec_command_conninfo(), get_prompt(), main(), session_username(), and SyncVariables().

◆ pwdfMatchesString()

static char * pwdfMatchesString ( char *  buf,
const char *  token 
)
static

Definition at line 7376 of file fe-connect.c.

7377 {
7378  char *tbuf;
7379  const char *ttok;
7380  bool bslash = false;
7381 
7382  if (buf == NULL || token == NULL)
7383  return NULL;
7384  tbuf = buf;
7385  ttok = token;
7386  if (tbuf[0] == '*' && tbuf[1] == ':')
7387  return tbuf + 2;
7388  while (*tbuf != 0)
7389  {
7390  if (*tbuf == '\\' && !bslash)
7391  {
7392  tbuf++;
7393  bslash = true;
7394  }
7395  if (*tbuf == ':' && *ttok == 0 && !bslash)
7396  return tbuf + 1;
7397  bslash = false;
7398  if (*ttok == 0)
7399  return NULL;
7400  if (*tbuf == *ttok)
7401  {
7402  tbuf++;
7403  ttok++;
7404  }
7405  else
7406  return NULL;
7407  }
7408  return NULL;
7409 }
#define token
Definition: indent_globs.h:126

References buf, and token.

Referenced by passwordFromFile().

◆ recognized_connection_string()

static bool recognized_connection_string ( const char *  connstr)
static

Definition at line 5832 of file fe-connect.c.

5833 {
5834  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
5835 }

References connstr, and uri_prefix_length().

Referenced by conninfo_array_parse(), and PQsetdbLogin().

◆ release_conn_addrinfo()

static void release_conn_addrinfo ( PGconn conn)
static

Definition at line 4774 of file fe-connect.c.

4775 {
4776  if (conn->addr)
4777  {
4778  free(conn->addr);
4779  conn->addr = NULL;
4780  }
4781 }

References pg_conn::addr, conn, and free.

Referenced by freePGconn(), pqClosePGconn(), and PQconnectPoll().

◆ select_next_encryption_method()

static bool select_next_encryption_method ( PGconn conn,
bool  have_valid_connection 
)
static

Definition at line 4380 of file fe-connect.c.

4381 {
4382  int remaining_methods;
4383 
4384 #define SELECT_NEXT_METHOD(method) \
4385  do { \
4386  if ((remaining_methods & method) != 0) \
4387  { \
4388  conn->current_enc_method = method; \
4389  return true; \
4390  } \
4391  } while (false)
4392 
4393  remaining_methods = conn->allowed_enc_methods & ~conn->failed_enc_methods;
4394 
4395  /*
4396  * Try GSSAPI before SSL
4397  */
4398 #ifdef ENABLE_GSS
4399  if ((remaining_methods & ENC_GSSAPI) != 0)
4400  {
4401  /*
4402  * If GSSAPI encryption is enabled, then call pg_GSS_have_cred_cache()
4403  * which will return true if we can acquire credentials (and give us a
4404  * handle to use in conn->gcred), and then send a packet to the server
4405  * asking for GSSAPI Encryption (and skip past SSL negotiation and
4406  * regular startup below).
4407  */
4408  if (!conn->gctx)
4409  {
4410  if (!pg_GSS_have_cred_cache(&conn->gcred))
4411  {
4413  remaining_methods &= ~ENC_GSSAPI;
4414 
4415  if (conn->gssencmode[0] == 'r')
4416  {
4418  "GSSAPI encryption required but no credential cache");
4419  }
4420  }
4421  }
4422  }
4423 
4425 #endif
4426 
4427  /* With sslmode=allow, try plaintext connection before SSL. */
4428  if (conn->sslmode[0] == 'a')
4430 
4431  /*
4432  * If enabled, try direct SSL. Unless we have a valid TCP connection that
4433  * failed negotiating GSSAPI encryption or a plaintext connection in case
4434  * of sslmode='allow'; in that case we prefer to reuse the connection with
4435  * negotiated SSL, instead of reconnecting to do direct SSL. The point of
4436  * direct SSL is to avoid the roundtrip from the negotiation, but
4437  * reconnecting would also incur a roundtrip.
4438  */
4439  if (have_valid_connection)
4441 
4444 
4445  if (conn->sslmode[0] != 'a')
4447 
4448  /* No more options */
4450  return false;
4451 #undef SELECT_NEXT_METHOD
4452 }
#define SELECT_NEXT_METHOD(method)

References pg_conn::allowed_enc_methods, conn, pg_conn::current_enc_method, ENC_DIRECT_SSL, ENC_ERROR, ENC_GSSAPI, ENC_NEGOTIATED_SSL, ENC_PLAINTEXT, pg_conn::failed_enc_methods, pg_conn::gssencmode, libpq_append_conn_error(), pg_GSS_have_cred_cache(), SELECT_NEXT_METHOD, and pg_conn::sslmode.

Referenced by connection_failed(), and init_allowed_encryption_methods().

◆ sendTerminateConn()

static void sendTerminateConn ( PGconn conn)
static

Definition at line 4788 of file fe-connect.c.

4789 {
4790  /*
4791  * The Postgres cancellation protocol does not have a notion of a
4792  * Terminate message, so don't send one.
4793  */
4794  if (conn->cancelRequest)
4795  return;
4796 
4797  /*
4798  * Note that the protocol doesn't allow us to send Terminate messages
4799  * during the startup phase.
4800  */
4802  {
4803  /*
4804  * Try to send "close connection" message to backend. Ignore any
4805  * error.
4806  */
4808  pqPutMsgEnd(conn);
4809  (void) pqFlush(conn);
4810  }
4811 }
#define PqMsg_Terminate
Definition: protocol.h:28

References pg_conn::cancelRequest, conn, CONNECTION_OK, PGINVALID_SOCKET, pqFlush(), PqMsg_Terminate, pqPutMsgEnd(), pqPutMsgStart(), pg_conn::sock, and pg_conn::status.

Referenced by pqClosePGconn(), and PQconnectPoll().

◆ setKeepalivesCount()

static int setKeepalivesCount ( PGconn conn)
static

Definition at line 2238 of file fe-connect.c.

2239 {
2240  int count;
2241 
2242  if (conn->keepalives_count == NULL)
2243  return 1;
2244 
2245  if (!pqParseIntParam(conn->keepalives_count, &count, conn,
2246  "keepalives_count"))
2247  return 0;
2248  if (count < 0)
2249  count = 0;
2250 
2251 #ifdef TCP_KEEPCNT
2252  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
2253  (char *) &count, sizeof(count)) < 0)
2254  {
2255  char sebuf[PG_STRERROR_R_BUFLEN];
2256 
2257  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2258  "setsockopt",
2259  "TCP_KEEPCNT",
2260  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2261  return 0;
2262  }
2263 #endif
2264 
2265  return 1;
2266 }

References conn, pg_conn::keepalives_count, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, pqParseIntParam(), pg_conn::sock, SOCK_ERRNO, and SOCK_STRERROR.

Referenced by PQconnectPoll().

◆ setKeepalivesIdle()

static int setKeepalivesIdle ( PGconn conn)
static

Definition at line 2169 of file fe-connect.c.

2170 {
2171  int idle;
2172 
2173  if (conn->keepalives_idle == NULL)
2174  return 1;
2175 
2176  if (!pqParseIntParam(conn->keepalives_idle, &idle, conn,
2177  "keepalives_idle"))
2178  return 0;
2179  if (idle < 0)
2180  idle = 0;
2181 
2182 #ifdef PG_TCP_KEEPALIVE_IDLE
2183  if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2184  (char *) &idle, sizeof(idle)) < 0)
2185  {
2186  char sebuf[PG_STRERROR_R_BUFLEN];
2187 
2188  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2189  "setsockopt",
2190  PG_TCP_KEEPALIVE_IDLE_STR,
2191  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2192  return 0;
2193  }
2194 #endif
2195 
2196  return 1;
2197 }

References conn, pg_conn::keepalives_idle, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, pqParseIntParam(), pg_conn::sock, SOCK_ERRNO, and SOCK_STRERROR.

Referenced by PQconnectPoll().

◆ setKeepalivesInterval()

static int setKeepalivesInterval ( PGconn conn)
static

Definition at line 2203 of file fe-connect.c.

2204 {
2205  int interval;
2206 
2207  if (conn->keepalives_interval == NULL)
2208  return 1;
2209 
2211  "keepalives_interval"))
2212  return 0;
2213  if (interval < 0)
2214  interval = 0;
2215 
2216 #ifdef TCP_KEEPINTVL
2217  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
2218  (char *) &interval, sizeof(interval)) < 0)
2219  {
2220  char sebuf[PG_STRERROR_R_BUFLEN];
2221 
2222  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2223  "setsockopt",
2224  "TCP_KEEPINTVL",
2225  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2226  return 0;
2227  }
2228 #endif
2229 
2230  return 1;
2231 }

References conn, pg_conn::keepalives_interval, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, pqParseIntParam(), pg_conn::sock, SOCK_ERRNO, and SOCK_STRERROR.

Referenced by PQconnectPoll().

◆ setTCPUserTimeout()

static int setTCPUserTimeout ( PGconn conn)
static

Definition at line 2335 of file fe-connect.c.

2336 {
2337  int timeout;
2338 
2339  if (conn->pgtcp_user_timeout == NULL)
2340  return 1;
2341 
2342  if (!pqParseIntParam(conn->pgtcp_user_timeout, &timeout, conn,
2343  "tcp_user_timeout"))
2344  return 0;
2345 
2346  if (timeout < 0)
2347  timeout = 0;
2348 
2349 #ifdef TCP_USER_TIMEOUT
2350  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2351  (char *) &timeout, sizeof(timeout)) < 0)
2352  {
2353  char sebuf[256];
2354 
2355  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2356  "setsockopt",
2357  "TCP_USER_TIMEOUT",
2358  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2359  return 0;
2360  }
2361 #endif
2362 
2363  return 1;
2364 }

References conn, libpq_append_conn_error(), pg_conn::pgtcp_user_timeout, pqParseIntParam(), pg_conn::sock, SOCK_ERRNO, and SOCK_STRERROR.

Referenced by PQconnectPoll().

◆ sslVerifyProtocolRange()

static bool sslVerifyProtocolRange ( const char *  min,
const char *  max 
)
static

Definition at line 7602 of file fe-connect.c.

7603 {
7606 
7607  /* If at least one of the bounds is not set, the range is valid */
7608  if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
7609  return true;
7610 
7611  /*
7612  * If the minimum version is the lowest one we accept, then all options
7613  * for the maximum are valid.
7614  */
7615  if (pg_strcasecmp(min, "TLSv1") == 0)
7616  return true;
7617 
7618  /*
7619  * The minimum bound is valid, and cannot be TLSv1, so using TLSv1 for the
7620  * maximum is incorrect.
7621  */
7622  if (pg_strcasecmp(max, "TLSv1") == 0)
7623  return false;
7624 
7625  /*
7626  * At this point we know that we have a mix of TLSv1.1 through 1.3
7627  * versions.
7628  */
7629  if (pg_strcasecmp(min, max) > 0)
7630  return false;
7631 
7632  return true;
7633 }
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36

References Assert, pg_strcasecmp(), and sslVerifyProtocolVersion().

Referenced by pqConnectOptions2().

◆ sslVerifyProtocolVersion()

static bool sslVerifyProtocolVersion ( const char *  version)
static

Definition at line 7576 of file fe-connect.c.

7577 {
7578  /*
7579  * An empty string and a NULL value are considered valid as it is
7580  * equivalent to ignoring the parameter.
7581  */
7582  if (!version || strlen(version) == 0)
7583  return true;
7584 
7585  if (pg_strcasecmp(version, "TLSv1") == 0 ||
7586  pg_strcasecmp(version, "TLSv1.1") == 0 ||
7587  pg_strcasecmp(version, "TLSv1.2") == 0 ||
7588  pg_strcasecmp(version, "TLSv1.3") == 0)
7589  return true;
7590 
7591  /* anything else is wrong */
7592  return false;
7593 }

References pg_strcasecmp().

Referenced by pqConnectOptions2(), and sslVerifyProtocolRange().

◆ store_conn_addrinfo()

static int store_conn_addrinfo ( PGconn conn,
struct addrinfo *  addrlist 
)
static

Definition at line 4735 of file fe-connect.c.

4736 {
4737  struct addrinfo *ai = addrlist;
4738 
4739  conn->whichaddr = 0;
4740 
4741  conn->naddr = 0;
4742  while (ai)
4743  {
4744  ai = ai->ai_next;
4745  conn->naddr++;
4746  }
4747 
4748  conn->addr = calloc(conn->naddr, sizeof(AddrInfo));
4749  if (conn->addr == NULL)
4750  {
4751  libpq_append_conn_error(conn, "out of memory");
4752  return 1;
4753  }
4754 
4755  ai = addrlist;
4756  for (int i = 0; i < conn->naddr; i++)
4757  {
4758  conn->addr[i].family = ai->ai_family;
4759 
4760  memcpy(&conn->addr[i].addr.addr, ai->ai_addr,
4761  ai->ai_addrlen);
4762  conn->addr[i].addr.salen = ai->ai_addrlen;
4763  ai = ai->ai_next;
4764  }
4765 
4766  return 0;
4767 }

References AddrInfo::addr, SockAddr::addr, pg_conn::addr, calloc, conn, AddrInfo::family, i, libpq_append_conn_error(), pg_conn::naddr, SockAddr::salen, and pg_conn::whichaddr.

Referenced by PQconnectPoll().

◆ uri_prefix_length()

static int uri_prefix_length ( const char *  connstr)
static

Definition at line 5809 of file fe-connect.c.

5810 {
5811  if (strncmp(connstr, uri_designator,
5812  sizeof(uri_designator) - 1) == 0)
5813  return sizeof(uri_designator) - 1;
5814 
5815  if (strncmp(connstr, short_uri_designator,
5816  sizeof(short_uri_designator) - 1) == 0)
5817  return sizeof(short_uri_designator) - 1;
5818 
5819  return 0;
5820 }
static const char short_uri_designator[]
Definition: fe-connect.c:392
static const char uri_designator[]
Definition: fe-connect.c:391

References connstr, short_uri_designator, and uri_designator.

Referenced by conninfo_uri_parse_options(), parse_connection_string(), and recognized_connection_string().

◆ useKeepalives()

static int useKeepalives ( PGconn conn)
static

Definition at line 2151 of file fe-connect.c.

2152 {
2153  char *ep;
2154  int val;
2155 
2156  if (conn->keepalives == NULL)
2157  return 1;
2158  val = strtol(conn->keepalives, &ep, 10);
2159  if (*ep)
2160  return -1;
2161  return val != 0 ? 1 : 0;
2162 }

References conn, pg_conn::keepalives, and val.

Referenced by PQconnectPoll().

Variable Documentation

◆ EnvironmentOptions

const PQEnvironmentOption EnvironmentOptions[]
static
Initial value:
=
{
{
"PGDATESTYLE", "datestyle"
},
{
"PGTZ", "timezone"
},
{
"PGGEQO", "geqo"
},
{
NULL, NULL
}
}

Definition at line 372 of file fe-connect.c.

Referenced by PQconnectPoll().

◆ pg_g_threadlock

Definition at line 455 of file fe-connect.c.

Referenced by PQregisterThreadLock().

◆ PQconninfoOptions

const internalPQconninfoOption PQconninfoOptions[]
static

Definition at line 190 of file fe-connect.c.

Referenced by conninfo_init(), fillPGconn(), PQconninfo(), and pqCopyPGconn().

◆ short_uri_designator

const char short_uri_designator[] = "postgres://"
static

Definition at line 392 of file fe-connect.c.

Referenced by uri_prefix_length().

◆ uri_designator

const char uri_designator[] = "postgresql://"
static

Definition at line 391 of file fe-connect.c.

Referenced by uri_prefix_length().