PostgreSQL Source Code  git master
fe-connect.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * fe-connect.c
4  * functions related to setting up a connection to the backend
5  *
6  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/interfaces/libpq/fe-connect.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres_fe.h"
17 
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <netdb.h>
22 #include <time.h>
23 #include <unistd.h>
24 
25 #include "common/ip.h"
26 #include "common/link-canary.h"
27 #include "common/scram-common.h"
28 #include "common/string.h"
29 #include "fe-auth.h"
30 #include "libpq-fe.h"
31 #include "libpq-int.h"
32 #include "mb/pg_wchar.h"
33 #include "pg_config_paths.h"
34 #include "port/pg_bswap.h"
35 
36 #ifdef WIN32
37 #include "win32.h"
38 #ifdef _WIN32_IE
39 #undef _WIN32_IE
40 #endif
41 #define _WIN32_IE 0x0500
42 #ifdef near
43 #undef near
44 #endif
45 #define near
46 #include <shlobj.h>
47 #include <mstcpip.h>
48 #else
49 #include <sys/socket.h>
50 #include <netdb.h>
51 #include <netinet/in.h>
52 #include <netinet/tcp.h>
53 #include <pwd.h>
54 #endif
55 
56 #ifdef WIN32
57 #include "pthread-win32.h"
58 #else
59 #include <pthread.h>
60 #endif
61 
62 #ifdef USE_LDAP
63 #ifdef WIN32
64 #include <winldap.h>
65 #else
66 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
67 #define LDAP_DEPRECATED 1
68 #include <ldap.h>
69 typedef struct timeval LDAP_TIMEVAL;
70 #endif
71 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
72  PQExpBuffer errorMessage);
73 #endif
74 
75 #ifndef WIN32
76 #define PGPASSFILE ".pgpass"
77 #else
78 #define PGPASSFILE "pgpass.conf"
79 #endif
80 
81 /*
82  * Pre-9.0 servers will return this SQLSTATE if asked to set
83  * application_name in a startup packet. We hard-wire the value rather
84  * than looking into errcodes.h since it reflects historical behavior
85  * rather than that of the current code.
86  */
87 #define ERRCODE_APPNAME_UNKNOWN "42704"
88 
89 /* This is part of the protocol so just define it */
90 #define ERRCODE_INVALID_PASSWORD "28P01"
91 /* This too */
92 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
93 
94 /*
95  * Cope with the various platform-specific ways to spell TCP keepalive socket
96  * options. This doesn't cover Windows, which as usual does its own thing.
97  */
98 #if defined(TCP_KEEPIDLE)
99 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
100 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
101 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
102 #elif defined(TCP_KEEPALIVE_THRESHOLD)
103 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
104 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
105 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
106 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
107 /* TCP_KEEPALIVE is the name of this option on macOS */
108 /* Caution: Solaris has this symbol but it means something different */
109 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
110 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
111 #endif
112 
113 /*
114  * fall back options if they are not specified by arguments or defined
115  * by environment variables
116  */
117 #define DefaultHost "localhost"
118 #define DefaultOption ""
119 #ifdef USE_SSL
120 #define DefaultChannelBinding "prefer"
121 #else
122 #define DefaultChannelBinding "disable"
123 #endif
124 #define DefaultTargetSessionAttrs "any"
125 #define DefaultLoadBalanceHosts "disable"
126 #ifdef USE_SSL
127 #define DefaultSSLMode "prefer"
128 #define DefaultSSLCertMode "allow"
129 #else
130 #define DefaultSSLMode "disable"
131 #define DefaultSSLCertMode "disable"
132 #endif
133 #define DefaultSSLNegotiation "postgres"
134 #ifdef ENABLE_GSS
135 #include "fe-gssapi-common.h"
136 #define DefaultGSSMode "prefer"
137 #else
138 #define DefaultGSSMode "disable"
139 #endif
140 
141 /* ----------
142  * Definition of the conninfo parameters and their fallback resources.
143  *
144  * If Environment-Var and Compiled-in are specified as NULL, no
145  * fallback is available. If after all no value can be determined
146  * for an option, an error is returned.
147  *
148  * The value for the username is treated specially in conninfo_add_defaults.
149  * If the value is not obtained any other way, the username is determined
150  * by pg_fe_getauthname().
151  *
152  * The Label and Disp-Char entries are provided for applications that
153  * want to use PQconndefaults() to create a generic database connection
154  * dialog. Disp-Char is defined as follows:
155  * "" Normal input field
156  * "*" Password field - hide value
157  * "D" Debug option - don't show by default
158  *
159  * PQconninfoOptions[] is a constant static array that we use to initialize
160  * a dynamically allocated working copy. All the "val" fields in
161  * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
162  * fields point to malloc'd strings that should be freed when the working
163  * array is freed (see PQconninfoFree).
164  *
165  * The first part of each struct is identical to the one in libpq-fe.h,
166  * which is required since we memcpy() data between the two!
167  * ----------
168  */
170 {
171  char *keyword; /* The keyword of the option */
172  char *envvar; /* Fallback environment variable name */
173  char *compiled; /* Fallback compiled in default value */
174  char *val; /* Option's current value, or NULL */
175  char *label; /* Label for field in connect dialog */
176  char *dispchar; /* Indicates how to display this field in a
177  * connect dialog. Values are: "" Display
178  * entered value as is "*" Password field -
179  * hide value "D" Debug option - don't show
180  * by default */
181  int dispsize; /* Field size in characters for dialog */
182  /* ---
183  * Anything above this comment must be synchronized with
184  * PQconninfoOption in libpq-fe.h, since we memcpy() data
185  * between them!
186  * ---
187  */
188  off_t connofs; /* Offset into PGconn struct, -1 if not there */
190 
192  {"service", "PGSERVICE", NULL, NULL,
193  "Database-Service", "", 20, -1},
194 
195  {"user", "PGUSER", NULL, NULL,
196  "Database-User", "", 20,
197  offsetof(struct pg_conn, pguser)},
198 
199  {"password", "PGPASSWORD", NULL, NULL,
200  "Database-Password", "*", 20,
201  offsetof(struct pg_conn, pgpass)},
202 
203  {"passfile", "PGPASSFILE", NULL, NULL,
204  "Database-Password-File", "", 64,
205  offsetof(struct pg_conn, pgpassfile)},
206 
207  {"channel_binding", "PGCHANNELBINDING", DefaultChannelBinding, NULL,
208  "Channel-Binding", "", 8, /* sizeof("require") == 8 */
209  offsetof(struct pg_conn, channel_binding)},
210 
211  {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
212  "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
213  offsetof(struct pg_conn, connect_timeout)},
214 
215  {"dbname", "PGDATABASE", NULL, NULL,
216  "Database-Name", "", 20,
217  offsetof(struct pg_conn, dbName)},
218 
219  {"host", "PGHOST", NULL, NULL,
220  "Database-Host", "", 40,
221  offsetof(struct pg_conn, pghost)},
222 
223  {"hostaddr", "PGHOSTADDR", NULL, NULL,
224  "Database-Host-IP-Address", "", 45,
225  offsetof(struct pg_conn, pghostaddr)},
226 
227  {"port", "PGPORT", DEF_PGPORT_STR, NULL,
228  "Database-Port", "", 6,
229  offsetof(struct pg_conn, pgport)},
230 
231  {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
232  "Client-Encoding", "", 10,
233  offsetof(struct pg_conn, client_encoding_initial)},
234 
235  {"options", "PGOPTIONS", DefaultOption, NULL,
236  "Backend-Options", "", 40,
237  offsetof(struct pg_conn, pgoptions)},
238 
239  {"application_name", "PGAPPNAME", NULL, NULL,
240  "Application-Name", "", 64,
241  offsetof(struct pg_conn, appname)},
242 
243  {"fallback_application_name", NULL, NULL, NULL,
244  "Fallback-Application-Name", "", 64,
245  offsetof(struct pg_conn, fbappname)},
246 
247  {"keepalives", NULL, NULL, NULL,
248  "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
249  offsetof(struct pg_conn, keepalives)},
250 
251  {"keepalives_idle", NULL, NULL, NULL,
252  "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
253  offsetof(struct pg_conn, keepalives_idle)},
254 
255  {"keepalives_interval", NULL, NULL, NULL,
256  "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
257  offsetof(struct pg_conn, keepalives_interval)},
258 
259  {"keepalives_count", NULL, NULL, NULL,
260  "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
261  offsetof(struct pg_conn, keepalives_count)},
262 
263  {"tcp_user_timeout", NULL, NULL, NULL,
264  "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
265  offsetof(struct pg_conn, pgtcp_user_timeout)},
266 
267  /*
268  * ssl options are allowed even without client SSL support because the
269  * client can still handle SSL modes "disable" and "allow". Other
270  * parameters have no effect on non-SSL connections, so there is no reason
271  * to exclude them since none of them are mandatory.
272  */
273  {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
274  "SSL-Mode", "", 12, /* sizeof("verify-full") == 12 */
275  offsetof(struct pg_conn, sslmode)},
276 
277  {"sslnegotiation", "PGSSLNEGOTIATION", DefaultSSLNegotiation, NULL,
278  "SSL-Negotiation", "", 9, /* sizeof("postgres") == 9 */
279  offsetof(struct pg_conn, sslnegotiation)},
280 
281  {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
282  "SSL-Compression", "", 1,
283  offsetof(struct pg_conn, sslcompression)},
284 
285  {"sslcert", "PGSSLCERT", NULL, NULL,
286  "SSL-Client-Cert", "", 64,
287  offsetof(struct pg_conn, sslcert)},
288 
289  {"sslkey", "PGSSLKEY", NULL, NULL,
290  "SSL-Client-Key", "", 64,
291  offsetof(struct pg_conn, sslkey)},
292 
293  {"sslcertmode", "PGSSLCERTMODE", NULL, NULL,
294  "SSL-Client-Cert-Mode", "", 8, /* sizeof("disable") == 8 */
295  offsetof(struct pg_conn, sslcertmode)},
296 
297  {"sslpassword", NULL, NULL, NULL,
298  "SSL-Client-Key-Password", "*", 20,
299  offsetof(struct pg_conn, sslpassword)},
300 
301  {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
302  "SSL-Root-Certificate", "", 64,
303  offsetof(struct pg_conn, sslrootcert)},
304 
305  {"sslcrl", "PGSSLCRL", NULL, NULL,
306  "SSL-Revocation-List", "", 64,
307  offsetof(struct pg_conn, sslcrl)},
308 
309  {"sslcrldir", "PGSSLCRLDIR", NULL, NULL,
310  "SSL-Revocation-List-Dir", "", 64,
311  offsetof(struct pg_conn, sslcrldir)},
312 
313  {"sslsni", "PGSSLSNI", "1", NULL,
314  "SSL-SNI", "", 1,
315  offsetof(struct pg_conn, sslsni)},
316 
317  {"requirepeer", "PGREQUIREPEER", NULL, NULL,
318  "Require-Peer", "", 10,
319  offsetof(struct pg_conn, requirepeer)},
320 
321  {"require_auth", "PGREQUIREAUTH", NULL, NULL,
322  "Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */
323  offsetof(struct pg_conn, require_auth)},
324 
325  {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL,
326  "SSL-Minimum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
327  offsetof(struct pg_conn, ssl_min_protocol_version)},
328 
329  {"ssl_max_protocol_version", "PGSSLMAXPROTOCOLVERSION", NULL, NULL,
330  "SSL-Maximum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
331  offsetof(struct pg_conn, ssl_max_protocol_version)},
332 
333  /*
334  * As with SSL, all GSS options are exposed even in builds that don't have
335  * support.
336  */
337  {"gssencmode", "PGGSSENCMODE", DefaultGSSMode, NULL,
338  "GSSENC-Mode", "", 8, /* sizeof("disable") == 8 */
339  offsetof(struct pg_conn, gssencmode)},
340 
341  /* Kerberos and GSSAPI authentication support specifying the service name */
342  {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
343  "Kerberos-service-name", "", 20,
344  offsetof(struct pg_conn, krbsrvname)},
345 
346  {"gsslib", "PGGSSLIB", NULL, NULL,
347  "GSS-library", "", 7, /* sizeof("gssapi") == 7 */
348  offsetof(struct pg_conn, gsslib)},
349 
350  {"gssdelegation", "PGGSSDELEGATION", "0", NULL,
351  "GSS-delegation", "", 1,
352  offsetof(struct pg_conn, gssdelegation)},
353 
354  {"replication", NULL, NULL, NULL,
355  "Replication", "D", 5,
356  offsetof(struct pg_conn, replication)},
357 
358  {"target_session_attrs", "PGTARGETSESSIONATTRS",
360  "Target-Session-Attrs", "", 15, /* sizeof("prefer-standby") = 15 */
361  offsetof(struct pg_conn, target_session_attrs)},
362 
363  {"load_balance_hosts", "PGLOADBALANCEHOSTS",
365  "Load-Balance-Hosts", "", 8, /* sizeof("disable") = 8 */
366  offsetof(struct pg_conn, load_balance_hosts)},
367 
368  /* Terminating entry --- MUST BE LAST */
369  {NULL, NULL, NULL, NULL,
370  NULL, NULL, 0}
371 };
372 
374 {
375  /* common user-interface settings */
376  {
377  "PGDATESTYLE", "datestyle"
378  },
379  {
380  "PGTZ", "timezone"
381  },
382  /* internal performance-related settings */
383  {
384  "PGGEQO", "geqo"
385  },
386  {
387  NULL, NULL
388  }
389 };
390 
391 /* The connection URI must start with either of the following designators: */
392 static const char uri_designator[] = "postgresql://";
393 static const char short_uri_designator[] = "postgres://";
394 
395 static bool connectOptions1(PGconn *conn, const char *conninfo);
397 #if defined(USE_SSL) || defined(ENABLE_GSS)
398 static int encryption_negotiation_failed(PGconn *conn);
399 #endif
400 static bool connection_failed(PGconn *conn);
401 static bool select_next_encryption_method(PGconn *conn, bool have_valid_connection);
403 static void pqFreeCommandQueue(PGcmdQueueEntry *queue);
404 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
405 static void freePGconn(PGconn *conn);
406 static void release_conn_addrinfo(PGconn *conn);
407 static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist);
408 static void sendTerminateConn(PGconn *conn);
409 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
411  PQExpBuffer errorMessage, bool use_defaults);
412 static int uri_prefix_length(const char *connstr);
413 static bool recognized_connection_string(const char *connstr);
414 static PQconninfoOption *conninfo_parse(const char *conninfo,
415  PQExpBuffer errorMessage, bool use_defaults);
416 static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
417  const char *const *values, PQExpBuffer errorMessage,
418  bool use_defaults, int expand_dbname);
420  PQExpBuffer errorMessage);
421 static PQconninfoOption *conninfo_uri_parse(const char *uri,
422  PQExpBuffer errorMessage, bool use_defaults);
424  const char *uri, PQExpBuffer errorMessage);
425 static bool conninfo_uri_parse_params(char *params,
426  PQconninfoOption *connOptions,
427  PQExpBuffer errorMessage);
428 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
429 static bool get_hexdigit(char digit, int *value);
430 static const char *conninfo_getval(PQconninfoOption *connOptions,
431  const char *keyword);
433  const char *keyword, const char *value,
434  PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
435 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
436  const char *keyword);
437 static void defaultNoticeReceiver(void *arg, const PGresult *res);
438 static void defaultNoticeProcessor(void *arg, const char *message);
440  PQExpBuffer errorMessage);
441 static int parseServiceFile(const char *serviceFile,
442  const char *service,
444  PQExpBuffer errorMessage,
445  bool *group_found);
446 static char *pwdfMatchesString(char *buf, const char *token);
447 static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
448  const char *username, const char *pgpassfile);
449 static void pgpassfileWarning(PGconn *conn);
450 static void default_threadlock(int acquire);
451 static bool sslVerifyProtocolVersion(const char *version);
452 static bool sslVerifyProtocolRange(const char *min, const char *max);
453 
454 
455 /* global variable because fe-auth.c needs to access it */
457 
458 
459 /*
460  * pqDropConnection
461  *
462  * Close any physical connection to the server, and reset associated
463  * state inside the connection object. We don't release state that
464  * would be needed to reconnect, though, nor local state that might still
465  * be useful later.
466  *
467  * We can always flush the output buffer, since there's no longer any hope
468  * of sending that data. However, unprocessed input data might still be
469  * valuable, so the caller must tell us whether to flush that or not.
470  */
471 void
472 pqDropConnection(PGconn *conn, bool flushInput)
473 {
474  /* Drop any SSL state */
476 
477  /* Close the socket itself */
478  if (conn->sock != PGINVALID_SOCKET)
481 
482  /* Optionally discard any unread data */
483  if (flushInput)
484  conn->inStart = conn->inCursor = conn->inEnd = 0;
485 
486  /* Always discard any unsent data */
487  conn->outCount = 0;
488 
489  /* Likewise, discard any pending pipelined commands */
493  conn->cmd_queue_recycle = NULL;
494 
495  /* Free authentication/encryption state */
496 #ifdef ENABLE_GSS
497  {
498  OM_uint32 min_s;
499 
500  if (conn->gcred != GSS_C_NO_CREDENTIAL)
501  {
502  gss_release_cred(&min_s, &conn->gcred);
503  conn->gcred = GSS_C_NO_CREDENTIAL;
504  }
505  if (conn->gctx)
506  gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
507  if (conn->gtarg_nam)
508  gss_release_name(&min_s, &conn->gtarg_nam);
509  if (conn->gss_SendBuffer)
510  {
511  free(conn->gss_SendBuffer);
512  conn->gss_SendBuffer = NULL;
513  }
514  if (conn->gss_RecvBuffer)
515  {
516  free(conn->gss_RecvBuffer);
517  conn->gss_RecvBuffer = NULL;
518  }
519  if (conn->gss_ResultBuffer)
520  {
521  free(conn->gss_ResultBuffer);
522  conn->gss_ResultBuffer = NULL;
523  }
524  conn->gssenc = false;
525  }
526 #endif
527 #ifdef ENABLE_SSPI
528  if (conn->sspitarget)
529  {
530  free(conn->sspitarget);
531  conn->sspitarget = NULL;
532  }
533  if (conn->sspicred)
534  {
535  FreeCredentialsHandle(conn->sspicred);
536  free(conn->sspicred);
537  conn->sspicred = NULL;
538  }
539  if (conn->sspictx)
540  {
541  DeleteSecurityContext(conn->sspictx);
542  free(conn->sspictx);
543  conn->sspictx = NULL;
544  }
545  conn->usesspi = 0;
546 #endif
547  if (conn->sasl_state)
548  {
550  conn->sasl_state = NULL;
551  }
552 }
553 
554 /*
555  * pqFreeCommandQueue
556  * Free all the entries of PGcmdQueueEntry queue passed.
557  */
558 static void
560 {
561  while (queue != NULL)
562  {
563  PGcmdQueueEntry *cur = queue;
564 
565  queue = cur->next;
566  free(cur->query);
567  free(cur);
568  }
569 }
570 
571 /*
572  * pqDropServerData
573  *
574  * Clear all connection state data that was received from (or deduced about)
575  * the server. This is essential to do between connection attempts to
576  * different servers, else we may incorrectly hold over some data from the
577  * old server.
578  *
579  * It would be better to merge this into pqDropConnection, perhaps, but
580  * right now we cannot because that function is called immediately on
581  * detection of connection loss (cf. pqReadData, for instance). This data
582  * should be kept until we are actually starting a new connection.
583  */
584 static void
586 {
587  PGnotify *notify;
588  pgParameterStatus *pstatus;
589 
590  /* Forget pending notifies */
591  notify = conn->notifyHead;
592  while (notify != NULL)
593  {
594  PGnotify *prev = notify;
595 
596  notify = notify->next;
597  free(prev);
598  }
599  conn->notifyHead = conn->notifyTail = NULL;
600 
601  /* Reset ParameterStatus data, as well as variables deduced from it */
602  pstatus = conn->pstatus;
603  while (pstatus != NULL)
604  {
605  pgParameterStatus *prev = pstatus;
606 
607  pstatus = pstatus->next;
608  free(prev);
609  }
610  conn->pstatus = NULL;
612  conn->std_strings = false;
616  conn->sversion = 0;
617 
618  /* Drop large-object lookup data */
619  free(conn->lobjfuncs);
620  conn->lobjfuncs = NULL;
621 
622  /* Reset assorted other per-connection state */
623  conn->last_sqlstate[0] = '\0';
624  conn->auth_req_received = false;
625  conn->client_finished_auth = false;
626  conn->password_needed = false;
627  conn->gssapi_used = false;
628  conn->write_failed = false;
630  conn->write_err_msg = NULL;
631 
632  /*
633  * Cancel connections need to retain their be_pid and be_key across
634  * PQcancelReset invocations, otherwise they would not have access to the
635  * secret token of the connection they are supposed to cancel.
636  */
637  if (!conn->cancelRequest)
638  {
639  conn->be_pid = 0;
640  conn->be_key = 0;
641  }
642 }
643 
644 
645 /*
646  * Connecting to a Database
647  *
648  * There are now six different ways a user of this API can connect to the
649  * database. Two are not recommended for use in new code, because of their
650  * lack of extensibility with respect to the passing of options to the
651  * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
652  * to the latter).
653  *
654  * If it is desired to connect in a synchronous (blocking) manner, use the
655  * function PQconnectdb or PQconnectdbParams. The former accepts a string of
656  * option = value pairs (or a URI) which must be parsed; the latter takes two
657  * NULL terminated arrays instead.
658  *
659  * To connect in an asynchronous (non-blocking) manner, use the functions
660  * PQconnectStart or PQconnectStartParams (which differ in the same way as
661  * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
662  *
663  * The non-exported functions pqConnectDBStart, pqConnectDBComplete are
664  * part of the connection procedure implementation.
665  */
666 
667 /*
668  * PQconnectdbParams
669  *
670  * establishes a connection to a postgres backend through the postmaster
671  * using connection information in two arrays.
672  *
673  * The keywords array is defined as
674  *
675  * const char *params[] = {"option1", "option2", NULL}
676  *
677  * The values array is defined as
678  *
679  * const char *values[] = {"value1", "value2", NULL}
680  *
681  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
682  * if a memory allocation failed.
683  * If the status field of the connection returned is CONNECTION_BAD,
684  * then some fields may be null'ed out instead of having valid values.
685  *
686  * You should call PQfinish (if conn is not NULL) regardless of whether this
687  * call succeeded.
688  */
689 PGconn *
690 PQconnectdbParams(const char *const *keywords,
691  const char *const *values,
692  int expand_dbname)
693 {
694  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
695 
696  if (conn && conn->status != CONNECTION_BAD)
697  (void) pqConnectDBComplete(conn);
698 
699  return conn;
700 }
701 
702 /*
703  * PQpingParams
704  *
705  * check server status, accepting parameters identical to PQconnectdbParams
706  */
707 PGPing
708 PQpingParams(const char *const *keywords,
709  const char *const *values,
710  int expand_dbname)
711 {
712  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
713  PGPing ret;
714 
715  ret = internal_ping(conn);
716  PQfinish(conn);
717 
718  return ret;
719 }
720 
721 /*
722  * PQconnectdb
723  *
724  * establishes a connection to a postgres backend through the postmaster
725  * using connection information in a string.
726  *
727  * The conninfo string is either a whitespace-separated list of
728  *
729  * option = value
730  *
731  * definitions or a URI (refer to the documentation for details.) Value
732  * might be a single value containing no whitespaces or a single quoted
733  * string. If a single quote should appear anywhere in the value, it must be
734  * escaped with a backslash like \'
735  *
736  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
737  * if a memory allocation failed.
738  * If the status field of the connection returned is CONNECTION_BAD,
739  * then some fields may be null'ed out instead of having valid values.
740  *
741  * You should call PQfinish (if conn is not NULL) regardless of whether this
742  * call succeeded.
743  */
744 PGconn *
745 PQconnectdb(const char *conninfo)
746 {
747  PGconn *conn = PQconnectStart(conninfo);
748 
749  if (conn && conn->status != CONNECTION_BAD)
750  (void) pqConnectDBComplete(conn);
751 
752  return conn;
753 }
754 
755 /*
756  * PQping
757  *
758  * check server status, accepting parameters identical to PQconnectdb
759  */
760 PGPing
761 PQping(const char *conninfo)
762 {
763  PGconn *conn = PQconnectStart(conninfo);
764  PGPing ret;
765 
766  ret = internal_ping(conn);
767  PQfinish(conn);
768 
769  return ret;
770 }
771 
772 /*
773  * PQconnectStartParams
774  *
775  * Begins the establishment of a connection to a postgres backend through the
776  * postmaster using connection information in a struct.
777  *
778  * See comment for PQconnectdbParams for the definition of the string format.
779  *
780  * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
781  * you should not attempt to proceed with this connection. If the status
782  * field of the connection returned is CONNECTION_BAD, an error has
783  * occurred. In this case you should call PQfinish on the result, (perhaps
784  * inspecting the error message first). Other fields of the structure may not
785  * be valid if that occurs. If the status field is not CONNECTION_BAD, then
786  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
787  * this is necessary.
788  *
789  * See PQconnectPoll for more info.
790  */
791 PGconn *
792 PQconnectStartParams(const char *const *keywords,
793  const char *const *values,
794  int expand_dbname)
795 {
796  PGconn *conn;
797  PQconninfoOption *connOptions;
798 
799  /*
800  * Allocate memory for the conn structure. Note that we also expect this
801  * to initialize conn->errorMessage to empty. All subsequent steps during
802  * connection initialization will only append to that buffer.
803  */
805  if (conn == NULL)
806  return NULL;
807 
808  /*
809  * Parse the conninfo arrays
810  */
811  connOptions = conninfo_array_parse(keywords, values,
812  &conn->errorMessage,
813  true, expand_dbname);
814  if (connOptions == NULL)
815  {
817  /* errorMessage is already set */
818  return conn;
819  }
820 
821  /*
822  * Move option values into conn structure
823  */
824  if (!fillPGconn(conn, connOptions))
825  {
826  PQconninfoFree(connOptions);
827  return conn;
828  }
829 
830  /*
831  * Free the option info - all is in conn now
832  */
833  PQconninfoFree(connOptions);
834 
835  /*
836  * Compute derived options
837  */
838  if (!pqConnectOptions2(conn))
839  return conn;
840 
841  /*
842  * Connect to the database
843  */
844  if (!pqConnectDBStart(conn))
845  {
846  /* Just in case we failed to set it in pqConnectDBStart */
848  }
849 
850  return conn;
851 }
852 
853 /*
854  * PQconnectStart
855  *
856  * Begins the establishment of a connection to a postgres backend through the
857  * postmaster using connection information in a string.
858  *
859  * See comment for PQconnectdb for the definition of the string format.
860  *
861  * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
862  * you should not attempt to proceed with this connection. If the status
863  * field of the connection returned is CONNECTION_BAD, an error has
864  * occurred. In this case you should call PQfinish on the result, (perhaps
865  * inspecting the error message first). Other fields of the structure may not
866  * be valid if that occurs. If the status field is not CONNECTION_BAD, then
867  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
868  * this is necessary.
869  *
870  * See PQconnectPoll for more info.
871  */
872 PGconn *
873 PQconnectStart(const char *conninfo)
874 {
875  PGconn *conn;
876 
877  /*
878  * Allocate memory for the conn structure. Note that we also expect this
879  * to initialize conn->errorMessage to empty. All subsequent steps during
880  * connection initialization will only append to that buffer.
881  */
883  if (conn == NULL)
884  return NULL;
885 
886  /*
887  * Parse the conninfo string
888  */
889  if (!connectOptions1(conn, conninfo))
890  return conn;
891 
892  /*
893  * Compute derived options
894  */
895  if (!pqConnectOptions2(conn))
896  return conn;
897 
898  /*
899  * Connect to the database
900  */
901  if (!pqConnectDBStart(conn))
902  {
903  /* Just in case we failed to set it in pqConnectDBStart */
905  }
906 
907  return conn;
908 }
909 
910 /*
911  * Move option values into conn structure
912  *
913  * Don't put anything cute here --- intelligence should be in
914  * pqConnectOptions2 ...
915  *
916  * Returns true on success. On failure, returns false and sets error message.
917  */
918 static bool
920 {
922 
923  for (option = PQconninfoOptions; option->keyword; option++)
924  {
925  if (option->connofs >= 0)
926  {
927  const char *tmp = conninfo_getval(connOptions, option->keyword);
928 
929  if (tmp)
930  {
931  char **connmember = (char **) ((char *) conn + option->connofs);
932 
933  free(*connmember);
934  *connmember = strdup(tmp);
935  if (*connmember == NULL)
936  {
937  libpq_append_conn_error(conn, "out of memory");
938  return false;
939  }
940  }
941  }
942  }
943 
944  return true;
945 }
946 
947 /*
948  * Copy over option values from srcConn to dstConn
949  *
950  * Don't put anything cute here --- intelligence should be in
951  * pqConnectOptions2 ...
952  *
953  * Returns true on success. On failure, returns false and sets error message of
954  * dstConn.
955  */
956 bool
957 pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
958 {
960 
961  /* copy over connection options */
962  for (option = PQconninfoOptions; option->keyword; option++)
963  {
964  if (option->connofs >= 0)
965  {
966  const char **tmp = (const char **) ((char *) srcConn + option->connofs);
967 
968  if (*tmp)
969  {
970  char **dstConnmember = (char **) ((char *) dstConn + option->connofs);
971 
972  if (*dstConnmember)
973  free(*dstConnmember);
974  *dstConnmember = strdup(*tmp);
975  if (*dstConnmember == NULL)
976  {
977  libpq_append_conn_error(dstConn, "out of memory");
978  return false;
979  }
980  }
981  }
982  }
983  return true;
984 }
985 
986 /*
987  * connectOptions1
988  *
989  * Internal subroutine to set up connection parameters given an already-
990  * created PGconn and a conninfo string. Derived settings should be
991  * processed by calling pqConnectOptions2 next. (We split them because
992  * PQsetdbLogin overrides defaults in between.)
993  *
994  * Returns true if OK, false if trouble (in which case errorMessage is set
995  * and so is conn->status).
996  */
997 static bool
998 connectOptions1(PGconn *conn, const char *conninfo)
999 {
1000  PQconninfoOption *connOptions;
1001 
1002  /*
1003  * Parse the conninfo string
1004  */
1005  connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
1006  if (connOptions == NULL)
1007  {
1009  /* errorMessage is already set */
1010  return false;
1011  }
1012 
1013  /*
1014  * Move option values into conn structure
1015  */
1016  if (!fillPGconn(conn, connOptions))
1017  {
1019  PQconninfoFree(connOptions);
1020  return false;
1021  }
1022 
1023  /*
1024  * Free the option info - all is in conn now
1025  */
1026  PQconninfoFree(connOptions);
1027 
1028  return true;
1029 }
1030 
1031 /*
1032  * Count the number of elements in a simple comma-separated list.
1033  */
1034 static int
1036 {
1037  int n;
1038 
1039  n = 1;
1040  for (; *input != '\0'; input++)
1041  {
1042  if (*input == ',')
1043  n++;
1044  }
1045 
1046  return n;
1047 }
1048 
1049 /*
1050  * Parse a simple comma-separated list.
1051  *
1052  * On each call, returns a malloc'd copy of the next element, and sets *more
1053  * to indicate whether there are any more elements in the list after this,
1054  * and updates *startptr to point to the next element, if any.
1055  *
1056  * On out of memory, returns NULL.
1057  */
1058 static char *
1059 parse_comma_separated_list(char **startptr, bool *more)
1060 {
1061  char *p;
1062  char *s = *startptr;
1063  char *e;
1064  int len;
1065 
1066  /*
1067  * Search for the end of the current element; a comma or end-of-string
1068  * acts as a terminator.
1069  */
1070  e = s;
1071  while (*e != '\0' && *e != ',')
1072  ++e;
1073  *more = (*e == ',');
1074 
1075  len = e - s;
1076  p = (char *) malloc(sizeof(char) * (len + 1));
1077  if (p)
1078  {
1079  memcpy(p, s, len);
1080  p[len] = '\0';
1081  }
1082  *startptr = e + 1;
1083 
1084  return p;
1085 }
1086 
1087 /*
1088  * Initializes the prng_state field of the connection. We want something
1089  * unpredictable, so if possible, use high-quality random bits for the
1090  * seed. Otherwise, fall back to a seed based on the connection address,
1091  * timestamp and PID.
1092  */
1093 static void
1095 {
1096  uint64 rseed;
1097  struct timeval tval = {0};
1098 
1100  return;
1101 
1102  gettimeofday(&tval, NULL);
1103 
1104  rseed = ((uintptr_t) conn) ^
1105  ((uint64) getpid()) ^
1106  ((uint64) tval.tv_usec) ^
1107  ((uint64) tval.tv_sec);
1108 
1109  pg_prng_seed(&conn->prng_state, rseed);
1110 }
1111 
1112 /*
1113  * pqConnectOptions2
1114  *
1115  * Compute derived connection options after absorbing all user-supplied info.
1116  *
1117  * Returns true if OK, false if trouble (in which case errorMessage is set
1118  * and so is conn->status).
1119  */
1120 bool
1122 {
1123  int i;
1124 
1125  /*
1126  * Allocate memory for details about each host to which we might possibly
1127  * try to connect. For that, count the number of elements in the hostaddr
1128  * or host options. If neither is given, assume one host.
1129  */
1130  conn->whichhost = 0;
1131  if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1133  else if (conn->pghost && conn->pghost[0] != '\0')
1135  else
1136  conn->nconnhost = 1;
1137  conn->connhost = (pg_conn_host *)
1138  calloc(conn->nconnhost, sizeof(pg_conn_host));
1139  if (conn->connhost == NULL)
1140  goto oom_error;
1141 
1142  /*
1143  * We now have one pg_conn_host structure per possible host. Fill in the
1144  * host and hostaddr fields for each, by splitting the parameter strings.
1145  */
1146  if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1147  {
1148  char *s = conn->pghostaddr;
1149  bool more = true;
1150 
1151  for (i = 0; i < conn->nconnhost && more; i++)
1152  {
1154  if (conn->connhost[i].hostaddr == NULL)
1155  goto oom_error;
1156  }
1157 
1158  /*
1159  * If hostaddr was given, the array was allocated according to the
1160  * number of elements in the hostaddr list, so it really should be the
1161  * right size.
1162  */
1163  Assert(!more);
1164  Assert(i == conn->nconnhost);
1165  }
1166 
1167  if (conn->pghost != NULL && conn->pghost[0] != '\0')
1168  {
1169  char *s = conn->pghost;
1170  bool more = true;
1171 
1172  for (i = 0; i < conn->nconnhost && more; i++)
1173  {
1175  if (conn->connhost[i].host == NULL)
1176  goto oom_error;
1177  }
1178 
1179  /* Check for wrong number of host items. */
1180  if (more || i != conn->nconnhost)
1181  {
1183  libpq_append_conn_error(conn, "could not match %d host names to %d hostaddr values",
1185  return false;
1186  }
1187  }
1188 
1189  /*
1190  * Now, for each host slot, identify the type of address spec, and fill in
1191  * the default address if nothing was given.
1192  */
1193  for (i = 0; i < conn->nconnhost; i++)
1194  {
1195  pg_conn_host *ch = &conn->connhost[i];
1196 
1197  if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1198  ch->type = CHT_HOST_ADDRESS;
1199  else if (ch->host != NULL && ch->host[0] != '\0')
1200  {
1201  ch->type = CHT_HOST_NAME;
1202  if (is_unixsock_path(ch->host))
1203  ch->type = CHT_UNIX_SOCKET;
1204  }
1205  else
1206  {
1207  free(ch->host);
1208 
1209  /*
1210  * This bit selects the default host location. If you change
1211  * this, see also pg_regress.
1212  */
1213  if (DEFAULT_PGSOCKET_DIR[0])
1214  {
1215  ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1216  ch->type = CHT_UNIX_SOCKET;
1217  }
1218  else
1219  {
1220  ch->host = strdup(DefaultHost);
1221  ch->type = CHT_HOST_NAME;
1222  }
1223  if (ch->host == NULL)
1224  goto oom_error;
1225  }
1226  }
1227 
1228  /*
1229  * Next, work out the port number corresponding to each host name.
1230  *
1231  * Note: unlike the above for host names, this could leave the port fields
1232  * as null or empty strings. We will substitute DEF_PGPORT whenever we
1233  * read such a port field.
1234  */
1235  if (conn->pgport != NULL && conn->pgport[0] != '\0')
1236  {
1237  char *s = conn->pgport;
1238  bool more = true;
1239 
1240  for (i = 0; i < conn->nconnhost && more; i++)
1241  {
1243  if (conn->connhost[i].port == NULL)
1244  goto oom_error;
1245  }
1246 
1247  /*
1248  * If exactly one port was given, use it for every host. Otherwise,
1249  * there must be exactly as many ports as there were hosts.
1250  */
1251  if (i == 1 && !more)
1252  {
1253  for (i = 1; i < conn->nconnhost; i++)
1254  {
1255  conn->connhost[i].port = strdup(conn->connhost[0].port);
1256  if (conn->connhost[i].port == NULL)
1257  goto oom_error;
1258  }
1259  }
1260  else if (more || i != conn->nconnhost)
1261  {
1263  libpq_append_conn_error(conn, "could not match %d port numbers to %d hosts",
1265  return false;
1266  }
1267  }
1268 
1269  /*
1270  * If user name was not given, fetch it. (Most likely, the fetch will
1271  * fail, since the only way we get here is if pg_fe_getauthname() failed
1272  * during conninfo_add_defaults(). But now we want an error message.)
1273  */
1274  if (conn->pguser == NULL || conn->pguser[0] == '\0')
1275  {
1276  free(conn->pguser);
1278  if (!conn->pguser)
1279  {
1281  return false;
1282  }
1283  }
1284 
1285  /*
1286  * If database name was not given, default it to equal user name
1287  */
1288  if (conn->dbName == NULL || conn->dbName[0] == '\0')
1289  {
1290  free(conn->dbName);
1291  conn->dbName = strdup(conn->pguser);
1292  if (!conn->dbName)
1293  goto oom_error;
1294  }
1295 
1296  /*
1297  * If password was not given, try to look it up in password file. Note
1298  * that the result might be different for each host/port pair.
1299  */
1300  if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1301  {
1302  /* If password file wasn't specified, use ~/PGPASSFILE */
1303  if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1304  {
1305  char homedir[MAXPGPATH];
1306 
1307  if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1308  {
1309  free(conn->pgpassfile);
1311  if (!conn->pgpassfile)
1312  goto oom_error;
1313  snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1314  homedir, PGPASSFILE);
1315  }
1316  }
1317 
1318  if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1319  {
1320  for (i = 0; i < conn->nconnhost; i++)
1321  {
1322  /*
1323  * Try to get a password for this host from file. We use host
1324  * for the hostname search key if given, else hostaddr (at
1325  * least one of them is guaranteed nonempty by now).
1326  */
1327  const char *pwhost = conn->connhost[i].host;
1328 
1329  if (pwhost == NULL || pwhost[0] == '\0')
1330  pwhost = conn->connhost[i].hostaddr;
1331 
1332  conn->connhost[i].password =
1333  passwordFromFile(pwhost,
1334  conn->connhost[i].port,
1335  conn->dbName,
1336  conn->pguser,
1337  conn->pgpassfile);
1338  }
1339  }
1340  }
1341 
1342  /*
1343  * parse and validate require_auth option
1344  */
1345  if (conn->require_auth && conn->require_auth[0])
1346  {
1347  char *s = conn->require_auth;
1348  bool first,
1349  more;
1350  bool negated = false;
1351 
1352  /*
1353  * By default, start from an empty set of allowed options and add to
1354  * it.
1355  */
1356  conn->auth_required = true;
1358 
1359  for (first = true, more = true; more; first = false)
1360  {
1361  char *method,
1362  *part;
1363  uint32 bits;
1364 
1365  part = parse_comma_separated_list(&s, &more);
1366  if (part == NULL)
1367  goto oom_error;
1368 
1369  /*
1370  * Check for negation, e.g. '!password'. If one element is
1371  * negated, they all have to be.
1372  */
1373  method = part;
1374  if (*method == '!')
1375  {
1376  if (first)
1377  {
1378  /*
1379  * Switch to a permissive set of allowed options, and
1380  * subtract from it.
1381  */
1382  conn->auth_required = false;
1383  conn->allowed_auth_methods = -1;
1384  }
1385  else if (!negated)
1386  {
1388  libpq_append_conn_error(conn, "negative require_auth method \"%s\" cannot be mixed with non-negative methods",
1389  method);
1390 
1391  free(part);
1392  return false;
1393  }
1394 
1395  negated = true;
1396  method++;
1397  }
1398  else if (negated)
1399  {
1401  libpq_append_conn_error(conn, "require_auth method \"%s\" cannot be mixed with negative methods",
1402  method);
1403 
1404  free(part);
1405  return false;
1406  }
1407 
1408  if (strcmp(method, "password") == 0)
1409  {
1410  bits = (1 << AUTH_REQ_PASSWORD);
1411  }
1412  else if (strcmp(method, "md5") == 0)
1413  {
1414  bits = (1 << AUTH_REQ_MD5);
1415  }
1416  else if (strcmp(method, "gss") == 0)
1417  {
1418  bits = (1 << AUTH_REQ_GSS);
1419  bits |= (1 << AUTH_REQ_GSS_CONT);
1420  }
1421  else if (strcmp(method, "sspi") == 0)
1422  {
1423  bits = (1 << AUTH_REQ_SSPI);
1424  bits |= (1 << AUTH_REQ_GSS_CONT);
1425  }
1426  else if (strcmp(method, "scram-sha-256") == 0)
1427  {
1428  /* This currently assumes that SCRAM is the only SASL method. */
1429  bits = (1 << AUTH_REQ_SASL);
1430  bits |= (1 << AUTH_REQ_SASL_CONT);
1431  bits |= (1 << AUTH_REQ_SASL_FIN);
1432  }
1433  else if (strcmp(method, "none") == 0)
1434  {
1435  /*
1436  * Special case: let the user explicitly allow (or disallow)
1437  * connections where the server does not send an explicit
1438  * authentication challenge, such as "trust" and "cert" auth.
1439  */
1440  if (negated) /* "!none" */
1441  {
1442  if (conn->auth_required)
1443  goto duplicate;
1444 
1445  conn->auth_required = true;
1446  }
1447  else /* "none" */
1448  {
1449  if (!conn->auth_required)
1450  goto duplicate;
1451 
1452  conn->auth_required = false;
1453  }
1454 
1455  free(part);
1456  continue; /* avoid the bitmask manipulation below */
1457  }
1458  else
1459  {
1461  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1462  "require_auth", method);
1463 
1464  free(part);
1465  return false;
1466  }
1467 
1468  /* Update the bitmask. */
1469  if (negated)
1470  {
1471  if ((conn->allowed_auth_methods & bits) == 0)
1472  goto duplicate;
1473 
1474  conn->allowed_auth_methods &= ~bits;
1475  }
1476  else
1477  {
1478  if ((conn->allowed_auth_methods & bits) == bits)
1479  goto duplicate;
1480 
1481  conn->allowed_auth_methods |= bits;
1482  }
1483 
1484  free(part);
1485  continue;
1486 
1487  duplicate:
1488 
1489  /*
1490  * A duplicated method probably indicates a typo in a setting
1491  * where typos are extremely risky.
1492  */
1494  libpq_append_conn_error(conn, "require_auth method \"%s\" is specified more than once",
1495  part);
1496 
1497  free(part);
1498  return false;
1499  }
1500  }
1501 
1502  /*
1503  * validate channel_binding option
1504  */
1505  if (conn->channel_binding)
1506  {
1507  if (strcmp(conn->channel_binding, "disable") != 0
1508  && strcmp(conn->channel_binding, "prefer") != 0
1509  && strcmp(conn->channel_binding, "require") != 0)
1510  {
1512  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1513  "channel_binding", conn->channel_binding);
1514  return false;
1515  }
1516  }
1517  else
1518  {
1520  if (!conn->channel_binding)
1521  goto oom_error;
1522  }
1523 
1524 #ifndef USE_SSL
1525 
1526  /*
1527  * sslrootcert=system is not supported. Since setting this changes the
1528  * default sslmode, check this _before_ we validate sslmode, to avoid
1529  * confusing the user with errors for an option they may not have set.
1530  */
1531  if (conn->sslrootcert
1532  && strcmp(conn->sslrootcert, "system") == 0)
1533  {
1535  libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1536  "sslrootcert", conn->sslrootcert);
1537  return false;
1538  }
1539 #endif
1540 
1541  /*
1542  * validate sslmode option
1543  */
1544  if (conn->sslmode)
1545  {
1546  if (strcmp(conn->sslmode, "disable") != 0
1547  && strcmp(conn->sslmode, "allow") != 0
1548  && strcmp(conn->sslmode, "prefer") != 0
1549  && strcmp(conn->sslmode, "require") != 0
1550  && strcmp(conn->sslmode, "verify-ca") != 0
1551  && strcmp(conn->sslmode, "verify-full") != 0)
1552  {
1554  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1555  "sslmode", conn->sslmode);
1556  return false;
1557  }
1558 
1559 #ifndef USE_SSL
1560  switch (conn->sslmode[0])
1561  {
1562  case 'a': /* "allow" */
1563  case 'p': /* "prefer" */
1564 
1565  /*
1566  * warn user that an SSL connection will never be negotiated
1567  * since SSL was not compiled in?
1568  */
1569  break;
1570 
1571  case 'r': /* "require" */
1572  case 'v': /* "verify-ca" or "verify-full" */
1574  libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1575  "sslmode", conn->sslmode);
1576  return false;
1577  }
1578 #endif
1579  }
1580  else
1581  {
1582  conn->sslmode = strdup(DefaultSSLMode);
1583  if (!conn->sslmode)
1584  goto oom_error;
1585  }
1586 
1587  /*
1588  * validate sslnegotiation option, default is "postgres" for the postgres
1589  * style negotiated connection with an extra round trip but more options.
1590  */
1591  if (conn->sslnegotiation)
1592  {
1593  if (strcmp(conn->sslnegotiation, "postgres") != 0
1594  && strcmp(conn->sslnegotiation, "direct") != 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, "%s value \"%s\" invalid when SSL support is not compiled in",
1607  "sslnegotiation", conn->sslnegotiation);
1608  return false;
1609  }
1610 #endif
1611 
1612  /*
1613  * Don't allow direct SSL negotiation with sslmode='prefer', because
1614  * that poses a risk of unintentional fallback to plaintext connection
1615  * when connecting to a pre-v17 server that does not support direct
1616  * SSL connections. To keep things simple, don't allow it with
1617  * sslmode='allow' or sslmode='disable' either. If a user goes through
1618  * the trouble of setting sslnegotiation='direct', they probably
1619  * intend to use SSL, and sslmode=disable or allow is probably a user
1620  * user mistake anyway.
1621  */
1622  if (conn->sslnegotiation[0] == 'd' &&
1623  conn->sslmode[0] != 'r' && conn->sslmode[0] != 'v')
1624  {
1626  libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslnegotiation=direct (use \"require\", \"verify-ca\", or \"verify-full\")",
1627  conn->sslmode);
1628  return false;
1629  }
1630  }
1631  else
1632  {
1634  if (!conn->sslnegotiation)
1635  goto oom_error;
1636  }
1637 
1638 #ifdef USE_SSL
1639 
1640  /*
1641  * If sslrootcert=system, make sure our chosen sslmode is compatible.
1642  */
1643  if (conn->sslrootcert
1644  && strcmp(conn->sslrootcert, "system") == 0
1645  && strcmp(conn->sslmode, "verify-full") != 0)
1646  {
1648  libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslrootcert=system (use \"verify-full\")",
1649  conn->sslmode);
1650  return false;
1651  }
1652 #endif
1653 
1654  /*
1655  * Validate TLS protocol versions for ssl_min_protocol_version and
1656  * ssl_max_protocol_version.
1657  */
1659  {
1661  libpq_append_conn_error(conn, "invalid \"%s\" value: \"%s\"",
1662  "ssl_min_protocol_version",
1664  return false;
1665  }
1667  {
1669  libpq_append_conn_error(conn, "invalid \"%s\" value: \"%s\"",
1670  "ssl_max_protocol_version",
1672  return false;
1673  }
1674 
1675  /*
1676  * Check if the range of SSL protocols defined is correct. This is done
1677  * at this early step because this is independent of the SSL
1678  * implementation used, and this avoids unnecessary cycles with an
1679  * already-built SSL context when the connection is being established, as
1680  * it would be doomed anyway.
1681  */
1684  {
1686  libpq_append_conn_error(conn, "invalid SSL protocol version range");
1687  return false;
1688  }
1689 
1690  /*
1691  * validate sslcertmode option
1692  */
1693  if (conn->sslcertmode)
1694  {
1695  if (strcmp(conn->sslcertmode, "disable") != 0 &&
1696  strcmp(conn->sslcertmode, "allow") != 0 &&
1697  strcmp(conn->sslcertmode, "require") != 0)
1698  {
1700  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1701  "sslcertmode", conn->sslcertmode);
1702  return false;
1703  }
1704 #ifndef USE_SSL
1705  if (strcmp(conn->sslcertmode, "require") == 0)
1706  {
1708  libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1709  "sslcertmode", conn->sslcertmode);
1710  return false;
1711  }
1712 #endif
1713 #ifndef HAVE_SSL_CTX_SET_CERT_CB
1714 
1715  /*
1716  * Without a certificate callback, the current implementation can't
1717  * figure out if a certificate was actually requested, so "require" is
1718  * useless.
1719  */
1720  if (strcmp(conn->sslcertmode, "require") == 0)
1721  {
1723  libpq_append_conn_error(conn, "%s value \"%s\" is not supported (check OpenSSL version)",
1724  "sslcertmode", conn->sslcertmode);
1725  return false;
1726  }
1727 #endif
1728  }
1729  else
1730  {
1731  conn->sslcertmode = strdup(DefaultSSLCertMode);
1732  if (!conn->sslcertmode)
1733  goto oom_error;
1734  }
1735 
1736  /*
1737  * validate gssencmode option
1738  */
1739  if (conn->gssencmode)
1740  {
1741  if (strcmp(conn->gssencmode, "disable") != 0 &&
1742  strcmp(conn->gssencmode, "prefer") != 0 &&
1743  strcmp(conn->gssencmode, "require") != 0)
1744  {
1746  libpq_append_conn_error(conn, "invalid %s value: \"%s\"", "gssencmode", conn->gssencmode);
1747  return false;
1748  }
1749 #ifndef ENABLE_GSS
1750  if (strcmp(conn->gssencmode, "require") == 0)
1751  {
1753  libpq_append_conn_error(conn, "gssencmode value \"%s\" invalid when GSSAPI support is not compiled in",
1754  conn->gssencmode);
1755  return false;
1756  }
1757 #endif
1758  }
1759  else
1760  {
1761  conn->gssencmode = strdup(DefaultGSSMode);
1762  if (!conn->gssencmode)
1763  goto oom_error;
1764  }
1765 
1766  /*
1767  * validate target_session_attrs option, and set target_server_type
1768  */
1770  {
1771  if (strcmp(conn->target_session_attrs, "any") == 0)
1773  else if (strcmp(conn->target_session_attrs, "read-write") == 0)
1775  else if (strcmp(conn->target_session_attrs, "read-only") == 0)
1777  else if (strcmp(conn->target_session_attrs, "primary") == 0)
1779  else if (strcmp(conn->target_session_attrs, "standby") == 0)
1781  else if (strcmp(conn->target_session_attrs, "prefer-standby") == 0)
1783  else
1784  {
1786  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1787  "target_session_attrs",
1789  return false;
1790  }
1791  }
1792  else
1794 
1795  /*
1796  * validate load_balance_hosts option, and set load_balance_type
1797  */
1798  if (conn->load_balance_hosts)
1799  {
1800  if (strcmp(conn->load_balance_hosts, "disable") == 0)
1802  else if (strcmp(conn->load_balance_hosts, "random") == 0)
1804  else
1805  {
1807  libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1808  "load_balance_hosts",
1810  return false;
1811  }
1812  }
1813  else
1815 
1817  {
1819 
1820  /*
1821  * This is the "inside-out" variant of the Fisher-Yates shuffle
1822  * algorithm. Notionally, we append each new value to the array and
1823  * then swap it with a randomly-chosen array element (possibly
1824  * including itself, else we fail to generate permutations with the
1825  * last integer last). The swap step can be optimized by combining it
1826  * with the insertion.
1827  */
1828  for (i = 1; i < conn->nconnhost; i++)
1829  {
1830  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
1831  pg_conn_host temp = conn->connhost[j];
1832 
1833  conn->connhost[j] = conn->connhost[i];
1834  conn->connhost[i] = temp;
1835  }
1836  }
1837 
1838  /*
1839  * Resolve special "auto" client_encoding from the locale
1840  */
1842  strcmp(conn->client_encoding_initial, "auto") == 0)
1843  {
1847  goto oom_error;
1848  }
1849 
1850  /*
1851  * Only if we get this far is it appropriate to try to connect. (We need a
1852  * state flag, rather than just the boolean result of this function, in
1853  * case someone tries to PQreset() the PGconn.)
1854  */
1855  conn->options_valid = true;
1856 
1857  return true;
1858 
1859 oom_error:
1861  libpq_append_conn_error(conn, "out of memory");
1862  return false;
1863 }
1864 
1865 /*
1866  * PQconndefaults
1867  *
1868  * Construct a default connection options array, which identifies all the
1869  * available options and shows any default values that are available from the
1870  * environment etc. On error (eg out of memory), NULL is returned.
1871  *
1872  * Using this function, an application may determine all possible options
1873  * and their current default values.
1874  *
1875  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1876  * and should be freed when no longer needed via PQconninfoFree(). (In prior
1877  * versions, the returned array was static, but that's not thread-safe.)
1878  * Pre-7.0 applications that use this function will see a small memory leak
1879  * until they are updated to call PQconninfoFree.
1880  */
1883 {
1884  PQExpBufferData errorBuf;
1885  PQconninfoOption *connOptions;
1886 
1887  /* We don't actually report any errors here, but callees want a buffer */
1888  initPQExpBuffer(&errorBuf);
1889  if (PQExpBufferDataBroken(errorBuf))
1890  return NULL; /* out of memory already :-( */
1891 
1892  connOptions = conninfo_init(&errorBuf);
1893  if (connOptions != NULL)
1894  {
1895  /* pass NULL errorBuf to ignore errors */
1896  if (!conninfo_add_defaults(connOptions, NULL))
1897  {
1898  PQconninfoFree(connOptions);
1899  connOptions = NULL;
1900  }
1901  }
1902 
1903  termPQExpBuffer(&errorBuf);
1904  return connOptions;
1905 }
1906 
1907 /* ----------------
1908  * PQsetdbLogin
1909  *
1910  * establishes a connection to a postgres backend through the postmaster
1911  * at the specified host and port.
1912  *
1913  * returns a PGconn* which is needed for all subsequent libpq calls
1914  *
1915  * if the status field of the connection returned is CONNECTION_BAD,
1916  * then only the errorMessage is likely to be useful.
1917  * ----------------
1918  */
1919 PGconn *
1920 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1921  const char *pgtty, const char *dbName, const char *login,
1922  const char *pwd)
1923 {
1924  PGconn *conn;
1925 
1926  /*
1927  * Allocate memory for the conn structure. Note that we also expect this
1928  * to initialize conn->errorMessage to empty. All subsequent steps during
1929  * connection initialization will only append to that buffer.
1930  */
1931  conn = pqMakeEmptyPGconn();
1932  if (conn == NULL)
1933  return NULL;
1934 
1935  /*
1936  * If the dbName parameter contains what looks like a connection string,
1937  * parse it into conn struct using connectOptions1.
1938  */
1940  {
1941  if (!connectOptions1(conn, dbName))
1942  return conn;
1943  }
1944  else
1945  {
1946  /*
1947  * Old-style path: first, parse an empty conninfo string in order to
1948  * set up the same defaults that PQconnectdb() would use.
1949  */
1950  if (!connectOptions1(conn, ""))
1951  return conn;
1952 
1953  /* Insert dbName parameter value into struct */
1954  if (dbName && dbName[0] != '\0')
1955  {
1956  free(conn->dbName);
1957  conn->dbName = strdup(dbName);
1958  if (!conn->dbName)
1959  goto oom_error;
1960  }
1961  }
1962 
1963  /*
1964  * Insert remaining parameters into struct, overriding defaults (as well
1965  * as any conflicting data from dbName taken as a conninfo).
1966  */
1967  if (pghost && pghost[0] != '\0')
1968  {
1969  free(conn->pghost);
1970  conn->pghost = strdup(pghost);
1971  if (!conn->pghost)
1972  goto oom_error;
1973  }
1974 
1975  if (pgport && pgport[0] != '\0')
1976  {
1977  free(conn->pgport);
1978  conn->pgport = strdup(pgport);
1979  if (!conn->pgport)
1980  goto oom_error;
1981  }
1982 
1983  if (pgoptions && pgoptions[0] != '\0')
1984  {
1985  free(conn->pgoptions);
1986  conn->pgoptions = strdup(pgoptions);
1987  if (!conn->pgoptions)
1988  goto oom_error;
1989  }
1990 
1991  if (login && login[0] != '\0')
1992  {
1993  free(conn->pguser);
1994  conn->pguser = strdup(login);
1995  if (!conn->pguser)
1996  goto oom_error;
1997  }
1998 
1999  if (pwd && pwd[0] != '\0')
2000  {
2001  free(conn->pgpass);
2002  conn->pgpass = strdup(pwd);
2003  if (!conn->pgpass)
2004  goto oom_error;
2005  }
2006 
2007  /*
2008  * Compute derived options
2009  */
2010  if (!pqConnectOptions2(conn))
2011  return conn;
2012 
2013  /*
2014  * Connect to the database
2015  */
2016  if (pqConnectDBStart(conn))
2017  (void) pqConnectDBComplete(conn);
2018 
2019  return conn;
2020 
2021 oom_error:
2023  libpq_append_conn_error(conn, "out of memory");
2024  return conn;
2025 }
2026 
2027 
2028 /* ----------
2029  * connectNoDelay -
2030  * Sets the TCP_NODELAY socket option.
2031  * Returns 1 if successful, 0 if not.
2032  * ----------
2033  */
2034 static int
2036 {
2037 #ifdef TCP_NODELAY
2038  int on = 1;
2039 
2040  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
2041  (char *) &on,
2042  sizeof(on)) < 0)
2043  {
2044  char sebuf[PG_STRERROR_R_BUFLEN];
2045 
2046  libpq_append_conn_error(conn, "could not set socket to TCP no delay mode: %s",
2047  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2048  return 0;
2049  }
2050 #endif
2051 
2052  return 1;
2053 }
2054 
2055 /* ----------
2056  * Write currently connected IP address into host_addr (of len host_addr_len).
2057  * If unable to, set it to the empty string.
2058  * ----------
2059  */
2060 static void
2061 getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
2062 {
2063  struct sockaddr_storage *addr = &conn->raddr.addr;
2064 
2065  if (addr->ss_family == AF_INET)
2066  {
2067  if (pg_inet_net_ntop(AF_INET,
2068  &((struct sockaddr_in *) addr)->sin_addr.s_addr,
2069  32,
2070  host_addr, host_addr_len) == NULL)
2071  host_addr[0] = '\0';
2072  }
2073  else if (addr->ss_family == AF_INET6)
2074  {
2075  if (pg_inet_net_ntop(AF_INET6,
2076  &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
2077  128,
2078  host_addr, host_addr_len) == NULL)
2079  host_addr[0] = '\0';
2080  }
2081  else
2082  host_addr[0] = '\0';
2083 }
2084 
2085 /*
2086  * emitHostIdentityInfo -
2087  * Speculatively append "connection to server so-and-so failed: " to
2088  * conn->errorMessage once we've identified the current connection target
2089  * address. This ensures that any subsequent error message will be properly
2090  * attributed to the server we couldn't connect to. conn->raddr must be
2091  * valid, and the result of getHostaddr() must be supplied.
2092  */
2093 static void
2094 emitHostIdentityInfo(PGconn *conn, const char *host_addr)
2095 {
2096  if (conn->raddr.addr.ss_family == AF_UNIX)
2097  {
2098  char service[NI_MAXHOST];
2099 
2101  NULL, 0,
2102  service, sizeof(service),
2103  NI_NUMERICSERV);
2105  libpq_gettext("connection to server on socket \"%s\" failed: "),
2106  service);
2107  }
2108  else
2109  {
2110  const char *displayed_host;
2111  const char *displayed_port;
2112 
2113  /* To which host and port were we actually connecting? */
2115  displayed_host = conn->connhost[conn->whichhost].hostaddr;
2116  else
2117  displayed_host = conn->connhost[conn->whichhost].host;
2118  displayed_port = conn->connhost[conn->whichhost].port;
2119  if (displayed_port == NULL || displayed_port[0] == '\0')
2120  displayed_port = DEF_PGPORT_STR;
2121 
2122  /*
2123  * If the user did not supply an IP address using 'hostaddr', and
2124  * 'host' was missing or does not match our lookup, display the
2125  * looked-up IP address.
2126  */
2128  host_addr[0] &&
2129  strcmp(displayed_host, host_addr) != 0)
2131  libpq_gettext("connection to server at \"%s\" (%s), port %s failed: "),
2132  displayed_host, host_addr,
2133  displayed_port);
2134  else
2136  libpq_gettext("connection to server at \"%s\", port %s failed: "),
2137  displayed_host,
2138  displayed_port);
2139  }
2140 }
2141 
2142 /* ----------
2143  * connectFailureMessage -
2144  * create a friendly error message on connection failure,
2145  * using the given errno value. Use this for error cases that
2146  * imply that there's no server there.
2147  * ----------
2148  */
2149 static void
2151 {
2152  char sebuf[PG_STRERROR_R_BUFLEN];
2153 
2155  "%s\n",
2156  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2157 
2158  if (conn->raddr.addr.ss_family == AF_UNIX)
2159  libpq_append_conn_error(conn, "\tIs the server running locally and accepting connections on that socket?");
2160  else
2161  libpq_append_conn_error(conn, "\tIs the server running on that host and accepting TCP/IP connections?");
2162 }
2163 
2164 /*
2165  * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
2166  * conn->keepalives is set to a value which is not parseable as an
2167  * integer.
2168  */
2169 static int
2171 {
2172  int val;
2173 
2174  if (conn->keepalives == NULL)
2175  return 1;
2176 
2177  if (!pqParseIntParam(conn->keepalives, &val, conn, "keepalives"))
2178  return -1;
2179 
2180  return val != 0 ? 1 : 0;
2181 }
2182 
2183 #ifndef WIN32
2184 /*
2185  * Set the keepalive idle timer.
2186  */
2187 static int
2189 {
2190  int idle;
2191 
2192  if (conn->keepalives_idle == NULL)
2193  return 1;
2194 
2195  if (!pqParseIntParam(conn->keepalives_idle, &idle, conn,
2196  "keepalives_idle"))
2197  return 0;
2198  if (idle < 0)
2199  idle = 0;
2200 
2201 #ifdef PG_TCP_KEEPALIVE_IDLE
2202  if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2203  (char *) &idle, sizeof(idle)) < 0)
2204  {
2205  char sebuf[PG_STRERROR_R_BUFLEN];
2206 
2207  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2208  "setsockopt",
2209  PG_TCP_KEEPALIVE_IDLE_STR,
2210  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2211  return 0;
2212  }
2213 #endif
2214 
2215  return 1;
2216 }
2217 
2218 /*
2219  * Set the keepalive interval.
2220  */
2221 static int
2223 {
2224  int interval;
2225 
2226  if (conn->keepalives_interval == NULL)
2227  return 1;
2228 
2230  "keepalives_interval"))
2231  return 0;
2232  if (interval < 0)
2233  interval = 0;
2234 
2235 #ifdef TCP_KEEPINTVL
2236  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
2237  (char *) &interval, sizeof(interval)) < 0)
2238  {
2239  char sebuf[PG_STRERROR_R_BUFLEN];
2240 
2241  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2242  "setsockopt",
2243  "TCP_KEEPINTVL",
2244  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2245  return 0;
2246  }
2247 #endif
2248 
2249  return 1;
2250 }
2251 
2252 /*
2253  * Set the count of lost keepalive packets that will trigger a connection
2254  * break.
2255  */
2256 static int
2258 {
2259  int count;
2260 
2261  if (conn->keepalives_count == NULL)
2262  return 1;
2263 
2264  if (!pqParseIntParam(conn->keepalives_count, &count, conn,
2265  "keepalives_count"))
2266  return 0;
2267  if (count < 0)
2268  count = 0;
2269 
2270 #ifdef TCP_KEEPCNT
2271  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
2272  (char *) &count, sizeof(count)) < 0)
2273  {
2274  char sebuf[PG_STRERROR_R_BUFLEN];
2275 
2276  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2277  "setsockopt",
2278  "TCP_KEEPCNT",
2279  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2280  return 0;
2281  }
2282 #endif
2283 
2284  return 1;
2285 }
2286 #else /* WIN32 */
2287 #ifdef SIO_KEEPALIVE_VALS
2288 /*
2289  * Enable keepalives and set the keepalive values on Win32,
2290  * where they are always set in one batch.
2291  *
2292  * CAUTION: This needs to be signal safe, since it's used by PQcancel.
2293  */
2294 int
2295 pqSetKeepalivesWin32(pgsocket sock, int idle, int interval)
2296 {
2297  struct tcp_keepalive ka;
2298  DWORD retsize;
2299 
2300  if (idle <= 0)
2301  idle = 2 * 60 * 60; /* 2 hours = default */
2302  if (interval <= 0)
2303  interval = 1; /* 1 second = default */
2304 
2305  ka.onoff = 1;
2306  ka.keepalivetime = idle * 1000;
2307  ka.keepaliveinterval = interval * 1000;
2308 
2309  if (WSAIoctl(sock,
2310  SIO_KEEPALIVE_VALS,
2311  (LPVOID) &ka,
2312  sizeof(ka),
2313  NULL,
2314  0,
2315  &retsize,
2316  NULL,
2317  NULL)
2318  != 0)
2319  return 0;
2320  return 1;
2321 }
2322 
2323 static int
2324 prepKeepalivesWin32(PGconn *conn)
2325 {
2326  int idle = -1;
2327  int interval = -1;
2328 
2329  if (conn->keepalives_idle &&
2331  "keepalives_idle"))
2332  return 0;
2333  if (conn->keepalives_interval &&
2335  "keepalives_interval"))
2336  return 0;
2337 
2338  if (!pqSetKeepalivesWin32(conn->sock, idle, interval))
2339  {
2340  libpq_append_conn_error(conn, "%s(%s) failed: error code %d",
2341  "WSAIoctl", "SIO_KEEPALIVE_VALS",
2342  WSAGetLastError());
2343  return 0;
2344  }
2345  return 1;
2346 }
2347 #endif /* SIO_KEEPALIVE_VALS */
2348 #endif /* WIN32 */
2349 
2350 /*
2351  * Set the TCP user timeout.
2352  */
2353 static int
2355 {
2356  int timeout;
2357 
2358  if (conn->pgtcp_user_timeout == NULL)
2359  return 1;
2360 
2361  if (!pqParseIntParam(conn->pgtcp_user_timeout, &timeout, conn,
2362  "tcp_user_timeout"))
2363  return 0;
2364 
2365  if (timeout < 0)
2366  timeout = 0;
2367 
2368 #ifdef TCP_USER_TIMEOUT
2369  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2370  (char *) &timeout, sizeof(timeout)) < 0)
2371  {
2372  char sebuf[256];
2373 
2374  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2375  "setsockopt",
2376  "TCP_USER_TIMEOUT",
2377  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2378  return 0;
2379  }
2380 #endif
2381 
2382  return 1;
2383 }
2384 
2385 /* ----------
2386  * pqConnectDBStart -
2387  * Begin the process of making a connection to the backend.
2388  *
2389  * Returns 1 if successful, 0 if not.
2390  * ----------
2391  */
2392 int
2394 {
2395  if (!conn)
2396  return 0;
2397 
2398  if (!conn->options_valid)
2399  goto connect_errReturn;
2400 
2401  /*
2402  * Check for bad linking to backend-internal versions of src/common
2403  * functions (see comments in link-canary.c for the reason we need this).
2404  * Nobody but developers should see this message, so we don't bother
2405  * translating it.
2406  */
2408  {
2410  "libpq is incorrectly linked to backend functions\n");
2411  goto connect_errReturn;
2412  }
2413 
2414  /* Ensure our buffers are empty */
2415  conn->inStart = conn->inCursor = conn->inEnd = 0;
2416  conn->outCount = 0;
2417 
2418  /*
2419  * Set up to try to connect to the first host. (Setting whichhost = -1 is
2420  * a bit of a cheat, but PQconnectPoll will advance it to 0 before
2421  * anything else looks at it.)
2422  *
2423  * Cancel requests are special though, they should only try one host and
2424  * address, and these fields have already been set up in PQcancelCreate,
2425  * so leave these fields alone for cancel requests.
2426  */
2427  if (!conn->cancelRequest)
2428  {
2429  conn->whichhost = -1;
2430  conn->try_next_host = true;
2431  conn->try_next_addr = false;
2432  }
2433 
2435 
2436  /* Also reset the target_server_type state if needed */
2439 
2440  /*
2441  * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
2442  * so that it can easily be re-executed if needed again during the
2443  * asynchronous startup process. However, we must run it once here,
2444  * because callers expect a success return from this routine to mean that
2445  * we are in PGRES_POLLING_WRITING connection state.
2446  */
2448  return 1;
2449 
2450 connect_errReturn:
2451 
2452  /*
2453  * If we managed to open a socket, close it immediately rather than
2454  * waiting till PQfinish. (The application cannot have gotten the socket
2455  * from PQsocket yet, so this doesn't risk breaking anything.)
2456  */
2457  pqDropConnection(conn, true);
2459  return 0;
2460 }
2461 
2462 
2463 /*
2464  * pqConnectDBComplete
2465  *
2466  * Block and complete a connection.
2467  *
2468  * Returns 1 on success, 0 on failure.
2469  */
2470 int
2472 {
2474  pg_usec_time_t end_time = -1;
2475  int timeout = 0;
2476  int last_whichhost = -2; /* certainly different from whichhost */
2477  int last_whichaddr = -2; /* certainly different from whichaddr */
2478 
2479  if (conn == NULL || conn->status == CONNECTION_BAD)
2480  return 0;
2481 
2482  /*
2483  * Set up a time limit, if connect_timeout is greater than zero.
2484  */
2485  if (conn->connect_timeout != NULL)
2486  {
2487  if (!pqParseIntParam(conn->connect_timeout, &timeout, conn,
2488  "connect_timeout"))
2489  {
2490  /* mark the connection as bad to report the parsing failure */
2492  return 0;
2493  }
2494  }
2495 
2496  for (;;)
2497  {
2498  int ret = 0;
2499 
2500  /*
2501  * (Re)start the connect_timeout timer if it's active and we are
2502  * considering a different host than we were last time through. If
2503  * we've already succeeded, though, needn't recalculate.
2504  */
2505  if (flag != PGRES_POLLING_OK &&
2506  timeout > 0 &&
2507  (conn->whichhost != last_whichhost ||
2508  conn->whichaddr != last_whichaddr))
2509  {
2510  end_time = PQgetCurrentTimeUSec() + (pg_usec_time_t) timeout * 1000000;
2511  last_whichhost = conn->whichhost;
2512  last_whichaddr = conn->whichaddr;
2513  }
2514 
2515  /*
2516  * Wait, if necessary. Note that the initial state (just after
2517  * PQconnectStart) is to wait for the socket to select for writing.
2518  */
2519  switch (flag)
2520  {
2521  case PGRES_POLLING_OK:
2522  return 1; /* success! */
2523 
2524  case PGRES_POLLING_READING:
2525  ret = pqWaitTimed(1, 0, conn, end_time);
2526  if (ret == -1)
2527  {
2528  /* hard failure, eg select() problem, aborts everything */
2530  return 0;
2531  }
2532  break;
2533 
2534  case PGRES_POLLING_WRITING:
2535  ret = pqWaitTimed(0, 1, conn, end_time);
2536  if (ret == -1)
2537  {
2538  /* hard failure, eg select() problem, aborts everything */
2540  return 0;
2541  }
2542  break;
2543 
2544  default:
2545  /* Just in case we failed to set it in PQconnectPoll */
2547  return 0;
2548  }
2549 
2550  if (ret == 1) /* connect_timeout elapsed */
2551  {
2552  /*
2553  * Give up on current server/address, try the next one.
2554  */
2555  conn->try_next_addr = true;
2557  }
2558 
2559  /*
2560  * Now try to advance the state machine.
2561  */
2562  if (conn->cancelRequest)
2564  else
2565  flag = PQconnectPoll(conn);
2566  }
2567 }
2568 
2569 /* ----------------
2570  * PQconnectPoll
2571  *
2572  * Poll an asynchronous connection.
2573  *
2574  * Returns a PostgresPollingStatusType.
2575  * Before calling this function, use select(2) to determine when data
2576  * has arrived..
2577  *
2578  * You must call PQfinish whether or not this fails.
2579  *
2580  * This function and PQconnectStart are intended to allow connections to be
2581  * made without blocking the execution of your program on remote I/O. However,
2582  * there are a number of caveats:
2583  *
2584  * o If you call PQtrace, ensure that the stream object into which you trace
2585  * will not block.
2586  * o If you do not supply an IP address for the remote host (i.e. you
2587  * supply a host name instead) then PQconnectStart will block on
2588  * getaddrinfo. You will be fine if using Unix sockets (i.e. by
2589  * supplying neither a host name nor a host address).
2590  * o If your backend wants to use Kerberos authentication then you must
2591  * supply both a host name and a host address, otherwise this function
2592  * may block on gethostname.
2593  *
2594  * ----------------
2595  */
2598 {
2599  bool reset_connection_state_machine = false;
2600  bool need_new_connection = false;
2601  PGresult *res;
2602  char sebuf[PG_STRERROR_R_BUFLEN];
2603  int optval;
2604 
2605  if (conn == NULL)
2606  return PGRES_POLLING_FAILED;
2607 
2608  /* Get the new data */
2609  switch (conn->status)
2610  {
2611  /*
2612  * We really shouldn't have been polled in these two cases, but we
2613  * can handle it.
2614  */
2615  case CONNECTION_BAD:
2616  return PGRES_POLLING_FAILED;
2617  case CONNECTION_OK:
2618  return PGRES_POLLING_OK;
2619 
2620  /* These are reading states */
2622  case CONNECTION_AUTH_OK:
2624  case CONNECTION_CONSUME:
2626  {
2627  /* Load waiting data */
2628  int n = pqReadData(conn);
2629 
2630  if (n < 0)
2631  goto error_return;
2632  if (n == 0)
2633  return PGRES_POLLING_READING;
2634 
2635  break;
2636  }
2637 
2638  /* These are writing states, so we just proceed. */
2639  case CONNECTION_STARTED:
2640  case CONNECTION_MADE:
2641  break;
2642 
2643  /* Special cases: proceed without waiting. */
2645  case CONNECTION_NEEDED:
2648  break;
2649 
2650  default:
2651  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2652  goto error_return;
2653  }
2654 
2655 
2656 keep_going: /* We will come back to here until there is
2657  * nothing left to do. */
2658 
2659  /* Time to advance to next address, or next host if no more addresses? */
2660  if (conn->try_next_addr)
2661  {
2662  if (conn->whichaddr < conn->naddr)
2663  {
2664  conn->whichaddr++;
2665  reset_connection_state_machine = true;
2666  }
2667  else
2668  conn->try_next_host = true;
2669  conn->try_next_addr = false;
2670  }
2671 
2672  /* Time to advance to next connhost[] entry? */
2673  if (conn->try_next_host)
2674  {
2675  pg_conn_host *ch;
2676  struct addrinfo hint;
2677  struct addrinfo *addrlist;
2678  int thisport;
2679  int ret;
2680  char portstr[MAXPGPATH];
2681 
2682  if (conn->whichhost + 1 < conn->nconnhost)
2683  conn->whichhost++;
2684  else
2685  {
2686  /*
2687  * Oops, no more hosts.
2688  *
2689  * If we are trying to connect in "prefer-standby" mode, then drop
2690  * the standby requirement and start over. Don't do this for
2691  * cancel requests though, since we are certain the list of
2692  * servers won't change as the target_server_type option is not
2693  * applicable to those connections.
2694  *
2695  * Otherwise, an appropriate error message is already set up, so
2696  * we just need to set the right status.
2697  */
2699  conn->nconnhost > 0 &&
2700  !conn->cancelRequest)
2701  {
2703  conn->whichhost = 0;
2704  }
2705  else
2706  goto error_return;
2707  }
2708 
2709  /* Drop any address info for previous host */
2711 
2712  /*
2713  * Look up info for the new host. On failure, log the problem in
2714  * conn->errorMessage, then loop around to try the next host. (Note
2715  * we don't clear try_next_host until we've succeeded.)
2716  */
2717  ch = &conn->connhost[conn->whichhost];
2718 
2719  /* Initialize hint structure */
2720  MemSet(&hint, 0, sizeof(hint));
2721  hint.ai_socktype = SOCK_STREAM;
2722  hint.ai_family = AF_UNSPEC;
2723 
2724  /* Figure out the port number we're going to use. */
2725  if (ch->port == NULL || ch->port[0] == '\0')
2726  thisport = DEF_PGPORT;
2727  else
2728  {
2729  if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
2730  goto error_return;
2731 
2732  if (thisport < 1 || thisport > 65535)
2733  {
2734  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2735  goto keep_going;
2736  }
2737  }
2738  snprintf(portstr, sizeof(portstr), "%d", thisport);
2739 
2740  /* Use pg_getaddrinfo_all() to resolve the address */
2741  switch (ch->type)
2742  {
2743  case CHT_HOST_NAME:
2744  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2745  &addrlist);
2746  if (ret || !addrlist)
2747  {
2748  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2749  ch->host, gai_strerror(ret));
2750  goto keep_going;
2751  }
2752  break;
2753 
2754  case CHT_HOST_ADDRESS:
2755  hint.ai_flags = AI_NUMERICHOST;
2756  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2757  &addrlist);
2758  if (ret || !addrlist)
2759  {
2760  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2761  ch->hostaddr, gai_strerror(ret));
2762  goto keep_going;
2763  }
2764  break;
2765 
2766  case CHT_UNIX_SOCKET:
2767  hint.ai_family = AF_UNIX;
2768  UNIXSOCK_PATH(portstr, thisport, ch->host);
2769  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2770  {
2771  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2772  portstr,
2773  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2774  goto keep_going;
2775  }
2776 
2777  /*
2778  * NULL hostname tells pg_getaddrinfo_all to parse the service
2779  * name as a Unix-domain socket path.
2780  */
2781  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2782  &addrlist);
2783  if (ret || !addrlist)
2784  {
2785  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2786  portstr, gai_strerror(ret));
2787  goto keep_going;
2788  }
2789  break;
2790  }
2791 
2792  /*
2793  * Store a copy of the addrlist in private memory so we can perform
2794  * randomization for load balancing.
2795  */
2796  ret = store_conn_addrinfo(conn, addrlist);
2797  pg_freeaddrinfo_all(hint.ai_family, addrlist);
2798  if (ret)
2799  goto error_return; /* message already logged */
2800 
2801  /*
2802  * If random load balancing is enabled we shuffle the addresses.
2803  */
2805  {
2806  /*
2807  * This is the "inside-out" variant of the Fisher-Yates shuffle
2808  * algorithm. Notionally, we append each new value to the array
2809  * and then swap it with a randomly-chosen array element (possibly
2810  * including itself, else we fail to generate permutations with
2811  * the last integer last). The swap step can be optimized by
2812  * combining it with the insertion.
2813  *
2814  * We don't need to initialize conn->prng_state here, because that
2815  * already happened in pqConnectOptions2.
2816  */
2817  for (int i = 1; i < conn->naddr; i++)
2818  {
2819  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2820  AddrInfo temp = conn->addr[j];
2821 
2822  conn->addr[j] = conn->addr[i];
2823  conn->addr[i] = temp;
2824  }
2825  }
2826 
2827  reset_connection_state_machine = true;
2828  conn->try_next_host = false;
2829  }
2830 
2831  /* Reset connection state machine? */
2832  if (reset_connection_state_machine)
2833  {
2834  /*
2835  * (Re) initialize our connection control variables for a set of
2836  * connection attempts to a single server address. These variables
2837  * must persist across individual connection attempts, but we must
2838  * reset them when we start to consider a new server.
2839  */
2840  conn->pversion = PG_PROTOCOL(3, 0);
2841  conn->send_appname = true;
2842  conn->failed_enc_methods = 0;
2843  conn->current_enc_method = 0;
2845  reset_connection_state_machine = false;
2846  need_new_connection = true;
2847  }
2848 
2849  /* Force a new connection (perhaps to the same server as before)? */
2850  if (need_new_connection)
2851  {
2852  /* Drop any existing connection */
2853  pqDropConnection(conn, true);
2854 
2855  /* Reset all state obtained from old server */
2857 
2858  /* Drop any PGresult we might have, too */
2863 
2864  /* Reset conn->status to put the state machine in the right state */
2866 
2867  need_new_connection = false;
2868  }
2869 
2870  /*
2871  * Decide what to do next, if server rejects SSL or GSS negotiation, but
2872  * the connection is still valid. If there are no options left, error out
2873  * with 'msg'.
2874  */
2875 #define ENCRYPTION_NEGOTIATION_FAILED(msg) \
2876  do { \
2877  switch (encryption_negotiation_failed(conn)) \
2878  { \
2879  case 0: \
2880  libpq_append_conn_error(conn, (msg)); \
2881  goto error_return; \
2882  case 1: \
2883  conn->status = CONNECTION_MADE; \
2884  return PGRES_POLLING_WRITING; \
2885  case 2: \
2886  need_new_connection = true; \
2887  goto keep_going; \
2888  } \
2889  } while(0);
2890 
2891  /*
2892  * Decide what to do next, if connection fails. If there are no options
2893  * left, return with an error. The error message has already been written
2894  * to the connection's error buffer.
2895  */
2896 #define CONNECTION_FAILED() \
2897  do { \
2898  if (connection_failed(conn)) \
2899  { \
2900  need_new_connection = true; \
2901  goto keep_going; \
2902  } \
2903  else \
2904  goto error_return; \
2905  } while(0);
2906 
2907  /* Now try to advance the state machine for this connection */
2908  switch (conn->status)
2909  {
2910  case CONNECTION_NEEDED:
2911  {
2912  /*
2913  * Try to initiate a connection to one of the addresses
2914  * returned by pg_getaddrinfo_all(). conn->whichaddr is the
2915  * next one to try.
2916  *
2917  * The extra level of braces here is historical. It's not
2918  * worth reindenting this whole switch case to remove 'em.
2919  */
2920  {
2921  char host_addr[NI_MAXHOST];
2922  int sock_type;
2923  AddrInfo *addr_cur;
2924 
2925  /*
2926  * Advance to next possible host, if we've tried all of
2927  * the addresses for the current host.
2928  */
2929  if (conn->whichaddr == conn->naddr)
2930  {
2931  conn->try_next_host = true;
2932  goto keep_going;
2933  }
2934  addr_cur = &conn->addr[conn->whichaddr];
2935 
2936  /* Remember current address for possible use later */
2937  memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
2938 
2939 #ifdef ENABLE_GSS
2940 
2941  /*
2942  * Before establishing the connection, check if it's
2943  * doomed to fail because gssencmode='require' but GSSAPI
2944  * is not available.
2945  */
2946  if (conn->gssencmode[0] == 'r')
2947  {
2948  if (conn->raddr.addr.ss_family == AF_UNIX)
2949  {
2951  "GSSAPI encryption required but it is not supported over a local socket");
2952  goto error_return;
2953  }
2954  if (conn->gcred == GSS_C_NO_CREDENTIAL)
2955  {
2956  if (!pg_GSS_have_cred_cache(&conn->gcred))
2957  {
2959  "GSSAPI encryption required but no credential cache");
2960  goto error_return;
2961  }
2962  }
2963  }
2964 #endif
2965 
2966  /*
2967  * Choose the encryption method to try first. Do this
2968  * before establishing the connection, so that if none of
2969  * the modes allowed by the connections options are
2970  * available, we can error out before establishing the
2971  * connection.
2972  */
2974  goto error_return;
2975 
2976  /*
2977  * Set connip, too. Note we purposely ignore strdup
2978  * failure; not a big problem if it fails.
2979  */
2980  if (conn->connip != NULL)
2981  {
2982  free(conn->connip);
2983  conn->connip = NULL;
2984  }
2985  getHostaddr(conn, host_addr, NI_MAXHOST);
2986  if (host_addr[0])
2987  conn->connip = strdup(host_addr);
2988 
2989  /* Try to create the socket */
2990  sock_type = SOCK_STREAM;
2991 #ifdef SOCK_CLOEXEC
2992 
2993  /*
2994  * Atomically mark close-on-exec, if possible on this
2995  * platform, so that there isn't a window where a
2996  * subprogram executed by another thread inherits the
2997  * socket. See fallback code below.
2998  */
2999  sock_type |= SOCK_CLOEXEC;
3000 #endif
3001 #ifdef SOCK_NONBLOCK
3002 
3003  /*
3004  * We might as well skip a system call for nonblocking
3005  * mode too, if we can.
3006  */
3007  sock_type |= SOCK_NONBLOCK;
3008 #endif
3009  conn->sock = socket(addr_cur->family, sock_type, 0);
3010  if (conn->sock == PGINVALID_SOCKET)
3011  {
3012  int errorno = SOCK_ERRNO;
3013 
3014  /*
3015  * Silently ignore socket() failure if we have more
3016  * addresses to try; this reduces useless chatter in
3017  * cases where the address list includes both IPv4 and
3018  * IPv6 but kernel only accepts one family.
3019  */
3020  if (conn->whichaddr < conn->naddr ||
3021  conn->whichhost + 1 < conn->nconnhost)
3022  {
3023  conn->try_next_addr = true;
3024  goto keep_going;
3025  }
3026  emitHostIdentityInfo(conn, host_addr);
3027  libpq_append_conn_error(conn, "could not create socket: %s",
3028  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
3029  goto error_return;
3030  }
3031 
3032  /*
3033  * Once we've identified a target address, all errors
3034  * except the preceding socket()-failure case should be
3035  * prefixed with host-identity information. (If the
3036  * connection succeeds, the contents of conn->errorMessage
3037  * won't matter, so this is harmless.)
3038  */
3039  emitHostIdentityInfo(conn, host_addr);
3040 
3041  /*
3042  * Select socket options: no delay of outgoing data for
3043  * TCP sockets, nonblock mode, close-on-exec. Try the
3044  * next address if any of this fails.
3045  */
3046  if (addr_cur->family != AF_UNIX)
3047  {
3048  if (!connectNoDelay(conn))
3049  {
3050  /* error message already created */
3051  conn->try_next_addr = true;
3052  goto keep_going;
3053  }
3054  }
3055 #ifndef SOCK_NONBLOCK
3056  if (!pg_set_noblock(conn->sock))
3057  {
3058  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
3059  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3060  conn->try_next_addr = true;
3061  goto keep_going;
3062  }
3063 #endif
3064 
3065 #ifndef SOCK_CLOEXEC
3066 #ifdef F_SETFD
3067  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
3068  {
3069  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
3070  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3071  conn->try_next_addr = true;
3072  goto keep_going;
3073  }
3074 #endif /* F_SETFD */
3075 #endif
3076 
3077  if (addr_cur->family != AF_UNIX)
3078  {
3079 #ifndef WIN32
3080  int on = 1;
3081 #endif
3082  int usekeepalives = useKeepalives(conn);
3083  int err = 0;
3084 
3085  if (usekeepalives < 0)
3086  {
3087  /* error is already reported */
3088  err = 1;
3089  }
3090  else if (usekeepalives == 0)
3091  {
3092  /* Do nothing */
3093  }
3094 #ifndef WIN32
3095  else if (setsockopt(conn->sock,
3096  SOL_SOCKET, SO_KEEPALIVE,
3097  (char *) &on, sizeof(on)) < 0)
3098  {
3099  libpq_append_conn_error(conn, "%s(%s) failed: %s",
3100  "setsockopt",
3101  "SO_KEEPALIVE",
3102  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3103  err = 1;
3104  }
3105  else if (!setKeepalivesIdle(conn)
3107  || !setKeepalivesCount(conn))
3108  err = 1;
3109 #else /* WIN32 */
3110 #ifdef SIO_KEEPALIVE_VALS
3111  else if (!prepKeepalivesWin32(conn))
3112  err = 1;
3113 #endif /* SIO_KEEPALIVE_VALS */
3114 #endif /* WIN32 */
3115  else if (!setTCPUserTimeout(conn))
3116  err = 1;
3117 
3118  if (err)
3119  {
3120  conn->try_next_addr = true;
3121  goto keep_going;
3122  }
3123  }
3124 
3125  /*----------
3126  * We have three methods of blocking SIGPIPE during
3127  * send() calls to this socket:
3128  *
3129  * - setsockopt(sock, SO_NOSIGPIPE)
3130  * - send(sock, ..., MSG_NOSIGNAL)
3131  * - setting the signal mask to SIG_IGN during send()
3132  *
3133  * The third method requires three syscalls per send,
3134  * so we prefer either of the first two, but they are
3135  * less portable. The state is tracked in the following
3136  * members of PGconn:
3137  *
3138  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3139  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3140  *
3141  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3142  * and we're done. Otherwise, set sigpipe_flag so that
3143  * we will try MSG_NOSIGNAL on sends. If we get an error
3144  * with MSG_NOSIGNAL, we'll clear that flag and revert to
3145  * signal masking.
3146  *----------
3147  */
3148  conn->sigpipe_so = false;
3149 #ifdef MSG_NOSIGNAL
3150  conn->sigpipe_flag = true;
3151 #else
3152  conn->sigpipe_flag = false;
3153 #endif /* MSG_NOSIGNAL */
3154 
3155 #ifdef SO_NOSIGPIPE
3156  optval = 1;
3157  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3158  (char *) &optval, sizeof(optval)) == 0)
3159  {
3160  conn->sigpipe_so = true;
3161  conn->sigpipe_flag = false;
3162  }
3163 #endif /* SO_NOSIGPIPE */
3164 
3165  /*
3166  * Start/make connection. This should not block, since we
3167  * are in nonblock mode. If it does, well, too bad.
3168  */
3169  if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3170  addr_cur->addr.salen) < 0)
3171  {
3172  if (SOCK_ERRNO == EINPROGRESS ||
3173 #ifdef WIN32
3174  SOCK_ERRNO == EWOULDBLOCK ||
3175 #endif
3176  SOCK_ERRNO == EINTR)
3177  {
3178  /*
3179  * This is fine - we're in non-blocking mode, and
3180  * the connection is in progress. Tell caller to
3181  * wait for write-ready on socket.
3182  */
3184  return PGRES_POLLING_WRITING;
3185  }
3186  /* otherwise, trouble */
3187  }
3188  else
3189  {
3190  /*
3191  * Hm, we're connected already --- seems the "nonblock
3192  * connection" wasn't. Advance the state machine and
3193  * go do the next stuff.
3194  */
3196  goto keep_going;
3197  }
3198 
3199  /*
3200  * This connection failed. Add the error report to
3201  * conn->errorMessage, then try the next address if any.
3202  */
3204  conn->try_next_addr = true;
3205  goto keep_going;
3206  }
3207  }
3208 
3209  case CONNECTION_STARTED:
3210  {
3211  socklen_t optlen = sizeof(optval);
3212 
3213  /*
3214  * Write ready, since we've made it here, so the connection
3215  * has been made ... or has failed.
3216  */
3217 
3218  /*
3219  * Now check (using getsockopt) that there is not an error
3220  * state waiting for us on the socket.
3221  */
3222 
3223  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3224  (char *) &optval, &optlen) == -1)
3225  {
3226  libpq_append_conn_error(conn, "could not get socket error status: %s",
3227  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3228  goto error_return;
3229  }
3230  else if (optval != 0)
3231  {
3232  /*
3233  * When using a nonblocking connect, we will typically see
3234  * connect failures at this point, so provide a friendly
3235  * error message.
3236  */
3237  connectFailureMessage(conn, optval);
3238 
3239  /*
3240  * Try the next address if any, just as in the case where
3241  * connect() returned failure immediately.
3242  */
3243  conn->try_next_addr = true;
3244  goto keep_going;
3245  }
3246 
3247  /* Fill in the client address */
3248  conn->laddr.salen = sizeof(conn->laddr.addr);
3249  if (getsockname(conn->sock,
3250  (struct sockaddr *) &conn->laddr.addr,
3251  &conn->laddr.salen) < 0)
3252  {
3253  libpq_append_conn_error(conn, "could not get client address from socket: %s",
3254  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3255  goto error_return;
3256  }
3257 
3258  /*
3259  * Implement requirepeer check, if requested and it's a
3260  * Unix-domain socket.
3261  */
3262  if (conn->requirepeer && conn->requirepeer[0] &&
3263  conn->raddr.addr.ss_family == AF_UNIX)
3264  {
3265 #ifndef WIN32
3266  char *remote_username;
3267 #endif
3268  uid_t uid;
3269  gid_t gid;
3270 
3271  errno = 0;
3272  if (getpeereid(conn->sock, &uid, &gid) != 0)
3273  {
3274  /*
3275  * Provide special error message if getpeereid is a
3276  * stub
3277  */
3278  if (errno == ENOSYS)
3279  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3280  else
3281  libpq_append_conn_error(conn, "could not get peer credentials: %s",
3282  strerror_r(errno, sebuf, sizeof(sebuf)));
3283  goto error_return;
3284  }
3285 
3286 #ifndef WIN32
3287  remote_username = pg_fe_getusername(uid,
3288  &conn->errorMessage);
3289  if (remote_username == NULL)
3290  goto error_return; /* message already logged */
3291 
3292  if (strcmp(remote_username, conn->requirepeer) != 0)
3293  {
3294  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3295  conn->requirepeer, remote_username);
3296  free(remote_username);
3297  goto error_return;
3298  }
3299  free(remote_username);
3300 #else /* WIN32 */
3301  /* should have failed with ENOSYS above */
3302  Assert(false);
3303 #endif /* WIN32 */
3304  }
3305 
3306  /*
3307  * Make sure we can write before advancing to next step.
3308  */
3310  return PGRES_POLLING_WRITING;
3311  }
3312 
3313  case CONNECTION_MADE:
3314  {
3315  char *startpacket;
3316  int packetlen;
3317 
3318 #ifdef ENABLE_GSS
3319 
3320  /*
3321  * If GSSAPI encryption is enabled, send a packet to the
3322  * server asking for GSSAPI Encryption and proceed with GSSAPI
3323  * handshake. We will come back here after GSSAPI encryption
3324  * has been established, with conn->gctx set.
3325  */
3326  if (conn->current_enc_method == ENC_GSSAPI && !conn->gctx)
3327  {
3329 
3330  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3331  {
3332  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3333  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3334  goto error_return;
3335  }
3336 
3337  /* Ok, wait for response */
3339  return PGRES_POLLING_READING;
3340  }
3341 #endif
3342 
3343 #ifdef USE_SSL
3344 
3345  /*
3346  * If SSL is enabled, start the SSL negotiation. We will come
3347  * back here after SSL encryption has been established, with
3348  * ssl_in_use set.
3349  */
3351  {
3352  /*
3353  * If traditional postgres SSL negotiation is used, send
3354  * the SSL request. In direct negotiation, jump straight
3355  * into the SSL handshake.
3356  */
3357  if (conn->sslnegotiation[0] == 'p')
3358  {
3359  ProtocolVersion pv;
3360 
3361  /*
3362  * Send the SSL request packet.
3363  *
3364  * Theoretically, this could block, but it really
3365  * shouldn't since we only got here if the socket is
3366  * write-ready.
3367  */
3369  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3370  {
3371  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3372  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3373  goto error_return;
3374  }
3375  /* Ok, wait for response */
3377  return PGRES_POLLING_READING;
3378  }
3379  else
3380  {
3381  Assert(conn->sslnegotiation[0] == 'd');
3383  return PGRES_POLLING_WRITING;
3384  }
3385  }
3386 #endif /* USE_SSL */
3387 
3388  /*
3389  * For cancel requests this is as far as we need to go in the
3390  * connection establishment. Now we can actually send our
3391  * cancellation request.
3392  */
3393  if (conn->cancelRequest)
3394  {
3395  CancelRequestPacket cancelpacket;
3396 
3397  packetlen = sizeof(cancelpacket);
3399  cancelpacket.backendPID = pg_hton32(conn->be_pid);
3400  cancelpacket.cancelAuthCode = pg_hton32(conn->be_key);
3401  if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK)
3402  {
3403  libpq_append_conn_error(conn, "could not send cancel packet: %s",
3404  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3405  goto error_return;
3406  }
3408  return PGRES_POLLING_READING;
3409  }
3410 
3411  /*
3412  * We have now established encryption, or we are happy to
3413  * proceed without.
3414  */
3415 
3416  /* Build the startup packet. */
3417  startpacket = pqBuildStartupPacket3(conn, &packetlen,
3419  if (!startpacket)
3420  {
3421  libpq_append_conn_error(conn, "out of memory");
3422  goto error_return;
3423  }
3424 
3425  /*
3426  * Send the startup packet.
3427  *
3428  * Theoretically, this could block, but it really shouldn't
3429  * since we only got here if the socket is write-ready.
3430  */
3431  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3432  {
3433  libpq_append_conn_error(conn, "could not send startup packet: %s",
3434  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3435  free(startpacket);
3436  goto error_return;
3437  }
3438 
3439  free(startpacket);
3440 
3442  return PGRES_POLLING_READING;
3443  }
3444 
3445  /*
3446  * Handle SSL negotiation: wait for postmaster messages and
3447  * respond as necessary.
3448  */
3450  {
3451 #ifdef USE_SSL
3452  PostgresPollingStatusType pollres;
3453 
3454  /*
3455  * On first time through with traditional SSL negotiation, get
3456  * the postmaster's response to our SSLRequest packet. With
3457  * sslnegotiation='direct', go straight to initiating SSL.
3458  */
3459  if (!conn->ssl_in_use && conn->sslnegotiation[0] == 'p')
3460  {
3461  /*
3462  * We use pqReadData here since it has the logic to
3463  * distinguish no-data-yet from connection closure. Since
3464  * conn->ssl isn't set, a plain recv() will occur.
3465  */
3466  char SSLok;
3467  int rdresult;
3468 
3469  rdresult = pqReadData(conn);
3470  if (rdresult < 0)
3471  {
3472  /* errorMessage is already filled in */
3473  goto error_return;
3474  }
3475  if (rdresult == 0)
3476  {
3477  /* caller failed to wait for data */
3478  return PGRES_POLLING_READING;
3479  }
3480  if (pqGetc(&SSLok, conn) < 0)
3481  {
3482  /* should not happen really */
3483  return PGRES_POLLING_READING;
3484  }
3485  if (SSLok == 'S')
3486  {
3487  if (conn->Pfdebug)
3488  pqTraceOutputCharResponse(conn, "SSLResponse",
3489  SSLok);
3490  /* mark byte consumed */
3491  conn->inStart = conn->inCursor;
3492  }
3493  else if (SSLok == 'N')
3494  {
3495  if (conn->Pfdebug)
3496  pqTraceOutputCharResponse(conn, "SSLResponse",
3497  SSLok);
3498  /* mark byte consumed */
3499  conn->inStart = conn->inCursor;
3500 
3501  /*
3502  * The connection is still valid, so if it's OK to
3503  * continue without SSL, we can proceed using this
3504  * connection. Otherwise return with an error.
3505  */
3506  ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server does not support SSL, but SSL was required"));
3507  }
3508  else if (SSLok == 'E')
3509  {
3510  /*
3511  * Server failure of some sort, such as failure to
3512  * fork a backend process. We need to process and
3513  * report the error message, which might be formatted
3514  * according to either protocol 2 or protocol 3.
3515  * Rather than duplicate the code for that, we flip
3516  * into AWAITING_RESPONSE state and let the code there
3517  * deal with it. Note we have *not* consumed the "E"
3518  * byte here.
3519  */
3521 
3522  /*
3523  * Don't fall back to a plaintext connection after
3524  * reading the error.
3525  */
3527  goto keep_going;
3528  }
3529  else
3530  {
3531  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3532  SSLok);
3533  goto error_return;
3534  }
3535  }
3536 
3537  /*
3538  * Begin or continue the SSL negotiation process.
3539  */
3540  pollres = pqsecure_open_client(conn);
3541  if (pollres == PGRES_POLLING_OK)
3542  {
3543  /*
3544  * At this point we should have no data already buffered.
3545  * If we do, it was received before we performed the SSL
3546  * handshake, so it wasn't encrypted and indeed may have
3547  * been injected by a man-in-the-middle.
3548  */
3549  if (conn->inCursor != conn->inEnd)
3550  {
3551  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3552  goto error_return;
3553  }
3554 
3555  /* SSL handshake done, ready to send startup packet */
3557  return PGRES_POLLING_WRITING;
3558  }
3559  if (pollres == PGRES_POLLING_FAILED)
3560  {
3561  /*
3562  * SSL handshake failed. We will retry with a plaintext
3563  * connection, if permitted by sslmode.
3564  */
3566  }
3567  /* Else, return POLLING_READING or POLLING_WRITING status */
3568  return pollres;
3569 #else /* !USE_SSL */
3570  /* can't get here */
3571  goto error_return;
3572 #endif /* USE_SSL */
3573  }
3574 
3576  {
3577 #ifdef ENABLE_GSS
3578  PostgresPollingStatusType pollres;
3579 
3580  /*
3581  * If we haven't yet, get the postmaster's response to our
3582  * negotiation packet
3583  */
3584  if (!conn->gctx)
3585  {
3586  char gss_ok;
3587  int rdresult = pqReadData(conn);
3588 
3589  if (rdresult < 0)
3590  /* pqReadData fills in error message */
3591  goto error_return;
3592  else if (rdresult == 0)
3593  /* caller failed to wait for data */
3594  return PGRES_POLLING_READING;
3595  if (pqGetc(&gss_ok, conn) < 0)
3596  /* shouldn't happen... */
3597  return PGRES_POLLING_READING;
3598 
3599  if (gss_ok == 'E')
3600  {
3601  /*
3602  * Server failure of some sort, possibly protocol
3603  * version support failure. We need to process and
3604  * report the error message, which might be formatted
3605  * according to either protocol 2 or protocol 3.
3606  * Rather than duplicate the code for that, we flip
3607  * into AWAITING_RESPONSE state and let the code there
3608  * deal with it. Note we have *not* consumed the "E"
3609  * byte here.
3610  *
3611  * Note that unlike on an error response to
3612  * SSLRequest, we allow falling back to SSL or
3613  * plaintext connection here. GSS support was
3614  * introduced in PostgreSQL version 12, so an error
3615  * response might mean that we are connecting to a
3616  * pre-v12 server.
3617  */
3619  goto keep_going;
3620  }
3621 
3622  /* mark byte consumed */
3623  conn->inStart = conn->inCursor;
3624 
3625  if (gss_ok == 'N')
3626  {
3627  if (conn->Pfdebug)
3628  pqTraceOutputCharResponse(conn, "GSSENCResponse",
3629  gss_ok);
3630 
3631  /*
3632  * The connection is still valid, so if it's OK to
3633  * continue without GSS, we can proceed using this
3634  * connection. Otherwise return with an error.
3635  */
3636  ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server doesn't support GSSAPI encryption, but it was required"));
3637  }
3638  else if (gss_ok != 'G')
3639  {
3640  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3641  gss_ok);
3642  goto error_return;
3643  }
3644 
3645  if (conn->Pfdebug)
3646  pqTraceOutputCharResponse(conn, "GSSENCResponse",
3647  gss_ok);
3648  }
3649 
3650  /* Begin or continue GSSAPI negotiation */
3651  pollres = pqsecure_open_gss(conn);
3652  if (pollres == PGRES_POLLING_OK)
3653  {
3654  /*
3655  * At this point we should have no data already buffered.
3656  * If we do, it was received before we performed the GSS
3657  * handshake, so it wasn't encrypted and indeed may have
3658  * been injected by a man-in-the-middle.
3659  */
3660  if (conn->inCursor != conn->inEnd)
3661  {
3662  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3663  goto error_return;
3664  }
3665 
3666  /* All set for startup packet */
3668  return PGRES_POLLING_WRITING;
3669  }
3670  else if (pollres == PGRES_POLLING_FAILED)
3671  {
3672  /*
3673  * GSS handshake failed. We will retry with an SSL or
3674  * plaintext connection, if permitted by the options.
3675  */
3677  }
3678  /* Else, return POLLING_READING or POLLING_WRITING status */
3679  return pollres;
3680 #else /* !ENABLE_GSS */
3681  /* unreachable */
3682  goto error_return;
3683 #endif /* ENABLE_GSS */
3684  }
3685 
3686  /*
3687  * Handle authentication exchange: wait for postmaster messages
3688  * and respond as necessary.
3689  */
3691  {
3692  char beresp;
3693  int msgLength;
3694  int avail;
3695  AuthRequest areq;
3696  int res;
3697 
3698  /*
3699  * Scan the message from current point (note that if we find
3700  * the message is incomplete, we will return without advancing
3701  * inStart, and resume here next time).
3702  */
3703  conn->inCursor = conn->inStart;
3704 
3705  /* Read type byte */
3706  if (pqGetc(&beresp, conn))
3707  {
3708  /* We'll come back when there is more data */
3709  return PGRES_POLLING_READING;
3710  }
3711 
3712  /*
3713  * Validate message type: we expect only an authentication
3714  * request, NegotiateProtocolVersion, or an error here.
3715  * Anything else probably means it's not Postgres on the other
3716  * end at all.
3717  */
3718  if (beresp != PqMsg_AuthenticationRequest &&
3719  beresp != PqMsg_ErrorResponse &&
3721  {
3722  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3723  beresp);
3724  goto error_return;
3725  }
3726 
3727  /* Read message length word */
3728  if (pqGetInt(&msgLength, 4, conn))
3729  {
3730  /* We'll come back when there is more data */
3731  return PGRES_POLLING_READING;
3732  }
3733 
3734  /*
3735  * Try to validate message length before using it.
3736  *
3737  * Authentication requests can't be very large, although GSS
3738  * auth requests may not be that small. Same for
3739  * NegotiateProtocolVersion.
3740  *
3741  * Errors can be a little larger, but not huge. If we see a
3742  * large apparent length in an error, it means we're really
3743  * talking to a pre-3.0-protocol server; cope. (Before
3744  * version 14, the server also used the old protocol for
3745  * errors that happened before processing the startup packet.)
3746  */
3747  if (beresp == PqMsg_AuthenticationRequest &&
3748  (msgLength < 8 || msgLength > 2000))
3749  {
3750  libpq_append_conn_error(conn, "received invalid authentication request");
3751  goto error_return;
3752  }
3753  if (beresp == PqMsg_NegotiateProtocolVersion &&
3754  (msgLength < 8 || msgLength > 2000))
3755  {
3756  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3757  goto error_return;
3758  }
3759 
3760 #define MAX_ERRLEN 30000
3761  if (beresp == PqMsg_ErrorResponse &&
3762  (msgLength < 8 || msgLength > MAX_ERRLEN))
3763  {
3764  /* Handle error from a pre-3.0 server */
3765  conn->inCursor = conn->inStart + 1; /* reread data */
3767  {
3768  /*
3769  * We may not have authenticated the server yet, so
3770  * don't let the buffer grow forever.
3771  */
3772  avail = conn->inEnd - conn->inCursor;
3773  if (avail > MAX_ERRLEN)
3774  {
3775  libpq_append_conn_error(conn, "received invalid error message");
3776  goto error_return;
3777  }
3778 
3779  /* We'll come back when there is more data */
3780  return PGRES_POLLING_READING;
3781  }
3782  /* OK, we read the message; mark data consumed */
3784 
3785  /*
3786  * Before 7.2, the postmaster didn't always end its
3787  * messages with a newline, so add one if needed to
3788  * conform to libpq conventions.
3789  */
3790  if (conn->errorMessage.len == 0 ||
3791  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3792  {
3794  }
3795 
3796  goto error_return;
3797  }
3798 #undef MAX_ERRLEN
3799 
3800  /*
3801  * Can't process if message body isn't all here yet.
3802  *
3803  * After this check passes, any further EOF during parsing
3804  * implies that the server sent a bad/truncated message.
3805  * Reading more bytes won't help in that case, so don't return
3806  * PGRES_POLLING_READING after this point.
3807  */
3808  msgLength -= 4;
3809  avail = conn->inEnd - conn->inCursor;
3810  if (avail < msgLength)
3811  {
3812  /*
3813  * Before returning, try to enlarge the input buffer if
3814  * needed to hold the whole message; see notes in
3815  * pqParseInput3.
3816  */
3817  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3818  conn))
3819  goto error_return;
3820  /* We'll come back when there is more data */
3821  return PGRES_POLLING_READING;
3822  }
3823 
3824  /* Handle errors. */
3825  if (beresp == PqMsg_ErrorResponse)
3826  {
3827  if (pqGetErrorNotice3(conn, true))
3828  {
3829  libpq_append_conn_error(conn, "received invalid error message");
3830  goto error_return;
3831  }
3832  /* OK, we read the message; mark data consumed */
3834 
3835  /*
3836  * If error is "cannot connect now", try the next host if
3837  * any (but we don't want to consider additional addresses
3838  * for this host, nor is there much point in changing SSL
3839  * or GSS mode). This is helpful when dealing with
3840  * standby servers that might not be in hot-standby state.
3841  */
3842  if (strcmp(conn->last_sqlstate,
3844  {
3845  conn->try_next_host = true;
3846  goto keep_going;
3847  }
3848 
3849  /* Check to see if we should mention pgpassfile */
3851 
3853  }
3854  else if (beresp == PqMsg_NegotiateProtocolVersion)
3855  {
3857  {
3858  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3859  goto error_return;
3860  }
3861  /* OK, we read the message; mark data consumed */
3863  goto error_return;
3864  }
3865 
3866  /* It is an authentication request. */
3867  conn->auth_req_received = true;
3868 
3869  /* Get the type of request. */
3870  if (pqGetInt((int *) &areq, 4, conn))
3871  {
3872  /* can't happen because we checked the length already */
3873  libpq_append_conn_error(conn, "received invalid authentication request");
3874  goto error_return;
3875  }
3876  msgLength -= 4;
3877 
3878  /*
3879  * Process the rest of the authentication request message, and
3880  * respond to it if necessary.
3881  *
3882  * Note that conn->pghost must be non-NULL if we are going to
3883  * avoid the Kerberos code doing a hostname look-up.
3884  */
3885  res = pg_fe_sendauth(areq, msgLength, conn);
3886 
3887  /*
3888  * OK, we have processed the message; mark data consumed. We
3889  * don't call pqParseDone here because we already traced this
3890  * message inside pg_fe_sendauth.
3891  */
3892  conn->inStart = conn->inCursor;
3893 
3894  if (res != STATUS_OK)
3895  goto error_return;
3896 
3897  /*
3898  * Just make sure that any data sent by pg_fe_sendauth is
3899  * flushed out. Although this theoretically could block, it
3900  * really shouldn't since we don't send large auth responses.
3901  */
3902  if (pqFlush(conn))
3903  goto error_return;
3904 
3905  if (areq == AUTH_REQ_OK)
3906  {
3907  /* We are done with authentication exchange */
3909 
3910  /*
3911  * Set asyncStatus so that PQgetResult will think that
3912  * what comes back next is the result of a query. See
3913  * below.
3914  */
3916  }
3917 
3918  /* Look to see if we have more data yet. */
3919  goto keep_going;
3920  }
3921 
3922  case CONNECTION_AUTH_OK:
3923  {
3924  /*
3925  * Now we expect to hear from the backend. A ReadyForQuery
3926  * message indicates that startup is successful, but we might
3927  * also get an Error message indicating failure. (Notice
3928  * messages indicating nonfatal warnings are also allowed by
3929  * the protocol, as are ParameterStatus and BackendKeyData
3930  * messages.) Easiest way to handle this is to let
3931  * PQgetResult() read the messages. We just have to fake it
3932  * out about the state of the connection, by setting
3933  * asyncStatus = PGASYNC_BUSY (done above).
3934  */
3935 
3936  if (PQisBusy(conn))
3937  return PGRES_POLLING_READING;
3938 
3939  res = PQgetResult(conn);
3940 
3941  /*
3942  * NULL return indicating we have gone to IDLE state is
3943  * expected
3944  */
3945  if (res)
3946  {
3948  libpq_append_conn_error(conn, "unexpected message from server during startup");
3949  else if (conn->send_appname &&
3950  (conn->appname || conn->fbappname))
3951  {
3952  /*
3953  * If we tried to send application_name, check to see
3954  * if the error is about that --- pre-9.0 servers will
3955  * reject it at this stage of the process. If so,
3956  * close the connection and retry without sending
3957  * application_name. We could possibly get a false
3958  * SQLSTATE match here and retry uselessly, but there
3959  * seems no great harm in that; we'll just get the
3960  * same error again if it's unrelated.
3961  */
3962  const char *sqlstate;
3963 
3965  if (sqlstate &&
3966  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3967  {
3968  PQclear(res);
3969  conn->send_appname = false;
3970  need_new_connection = true;
3971  goto keep_going;
3972  }
3973  }
3974 
3975  /*
3976  * if the resultStatus is FATAL, then conn->errorMessage
3977  * already has a copy of the error; needn't copy it back.
3978  * But add a newline if it's not there already, since
3979  * postmaster error messages may not have one.
3980  */
3981  if (conn->errorMessage.len <= 0 ||
3982  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3984  PQclear(res);
3985  goto error_return;
3986  }
3987 
3988  /* Almost there now ... */
3990  goto keep_going;
3991  }
3992 
3994  {
3995  /*
3996  * If a read-write, read-only, primary, or standby connection
3997  * is required, see if we have one.
3998  */
4001  {
4002  bool read_only_server;
4003 
4004  /*
4005  * If the server didn't report
4006  * "default_transaction_read_only" or "in_hot_standby" at
4007  * startup, we must determine its state by sending the
4008  * query "SHOW transaction_read_only". This GUC exists in
4009  * all server versions that support 3.0 protocol.
4010  */
4013  {
4014  /*
4015  * We use PQsendQueryContinue so that
4016  * conn->errorMessage does not get cleared. We need
4017  * to preserve any error messages related to previous
4018  * hosts we have tried and failed to connect to.
4019  */
4022  "SHOW transaction_read_only"))
4023  goto error_return;
4024  /* We'll return to this state when we have the answer */
4026  return PGRES_POLLING_READING;
4027  }
4028 
4029  /* OK, we can make the test */
4030  read_only_server =
4033 
4035  read_only_server : !read_only_server)
4036  {
4037  /* Wrong server state, reject and try the next host */
4039  libpq_append_conn_error(conn, "session is read-only");
4040  else
4041  libpq_append_conn_error(conn, "session is not read-only");
4042 
4043  /* Close connection politely. */
4046 
4047  /*
4048  * Try next host if any, but we don't want to consider
4049  * additional addresses for this host.
4050  */
4051  conn->try_next_host = true;
4052  goto keep_going;
4053  }
4054  }
4058  {
4059  /*
4060  * If the server didn't report "in_hot_standby" at
4061  * startup, we must determine its state by sending the
4062  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
4063  * before 9.0 don't have that function, but by the same
4064  * token they don't have any standby mode, so we may just
4065  * assume the result.
4066  */
4067  if (conn->sversion < 90000)
4069 
4071  {
4072  /*
4073  * We use PQsendQueryContinue so that
4074  * conn->errorMessage does not get cleared. We need
4075  * to preserve any error messages related to previous
4076  * hosts we have tried and failed to connect to.
4077  */
4080  "SELECT pg_catalog.pg_is_in_recovery()"))
4081  goto error_return;
4082  /* We'll return to this state when we have the answer */
4084  return PGRES_POLLING_READING;
4085  }
4086 
4087  /* OK, we can make the test */
4091  {
4092  /* Wrong server state, reject and try the next host */
4094  libpq_append_conn_error(conn, "server is in hot standby mode");
4095  else
4096  libpq_append_conn_error(conn, "server is not in hot standby mode");
4097 
4098  /* Close connection politely. */
4101 
4102  /*
4103  * Try next host if any, but we don't want to consider
4104  * additional addresses for this host.
4105  */
4106  conn->try_next_host = true;
4107  goto keep_going;
4108  }
4109  }
4110 
4111  /*
4112  * For non cancel requests we can release the address list
4113  * now. For cancel requests we never actually resolve
4114  * addresses and instead the addrinfo exists for the lifetime
4115  * of the connection.
4116  */
4117  if (!conn->cancelRequest)
4119 
4120  /*
4121  * Contents of conn->errorMessage are no longer interesting
4122  * (and it seems some clients expect it to be empty after a
4123  * successful connection).
4124  */
4126 
4127  /* We are open for business! */
4129  return PGRES_POLLING_OK;
4130  }
4131 
4132  case CONNECTION_CONSUME:
4133  {
4134  /*
4135  * This state just makes sure the connection is idle after
4136  * we've obtained the result of a SHOW or SELECT query. Once
4137  * we're clear, return to CONNECTION_CHECK_TARGET state to
4138  * decide what to do next. We must transiently set status =
4139  * CONNECTION_OK in order to use the result-consuming
4140  * subroutines.
4141  */
4143  if (!PQconsumeInput(conn))
4144  goto error_return;
4145 
4146  if (PQisBusy(conn))
4147  {
4149  return PGRES_POLLING_READING;
4150  }
4151 
4152  /* Call PQgetResult() again until we get a NULL result */
4153  res = PQgetResult(conn);
4154  if (res != NULL)
4155  {
4156  PQclear(res);
4158  return PGRES_POLLING_READING;
4159  }
4160 
4162  goto keep_going;
4163  }
4164 
4166  {
4167  /*
4168  * Waiting for result of "SHOW transaction_read_only". We
4169  * must transiently set status = CONNECTION_OK in order to use
4170  * the result-consuming subroutines.
4171  */
4173  if (!PQconsumeInput(conn))
4174  goto error_return;
4175 
4176  if (PQisBusy(conn))
4177  {
4179  return PGRES_POLLING_READING;
4180  }
4181 
4182  res = PQgetResult(conn);
4183  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4184  PQntuples(res) == 1)
4185  {
4186  char *val = PQgetvalue(res, 0, 0);
4187 
4188  /*
4189  * "transaction_read_only = on" proves that at least one
4190  * of default_transaction_read_only and in_hot_standby is
4191  * on, but we don't actually know which. We don't care
4192  * though for the purpose of identifying a read-only
4193  * session, so satisfy the CONNECTION_CHECK_TARGET code by
4194  * claiming they are both on. On the other hand, if it's
4195  * a read-write session, they are certainly both off.
4196  */
4197  if (strncmp(val, "on", 2) == 0)
4198  {
4201  }
4202  else
4203  {
4206  }
4207  PQclear(res);
4208 
4209  /* Finish reading messages before continuing */
4211  goto keep_going;
4212  }
4213 
4214  /* Something went wrong with "SHOW transaction_read_only". */
4215  PQclear(res);
4216 
4217  /* Append error report to conn->errorMessage. */
4218  libpq_append_conn_error(conn, "\"%s\" failed",
4219  "SHOW transaction_read_only");
4220 
4221  /* Close connection politely. */
4224 
4225  /* Try next host. */
4226  conn->try_next_host = true;
4227  goto keep_going;
4228  }
4229 
4231  {
4232  /*
4233  * Waiting for result of "SELECT pg_is_in_recovery()". We
4234  * must transiently set status = CONNECTION_OK in order to use
4235  * the result-consuming subroutines.
4236  */
4238  if (!PQconsumeInput(conn))
4239  goto error_return;
4240 
4241  if (PQisBusy(conn))
4242  {
4244  return PGRES_POLLING_READING;
4245  }
4246 
4247  res = PQgetResult(conn);
4248  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4249  PQntuples(res) == 1)
4250  {
4251  char *val = PQgetvalue(res, 0, 0);
4252 
4253  if (strncmp(val, "t", 1) == 0)
4255  else
4257  PQclear(res);
4258 
4259  /* Finish reading messages before continuing */
4261  goto keep_going;
4262  }
4263 
4264  /* Something went wrong with "SELECT pg_is_in_recovery()". */
4265  PQclear(res);
4266 
4267  /* Append error report to conn->errorMessage. */
4268  libpq_append_conn_error(conn, "\"%s\" failed",
4269  "SELECT pg_is_in_recovery()");
4270 
4271  /* Close connection politely. */
4274 
4275  /* Try next host. */
4276  conn->try_next_host = true;
4277  goto keep_going;
4278  }
4279 
4280  default:
4282  "invalid connection state %d, probably indicative of memory corruption",
4283  conn->status);
4284  goto error_return;
4285  }
4286 
4287  /* Unreachable */
4288 
4289 error_return:
4290 
4291  /*
4292  * We used to close the socket at this point, but that makes it awkward
4293  * for those above us if they wish to remove this socket from their own
4294  * records (an fd_set for example). We'll just have this socket closed
4295  * when PQfinish is called (which is compulsory even after an error, since
4296  * the connection structure must be freed).
4297  */
4299  return PGRES_POLLING_FAILED;
4300 }
4301 
4302 /*
4303  * Initialize the state machine for negotiating encryption
4304  */
4305 static bool
4307 {
4308  if (conn->raddr.addr.ss_family == AF_UNIX)
4309  {
4310  /* Don't request SSL or GSSAPI over Unix sockets */
4312 
4313  /*
4314  * XXX: we probably should not do this. sslmode=require works
4315  * differently
4316  */
4317  if (conn->gssencmode[0] == 'r')
4318  {
4320  "GSSAPI encryption required but it is not supported over a local socket");
4323  return false;
4324  }
4325 
4328  return true;
4329  }
4330 
4331  /* initialize based on sslmode and gssencmode */
4333 
4334 #ifdef USE_SSL
4335  /* sslmode anything but 'disable', and GSSAPI not required */
4336  if (conn->sslmode[0] != 'd' && conn->gssencmode[0] != 'r')
4337  {
4339  }
4340 #endif
4341 
4342 #ifdef ENABLE_GSS
4343  if (conn->gssencmode[0] != 'd')
4345 #endif
4346 
4347  if ((conn->sslmode[0] == 'd' || conn->sslmode[0] == 'p' || conn->sslmode[0] == 'a') &&
4348  (conn->gssencmode[0] == 'd' || conn->gssencmode[0] == 'p'))
4349  {
4351  }
4352 
4353  return select_next_encryption_method(conn, false);
4354 }
4355 
4356 /*
4357  * Out-of-line portion of the ENCRYPTION_NEGOTIATION_FAILED() macro in the
4358  * PQconnectPoll state machine.
4359  *
4360  * Return value:
4361  * 0: connection failed and we are out of encryption methods to try. return an error
4362  * 1: Retry with next connection method. The TCP connection is still valid and in
4363  * known state, so we can proceed with the negotiating next method without
4364  * reconnecting.
4365  * 2: Disconnect, and retry with next connection method.
4366  *
4367  * conn->current_enc_method is updated to the next method to try.
4368  */
4369 #if defined(USE_SSL) || defined(ENABLE_GSS)
4370 static int
4371 encryption_negotiation_failed(PGconn *conn)
4372 {
4375 
4377  {
4378  /* An existing connection cannot be reused for direct SSL */
4379  if (conn->current_enc_method == ENC_SSL && conn->sslnegotiation[0] == 'd')
4380  return 2;
4381  else
4382  return 1;
4383  }
4384  else
4385  return 0;
4386 }
4387 #endif
4388 
4389 /*
4390  * Out-of-line portion of the CONNECTION_FAILED() macro
4391  *
4392  * Returns true, if we should reconnect and retry with a different encryption
4393  * method. conn->current_enc_method is updated to the next method to try.
4394  */
4395 static bool
4397 {
4400 
4401  return select_next_encryption_method(conn, false);
4402 }
4403 
4404 /*
4405  * Choose the next encryption method to try. If this is a retry,
4406  * conn->failed_enc_methods has already been updated. The function sets
4407  * conn->current_enc_method to the next method to try. Returns false if no
4408  * encryption methods remain.
4409  */
4410 static bool
4411 select_next_encryption_method(PGconn *conn, bool have_valid_connection)
4412 {
4413  int remaining_methods;
4414 
4415 #define SELECT_NEXT_METHOD(method) \
4416  do { \
4417  if ((remaining_methods & method) != 0) \
4418  { \
4419  conn->current_enc_method = method; \
4420  return true; \
4421  } \
4422  } while (false)
4423 
4424  remaining_methods = conn->allowed_enc_methods & ~conn->failed_enc_methods;
4425 
4426  /*
4427  * Try GSSAPI before SSL
4428  */
4429 #ifdef ENABLE_GSS
4430  if ((remaining_methods & ENC_GSSAPI) != 0)
4431  {
4432  /*
4433  * If GSSAPI encryption is enabled, then call pg_GSS_have_cred_cache()
4434  * which will return true if we can acquire credentials (and give us a
4435  * handle to use in conn->gcred), and then send a packet to the server
4436  * asking for GSSAPI Encryption (and skip past SSL negotiation and
4437  * regular startup below).
4438  */
4439  if (!conn->gctx)
4440  {
4441  if (!pg_GSS_have_cred_cache(&conn->gcred))
4442  {
4444  remaining_methods &= ~ENC_GSSAPI;
4445 
4446  if (conn->gssencmode[0] == 'r')
4447  {
4449  "GSSAPI encryption required but no credential cache");
4450  }
4451  }
4452  }
4453  }
4454 
4456 #endif
4457 
4458  /*
4459  * The order between SSL encryption and plaintext depends on sslmode. With
4460  * sslmode=allow, try plaintext connection before SSL. With
4461  * sslmode=prefer, it's the other way round. With other modes, we only try
4462  * plaintext or SSL connections so the order they're listed here doesn't
4463  * matter.
4464  */
4465  if (conn->sslmode[0] == 'a')
4467 
4469 
4470  if (conn->sslmode[0] != 'a')
4472 
4473  /* No more options */
4475  return false;
4476 #undef SELECT_NEXT_METHOD
4477 }
4478 
4479 /*
4480  * internal_ping
4481  * Determine if a server is running and if we can connect to it.
4482  *
4483  * The argument is a connection that's been started, but not completed.
4484  */
4485 static PGPing
4487 {
4488  /* Say "no attempt" if we never got to PQconnectPoll */
4489  if (!conn || !conn->options_valid)
4490  return PQPING_NO_ATTEMPT;
4491 
4492  /* Attempt to complete the connection */
4493  if (conn->status != CONNECTION_BAD)
4494  (void) pqConnectDBComplete(conn);
4495 
4496  /* Definitely OK if we succeeded */
4497  if (conn->status != CONNECTION_BAD)
4498  return PQPING_OK;
4499 
4500  /*
4501  * Here begins the interesting part of "ping": determine the cause of the
4502  * failure in sufficient detail to decide what to return. We do not want
4503  * to report that the server is not up just because we didn't have a valid
4504  * password, for example. In fact, any sort of authentication request
4505  * implies the server is up. (We need this check since the libpq side of
4506  * things might have pulled the plug on the connection before getting an
4507  * error as such from the postmaster.)
4508  */
4509  if (conn->auth_req_received)
4510  return PQPING_OK;
4511 
4512  /*
4513  * If we failed to get any ERROR response from the postmaster, report
4514  * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
4515  * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
4516  * out of support. Another corner case where the server could return a
4517  * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
4518  * isn't totally unreasonable for that anyway. We expect that every other
4519  * failure case in a modern server will produce a report with a SQLSTATE.
4520  *
4521  * NOTE: whenever we get around to making libpq generate SQLSTATEs for
4522  * client-side errors, we should either not store those into
4523  * last_sqlstate, or add an extra flag so we can tell client-side errors
4524  * apart from server-side ones.
4525  */
4526  if (strlen(conn->last_sqlstate) != 5)
4527  return PQPING_NO_RESPONSE;
4528 
4529  /*
4530  * Report PQPING_REJECT if server says it's not accepting connections.
4531  */
4532  if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
4533  return PQPING_REJECT;
4534 
4535  /*
4536  * Any other SQLSTATE can be taken to indicate that the server is up.
4537  * Presumably it didn't like our username, password, or database name; or
4538  * perhaps it had some transient failure, but that should not be taken as
4539  * meaning "it's down".
4540  */
4541  return PQPING_OK;
4542 }
4543 
4544 
4545 /*
4546  * pqMakeEmptyPGconn
4547  * - create a PGconn data structure with (as yet) no interesting data
4548  */
4549 PGconn *
4551 {
4552  PGconn *conn;
4553 
4554 #ifdef WIN32
4555 
4556  /*
4557  * Make sure socket support is up and running in this process.
4558  *
4559  * Note: the Windows documentation says that we should eventually do a
4560  * matching WSACleanup() call, but experience suggests that that is at
4561  * least as likely to cause problems as fix them. So we don't.
4562  */
4563  static bool wsastartup_done = false;
4564 
4565  if (!wsastartup_done)
4566  {
4567  WSADATA wsaData;
4568 
4569  if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4570  return NULL;
4571  wsastartup_done = true;
4572  }
4573 
4574  /* Forget any earlier error */
4575  WSASetLastError(0);
4576 #endif /* WIN32 */
4577 
4578  conn = (PGconn *) malloc(sizeof(PGconn));
4579  if (conn == NULL)
4580  return conn;
4581 
4582  /* Zero all pointers and booleans */
4583  MemSet(conn, 0, sizeof(PGconn));
4584 
4585  /* install default notice hooks */
4588 
4593  conn->options_valid = false;
4594  conn->nonblocking = false;
4596  conn->std_strings = false; /* unless server says differently */
4603  conn->Pfdebug = NULL;
4604 
4605  /*
4606  * We try to send at least 8K at a time, which is the usual size of pipe
4607  * buffers on Unix systems. That way, when we are sending a large amount
4608  * of data, we avoid incurring extra kernel context swaps for partial
4609  * bufferloads. The output buffer is initially made 16K in size, and we
4610  * try to dump it after accumulating 8K.
4611  *
4612  * With the same goal of minimizing context swaps, the input buffer will
4613  * be enlarged anytime it has less than 8K free, so we initially allocate
4614  * twice that.
4615  */
4616  conn->inBufSize = 16 * 1024;
4617  conn->inBuffer = (char *) malloc(conn->inBufSize);
4618  conn->outBufSize = 16 * 1024;
4619  conn->outBuffer = (char *) malloc(conn->outBufSize);
4620  conn->rowBufLen = 32;
4621  conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
4624 
4625  if (conn->inBuffer == NULL ||
4626  conn->outBuffer == NULL ||
4627  conn->rowBuf == NULL ||
4630  {
4631  /* out of memory already :-( */
4632  freePGconn(conn);
4633  conn = NULL;
4634  }
4635 
4636  return conn;
4637 }
4638 
4639 /*
4640  * freePGconn
4641  * - free an idle (closed) PGconn data structure
4642  *
4643  * NOTE: this should not overlap any functionality with pqClosePGconn().
4644  * Clearing/resetting of transient state belongs there; what we do here is
4645  * release data that is to be held for the life of the PGconn structure.
4646  * If a value ought to be cleared/freed during PQreset(), do it there not here.
4647  */
4648 static void
4650 {
4651  /* let any event procs clean up their state data */
4652  for (int i = 0; i < conn->nEvents; i++)
4653  {
4654  PGEventConnDestroy evt;
4655 
4656  evt.conn = conn;
4657  (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
4658  conn->events[i].passThrough);
4659  free(conn->events[i].name);
4660  }
4661 
4664 
4666  free(conn->events);
4667  free(conn->pghost);
4668  free(conn->pghostaddr);
4669  free(conn->pgport);
4672  free(conn->pgoptions);
4673  free(conn->appname);
4674  free(conn->fbappname);
4675  free(conn->dbName);
4676  free(conn->replication);
4677  free(conn->pguser);
4678  if (conn->pgpass)
4679  {
4680  explicit_bzero(conn->pgpass, strlen(conn->pgpass));
4681  free(conn->pgpass);
4682  }
4683  free(conn->pgpassfile);
4685  free(conn->keepalives);
4689  free(conn->sslmode);
4691  free(conn->sslcert);
4692  free(conn->sslkey);
4693  if (conn->sslpassword)
4694  {
4696  free(conn->sslpassword);
4697  }
4698  free(conn->sslcertmode);
4699  free(conn->sslrootcert);
4700  free(conn->sslcrl);
4701  free(conn->sslcrldir);
4703  free(conn->sslsni);
4704  free(conn->requirepeer);
4708  free(conn->gssencmode);
4709  free(conn->krbsrvname);
4710  free(conn->gsslib);
4712  free(conn->connip);
4713  /* Note that conn->Pfdebug is not ours to close or free */
4715  free(conn->inBuffer);
4716  free(conn->outBuffer);
4717  free(conn->rowBuf);
4722 
4723  free(conn);
4724 }
4725 
4726 /*
4727  * pqReleaseConnHosts
4728  * - Free the host list in the PGconn.
4729  */
4730 void
4732 {
4733  if (conn->connhost)
4734  {
4735  for (int i = 0; i < conn->nconnhost; ++i)
4736  {
4737  free(conn->connhost[i].host);
4739  free(conn->connhost[i].port);
4740  if (conn->connhost[i].password != NULL)
4741  {
4743  strlen(conn->connhost[i].password));
4745  }
4746  }
4747  free(conn->connhost);
4748  }
4749 }
4750 
4751 /*
4752  * store_conn_addrinfo
4753  * - copy addrinfo to PGconn object
4754  *
4755  * Copies the addrinfos from addrlist to the PGconn object such that the
4756  * addrinfos can be manipulated by libpq. Returns a positive integer on
4757  * failure, otherwise zero.
4758  */
4759 static int
4760 store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
4761 {
4762  struct addrinfo *ai = addrlist;
4763 
4764  conn->whichaddr = 0;
4765 
4766  conn->naddr = 0;
4767  while (ai)
4768  {
4769  ai = ai->ai_next;
4770  conn->naddr++;
4771  }
4772 
4773  conn->addr = calloc(conn->naddr, sizeof(AddrInfo));
4774  if (conn->addr == NULL)
4775  {
4776  libpq_append_conn_error(conn, "out of memory");
4777  return 1;
4778  }
4779 
4780  ai = addrlist;
4781  for (int i = 0; i < conn->naddr; i++)
4782  {
4783  conn->addr[i].family = ai->ai_family;
4784 
4785  memcpy(&conn->addr[i].addr.addr, ai->ai_addr,
4786  ai->ai_addrlen);
4787  conn->addr[i].addr.salen = ai->ai_addrlen;
4788  ai = ai->ai_next;
4789  }
4790 
4791  return 0;
4792 }
4793 
4794 /*
4795  * release_conn_addrinfo
4796  * - Free any addrinfo list in the PGconn.
4797  */
4798 static void
4800 {
4801  if (conn->addr)
4802  {
4803  free(conn->addr);
4804  conn->addr = NULL;
4805  }
4806 }
4807 
4808 /*
4809  * sendTerminateConn
4810  * - Send a terminate message to backend.
4811  */
4812 static void
4814 {
4815  /*
4816  * The Postgres cancellation protocol does not have a notion of a
4817  * Terminate message, so don't send one.
4818  */
4819  if (conn->cancelRequest)
4820  return;
4821 
4822  /*
4823  * Note that the protocol doesn't allow us to send Terminate messages
4824  * during the startup phase.
4825  */
4827  {
4828  /*
4829  * Try to send "close connection" message to backend. Ignore any
4830  * error.
4831  */
4833  pqPutMsgEnd(conn);
4834  (void) pqFlush(conn);
4835  }
4836 }
4837 
4838 /*
4839  * pqClosePGconn
4840  * - properly close a connection to the backend
4841  *
4842  * This should reset or release all transient state, but NOT the connection
4843  * parameters. On exit, the PGconn should be in condition to start a fresh
4844  * connection with the same parameters (see PQreset()).
4845  */
4846 void
4848 {
4849  /*
4850  * If possible, send Terminate message to close the connection politely.
4851  */
4853 
4854  /*
4855  * Must reset the blocking status so a possible reconnect will work.
4856  *
4857  * Don't call PQsetnonblocking() because it will fail if it's unable to
4858  * flush the connection.
4859  */
4860  conn->nonblocking = false;
4861 
4862  /*
4863  * Close the connection, reset all transient state, flush I/O buffers.
4864  * Note that this includes clearing conn's error state; we're no longer
4865  * interested in any failures associated with the old connection, and we
4866  * want a clean slate for any new connection attempt.
4867  */
4868  pqDropConnection(conn, true);
4869  conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
4873  pqClearAsyncResult(conn); /* deallocate result */
4875 
4876  /*
4877  * Release addrinfo, but since cancel requests never change their addrinfo
4878  * we don't do that. Otherwise we would have to rebuild it during a
4879  * PQcancelReset.
4880  */
4881  if (!conn->cancelRequest)
4883 
4884  /* Reset all state obtained from server, too */
4886 }
4887 
4888 /*
4889  * PQfinish: properly close a connection to the backend. Also frees
4890  * the PGconn data structure so it shouldn't be re-used after this.
4891  */
4892 void
4894 {
4895  if (conn)
4896  {
4898  freePGconn(conn);
4899  }
4900 }
4901 
4902 /*
4903  * PQreset: resets the connection to the backend by closing the
4904  * existing connection and creating a new one.
4905  */
4906 void
4908 {
4909  if (conn)
4910  {
4912 
4914  {
4915  /*
4916  * Notify event procs of successful reset.
4917  */
4918  int i;
4919 
4920  for (i = 0; i < conn->nEvents; i++)
4921  {
4922  PGEventConnReset evt;
4923 
4924  evt.conn = conn;
4925  (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4926  conn->events[i].passThrough);
4927  }
4928  }
4929  }
4930 }
4931 
4932 
4933 /*
4934  * PQresetStart:
4935  * resets the connection to the backend
4936  * closes the existing connection and makes a new one
4937  * Returns 1 on success, 0 on failure.
4938  */
4939 int
4941 {
4942  if (conn)
4943  {
4945 
4946  return pqConnectDBStart(conn);
4947  }
4948 
4949  return 0;
4950 }
4951 
4952 
4953 /*
4954  * PQresetPoll:
4955  * resets the connection to the backend
4956  * closes the existing connection and makes a new one
4957  */
4960 {
4961  if (conn)
4962  {
4964 
4965  if (status == PGRES_POLLING_OK)
4966  {
4967  /*
4968  * Notify event procs of successful reset.
4969  */
4970  int i;
4971 
4972  for (i = 0; i < conn->nEvents; i++)
4973  {
4974  PGEventConnReset evt;
4975 
4976  evt.conn = conn;
4977  (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4978  conn->events[i].passThrough);
4979  }
4980  }
4981 
4982  return status;
4983  }
4984 
4985  return PGRES_POLLING_FAILED;
4986 }
4987 
4988 /*
4989  * pqPacketSend() -- convenience routine to send a message to server.
4990  *
4991  * pack_type: the single-byte message type code. (Pass zero for startup
4992  * packets, which have no message type code.)
4993  *
4994  * buf, buf_len: contents of message. The given length includes only what
4995  * is in buf; the message type and message length fields are added here.
4996  *
4997  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4998  * SIDE_EFFECTS: may block.
4999  */
5000 int
5001 pqPacketSend(PGconn *conn, char pack_type,
5002  const void *buf, size_t buf_len)
5003 {
5004  /* Start the message. */
5005  if (pqPutMsgStart(pack_type, conn))
5006  return STATUS_ERROR;
5007 
5008  /* Send the message body. */
5009  if (pqPutnchar(buf, buf_len, conn))
5010  return STATUS_ERROR;
5011 
5012  /* Finish the message. */
5013  if (pqPutMsgEnd(conn))
5014  return STATUS_ERROR;
5015 
5016  /* Flush to ensure backend gets it. */
5017  if (pqFlush(conn))
5018  return STATUS_ERROR;
5019 
5020  return STATUS_OK;
5021 }
5022 
5023 #ifdef USE_LDAP
5024 
5025 #define LDAP_URL "ldap://"
5026 #define LDAP_DEF_PORT 389
5027 #define PGLDAP_TIMEOUT 2
5028 
5029 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
5030 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
5031 
5032 
5033 /*
5034  * ldapServiceLookup
5035  *
5036  * Search the LDAP URL passed as first argument, treat the result as a
5037  * string of connection options that are parsed and added to the array of
5038  * options passed as second argument.
5039  *
5040  * LDAP URLs must conform to RFC 1959 without escape sequences.
5041  * ldap://host:port/dn?attributes?scope?filter?extensions
5042  *
5043  * Returns
5044  * 0 if the lookup was successful,
5045  * 1 if the connection to the LDAP server could be established but
5046  * the search was unsuccessful,
5047  * 2 if a connection could not be established, and
5048  * 3 if a fatal error occurred.
5049  *
5050  * An error message is appended to *errorMessage for return codes 1 and 3.
5051  */
5052 static int
5053 ldapServiceLookup(const char *purl, PQconninfoOption *options,
5054  PQExpBuffer errorMessage)
5055 {
5056  int port = LDAP_DEF_PORT,
5057  scope,
5058  rc,
5059  size,
5060  state,
5061  oldstate,
5062  i;
5063 #ifndef WIN32
5064  int msgid;
5065 #endif
5066  bool found_keyword;
5067  char *url,
5068  *hostname,
5069  *portstr,
5070  *endptr,
5071  *dn,
5072  *scopestr,
5073  *filter,
5074  *result,
5075  *p,
5076  *p1 = NULL,
5077  *optname = NULL,
5078  *optval = NULL;
5079  char *attrs[2] = {NULL, NULL};
5080  LDAP *ld = NULL;
5081  LDAPMessage *res,
5082  *entry;
5083  struct berval **values;
5084  LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
5085 
5086  if ((url = strdup(purl)) == NULL)
5087  {
5088  libpq_append_error(errorMessage, "out of memory");
5089  return 3;
5090  }
5091 
5092  /*
5093  * Parse URL components, check for correctness. Basically, url has '\0'
5094  * placed at component boundaries and variables are pointed at each
5095  * component.
5096  */
5097 
5098  if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
5099  {
5100  libpq_append_error(errorMessage,
5101  "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
5102  free(url);
5103  return 3;
5104  }
5105 
5106  /* hostname */
5107  hostname = url + strlen(LDAP_URL);
5108  if (*hostname == '/') /* no hostname? */
5109  hostname = DefaultHost; /* the default */
5110 
5111  /* dn, "distinguished name" */
5112  p = strchr(url + strlen(LDAP_URL), '/');
5113  if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5114  {
5115  libpq_append_error(errorMessage,
5116  "invalid LDAP URL \"%s\": missing distinguished name",
5117  purl);
5118  free(url);
5119  return 3;
5120  }
5121  *p = '\0'; /* terminate hostname */
5122  dn = p + 1;
5123 
5124  /* attribute */
5125  if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5126  {
5127  libpq_append_error(errorMessage,
5128  "invalid LDAP URL \"%s\": must have exactly one attribute",
5129  purl);
5130  free(url);
5131  return 3;
5132  }
5133  *p = '\0';
5134  attrs[0] = p + 1;
5135 
5136  /* scope */
5137  if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5138  {
5139  libpq_append_error(errorMessage,
5140  "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5141  purl);
5142  free(url);
5143  return 3;
5144  }
5145  *p = '\0';
5146  scopestr = p + 1;
5147 
5148  /* filter */
5149  if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5150  {
5151  libpq_append_error(errorMessage,
5152  "invalid LDAP URL \"%s\": no filter",
5153  purl);
5154  free(url);
5155  return 3;
5156  }
5157  *p = '\0';
5158  filter = p + 1;
5159  if ((p = strchr(filter, '?')) != NULL)
5160  *p = '\0';
5161 
5162  /* port number? */
5163  if ((p1 = strchr(hostname, ':')) != NULL)
5164  {
5165  long lport;
5166 
5167  *p1 = '\0';
5168  portstr = p1 + 1;
5169  errno = 0;
5170  lport = strtol(portstr, &endptr, 10);
5171  if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
5172  {
5173  libpq_append_error(errorMessage,
5174  "invalid LDAP URL \"%s\": invalid port number",
5175  purl);
5176  free(url);
5177  return 3;
5178  }
5179  port = (int) lport;
5180  }
5181 
5182  /* Allow only one attribute */
5183  if (strchr(attrs[0], ',') != NULL)
5184  {
5185  libpq_append_error(errorMessage,
5186  "invalid LDAP URL \"%s\": must have exactly one attribute",
5187  purl);
5188  free(url);
5189  return 3;
5190  }
5191 
5192  /* set scope */
5193  if (pg_strcasecmp(scopestr, "base") == 0)
5194  scope = LDAP_SCOPE_BASE;
5195  else if (pg_strcasecmp(scopestr, "one") == 0)
5196  scope = LDAP_SCOPE_ONELEVEL;
5197  else if (pg_strcasecmp(scopestr, "sub") == 0)
5198  scope = LDAP_SCOPE_SUBTREE;
5199  else
5200  {
5201  libpq_append_error(errorMessage,
5202  "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5203  purl);
5204  free(url);
5205  return 3;
5206  }
5207 
5208  /* initialize LDAP structure */
5209  if ((ld = ldap_init(hostname, port)) == NULL)
5210  {
5211  libpq_append_error(errorMessage, "could not create LDAP structure");
5212  free(url);
5213  return 3;
5214  }
5215 
5216  /*
5217  * Perform an explicit anonymous bind.
5218  *
5219  * LDAP does not require that an anonymous bind is performed explicitly,
5220  * but we want to distinguish between the case where LDAP bind does not
5221  * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
5222  * service control file) and the case where querying the LDAP server fails
5223  * (return 1 to end parsing).
5224  *
5225  * Unfortunately there is no way of setting a timeout that works for both
5226  * Windows and OpenLDAP.
5227  */
5228 #ifdef WIN32
5229  /* the nonstandard ldap_connect function performs an anonymous bind */
5230  if (ldap_connect(ld, &time) != LDAP_SUCCESS)
5231  {
5232  /* error or timeout in ldap_connect */
5233  free(url);
5234  ldap_unbind(ld);
5235  return 2;
5236  }
5237 #else /* !WIN32 */
5238  /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
5239  if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5240  {
5241  free(url);
5242  ldap_unbind(ld);
5243  return 3;
5244  }
5245 
5246  /* anonymous bind */
5247  if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
5248  {
5249  /* error or network timeout */
5250  free(url);
5251  ldap_unbind(ld);
5252  return 2;
5253  }
5254 
5255  /* wait some time for the connection to succeed */
5256  res = NULL;
5257  if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
5258  res == NULL)
5259  {
5260  /* error or timeout */
5261  if (res != NULL)
5262  ldap_msgfree(res);
5263  free(url);
5264  ldap_unbind(ld);
5265  return 2;
5266  }
5267  ldap_msgfree(res);
5268 
5269  /* reset timeout */
5270  time.tv_sec = -1;
5271  if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5272  {
5273  free(url);
5274  ldap_unbind(ld);
5275  return 3;
5276  }
5277 #endif /* WIN32 */
5278 
5279  /* search */
5280  res = NULL;
5281  if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
5282  != LDAP_SUCCESS)
5283  {
5284  if (res != NULL)
5285  ldap_msgfree(res);
5286  libpq_append_error(errorMessage, "lookup on LDAP server failed: %s", ldap_err2string(rc));
5287  ldap_unbind(ld);
5288  free(url);
5289  return 1;
5290  }
5291 
5292  /* complain if there was not exactly one result */
5293  if ((rc = ldap_count_entries(ld, res)) != 1)
5294  {
5295  if (rc > 1)
5296  libpq_append_error(errorMessage, "more than one entry found on LDAP lookup");
5297  else
5298  libpq_append_error(errorMessage, "no entry found on LDAP lookup");
5299  ldap_msgfree(res);
5300  ldap_unbind(ld);
5301  free(url);
5302  return 1;
5303  }
5304 
5305  /* get entry */
5306  if ((entry = ldap_first_entry(ld, res)) == NULL)
5307  {
5308  /* should never happen */
5309  libpq_append_error(errorMessage, "no entry found on LDAP lookup");
5310  ldap_msgfree(res);
5311  ldap_unbind(ld);
5312  free(url);
5313  return 1;
5314  }
5315 
5316  /* get values */
5317  if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
5318  {
5319  libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
5320  ldap_msgfree(res);
5321  ldap_unbind(ld);
5322  free(url);
5323  return 1;
5324  }
5325 
5326  ldap_msgfree(res);
5327  free(url);
5328 
5329  if (values[0] == NULL)
5330  {
5331  libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
5332  ldap_value_free_len(values);
5333  ldap_unbind(ld);
5334  return 1;
5335  }
5336 
5337  /* concatenate values into a single string with newline terminators */
5338  size = 1; /* for the trailing null */
5339  for (i = 0; values[i] != NULL; i++)
5340  size += values[i]->bv_len + 1;
5341  if ((result = malloc(size)) == NULL)
5342  {
5343  libpq_append_error(errorMessage, "out of memory");
5344  ldap_value_free_len(values);
5345  ldap_unbind(ld);
5346  return 3;
5347  }
5348  p = result;
5349  for (i = 0; values[i] != NULL; i++)
5350  {
5351  memcpy(p, values[i]->bv_val, values[i]->bv_len);
5352  p += values[i]->bv_len;
5353  *(p++) = '\n';
5354  }
5355  *p = '\0';
5356 
5357  ldap_value_free_len(values);
5358  ldap_unbind(ld);
5359 
5360  /* parse result string */
5361  oldstate = state = 0;
5362  for (p = result; *p != '\0'; ++p)
5363  {
5364  switch (state)
5365  {
5366  case 0: /* between entries */
5367  if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
5368  {
5369  optname = p;
5370  state = 1;
5371  }
5372  break;
5373  case 1: /* in option name */
5374  if (ld_is_sp_tab(*p))
5375  {
5376  *p = '\0';
5377  state = 2;
5378  }
5379  else if (ld_is_nl_cr(*p))
5380  {
5381  libpq_append_error(errorMessage,
5382  "missing \"=\" after \"%s\" in connection info string",
5383  optname);
5384  free(result);
5385  return 3;
5386  }
5387  else if (*p == '=')
5388  {
5389  *p = '\0';
5390  state = 3;
5391  }
5392  break;
5393  case 2: /* after option name */
5394  if (*p == '=')
5395  {
5396  state = 3;
5397  }
5398  else if (!ld_is_sp_tab(*p))
5399  {
5400  libpq_append_error(errorMessage,
5401  "missing \"=\" after \"%s\" in connection info string",
5402  optname);
5403  free(result);
5404  return 3;
5405  }
5406  break;
5407  case 3: /* before option value */
5408  if (*p == '\'')
5409  {
5410  optval = p + 1;
5411  p1 = p + 1;
5412  state = 5;
5413  }
5414  else if (ld_is_nl_cr(*p))
5415  {
5416  optval = optname + strlen(optname); /* empty */
5417  state = 0;
5418  }
5419  else if (!ld_is_sp_tab(*p))
5420  {
5421  optval = p;
5422  state = 4;
5423  }
5424  break;
5425  case 4: /* in unquoted option value */
5426  if (ld_is_sp_tab(*p) || ld_is_nl_cr(*