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