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