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