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