Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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 "fe-auth-oauth.h"
32#include "libpq-fe.h"
33#include "libpq-int.h"
34#include "mb/pg_wchar.h"
35#include "pg_config_paths.h"
36#include "port/pg_bswap.h"
37
38#ifdef WIN32
39#include "win32.h"
40#ifdef _WIN32_IE
41#undef _WIN32_IE
42#endif
43#define _WIN32_IE 0x0500
44#ifdef near
45#undef near
46#endif
47#define near
48#include <shlobj.h>
49#include <mstcpip.h>
50#else
51#include <sys/socket.h>
52#include <netdb.h>
53#include <netinet/in.h>
54#include <netinet/tcp.h>
55#include <pwd.h>
56#endif
57
58#ifdef WIN32
59#include "pthread-win32.h"
60#else
61#include <pthread.h>
62#endif
63
64#ifdef USE_LDAP
65#ifdef WIN32
66#include <winldap.h>
67#else
68/* OpenLDAP deprecates RFC 1823, but we want standard conformance */
69#define LDAP_DEPRECATED 1
70#include <ldap.h>
71typedef struct timeval LDAP_TIMEVAL;
72#endif
73static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
74 PQExpBuffer errorMessage);
75#endif
76
77#ifndef WIN32
78#define PGPASSFILE ".pgpass"
79#else
80#define PGPASSFILE "pgpass.conf"
81#endif
82
83/*
84 * Pre-9.0 servers will return this SQLSTATE if asked to set
85 * application_name in a startup packet. We hard-wire the value rather
86 * than looking into errcodes.h since it reflects historical behavior
87 * rather than that of the current code.
88 */
89#define ERRCODE_APPNAME_UNKNOWN "42704"
90
91/* This is part of the protocol so just define it */
92#define ERRCODE_INVALID_PASSWORD "28P01"
93/* This too */
94#define ERRCODE_CANNOT_CONNECT_NOW "57P03"
95
96/*
97 * Cope with the various platform-specific ways to spell TCP keepalive socket
98 * options. This doesn't cover Windows, which as usual does its own thing.
99 */
100#if defined(TCP_KEEPIDLE)
101/* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
102#define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
103#define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
104#elif defined(TCP_KEEPALIVE_THRESHOLD)
105/* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
106#define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
107#define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
108#elif defined(TCP_KEEPALIVE) && defined(__darwin__)
109/* TCP_KEEPALIVE is the name of this option on macOS */
110/* Caution: Solaris has this symbol but it means something different */
111#define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
112#define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
113#endif
114
115/*
116 * fall back options if they are not specified by arguments or defined
117 * by environment variables
118 */
119#define DefaultHost "localhost"
120#define DefaultOption ""
121#ifdef USE_SSL
122#define DefaultChannelBinding "prefer"
123#else
124#define DefaultChannelBinding "disable"
125#endif
126#define DefaultTargetSessionAttrs "any"
127#define DefaultLoadBalanceHosts "disable"
128#ifdef USE_SSL
129#define DefaultSSLMode "prefer"
130#define DefaultSSLCertMode "allow"
131#else
132#define DefaultSSLMode "disable"
133#define DefaultSSLCertMode "disable"
134#endif
135#define DefaultSSLNegotiation "postgres"
136#ifdef ENABLE_GSS
137#include "fe-gssapi-common.h"
138#define DefaultGSSMode "prefer"
139#else
140#define DefaultGSSMode "disable"
141#endif
142
143/* ----------
144 * Definition of the conninfo parameters and their fallback resources.
145 *
146 * If Environment-Var and Compiled-in are specified as NULL, no
147 * fallback is available. If after all no value can be determined
148 * for an option, an error is returned.
149 *
150 * The value for the username is treated specially in conninfo_add_defaults.
151 * If the value is not obtained any other way, the username is determined
152 * by pg_fe_getauthname().
153 *
154 * The Label and Disp-Char entries are provided for applications that
155 * want to use PQconndefaults() to create a generic database connection
156 * dialog. Disp-Char is defined as follows:
157 * "" Normal input field
158 * "*" Password field - hide value
159 * "D" Debug option - don't show by default
160 *
161 * NB: Server-side clients -- dblink, postgres_fdw, libpqrcv -- use dispchar to
162 * determine which options to expose to end users, and how. Changing dispchar
163 * has compatibility and security implications for those clients. For example,
164 * postgres_fdw will attach a "*" option to USER MAPPING instead of the default
165 * SERVER, and it disallows setting "D" options entirely.
166 *
167 * PQconninfoOptions[] is a constant static array that we use to initialize
168 * a dynamically allocated working copy. All the "val" fields in
169 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
170 * fields point to malloc'd strings that should be freed when the working
171 * array is freed (see PQconninfoFree).
172 *
173 * The first part of each struct is identical to the one in libpq-fe.h,
174 * which is required since we memcpy() data between the two!
175 * ----------
176 */
178{
179 char *keyword; /* The keyword of the option */
180 char *envvar; /* Fallback environment variable name */
181 char *compiled; /* Fallback compiled in default value */
182 char *val; /* Option's current value, or NULL */
183 char *label; /* Label for field in connect dialog */
184 char *dispchar; /* Indicates how to display this field in a
185 * connect dialog. Values are: "" Display
186 * entered value as is "*" Password field -
187 * hide value "D" Debug option - don't show
188 * by default */
189 int dispsize; /* Field size in characters for dialog */
190 /* ---
191 * Anything above this comment must be synchronized with
192 * PQconninfoOption in libpq-fe.h, since we memcpy() data
193 * between them!
194 * ---
195 */
196 off_t connofs; /* Offset into PGconn struct, -1 if not there */
198
200 {"service", "PGSERVICE", NULL, NULL,
201 "Database-Service", "", 20,
202 offsetof(struct pg_conn, pgservice)},
203
204 {"servicefile", "PGSERVICEFILE", NULL, NULL,
205 "Database-Service-File", "", 64,
206 offsetof(struct pg_conn, pgservicefile)},
207
208 {"user", "PGUSER", NULL, NULL,
209 "Database-User", "", 20,
210 offsetof(struct pg_conn, pguser)},
211
212 {"password", "PGPASSWORD", NULL, NULL,
213 "Database-Password", "*", 20,
214 offsetof(struct pg_conn, pgpass)},
215
216 {"passfile", "PGPASSFILE", NULL, NULL,
217 "Database-Password-File", "", 64,
218 offsetof(struct pg_conn, pgpassfile)},
219
220 {"channel_binding", "PGCHANNELBINDING", DefaultChannelBinding, NULL,
221 "Channel-Binding", "", 8, /* sizeof("require") == 8 */
222 offsetof(struct pg_conn, channel_binding)},
223
224 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
225 "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
226 offsetof(struct pg_conn, connect_timeout)},
227
228 {"dbname", "PGDATABASE", NULL, NULL,
229 "Database-Name", "", 20,
230 offsetof(struct pg_conn, dbName)},
231
232 {"host", "PGHOST", NULL, NULL,
233 "Database-Host", "", 40,
234 offsetof(struct pg_conn, pghost)},
235
236 {"hostaddr", "PGHOSTADDR", NULL, NULL,
237 "Database-Host-IP-Address", "", 45,
238 offsetof(struct pg_conn, pghostaddr)},
239
240 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
241 "Database-Port", "", 6,
242 offsetof(struct pg_conn, pgport)},
243
244 {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
245 "Client-Encoding", "", 10,
246 offsetof(struct pg_conn, client_encoding_initial)},
247
248 {"options", "PGOPTIONS", DefaultOption, NULL,
249 "Backend-Options", "", 40,
250 offsetof(struct pg_conn, pgoptions)},
251
252 {"application_name", "PGAPPNAME", NULL, NULL,
253 "Application-Name", "", 64,
254 offsetof(struct pg_conn, appname)},
255
256 {"fallback_application_name", NULL, NULL, NULL,
257 "Fallback-Application-Name", "", 64,
258 offsetof(struct pg_conn, fbappname)},
259
260 {"keepalives", NULL, NULL, NULL,
261 "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
262 offsetof(struct pg_conn, keepalives)},
263
264 {"keepalives_idle", NULL, NULL, NULL,
265 "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
266 offsetof(struct pg_conn, keepalives_idle)},
267
268 {"keepalives_interval", NULL, NULL, NULL,
269 "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
270 offsetof(struct pg_conn, keepalives_interval)},
271
272 {"keepalives_count", NULL, NULL, NULL,
273 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
274 offsetof(struct pg_conn, keepalives_count)},
275
276 {"tcp_user_timeout", NULL, NULL, NULL,
277 "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
278 offsetof(struct pg_conn, pgtcp_user_timeout)},
279
280 /*
281 * ssl options are allowed even without client SSL support because the
282 * client can still handle SSL modes "disable" and "allow". Other
283 * parameters have no effect on non-SSL connections, so there is no reason
284 * to exclude them since none of them are mandatory.
285 */
286 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
287 "SSL-Mode", "", 12, /* sizeof("verify-full") == 12 */
288 offsetof(struct pg_conn, sslmode)},
289
290 {"sslnegotiation", "PGSSLNEGOTIATION", DefaultSSLNegotiation, NULL,
291 "SSL-Negotiation", "", 9, /* sizeof("postgres") == 9 */
292 offsetof(struct pg_conn, sslnegotiation)},
293
294 {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
295 "SSL-Compression", "", 1,
296 offsetof(struct pg_conn, sslcompression)},
297
298 {"sslcert", "PGSSLCERT", NULL, NULL,
299 "SSL-Client-Cert", "", 64,
300 offsetof(struct pg_conn, sslcert)},
301
302 {"sslkey", "PGSSLKEY", NULL, NULL,
303 "SSL-Client-Key", "", 64,
304 offsetof(struct pg_conn, sslkey)},
305
306 {"sslcertmode", "PGSSLCERTMODE", NULL, NULL,
307 "SSL-Client-Cert-Mode", "", 8, /* sizeof("disable") == 8 */
308 offsetof(struct pg_conn, sslcertmode)},
309
310 {"sslpassword", NULL, NULL, NULL,
311 "SSL-Client-Key-Password", "*", 20,
312 offsetof(struct pg_conn, sslpassword)},
313
314 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
315 "SSL-Root-Certificate", "", 64,
316 offsetof(struct pg_conn, sslrootcert)},
317
318 {"sslcrl", "PGSSLCRL", NULL, NULL,
319 "SSL-Revocation-List", "", 64,
320 offsetof(struct pg_conn, sslcrl)},
321
322 {"sslcrldir", "PGSSLCRLDIR", NULL, NULL,
323 "SSL-Revocation-List-Dir", "", 64,
324 offsetof(struct pg_conn, sslcrldir)},
325
326 {"sslsni", "PGSSLSNI", "1", NULL,
327 "SSL-SNI", "", 1,
328 offsetof(struct pg_conn, sslsni)},
329
330 {"requirepeer", "PGREQUIREPEER", NULL, NULL,
331 "Require-Peer", "", 10,
332 offsetof(struct pg_conn, requirepeer)},
333
334 {"require_auth", "PGREQUIREAUTH", NULL, NULL,
335 "Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */
336 offsetof(struct pg_conn, require_auth)},
337
338 {"min_protocol_version", "PGMINPROTOCOLVERSION",
339 NULL, NULL,
340 "Min-Protocol-Version", "", 6, /* sizeof("latest") = 6 */
341 offsetof(struct pg_conn, min_protocol_version)},
342
343 {"max_protocol_version", "PGMAXPROTOCOLVERSION",
344 NULL, NULL,
345 "Max-Protocol-Version", "", 6, /* sizeof("latest") = 6 */
346 offsetof(struct pg_conn, max_protocol_version)},
347
348 {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL,
349 "SSL-Minimum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
350 offsetof(struct pg_conn, ssl_min_protocol_version)},
351
352 {"ssl_max_protocol_version", "PGSSLMAXPROTOCOLVERSION", NULL, NULL,
353 "SSL-Maximum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
354 offsetof(struct pg_conn, ssl_max_protocol_version)},
355
356 /*
357 * As with SSL, all GSS options are exposed even in builds that don't have
358 * support.
359 */
360 {"gssencmode", "PGGSSENCMODE", DefaultGSSMode, NULL,
361 "GSSENC-Mode", "", 8, /* sizeof("disable") == 8 */
362 offsetof(struct pg_conn, gssencmode)},
363
364 /* Kerberos and GSSAPI authentication support specifying the service name */
365 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
366 "Kerberos-service-name", "", 20,
367 offsetof(struct pg_conn, krbsrvname)},
368
369 {"gsslib", "PGGSSLIB", NULL, NULL,
370 "GSS-library", "", 7, /* sizeof("gssapi") == 7 */
371 offsetof(struct pg_conn, gsslib)},
372
373 {"gssdelegation", "PGGSSDELEGATION", "0", NULL,
374 "GSS-delegation", "", 1,
375 offsetof(struct pg_conn, gssdelegation)},
376
377 {"replication", NULL, NULL, NULL,
378 "Replication", "D", 5,
379 offsetof(struct pg_conn, replication)},
380
381 {"target_session_attrs", "PGTARGETSESSIONATTRS",
383 "Target-Session-Attrs", "", 15, /* sizeof("prefer-standby") = 15 */
384 offsetof(struct pg_conn, target_session_attrs)},
385
386 {"load_balance_hosts", "PGLOADBALANCEHOSTS",
388 "Load-Balance-Hosts", "", 8, /* sizeof("disable") = 8 */
389 offsetof(struct pg_conn, load_balance_hosts)},
390
391 {"scram_client_key", NULL, NULL, NULL, "SCRAM-Client-Key", "D", SCRAM_MAX_KEY_LEN * 2,
392 offsetof(struct pg_conn, scram_client_key)},
393
394 {"scram_server_key", NULL, NULL, NULL, "SCRAM-Server-Key", "D", SCRAM_MAX_KEY_LEN * 2,
395 offsetof(struct pg_conn, scram_server_key)},
396
397 /* OAuth v2 */
398 {"oauth_issuer", NULL, NULL, NULL,
399 "OAuth-Issuer", "", 40,
400 offsetof(struct pg_conn, oauth_issuer)},
401
402 {"oauth_client_id", NULL, NULL, NULL,
403 "OAuth-Client-ID", "", 40,
404 offsetof(struct pg_conn, oauth_client_id)},
405
406 {"oauth_client_secret", NULL, NULL, NULL,
407 "OAuth-Client-Secret", "*", 40,
408 offsetof(struct pg_conn, oauth_client_secret)},
409
410 {"oauth_scope", NULL, NULL, NULL,
411 "OAuth-Scope", "", 15,
412 offsetof(struct pg_conn, oauth_scope)},
413
414 {"sslkeylogfile", NULL, NULL, NULL,
415 "SSL-Key-Log-File", "D", 64,
416 offsetof(struct pg_conn, sslkeylogfile)},
417
418 /* Terminating entry --- MUST BE LAST */
419 {NULL, NULL, NULL, NULL,
420 NULL, NULL, 0}
421};
422
424{
425 /* common user-interface settings */
426 {
427 "PGDATESTYLE", "datestyle"
428 },
429 {
430 "PGTZ", "timezone"
431 },
432 /* internal performance-related settings */
433 {
434 "PGGEQO", "geqo"
435 },
436 {
437 NULL, NULL
438 }
439};
440
442{
445};
446#define SASL_MECHANISM_COUNT lengthof(supported_sasl_mechs)
447
448/* The connection URI must start with either of the following designators: */
449static const char uri_designator[] = "postgresql://";
450static const char short_uri_designator[] = "postgres://";
451
452static bool connectOptions1(PGconn *conn, const char *conninfo);
454#if defined(USE_SSL) || defined(ENABLE_GSS)
455static int encryption_negotiation_failed(PGconn *conn);
456#endif
457static bool connection_failed(PGconn *conn);
458static bool select_next_encryption_method(PGconn *conn, bool have_valid_connection);
460static void pqFreeCommandQueue(PGcmdQueueEntry *queue);
461static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
462static void freePGconn(PGconn *conn);
463static void release_conn_addrinfo(PGconn *conn);
464static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist);
465static void sendTerminateConn(PGconn *conn);
466static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
468 PQExpBuffer errorMessage, bool use_defaults);
469static int uri_prefix_length(const char *connstr);
470static bool recognized_connection_string(const char *connstr);
471static PQconninfoOption *conninfo_parse(const char *conninfo,
472 PQExpBuffer errorMessage, bool use_defaults);
473static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
474 const char *const *values, PQExpBuffer errorMessage,
475 bool use_defaults, int expand_dbname);
477 PQExpBuffer errorMessage);
478static PQconninfoOption *conninfo_uri_parse(const char *uri,
479 PQExpBuffer errorMessage, bool use_defaults);
481 const char *uri, PQExpBuffer errorMessage);
482static bool conninfo_uri_parse_params(char *params,
483 PQconninfoOption *connOptions,
484 PQExpBuffer errorMessage);
485static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
486static bool get_hexdigit(char digit, int *value);
487static const char *conninfo_getval(PQconninfoOption *connOptions,
488 const char *keyword);
490 const char *keyword, const char *value,
491 PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
493 const char *keyword);
494static void defaultNoticeReceiver(void *arg, const PGresult *res);
495static void defaultNoticeProcessor(void *arg, const char *message);
497 PQExpBuffer errorMessage);
498static int parseServiceFile(const char *serviceFile,
499 const char *service,
501 PQExpBuffer errorMessage,
502 bool *group_found);
503static char *pwdfMatchesString(char *buf, const char *token);
504static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
505 const char *username, const char *pgpassfile);
506static void pgpassfileWarning(PGconn *conn);
507static void default_threadlock(int acquire);
508static bool sslVerifyProtocolVersion(const char *version);
509static bool sslVerifyProtocolRange(const char *min, const char *max);
510static bool pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, const char *context);
511
512
513/* global variable because fe-auth.c needs to access it */
515
516
517/*
518 * pqDropConnection
519 *
520 * Close any physical connection to the server, and reset associated
521 * state inside the connection object. We don't release state that
522 * would be needed to reconnect, though, nor local state that might still
523 * be useful later.
524 *
525 * We can always flush the output buffer, since there's no longer any hope
526 * of sending that data. However, unprocessed input data might still be
527 * valuable, so the caller must tell us whether to flush that or not.
528 */
529void
530pqDropConnection(PGconn *conn, bool flushInput)
531{
532 /* Drop any SSL state */
534
535 /* Close the socket itself */
536 if (conn->sock != PGINVALID_SOCKET)
539
540 /* Optionally discard any unread data */
541 if (flushInput)
542 conn->inStart = conn->inCursor = conn->inEnd = 0;
543
544 /* Always discard any unsent data */
545 conn->outCount = 0;
546
547 /* Likewise, discard any pending pipelined commands */
551 conn->cmd_queue_recycle = NULL;
552
553 /* Free authentication/encryption state */
555 {
556 /*
557 * Any in-progress async authentication should be torn down first so
558 * that cleanup_async_auth() can depend on the other authentication
559 * state if necessary.
560 */
562 conn->cleanup_async_auth = NULL;
563 }
564 conn->async_auth = NULL;
565 /* cleanup_async_auth() should have done this, but make sure */
567#ifdef ENABLE_GSS
568 {
569 OM_uint32 min_s;
570
571 if (conn->gcred != GSS_C_NO_CREDENTIAL)
572 {
573 gss_release_cred(&min_s, &conn->gcred);
574 conn->gcred = GSS_C_NO_CREDENTIAL;
575 }
576 if (conn->gctx)
577 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
578 if (conn->gtarg_nam)
579 gss_release_name(&min_s, &conn->gtarg_nam);
580 if (conn->gss_SendBuffer)
581 {
582 free(conn->gss_SendBuffer);
583 conn->gss_SendBuffer = NULL;
584 }
585 if (conn->gss_RecvBuffer)
586 {
587 free(conn->gss_RecvBuffer);
588 conn->gss_RecvBuffer = NULL;
589 }
590 if (conn->gss_ResultBuffer)
591 {
592 free(conn->gss_ResultBuffer);
593 conn->gss_ResultBuffer = NULL;
594 }
595 conn->gssenc = false;
596 }
597#endif
598#ifdef ENABLE_SSPI
599 if (conn->sspitarget)
600 {
601 free(conn->sspitarget);
602 conn->sspitarget = NULL;
603 }
604 if (conn->sspicred)
605 {
606 FreeCredentialsHandle(conn->sspicred);
607 free(conn->sspicred);
608 conn->sspicred = NULL;
609 }
610 if (conn->sspictx)
611 {
612 DeleteSecurityContext(conn->sspictx);
613 free(conn->sspictx);
614 conn->sspictx = NULL;
615 }
616 conn->usesspi = 0;
617#endif
618 if (conn->sasl_state)
619 {
621 conn->sasl_state = NULL;
622 }
623}
624
625/*
626 * pqFreeCommandQueue
627 * Free all the entries of PGcmdQueueEntry queue passed.
628 */
629static void
631{
632 while (queue != NULL)
633 {
634 PGcmdQueueEntry *cur = queue;
635
636 queue = cur->next;
637 free(cur->query);
638 free(cur);
639 }
640}
641
642/*
643 * pqDropServerData
644 *
645 * Clear all connection state data that was received from (or deduced about)
646 * the server. This is essential to do between connection attempts to
647 * different servers, else we may incorrectly hold over some data from the
648 * old server.
649 *
650 * It would be better to merge this into pqDropConnection, perhaps, but
651 * right now we cannot because that function is called immediately on
652 * detection of connection loss (cf. pqReadData, for instance). This data
653 * should be kept until we are actually starting a new connection.
654 */
655static void
657{
658 PGnotify *notify;
659 pgParameterStatus *pstatus;
660
661 /* Forget pending notifies */
662 notify = conn->notifyHead;
663 while (notify != NULL)
664 {
665 PGnotify *prev = notify;
666
667 notify = notify->next;
668 free(prev);
669 }
670 conn->notifyHead = conn->notifyTail = NULL;
671
672 /* Reset ParameterStatus data, as well as variables deduced from it */
673 pstatus = conn->pstatus;
674 while (pstatus != NULL)
675 {
676 pgParameterStatus *prev = pstatus;
677
678 pstatus = pstatus->next;
679 free(prev);
680 }
681 conn->pstatus = NULL;
683 conn->std_strings = false;
687 conn->sversion = 0;
688
689 /* Drop large-object lookup data */
691 conn->lobjfuncs = NULL;
692
693 /* Reset assorted other per-connection state */
694 conn->last_sqlstate[0] = '\0';
695 conn->pversion_negotiated = false;
696 conn->auth_req_received = false;
697 conn->client_finished_auth = false;
698 conn->password_needed = false;
699 conn->gssapi_used = false;
700 conn->write_failed = false;
702 conn->write_err_msg = NULL;
703 conn->oauth_want_retry = false;
704
705 /*
706 * Cancel connections need to retain their be_pid and be_cancel_key across
707 * PQcancelReset invocations, otherwise they would not have access to the
708 * secret token of the connection they are supposed to cancel.
709 */
710 if (!conn->cancelRequest)
711 {
712 conn->be_pid = 0;
713 if (conn->be_cancel_key != NULL)
714 {
716 conn->be_cancel_key = NULL;
717 }
719 }
720}
721
722
723/*
724 * Connecting to a Database
725 *
726 * There are now six different ways a user of this API can connect to the
727 * database. Two are not recommended for use in new code, because of their
728 * lack of extensibility with respect to the passing of options to the
729 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
730 * to the latter).
731 *
732 * If it is desired to connect in a synchronous (blocking) manner, use the
733 * function PQconnectdb or PQconnectdbParams. The former accepts a string of
734 * option = value pairs (or a URI) which must be parsed; the latter takes two
735 * NULL terminated arrays instead.
736 *
737 * To connect in an asynchronous (non-blocking) manner, use the functions
738 * PQconnectStart or PQconnectStartParams (which differ in the same way as
739 * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
740 *
741 * The non-exported functions pqConnectDBStart, pqConnectDBComplete are
742 * part of the connection procedure implementation.
743 */
744
745/*
746 * PQconnectdbParams
747 *
748 * establishes a connection to a postgres backend through the postmaster
749 * using connection information in two arrays.
750 *
751 * The keywords array is defined as
752 *
753 * const char *params[] = {"option1", "option2", NULL}
754 *
755 * The values array is defined as
756 *
757 * const char *values[] = {"value1", "value2", NULL}
758 *
759 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
760 * if a memory allocation failed.
761 * If the status field of the connection returned is CONNECTION_BAD,
762 * then some fields may be null'ed out instead of having valid values.
763 *
764 * You should call PQfinish (if conn is not NULL) regardless of whether this
765 * call succeeded.
766 */
767PGconn *
768PQconnectdbParams(const char *const *keywords,
769 const char *const *values,
770 int expand_dbname)
771{
772 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
773
774 if (conn && conn->status != CONNECTION_BAD)
776
777 return conn;
778}
779
780/*
781 * PQpingParams
782 *
783 * check server status, accepting parameters identical to PQconnectdbParams
784 */
785PGPing
786PQpingParams(const char *const *keywords,
787 const char *const *values,
788 int expand_dbname)
789{
790 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
791 PGPing ret;
792
793 ret = internal_ping(conn);
794 PQfinish(conn);
795
796 return ret;
797}
798
799/*
800 * PQconnectdb
801 *
802 * establishes a connection to a postgres backend through the postmaster
803 * using connection information in a string.
804 *
805 * The conninfo string is either a whitespace-separated list of
806 *
807 * option = value
808 *
809 * definitions or a URI (refer to the documentation for details.) Value
810 * might be a single value containing no whitespaces or a single quoted
811 * string. If a single quote should appear anywhere in the value, it must be
812 * escaped with a backslash like \'
813 *
814 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
815 * if a memory allocation failed.
816 * If the status field of the connection returned is CONNECTION_BAD,
817 * then some fields may be null'ed out instead of having valid values.
818 *
819 * You should call PQfinish (if conn is not NULL) regardless of whether this
820 * call succeeded.
821 */
822PGconn *
823PQconnectdb(const char *conninfo)
824{
825 PGconn *conn = PQconnectStart(conninfo);
826
827 if (conn && conn->status != CONNECTION_BAD)
829
830 return conn;
831}
832
833/*
834 * PQping
835 *
836 * check server status, accepting parameters identical to PQconnectdb
837 */
838PGPing
839PQping(const char *conninfo)
840{
841 PGconn *conn = PQconnectStart(conninfo);
842 PGPing ret;
843
844 ret = internal_ping(conn);
845 PQfinish(conn);
846
847 return ret;
848}
849
850/*
851 * PQconnectStartParams
852 *
853 * Begins the establishment of a connection to a postgres backend through the
854 * postmaster using connection information in a struct.
855 *
856 * See comment for PQconnectdbParams for the definition of the string format.
857 *
858 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
859 * you should not attempt to proceed with this connection. If the status
860 * field of the connection returned is CONNECTION_BAD, an error has
861 * occurred. In this case you should call PQfinish on the result, (perhaps
862 * inspecting the error message first). Other fields of the structure may not
863 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
864 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
865 * this is necessary.
866 *
867 * See PQconnectPoll for more info.
868 */
869PGconn *
871 const char *const *values,
872 int expand_dbname)
873{
874 PGconn *conn;
875 PQconninfoOption *connOptions;
876
877 /*
878 * Allocate memory for the conn structure. Note that we also expect this
879 * to initialize conn->errorMessage to empty. All subsequent steps during
880 * connection initialization will only append to that buffer.
881 */
883 if (conn == NULL)
884 return NULL;
885
886 /*
887 * Parse the conninfo arrays
888 */
889 connOptions = conninfo_array_parse(keywords, values,
891 true, expand_dbname);
892 if (connOptions == NULL)
893 {
895 /* errorMessage is already set */
896 return conn;
897 }
898
899 /*
900 * Move option values into conn structure
901 */
902 if (!fillPGconn(conn, connOptions))
903 {
904 PQconninfoFree(connOptions);
905 return conn;
906 }
907
908 /*
909 * Free the option info - all is in conn now
910 */
911 PQconninfoFree(connOptions);
912
913 /*
914 * Compute derived options
915 */
917 return conn;
918
919 /*
920 * Connect to the database
921 */
923 {
924 /* Just in case we failed to set it in pqConnectDBStart */
926 }
927
928 return conn;
929}
930
931/*
932 * PQconnectStart
933 *
934 * Begins the establishment of a connection to a postgres backend through the
935 * postmaster using connection information in a string.
936 *
937 * See comment for PQconnectdb for the definition of the string format.
938 *
939 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
940 * you should not attempt to proceed with this connection. If the status
941 * field of the connection returned is CONNECTION_BAD, an error has
942 * occurred. In this case you should call PQfinish on the result, (perhaps
943 * inspecting the error message first). Other fields of the structure may not
944 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
945 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
946 * this is necessary.
947 *
948 * See PQconnectPoll for more info.
949 */
950PGconn *
951PQconnectStart(const char *conninfo)
952{
953 PGconn *conn;
954
955 /*
956 * Allocate memory for the conn structure. Note that we also expect this
957 * to initialize conn->errorMessage to empty. All subsequent steps during
958 * connection initialization will only append to that buffer.
959 */
961 if (conn == NULL)
962 return NULL;
963
964 /*
965 * Parse the conninfo string
966 */
967 if (!connectOptions1(conn, conninfo))
968 return conn;
969
970 /*
971 * Compute derived options
972 */
974 return conn;
975
976 /*
977 * Connect to the database
978 */
980 {
981 /* Just in case we failed to set it in pqConnectDBStart */
983 }
984
985 return conn;
986}
987
988/*
989 * Move option values into conn structure
990 *
991 * Don't put anything cute here --- intelligence should be in
992 * pqConnectOptions2 ...
993 *
994 * Returns true on success. On failure, returns false and sets error message.
995 */
996static bool
998{
1000
1001 for (option = PQconninfoOptions; option->keyword; option++)
1002 {
1003 if (option->connofs >= 0)
1004 {
1005 const char *tmp = conninfo_getval(connOptions, option->keyword);
1006
1007 if (tmp)
1008 {
1009 char **connmember = (char **) ((char *) conn + option->connofs);
1010
1011 free(*connmember);
1012 *connmember = strdup(tmp);
1013 if (*connmember == NULL)
1014 {
1015 libpq_append_conn_error(conn, "out of memory");
1016 return false;
1017 }
1018 }
1019 }
1020 }
1021
1022 return true;
1023}
1024
1025/*
1026 * Copy over option values from srcConn to dstConn
1027 *
1028 * Don't put anything cute here --- intelligence should be in
1029 * pqConnectOptions2 ...
1030 *
1031 * Returns true on success. On failure, returns false and sets error message of
1032 * dstConn.
1033 */
1034bool
1035pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
1036{
1038
1039 /* copy over connection options */
1040 for (option = PQconninfoOptions; option->keyword; option++)
1041 {
1042 if (option->connofs >= 0)
1043 {
1044 const char **tmp = (const char **) ((char *) srcConn + option->connofs);
1045
1046 if (*tmp)
1047 {
1048 char **dstConnmember = (char **) ((char *) dstConn + option->connofs);
1049
1050 if (*dstConnmember)
1051 free(*dstConnmember);
1052 *dstConnmember = strdup(*tmp);
1053 if (*dstConnmember == NULL)
1054 {
1055 libpq_append_conn_error(dstConn, "out of memory");
1056 return false;
1057 }
1058 }
1059 }
1060 }
1061 return true;
1062}
1063
1064/*
1065 * connectOptions1
1066 *
1067 * Internal subroutine to set up connection parameters given an already-
1068 * created PGconn and a conninfo string. Derived settings should be
1069 * processed by calling pqConnectOptions2 next. (We split them because
1070 * PQsetdbLogin overrides defaults in between.)
1071 *
1072 * Returns true if OK, false if trouble (in which case errorMessage is set
1073 * and so is conn->status).
1074 */
1075static bool
1076connectOptions1(PGconn *conn, const char *conninfo)
1077{
1078 PQconninfoOption *connOptions;
1079
1080 /*
1081 * Parse the conninfo string
1082 */
1083 connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
1084 if (connOptions == NULL)
1085 {
1087 /* errorMessage is already set */
1088 return false;
1089 }
1090
1091 /*
1092 * Move option values into conn structure
1093 */
1094 if (!fillPGconn(conn, connOptions))
1095 {
1097 PQconninfoFree(connOptions);
1098 return false;
1099 }
1100
1101 /*
1102 * Free the option info - all is in conn now
1103 */
1104 PQconninfoFree(connOptions);
1105
1106 return true;
1107}
1108
1109/*
1110 * Count the number of elements in a simple comma-separated list.
1111 */
1112static int
1114{
1115 int n;
1116
1117 n = 1;
1118 for (; *input != '\0'; input++)
1119 {
1120 if (*input == ',')
1121 n++;
1122 }
1123
1124 return n;
1125}
1126
1127/*
1128 * Parse a simple comma-separated list.
1129 *
1130 * On each call, returns a malloc'd copy of the next element, and sets *more
1131 * to indicate whether there are any more elements in the list after this,
1132 * and updates *startptr to point to the next element, if any.
1133 *
1134 * On out of memory, returns NULL.
1135 */
1136static char *
1137parse_comma_separated_list(char **startptr, bool *more)
1138{
1139 char *p;
1140 char *s = *startptr;
1141 char *e;
1142 int len;
1143
1144 /*
1145 * Search for the end of the current element; a comma or end-of-string
1146 * acts as a terminator.
1147 */
1148 e = s;
1149 while (*e != '\0' && *e != ',')
1150 ++e;
1151 *more = (*e == ',');
1152
1153 len = e - s;
1154 p = (char *) malloc(sizeof(char) * (len + 1));
1155 if (p)
1156 {
1157 memcpy(p, s, len);
1158 p[len] = '\0';
1159 }
1160 *startptr = e + 1;
1161
1162 return p;
1163}
1164
1165/*
1166 * Initializes the prng_state field of the connection. We want something
1167 * unpredictable, so if possible, use high-quality random bits for the
1168 * seed. Otherwise, fall back to a seed based on the connection address,
1169 * timestamp and PID.
1170 */
1171static void
1173{
1174 uint64 rseed;
1175 struct timeval tval = {0};
1176
1178 return;
1179
1180 gettimeofday(&tval, NULL);
1181
1182 rseed = ((uintptr_t) conn) ^
1183 ((uint64) getpid()) ^
1184 ((uint64) tval.tv_usec) ^
1185 ((uint64) tval.tv_sec);
1186
1187 pg_prng_seed(&conn->prng_state, rseed);
1188}
1189
1190/*
1191 * Fills the connection's allowed_sasl_mechs list with all supported SASL
1192 * mechanisms.
1193 */
1194static inline void
1196{
1197 /*---
1198 * We only support two mechanisms at the moment, so rather than deal with a
1199 * linked list, conn->allowed_sasl_mechs is an array of static length. We
1200 * rely on the compile-time assertion here to keep us honest.
1201 *
1202 * To add a new mechanism to require_auth,
1203 * - add it to supported_sasl_mechs,
1204 * - update the length of conn->allowed_sasl_mechs,
1205 * - handle the new mechanism name in the require_auth portion of
1206 * pqConnectOptions2(), below.
1207 */
1209 "conn->allowed_sasl_mechs[] is not sufficiently large for holding all supported SASL mechanisms");
1210
1211 for (int i = 0; i < SASL_MECHANISM_COUNT; i++)
1213}
1214
1215/*
1216 * Clears the connection's allowed_sasl_mechs list.
1217 */
1218static inline void
1220{
1221 for (int i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
1222 conn->allowed_sasl_mechs[i] = NULL;
1223}
1224
1225/*
1226 * Helper routine that searches the static allowed_sasl_mechs list for a
1227 * specific mechanism.
1228 */
1229static inline int
1231{
1232 for (int i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
1233 {
1234 if (conn->allowed_sasl_mechs[i] == mech)
1235 return i;
1236 }
1237
1238 return -1;
1239}
1240
1241/*
1242 * pqConnectOptions2
1243 *
1244 * Compute derived connection options after absorbing all user-supplied info.
1245 *
1246 * Returns true if OK, false if trouble (in which case errorMessage is set
1247 * and so is conn->status).
1248 */
1249bool
1251{
1252 int i;
1253
1254 /*
1255 * Allocate memory for details about each host to which we might possibly
1256 * try to connect. For that, count the number of elements in the hostaddr
1257 * or host options. If neither is given, assume one host.
1258 */
1259 conn->whichhost = 0;
1260 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1262 else if (conn->pghost && conn->pghost[0] != '\0')
1264 else
1265 conn->nconnhost = 1;
1267 calloc(conn->nconnhost, sizeof(pg_conn_host));
1268 if (conn->connhost == NULL)
1269 goto oom_error;
1270
1271 /*
1272 * We now have one pg_conn_host structure per possible host. Fill in the
1273 * host and hostaddr fields for each, by splitting the parameter strings.
1274 */
1275 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1276 {
1277 char *s = conn->pghostaddr;
1278 bool more = true;
1279
1280 for (i = 0; i < conn->nconnhost && more; i++)
1281 {
1283 if (conn->connhost[i].hostaddr == NULL)
1284 goto oom_error;
1285 }
1286
1287 /*
1288 * If hostaddr was given, the array was allocated according to the
1289 * number of elements in the hostaddr list, so it really should be the
1290 * right size.
1291 */
1292 Assert(!more);
1293 Assert(i == conn->nconnhost);
1294 }
1295
1296 if (conn->pghost != NULL && conn->pghost[0] != '\0')
1297 {
1298 char *s = conn->pghost;
1299 bool more = true;
1300
1301 for (i = 0; i < conn->nconnhost && more; i++)
1302 {
1304 if (conn->connhost[i].host == NULL)
1305 goto oom_error;
1306 }
1307
1308 /* Check for wrong number of host items. */
1309 if (more || i != conn->nconnhost)
1310 {
1312 libpq_append_conn_error(conn, "could not match %d host names to %d hostaddr values",
1314 return false;
1315 }
1316 }
1317
1318 /*
1319 * Now, for each host slot, identify the type of address spec, and fill in
1320 * the default address if nothing was given.
1321 */
1322 for (i = 0; i < conn->nconnhost; i++)
1323 {
1324 pg_conn_host *ch = &conn->connhost[i];
1325
1326 if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1327 ch->type = CHT_HOST_ADDRESS;
1328 else if (ch->host != NULL && ch->host[0] != '\0')
1329 {
1330 ch->type = CHT_HOST_NAME;
1331 if (is_unixsock_path(ch->host))
1332 ch->type = CHT_UNIX_SOCKET;
1333 }
1334 else
1335 {
1336 free(ch->host);
1337
1338 /*
1339 * This bit selects the default host location. If you change
1340 * this, see also pg_regress.
1341 */
1342 if (DEFAULT_PGSOCKET_DIR[0])
1343 {
1344 ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1345 ch->type = CHT_UNIX_SOCKET;
1346 }
1347 else
1348 {
1349 ch->host = strdup(DefaultHost);
1350 ch->type = CHT_HOST_NAME;
1351 }
1352 if (ch->host == NULL)
1353 goto oom_error;
1354 }
1355 }
1356
1357 /*
1358 * Next, work out the port number corresponding to each host name.
1359 *
1360 * Note: unlike the above for host names, this could leave the port fields
1361 * as null or empty strings. We will substitute DEF_PGPORT whenever we
1362 * read such a port field.
1363 */
1364 if (conn->pgport != NULL && conn->pgport[0] != '\0')
1365 {
1366 char *s = conn->pgport;
1367 bool more = true;
1368
1369 for (i = 0; i < conn->nconnhost && more; i++)
1370 {
1372 if (conn->connhost[i].port == NULL)
1373 goto oom_error;
1374 }
1375
1376 /*
1377 * If exactly one port was given, use it for every host. Otherwise,
1378 * there must be exactly as many ports as there were hosts.
1379 */
1380 if (i == 1 && !more)
1381 {
1382 for (i = 1; i < conn->nconnhost; i++)
1383 {
1384 conn->connhost[i].port = strdup(conn->connhost[0].port);
1385 if (conn->connhost[i].port == NULL)
1386 goto oom_error;
1387 }
1388 }
1389 else if (more || i != conn->nconnhost)
1390 {
1392 libpq_append_conn_error(conn, "could not match %d port numbers to %d hosts",
1394 return false;
1395 }
1396 }
1397
1398 /*
1399 * If user name was not given, fetch it. (Most likely, the fetch will
1400 * fail, since the only way we get here is if pg_fe_getauthname() failed
1401 * during conninfo_add_defaults(). But now we want an error message.)
1402 */
1403 if (conn->pguser == NULL || conn->pguser[0] == '\0')
1404 {
1405 free(conn->pguser);
1407 if (!conn->pguser)
1408 {
1410 return false;
1411 }
1412 }
1413
1414 /*
1415 * If database name was not given, default it to equal user name
1416 */
1417 if (conn->dbName == NULL || conn->dbName[0] == '\0')
1418 {
1419 free(conn->dbName);
1420 conn->dbName = strdup(conn->pguser);
1421 if (!conn->dbName)
1422 goto oom_error;
1423 }
1424
1425 /*
1426 * If password was not given, try to look it up in password file. Note
1427 * that the result might be different for each host/port pair.
1428 */
1429 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1430 {
1431 /* If password file wasn't specified, use ~/PGPASSFILE */
1432 if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1433 {
1434 char homedir[MAXPGPATH];
1435
1436 if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1437 {
1440 if (!conn->pgpassfile)
1441 goto oom_error;
1442 snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1443 homedir, PGPASSFILE);
1444 }
1445 }
1446
1447 if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1448 {
1449 for (i = 0; i < conn->nconnhost; i++)
1450 {
1451 /*
1452 * Try to get a password for this host from file. We use host
1453 * for the hostname search key if given, else hostaddr (at
1454 * least one of them is guaranteed nonempty by now).
1455 */
1456 const char *pwhost = conn->connhost[i].host;
1457
1458 if (pwhost == NULL || pwhost[0] == '\0')
1459 pwhost = conn->connhost[i].hostaddr;
1460
1462 passwordFromFile(pwhost,
1463 conn->connhost[i].port,
1464 conn->dbName,
1465 conn->pguser,
1466 conn->pgpassfile);
1467 }
1468 }
1469 }
1470
1471 /*
1472 * parse and validate require_auth option
1473 */
1474 if (conn->require_auth && conn->require_auth[0])
1475 {
1476 char *s = conn->require_auth;
1477 bool first,
1478 more;
1479 bool negated = false;
1480
1481 /*
1482 * By default, start from an empty set of allowed methods and
1483 * mechanisms, and add to it.
1484 */
1485 conn->auth_required = true;
1488
1489 for (first = true, more = true; more; first = false)
1490 {
1491 char *method,
1492 *part;
1493 uint32 bits = 0;
1494 const pg_fe_sasl_mech *mech = NULL;
1495
1496 part = parse_comma_separated_list(&s, &more);
1497 if (part == NULL)
1498 goto oom_error;
1499
1500 /*
1501 * Check for negation, e.g. '!password'. If one element is
1502 * negated, they all have to be.
1503 */
1504 method = part;
1505 if (*method == '!')
1506 {
1507 if (first)
1508 {
1509 /*
1510 * Switch to a permissive set of allowed methods and
1511 * mechanisms, and subtract from it.
1512 */
1513 conn->auth_required = false;
1516 }
1517 else if (!negated)
1518 {
1520 libpq_append_conn_error(conn, "negative require_auth method \"%s\" cannot be mixed with non-negative methods",
1521 method);
1522
1523 free(part);
1524 return false;
1525 }
1526
1527 negated = true;
1528 method++;
1529 }
1530 else if (negated)
1531 {
1533 libpq_append_conn_error(conn, "require_auth method \"%s\" cannot be mixed with negative methods",
1534 method);
1535
1536 free(part);
1537 return false;
1538 }
1539
1540 /*
1541 * First group: methods that can be handled solely with the
1542 * authentication request codes.
1543 */
1544 if (strcmp(method, "password") == 0)
1545 {
1546 bits = (1 << AUTH_REQ_PASSWORD);
1547 }
1548 else if (strcmp(method, "md5") == 0)
1549 {
1550 bits = (1 << AUTH_REQ_MD5);
1551 }
1552 else if (strcmp(method, "gss") == 0)
1553 {
1554 bits = (1 << AUTH_REQ_GSS);
1555 bits |= (1 << AUTH_REQ_GSS_CONT);
1556 }
1557 else if (strcmp(method, "sspi") == 0)
1558 {
1559 bits = (1 << AUTH_REQ_SSPI);
1560 bits |= (1 << AUTH_REQ_GSS_CONT);
1561 }
1562
1563 /*
1564 * Next group: SASL mechanisms. All of these use the same request
1565 * codes, so the list of allowed mechanisms is tracked separately.
1566 *
1567 * supported_sasl_mechs must contain all mechanisms handled here.
1568 */
1569 else if (strcmp(method, "scram-sha-256") == 0)
1570 {
1571 mech = &pg_scram_mech;
1572 }
1573 else if (strcmp(method, "oauth") == 0)
1574 {
1575 mech = &pg_oauth_mech;
1576 }
1577
1578 /*
1579 * Final group: meta-options.
1580 */
1581 else if (strcmp(method, "none") == 0)
1582 {
1583 /*
1584 * Special case: let the user explicitly allow (or disallow)
1585 * connections where the server does not send an explicit
1586 * authentication challenge, such as "trust" and "cert" auth.
1587 */
1588 if (negated) /* "!none" */
1589 {
1590 if (conn->auth_required)
1591 goto duplicate;
1592
1593 conn->auth_required = true;
1594 }
1595 else /* "none" */
1596 {
1597 if (!conn->auth_required)
1598 goto duplicate;
1599
1600 conn->auth_required = false;
1601 }
1602
1603 free(part);
1604 continue; /* avoid the bitmask manipulation below */
1605 }
1606 else
1607 {
1609 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1610 "require_auth", method);
1611
1612 free(part);
1613 return false;
1614 }
1615
1616 if (mech)
1617 {
1618 /*
1619 * Update the mechanism set only. The method bitmask will be
1620 * updated for SASL further down.
1621 */
1622 Assert(!bits);
1623
1624 if (negated)
1625 {
1626 /* Remove the existing mechanism from the list. */
1628 if (i < 0)
1629 goto duplicate;
1630
1631 conn->allowed_sasl_mechs[i] = NULL;
1632 }
1633 else
1634 {
1635 /*
1636 * Find a space to put the new mechanism (after making
1637 * sure it's not already there).
1638 */
1640 if (i >= 0)
1641 goto duplicate;
1642
1644 if (i < 0)
1645 {
1646 /* Should not happen; the pointer list is corrupted. */
1647 Assert(false);
1648
1651 "internal error: no space in allowed_sasl_mechs");
1652 free(part);
1653 return false;
1654 }
1655
1656 conn->allowed_sasl_mechs[i] = mech;
1657 }
1658 }
1659 else
1660 {
1661 /* Update the method bitmask. */
1662 Assert(bits);
1663
1664 if (negated)
1665 {
1666 if ((conn->allowed_auth_methods & bits) == 0)
1667 goto duplicate;
1668
1669 conn->allowed_auth_methods &= ~bits;
1670 }
1671 else
1672 {
1673 if ((conn->allowed_auth_methods & bits) == bits)
1674 goto duplicate;
1675
1676 conn->allowed_auth_methods |= bits;
1677 }
1678 }
1679
1680 free(part);
1681 continue;
1682
1683 duplicate:
1684
1685 /*
1686 * A duplicated method probably indicates a typo in a setting
1687 * where typos are extremely risky.
1688 */
1690 libpq_append_conn_error(conn, "require_auth method \"%s\" is specified more than once",
1691 part);
1692
1693 free(part);
1694 return false;
1695 }
1696
1697 /*
1698 * Finally, allow SASL authentication requests if (and only if) we've
1699 * allowed any mechanisms.
1700 */
1701 {
1702 bool allowed = false;
1703 const uint32 sasl_bits =
1704 (1 << AUTH_REQ_SASL)
1705 | (1 << AUTH_REQ_SASL_CONT)
1706 | (1 << AUTH_REQ_SASL_FIN);
1707
1708 for (i = 0; i < lengthof(conn->allowed_sasl_mechs); i++)
1709 {
1711 {
1712 allowed = true;
1713 break;
1714 }
1715 }
1716
1717 /*
1718 * For the standard case, add the SASL bits to the (default-empty)
1719 * set if needed. For the negated case, remove them.
1720 */
1721 if (!negated && allowed)
1722 conn->allowed_auth_methods |= sasl_bits;
1723 else if (negated && !allowed)
1724 conn->allowed_auth_methods &= ~sasl_bits;
1725 }
1726 }
1727
1728 /*
1729 * validate channel_binding option
1730 */
1731 if (conn->channel_binding)
1732 {
1733 if (strcmp(conn->channel_binding, "disable") != 0
1734 && strcmp(conn->channel_binding, "prefer") != 0
1735 && strcmp(conn->channel_binding, "require") != 0)
1736 {
1738 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1739 "channel_binding", conn->channel_binding);
1740 return false;
1741 }
1742 }
1743 else
1744 {
1746 if (!conn->channel_binding)
1747 goto oom_error;
1748 }
1749
1750#ifndef USE_SSL
1751
1752 /*
1753 * sslrootcert=system is not supported. Since setting this changes the
1754 * default sslmode, check this _before_ we validate sslmode, to avoid
1755 * confusing the user with errors for an option they may not have set.
1756 */
1757 if (conn->sslrootcert
1758 && strcmp(conn->sslrootcert, "system") == 0)
1759 {
1761 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1762 "sslrootcert", conn->sslrootcert);
1763 return false;
1764 }
1765#endif
1766
1767 /*
1768 * validate sslmode option
1769 */
1770 if (conn->sslmode)
1771 {
1772 if (strcmp(conn->sslmode, "disable") != 0
1773 && strcmp(conn->sslmode, "allow") != 0
1774 && strcmp(conn->sslmode, "prefer") != 0
1775 && strcmp(conn->sslmode, "require") != 0
1776 && strcmp(conn->sslmode, "verify-ca") != 0
1777 && strcmp(conn->sslmode, "verify-full") != 0)
1778 {
1780 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1781 "sslmode", conn->sslmode);
1782 return false;
1783 }
1784
1785#ifndef USE_SSL
1786 switch (conn->sslmode[0])
1787 {
1788 case 'a': /* "allow" */
1789 case 'p': /* "prefer" */
1790
1791 /*
1792 * warn user that an SSL connection will never be negotiated
1793 * since SSL was not compiled in?
1794 */
1795 break;
1796
1797 case 'r': /* "require" */
1798 case 'v': /* "verify-ca" or "verify-full" */
1800 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1801 "sslmode", conn->sslmode);
1802 return false;
1803 }
1804#endif
1805 }
1806 else
1807 {
1808 conn->sslmode = strdup(DefaultSSLMode);
1809 if (!conn->sslmode)
1810 goto oom_error;
1811 }
1812
1813 /*
1814 * validate sslnegotiation option, default is "postgres" for the postgres
1815 * style negotiated connection with an extra round trip but more options.
1816 */
1817 if (conn->sslnegotiation)
1818 {
1819 if (strcmp(conn->sslnegotiation, "postgres") != 0
1820 && strcmp(conn->sslnegotiation, "direct") != 0)
1821 {
1823 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1824 "sslnegotiation", conn->sslnegotiation);
1825 return false;
1826 }
1827
1828#ifndef USE_SSL
1829 if (conn->sslnegotiation[0] != 'p')
1830 {
1832 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1833 "sslnegotiation", conn->sslnegotiation);
1834 return false;
1835 }
1836#endif
1837
1838 /*
1839 * Don't allow direct SSL negotiation with sslmode='prefer', because
1840 * that poses a risk of unintentional fallback to plaintext connection
1841 * when connecting to a pre-v17 server that does not support direct
1842 * SSL connections. To keep things simple, don't allow it with
1843 * sslmode='allow' or sslmode='disable' either. If a user goes through
1844 * the trouble of setting sslnegotiation='direct', they probably
1845 * intend to use SSL, and sslmode=disable or allow is probably a user
1846 * mistake anyway.
1847 */
1848 if (conn->sslnegotiation[0] == 'd' &&
1849 conn->sslmode[0] != 'r' && conn->sslmode[0] != 'v')
1850 {
1852 libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslnegotiation=direct (use \"require\", \"verify-ca\", or \"verify-full\")",
1853 conn->sslmode);
1854 return false;
1855 }
1856 }
1857 else
1858 {
1860 if (!conn->sslnegotiation)
1861 goto oom_error;
1862 }
1863
1864#ifdef USE_SSL
1865
1866 /*
1867 * If sslrootcert=system, make sure our chosen sslmode is compatible.
1868 */
1869 if (conn->sslrootcert
1870 && strcmp(conn->sslrootcert, "system") == 0
1871 && strcmp(conn->sslmode, "verify-full") != 0)
1872 {
1874 libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslrootcert=system (use \"verify-full\")",
1875 conn->sslmode);
1876 return false;
1877 }
1878#endif
1879
1880 /*
1881 * Validate TLS protocol versions for ssl_min_protocol_version and
1882 * ssl_max_protocol_version.
1883 */
1885 {
1887 libpq_append_conn_error(conn, "invalid \"%s\" value: \"%s\"",
1888 "ssl_min_protocol_version",
1890 return false;
1891 }
1893 {
1895 libpq_append_conn_error(conn, "invalid \"%s\" value: \"%s\"",
1896 "ssl_max_protocol_version",
1898 return false;
1899 }
1900
1901 /*
1902 * Check if the range of SSL protocols defined is correct. This is done
1903 * at this early step because this is independent of the SSL
1904 * implementation used, and this avoids unnecessary cycles with an
1905 * already-built SSL context when the connection is being established, as
1906 * it would be doomed anyway.
1907 */
1910 {
1912 libpq_append_conn_error(conn, "invalid SSL protocol version range");
1913 return false;
1914 }
1915
1916 /*
1917 * validate sslcertmode option
1918 */
1919 if (conn->sslcertmode)
1920 {
1921 if (strcmp(conn->sslcertmode, "disable") != 0 &&
1922 strcmp(conn->sslcertmode, "allow") != 0 &&
1923 strcmp(conn->sslcertmode, "require") != 0)
1924 {
1926 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1927 "sslcertmode", conn->sslcertmode);
1928 return false;
1929 }
1930#ifndef USE_SSL
1931 if (strcmp(conn->sslcertmode, "require") == 0)
1932 {
1934 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1935 "sslcertmode", conn->sslcertmode);
1936 return false;
1937 }
1938#endif
1939#ifndef HAVE_SSL_CTX_SET_CERT_CB
1940
1941 /*
1942 * Without a certificate callback, the current implementation can't
1943 * figure out if a certificate was actually requested, so "require" is
1944 * useless.
1945 */
1946 if (strcmp(conn->sslcertmode, "require") == 0)
1947 {
1949 libpq_append_conn_error(conn, "%s value \"%s\" is not supported (check OpenSSL version)",
1950 "sslcertmode", conn->sslcertmode);
1951 return false;
1952 }
1953#endif
1954 }
1955 else
1956 {
1958 if (!conn->sslcertmode)
1959 goto oom_error;
1960 }
1961
1962 /*
1963 * validate gssencmode option
1964 */
1965 if (conn->gssencmode)
1966 {
1967 if (strcmp(conn->gssencmode, "disable") != 0 &&
1968 strcmp(conn->gssencmode, "prefer") != 0 &&
1969 strcmp(conn->gssencmode, "require") != 0)
1970 {
1972 libpq_append_conn_error(conn, "invalid %s value: \"%s\"", "gssencmode", conn->gssencmode);
1973 return false;
1974 }
1975#ifndef ENABLE_GSS
1976 if (strcmp(conn->gssencmode, "require") == 0)
1977 {
1979 libpq_append_conn_error(conn, "gssencmode value \"%s\" invalid when GSSAPI support is not compiled in",
1980 conn->gssencmode);
1981 return false;
1982 }
1983#endif
1984 }
1985 else
1986 {
1987 conn->gssencmode = strdup(DefaultGSSMode);
1988 if (!conn->gssencmode)
1989 goto oom_error;
1990 }
1991
1992 /*
1993 * validate target_session_attrs option, and set target_server_type
1994 */
1996 {
1997 if (strcmp(conn->target_session_attrs, "any") == 0)
1999 else if (strcmp(conn->target_session_attrs, "read-write") == 0)
2001 else if (strcmp(conn->target_session_attrs, "read-only") == 0)
2003 else if (strcmp(conn->target_session_attrs, "primary") == 0)
2005 else if (strcmp(conn->target_session_attrs, "standby") == 0)
2007 else if (strcmp(conn->target_session_attrs, "prefer-standby") == 0)
2009 else
2010 {
2012 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
2013 "target_session_attrs",
2015 return false;
2016 }
2017 }
2018 else
2020
2022 {
2023 int len;
2024
2028 goto oom_error;
2031 if (len < 0)
2032 {
2033 libpq_append_conn_error(conn, "invalid SCRAM client key");
2034 return false;
2035 }
2036 if (len != SCRAM_MAX_KEY_LEN)
2037 {
2038 libpq_append_conn_error(conn, "invalid SCRAM client key length: %d", len);
2039 return false;
2040 }
2042 }
2043
2045 {
2046 int len;
2047
2051 goto oom_error;
2054 if (len < 0)
2055 {
2056 libpq_append_conn_error(conn, "invalid SCRAM server key");
2057 return false;
2058 }
2059 if (len != SCRAM_MAX_KEY_LEN)
2060 {
2061 libpq_append_conn_error(conn, "invalid SCRAM server key length: %d", len);
2062 return false;
2063 }
2065 }
2066
2067 /*
2068 * validate load_balance_hosts option, and set load_balance_type
2069 */
2071 {
2072 if (strcmp(conn->load_balance_hosts, "disable") == 0)
2074 else if (strcmp(conn->load_balance_hosts, "random") == 0)
2076 else
2077 {
2079 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
2080 "load_balance_hosts",
2082 return false;
2083 }
2084 }
2085 else
2087
2089 {
2091
2092 /*
2093 * This is the "inside-out" variant of the Fisher-Yates shuffle
2094 * algorithm. Notionally, we append each new value to the array and
2095 * then swap it with a randomly-chosen array element (possibly
2096 * including itself, else we fail to generate permutations with the
2097 * last integer last). The swap step can be optimized by combining it
2098 * with the insertion.
2099 */
2100 for (i = 1; i < conn->nconnhost; i++)
2101 {
2102 int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2103 pg_conn_host temp = conn->connhost[j];
2104
2105 conn->connhost[j] = conn->connhost[i];
2106 conn->connhost[i] = temp;
2107 }
2108 }
2109
2111 {
2112 if (!pqParseProtocolVersion(conn->min_protocol_version, &conn->min_pversion, conn, "min_protocol_version"))
2113 {
2115 return false;
2116 }
2117 }
2118 else
2119 {
2121 }
2122
2124 {
2125 if (!pqParseProtocolVersion(conn->max_protocol_version, &conn->max_pversion, conn, "max_protocol_version"))
2126 {
2128 return false;
2129 }
2130 }
2131 else
2132 {
2133 /*
2134 * To not break connecting to older servers/poolers that do not yet
2135 * support NegotiateProtocolVersion, default to the 3.0 protocol at
2136 * least for a while longer. Except when min_protocol_version is set
2137 * to something larger, then we might as well default to the latest.
2138 */
2139 if (conn->min_pversion > PG_PROTOCOL(3, 0))
2141 else
2142 conn->max_pversion = PG_PROTOCOL(3, 0);
2143 }
2144
2146 {
2148 libpq_append_conn_error(conn, "\"%s\" is greater than \"%s\"", "min_protocol_version", "max_protocol_version");
2149 return false;
2150 }
2151
2152 /*
2153 * Resolve special "auto" client_encoding from the locale
2154 */
2156 strcmp(conn->client_encoding_initial, "auto") == 0)
2157 {
2161 goto oom_error;
2162 }
2163
2164 /*
2165 * Only if we get this far is it appropriate to try to connect. (We need a
2166 * state flag, rather than just the boolean result of this function, in
2167 * case someone tries to PQreset() the PGconn.)
2168 */
2169 conn->options_valid = true;
2170
2171 return true;
2172
2173oom_error:
2175 libpq_append_conn_error(conn, "out of memory");
2176 return false;
2177}
2178
2179/*
2180 * PQconndefaults
2181 *
2182 * Construct a default connection options array, which identifies all the
2183 * available options and shows any default values that are available from the
2184 * environment etc. On error (eg out of memory), NULL is returned.
2185 *
2186 * Using this function, an application may determine all possible options
2187 * and their current default values.
2188 *
2189 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
2190 * and should be freed when no longer needed via PQconninfoFree(). (In prior
2191 * versions, the returned array was static, but that's not thread-safe.)
2192 * Pre-7.0 applications that use this function will see a small memory leak
2193 * until they are updated to call PQconninfoFree.
2194 */
2197{
2198 PQExpBufferData errorBuf;
2199 PQconninfoOption *connOptions;
2200
2201 /* We don't actually report any errors here, but callees want a buffer */
2202 initPQExpBuffer(&errorBuf);
2203 if (PQExpBufferDataBroken(errorBuf))
2204 return NULL; /* out of memory already :-( */
2205
2206 connOptions = conninfo_init(&errorBuf);
2207 if (connOptions != NULL)
2208 {
2209 /* pass NULL errorBuf to ignore errors */
2210 if (!conninfo_add_defaults(connOptions, NULL))
2211 {
2212 PQconninfoFree(connOptions);
2213 connOptions = NULL;
2214 }
2215 }
2216
2217 termPQExpBuffer(&errorBuf);
2218 return connOptions;
2219}
2220
2221/* ----------------
2222 * PQsetdbLogin
2223 *
2224 * establishes a connection to a postgres backend through the postmaster
2225 * at the specified host and port.
2226 *
2227 * returns a PGconn* which is needed for all subsequent libpq calls
2228 *
2229 * if the status field of the connection returned is CONNECTION_BAD,
2230 * then only the errorMessage is likely to be useful.
2231 * ----------------
2232 */
2233PGconn *
2234PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
2235 const char *pgtty, const char *dbName, const char *login,
2236 const char *pwd)
2237{
2238 PGconn *conn;
2239
2240 /*
2241 * Allocate memory for the conn structure. Note that we also expect this
2242 * to initialize conn->errorMessage to empty. All subsequent steps during
2243 * connection initialization will only append to that buffer.
2244 */
2246 if (conn == NULL)
2247 return NULL;
2248
2249 /*
2250 * If the dbName parameter contains what looks like a connection string,
2251 * parse it into conn struct using connectOptions1.
2252 */
2254 {
2256 return conn;
2257 }
2258 else
2259 {
2260 /*
2261 * Old-style path: first, parse an empty conninfo string in order to
2262 * set up the same defaults that PQconnectdb() would use.
2263 */
2264 if (!connectOptions1(conn, ""))
2265 return conn;
2266
2267 /* Insert dbName parameter value into struct */
2268 if (dbName && dbName[0] != '\0')
2269 {
2270 free(conn->dbName);
2271 conn->dbName = strdup(dbName);
2272 if (!conn->dbName)
2273 goto oom_error;
2274 }
2275 }
2276
2277 /*
2278 * Insert remaining parameters into struct, overriding defaults (as well
2279 * as any conflicting data from dbName taken as a conninfo).
2280 */
2281 if (pghost && pghost[0] != '\0')
2282 {
2283 free(conn->pghost);
2284 conn->pghost = strdup(pghost);
2285 if (!conn->pghost)
2286 goto oom_error;
2287 }
2288
2289 if (pgport && pgport[0] != '\0')
2290 {
2291 free(conn->pgport);
2292 conn->pgport = strdup(pgport);
2293 if (!conn->pgport)
2294 goto oom_error;
2295 }
2296
2297 if (pgoptions && pgoptions[0] != '\0')
2298 {
2300 conn->pgoptions = strdup(pgoptions);
2301 if (!conn->pgoptions)
2302 goto oom_error;
2303 }
2304
2305 if (login && login[0] != '\0')
2306 {
2307 free(conn->pguser);
2308 conn->pguser = strdup(login);
2309 if (!conn->pguser)
2310 goto oom_error;
2311 }
2312
2313 if (pwd && pwd[0] != '\0')
2314 {
2315 free(conn->pgpass);
2316 conn->pgpass = strdup(pwd);
2317 if (!conn->pgpass)
2318 goto oom_error;
2319 }
2320
2321 /*
2322 * Compute derived options
2323 */
2324 if (!pqConnectOptions2(conn))
2325 return conn;
2326
2327 /*
2328 * Connect to the database
2329 */
2331 (void) pqConnectDBComplete(conn);
2332
2333 return conn;
2334
2335oom_error:
2337 libpq_append_conn_error(conn, "out of memory");
2338 return conn;
2339}
2340
2341
2342/* ----------
2343 * connectNoDelay -
2344 * Sets the TCP_NODELAY socket option.
2345 * Returns 1 if successful, 0 if not.
2346 * ----------
2347 */
2348static int
2350{
2351#ifdef TCP_NODELAY
2352 int on = 1;
2353
2354 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
2355 (char *) &on,
2356 sizeof(on)) < 0)
2357 {
2358 char sebuf[PG_STRERROR_R_BUFLEN];
2359
2360 libpq_append_conn_error(conn, "could not set socket to TCP no delay mode: %s",
2361 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2362 return 0;
2363 }
2364#endif
2365
2366 return 1;
2367}
2368
2369/* ----------
2370 * Write currently connected IP address into host_addr (of len host_addr_len).
2371 * If unable to, set it to the empty string.
2372 * ----------
2373 */
2374static void
2375getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
2376{
2377 struct sockaddr_storage *addr = &conn->raddr.addr;
2378
2379 if (addr->ss_family == AF_INET)
2380 {
2381 if (pg_inet_net_ntop(AF_INET,
2382 &((struct sockaddr_in *) addr)->sin_addr.s_addr,
2383 32,
2384 host_addr, host_addr_len) == NULL)
2385 host_addr[0] = '\0';
2386 }
2387 else if (addr->ss_family == AF_INET6)
2388 {
2389 if (pg_inet_net_ntop(AF_INET6,
2390 &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
2391 128,
2392 host_addr, host_addr_len) == NULL)
2393 host_addr[0] = '\0';
2394 }
2395 else
2396 host_addr[0] = '\0';
2397}
2398
2399/*
2400 * emitHostIdentityInfo -
2401 * Speculatively append "connection to server so-and-so failed: " to
2402 * conn->errorMessage once we've identified the current connection target
2403 * address. This ensures that any subsequent error message will be properly
2404 * attributed to the server we couldn't connect to. conn->raddr must be
2405 * valid, and the result of getHostaddr() must be supplied.
2406 */
2407static void
2408emitHostIdentityInfo(PGconn *conn, const char *host_addr)
2409{
2410 if (conn->raddr.addr.ss_family == AF_UNIX)
2411 {
2412 char service[NI_MAXHOST];
2413
2415 NULL, 0,
2416 service, sizeof(service),
2417 NI_NUMERICSERV);
2419 libpq_gettext("connection to server on socket \"%s\" failed: "),
2420 service);
2421 }
2422 else
2423 {
2424 const char *displayed_host;
2425 const char *displayed_port;
2426
2427 /* To which host and port were we actually connecting? */
2429 displayed_host = conn->connhost[conn->whichhost].hostaddr;
2430 else
2431 displayed_host = conn->connhost[conn->whichhost].host;
2432 displayed_port = conn->connhost[conn->whichhost].port;
2433 if (displayed_port == NULL || displayed_port[0] == '\0')
2434 displayed_port = DEF_PGPORT_STR;
2435
2436 /*
2437 * If the user did not supply an IP address using 'hostaddr', and
2438 * 'host' was missing or does not match our lookup, display the
2439 * looked-up IP address.
2440 */
2442 host_addr[0] &&
2443 strcmp(displayed_host, host_addr) != 0)
2445 libpq_gettext("connection to server at \"%s\" (%s), port %s failed: "),
2446 displayed_host, host_addr,
2447 displayed_port);
2448 else
2450 libpq_gettext("connection to server at \"%s\", port %s failed: "),
2451 displayed_host,
2452 displayed_port);
2453 }
2454}
2455
2456/* ----------
2457 * connectFailureMessage -
2458 * create a friendly error message on connection failure,
2459 * using the given errno value. Use this for error cases that
2460 * imply that there's no server there.
2461 * ----------
2462 */
2463static void
2465{
2466 char sebuf[PG_STRERROR_R_BUFLEN];
2467
2469 "%s\n",
2470 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2471
2472 if (conn->raddr.addr.ss_family == AF_UNIX)
2473 libpq_append_conn_error(conn, "\tIs the server running locally and accepting connections on that socket?");
2474 else
2475 libpq_append_conn_error(conn, "\tIs the server running on that host and accepting TCP/IP connections?");
2476}
2477
2478/*
2479 * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
2480 * conn->keepalives is set to a value which is not parseable as an
2481 * integer.
2482 */
2483static int
2485{
2486 int val;
2487
2488 if (conn->keepalives == NULL)
2489 return 1;
2490
2491 if (!pqParseIntParam(conn->keepalives, &val, conn, "keepalives"))
2492 return -1;
2493
2494 return val != 0 ? 1 : 0;
2495}
2496
2497#ifndef WIN32
2498/*
2499 * Set the keepalive idle timer.
2500 */
2501static int
2503{
2504 int idle;
2505
2506 if (conn->keepalives_idle == NULL)
2507 return 1;
2508
2510 "keepalives_idle"))
2511 return 0;
2512 if (idle < 0)
2513 idle = 0;
2514
2515#ifdef PG_TCP_KEEPALIVE_IDLE
2516 if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2517 (char *) &idle, sizeof(idle)) < 0)
2518 {
2519 char sebuf[PG_STRERROR_R_BUFLEN];
2520
2521 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2522 "setsockopt",
2523 PG_TCP_KEEPALIVE_IDLE_STR,
2524 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2525 return 0;
2526 }
2527#endif
2528
2529 return 1;
2530}
2531
2532/*
2533 * Set the keepalive interval.
2534 */
2535static int
2537{
2538 int interval;
2539
2540 if (conn->keepalives_interval == NULL)
2541 return 1;
2542
2544 "keepalives_interval"))
2545 return 0;
2546 if (interval < 0)
2547 interval = 0;
2548
2549#ifdef TCP_KEEPINTVL
2550 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
2551 (char *) &interval, sizeof(interval)) < 0)
2552 {
2553 char sebuf[PG_STRERROR_R_BUFLEN];
2554
2555 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2556 "setsockopt",
2557 "TCP_KEEPINTVL",
2558 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2559 return 0;
2560 }
2561#endif
2562
2563 return 1;
2564}
2565
2566/*
2567 * Set the count of lost keepalive packets that will trigger a connection
2568 * break.
2569 */
2570static int
2572{
2573 int count;
2574
2575 if (conn->keepalives_count == NULL)
2576 return 1;
2577
2579 "keepalives_count"))
2580 return 0;
2581 if (count < 0)
2582 count = 0;
2583
2584#ifdef TCP_KEEPCNT
2585 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
2586 (char *) &count, sizeof(count)) < 0)
2587 {
2588 char sebuf[PG_STRERROR_R_BUFLEN];
2589
2590 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2591 "setsockopt",
2592 "TCP_KEEPCNT",
2593 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2594 return 0;
2595 }
2596#endif
2597
2598 return 1;
2599}
2600#else /* WIN32 */
2601#ifdef SIO_KEEPALIVE_VALS
2602/*
2603 * Enable keepalives and set the keepalive values on Win32,
2604 * where they are always set in one batch.
2605 *
2606 * CAUTION: This needs to be signal safe, since it's used by PQcancel.
2607 */
2608int
2609pqSetKeepalivesWin32(pgsocket sock, int idle, int interval)
2610{
2611 struct tcp_keepalive ka;
2612 DWORD retsize;
2613
2614 if (idle <= 0)
2615 idle = 2 * 60 * 60; /* 2 hours = default */
2616 if (interval <= 0)
2617 interval = 1; /* 1 second = default */
2618
2619 ka.onoff = 1;
2620 ka.keepalivetime = idle * 1000;
2621 ka.keepaliveinterval = interval * 1000;
2622
2623 if (WSAIoctl(sock,
2624 SIO_KEEPALIVE_VALS,
2625 (LPVOID) &ka,
2626 sizeof(ka),
2627 NULL,
2628 0,
2629 &retsize,
2630 NULL,
2631 NULL)
2632 != 0)
2633 return 0;
2634 return 1;
2635}
2636
2637static int
2638prepKeepalivesWin32(PGconn *conn)
2639{
2640 int idle = -1;
2641 int interval = -1;
2642
2643 if (conn->keepalives_idle &&
2645 "keepalives_idle"))
2646 return 0;
2649 "keepalives_interval"))
2650 return 0;
2651
2652 if (!pqSetKeepalivesWin32(conn->sock, idle, interval))
2653 {
2654 libpq_append_conn_error(conn, "%s(%s) failed: error code %d",
2655 "WSAIoctl", "SIO_KEEPALIVE_VALS",
2656 WSAGetLastError());
2657 return 0;
2658 }
2659 return 1;
2660}
2661#endif /* SIO_KEEPALIVE_VALS */
2662#endif /* WIN32 */
2663
2664/*
2665 * Set the TCP user timeout.
2666 */
2667static int
2669{
2670 int timeout;
2671
2672 if (conn->pgtcp_user_timeout == NULL)
2673 return 1;
2674
2676 "tcp_user_timeout"))
2677 return 0;
2678
2679 if (timeout < 0)
2680 timeout = 0;
2681
2682#ifdef TCP_USER_TIMEOUT
2683 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2684 (char *) &timeout, sizeof(timeout)) < 0)
2685 {
2686 char sebuf[256];
2687
2688 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2689 "setsockopt",
2690 "TCP_USER_TIMEOUT",
2691 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2692 return 0;
2693 }
2694#endif
2695
2696 return 1;
2697}
2698
2699/* ----------
2700 * pqConnectDBStart -
2701 * Begin the process of making a connection to the backend.
2702 *
2703 * Returns 1 if successful, 0 if not.
2704 * ----------
2705 */
2706int
2708{
2709 if (!conn)
2710 return 0;
2711
2712 if (!conn->options_valid)
2713 goto connect_errReturn;
2714
2715 /*
2716 * Check for bad linking to backend-internal versions of src/common
2717 * functions (see comments in link-canary.c for the reason we need this).
2718 * Nobody but developers should see this message, so we don't bother
2719 * translating it.
2720 */
2722 {
2724 "libpq is incorrectly linked to backend functions\n");
2725 goto connect_errReturn;
2726 }
2727
2728 /* Ensure our buffers are empty */
2729 conn->inStart = conn->inCursor = conn->inEnd = 0;
2730 conn->outCount = 0;
2731
2732 /*
2733 * Set up to try to connect to the first host. (Setting whichhost = -1 is
2734 * a bit of a cheat, but PQconnectPoll will advance it to 0 before
2735 * anything else looks at it.)
2736 *
2737 * Cancel requests are special though, they should only try one host and
2738 * address, and these fields have already been set up in PQcancelCreate,
2739 * so leave these fields alone for cancel requests.
2740 */
2741 if (!conn->cancelRequest)
2742 {
2743 conn->whichhost = -1;
2744 conn->try_next_host = true;
2745 conn->try_next_addr = false;
2746 }
2747
2749
2750 /* Also reset the target_server_type state if needed */
2753
2754 /*
2755 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
2756 * so that it can easily be re-executed if needed again during the
2757 * asynchronous startup process. However, we must run it once here,
2758 * because callers expect a success return from this routine to mean that
2759 * we are in PGRES_POLLING_WRITING connection state.
2760 */
2762 return 1;
2763
2764connect_errReturn:
2765
2766 /*
2767 * If we managed to open a socket, close it immediately rather than
2768 * waiting till PQfinish. (The application cannot have gotten the socket
2769 * from PQsocket yet, so this doesn't risk breaking anything.)
2770 */
2771 pqDropConnection(conn, true);
2773 return 0;
2774}
2775
2776
2777/*
2778 * pqConnectDBComplete
2779 *
2780 * Block and complete a connection.
2781 *
2782 * Returns 1 on success, 0 on failure.
2783 */
2784int
2786{
2789 int timeout = 0;
2790 int last_whichhost = -2; /* certainly different from whichhost */
2791 int last_whichaddr = -2; /* certainly different from whichaddr */
2792
2793 if (conn == NULL || conn->status == CONNECTION_BAD)
2794 return 0;
2795
2796 /*
2797 * Set up a time limit, if connect_timeout is greater than zero.
2798 */
2799 if (conn->connect_timeout != NULL)
2800 {
2801 if (!pqParseIntParam(conn->connect_timeout, &timeout, conn,
2802 "connect_timeout"))
2803 {
2804 /* mark the connection as bad to report the parsing failure */
2806 return 0;
2807 }
2808 }
2809
2810 for (;;)
2811 {
2812 int ret = 0;
2813
2814 /*
2815 * (Re)start the connect_timeout timer if it's active and we are
2816 * considering a different host than we were last time through. If
2817 * we've already succeeded, though, needn't recalculate.
2818 */
2819 if (flag != PGRES_POLLING_OK &&
2820 timeout > 0 &&
2821 (conn->whichhost != last_whichhost ||
2822 conn->whichaddr != last_whichaddr))
2823 {
2824 end_time = PQgetCurrentTimeUSec() + (pg_usec_time_t) timeout * 1000000;
2825 last_whichhost = conn->whichhost;
2826 last_whichaddr = conn->whichaddr;
2827 }
2828
2829 /*
2830 * Wait, if necessary. Note that the initial state (just after
2831 * PQconnectStart) is to wait for the socket to select for writing.
2832 */
2833 switch (flag)
2834 {
2835 case PGRES_POLLING_OK:
2836 return 1; /* success! */
2837
2839 ret = pqWaitTimed(1, 0, conn, end_time);
2840 if (ret == -1)
2841 {
2842 /* hard failure, eg select() problem, aborts everything */
2844 return 0;
2845 }
2846 break;
2847
2849 ret = pqWaitTimed(0, 1, conn, end_time);
2850 if (ret == -1)
2851 {
2852 /* hard failure, eg select() problem, aborts everything */
2854 return 0;
2855 }
2856 break;
2857
2858 default:
2859 /* Just in case we failed to set it in PQconnectPoll */
2861 return 0;
2862 }
2863
2864 if (ret == 1) /* connect_timeout elapsed */
2865 {
2866 /*
2867 * Give up on current server/address, try the next one.
2868 */
2869 conn->try_next_addr = true;
2871 }
2872
2873 /*
2874 * Now try to advance the state machine.
2875 */
2876 if (conn->cancelRequest)
2878 else
2880 }
2881}
2882
2883/* ----------------
2884 * PQconnectPoll
2885 *
2886 * Poll an asynchronous connection.
2887 *
2888 * Returns a PostgresPollingStatusType.
2889 * Before calling this function, use select(2) to determine when data
2890 * has arrived..
2891 *
2892 * You must call PQfinish whether or not this fails.
2893 *
2894 * This function and PQconnectStart are intended to allow connections to be
2895 * made without blocking the execution of your program on remote I/O. However,
2896 * there are a number of caveats:
2897 *
2898 * o If you call PQtrace, ensure that the stream object into which you trace
2899 * will not block.
2900 * o If you do not supply an IP address for the remote host (i.e. you
2901 * supply a host name instead) then PQconnectStart will block on
2902 * getaddrinfo. You will be fine if using Unix sockets (i.e. by
2903 * supplying neither a host name nor a host address).
2904 * o If your backend wants to use Kerberos authentication then you must
2905 * supply both a host name and a host address, otherwise this function
2906 * may block on gethostname.
2907 *
2908 * ----------------
2909 */
2912{
2913 bool reset_connection_state_machine = false;
2914 bool need_new_connection = false;
2915 PGresult *res;
2916 char sebuf[PG_STRERROR_R_BUFLEN];
2917 int optval;
2918
2919 if (conn == NULL)
2920 return PGRES_POLLING_FAILED;
2921
2922 /* Get the new data */
2923 switch (conn->status)
2924 {
2925 /*
2926 * We really shouldn't have been polled in these two cases, but we
2927 * can handle it.
2928 */
2929 case CONNECTION_BAD:
2930 return PGRES_POLLING_FAILED;
2931 case CONNECTION_OK:
2932 return PGRES_POLLING_OK;
2933
2934 /* These are reading states */
2936 case CONNECTION_AUTH_OK:
2938 case CONNECTION_CONSUME:
2940 {
2941 /* Load waiting data */
2942 int n = pqReadData(conn);
2943
2944 if (n < 0)
2945 goto error_return;
2946 if (n == 0)
2947 return PGRES_POLLING_READING;
2948
2949 break;
2950 }
2951
2952 /* These are writing states, so we just proceed. */
2953 case CONNECTION_STARTED:
2954 case CONNECTION_MADE:
2955 break;
2956
2957 /* Special cases: proceed without waiting. */
2959 case CONNECTION_NEEDED:
2963 break;
2964
2965 default:
2966 libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2967 goto error_return;
2968 }
2969
2970
2971keep_going: /* We will come back to here until there is
2972 * nothing left to do. */
2973
2974 /* Time to advance to next address, or next host if no more addresses? */
2975 if (conn->try_next_addr)
2976 {
2977 if (conn->whichaddr < conn->naddr)
2978 {
2979 conn->whichaddr++;
2980 reset_connection_state_machine = true;
2981 }
2982 else
2983 conn->try_next_host = true;
2984 conn->try_next_addr = false;
2985 }
2986
2987 /* Time to advance to next connhost[] entry? */
2988 if (conn->try_next_host)
2989 {
2990 pg_conn_host *ch;
2991 struct addrinfo hint;
2992 struct addrinfo *addrlist;
2993 int thisport;
2994 int ret;
2995 char portstr[MAXPGPATH];
2996
2997 if (conn->whichhost + 1 < conn->nconnhost)
2998 conn->whichhost++;
2999 else
3000 {
3001 /*
3002 * Oops, no more hosts.
3003 *
3004 * If we are trying to connect in "prefer-standby" mode, then drop
3005 * the standby requirement and start over. Don't do this for
3006 * cancel requests though, since we are certain the list of
3007 * servers won't change as the target_server_type option is not
3008 * applicable to those connections.
3009 *
3010 * Otherwise, an appropriate error message is already set up, so
3011 * we just need to set the right status.
3012 */
3014 conn->nconnhost > 0 &&
3016 {
3018 conn->whichhost = 0;
3019 }
3020 else
3021 goto error_return;
3022 }
3023
3024 /* Drop any address info for previous host */
3026
3027 /*
3028 * Look up info for the new host. On failure, log the problem in
3029 * conn->errorMessage, then loop around to try the next host. (Note
3030 * we don't clear try_next_host until we've succeeded.)
3031 */
3032 ch = &conn->connhost[conn->whichhost];
3033
3034 /* Initialize hint structure */
3035 MemSet(&hint, 0, sizeof(hint));
3036 hint.ai_socktype = SOCK_STREAM;
3037 hint.ai_family = AF_UNSPEC;
3038
3039 /* Figure out the port number we're going to use. */
3040 if (ch->port == NULL || ch->port[0] == '\0')
3041 thisport = DEF_PGPORT;
3042 else
3043 {
3044 if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
3045 goto error_return;
3046
3047 if (thisport < 1 || thisport > 65535)
3048 {
3049 libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
3050 goto keep_going;
3051 }
3052 }
3053 snprintf(portstr, sizeof(portstr), "%d", thisport);
3054
3055 /* Use pg_getaddrinfo_all() to resolve the address */
3056 switch (ch->type)
3057 {
3058 case CHT_HOST_NAME:
3059 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
3060 &addrlist);
3061 if (ret || !addrlist)
3062 {
3063 libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
3064 ch->host, gai_strerror(ret));
3065 goto keep_going;
3066 }
3067 break;
3068
3069 case CHT_HOST_ADDRESS:
3070 hint.ai_flags = AI_NUMERICHOST;
3071 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
3072 &addrlist);
3073 if (ret || !addrlist)
3074 {
3075 libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
3076 ch->hostaddr, gai_strerror(ret));
3077 goto keep_going;
3078 }
3079 break;
3080
3081 case CHT_UNIX_SOCKET:
3082 hint.ai_family = AF_UNIX;
3083 UNIXSOCK_PATH(portstr, thisport, ch->host);
3084 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
3085 {
3086 libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
3087 portstr,
3088 (int) (UNIXSOCK_PATH_BUFLEN - 1));
3089 goto keep_going;
3090 }
3091
3092 /*
3093 * NULL hostname tells pg_getaddrinfo_all to parse the service
3094 * name as a Unix-domain socket path.
3095 */
3096 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
3097 &addrlist);
3098 if (ret || !addrlist)
3099 {
3100 libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
3101 portstr, gai_strerror(ret));
3102 goto keep_going;
3103 }
3104 break;
3105 }
3106
3107 /*
3108 * Store a copy of the addrlist in private memory so we can perform
3109 * randomization for load balancing.
3110 */
3111 ret = store_conn_addrinfo(conn, addrlist);
3112 pg_freeaddrinfo_all(hint.ai_family, addrlist);
3113 if (ret)
3114 goto error_return; /* message already logged */
3115
3116 /*
3117 * If random load balancing is enabled we shuffle the addresses.
3118 */
3120 {
3121 /*
3122 * This is the "inside-out" variant of the Fisher-Yates shuffle
3123 * algorithm. Notionally, we append each new value to the array
3124 * and then swap it with a randomly-chosen array element (possibly
3125 * including itself, else we fail to generate permutations with
3126 * the last integer last). The swap step can be optimized by
3127 * combining it with the insertion.
3128 *
3129 * We don't need to initialize conn->prng_state here, because that
3130 * already happened in pqConnectOptions2.
3131 */
3132 for (int i = 1; i < conn->naddr; i++)
3133 {
3134 int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
3135 AddrInfo temp = conn->addr[j];
3136
3137 conn->addr[j] = conn->addr[i];
3138 conn->addr[i] = temp;
3139 }
3140 }
3141
3142 reset_connection_state_machine = true;
3143 conn->try_next_host = false;
3144 }
3145
3146 /* Reset connection state machine? */
3147 if (reset_connection_state_machine)
3148 {
3149 /*
3150 * (Re) initialize our connection control variables for a set of
3151 * connection attempts to a single server address. These variables
3152 * must persist across individual connection attempts, but we must
3153 * reset them when we start to consider a new server.
3154 */
3156 conn->send_appname = true;
3160 reset_connection_state_machine = false;
3161 need_new_connection = true;
3162 }
3163
3164 /* Force a new connection (perhaps to the same server as before)? */
3165 if (need_new_connection)
3166 {
3167 /* Drop any existing connection */
3168 pqDropConnection(conn, true);
3169
3170 /* Reset all state obtained from old server */
3172
3173 /* Drop any PGresult we might have, too */
3178
3179 /* Reset conn->status to put the state machine in the right state */
3181
3182 need_new_connection = false;
3183 }
3184
3185 /*
3186 * Decide what to do next, if server rejects SSL or GSS negotiation, but
3187 * the connection is still valid. If there are no options left, error out
3188 * with 'msg'.
3189 */
3190#define ENCRYPTION_NEGOTIATION_FAILED(msg) \
3191 do { \
3192 switch (encryption_negotiation_failed(conn)) \
3193 { \
3194 case 0: \
3195 libpq_append_conn_error(conn, (msg)); \
3196 goto error_return; \
3197 case 1: \
3198 conn->status = CONNECTION_MADE; \
3199 return PGRES_POLLING_WRITING; \
3200 case 2: \
3201 need_new_connection = true; \
3202 goto keep_going; \
3203 } \
3204 } while(0);
3205
3206 /*
3207 * Decide what to do next, if connection fails. If there are no options
3208 * left, return with an error. The error message has already been written
3209 * to the connection's error buffer.
3210 */
3211#define CONNECTION_FAILED() \
3212 do { \
3213 if (connection_failed(conn)) \
3214 { \
3215 need_new_connection = true; \
3216 goto keep_going; \
3217 } \
3218 else \
3219 goto error_return; \
3220 } while(0);
3221
3222 /* Now try to advance the state machine for this connection */
3223 switch (conn->status)
3224 {
3225 case CONNECTION_NEEDED:
3226 {
3227 /*
3228 * Try to initiate a connection to one of the addresses
3229 * returned by pg_getaddrinfo_all(). conn->whichaddr is the
3230 * next one to try.
3231 *
3232 * The extra level of braces here is historical. It's not
3233 * worth reindenting this whole switch case to remove 'em.
3234 */
3235 {
3236 char host_addr[NI_MAXHOST];
3237 int sock_type;
3238 AddrInfo *addr_cur;
3239
3240 /*
3241 * Advance to next possible host, if we've tried all of
3242 * the addresses for the current host.
3243 */
3244 if (conn->whichaddr == conn->naddr)
3245 {
3246 conn->try_next_host = true;
3247 goto keep_going;
3248 }
3249 addr_cur = &conn->addr[conn->whichaddr];
3250
3251 /* Remember current address for possible use later */
3252 memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
3253
3254#ifdef ENABLE_GSS
3255
3256 /*
3257 * Before establishing the connection, check if it's
3258 * doomed to fail because gssencmode='require' but GSSAPI
3259 * is not available.
3260 */
3261 if (conn->gssencmode[0] == 'r')
3262 {
3263 if (conn->raddr.addr.ss_family == AF_UNIX)
3264 {
3266 "GSSAPI encryption required but it is not supported over a local socket");
3267 goto error_return;
3268 }
3269 if (conn->gcred == GSS_C_NO_CREDENTIAL)
3270 {
3271 if (!pg_GSS_have_cred_cache(&conn->gcred))
3272 {
3274 "GSSAPI encryption required but no credential cache");
3275 goto error_return;
3276 }
3277 }
3278 }
3279#endif
3280
3281 /*
3282 * Choose the encryption method to try first. Do this
3283 * before establishing the connection, so that if none of
3284 * the modes allowed by the connections options are
3285 * available, we can error out before establishing the
3286 * connection.
3287 */
3289 goto error_return;
3290
3291 /*
3292 * Set connip, too. Note we purposely ignore strdup
3293 * failure; not a big problem if it fails.
3294 */
3295 if (conn->connip != NULL)
3296 {
3297 free(conn->connip);
3298 conn->connip = NULL;
3299 }
3300 getHostaddr(conn, host_addr, NI_MAXHOST);
3301 if (host_addr[0])
3302 conn->connip = strdup(host_addr);
3303
3304 /* Try to create the socket */
3305 sock_type = SOCK_STREAM;
3306#ifdef SOCK_CLOEXEC
3307
3308 /*
3309 * Atomically mark close-on-exec, if possible on this
3310 * platform, so that there isn't a window where a
3311 * subprogram executed by another thread inherits the
3312 * socket. See fallback code below.
3313 */
3314 sock_type |= SOCK_CLOEXEC;
3315#endif
3316#ifdef SOCK_NONBLOCK
3317
3318 /*
3319 * We might as well skip a system call for nonblocking
3320 * mode too, if we can.
3321 */
3322 sock_type |= SOCK_NONBLOCK;
3323#endif
3324 conn->sock = socket(addr_cur->family, sock_type, 0);
3325 if (conn->sock == PGINVALID_SOCKET)
3326 {
3327 int errorno = SOCK_ERRNO;
3328
3329 /*
3330 * Silently ignore socket() failure if we have more
3331 * addresses to try; this reduces useless chatter in
3332 * cases where the address list includes both IPv4 and
3333 * IPv6 but kernel only accepts one family.
3334 */
3335 if (conn->whichaddr < conn->naddr ||
3336 conn->whichhost + 1 < conn->nconnhost)
3337 {
3338 conn->try_next_addr = true;
3339 goto keep_going;
3340 }
3341 emitHostIdentityInfo(conn, host_addr);
3342 libpq_append_conn_error(conn, "could not create socket: %s",
3343 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
3344 goto error_return;
3345 }
3346
3347 /*
3348 * Once we've identified a target address, all errors
3349 * except the preceding socket()-failure case should be
3350 * prefixed with host-identity information. (If the
3351 * connection succeeds, the contents of conn->errorMessage
3352 * won't matter, so this is harmless.)
3353 */
3354 emitHostIdentityInfo(conn, host_addr);
3355
3356 /*
3357 * Select socket options: no delay of outgoing data for
3358 * TCP sockets, nonblock mode, close-on-exec. Try the
3359 * next address if any of this fails.
3360 */
3361 if (addr_cur->family != AF_UNIX)
3362 {
3363 if (!connectNoDelay(conn))
3364 {
3365 /* error message already created */
3366 conn->try_next_addr = true;
3367 goto keep_going;
3368 }
3369 }
3370#ifndef SOCK_NONBLOCK
3371 if (!pg_set_noblock(conn->sock))
3372 {
3373 libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
3374 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3375 conn->try_next_addr = true;
3376 goto keep_going;
3377 }
3378#endif
3379
3380#ifndef SOCK_CLOEXEC
3381#ifdef F_SETFD
3382 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
3383 {
3384 libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
3385 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3386 conn->try_next_addr = true;
3387 goto keep_going;
3388 }
3389#endif /* F_SETFD */
3390#endif
3391
3392 if (addr_cur->family != AF_UNIX)
3393 {
3394#ifndef WIN32
3395 int on = 1;
3396#endif
3397 int usekeepalives = useKeepalives(conn);
3398 int err = 0;
3399
3400 if (usekeepalives < 0)
3401 {
3402 /* error is already reported */
3403 err = 1;
3404 }
3405 else if (usekeepalives == 0)
3406 {
3407 /* Do nothing */
3408 }
3409#ifndef WIN32
3410 else if (setsockopt(conn->sock,
3411 SOL_SOCKET, SO_KEEPALIVE,
3412 (char *) &on, sizeof(on)) < 0)
3413 {
3414 libpq_append_conn_error(conn, "%s(%s) failed: %s",
3415 "setsockopt",
3416 "SO_KEEPALIVE",
3417 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3418 err = 1;
3419 }
3420 else if (!setKeepalivesIdle(conn)
3423 err = 1;
3424#else /* WIN32 */
3425#ifdef SIO_KEEPALIVE_VALS
3426 else if (!prepKeepalivesWin32(conn))
3427 err = 1;
3428#endif /* SIO_KEEPALIVE_VALS */
3429#endif /* WIN32 */
3430 else if (!setTCPUserTimeout(conn))
3431 err = 1;
3432
3433 if (err)
3434 {
3435 conn->try_next_addr = true;
3436 goto keep_going;
3437 }
3438 }
3439
3440 /*----------
3441 * We have three methods of blocking SIGPIPE during
3442 * send() calls to this socket:
3443 *
3444 * - setsockopt(sock, SO_NOSIGPIPE)
3445 * - send(sock, ..., MSG_NOSIGNAL)
3446 * - setting the signal mask to SIG_IGN during send()
3447 *
3448 * The third method requires three syscalls per send,
3449 * so we prefer either of the first two, but they are
3450 * less portable. The state is tracked in the following
3451 * members of PGconn:
3452 *
3453 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3454 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3455 *
3456 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3457 * and we're done. Otherwise, set sigpipe_flag so that
3458 * we will try MSG_NOSIGNAL on sends. If we get an error
3459 * with MSG_NOSIGNAL, we'll clear that flag and revert to
3460 * signal masking.
3461 *----------
3462 */
3463 conn->sigpipe_so = false;
3464#ifdef MSG_NOSIGNAL
3465 conn->sigpipe_flag = true;
3466#else
3467 conn->sigpipe_flag = false;
3468#endif /* MSG_NOSIGNAL */
3469
3470#ifdef SO_NOSIGPIPE
3471 optval = 1;
3472 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3473 (char *) &optval, sizeof(optval)) == 0)
3474 {
3475 conn->sigpipe_so = true;
3476 conn->sigpipe_flag = false;
3477 }
3478#endif /* SO_NOSIGPIPE */
3479
3480 /*
3481 * Start/make connection. This should not block, since we
3482 * are in nonblock mode. If it does, well, too bad.
3483 */
3484 if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3485 addr_cur->addr.salen) < 0)
3486 {
3487 if (SOCK_ERRNO == EINPROGRESS ||
3488#ifdef WIN32
3490#endif
3491 SOCK_ERRNO == EINTR)
3492 {
3493 /*
3494 * This is fine - we're in non-blocking mode, and
3495 * the connection is in progress. Tell caller to
3496 * wait for write-ready on socket.
3497 */
3499 return PGRES_POLLING_WRITING;
3500 }
3501 /* otherwise, trouble */
3502 }
3503 else
3504 {
3505 /*
3506 * Hm, we're connected already --- seems the "nonblock
3507 * connection" wasn't. Advance the state machine and
3508 * go do the next stuff.
3509 */
3511 goto keep_going;
3512 }
3513
3514 /*
3515 * This connection failed. Add the error report to
3516 * conn->errorMessage, then try the next address if any.
3517 */
3519 conn->try_next_addr = true;
3520 goto keep_going;
3521 }
3522 }
3523
3524 case CONNECTION_STARTED:
3525 {
3526 socklen_t optlen = sizeof(optval);
3527
3528 /*
3529 * Write ready, since we've made it here, so the connection
3530 * has been made ... or has failed.
3531 */
3532
3533 /*
3534 * Now check (using getsockopt) that there is not an error
3535 * state waiting for us on the socket.
3536 */
3537
3538 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3539 (char *) &optval, &optlen) == -1)
3540 {
3541 libpq_append_conn_error(conn, "could not get socket error status: %s",
3542 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3543 goto error_return;
3544 }
3545 else if (optval != 0)
3546 {
3547 /*
3548 * When using a nonblocking connect, we will typically see
3549 * connect failures at this point, so provide a friendly
3550 * error message.
3551 */
3552 connectFailureMessage(conn, optval);
3553
3554 /*
3555 * Try the next address if any, just as in the case where
3556 * connect() returned failure immediately.
3557 */
3558 conn->try_next_addr = true;
3559 goto keep_going;
3560 }
3561
3562 /* Fill in the client address */
3563 conn->laddr.salen = sizeof(conn->laddr.addr);
3564 if (getsockname(conn->sock,
3565 (struct sockaddr *) &conn->laddr.addr,
3566 &conn->laddr.salen) < 0)
3567 {
3568 libpq_append_conn_error(conn, "could not get client address from socket: %s",
3569 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3570 goto error_return;
3571 }
3572
3573 /*
3574 * Implement requirepeer check, if requested and it's a
3575 * Unix-domain socket.
3576 */
3577 if (conn->requirepeer && conn->requirepeer[0] &&
3578 conn->raddr.addr.ss_family == AF_UNIX)
3579 {
3580#ifndef WIN32
3581 char *remote_username;
3582#endif
3583 uid_t uid;
3584 gid_t gid;
3585
3586 errno = 0;
3587 if (getpeereid(conn->sock, &uid, &gid) != 0)
3588 {
3589 /*
3590 * Provide special error message if getpeereid is a
3591 * stub
3592 */
3593 if (errno == ENOSYS)
3594 libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3595 else
3596 libpq_append_conn_error(conn, "could not get peer credentials: %s",
3597 strerror_r(errno, sebuf, sizeof(sebuf)));
3598 goto error_return;
3599 }
3600
3601#ifndef WIN32
3602 remote_username = pg_fe_getusername(uid,
3603 &conn->errorMessage);
3604 if (remote_username == NULL)
3605 goto error_return; /* message already logged */
3606
3607 if (strcmp(remote_username, conn->requirepeer) != 0)
3608 {
3609 libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3610 conn->requirepeer, remote_username);
3611 free(remote_username);
3612 goto error_return;
3613 }
3614 free(remote_username);
3615#else /* WIN32 */
3616 /* should have failed with ENOSYS above */
3617 Assert(false);
3618#endif /* WIN32 */
3619 }
3620
3621 /*
3622 * Make sure we can write before advancing to next step.
3623 */
3625 return PGRES_POLLING_WRITING;
3626 }
3627
3628 case CONNECTION_MADE:
3629 {
3630 char *startpacket;
3631 int packetlen;
3632
3633#ifdef ENABLE_GSS
3634
3635 /*
3636 * If GSSAPI encryption is enabled, send a packet to the
3637 * server asking for GSSAPI Encryption and proceed with GSSAPI
3638 * handshake. We will come back here after GSSAPI encryption
3639 * has been established, with conn->gctx set.
3640 */
3641 if (conn->current_enc_method == ENC_GSSAPI && !conn->gctx)
3642 {
3644
3645 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3646 {
3647 libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3648 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3649 goto error_return;
3650 }
3651
3652 /* Ok, wait for response */
3654 return PGRES_POLLING_READING;
3655 }
3656#endif
3657
3658#ifdef USE_SSL
3659
3660 /*
3661 * If SSL is enabled, start the SSL negotiation. We will come
3662 * back here after SSL encryption has been established, with
3663 * ssl_in_use set.
3664 */
3666 {
3667 /*
3668 * If traditional postgres SSL negotiation is used, send
3669 * the SSL request. In direct negotiation, jump straight
3670 * into the SSL handshake.
3671 */
3672 if (conn->sslnegotiation[0] == 'p')
3673 {
3674 ProtocolVersion pv;
3675
3676 /*
3677 * Send the SSL request packet.
3678 *
3679 * Theoretically, this could block, but it really
3680 * shouldn't since we only got here if the socket is
3681 * write-ready.
3682 */
3684 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3685 {
3686 libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3687 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3688 goto error_return;
3689 }
3690 /* Ok, wait for response */
3692 return PGRES_POLLING_READING;
3693 }
3694 else
3695 {
3696 Assert(conn->sslnegotiation[0] == 'd');
3698 return PGRES_POLLING_WRITING;
3699 }
3700 }
3701#endif /* USE_SSL */
3702
3703 /*
3704 * For cancel requests this is as far as we need to go in the
3705 * connection establishment. Now we can actually send our
3706 * cancellation request.
3707 */
3708 if (conn->cancelRequest)
3709 {
3711 {
3712 libpq_append_conn_error(conn, "could not send cancel packet: %s",
3713 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3714 goto error_return;
3715 }
3717 return PGRES_POLLING_READING;
3718 }
3719
3720 /*
3721 * We have now established encryption, or we are happy to
3722 * proceed without.
3723 */
3724
3725 /* Build the startup packet. */
3726 startpacket = pqBuildStartupPacket3(conn, &packetlen,
3728 if (!startpacket)
3729 {
3730 libpq_append_conn_error(conn, "out of memory");
3731 goto error_return;
3732 }
3733
3734 /*
3735 * Send the startup packet.
3736 *
3737 * Theoretically, this could block, but it really shouldn't
3738 * since we only got here if the socket is write-ready.
3739 */
3740 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3741 {
3742 libpq_append_conn_error(conn, "could not send startup packet: %s",
3743 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3744 free(startpacket);
3745 goto error_return;
3746 }
3747
3748 free(startpacket);
3749
3751 return PGRES_POLLING_READING;
3752 }
3753
3754 /*
3755 * Handle SSL negotiation: wait for postmaster messages and
3756 * respond as necessary.
3757 */
3759 {
3760#ifdef USE_SSL
3762
3763 /*
3764 * On first time through with traditional SSL negotiation, get
3765 * the postmaster's response to our SSLRequest packet. With
3766 * sslnegotiation='direct', go straight to initiating SSL.
3767 */
3768 if (!conn->ssl_in_use && conn->sslnegotiation[0] == 'p')
3769 {
3770 /*
3771 * We use pqReadData here since it has the logic to
3772 * distinguish no-data-yet from connection closure. Since
3773 * conn->ssl isn't set, a plain recv() will occur.
3774 */
3775 char SSLok;
3776 int rdresult;
3777
3778 rdresult = pqReadData(conn);
3779 if (rdresult < 0)
3780 {
3781 /* errorMessage is already filled in */
3782 goto error_return;
3783 }
3784 if (rdresult == 0)
3785 {
3786 /* caller failed to wait for data */
3787 return PGRES_POLLING_READING;
3788 }
3789 if (pqGetc(&SSLok, conn) < 0)
3790 {
3791 /* should not happen really */
3792 return PGRES_POLLING_READING;
3793 }
3794 if (SSLok == 'S')
3795 {
3796 if (conn->Pfdebug)
3797 pqTraceOutputCharResponse(conn, "SSLResponse",
3798 SSLok);
3799 /* mark byte consumed */
3801 }
3802 else if (SSLok == 'N')
3803 {
3804 if (conn->Pfdebug)
3805 pqTraceOutputCharResponse(conn, "SSLResponse",
3806 SSLok);
3807 /* mark byte consumed */
3809
3810 /*
3811 * The connection is still valid, so if it's OK to
3812 * continue without SSL, we can proceed using this
3813 * connection. Otherwise return with an error.
3814 */
3815 ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server does not support SSL, but SSL was required"));
3816 }
3817 else if (SSLok == 'E')
3818 {
3819 /*
3820 * Server failure of some sort, such as failure to
3821 * fork a backend process. Don't bother retrieving
3822 * the error message; we should not trust it as the
3823 * server has not been authenticated yet.
3824 */
3825 libpq_append_conn_error(conn, "server sent an error response during SSL exchange");
3826 goto error_return;
3827 }
3828 else
3829 {
3830 libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3831 SSLok);
3832 goto error_return;
3833 }
3834 }
3835
3836 /*
3837 * Begin or continue the SSL negotiation process.
3838 */
3839 pollres = pqsecure_open_client(conn);
3840 if (pollres == PGRES_POLLING_OK)
3841 {
3842 /*
3843 * At this point we should have no data already buffered.
3844 * If we do, it was received before we performed the SSL
3845 * handshake, so it wasn't encrypted and indeed may have
3846 * been injected by a man-in-the-middle.
3847 */
3848 if (conn->inCursor != conn->inEnd)
3849 {
3850 libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3851 goto error_return;
3852 }
3853
3854 /* SSL handshake done, ready to send startup packet */
3856 return PGRES_POLLING_WRITING;
3857 }
3858 if (pollres == PGRES_POLLING_FAILED)
3859 {
3860 /*
3861 * SSL handshake failed. We will retry with a plaintext
3862 * connection, if permitted by sslmode.
3863 */
3865 }
3866 /* Else, return POLLING_READING or POLLING_WRITING status */
3867 return pollres;
3868#else /* !USE_SSL */
3869 /* can't get here */
3870 goto error_return;
3871#endif /* USE_SSL */
3872 }
3873
3875 {
3876#ifdef ENABLE_GSS
3878
3879 /*
3880 * If we haven't yet, get the postmaster's response to our
3881 * negotiation packet
3882 */
3883 if (!conn->gctx)
3884 {
3885 char gss_ok;
3886 int rdresult = pqReadData(conn);
3887
3888 if (rdresult < 0)
3889 /* pqReadData fills in error message */
3890 goto error_return;
3891 else if (rdresult == 0)
3892 /* caller failed to wait for data */
3893 return PGRES_POLLING_READING;
3894 if (pqGetc(&gss_ok, conn) < 0)
3895 /* shouldn't happen... */
3896 return PGRES_POLLING_READING;
3897
3898 if (gss_ok == 'E')
3899 {
3900 /*
3901 * Server failure of some sort, possibly protocol
3902 * version support failure. Don't bother retrieving
3903 * the error message; we should not trust it anyway as
3904 * the server has not authenticated yet.
3905 *
3906 * Note that unlike on an error response to
3907 * SSLRequest, we allow falling back to SSL or
3908 * plaintext connection here. GSS support was
3909 * introduced in PostgreSQL version 12, so an error
3910 * response might mean that we are connecting to a
3911 * pre-v12 server.
3912 */
3913 libpq_append_conn_error(conn, "server sent an error response during GSS encryption exchange");
3915 }
3916
3917 /* mark byte consumed */
3919
3920 if (gss_ok == 'N')
3921 {
3922 if (conn->Pfdebug)
3923 pqTraceOutputCharResponse(conn, "GSSENCResponse",
3924 gss_ok);
3925
3926 /*
3927 * The connection is still valid, so if it's OK to
3928 * continue without GSS, we can proceed using this
3929 * connection. Otherwise return with an error.
3930 */
3931 ENCRYPTION_NEGOTIATION_FAILED(libpq_gettext("server doesn't support GSSAPI encryption, but it was required"));
3932 }
3933 else if (gss_ok != 'G')
3934 {
3935 libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3936 gss_ok);
3937 goto error_return;
3938 }
3939
3940 if (conn->Pfdebug)
3941 pqTraceOutputCharResponse(conn, "GSSENCResponse",
3942 gss_ok);
3943 }
3944
3945 /* Begin or continue GSSAPI negotiation */
3946 pollres = pqsecure_open_gss(conn);
3947 if (pollres == PGRES_POLLING_OK)
3948 {
3949 /*
3950 * At this point we should have no data already buffered.
3951 * If we do, it was received before we performed the GSS
3952 * handshake, so it wasn't encrypted and indeed may have
3953 * been injected by a man-in-the-middle.
3954 */
3955 if (conn->inCursor != conn->inEnd)
3956 {
3957 libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3958 goto error_return;
3959 }
3960
3961 /* All set for startup packet */
3963 return PGRES_POLLING_WRITING;
3964 }
3965 else if (pollres == PGRES_POLLING_FAILED)
3966 {
3967 /*
3968 * GSS handshake failed. We will retry with an SSL or
3969 * plaintext connection, if permitted by the options.
3970 */
3972 }
3973 /* Else, return POLLING_READING or POLLING_WRITING status */
3974 return pollres;
3975#else /* !ENABLE_GSS */
3976 /* unreachable */
3977 goto error_return;
3978#endif /* ENABLE_GSS */
3979 }
3980
3981 /*
3982 * Handle authentication exchange: wait for postmaster messages
3983 * and respond as necessary.
3984 */
3986 {
3987 char beresp;
3988 int msgLength;
3989 int avail;
3990 AuthRequest areq;
3991 int res;
3992 bool async;
3993
3994 /*
3995 * Scan the message from current point (note that if we find
3996 * the message is incomplete, we will return without advancing
3997 * inStart, and resume here next time).
3998 */
4000
4001 /* Read type byte */
4002 if (pqGetc(&beresp, conn))
4003 {
4004 /* We'll come back when there is more data */
4005 return PGRES_POLLING_READING;
4006 }
4007
4008 /*
4009 * Validate message type: we expect only an authentication
4010 * request, NegotiateProtocolVersion, or an error here.
4011 * Anything else probably means it's not Postgres on the other
4012 * end at all.
4013 */
4014 if (beresp != PqMsg_AuthenticationRequest &&
4015 beresp != PqMsg_ErrorResponse &&
4017 {
4018 libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
4019 beresp);
4020 goto error_return;
4021 }
4022
4023 /* Read message length word */
4024 if (pqGetInt(&msgLength, 4, conn))
4025 {
4026 /* We'll come back when there is more data */
4027 return PGRES_POLLING_READING;
4028 }
4029
4030 /*
4031 * Try to validate message length before using it.
4032 *
4033 * Authentication requests can't be very large, although GSS
4034 * auth requests may not be that small. Same for
4035 * NegotiateProtocolVersion.
4036 *
4037 * Errors can be a little larger, but not huge. If we see a
4038 * large apparent length in an error, it means we're really
4039 * talking to a pre-3.0-protocol server; cope. (Before
4040 * version 14, the server also used the old protocol for
4041 * errors that happened before processing the startup packet.)
4042 */
4043 if (beresp == PqMsg_AuthenticationRequest &&
4044 (msgLength < 8 || msgLength > 2000))
4045 {
4046 libpq_append_conn_error(conn, "received invalid authentication request");
4047 goto error_return;
4048 }
4049 if (beresp == PqMsg_NegotiateProtocolVersion &&
4050 (msgLength < 8 || msgLength > 2000))
4051 {
4052 libpq_append_conn_error(conn, "received invalid protocol negotiation message");
4053 goto error_return;
4054 }
4055
4056#define MAX_ERRLEN 30000
4057 if (beresp == PqMsg_ErrorResponse &&
4058 (msgLength < 8 || msgLength > MAX_ERRLEN))
4059 {
4060 /* Handle error from a pre-3.0 server */
4061 conn->inCursor = conn->inStart + 1; /* reread data */
4063 {
4064 /*
4065 * We may not have authenticated the server yet, so
4066 * don't let the buffer grow forever.
4067 */
4068 avail = conn->inEnd - conn->inCursor;
4069 if (avail > MAX_ERRLEN)
4070 {
4071 libpq_append_conn_error(conn, "received invalid error message");
4072 goto error_return;
4073 }
4074
4075 /* We'll come back when there is more data */
4076 return PGRES_POLLING_READING;
4077 }
4078 /* OK, we read the message; mark data consumed */
4080
4081 /*
4082 * Before 7.2, the postmaster didn't always end its
4083 * messages with a newline, so add one if needed to
4084 * conform to libpq conventions.
4085 */
4086 if (conn->errorMessage.len == 0 ||
4087 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
4088 {
4090 }
4091
4092 goto error_return;
4093 }
4094#undef MAX_ERRLEN
4095
4096 /*
4097 * Can't process if message body isn't all here yet.
4098 *
4099 * After this check passes, any further EOF during parsing
4100 * implies that the server sent a bad/truncated message.
4101 * Reading more bytes won't help in that case, so don't return
4102 * PGRES_POLLING_READING after this point.
4103 */
4104 msgLength -= 4;
4105 avail = conn->inEnd - conn->inCursor;
4106 if (avail < msgLength)
4107 {
4108 /*
4109 * Before returning, try to enlarge the input buffer if
4110 * needed to hold the whole message; see notes in
4111 * pqParseInput3.
4112 */
4113 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
4114 conn))
4115 goto error_return;
4116 /* We'll come back when there is more data */
4117 return PGRES_POLLING_READING;
4118 }
4119
4120 /* Handle errors. */
4121 if (beresp == PqMsg_ErrorResponse)
4122 {
4123 if (pqGetErrorNotice3(conn, true))
4124 {
4125 libpq_append_conn_error(conn, "received invalid error message");
4126 goto error_return;
4127 }
4128 /* OK, we read the message; mark data consumed */
4130
4131 /*
4132 * If error is "cannot connect now", try the next host if
4133 * any (but we don't want to consider additional addresses
4134 * for this host, nor is there much point in changing SSL
4135 * or GSS mode). This is helpful when dealing with
4136 * standby servers that might not be in hot-standby state.
4137 */
4138 if (strcmp(conn->last_sqlstate,
4140 {
4141 conn->try_next_host = true;
4142 goto keep_going;
4143 }
4144
4145 /* Check to see if we should mention pgpassfile */
4147
4149 }
4150 /* Handle NegotiateProtocolVersion */
4151 else if (beresp == PqMsg_NegotiateProtocolVersion)
4152 {
4154 {
4155 libpq_append_conn_error(conn, "received duplicate protocol negotiation message");
4156 goto error_return;
4157 }
4159 {
4160 /* pqGetNegotiateProtocolVersion3 set error already */
4161 goto error_return;
4162 }
4163 conn->pversion_negotiated = true;
4164
4165 /* OK, we read the message; mark data consumed */
4167
4168 goto keep_going;
4169 }
4170
4171 /* It is an authentication request. */
4172 conn->auth_req_received = true;
4173
4174 /* Get the type of request. */
4175 if (pqGetInt((int *) &areq, 4, conn))
4176 {
4177 /* can't happen because we checked the length already */
4178 libpq_append_conn_error(conn, "received invalid authentication request");
4179 goto error_return;
4180 }
4181 msgLength -= 4;
4182
4183 /*
4184 * Process the rest of the authentication request message, and
4185 * respond to it if necessary.
4186 *
4187 * Note that conn->pghost must be non-NULL if we are going to
4188 * avoid the Kerberos code doing a hostname look-up.
4189 */
4190 res = pg_fe_sendauth(areq, msgLength, conn, &async);
4191
4192 if (async && (res == STATUS_OK))
4193 {
4194 /*
4195 * We'll come back later once we're ready to respond.
4196 * Don't consume the request yet.
4197 */
4199 goto keep_going;
4200 }
4201
4202 /*
4203 * OK, we have processed the message; mark data consumed. We
4204 * don't call pqParseDone here because we already traced this
4205 * message inside pg_fe_sendauth.
4206 */
4208
4209 if (res != STATUS_OK)
4210 {
4211 /*
4212 * OAuth connections may perform two-step discovery, where
4213 * the first connection is a dummy.
4214 */
4216 {
4217 need_new_connection = true;
4218 goto keep_going;
4219 }
4220
4221 goto error_return;
4222 }
4223
4224 /*
4225 * Just make sure that any data sent by pg_fe_sendauth is
4226 * flushed out. Although this theoretically could block, it
4227 * really shouldn't since we don't send large auth responses.
4228 */
4229 if (pqFlush(conn))
4230 goto error_return;
4231
4232 if (areq == AUTH_REQ_OK)
4233 {
4234 /* We are done with authentication exchange */
4236
4237 /*
4238 * Set asyncStatus so that PQgetResult will think that
4239 * what comes back next is the result of a query. See
4240 * below.
4241 */
4243 }
4244
4245 /* Look to see if we have more data yet. */
4246 goto keep_going;
4247 }
4248
4250 {
4252
4254 {
4255 /* programmer error; should not happen */
4257 "internal error: async authentication has no handler");
4258 goto error_return;
4259 }
4260
4261 /* Drive some external authentication work. */
4262 status = conn->async_auth(conn);
4263
4264 if (status == PGRES_POLLING_FAILED)
4265 goto error_return;
4266
4267 if (status == PGRES_POLLING_OK)
4268 {
4269 /* Done. Tear down the async implementation. */
4271 conn->cleanup_async_auth = NULL;
4272
4273 /*
4274 * Cleanup must unset altsock, both as an indication that
4275 * it's been released, and to stop pqSocketCheck from
4276 * looking at the wrong socket after async auth is done.
4277 */
4279 {
4280 Assert(false);
4282 "internal error: async cleanup did not release polling socket");
4283 goto error_return;
4284 }
4285
4286 /*
4287 * Reenter the authentication exchange with the server. We
4288 * didn't consume the message that started external
4289 * authentication, so it'll be reprocessed as if we just
4290 * received it.
4291 */
4293
4294 goto keep_going;
4295 }
4296
4297 /*
4298 * Caller needs to poll some more. conn->async_auth() should
4299 * have assigned an altsock to poll on.
4300 */
4302 {
4303 Assert(false);
4305 "internal error: async authentication did not set a socket for polling");
4306 goto error_return;
4307 }
4308
4309 return status;
4310 }
4311
4312 case CONNECTION_AUTH_OK:
4313 {
4314 /*
4315 * Now we expect to hear from the backend. A ReadyForQuery
4316 * message indicates that startup is successful, but we might
4317 * also get an Error message indicating failure. (Notice
4318 * messages indicating nonfatal warnings are also allowed by
4319 * the protocol, as are ParameterStatus and BackendKeyData
4320 * messages.) Easiest way to handle this is to let
4321 * PQgetResult() read the messages. We just have to fake it
4322 * out about the state of the connection, by setting
4323 * asyncStatus = PGASYNC_BUSY (done above).
4324 */
4325
4326 if (PQisBusy(conn))
4327 return PGRES_POLLING_READING;
4328
4329 res = PQgetResult(conn);
4330
4331 /*
4332 * NULL return indicating we have gone to IDLE state is
4333 * expected
4334 */
4335 if (res)
4336 {
4337 if (res->resultStatus != PGRES_FATAL_ERROR)
4338 libpq_append_conn_error(conn, "unexpected message from server during startup");
4339 else if (conn->send_appname &&
4340 (conn->appname || conn->fbappname))
4341 {
4342 /*
4343 * If we tried to send application_name, check to see
4344 * if the error is about that --- pre-9.0 servers will
4345 * reject it at this stage of the process. If so,
4346 * close the connection and retry without sending
4347 * application_name. We could possibly get a false
4348 * SQLSTATE match here and retry uselessly, but there
4349 * seems no great harm in that; we'll just get the
4350 * same error again if it's unrelated.
4351 */
4352 const char *sqlstate;
4353
4354 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
4355 if (sqlstate &&
4356 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
4357 {
4358 PQclear(res);
4359 conn->send_appname = false;
4360 need_new_connection = true;
4361 goto keep_going;
4362 }
4363 }
4364
4365 /*
4366 * if the resultStatus is FATAL, then conn->errorMessage
4367 * already has a copy of the error; needn't copy it back.
4368 * But add a newline if it's not there already, since
4369 * postmaster error messages may not have one.
4370 */
4371 if (conn->errorMessage.len <= 0 ||
4372 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
4374 PQclear(res);
4375 goto error_return;
4376 }
4377
4378 /* Almost there now ... */
4380 goto keep_going;
4381 }
4382
4384 {
4385 /*
4386 * If a read-write, read-only, primary, or standby connection
4387 * is required, see if we have one.
4388 */
4391 {
4392 bool read_only_server;
4393
4394 /*
4395 * If the server didn't report
4396 * "default_transaction_read_only" or "in_hot_standby" at
4397 * startup, we must determine its state by sending the
4398 * query "SHOW transaction_read_only". This GUC exists in
4399 * all server versions that support 3.0 protocol.
4400 */
4403 {
4404 /*
4405 * We use PQsendQueryContinue so that
4406 * conn->errorMessage does not get cleared. We need
4407 * to preserve any error messages related to previous
4408 * hosts we have tried and failed to connect to.
4409 */
4412 "SHOW transaction_read_only"))
4413 goto error_return;
4414 /* We'll return to this state when we have the answer */
4416 return PGRES_POLLING_READING;
4417 }
4418
4419 /* OK, we can make the test */
4420 read_only_server =
4423
4425 read_only_server : !read_only_server)
4426 {
4427 /* Wrong server state, reject and try the next host */
4429 libpq_append_conn_error(conn, "session is read-only");
4430 else
4431 libpq_append_conn_error(conn, "session is not read-only");
4432
4433 /* Close connection politely. */
4436
4437 /*
4438 * Try next host if any, but we don't want to consider
4439 * additional addresses for this host.
4440 */
4441 conn->try_next_host = true;
4442 goto keep_going;
4443 }
4444 }
4448 {
4449 /*
4450 * If the server didn't report "in_hot_standby" at
4451 * startup, we must determine its state by sending the
4452 * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
4453 * before 9.0 don't have that function, but by the same
4454 * token they don't have any standby mode, so we may just
4455 * assume the result.
4456 */
4457 if (conn->sversion < 90000)
4459
4461 {
4462 /*
4463 * We use PQsendQueryContinue so that
4464 * conn->errorMessage does not get cleared. We need
4465 * to preserve any error messages related to previous
4466 * hosts we have tried and failed to connect to.
4467 */
4470 "SELECT pg_catalog.pg_is_in_recovery()"))
4471 goto error_return;
4472 /* We'll return to this state when we have the answer */
4474 return PGRES_POLLING_READING;
4475 }
4476
4477 /* OK, we can make the test */
4481 {
4482 /* Wrong server state, reject and try the next host */
4484 libpq_append_conn_error(conn, "server is in hot standby mode");
4485 else
4486 libpq_append_conn_error(conn, "server is not in hot standby mode");
4487
4488 /* Close connection politely. */
4491
4492 /*
4493 * Try next host if any, but we don't want to consider
4494 * additional addresses for this host.
4495 */
4496 conn->try_next_host = true;
4497 goto keep_going;
4498 }
4499 }
4500
4501 /* Don't hold onto any OAuth tokens longer than necessary. */
4503
4504 /*
4505 * For non cancel requests we can release the address list
4506 * now. For cancel requests we never actually resolve
4507 * addresses and instead the addrinfo exists for the lifetime
4508 * of the connection.
4509 */
4510 if (!conn->cancelRequest)
4512
4513 /*
4514 * Contents of conn->errorMessage are no longer interesting
4515 * (and it seems some clients expect it to be empty after a
4516 * successful connection).
4517 */
4519
4520 /* We are open for business! */
4522 return PGRES_POLLING_OK;
4523 }
4524
4525 case CONNECTION_CONSUME:
4526 {
4527 /*
4528 * This state just makes sure the connection is idle after
4529 * we've obtained the result of a SHOW or SELECT query. Once
4530 * we're clear, return to CONNECTION_CHECK_TARGET state to
4531 * decide what to do next. We must transiently set status =
4532 * CONNECTION_OK in order to use the result-consuming
4533 * subroutines.
4534 */
4536 if (!PQconsumeInput(conn))
4537 goto error_return;
4538
4539 if (PQisBusy(conn))
4540 {
4542 return PGRES_POLLING_READING;
4543 }
4544
4545 /* Call PQgetResult() again until we get a NULL result */
4546 res = PQgetResult(conn);
4547 if (res != NULL)
4548 {
4549 PQclear(res);
4551 return PGRES_POLLING_READING;
4552 }
4553
4555 goto keep_going;
4556 }
4557
4559 {
4560 /*
4561 * Waiting for result of "SHOW transaction_read_only". We
4562 * must transiently set status = CONNECTION_OK in order to use
4563 * the result-consuming subroutines.
4564 */
4566 if (!PQconsumeInput(conn))
4567 goto error_return;
4568
4569 if (PQisBusy(conn))
4570 {
4572 return PGRES_POLLING_READING;
4573 }
4574
4575 res = PQgetResult(conn);
4576 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4577 PQntuples(res) == 1)
4578 {
4579 char *val = PQgetvalue(res, 0, 0);
4580
4581 /*
4582 * "transaction_read_only = on" proves that at least one
4583 * of default_transaction_read_only and in_hot_standby is
4584 * on, but we don't actually know which. We don't care
4585 * though for the purpose of identifying a read-only
4586 * session, so satisfy the CONNECTION_CHECK_TARGET code by
4587 * claiming they are both on. On the other hand, if it's
4588 * a read-write session, they are certainly both off.
4589 */
4590 if (strncmp(val, "on", 2) == 0)
4591 {
4594 }
4595 else
4596 {
4599 }
4600 PQclear(res);
4601
4602 /* Finish reading messages before continuing */
4604 goto keep_going;
4605 }
4606
4607 /* Something went wrong with "SHOW transaction_read_only". */
4608 PQclear(res);
4609
4610 /* Append error report to conn->errorMessage. */
4611 libpq_append_conn_error(conn, "\"%s\" failed",
4612 "SHOW transaction_read_only");
4613
4614 /* Close connection politely. */
4617
4618 /* Try next host. */
4619 conn->try_next_host = true;
4620 goto keep_going;
4621 }
4622
4624 {
4625 /*
4626 * Waiting for result of "SELECT pg_is_in_recovery()". We
4627 * must transiently set status = CONNECTION_OK in order to use
4628 * the result-consuming subroutines.
4629 */
4631 if (!PQconsumeInput(conn))
4632 goto error_return;
4633
4634 if (PQisBusy(conn))
4635 {
4637 return PGRES_POLLING_READING;
4638 }
4639
4640 res = PQgetResult(conn);
4641 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4642 PQntuples(res) == 1)
4643 {
4644 char *val = PQgetvalue(res, 0, 0);
4645
4646 if (strncmp(val, "t", 1) == 0)
4648 else
4650 PQclear(res);
4651
4652 /* Finish reading messages before continuing */
4654 goto keep_going;
4655 }
4656
4657 /* Something went wrong with "SELECT pg_is_in_recovery()". */
4658 PQclear(res);
4659
4660 /* Append error report to conn->errorMessage. */
4661 libpq_append_conn_error(conn, "\"%s\" failed",
4662 "SELECT pg_is_in_recovery()");
4663
4664 /* Close connection politely. */
4667
4668 /* Try next host. */
4669 conn->try_next_host = true;
4670 goto keep_going;
4671 }
4672
4673 default:
4675 "invalid connection state %d, probably indicative of memory corruption",
4676 conn->status);
4677 goto error_return;
4678 }
4679
4680 /* Unreachable */
4681
4682error_return:
4683
4684 /*
4685 * We used to close the socket at this point, but that makes it awkward
4686 * for those above us if they wish to remove this socket from their own
4687 * records (an fd_set for example). We'll just have this socket closed
4688 * when PQfinish is called (which is compulsory even after an error, since
4689 * the connection structure must be freed).
4690 */
4692 return PGRES_POLLING_FAILED;
4693}
4694
4695/*
4696 * Initialize the state machine for negotiating encryption
4697 */
4698static bool
4700{
4701 if (conn->raddr.addr.ss_family == AF_UNIX)
4702 {
4703 /* Don't request SSL or GSSAPI over Unix sockets */
4705
4706 /*
4707 * XXX: we probably should not do this. sslmode=require works
4708 * differently
4709 */
4710 if (conn->gssencmode[0] == 'r')
4711 {
4713 "GSSAPI encryption required but it is not supported over a local socket");
4716 return false;
4717 }
4718
4721 return true;
4722 }
4723
4724 /* initialize based on sslmode and gssencmode */
4726
4727#ifdef USE_SSL
4728 /* sslmode anything but 'disable', and GSSAPI not required */
4729 if (conn->sslmode[0] != 'd' && conn->gssencmode[0] != 'r')
4730 {
4732 }
4733#endif
4734
4735#ifdef ENABLE_GSS
4736 if (conn->gssencmode[0] != 'd')
4738#endif
4739
4740 if ((conn->sslmode[0] == 'd' || conn->sslmode[0] == 'p' || conn->sslmode[0] == 'a') &&
4741 (conn->gssencmode[0] == 'd' || conn->gssencmode[0] == 'p'))
4742 {
4744 }
4745
4746 return select_next_encryption_method(conn, false);
4747}
4748
4749/*
4750 * Out-of-line portion of the ENCRYPTION_NEGOTIATION_FAILED() macro in the
4751 * PQconnectPoll state machine.
4752 *
4753 * Return value:
4754 * 0: connection failed and we are out of encryption methods to try. return an error
4755 * 1: Retry with next connection method. The TCP connection is still valid and in
4756 * known state, so we can proceed with the negotiating next method without
4757 * reconnecting.
4758 * 2: Disconnect, and retry with next connection method.
4759 *
4760 * conn->current_enc_method is updated to the next method to try.
4761 */
4762#if defined(USE_SSL) || defined(ENABLE_GSS)
4763static int
4764encryption_negotiation_failed(PGconn *conn)
4765{
4768
4770 {
4771 /* An existing connection cannot be reused for direct SSL */
4772 if (conn->current_enc_method == ENC_SSL && conn->sslnegotiation[0] == 'd')
4773 return 2;
4774 else
4775 return 1;
4776 }
4777 else
4778 return 0;
4779}
4780#endif
4781
4782/*
4783 * Out-of-line portion of the CONNECTION_FAILED() macro
4784 *
4785 * Returns true, if we should reconnect and retry with a different encryption
4786 * method. conn->current_enc_method is updated to the next method to try.
4787 */
4788static bool
4790{
4793
4794 return select_next_encryption_method(conn, false);
4795}
4796
4797/*
4798 * Choose the next encryption method to try. If this is a retry,
4799 * conn->failed_enc_methods has already been updated. The function sets
4800 * conn->current_enc_method to the next method to try. Returns false if no
4801 * encryption methods remain.
4802 */
4803static bool
4804select_next_encryption_method(PGconn *conn, bool have_valid_connection)
4805{
4806 int remaining_methods;
4807
4808#define SELECT_NEXT_METHOD(method) \
4809 do { \
4810 if ((remaining_methods & method) != 0) \
4811 { \
4812 conn->current_enc_method = method; \
4813 return true; \
4814 } \
4815 } while (false)
4816
4817 remaining_methods = conn->allowed_enc_methods & ~conn->failed_enc_methods;
4818
4819 /*
4820 * Try GSSAPI before SSL
4821 */
4822#ifdef ENABLE_GSS
4823 if ((remaining_methods & ENC_GSSAPI) != 0)
4824 {
4825 /*
4826 * If GSSAPI encryption is enabled, then call pg_GSS_have_cred_cache()
4827 * which will return true if we can acquire credentials (and give us a
4828 * handle to use in conn->gcred), and then send a packet to the server
4829 * asking for GSSAPI Encryption (and skip past SSL negotiation and
4830 * regular startup below).
4831 */
4832 if (!conn->gctx)
4833 {
4834 if (!pg_GSS_have_cred_cache(&conn->gcred))
4835 {
4836 conn->allowed_enc_methods &= ~ENC_GSSAPI;
4837 remaining_methods &= ~ENC_GSSAPI;
4838
4839 if (conn->gssencmode[0] == 'r')
4840 {
4842 "GSSAPI encryption required but no credential cache");
4843 }
4844 }
4845 }
4846 }
4847
4849#endif
4850
4851 /*
4852 * The order between SSL encryption and plaintext depends on sslmode. With
4853 * sslmode=allow, try plaintext connection before SSL. With
4854 * sslmode=prefer, it's the other way round. With other modes, we only try
4855 * plaintext or SSL connections so the order they're listed here doesn't
4856 * matter.
4857 */
4858 if (conn->sslmode[0] == 'a')
4860
4862
4863 if (conn->sslmode[0] != 'a')
4865
4866 /* No more options */
4868 return false;
4869#undef SELECT_NEXT_METHOD
4870}
4871
4872/*
4873 * internal_ping
4874 * Determine if a server is running and if we can connect to it.
4875 *
4876 * The argument is a connection that's been started, but not completed.
4877 */
4878static PGPing
4880{
4881 /* Say "no attempt" if we never got to PQconnectPoll */
4882 if (!conn || !conn->options_valid)
4883 return PQPING_NO_ATTEMPT;
4884
4885 /* Attempt to complete the connection */
4886 if (conn->status != CONNECTION_BAD)
4887 (void) pqConnectDBComplete(conn);
4888
4889 /* Definitely OK if we succeeded */
4890 if (conn->status != CONNECTION_BAD)
4891 return PQPING_OK;
4892
4893 /*
4894 * Here begins the interesting part of "ping": determine the cause of the
4895 * failure in sufficient detail to decide what to return. We do not want
4896 * to report that the server is not up just because we didn't have a valid
4897 * password, for example. In fact, any sort of authentication request
4898 * implies the server is up. (We need this check since the libpq side of
4899 * things might have pulled the plug on the connection before getting an
4900 * error as such from the postmaster.)
4901 */
4903 return PQPING_OK;
4904
4905 /*
4906 * If we failed to get any ERROR response from the postmaster, report
4907 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
4908 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
4909 * out of support. Another corner case where the server could return a
4910 * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
4911 * isn't totally unreasonable for that anyway. We expect that every other
4912 * failure case in a modern server will produce a report with a SQLSTATE.
4913 *
4914 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
4915 * client-side errors, we should either not store those into
4916 * last_sqlstate, or add an extra flag so we can tell client-side errors
4917 * apart from server-side ones.
4918 */
4919 if (strlen(conn->last_sqlstate) != 5)
4920 return PQPING_NO_RESPONSE;
4921
4922 /*
4923 * Report PQPING_REJECT if server says it's not accepting connections.
4924 */
4926 return PQPING_REJECT;
4927
4928 /*
4929 * Any other SQLSTATE can be taken to indicate that the server is up.
4930 * Presumably it didn't like our username, password, or database name; or
4931 * perhaps it had some transient failure, but that should not be taken as
4932 * meaning "it's down".
4933 */
4934 return PQPING_OK;
4935}
4936
4937
4938/*
4939 * pqMakeEmptyPGconn
4940 * - create a PGconn data structure with (as yet) no interesting data
4941 */
4942PGconn *
4944{
4945 PGconn *conn;
4946
4947#ifdef WIN32
4948
4949 /*
4950 * Make sure socket support is up and running in this process.
4951 *
4952 * Note: the Windows documentation says that we should eventually do a
4953 * matching WSACleanup() call, but experience suggests that that is at
4954 * least as likely to cause problems as fix them. So we don't.
4955 */
4956 static bool wsastartup_done = false;
4957
4958 if (!wsastartup_done)
4959 {
4960 WSADATA wsaData;
4961
4962 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4963 return NULL;
4964 wsastartup_done = true;
4965 }
4966
4967 /* Forget any earlier error */
4968 WSASetLastError(0);
4969#endif /* WIN32 */
4970
4971 conn = (PGconn *) malloc(sizeof(PGconn));
4972 if (conn == NULL)
4973 return conn;
4974
4975 /* Zero all pointers and booleans */
4976 MemSet(conn, 0, sizeof(PGconn));
4977
4978 /* install default notice hooks */
4981
4986 conn->options_valid = false;
4987 conn->nonblocking = false;
4989 conn->std_strings = false; /* unless server says differently */
4997 conn->Pfdebug = NULL;
4998
4999 /*
5000 * We try to send at least 8K at a time, which is the usual size of pipe
5001 * buffers on Unix systems. That way, when we are sending a large amount
5002 * of data, we avoid incurring extra kernel context swaps for partial
5003 * bufferloads. The output buffer is initially made 16K in size, and we
5004 * try to dump it after accumulating 8K.
5005 *
5006 * With the same goal of minimizing context swaps, the input buffer will
5007 * be enlarged anytime it has less than 8K free, so we initially allocate
5008 * twice that.
5009 */
5010 conn->inBufSize = 16 * 1024;
5011 conn->inBuffer = (char *) malloc(conn->inBufSize);
5012 conn->outBufSize = 16 * 1024;
5013 conn->outBuffer = (char *) malloc(conn->outBufSize);
5014 conn->rowBufLen = 32;
5018
5019 if (conn->inBuffer == NULL ||
5020 conn->outBuffer == NULL ||
5021 conn->rowBuf == NULL ||
5024 {
5025 /* out of memory already :-( */
5027 conn = NULL;
5028 }
5029
5030 return conn;
5031}
5032
5033/*
5034 * freePGconn
5035 * - free an idle (closed) PGconn data structure
5036 *
5037 * NOTE: this should not overlap any functionality with pqClosePGconn().
5038 * Clearing/resetting of transient state belongs there; what we do here is
5039 * release data that is to be held for the life of the PGconn structure.
5040 * If a value ought to be cleared/freed during PQreset(), do it there not here.
5041 */
5042static void
5044{
5045 /* let any event procs clean up their state data */
5046 for (int i = 0; i < conn->nEvents; i++)
5047 {
5049
5050 evt.conn = conn;
5051 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
5053 free(conn->events[i].name);
5054 }
5055
5056 /* free everything not freed in pqClosePGconn */
5057 free(conn->pghost);
5059 free(conn->pgport);
5064 free(conn->appname);
5066 free(conn->dbName);
5070 free(conn->pguser);
5071 if (conn->pgpass)
5072 {
5073 explicit_bzero(conn->pgpass, strlen(conn->pgpass));
5074 free(conn->pgpass);
5075 }
5082 free(conn->sslmode);
5085 free(conn->sslkey);
5086 free(conn->sslcert);
5087 if (conn->sslpassword)
5088 {
5091 }
5094 free(conn->sslcrl);
5096 free(conn->sslsni);
5100 free(conn->gsslib);
5118 /* Note that conn->Pfdebug is not ours to close or free */
5119 free(conn->events);
5121 free(conn->connip);
5125 /* if this is a cancel connection, be_cancel_key may still be allocated */
5127 free(conn->inBuffer);
5129 free(conn->rowBuf);
5132
5133 free(conn);
5134}
5135
5136/*
5137 * pqReleaseConnHosts
5138 * - Free the host list in the PGconn.
5139 */
5140void
5142{
5143 if (conn->connhost)
5144 {
5145 for (int i = 0; i < conn->nconnhost; ++i)
5146 {
5147 free(conn->connhost[i].host);
5149 free(conn->connhost[i].port);
5150 if (conn->connhost[i].password != NULL)
5151 {
5153 strlen(conn->connhost[i].password));
5155 }
5156 }
5157 free(conn->connhost);
5158 conn->connhost = NULL;
5159 }
5160}
5161
5162/*
5163 * store_conn_addrinfo
5164 * - copy addrinfo to PGconn object
5165 *
5166 * Copies the addrinfos from addrlist to the PGconn object such that the
5167 * addrinfos can be manipulated by libpq. Returns a positive integer on
5168 * failure, otherwise zero.
5169 */
5170static int
5171store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
5172{
5173 struct addrinfo *ai = addrlist;
5174
5175 conn->whichaddr = 0;
5176
5177 conn->naddr = 0;
5178 while (ai)
5179 {
5180 ai = ai->ai_next;
5181 conn->naddr++;
5182 }
5183
5184 conn->addr = calloc(conn->naddr, sizeof(AddrInfo));
5185 if (conn->addr == NULL)
5186 {
5187 libpq_append_conn_error(conn, "out of memory");
5188 return 1;
5189 }
5190
5191 ai = addrlist;
5192 for (int i = 0; i < conn->naddr; i++)
5193 {
5194 conn->addr[i].family = ai->ai_family;
5195
5196 memcpy(&conn->addr[i].addr.addr, ai->ai_addr,
5197 ai->ai_addrlen);
5198 conn->addr[i].addr.salen = ai->ai_addrlen;
5199 ai = ai->ai_next;
5200 }
5201
5202 return 0;
5203}
5204
5205/*
5206 * release_conn_addrinfo
5207 * - Free any addrinfo list in the PGconn.
5208 */
5209static void
5211{
5212 if (conn->addr)
5213 {
5214 free(conn->addr);
5215 conn->addr = NULL;
5216 }
5217}
5218
5219/*
5220 * sendTerminateConn
5221 * - Send a terminate message to backend.
5222 */
5223static void
5225{
5226 /*
5227 * The Postgres cancellation protocol does not have a notion of a
5228 * Terminate message, so don't send one.
5229 */
5230 if (conn->cancelRequest)
5231 return;
5232
5233 /*
5234 * Note that the protocol doesn't allow us to send Terminate messages
5235 * during the startup phase.
5236 */
5238 {
5239 /*
5240 * Try to send "close connection" message to backend. Ignore any
5241 * error.
5242 */
5245 (void) pqFlush(conn);
5246 }
5247}
5248
5249/*
5250 * pqClosePGconn
5251 * - properly close a connection to the backend
5252 *
5253 * This should reset or release all transient state, but NOT the connection
5254 * parameters. On exit, the PGconn should be in condition to start a fresh
5255 * connection with the same parameters (see PQreset()).
5256 */
5257void
5259{
5260 /*
5261 * If possible, send Terminate message to close the connection politely.
5262 */
5264
5265 /*
5266 * Must reset the blocking status so a possible reconnect will work.
5267 *
5268 * Don't call PQsetnonblocking() because it will fail if it's unable to
5269 * flush the connection.
5270 */
5271 conn->nonblocking = false;
5272
5273 /*
5274 * Close the connection, reset all transient state, flush I/O buffers.
5275 * Note that this includes clearing conn's error state; we're no longer
5276 * interested in any failures associated with the old connection, and we
5277 * want a clean slate for any new connection attempt.
5278 */
5279 pqDropConnection(conn, true);
5280 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
5285 pqClearAsyncResult(conn); /* deallocate result */
5287
5288 /*
5289 * Release addrinfo, but since cancel requests never change their addrinfo
5290 * we don't do that. Otherwise we would have to rebuild it during a
5291 * PQcancelReset.
5292 */
5293 if (!conn->cancelRequest)
5295
5296 /* Reset all state obtained from server, too */
5298}
5299
5300/*
5301 * PQfinish: properly close a connection to the backend. Also frees
5302 * the PGconn data structure so it shouldn't be re-used after this.
5303 */
5304void
5306{
5307 if (conn)
5308 {
5311 }
5312}
5313
5314/*
5315 * PQreset: resets the connection to the backend by closing the
5316 * existing connection and creating a new one.
5317 */
5318void
5320{
5321 if (conn)
5322 {
5324
5326 {
5327 /*
5328 * Notify event procs of successful reset.
5329 */
5330 int i;
5331
5332 for (i = 0; i < conn->nEvents; i++)
5333 {
5334 PGEventConnReset evt;
5335
5336 evt.conn = conn;
5337 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
5339 }
5340 }
5341 }
5342}
5343
5344
5345/*
5346 * PQresetStart:
5347 * resets the connection to the backend
5348 * closes the existing connection and makes a new one
5349 * Returns 1 on success, 0 on failure.
5350 */
5351int
5353{
5354 if (conn)
5355 {
5357
5358 return pqConnectDBStart(conn);
5359 }
5360
5361 return 0;
5362}
5363
5364
5365/*
5366 * PQresetPoll:
5367 * resets the connection to the backend
5368 * closes the existing connection and makes a new one
5369 */
5372{
5373 if (conn)
5374 {
5376
5377 if (status == PGRES_POLLING_OK)
5378 {
5379 /*
5380 * Notify event procs of successful reset.
5381 */
5382 int i;
5383
5384 for (i = 0; i < conn->nEvents; i++)
5385 {
5386 PGEventConnReset evt;
5387
5388 evt.conn = conn;
5389 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
5391 }
5392 }
5393
5394 return status;
5395 }
5396
5397 return PGRES_POLLING_FAILED;
5398}
5399
5400/*
5401 * pqPacketSend() -- convenience routine to send a message to server.
5402 *
5403 * pack_type: the single-byte message type code. (Pass zero for startup
5404 * packets, which have no message type code.)
5405 *
5406 * buf, buf_len: contents of message. The given length includes only what
5407 * is in buf; the message type and message length fields are added here.
5408 *
5409 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
5410 * SIDE_EFFECTS: may block.
5411 */
5412int
5413pqPacketSend(PGconn *conn, char pack_type,
5414 const void *buf, size_t buf_len)
5415{
5416 /* Start the message. */
5417 if (pqPutMsgStart(pack_type, conn))
5418 return STATUS_ERROR;
5419
5420 /* Send the message body. */
5421 if (pqPutnchar(buf, buf_len, conn))
5422 return STATUS_ERROR;
5423
5424 /* Finish the message. */
5425 if (pqPutMsgEnd(conn))
5426 return STATUS_ERROR;
5427
5428 /* Flush to ensure backend gets it. */
5429 if (pqFlush(conn))
5430 return STATUS_ERROR;
5431
5432 return STATUS_OK;
5433}
5434
5435#ifdef USE_LDAP
5436
5437#define LDAP_URL "ldap://"
5438#define LDAP_DEF_PORT 389
5439#define PGLDAP_TIMEOUT 2
5440
5441#define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
5442#define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
5443
5444
5445/*
5446 * ldapServiceLookup
5447 *
5448 * Search the LDAP URL passed as first argument, treat the result as a
5449 * string of connection options that are parsed and added to the array of
5450 * options passed as second argument.
5451 *
5452 * LDAP URLs must conform to RFC 1959 without escape sequences.
5453 * ldap://host:port/dn?attributes?scope?filter?extensions
5454 *
5455 * Returns
5456 * 0 if the lookup was successful,
5457 * 1 if the connection to the LDAP server could be established but
5458 * the search was unsuccessful,
5459 * 2 if a connection could not be established, and
5460 * 3 if a fatal error occurred.
5461 *
5462 * An error message is appended to *errorMessage for return codes 1 and 3.
5463 */
5464static int
5465ldapServiceLookup(const char *purl, PQconninfoOption *options,
5466 PQExpBuffer errorMessage)
5467{
5468 int port = LDAP_DEF_PORT,
5469 scope,
5470 rc,
5471 size,
5472 state,
5473 oldstate,
5474 i;
5475#ifndef WIN32
5476 int msgid;
5477#endif
5478 bool found_keyword;
5479 char *url,
5480 *hostname,
5481 *portstr,
5482 *endptr,
5483 *dn,
5484 *scopestr,
5485 *filter,
5486 *result,
5487 *p,
5488 *p1 = NULL,
5489 *optname = NULL,
5490 *optval = NULL;
5491 char *attrs[2] = {NULL, NULL};
5492 LDAP *ld = NULL;
5493 LDAPMessage *res,
5494 *entry;
5495 struct berval **values;
5496 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
5497 int ldapversion = LDAP_VERSION3;
5498
5499 if ((url = strdup(purl)) == NULL)
5500 {
5501 libpq_append_error(errorMessage, "out of memory");
5502 return 3;
5503 }
5504
5505 /*
5506 * Parse URL components, check for correctness. Basically, url has '\0'
5507 * placed at component boundaries and variables are pointed at each
5508 * component.
5509 */
5510
5511 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
5512 {
5513 libpq_append_error(errorMessage,
5514 "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
5515 free(url);
5516 return 3;
5517 }
5518
5519 /* hostname */
5520 hostname = url + strlen(LDAP_URL);
5521 if (*hostname == '/') /* no hostname? */
5522 hostname = DefaultHost; /* the default */
5523
5524 /* dn, "distinguished name" */
5525 p = strchr(url + strlen(LDAP_URL), '/');
5526 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5527 {
5528 libpq_append_error(errorMessage,
5529 "invalid LDAP URL \"%s\": missing distinguished name",
5530 purl);
5531 free(url);
5532 return 3;
5533 }
5534 *p = '\0'; /* terminate hostname */
5535 dn = p + 1;
5536
5537 /* attribute */
5538 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5539 {
5540 libpq_append_error(errorMessage,
5541 "invalid LDAP URL \"%s\": must have exactly one attribute",
5542 purl);
5543 free(url);
5544 return 3;
5545 }
5546 *p = '\0';
5547 attrs[0] = p + 1;
5548
5549 /* scope */
5550 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5551 {
5552 libpq_append_error(errorMessage,
5553 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5554 purl);
5555 free(url);
5556 return 3;
5557 }
5558 *p = '\0';
5559 scopestr = p + 1;
5560
5561 /* filter */
5562 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
5563 {
5564 libpq_append_error(errorMessage,
5565 "invalid LDAP URL \"%s\": no filter",
5566 purl);
5567 free(url);
5568 return 3;
5569 }
5570 *p = '\0';
5571 filter = p + 1;
5572 if ((p = strchr(filter, '?')) != NULL)
5573 *p = '\0';
5574
5575 /* port number? */
5576 if ((p1 = strchr(hostname, ':')) != NULL)
5577 {
5578 long lport;
5579
5580 *p1 = '\0';
5581 portstr = p1 + 1;
5582 errno = 0;
5583 lport = strtol(portstr, &endptr, 10);
5584 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
5585 {
5586 libpq_append_error(errorMessage,
5587 "invalid LDAP URL \"%s\": invalid port number",
5588 purl);
5589 free(url);
5590 return 3;
5591 }
5592 port = (int) lport;
5593 }
5594
5595 /* Allow only one attribute */
5596 if (strchr(attrs[0], ',') != NULL)
5597 {
5598 libpq_append_error(errorMessage,
5599 "invalid LDAP URL \"%s\": must have exactly one attribute",
5600 purl);
5601 free(url);
5602 return 3;
5603 }
5604
5605 /* set scope */
5606 if (pg_strcasecmp(scopestr, "base") == 0)
5607 scope = LDAP_SCOPE_BASE;
5608 else if (pg_strcasecmp(scopestr, "one") == 0)
5609 scope = LDAP_SCOPE_ONELEVEL;
5610 else if (pg_strcasecmp(scopestr, "sub") == 0)
5611 scope = LDAP_SCOPE_SUBTREE;
5612 else
5613 {
5614 libpq_append_error(errorMessage,
5615 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5616 purl);
5617 free(url);
5618 return 3;
5619 }
5620
5621 /* initialize LDAP structure */
5622 if ((ld = ldap_init(hostname, port)) == NULL)
5623 {
5624 libpq_append_error(errorMessage, "could not create LDAP structure");
5625 free(url);
5626 return 3;
5627 }
5628
5629 if ((rc = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
5630 {
5631 libpq_append_error(errorMessage, "could not set LDAP protocol version: %s",
5632 ldap_err2string(rc));
5633 free(url);
5634 ldap_unbind(ld);
5635 return 3;
5636 }
5637
5638 /*
5639 * Perform an explicit anonymous bind.
5640 *
5641 * LDAP does not require that an anonymous bind is performed explicitly,
5642 * but we want to distinguish between the case where LDAP bind does not
5643 * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
5644 * service control file) and the case where querying the LDAP server fails
5645 * (return 1 to end parsing).
5646 *
5647 * Unfortunately there is no way of setting a timeout that works for both
5648 * Windows and OpenLDAP.
5649 */
5650#ifdef WIN32
5651 /* the nonstandard ldap_connect function performs an anonymous bind */
5652 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
5653 {
5654 /* error or timeout in ldap_connect */
5655 free(url);
5656 ldap_unbind(ld);
5657 return 2;
5658 }
5659#else /* !WIN32 */
5660 /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
5661 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5662 {
5663 free(url);
5664 ldap_unbind(ld);
5665 return 3;
5666 }
5667
5668 /* anonymous bind */
5669 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
5670 {
5671 /* error or network timeout */
5672 free(url);
5673 ldap_unbind(ld);
5674 return 2;
5675 }
5676
5677 /* wait some time for the connection to succeed */
5678 res = NULL;
5679 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
5680 res == NULL)
5681 {
5682 /* error or timeout */
5683 if (res != NULL)
5684 ldap_msgfree(res);
5685 free(url);
5686 ldap_unbind(ld);
5687 return 2;
5688 }
5689 ldap_msgfree(res);
5690
5691 /* reset timeout */
5692 time.tv_sec = -1;
5693 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5694 {
5695 free(url);
5696 ldap_unbind(ld);
5697 return 3;
5698 }
5699#endif /* WIN32 */
5700
5701 /* search */
5702 res = NULL;
5703 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
5704 != LDAP_SUCCESS)
5705 {
5706 if (res != NULL)
5707 ldap_msgfree(res);
5708 libpq_append_error(errorMessage, "lookup on LDAP server failed: %s", ldap_err2string(rc));
5709 ldap_unbind(ld);
5710 free(url);
5711 return 1;
5712 }
5713
5714 /* complain if there was not exactly one result */
5715 if ((rc = ldap_count_entries(ld, res)) != 1)
5716 {
5717 if (rc > 1)
5718 libpq_append_error(errorMessage, "more than one entry found on LDAP lookup");
5719 else
5720 libpq_append_error(errorMessage, "no entry found on LDAP lookup");
5721 ldap_msgfree(res);
5722 ldap_unbind(ld);
5723 free(url);
5724 return 1;
5725 }
5726
5727 /* get entry */
5728 if ((entry = ldap_first_entry(ld, res)) == NULL)
5729 {
5730 /* should never happen */
5731 libpq_append_error(errorMessage, "no entry found on LDAP lookup");
5732 ldap_msgfree(res);
5733 ldap_unbind(ld);
5734 free(url);
5735 return 1;
5736 }
5737
5738 /* get values */
5739 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
5740 {
5741 libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
5742 ldap_msgfree(res);
5743 ldap_unbind(ld);
5744 free(url);
5745 return 1;
5746 }
5747
5748 ldap_msgfree(res);
5749 free(url);
5750
5751 if (values[0] == NULL)
5752 {
5753 libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
5754 ldap_value_free_len(values);
5755 ldap_unbind(ld);
5756 return 1;
5757 }
5758
5759 /* concatenate values into a single string with newline terminators */
5760 size = 1; /* for the trailing null */
5761 for (i = 0; values[i] != NULL; i++)
5762 size += values[i]->bv_len + 1;
5763 if ((result = malloc(size)) == NULL)
5764 {
5765 libpq_append_error(errorMessage, "out of memory");
5766 ldap_value_free_len(values);
5767 ldap_unbind(ld);
5768 return 3;
5769 }
5770 p = result;
5771 for (i = 0; values[i] != NULL; i++)
5772 {
5773 memcpy(p, values[i]->bv_val, values[i]->bv_len);
5774 p += values[i]->bv_len;
5775 *(p++) = '\n';
5776 }
5777 *p = '\0';
5778
5779 ldap_value_free_len(values);
5780 ldap_unbind(ld);
5781
5782 /* parse result string */
5783 oldstate = state = 0;
5784 for (p = result; *p != '\0'; ++p)
5785 {
5786 switch (state)
5787 {
5788 case 0: /* between entries */
5789 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
5790 {
5791 optname = p;
5792 state = 1;
5793 }
5794 break;
5795 case 1: /* in option name */
5796 if (ld_is_sp_tab(*p))
5797 {
5798 *p = '\0';
5799 state = 2;
5800 }
5801 else if (ld_is_nl_cr(*p))
5802 {
5803 libpq_append_error(errorMessage,
5804 "missing \"=\" after \"%s\" in connection info string",
5805 optname);
5806 free(result);
5807 return 3;
5808 }
5809 else if (*p == '=')
5810 {
5811 *p = '\0';
5812 state = 3;
5813 }
5814 break;
5815 case 2: /* after option name */
5816 if (*p == '=')
5817 {
5818 state = 3;
5819 }
5820 else if (!ld_is_sp_tab(*p))
5821 {
5822 libpq_append_error(errorMessage,
5823 "missing \"=\" after \"%s\" in connection info string",
5824 optname);
5825 free(result);
5826 return 3;
5827 }
5828 break;
5829 case 3: /* before option value */
5830 if (*p == '\'')
5831 {
5832 optval = p + 1;
5833 p1 = p + 1;
5834 state = 5;
5835 }
5836 else if (ld_is_nl_cr(*p))
5837 {
5838 optval = optname + strlen(optname); /* empty */
5839 state = 0;
5840 }
5841 else if (!ld_is_sp_tab(*p))
5842 {
5843 optval = p;
5844 state = 4;
5845 }
5846 break;
5847 case 4: /* in unquoted option value */
5848 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
5849 {
5850 *p = '\0';
5851 state = 0;
5852 }
5853 break;
5854 case 5: /* in quoted option value */
5855 if (*p == '\'')
5856 {
5857 *p1 = '\0';
5858 state = 0;
5859 }
5860 else if (*p == '\\')
5861 state = 6;
5862 else
5863 *(p1++) = *p;
5864 break;
5865 case 6: /* in quoted option value after escape */
5866 *(p1++) = *p;
5867 state = 5;
5868 break;
5869 }
5870
5871 if (state == 0 && oldstate != 0)
5872 {
5873 found_keyword = false;
5874 for (i = 0; options[i].keyword; i++)
5875 {
5876 if (strcmp(options[i].keyword, optname) == 0)
5877 {
5878 if (options[i].val == NULL)
5879 {
5880 options[i].val = strdup(optval);
5881 if (!options[i].val)
5882 {
5883 libpq_append_error(errorMessage, "out of memory");
5884 free(result);
5885 return 3;
5886 }
5887 }
5888 found_keyword = true;
5889 break;
5890 }
5891 }
5892 if (!found_keyword)
5893 {
5894 libpq_append_error(errorMessage, "invalid connection option \"%s\"", optname);
5895 free(result);
5896 return 1;
5897 }
5898 optname = NULL;
5899 optval = NULL;
5900 }
5901 oldstate = state;
5902 }
5903
5904 free(result);
5905
5906 if (state == 5 || state == 6)
5907 {
5908 libpq_append_error(errorMessage,
5909 "unterminated quoted string in connection info string");
5910 return 3;
5911 }
5912
5913 return 0;
5914}
5915
5916#endif /* USE_LDAP */
5917
5918/*
5919 * parseServiceInfo: if a service name has been given, look it up and absorb
5920 * connection options from it into *options.
5921 *
5922 * Returns 0 on success, nonzero on failure. On failure, if errorMessage
5923 * isn't null, also store an error message there. (Note: the only reason
5924 * this function and related ones don't dump core on errorMessage == NULL
5925 * is the undocumented fact that appendPQExpBuffer does nothing when passed
5926 * a null PQExpBuffer pointer.)
5927 */
5928static int
5930{
5931 const char *service = conninfo_getval(options, "service");
5932 const char *service_fname = conninfo_getval(options, "servicefile");
5933 char serviceFile[MAXPGPATH];
5934 char *env;
5935 bool group_found = false;
5936 int status;
5937 struct stat stat_buf;
5938
5939 /*
5940 * We have to special-case the environment variable PGSERVICE here, since
5941 * this is and should be called before inserting environment defaults for
5942 * other connection options.
5943 */
5944 if (service == NULL)
5945 service = getenv("PGSERVICE");
5946
5947 /* If no service name given, nothing to do */
5948 if (service == NULL)
5949 return 0;
5950
5951 /*
5952 * First, try the "servicefile" option in connection string. Then, try
5953 * the PGSERVICEFILE environment variable. Finally, check
5954 * ~/.pg_service.conf (if that exists).
5955 */
5956 if (service_fname != NULL)
5957 strlcpy(serviceFile, service_fname, sizeof(serviceFile));
5958 else if ((env = getenv("PGSERVICEFILE")) != NULL)
5959 strlcpy(serviceFile, env, sizeof(serviceFile));
5960 else
5961 {
5962 char homedir[MAXPGPATH];
5963
5964 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5965 goto next_file;
5966 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5967 if (stat(serviceFile, &stat_buf) != 0)
5968 goto next_file;
5969 }
5970
5971 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5972 if (group_found || status != 0)
5973 return status;
5974
5975next_file:
5976
5977 /*
5978 * This could be used by any application so we can't use the binary
5979 * location to find our config files.
5980 */
5981 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5982 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5983 if (stat(serviceFile, &stat_buf) != 0)
5984 goto last_file;
5985
5986 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5987 if (status != 0)
5988 return status;
5989
5990last_file:
5991 if (!group_found)
5992 {
5993 libpq_append_error(errorMessage, "definition of service \"%s\" not found", service);
5994 return 3;
5995 }
5996
5997 return 0;
5998}
5999
6000static int
6001parseServiceFile(const char *serviceFile,
6002 const char *service,
6004 PQExpBuffer errorMessage,
6005 bool *group_found)
6006{
6007 int result = 0,
6008 linenr = 0,
6009 i;
6010 FILE *f;
6011 char *line;
6012 char buf[1024];
6013
6014 *group_found = false;
6015
6016 f = fopen(serviceFile, "r");
6017 if (f == NULL)
6018 {
6019 libpq_append_error(errorMessage, "service file \"%s\" not found", serviceFile);
6020 return 1;
6021 }
6022
6023 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
6024 {
6025 int len;
6026
6027 linenr++;
6028
6029 if (strlen(line) >= sizeof(buf) - 1)
6030 {
6031 libpq_append_error(errorMessage,
6032 "line %d too long in service file \"%s\"",
6033 linenr,
6034 serviceFile);
6035 result = 2;
6036 goto exit;
6037 }
6038
6039 /* ignore whitespace at end of line, especially the newline */
6040 len = strlen(line);
6041 while (len > 0 && isspace((unsigned char) line[len - 1]))
6042 line[--len] = '\0';
6043
6044 /* ignore leading whitespace too */
6045 while (*line && isspace((unsigned char) line[0]))
6046 line++;
6047
6048 /* ignore comments and empty lines */
6049 if (line[0] == '\0' || line[0] == '#')
6050 continue;
6051
6052 /* Check for right groupname */
6053 if (line[0] == '[')
6054 {
6055 if (*group_found)
6056 {
6057 /* end of desired group reached; return success */
6058 goto exit;
6059 }
6060
6061 if (strncmp(line + 1, service, strlen(service)) == 0 &&
6062 line[strlen(service) + 1] == ']')
6063 *group_found = true;
6064 else
6065 *group_found = false;
6066 }
6067 else
6068 {
6069 if (*group_found)
6070 {
6071 /*
6072 * Finally, we are in the right group and can parse the line
6073 */
6074 char *key,
6075 *val;
6076 bool found_keyword;
6077
6078#ifdef USE_LDAP
6079 if (strncmp(line, "ldap", 4) == 0)
6080 {
6081 int rc = ldapServiceLookup(line, options, errorMessage);
6082
6083 /* if rc = 2, go on reading for fallback */
6084 switch (rc)
6085 {
6086 case 0:
6087 goto exit;
6088 case 1:
6089 case 3:
6090 result = 3;
6091 goto exit;
6092 case 2:
6093 continue;
6094 }
6095 }
6096#endif
6097
6098 key = line;
6099 val = strchr(line, '=');
6100 if (val == NULL)
6101 {
6102 libpq_append_error(errorMessage,
6103 "syntax error in service file \"%s\", line %d",
6104 serviceFile,
6105 linenr);
6106 result = 3;
6107 goto exit;
6108 }
6109 *val++ = '\0';
6110
6111 if (strcmp(key, "service") == 0)
6112 {
6113 libpq_append_error(errorMessage,
6114 "nested \"service\" specifications not supported in service file \"%s\", line %d",
6115 serviceFile,
6116 linenr);
6117 result = 3;
6118 goto exit;
6119 }
6120
6121 if (strcmp(key, "servicefile") == 0)
6122 {
6123 libpq_append_error(errorMessage,
6124 "nested \"servicefile\" specifications not supported in service file \"%s\", line %d",
6125 serviceFile,
6126 linenr);
6127 result = 3;
6128 goto exit;
6129 }
6130
6131 /*
6132 * Set the parameter --- but don't override any previous
6133 * explicit setting.
6134 */
6135 found_keyword = false;
6136 for (i = 0; options[i].keyword; i++)
6137 {
6138 if (strcmp(options[i].keyword, key) == 0)
6139 {
6140 if (options[i].val == NULL)
6141 options[i].val = strdup(val);
6142 if (!options[i].val)
6143 {
6144 libpq_append_error(errorMessage, "out of memory");
6145 result = 3;
6146 goto exit;
6147 }
6148 found_keyword = true;
6149 break;
6150 }
6151 }
6152
6153 if (!found_keyword)
6154 {
6155 libpq_append_error(errorMessage,
6156 "syntax error in service file \"%s\", line %d",
6157 serviceFile,
6158 linenr);
6159 result = 3;
6160 goto exit;
6161 }
6162 }
6163 }
6164 }
6165
6166exit:
6167
6168 /*
6169 * If a service has been successfully found, set the "servicefile" option
6170 * if not already set. This matters when we use a default service file or
6171 * PGSERVICEFILE, where we want to be able track the value.
6172 */
6173 if (*group_found && result == 0)
6174 {
6175 for (i = 0; options[i].keyword; i++)
6176 {
6177 if (strcmp(options[i].keyword, "servicefile") != 0)
6178 continue;
6179
6180 /* If value is already set, nothing to do */
6181 if (options[i].val != NULL)
6182 break;
6183
6184 options[i].val = strdup(serviceFile);
6185 if (options[i].val == NULL)
6186 {
6187 libpq_append_error(errorMessage, "out of memory");
6188 result = 3;
6189 }
6190 break;
6191 }
6192 }
6193
6194 fclose(f);
6195
6196 return result;
6197}
6198
6199
6200/*
6201 * PQconninfoParse
6202 *
6203 * Parse a string like PQconnectdb() would do and return the
6204 * resulting connection options array. NULL is returned on failure.
6205 * The result contains only options specified directly in the string,
6206 * not any possible default values.
6207 *
6208 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
6209 * string on failure (use PQfreemem to free it). In out-of-memory conditions
6210 * both *errmsg and the result could be NULL.
6211 *
6212 * NOTE: the returned array is dynamically allocated and should
6213 * be freed when no longer needed via PQconninfoFree().
6214 */
6216PQconninfoParse(const char *conninfo, char **errmsg)
6217{
6218 PQExpBufferData errorBuf;
6219 PQconninfoOption *connOptions;
6220
6221 if (errmsg)
6222 *errmsg = NULL; /* default */
6223 initPQExpBuffer(&errorBuf);
6224 if (PQExpBufferDataBroken(errorBuf))
6225 return NULL; /* out of memory already :-( */
6226 connOptions = parse_connection_string(conninfo, &errorBuf, false);
6227 if (connOptions == NULL && errmsg)
6228 *errmsg = errorBuf.data;
6229 else
6230 termPQExpBuffer(&errorBuf);
6231 return connOptions;
6232}
6233
6234/*
6235 * Build a working copy of the constant PQconninfoOptions array.
6236 */
6237static PQconninfoOption *
6239{
6241 PQconninfoOption *opt_dest;
6242 const internalPQconninfoOption *cur_opt;
6243
6244 /*
6245 * Get enough memory for all options in PQconninfoOptions, even if some
6246 * end up being filtered out.
6247 */
6249 if (options == NULL)
6250 {
6251 libpq_append_error(errorMessage, "out of memory");
6252 return NULL;
6253 }
6254 opt_dest = options;
6255
6256 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
6257 {
6258 /* Only copy the public part of the struct, not the full internal */
6259 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
6260 opt_dest++;
6261 }
6262 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
6263
6264 return options;
6265}
6266
6267/*
6268 * Connection string parser
6269 *
6270 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
6271 * Otherwise, NULL is returned and an error message is added to errorMessage.
6272 *
6273 * If use_defaults is true, default values are filled in (from a service file,
6274 * environment variables, etc).
6275 */
6276static PQconninfoOption *
6278 bool use_defaults)
6279{
6280 /* Parse as URI if connection string matches URI prefix */
6281 if (uri_prefix_length(connstr) != 0)
6282 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
6283
6284 /* Parse as default otherwise */
6285 return conninfo_parse(connstr, errorMessage, use_defaults);
6286}
6287
6288/*
6289 * Checks if connection string starts with either of the valid URI prefix
6290 * designators.
6291 *
6292 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
6293 *
6294 * XXX this is duplicated in psql/common.c.
6295 */
6296static int
6298{
6299 if (strncmp(connstr, uri_designator,
6300 sizeof(uri_designator) - 1) == 0)
6301 return sizeof(uri_designator) - 1;
6302
6303 if (strncmp(connstr, short_uri_designator,
6304 sizeof(short_uri_designator) - 1) == 0)
6305 return sizeof(short_uri_designator) - 1;
6306
6307 return 0;
6308}
6309
6310/*
6311 * Recognized connection string either starts with a valid URI prefix or
6312 * contains a "=" in it.
6313 *
6314 * Must be consistent with parse_connection_string: anything for which this
6315 * returns true should at least look like it's parseable by that routine.
6316 *
6317 * XXX this is duplicated in psql/common.c
6318 */
6319static bool
6321{
6322 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
6323}
6324
6325/*
6326 * Subroutine for parse_connection_string
6327 *
6328 * Deal with a string containing key=value pairs.
6329 */
6330static PQconninfoOption *
6331conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
6332 bool use_defaults)
6333{
6334 char *pname;
6335 char *pval;
6336 char *buf;
6337 char *cp;
6338 char *cp2;
6340
6341 /* Make a working copy of PQconninfoOptions */
6342 options = conninfo_init(errorMessage);
6343 if (options == NULL)
6344 return NULL;
6345
6346 /* Need a modifiable copy of the input string */
6347 if ((buf = strdup(conninfo)) == NULL)
6348 {
6349 libpq_append_error(errorMessage, "out of memory");
6351 return NULL;
6352 }
6353 cp = buf;
6354
6355 while (*cp)
6356 {
6357 /* Skip blanks before the parameter name */
6358 if (isspace((unsigned char) *cp))
6359 {
6360 cp++;
6361 continue;
6362 }
6363
6364 /* Get the parameter name */
6365 pname = cp;
6366 while (*cp)
6367 {
6368 if (*cp == '=')
6369 break;
6370 if (isspace((unsigned char) *cp))
6371 {
6372 *cp++ = '\0';
6373 while (*cp)
6374 {
6375 if (!isspace((unsigned char) *cp))
6376 break;
6377 cp++;
6378 }
6379 break;
6380 }
6381 cp++;
6382 }
6383
6384 /* Check that there is a following '=' */
6385 if (*cp != '=')
6386 {
6387 libpq_append_error(errorMessage,
6388 "missing \"=\" after \"%s\" in connection info string",
6389 pname);
6391 free(buf);
6392 return NULL;
6393 }
6394 *cp++ = '\0';
6395
6396 /* Skip blanks after the '=' */
6397 while (*cp)
6398 {
6399 if (!isspace((unsigned char) *cp))
6400 break;
6401 cp++;
6402 }
6403
6404 /* Get the parameter value */
6405 pval = cp;
6406
6407 if (*cp != '\'')
6408 {
6409 cp2 = pval;
6410 while (*cp)
6411 {
6412 if (isspace((unsigned char) *cp))
6413 {
6414 *cp++ = '\0';
6415 break;
6416 }
6417 if (*cp == '\\')
6418 {
6419 cp++;
6420 if (*cp != '\0')
6421 *cp2++ = *cp++;
6422 }
6423 else
6424 *cp2++ = *cp++;
6425 }
6426 *cp2 = '\0';
6427 }
6428 else
6429 {
6430 cp2 = pval;
6431 cp++;
6432 for (;;)
6433 {
6434 if (*cp == '\0')
6435 {
6436 libpq_append_error(errorMessage, "unterminated quoted string in connection info string");
6438 free(buf);
6439 return NULL;
6440 }
6441 if (*cp == '\\')
6442 {
6443 cp++;
6444 if (*cp != '\0')
6445 *cp2++ = *cp++;
6446 continue;
6447 }
6448 if (*cp == '\'')
6449 {
6450 *cp2 = '\0';
6451 cp++;
6452 break;
6453 }
6454 *cp2++ = *cp++;
6455 }
6456 }
6457
6458 /*
6459 * Now that we have the name and the value, store the record.
6460 */
6461 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
6462 {
6464 free(buf);
6465 return NULL;
6466 }
6467 }
6468
6469 /* Done with the modifiable input string */
6470 free(buf);
6471
6472 /*
6473 * Add in defaults if the caller wants that.
6474 */
6475 if (use_defaults)
6476 {
6477 if (!conninfo_add_defaults(options, errorMessage))
6478 {
6480 return NULL;
6481 }
6482 }
6483
6484 return options;
6485}
6486
6487/*
6488 * Conninfo array parser routine
6489 *
6490 * If successful, a malloc'd PQconninfoOption array is returned.
6491 * If not successful, NULL is returned and an error message is
6492 * appended to errorMessage.
6493 * Defaults are supplied (from a service file, environment variables, etc)
6494 * for unspecified options, but only if use_defaults is true.
6495 *
6496 * If expand_dbname is non-zero, and the value passed for the first occurrence
6497 * of "dbname" keyword is a connection string (as indicated by
6498 * recognized_connection_string) then parse and process it, overriding any
6499 * previously processed conflicting keywords. Subsequent keywords will take
6500 * precedence, however. In-tree programs generally specify expand_dbname=true,
6501 * so command-line arguments naming a database can use a connection string.
6502 * Some code acquires arbitrary database names from known-literal sources like
6503 * PQdb(), PQconninfoParse() and pg_database.datname. When connecting to such
6504 * a database, in-tree code first wraps the name in a connection string.
6505 */
6506static PQconninfoOption *
6507conninfo_array_parse(const char *const *keywords, const char *const *values,
6508 PQExpBuffer errorMessage, bool use_defaults,
6509 int expand_dbname)
6510{
6512 PQconninfoOption *dbname_options = NULL;
6514 int i = 0;
6515
6516 /*
6517 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
6518 * actually a recognized connection string.
6519 */
6520 while (expand_dbname && keywords[i])
6521 {
6522 const char *pname = keywords[i];
6523 const char *pvalue = values[i];
6524
6525 /* first find "dbname" if any */
6526 if (strcmp(pname, "dbname") == 0 && pvalue)
6527 {
6528 /*
6529 * If value is a connection string, parse it, but do not use
6530 * defaults here -- those get picked up later. We only want to
6531 * override for those parameters actually passed.
6532 */
6533 if (recognized_connection_string(pvalue))
6534 {
6535 dbname_options = parse_connection_string(pvalue, errorMessage, false);
6536 if (dbname_options == NULL)
6537 return NULL;
6538 }
6539 break;
6540 }
6541 ++i;
6542 }
6543
6544 /* Make a working copy of PQconninfoOptions */
6545 options = conninfo_init(errorMessage);
6546 if (options == NULL)
6547 {
6548 PQconninfoFree(dbname_options);
6549 return NULL;
6550 }
6551
6552 /* Parse the keywords/values arrays */
6553 i = 0;
6554 while (keywords[i])
6555 {
6556 const char *pname = keywords[i];
6557 const char *pvalue = values[i];
6558
6559 if (pvalue != NULL && pvalue[0] != '\0')
6560 {
6561 /* Search for the param record */
6562 for (option = options; option->keyword != NULL; option++)
6563 {
6564 if (strcmp(option->keyword, pname) == 0)
6565 break;
6566 }
6567
6568 /* Check for invalid connection option */
6569 if (option->keyword == NULL)
6570 {
6571 libpq_append_error(errorMessage, "invalid connection option \"%s\"", pname);
6573 PQconninfoFree(dbname_options);
6574 return NULL;
6575 }
6576
6577 /*
6578 * If we are on the first dbname parameter, and we have a parsed
6579 * connection string, copy those parameters across, overriding any
6580 * existing previous settings.
6581 */
6582 if (strcmp(pname, "dbname") == 0 && dbname_options)
6583 {
6584 PQconninfoOption *str_option;
6585
6586 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
6587 {
6588 if (str_option->val != NULL)
6589 {
6590 int k;
6591
6592 for (k = 0; options[k].keyword; k++)
6593 {
6594 if (strcmp(options[k].keyword, str_option->keyword) == 0)
6595 {
6596 free(options[k].val);
6597 options[k].val = strdup(str_option->val);
6598 if (!options[k].val)
6599 {
6600 libpq_append_error(errorMessage, "out of memory");
6602 PQconninfoFree(dbname_options);
6603 return NULL;
6604 }
6605 break;
6606 }
6607 }
6608 }
6609 }
6610
6611 /*
6612 * Forget the parsed connection string, so that any subsequent
6613 * dbname parameters will not be expanded.
6614 */
6615 PQconninfoFree(dbname_options);
6616 dbname_options = NULL;
6617 }
6618 else
6619 {
6620 /*
6621 * Store the value, overriding previous settings
6622 */
6623 free(option->val);
6624 option->val = strdup(pvalue);
6625 if (!option->val)
6626 {
6627 libpq_append_error(errorMessage, "out of memory");
6629 PQconninfoFree(dbname_options);
6630 return NULL;
6631 }
6632 }
6633 }
6634 ++i;
6635 }
6636 PQconninfoFree(dbname_options);
6637
6638 /*
6639 * Add in defaults if the caller wants that.
6640 */
6641 if (use_defaults)
6642 {
6643 if (!conninfo_add_defaults(options, errorMessage))
6644 {
6646 return NULL;
6647 }
6648 }
6649
6650 return options;
6651}
6652
6653/*
6654 * Add the default values for any unspecified options to the connection
6655 * options array.
6656 *
6657 * Defaults are obtained from a service file, environment variables, etc.
6658 *
6659 * Returns true if successful, otherwise false; errorMessage, if supplied,
6660 * is filled in upon failure. Note that failure to locate a default value
6661 * is not an error condition here --- we just leave the option's value as
6662 * NULL.
6663 */
6664static bool
6666{
6668 PQconninfoOption *sslmode_default = NULL,
6669 *sslrootcert = NULL;
6670 char *tmp;
6671
6672 /*
6673 * If there's a service spec, use it to obtain any not-explicitly-given
6674 * parameters. Ignore error if no error message buffer is passed because
6675 * there is no way to pass back the failure message.
6676 */
6677 if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
6678 return false;
6679
6680 /*
6681 * Get the fallback resources for parameters not specified in the conninfo
6682 * string nor the service.
6683 */
6684 for (option = options; option->keyword != NULL; option++)
6685 {
6686 if (strcmp(option->keyword, "sslrootcert") == 0)
6687 sslrootcert = option; /* save for later */
6688
6689 if (option->val != NULL)
6690 continue; /* Value was in conninfo or service */
6691
6692 /*
6693 * Try to get the environment variable fallback
6694 */
6695 if (option->envvar != NULL)
6696 {
6697 if ((tmp = getenv(option->envvar)) != NULL)
6698 {
6699 option->val = strdup(tmp);
6700 if (!option->val)
6701 {
6702 if (errorMessage)
6703 libpq_append_error(errorMessage, "out of memory");
6704 return false;
6705 }
6706 continue;
6707 }
6708 }
6709
6710 /*
6711 * Interpret the deprecated PGREQUIRESSL environment variable. Per
6712 * tradition, translate values starting with "1" to sslmode=require,
6713 * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
6714 * PGSSLMODE takes precedence; the opposite was true before v9.3.
6715 */
6716 if (strcmp(option->keyword, "sslmode") == 0)
6717 {
6718 const char *requiresslenv = getenv("PGREQUIRESSL");
6719
6720 if (requiresslenv != NULL && requiresslenv[0] == '1')
6721 {
6722 option->val = strdup("require");
6723 if (!option->val)
6724 {
6725 if (errorMessage)
6726 libpq_append_error(errorMessage, "out of memory");
6727 return false;
6728 }
6729 continue;
6730 }
6731
6732 /*
6733 * sslmode is not specified. Let it be filled in with the compiled
6734 * default for now, but if sslrootcert=system, we'll override the
6735 * default later before returning.
6736 */
6737 sslmode_default = option;
6738 }
6739
6740 /*
6741 * No environment variable specified or the variable isn't set - try
6742 * compiled-in default
6743 */
6744 if (option->compiled != NULL)
6745 {
6746 option->val = strdup(option->compiled);
6747 if (!option->val)
6748 {
6749 if (errorMessage)
6750 libpq_append_error(errorMessage, "out of memory");
6751 return false;
6752 }
6753 continue;
6754 }
6755
6756 /*
6757 * Special handling for "user" option. Note that if pg_fe_getauthname
6758 * fails, we just leave the value as NULL; there's no need for this to
6759 * be an error condition if the caller provides a user name. The only
6760 * reason we do this now at all is so that callers of PQconndefaults
6761 * will see a correct default (barring error, of course).
6762 */
6763 if (strcmp(option->keyword, "user") == 0)
6764 {
6765 option->val = pg_fe_getauthname(NULL);
6766 continue;
6767 }
6768 }
6769
6770 /*
6771 * Special handling for sslrootcert=system with no sslmode explicitly
6772 * defined. In this case we want to strengthen the default sslmode to
6773 * verify-full.
6774 */
6775 if (sslmode_default && sslrootcert)
6776 {
6777 if (sslrootcert->val && strcmp(sslrootcert->val, "system") == 0)
6778 {
6779 free(sslmode_default->val);
6780
6781 sslmode_default->val = strdup("verify-full");
6782 if (!sslmode_default->val)
6783 {
6784 if (errorMessage)
6785 libpq_append_error(errorMessage, "out of memory");
6786 return false;
6787 }
6788 }
6789 }
6790
6791 return true;
6792}
6793
6794/*
6795 * Subroutine for parse_connection_string
6796 *
6797 * Deal with a URI connection string.
6798 */
6799static PQconninfoOption *
6800conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
6801 bool use_defaults)
6802{
6804
6805 /* Make a working copy of PQconninfoOptions */
6806 options = conninfo_init(errorMessage);
6807 if (options == NULL)
6808 return NULL;
6809
6810 if (!conninfo_uri_parse_options(options, uri, errorMessage))
6811 {
6813 return NULL;
6814 }
6815
6816 /*
6817 * Add in defaults if the caller wants that.
6818 */
6819 if (use_defaults)
6820 {
6821 if (!conninfo_add_defaults(options, errorMessage))
6822 {
6824 return NULL;
6825 }
6826 }
6827
6828 return options;
6829}
6830
6831/*
6832 * conninfo_uri_parse_options
6833 * Actual URI parser.
6834 *
6835 * If successful, returns true while the options array is filled with parsed
6836 * options from the URI.
6837 * If not successful, returns false and fills errorMessage accordingly.
6838 *
6839 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
6840 * 3986):
6841 *
6842 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
6843 *
6844 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
6845 * by literal square brackets. As an extension, we also allow multiple
6846 * netloc[:port] specifications, separated by commas:
6847 *
6848 * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
6849 *
6850 * Any of the URI parts might use percent-encoding (%xy).
6851 */
6852static bool
6854 PQExpBuffer errorMessage)
6855{
6856 int prefix_len;
6857 char *p;
6858 char *buf = NULL;
6859 char *start;
6860 char prevchar = '\0';
6861 char *user = NULL;
6862 char *host = NULL;
6863 bool retval = false;
6864 PQExpBufferData hostbuf;
6865 PQExpBufferData portbuf;
6866
6867 initPQExpBuffer(&hostbuf);
6868 initPQExpBuffer(&portbuf);
6869 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6870 {
6871 libpq_append_error(errorMessage, "out of memory");
6872 goto cleanup;
6873 }
6874
6875 /* need a modifiable copy of the input URI */
6876 buf = strdup(uri);
6877 if (buf == NULL)
6878 {
6879 libpq_append_error(errorMessage, "out of memory");
6880 goto cleanup;
6881 }
6882 start = buf;
6883
6884 /* Skip the URI prefix */
6885 prefix_len = uri_prefix_length(uri);
6886 if (prefix_len == 0)
6887 {
6888 /* Should never happen */
6889 libpq_append_error(errorMessage,
6890 "invalid URI propagated to internal parser routine: \"%s\"",
6891 uri);
6892 goto cleanup;
6893 }
6894 start += prefix_len;
6895 p = start;
6896
6897 /* Look ahead for possible user credentials designator */
6898 while (*p && *p != '@' && *p != '/')
6899 ++p;
6900 if (*p == '@')
6901 {
6902 /*
6903 * Found username/password designator, so URI should be of the form
6904 * "scheme://user[:password]@[netloc]".
6905 */
6906 user = start;
6907
6908 p = user;
6909 while (*p != ':' && *p != '@')
6910 ++p;
6911
6912 /* Save last char and cut off at end of user name */
6913 prevchar = *p;
6914 *p = '\0';
6915
6916 if (*user &&
6917 !conninfo_storeval(options, "user", user,
6918 errorMessage, false, true))
6919 goto cleanup;
6920
6921 if (prevchar == ':')
6922 {
6923 const char *password = p + 1;
6924
6925 while (*p != '@')
6926 ++p;
6927 *p = '\0';
6928
6929 if (*password &&
6930 !conninfo_storeval(options, "password", password,
6931 errorMessage, false, true))
6932 goto cleanup;
6933 }
6934
6935 /* Advance past end of parsed user name or password token */
6936 ++p;
6937 }
6938 else
6939 {
6940 /*
6941 * No username/password designator found. Reset to start of URI.
6942 */
6943 p = start;
6944 }
6945
6946 /*
6947 * There may be multiple netloc[:port] pairs, each separated from the next
6948 * by a comma. When we initially enter this loop, "p" has been
6949 * incremented past optional URI credential information at this point and
6950 * now points at the "netloc" part of the URI. On subsequent loop
6951 * iterations, "p" has been incremented past the comma separator and now
6952 * points at the start of the next "netloc".
6953 */
6954 for (;;)
6955 {
6956 /*
6957 * Look for IPv6 address.
6958 */
6959 if (*p == '[')
6960 {
6961 host = ++p;
6962 while (*p && *p != ']')
6963 ++p;
6964 if (!*p)
6965 {
6966 libpq_append_error(errorMessage,
6967 "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
6968 uri);
6969 goto cleanup;
6970 }
6971 if (p == host)
6972 {
6973 libpq_append_error(errorMessage,
6974 "IPv6 host address may not be empty in URI: \"%s\"",
6975 uri);
6976 goto cleanup;
6977 }
6978
6979 /* Cut off the bracket and advance */
6980 *(p++) = '\0';
6981
6982 /*
6983 * The address may be followed by a port specifier or a slash or a
6984 * query or a separator comma.
6985 */
6986 if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6987 {
6988 libpq_append_error(errorMessage,
6989 "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
6990 *p, (int) (p - buf + 1), uri);
6991 goto cleanup;
6992 }
6993 }
6994 else
6995 {
6996 /* not an IPv6 address: DNS-named or IPv4 netloc */
6997 host = p;
6998
6999 /*
7000 * Look for port specifier (colon) or end of host specifier
7001 * (slash) or query (question mark) or host separator (comma).
7002 */
7003 while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
7004 ++p;
7005 }
7006
7007 /* Save the hostname terminator before we null it */
7008 prevchar = *p;
7009 *p = '\0';
7010
7011 appendPQExpBufferStr(&hostbuf, host);
7012
7013 if (prevchar == ':')
7014 {
7015 const char *port = ++p; /* advance past host terminator */
7016
7017 while (*p && *p != '/' && *p != '?' && *p != ',')
7018 ++p;
7019
7020 prevchar = *p;
7021 *p = '\0';
7022
7023 appendPQExpBufferStr(&portbuf, port);
7024 }
7025
7026 if (prevchar != ',')
7027 break;
7028 ++p; /* advance past comma separator */
7029 appendPQExpBufferChar(&hostbuf, ',');
7030 appendPQExpBufferChar(&portbuf, ',');
7031 }
7032
7033 /* Save final values for host and port. */
7034 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
7035 goto cleanup;
7036 if (hostbuf.data[0] &&
7037 !conninfo_storeval(options, "host", hostbuf.data,
7038 errorMessage, false, true))
7039 goto cleanup;
7040 if (portbuf.data[0] &&
7041 !conninfo_storeval(options, "port", portbuf.data,
7042 errorMessage, false, true))
7043 goto cleanup;
7044
7045 if (prevchar && prevchar != '?')
7046 {
7047 const char *dbname = ++p; /* advance past host terminator */
7048
7049 /* Look for query parameters */
7050 while (*p && *p != '?')
7051 ++p;
7052
7053 prevchar = *p;
7054 *p = '\0';
7055
7056 /*
7057 * Avoid setting dbname to an empty string, as it forces the default
7058 * value (username) and ignores $PGDATABASE, as opposed to not setting
7059 * it at all.
7060 */
7061 if (*dbname &&
7062 !conninfo_storeval(options, "dbname", dbname,
7063 errorMessage, false, true))
7064 goto cleanup;
7065 }
7066
7067 if (prevchar)
7068 {
7069 ++p; /* advance past terminator */
7070
7071 if (!conninfo_uri_parse_params(p, options, errorMessage))
7072 goto cleanup;
7073 }
7074
7075 /* everything parsed okay */
7076 retval = true;
7077
7078cleanup:
7079 termPQExpBuffer(&hostbuf);
7080 termPQExpBuffer(&portbuf);
7081 free(buf);
7082 return retval;
7083}
7084
7085/*
7086 * Connection URI parameters parser routine
7087 *
7088 * If successful, returns true while connOptions is filled with parsed
7089 * parameters. Otherwise, returns false and fills errorMessage appropriately.
7090 *
7091 * Destructively modifies 'params' buffer.
7092 */
7093static bool
7095 PQconninfoOption *connOptions,
7096 PQExpBuffer errorMessage)
7097{
7098 while (*params)
7099 {
7100 char *keyword = params;
7101 char *value = NULL;
7102 char *p = params;
7103 bool malloced = false;
7104 int oldmsglen;
7105
7106 /*
7107 * Scan the params string for '=' and '&', marking the end of keyword
7108 * and value respectively.
7109 */
7110 for (;;)
7111 {
7112 if (*p == '=')
7113 {
7114 /* Was there '=' already? */
7115 if (value != NULL)
7116 {
7117 libpq_append_error(errorMessage,
7118 "extra key/value separator \"=\" in URI query parameter: \"%s\"",
7119 keyword);
7120 return false;
7121 }
7122 /* Cut off keyword, advance to value */
7123 *p++ = '\0';
7124 value = p;
7125 }
7126 else if (*p == '&' || *p == '\0')
7127 {
7128 /*
7129 * If not at the end, cut off value and advance; leave p
7130 * pointing to start of the next parameter, if any.
7131 */
7132 if (*p != '\0')
7133 *p++ = '\0';
7134 /* Was there '=' at all? */
7135 if (value == NULL)
7136 {
7137 libpq_append_error(errorMessage,
7138 "missing key/value separator \"=\" in URI query parameter: \"%s\"",
7139 keyword);
7140 return false;
7141 }
7142 /* Got keyword and value, go process them. */
7143 break;
7144 }
7145 else
7146 ++p; /* Advance over all other bytes. */
7147 }
7148
7149 keyword = conninfo_uri_decode(keyword, errorMessage);
7150 if (keyword == NULL)
7151 {
7152 /* conninfo_uri_decode already set an error message */
7153 return false;
7154 }
7155 value = conninfo_uri_decode(value, errorMessage);
7156 if (value == NULL)
7157 {
7158 /* conninfo_uri_decode already set an error message */
7159 free(keyword);
7160 return false;
7161 }
7162 malloced = true;
7163
7164 /*
7165 * Special keyword handling for improved JDBC compatibility.
7166 */
7167 if (strcmp(keyword, "ssl") == 0 &&
7168 strcmp(value, "true") == 0)
7169 {
7170 free(keyword);
7171 free(value);
7172 malloced = false;
7173
7174 keyword = "sslmode";
7175 value = "require";
7176 }
7177
7178 /*
7179 * Store the value if the corresponding option exists; ignore
7180 * otherwise. At this point both keyword and value are not
7181 * URI-encoded.
7182 */
7183 oldmsglen = errorMessage->len;
7184 if (!conninfo_storeval(connOptions, keyword, value,
7185 errorMessage, true, false))
7186 {
7187 /* Insert generic message if conninfo_storeval didn't give one. */
7188 if (errorMessage->len == oldmsglen)
7189 libpq_append_error(errorMessage,
7190 "invalid URI query parameter: \"%s\"",
7191 keyword);
7192 /* And fail. */
7193 if (malloced)
7194 {
7195 free(keyword);
7196 free(value);
7197 }
7198 return false;
7199 }
7200
7201 if (malloced)
7202 {
7203 free(keyword);
7204 free(value);
7205 }
7206
7207 /* Proceed to next key=value pair, if any */
7208 params = p;
7209 }
7210
7211 return true;
7212}
7213
7214/*
7215 * Connection URI decoder routine
7216 *
7217 * If successful, returns the malloc'd decoded string.
7218 * If not successful, returns NULL and fills errorMessage accordingly.
7219 *
7220 * The string is decoded by replacing any percent-encoded tokens with
7221 * corresponding characters, while preserving any non-encoded characters. A
7222 * percent-encoded token is a character triplet: a percent sign, followed by a
7223 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
7224 * treated identically.
7225 */
7226static char *
7227conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
7228{
7229 char *buf; /* result */
7230 char *p; /* output location */
7231 const char *q = str; /* input location */
7232
7233 buf = malloc(strlen(str) + 1);
7234 if (buf == NULL)
7235 {
7236 libpq_append_error(errorMessage, "out of memory");
7237 return NULL;
7238 }
7239 p = buf;
7240
7241 /* skip leading whitespaces */
7242 for (const char *s = q; *s == ' '; s++)
7243 {
7244 q++;
7245 continue;
7246 }
7247
7248 for (;;)
7249 {
7250 if (*q != '%')
7251 {
7252 /* if found a whitespace or NUL, the string ends */
7253 if (*q == ' ' || *q == '\0')
7254 goto end;
7255
7256 /* copy character */
7257 *(p++) = *(q++);
7258 }
7259 else
7260 {
7261 int hi;
7262 int lo;
7263 int c;
7264
7265 ++q; /* skip the percent sign itself */
7266
7267 /*
7268 * Possible EOL will be caught by the first call to
7269 * get_hexdigit(), so we never dereference an invalid q pointer.
7270 */
7271 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
7272 {
7273 libpq_append_error(errorMessage,
7274 "invalid percent-encoded token: \"%s\"",
7275 str);
7276 free(buf);
7277 return NULL;
7278 }
7279
7280 c = (hi << 4) | lo;
7281 if (c == 0)
7282 {
7283 libpq_append_error(errorMessage,
7284 "forbidden value %%00 in percent-encoded value: \"%s\"",
7285 str);
7286 free(buf);
7287 return NULL;
7288 }
7289 *(p++) = c;
7290 }
7291 }
7292
7293end:
7294
7295 /* skip trailing whitespaces */
7296 for (const char *s = q; *s == ' '; s++)
7297 {
7298 q++;
7299 continue;
7300 }
7301
7302 /* Not at the end of the string yet? Fail. */
7303 if (*q != '\0')
7304 {
7305 libpq_append_error(errorMessage,
7306 "unexpected spaces found in \"%s\", use percent-encoded spaces (%%20) instead",
7307 str);
7308 free(buf);
7309 return NULL;
7310 }
7311
7312 /* Copy NUL terminator */
7313 *p = '\0';
7314
7315 return buf;
7316}
7317
7318/*
7319 * Convert hexadecimal digit character to its integer value.
7320 *
7321 * If successful, returns true and value is filled with digit's base 16 value.
7322 * If not successful, returns false.
7323 *
7324 * Lower- and upper-case letters in the range A-F are treated identically.
7325 */
7326static bool
7327get_hexdigit(char digit, int *value)
7328{
7329 if ('0' <= digit && digit <= '9')
7330 *value = digit - '0';
7331 else if ('A' <= digit && digit <= 'F')
7332 *value = digit - 'A' + 10;
7333 else if ('a' <= digit && digit <= 'f')
7334 *value = digit - 'a' + 10;
7335 else
7336 return false;
7337
7338 return true;
7339}
7340
7341/*
7342 * Find an option value corresponding to the keyword in the connOptions array.
7343 *
7344 * If successful, returns a pointer to the corresponding option's value.
7345 * If not successful, returns NULL.
7346 */
7347static const char *
7349 const char *keyword)
7350{
7352
7353 option = conninfo_find(connOptions, keyword);
7354
7355 return option ? option->val : NULL;
7356}
7357
7358/*
7359 * Store a (new) value for an option corresponding to the keyword in
7360 * connOptions array.
7361 *
7362 * If uri_decode is true, the value is URI-decoded. The keyword is always
7363 * assumed to be non URI-encoded.
7364 *
7365 * If successful, returns a pointer to the corresponding PQconninfoOption,
7366 * which value is replaced with a strdup'd copy of the passed value string.
7367 * The existing value for the option is free'd before replacing, if any.
7368 *
7369 * If not successful, returns NULL and fills errorMessage accordingly.
7370 * However, if the reason of failure is an invalid keyword being passed and
7371 * ignoreMissing is true, errorMessage will be left untouched.
7372 */
7373static PQconninfoOption *
7375 const char *keyword, const char *value,
7376 PQExpBuffer errorMessage, bool ignoreMissing,
7377 bool uri_decode)
7378{
7380 char *value_copy;
7381
7382 /*
7383 * For backwards compatibility, requiressl=1 gets translated to
7384 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
7385 * (which is the default for sslmode).
7386 */
7387 if (strcmp(keyword, "requiressl") == 0)
7388 {
7389 keyword = "sslmode";
7390 if (value[0] == '1')
7391 value = "require";
7392 else
7393 value = "prefer";
7394 }
7395
7396 option = conninfo_find(connOptions, keyword);
7397 if (option == NULL)
7398 {
7399 if (!ignoreMissing)
7400 libpq_append_error(errorMessage,
7401 "invalid connection option \"%s\"",
7402 keyword);
7403 return NULL;
7404 }
7405
7406 if (uri_decode)
7407 {
7408 value_copy = conninfo_uri_decode(value, errorMessage);
7409 if (value_copy == NULL)
7410 /* conninfo_uri_decode already set an error message */
7411 return NULL;
7412 }
7413 else
7414 {
7415 value_copy = strdup(value);
7416 if (value_copy == NULL)
7417 {
7418 libpq_append_error(errorMessage, "out of memory");
7419 return NULL;
7420 }
7421 }
7422
7423 free(option->val);
7424 option->val = value_copy;
7425
7426 return option;
7427}
7428
7429/*
7430 * Find a PQconninfoOption option corresponding to the keyword in the
7431 * connOptions array.
7432 *
7433 * If successful, returns a pointer to the corresponding PQconninfoOption
7434 * structure.
7435 * If not successful, returns NULL.
7436 */
7437static PQconninfoOption *
7438conninfo_find(PQconninfoOption *connOptions, const char *keyword)
7439{
7441
7442 for (option = connOptions; option->keyword != NULL; option++)
7443 {
7444 if (strcmp(option->keyword, keyword) == 0)
7445 return option;
7446 }
7447
7448 return NULL;
7449}
7450
7451
7452/*
7453 * Return the connection options used for the connection
7454 */
7457{
7458 PQExpBufferData errorBuf;
7459 PQconninfoOption *connOptions;
7460
7461 if (conn == NULL)
7462 return NULL;
7463
7464 /*
7465 * We don't actually report any errors here, but callees want a buffer,
7466 * and we prefer not to trash the conn's errorMessage.
7467 */
7468 initPQExpBuffer(&errorBuf);
7469 if (PQExpBufferDataBroken(errorBuf))
7470 return NULL; /* out of memory already :-( */
7471
7472 connOptions = conninfo_init(&errorBuf);
7473
7474 if (connOptions != NULL)
7475 {
7477
7478 for (option = PQconninfoOptions; option->keyword; option++)
7479 {
7480 char **connmember;
7481
7482 if (option->connofs < 0)
7483 continue;
7484
7485 connmember = (char **) ((char *) conn + option->connofs);
7486
7487 if (*connmember)
7488 conninfo_storeval(connOptions, option->keyword, *connmember,
7489 &errorBuf, true, false);
7490 }
7491 }
7492
7493 termPQExpBuffer(&errorBuf);
7494
7495 return connOptions;
7496}
7497
7498
7499void
7501{
7502 if (connOptions == NULL)
7503 return;
7504
7505 for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
7506 free(option->val);
7507 free(connOptions);
7508}
7509
7510
7511/* =========== accessor functions for PGconn ========= */
7512char *
7514{
7515 if (!conn)
7516 return NULL;
7517 return conn->dbName;
7518}
7519
7520char *
7522{
7523 if (!conn)
7524 return NULL;
7525 return conn->pguser;
7526}
7527
7528char *
7530{
7531 char *password = NULL;
7532
7533 if (!conn)
7534 return NULL;
7535 if (conn->connhost != NULL)
7537 if (password == NULL)
7538 password = conn->pgpass;
7539 /* Historically we've returned "" not NULL for no password specified */
7540 if (password == NULL)
7541 password = "";
7542 return password;
7543}
7544
7545char *
7547{
7548 if (!conn)
7549 return NULL;
7550
7551 if (conn->connhost != NULL)
7552 {
7553 /*
7554 * Return the verbatim host value provided by user, or hostaddr in its
7555 * lack.
7556 */
7557 if (conn->connhost[conn->whichhost].host != NULL &&
7558 conn->connhost[conn->whichhost].host[0] != '\0')
7559 return conn->connhost[conn->whichhost].host;
7560 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
7561 conn->connhost[conn->whichhost].hostaddr[0] != '\0')
7563 }
7564
7565 return "";
7566}
7567
7568char *
7570{
7571 if (!conn)
7572 return NULL;
7573
7574 /* Return the parsed IP address */
7575 if (conn->connhost != NULL && conn->connip != NULL)
7576 return conn->connip;
7577
7578 return "";
7579}
7580
7581char *
7583{
7584 if (!conn)
7585 return NULL;
7586
7587 if (conn->connhost != NULL &&
7588 conn->connhost[conn->whichhost].port != NULL &&
7589 conn->connhost[conn->whichhost].port[0] != '\0')
7590 return conn->connhost[conn->whichhost].port;
7591
7592 return DEF_PGPORT_STR;
7593}
7594
7595/*
7596 * No longer does anything, but the function remains for API backwards
7597 * compatibility.
7598 */
7599char *
7601{
7602 if (!conn)
7603 return NULL;
7604 return "";
7605}
7606
7607char *
7609{
7610 if (!conn)
7611 return NULL;
7612 return conn->pgoptions;
7613}
7614
7617{
7618 if (!conn)
7619 return CONNECTION_BAD;
7620 return conn->status;
7621}
7622
7625{
7626 if (!conn || conn->status != CONNECTION_OK)
7627 return PQTRANS_UNKNOWN;
7629 return PQTRANS_ACTIVE;
7630 return conn->xactStatus;
7631}
7632
7633const char *
7634PQparameterStatus(const PGconn *conn, const char *paramName)
7635{
7636 const pgParameterStatus *pstatus;
7637
7638 if (!conn || !paramName)
7639 return NULL;
7640 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
7641 {
7642 if (strcmp(pstatus->name, paramName) == 0)
7643 return pstatus->value;
7644 }
7645 return NULL;
7646}
7647
7648int
7650{
7651 if (!conn)
7652 return 0;
7653 if (conn->status == CONNECTION_BAD)
7654 return 0;
7656}
7657
7658int
7660{
7661 if (!conn)
7662 return 0;
7663 if (conn->status == CONNECTION_BAD)
7664 return 0;
7666}
7667
7668int
7670{
7671 if (!conn)
7672 return 0;
7673 if (conn->status == CONNECTION_BAD)
7674 return 0;
7675 return conn->sversion;
7676}
7677
7678char *
7680{
7681 if (!conn)
7682 return libpq_gettext("connection pointer is NULL\n");
7683
7684 /*
7685 * The errorMessage buffer might be marked "broken" due to having
7686 * previously failed to allocate enough memory for the message. In that
7687 * case, tell the application we ran out of memory.
7688 */
7690 return libpq_gettext("out of memory\n");
7691
7692 return conn->errorMessage.data;
7693}
7694
7695/*
7696 * In Windows, socket values are unsigned, and an invalid socket value
7697 * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
7698 * warning). Ideally we would return an unsigned value for PQsocket() on
7699 * Windows, but that would cause the function's return value to differ from
7700 * Unix, so we just return -1 for invalid sockets.
7701 * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
7702 * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
7703 */
7704int
7706{
7707 if (!conn)
7708 return -1;
7710 return conn->altsock;
7711 return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
7712}
7713
7714int
7716{
7717 if (!conn || conn->status != CONNECTION_OK)
7718 return 0;
7719 return conn->be_pid;
7720}
7721
7724{
7725 if (!conn)
7726 return PQ_PIPELINE_OFF;
7727
7728 return conn->pipelineStatus;
7729}
7730
7731int
7733{
7734 char *password;
7735
7736 if (!conn)
7737 return false;
7738 password = PQpass(conn);
7739 if (conn->password_needed &&
7740 (password == NULL || password[0] == '\0'))
7741 return true;
7742 else
7743 return false;
7744}
7745
7746int
7748{
7749 if (!conn)
7750 return false;
7751 if (conn->password_needed)
7752 return true;
7753 else
7754 return false;
7755}
7756
7757int
7759{
7760 if (!conn)
7761 return false;
7762 if (conn->gssapi_used)
7763 return true;
7764 else
7765 return false;
7766}
7767
7768int
7770{
7771 if (!conn || conn->status != CONNECTION_OK)
7772 return -1;
7773 return conn->client_encoding;
7774}
7775
7776int
7778{
7779 char qbuf[128];
7780 static const char query[] = "set client_encoding to '%s'";
7781 PGresult *res;
7782 int status;
7783
7784 if (!conn || conn->status != CONNECTION_OK)
7785 return -1;
7786
7787 if (!encoding)
7788 return -1;
7789
7790 /* Resolve special "auto" value from the locale */
7791 if (strcmp(encoding, "auto") == 0)
7793
7794 /* check query buffer overflow */
7795 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
7796 return -1;
7797
7798 /* ok, now send a query */
7799 sprintf(qbuf, query, encoding);
7800 res = PQexec(conn, qbuf);
7801
7802 if (res == NULL)
7803 return -1;
7804 if (res->resultStatus != PGRES_COMMAND_OK)
7805 status = -1;
7806 else
7807 {
7808 /*
7809 * We rely on the backend to report the parameter value, and we'll
7810 * change state at that time.
7811 */
7812 status = 0; /* everything is ok */
7813 }
7814 PQclear(res);
7815 return status;
7816}
7817
7820{
7821 PGVerbosity old;
7822
7823 if (!conn)
7824 return PQERRORS_DEFAULT;
7825 old = conn->verbosity;
7826 conn->verbosity = verbosity;
7827 return old;
7828}
7829
7832{
7834
7835 if (!conn)
7836 return PQSHOW_CONTEXT_ERRORS;
7837 old = conn->show_context;
7838 conn->show_context = show_context;
7839 return old;
7840}
7841
7844{
7845 PQnoticeReceiver old;
7846
7847 if (conn == NULL)
7848 return NULL;
7849
7850 old = conn->noticeHooks.noticeRec;
7851 if (proc)
7852 {
7853 conn->noticeHooks.noticeRec = proc;
7855 }
7856 return old;
7857}
7858
7861{
7863
7864 if (conn == NULL)
7865 return NULL;
7866
7868 if (proc)
7869 {
7870 conn->noticeHooks.noticeProc = proc;
7872 }
7873 return old;
7874}
7875
7876/*
7877 * The default notice message receiver just gets the standard notice text
7878 * and sends it to the notice processor. This two-level setup exists
7879 * mostly for backwards compatibility; perhaps we should deprecate use of
7880 * PQsetNoticeProcessor?
7881 */
7882static void
7884{
7885 (void) arg; /* not used */
7886 if (res->noticeHooks.noticeProc != NULL)
7889}
7890
7891/*
7892 * The default notice message processor just prints the
7893 * message on stderr. Applications can override this if they
7894 * want the messages to go elsewhere (a window, for example).
7895 * Note that simply discarding notices is probably a bad idea.
7896 */
7897static void
7898defaultNoticeProcessor(void *arg, const char *message)
7899{
7900 (void) arg; /* not used */
7901 /* Note: we expect the supplied string to end with a newline already. */
7902 fprintf(stderr, "%s", message);
7903}
7904
7905/*
7906 * returns a pointer to the next token or NULL if the current
7907 * token doesn't match
7908 */
7909static char *
7910pwdfMatchesString(char *buf, const char *token)
7911{
7912 char *tbuf;
7913 const char *ttok;
7914 bool bslash = false;
7915
7916 if (buf == NULL || token == NULL)
7917 return NULL;
7918 tbuf = buf;
7919 ttok = token;
7920 if (tbuf[0] == '*' && tbuf[1] == ':')
7921 return tbuf + 2;
7922 while (*tbuf != 0)
7923 {
7924 if (*tbuf == '\\' && !bslash)
7925 {
7926 tbuf++;
7927 bslash = true;
7928 }
7929 if (*tbuf == ':' && *ttok == 0 && !bslash)
7930 return tbuf + 1;
7931 bslash = false;
7932 if (*ttok == 0)
7933 return NULL;
7934 if (*tbuf == *ttok)
7935 {
7936 tbuf++;
7937 ttok++;
7938 }
7939 else
7940 return NULL;
7941 }
7942 return NULL;
7943}
7944
7945/* Get a password from the password file. Return value is malloc'd. */
7946static char *
7947passwordFromFile(const char *hostname, const char *port, const char *dbname,
7948 const char *username, const char *pgpassfile)
7949{
7950 FILE *fp;
7951#ifndef WIN32
7952 struct stat stat_buf;
7953#endif
7955
7956 if (dbname == NULL || dbname[0] == '\0')
7957 return NULL;
7958
7959 if (username == NULL || username[0] == '\0')
7960 return NULL;
7961
7962 /* 'localhost' matches pghost of '' or the default socket directory */
7963 if (hostname == NULL || hostname[0] == '\0')
7965 else if (is_unixsock_path(hostname))
7966
7967 /*
7968 * We should probably use canonicalize_path(), but then we have to
7969 * bring path.c into libpq, and it doesn't seem worth it.
7970 */
7971 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
7973
7974 if (port == NULL || port[0] == '\0')
7975 port = DEF_PGPORT_STR;
7976
7977 /* If password file cannot be opened, ignore it. */
7978 fp = fopen(pgpassfile, "r");
7979 if (fp == NULL)
7980 return NULL;
7981
7982#ifndef WIN32
7983 if (fstat(fileno(fp), &stat_buf) != 0)
7984 {
7985 fclose(fp);
7986 return NULL;
7987 }
7988
7989 if (!S_ISREG(stat_buf.st_mode))
7990 {
7991 fprintf(stderr,
7992 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
7993 pgpassfile);
7994 fclose(fp);
7995 return NULL;
7996 }
7997
7998 /* If password file is insecure, alert the user and ignore it. */
7999 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
8000 {
8001 fprintf(stderr,
8002 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
8003 pgpassfile);
8004 fclose(fp);
8005 return NULL;
8006 }
8007#else
8008
8009 /*
8010 * On Win32, the directory is protected, so we don't have to check the
8011 * file.
8012 */
8013#endif
8014
8015 /* Use an expansible buffer to accommodate any reasonable line length */
8017
8018 while (!feof(fp) && !ferror(fp))
8019 {
8020 /* Make sure there's a reasonable amount of room in the buffer */
8021 if (!enlargePQExpBuffer(&buf, 128))
8022 break;
8023
8024 /* Read some data, appending it to what we already have */
8025 if (fgets(buf.data + buf.len, buf.maxlen - buf.len, fp) == NULL)
8026 break;
8027 buf.len += strlen(buf.data + buf.len);
8028
8029 /* If we don't yet have a whole line, loop around to read more */
8030 if (!(buf.len > 0 && buf.data[buf.len - 1] == '\n') && !feof(fp))
8031 continue;
8032
8033 /* ignore comments */
8034 if (buf.data[0] != '#')
8035 {
8036 char *t = buf.data;
8037 int len;
8038
8039 /* strip trailing newline and carriage return */
8040 len = pg_strip_crlf(t);
8041
8042 if (len > 0 &&
8043 (t = pwdfMatchesString(t, hostname)) != NULL &&
8044 (t = pwdfMatchesString(t, port)) != NULL &&
8045 (t = pwdfMatchesString(t, dbname)) != NULL &&
8046 (t = pwdfMatchesString(t, username)) != NULL)
8047 {
8048 /* Found a match. */
8049 char *ret,
8050 *p1,
8051 *p2;
8052
8053 ret = strdup(t);
8054
8055 fclose(fp);
8056 explicit_bzero(buf.data, buf.maxlen);
8058
8059 if (!ret)
8060 {
8061 /* Out of memory. XXX: an error message would be nice. */
8062 return NULL;
8063 }
8064
8065 /* De-escape password. */
8066 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
8067 {
8068 if (*p1 == '\\' && p1[1] != '\0')
8069 ++p1;
8070 *p2 = *p1;
8071 }
8072 *p2 = '\0';
8073
8074 return ret;
8075 }
8076 }
8077
8078 /* No match, reset buffer to prepare for next line. */
8079 buf.len = 0;
8080 }
8081
8082 fclose(fp);
8083 explicit_bzero(buf.data, buf.maxlen);
8085 return NULL;
8086}
8087
8088
8089/*
8090 * If the connection failed due to bad password, we should mention
8091 * if we got the password from the pgpassfile.
8092 */
8093static void
8095{
8096 /* If it was 'invalid authorization', add pgpassfile mention */
8097 /* only works with >= 9.0 servers */
8098 if (conn->password_needed &&
8099 conn->connhost[conn->whichhost].password != NULL &&
8100 conn->result)
8101 {
8102 const char *sqlstate = PQresultErrorField(conn->result,
8104
8105 if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
8106 libpq_append_conn_error(conn, "password retrieved from file \"%s\"",
8107 conn->pgpassfile);
8108 }
8109}
8110
8111/*
8112 * Check if the SSL protocol value given in input is valid or not.
8113 * This is used as a sanity check routine for the connection parameters
8114 * ssl_min_protocol_version and ssl_max_protocol_version.
8115 */
8116static bool
8117sslVerifyProtocolVersion(const char *version)
8118{
8119 /*
8120 * An empty string and a NULL value are considered valid as it is
8121 * equivalent to ignoring the parameter.
8122 */
8123 if (!version || strlen(version) == 0)
8124 return true;
8125
8126 if (pg_strcasecmp(version, "TLSv1") == 0 ||
8127 pg_strcasecmp(version, "TLSv1.1") == 0 ||
8128 pg_strcasecmp(version, "TLSv1.2") == 0 ||
8129 pg_strcasecmp(version, "TLSv1.3") == 0)
8130 return true;
8131
8132 /* anything else is wrong */
8133 return false;
8134}
8135
8136
8137/*
8138 * Ensure that the SSL protocol range given in input is correct. The check
8139 * is performed on the input string to keep it TLS backend agnostic. Input
8140 * to this function is expected verified with sslVerifyProtocolVersion().
8141 */
8142static bool
8143sslVerifyProtocolRange(const char *min, const char *max)
8144{
8147
8148 /* If at least one of the bounds is not set, the range is valid */
8149 if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
8150 return true;
8151
8152 /*
8153 * If the minimum version is the lowest one we accept, then all options
8154 * for the maximum are valid.
8155 */
8156 if (pg_strcasecmp(min, "TLSv1") == 0)
8157 return true;
8158
8159 /*
8160 * The minimum bound is valid, and cannot be TLSv1, so using TLSv1 for the
8161 * maximum is incorrect.
8162 */
8163 if (pg_strcasecmp(max, "TLSv1") == 0)
8164 return false;
8165
8166 /*
8167 * At this point we know that we have a mix of TLSv1.1 through 1.3
8168 * versions.
8169 */
8170 if (pg_strcasecmp(min, max) > 0)
8171 return false;
8172
8173 return true;
8174}
8175
8176
8177/*
8178 * Obtain user's home directory, return in given buffer
8179 *
8180 * On Unix, this actually returns the user's home directory. On Windows
8181 * it returns the PostgreSQL-specific application data folder.
8182 *
8183 * This is essentially the same as get_home_path(), but we don't use that
8184 * because we don't want to pull path.c into libpq (it pollutes application
8185 * namespace).
8186 *
8187 * Returns true on success, false on failure to obtain the directory name.
8188 *
8189 * CAUTION: although in most situations failure is unexpected, there are users
8190 * who like to run applications in a home-directory-less environment. On
8191 * failure, you almost certainly DO NOT want to report an error. Just act as
8192 * though whatever file you were hoping to find in the home directory isn't
8193 * there (which it isn't).
8194 */
8195bool
8197{
8198#ifndef WIN32
8199 const char *home;
8200
8201 home = getenv("HOME");
8202 if (home && home[0])
8203 {
8204 strlcpy(buf, home, bufsize);
8205 return true;
8206 }
8207 else
8208 {
8209 struct passwd pwbuf;
8210 struct passwd *pw;
8211 char tmpbuf[1024];
8212 int rc;
8213
8214 rc = getpwuid_r(geteuid(), &pwbuf, tmpbuf, sizeof tmpbuf, &pw);
8215 if (rc != 0 || !pw)
8216 return false;
8217 strlcpy(buf, pw->pw_dir, bufsize);
8218 return true;
8219 }
8220#else
8221 char tmppath[MAX_PATH];
8222
8223 ZeroMemory(tmppath, sizeof(tmppath));
8224 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
8225 return false;
8226 snprintf(buf, bufsize, "%s/postgresql", tmppath);
8227 return true;
8228#endif
8229}
8230
8231/*
8232 * Parse and try to interpret "value" as an integer value, and if successful,
8233 * store it in *result, complaining if there is any trailing garbage or an
8234 * overflow. This allows any number of leading and trailing whitespaces.
8235 */
8236bool
8237pqParseIntParam(const char *value, int *result, PGconn *conn,
8238 const char *context)
8239{
8240 char *end;
8241 long numval;
8242
8243 Assert(value != NULL);
8244
8245 *result = 0;
8246
8247 /* strtol(3) skips leading whitespaces */
8248 errno = 0;
8249 numval = strtol(value, &end, 10);
8250
8251 /*
8252 * If no progress was done during the parsing or an error happened, fail.
8253 * This tests properly for overflows of the result.
8254 */
8255 if (value == end || errno != 0 || numval != (int) numval)
8256 goto error;
8257
8258 /*
8259 * Skip any trailing whitespace; if anything but whitespace remains before
8260 * the terminating character, fail
8261 */
8262 while (*end != '\0' && isspace((unsigned char) *end))
8263 end++;
8264
8265 if (*end != '\0')
8266 goto error;
8267
8268 *result = numval;
8269 return true;
8270
8271error:
8272 libpq_append_conn_error(conn, "invalid integer value \"%s\" for connection option \"%s\"",
8273 value, context);
8274 return false;
8275}
8276
8277/*
8278 * Parse and try to interpret "value" as a ProtocolVersion value, and if
8279 * successful, store it in *result.
8280 */
8281static bool
8283 const char *context)
8284{
8285 if (strcmp(value, "latest") == 0)
8286 {
8287 *result = PG_PROTOCOL_LATEST;
8288 return true;
8289 }
8290 if (strcmp(value, "3.0") == 0)
8291 {
8292 *result = PG_PROTOCOL(3, 0);
8293 return true;
8294 }
8295
8296 /* 3.1 never existed, we went straight from 3.0 to 3.2 */
8297
8298 if (strcmp(value, "3.2") == 0)
8299 {
8300 *result = PG_PROTOCOL(3, 2);
8301 return true;
8302 }
8303
8304 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
8305 context, value);
8306 return false;
8307}
8308
8309/*
8310 * To keep the API consistent, the locking stubs are always provided, even
8311 * if they are not required.
8312 *
8313 * Since we neglected to provide any error-return convention in the
8314 * pgthreadlock_t API, we can't do much except Assert upon failure of any
8315 * mutex primitive. Fortunately, such failures appear to be nonexistent in
8316 * the field.
8317 */
8318
8319static void
8321{
8322 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
8323
8324 if (acquire)
8325 {
8326 if (pthread_mutex_lock(&singlethread_lock))
8327 Assert(false);
8328 }
8329 else
8330 {
8331 if (pthread_mutex_unlock(&singlethread_lock))
8332 Assert(false);
8333 }
8334}
8335
8338{
8340
8341 if (newhandler)
8342 pg_g_threadlock = newhandler;
8343 else
8345
8346 return prev;
8347}
int pg_b64_dec_len(int srclen)
Definition: base64.c:239
int pg_b64_decode(const char *src, int len, uint8 *dst, int dstlen)
Definition: base64.c:116
int ssl_min_protocol_version
Definition: be-secure.c:60
int ssl_max_protocol_version
Definition: be-secure.c:61
static Datum values[MAXATTR]
Definition: bootstrap.c:153
static void cleanup(void)
Definition: bootstrap.c:715
#define STATUS_OK
Definition: c.h:1169
uint64_t uint64
Definition: c.h:540
uint32_t uint32
Definition: c.h:539
#define lengthof(array)
Definition: c.h:788
#define MemSet(start, val, len)
Definition: c.h:1020
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:936
#define STATUS_ERROR
Definition: c.h:1170
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
struct cursor * cur
Definition: ecpg.c:29
int errmsg(const char *fmt,...)
Definition: elog.c:1071
void err(int eval, const char *fmt,...)
Definition: err.c:43
const pg_fe_sasl_mech pg_oauth_mech
Definition: fe-auth-oauth.c:40
void pqClearOAuthToken(PGconn *conn)
const pg_fe_sasl_mech pg_scram_mech
Definition: fe-auth-scram.c:33
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn, bool *async)
Definition: fe-auth.c:1066
char * pg_fe_getauthname(PQExpBuffer errorMessage)
Definition: fe-auth.c:1344
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1286
int PQsendCancelRequest(PGconn *cancelConn)
Definition: fe-cancel.c:472
PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn)
Definition: fe-cancel.c:226
static void pqFreeCommandQueue(PGcmdQueueEntry *queue)
Definition: fe-connect.c:630
#define MAX_ERRLEN
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7669
static const char * conninfo_getval(PQconninfoOption *connOptions, const char *keyword)
Definition: fe-connect.c:7348
int PQprotocolVersion(const PGconn *conn)
Definition: fe-connect.c:7649
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:530
int PQresetStart(PGconn *conn)
Definition: fe-connect.c:5352
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:1076
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:423
#define CONNECTION_FAILED()
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1250
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:6238
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:5224
char * PQoptions(const PGconn *conn)
Definition: fe-connect.c:7608
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2571
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:6277
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:2484
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:7513
static void defaultNoticeReceiver(void *arg, const PGresult *res)
Definition: fe-connect.c:7883
static int uri_prefix_length(const char *connstr)
Definition: fe-connect.c:6297
static bool pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, const char *context)
Definition: fe-connect.c:8282
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
Definition: fe-connect.c:5171
static int parseServiceFile(const char *serviceFile, const char *service, PQconninfoOption *options, PQExpBuffer errorMessage, bool *group_found)
Definition: fe-connect.c:6001
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:2464
#define DefaultHost
Definition: fe-connect.c:119
static char * passwordFromFile(const char *hostname, const char *port, const char *dbname, const char *username, const char *pgpassfile)
Definition: fe-connect.c:7947
static bool sslVerifyProtocolRange(const char *min, const char *max)
Definition: fe-connect.c:8143
static void default_threadlock(int acquire)
Definition: fe-connect.c:8320
int PQfullProtocolVersion(const PGconn *conn)
Definition: fe-connect.c:7659
static void libpq_prng_init(PGconn *conn)
Definition: fe-connect.c:1172
void PQreset(PGconn *conn)
Definition: fe-connect.c:5319
void pqClosePGconn(PGconn *conn)
Definition: fe-connect.c:5258
bool pqGetHomeDirectory(char *buf, int bufsize)
Definition: fe-connect.c:8196
#define DefaultSSLMode
Definition: fe-connect.c:132
struct _internalPQconninfoOption internalPQconninfoOption
static const char short_uri_designator[]
Definition: fe-connect.c:450
#define DefaultGSSMode
Definition: fe-connect.c:140
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:5210
char * PQport(const PGconn *conn)
Definition: fe-connect.c:7582
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7624
static int count_comma_separated_elems(const char *input)
Definition: fe-connect.c:1113
#define DefaultOption
Definition: fe-connect.c:120
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6665
static bool select_next_encryption_method(PGconn *conn, bool have_valid_connection)
Definition: fe-connect.c:4804
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:823
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:7546
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:89
static bool conninfo_uri_parse_params(char *params, PQconninfoOption *connOptions, PQExpBuffer errorMessage)
Definition: fe-connect.c:7094
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7747
static void clear_allowed_sasl_mechs(PGconn *conn)
Definition: fe-connect.c:1219
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:7456
static char * conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
Definition: fe-connect.c:7227
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2536
static void fill_allowed_sasl_mechs(PGconn *conn)
Definition: fe-connect.c:1195
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2502
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2911
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7500
#define DefaultChannelBinding
Definition: fe-connect.c:124
bool pqParseIntParam(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:8237
static void defaultNoticeProcessor(void *arg, const char *message)
Definition: fe-connect.c:7898
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:8094
char * PQtty(const PGconn *conn)
Definition: fe-connect.c:7600
static int index_of_allowed_sasl_mech(PGconn *conn, const pg_fe_sasl_mech *mech)
Definition: fe-connect.c:1230
static PGPing internal_ping(PGconn *conn)
Definition: fe-connect.c:4879
static PQconninfoOption * conninfo_find(PQconninfoOption *connOptions, const char *keyword)
Definition: fe-connect.c:7438
static const char uri_designator[]
Definition: fe-connect.c:449
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:6216
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7634
static bool sslVerifyProtocolVersion(const char *version)
Definition: fe-connect.c:8117
#define SELECT_NEXT_METHOD(method)
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7732
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7529
PostgresPollingStatusType PQresetPoll(PGconn *conn)
Definition: fe-connect.c:5371
int PQconnectionUsedGSSAPI(const PGconn *conn)
Definition: fe-connect.c:7758
static PQconninfoOption * conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:6800
void pqReleaseConnHosts(PGconn *conn)
Definition: fe-connect.c:5141
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:2408
static bool connection_failed(PGconn *conn)
Definition: fe-connect.c:4789
pgthreadlock_t pg_g_threadlock
Definition: fe-connect.c:514
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7616
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:951
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2668
static PQconninfoOption * conninfo_array_parse(const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
Definition: fe-connect.c:6507
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7769
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:870
static PQconninfoOption * conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:6331
void PQfinish(PGconn *conn)
Definition: fe-connect.c:5305
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:656
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4943
PGPing PQping(const char *conninfo)
Definition: fe-connect.c:839
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:7831
#define DefaultLoadBalanceHosts
Definition: fe-connect.c:127
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:2349
#define DefaultSSLNegotiation
Definition: fe-connect.c:135
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
Definition: fe-connect.c:7843
PGconn * PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
Definition: fe-connect.c:2234
char * PQhostaddr(const PGconn *conn)
Definition: fe-connect.c:7569
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:7715
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:2196
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:7374
#define PGPASSFILE
Definition: fe-connect.c:78
static bool conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, PQExpBuffer errorMessage)
Definition: fe-connect.c:6853
int pqConnectDBStart(PGconn *conn)
Definition: fe-connect.c:2707
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:2375
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:7521
static void freePGconn(PGconn *conn)
Definition: fe-connect.c:5043
bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
Definition: fe-connect.c:1035
static char * pwdfMatchesString(char *buf, const char *token)
Definition: fe-connect.c:7910
PGpipelineStatus PQpipelineStatus(const PGconn *conn)
Definition: fe-connect.c:7723
static bool get_hexdigit(char digit, int *value)
Definition: fe-connect.c:7327
#define ERRCODE_INVALID_PASSWORD
Definition: fe-connect.c:92
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7819
#define SASL_MECHANISM_COUNT
Definition: fe-connect.c:446
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:7860
#define DefaultSSLCertMode
Definition: fe-connect.c:133
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:94
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:199
#define ENCRYPTION_NEGOTIATION_FAILED(msg)
static bool recognized_connection_string(const char *connstr)
Definition: fe-connect.c:6320
#define DefaultTargetSessionAttrs
Definition: fe-connect.c:126
static int parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5929
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7679
static bool init_allowed_encryption_methods(PGconn *conn)
Definition: fe-connect.c:4699
static const pg_fe_sasl_mech * supported_sasl_mechs[]
Definition: fe-connect.c:441
PGPing PQpingParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:786
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7705
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2785
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7777
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:768
static char * parse_comma_separated_list(char **startptr, bool *more)
Definition: fe-connect.c:1137
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:5413
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:997
pgthreadlock_t PQregisterThreadLock(pgthreadlock_t newhandler)
Definition: fe-connect.c:8337
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1433
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1995
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:779
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2042
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2273
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqReadData(PGconn *conn)
Definition: fe-misc.c:606
int pqFlush(PGconn *conn)
Definition: fe-misc.c:994
void pqParseDone(PGconn *conn, int newInStart)
Definition: fe-misc.c:443
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:473
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:77
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:216
int pqPutnchar(const void *s, size_t len, PGconn *conn)
Definition: fe-misc.c:202
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:351
pg_usec_time_t PQgetCurrentTimeUSec(void)
Definition: fe-misc.c:1235
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1375
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, pg_usec_time_t end_time)
Definition: fe-misc.c:1035
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:142
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:532
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:896
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:138
void pqsecure_close(PGconn *conn)
Definition: fe-secure.c:152
void pqTraceOutputCharResponse(PGconn *conn, const char *responseType, char response)
Definition: fe-trace.c:915
Assert(PointerIsAligned(start, uint64))
return str start
const char * str
#define calloc(a, b)
Definition: header.h:55
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
#define token
Definition: indent_globs.h:126
#define bufsize
Definition: indent_globs.h:36
FILE * input
long val
Definition: informix.c:689
static struct @166 value
static char * username
Definition: initdb.c:153
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
int j
Definition: isn.c:78
int i
Definition: isn.c:77
static const JsonPathKeyword keywords[]
#define PQresultErrorMessage
#define PQgetvalue
Definition: libpq-be-fe.h:253
#define PQgetResult
Definition: libpq-be-fe.h:246
#define PQclear
Definition: libpq-be-fe.h:245
#define PQresultErrorField
Definition: libpq-be-fe.h:249
#define PQresultStatus
Definition: libpq-be-fe.h:247
#define PQntuples
Definition: libpq-be-fe.h:251
@ PGEVT_CONNDESTROY
Definition: libpq-events.h:31
@ PGEVT_CONNRESET
Definition: libpq-events.h:30
ConnStatusType
Definition: libpq-fe.h:83
@ CONNECTION_CONSUME
Definition: libpq-fe.h:102
@ CONNECTION_AUTHENTICATING
Definition: libpq-fe.h:109
@ CONNECTION_CHECK_STANDBY
Definition: libpq-fe.h:106
@ CONNECTION_STARTED
Definition: libpq-fe.h:92
@ CONNECTION_AWAITING_RESPONSE
Definition: libpq-fe.h:94
@ CONNECTION_MADE
Definition: libpq-fe.h:93
@ CONNECTION_CHECK_WRITABLE
Definition: libpq-fe.h:101
@ CONNECTION_BAD
Definition: libpq-fe.h:85
@ CONNECTION_OK
Definition: libpq-fe.h:84
@ CONNECTION_GSS_STARTUP
Definition: libpq-fe.h:103
@ CONNECTION_SSL_STARTUP
Definition: libpq-fe.h:99
@ CONNECTION_AUTH_OK
Definition: libpq-fe.h:96
@ CONNECTION_CHECK_TARGET
Definition: libpq-fe.h:104
@ CONNECTION_NEEDED
Definition: libpq-fe.h:100
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:136
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:128
void(* pgthreadlock_t)(int acquire)
Definition: libpq-fe.h:468
PGPing
Definition: libpq-fe.h:175
@ PQPING_OK
Definition: libpq-fe.h:176
@ PQPING_REJECT
Definition: libpq-fe.h:177
@ PQPING_NO_RESPONSE
Definition: libpq-fe.h:178
@ PQPING_NO_ATTEMPT
Definition: libpq-fe.h:179
PGContextVisibility
Definition: libpq-fe.h:163
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:165
PGTransactionStatusType
Definition: libpq-fe.h:146
@ PQTRANS_IDLE
Definition: libpq-fe.h:147
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:148
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:151
void(* PQnoticeReceiver)(void *arg, const PGresult *res)
Definition: libpq-fe.h:241
int64_t pg_usec_time_t
Definition: libpq-fe.h:238
void(* PQnoticeProcessor)(void *arg, const char *message)
Definition: libpq-fe.h:242
PostgresPollingStatusType
Definition: libpq-fe.h:114
@ PGRES_POLLING_OK
Definition: libpq-fe.h:118
@ PGRES_POLLING_READING
Definition: libpq-fe.h:116
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:117
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:115
PGpipelineStatus
Definition: libpq-fe.h:186
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:187
PGVerbosity
Definition: libpq-fe.h:155
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:157
@ PGASYNC_IDLE
Definition: libpq-int.h:215
@ PGASYNC_BUSY
Definition: libpq-int.h:216
@ LOAD_BALANCE_DISABLE
Definition: libpq-int.h:249
@ LOAD_BALANCE_RANDOM
Definition: libpq-int.h:250
#define SOCK_STRERROR
Definition: libpq-int.h:963
#define ENC_PLAINTEXT
Definition: libpq-int.h:230
#define ENC_GSSAPI
Definition: libpq-int.h:231
#define ENC_SSL
Definition: libpq-int.h:232
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:311
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:310
@ CHT_HOST_NAME
Definition: libpq-int.h:309
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:914
#define ENC_ERROR
Definition: libpq-int.h:229
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:241
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:240
@ SERVER_TYPE_ANY
Definition: libpq-int.h:237
@ SERVER_TYPE_READ_WRITE
Definition: libpq-int.h:238
@ SERVER_TYPE_PREFER_STANDBY_PASS2
Definition: libpq-int.h:243
@ SERVER_TYPE_PREFER_STANDBY
Definition: libpq-int.h:242
@ SERVER_TYPE_READ_ONLY
Definition: libpq-int.h:239
#define SOCK_ERRNO
Definition: oauth-utils.c:164
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: oauth-utils.c:95
#define libpq_gettext(x)
Definition: oauth-utils.h:86
@ PG_BOOL_YES
Definition: oauth-utils.h:74
@ PG_BOOL_NO
Definition: oauth-utils.h:75
@ PG_BOOL_UNKNOWN
Definition: oauth-utils.h:73
void * arg
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define MAXPGPATH
#define DEFAULT_PGSOCKET_DIR
const void size_t len
int32 encoding
Definition: pg_database.h:41
static const char * connstr
Definition: pg_dumpall.c:82
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition: pg_prng.c:144
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
#define pg_prng_strong_seed(state)
Definition: pg_prng.h:46
static char ** options
static char * user
Definition: pg_regress.c:119
static int port
Definition: pg_regress.c:115
static char portstr[16]
Definition: pg_regress.c:116
static char * hostname
Definition: pg_regress.c:114
static char * buf
Definition: pg_test_fsync.c:72
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
#define pg_encoding_to_char
Definition: pg_wchar.h:630
static int64 end_time
Definition: pgbench.c:176
static const char * pghost
Definition: pgbench.c:295
static const char * pgport
Definition: pgbench.c:296
static const char * dbName
Definition: pgbench.c:298
#define PG_STRERROR_R_BUFLEN
Definition: port.h:257
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * pg_inet_net_ntop(int af, const void *src, int bits, char *dst, size_t size)
Definition: inet_net_ntop.c:77
#define sprintf
Definition: port.h:241
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
void explicit_bzero(void *buf, size_t len)
int pgsocket
Definition: port.h:29
#define snprintf
Definition: port.h:239
unsigned int socklen_t
Definition: port.h:40
#define PGINVALID_SOCKET
Definition: port.h:31
#define strerror_r
Definition: port.h:256
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:301
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
#define closesocket
Definition: port.h:377
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:87
#define PG_PROTOCOL_EARLIEST
Definition: pqcomm.h:96
#define PG_PROTOCOL_FULL(v)
Definition: pqcomm.h:89
static bool is_unixsock_path(const char *path)
Definition: pqcomm.h:67
#define PG_PROTOCOL_LATEST
Definition: pqcomm.h:97
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:44
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:60
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:173
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:172
uint32 ProtocolVersion
Definition: pqcomm.h:99
uint32 AuthRequest
Definition: pqcomm.h:121
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:90
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:172
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
char * c
e
Definition: preproc-init.c:82
#define AUTH_REQ_SSPI
Definition: protocol.h:105
#define AUTH_REQ_SASL_CONT
Definition: protocol.h:107
#define AUTH_REQ_GSS
Definition: protocol.h:103
#define AUTH_REQ_MD5
Definition: protocol.h:101
#define AUTH_REQ_OK
Definition: protocol.h:96
#define PqMsg_AuthenticationRequest
Definition: protocol.h:50
#define PqMsg_NegotiateProtocolVersion
Definition: protocol.h:59
#define AUTH_REQ_PASSWORD
Definition: protocol.h:99
#define AUTH_REQ_GSS_CONT
Definition: protocol.h:104
#define PqMsg_ErrorResponse
Definition: protocol.h:44
#define AUTH_REQ_SASL
Definition: protocol.h:106
#define PqMsg_Terminate
Definition: protocol.h:28
#define AUTH_REQ_SASL_FIN
Definition: protocol.h:108
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:60
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:42
#define PTHREAD_MUTEX_INITIALIZER
Definition: pthread-win32.h:16
#define SCRAM_MAX_KEY_LEN
Definition: scram-common.h:30
#define SCRAM_SHA_256_DEFAULT_ITERATIONS
Definition: scram-common.h:50
const char * gai_strerror(int ecode)
static void error(void)
Definition: sql-dyntest.c:147
static char * password
Definition: streamutil.c:51
char * dbname
Definition: streamutil.c:49
PGconn * conn
Definition: streamutil.c:52
int pg_strip_crlf(char *str)
Definition: string.c:154
int family
Definition: pqcomm.h:38
SockAddr addr
Definition: pqcomm.h:39
void * passThrough
Definition: libpq-int.h:159
char * name
Definition: libpq-int.h:158
PGEventProc proc
Definition: libpq-int.h:157
void * noticeProcArg
Definition: libpq-int.h:152
PQnoticeReceiver noticeRec
Definition: libpq-int.h:149
PQnoticeProcessor noticeProc
Definition: libpq-int.h:151
void * noticeRecArg
Definition: libpq-int.h:150
struct sockaddr_storage addr
Definition: pqcomm.h:32
socklen_t salen
Definition: pqcomm.h:33
struct cursor * next
Definition: type.h:148
int val
Definition: getopt_long.h:22
struct pgNotify * next
Definition: libpq-fe.h:234
struct pgParameterStatus * next
Definition: libpq-int.h:271
char * host
Definition: libpq-int.h:358
char * password
Definition: libpq-int.h:362
char * port
Definition: libpq-int.h:360
char * hostaddr
Definition: libpq-int.h:359
pg_conn_host_type type
Definition: libpq-int.h:357
SockAddr laddr
Definition: libpq-int.h:501
bool try_next_host
Definition: libpq-int.h:538
AddrInfo * addr
Definition: libpq-int.h:541
uint8 * be_cancel_key
Definition: libpq-int.h:554
char * replication
Definition: libpq-int.h:391
uint8 * scram_client_key_binary
Definition: libpq-int.h:545
char * write_err_msg
Definition: libpq-int.h:513
uint8 failed_enc_methods
Definition: libpq-int.h:607
PGnotify * notifyHead
Definition: libpq-int.h:476
char * sslrootcert
Definition: libpq-int.h:413
PGdataValue * rowBuf
Definition: libpq-int.h:584
char * sslnegotiation
Definition: libpq-int.h:407
char * sslcompression
Definition: libpq-int.h:408
char * oauth_discovery_uri
Definition: libpq-int.h:441
bool sigpipe_flag
Definition: libpq-int.h:511
char * oauth_scope
Definition: libpq-int.h:445
int nconnhost
Definition: libpq-int.h:480
char * require_auth
Definition: libpq-int.h:428
pgsocket sock
Definition: libpq-int.h:499
char * inBuffer
Definition: libpq-int.h:567
char * channel_binding
Definition: libpq-int.h:398
ProtocolVersion pversion
Definition: libpq-int.h:503
bool std_strings
Definition: libpq-int.h:557
bool write_failed
Definition: libpq-int.h:512
char * sslcrldir
Definition: libpq-int.h:415
char * gssdelegation
Definition: libpq-int.h:422
char * pgoptions
Definition: libpq-int.h:387
bool send_appname
Definition: libpq-int.h:543
PGTransactionStatusType xactStatus
Definition: libpq-int.h:464
char * sslcrl
Definition: libpq-int.h:414
char * pghost
Definition: libpq-int.h:374
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:602
size_t scram_client_key_len
Definition: libpq-int.h:544
bool cancelRequest
Definition: libpq-int.h:434
int inCursor
Definition: libpq-int.h:570
char * ssl_max_protocol_version
Definition: libpq-int.h:426
PGTernaryBool in_hot_standby
Definition: libpq-int.h:559
uint8 * scram_server_key_binary
Definition: libpq-int.h:547
void(* cleanup_async_auth)(PGconn *conn)
Definition: libpq-int.h:529
char * pgpass
Definition: libpq-int.h:396
int be_pid
Definition: libpq-int.h:552
bool client_finished_auth
Definition: libpq-int.h:521
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:496
ProtocolVersion min_pversion
Definition: libpq-int.h:548
char * dbName
Definition: libpq-int.h:390
char * oauth_client_id
Definition: libpq-int.h:443
int inEnd
Definition: libpq-int.h:571
char * oauth_issuer
Definition: libpq-int.h:439
char * fbappname
Definition: libpq-int.h:389
char * sslcert
Definition: libpq-int.h:410
char * sslcertmode
Definition: libpq-int.h:412
uint32 allowed_auth_methods
Definition: libpq-int.h:517
char * target_session_attrs
Definition: libpq-int.h:427
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:490
uint8 current_enc_method
Definition: libpq-int.h:608
PGnotify * notifyTail
Definition: libpq-int.h:477
bool auth_required
Definition: libpq-int.h:515
int inBufSize
Definition: libpq-int.h:568
int naddr
Definition: libpq-int.h:539
char * sslpassword
Definition: libpq-int.h:411
bool nonblocking
Definition: libpq-int.h:467
bool gssapi_used
Definition: libpq-int.h:509
int client_encoding
Definition: libpq-int.h:556
PQExpBufferData workBuffer
Definition: libpq-int.h:678
int inStart
Definition: libpq-int.h:569
char * keepalives_idle
Definition: libpq-int.h:401
char * connip
Definition: libpq-int.h:483
int sversion
Definition: libpq-int.h:504
char * pgservicefile
Definition: libpq-int.h:393
bool auth_req_received
Definition: libpq-int.h:507
char * oauth_client_secret
Definition: libpq-int.h:444
char * max_protocol_version
Definition: libpq-int.h:424
char * load_balance_hosts
Definition: libpq-int.h:429
bool pversion_negotiated
Definition: libpq-int.h:505
bool oauth_want_retry
Definition: libpq-int.h:447
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:558
pgParameterStatus * pstatus
Definition: libpq-int.h:555
char * pguser
Definition: libpq-int.h:395
char * keepalives
Definition: libpq-int.h:400
char * min_protocol_version
Definition: libpq-int.h:423
PGresult * result
Definition: libpq-int.h:597
bool sigpipe_so
Definition: libpq-int.h:510
PGVerbosity verbosity
Definition: libpq-int.h:560
char * client_encoding_initial
Definition: libpq-int.h:386
char * keepalives_interval
Definition: libpq-int.h:402
int whichaddr
Definition: libpq-int.h:540
char * appname
Definition: libpq-int.h:388
char * sslmode
Definition: libpq-int.h:406
pg_prng_state prng_state
Definition: libpq-int.h:563
char * pgtcp_user_timeout
Definition: libpq-int.h:385
char * ssl_min_protocol_version
Definition: libpq-int.h:425
char * oauth_issuer_id
Definition: libpq-int.h:440
PQExpBufferData errorMessage
Definition: libpq-int.h:674
char * gssencmode
Definition: libpq-int.h:418
char * scram_server_key
Definition: libpq-int.h:431
int nEvents
Definition: libpq-int.h:458
char * pghostaddr
Definition: libpq-int.h:378
char * sslkey
Definition: libpq-int.h:409
pgsocket altsock
Definition: libpq-int.h:530
char * scram_client_key
Definition: libpq-int.h:430
ProtocolVersion max_pversion
Definition: libpq-int.h:549
char * sslkeylogfile
Definition: libpq-int.h:432
int rowBufLen
Definition: libpq-int.h:585
PostgresPollingStatusType(* async_auth)(PGconn *conn)
Definition: libpq-int.h:528
char * pgpassfile
Definition: libpq-int.h:397
char last_sqlstate[6]
Definition: libpq-int.h:465
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:463
PGLoadBalanceType load_balance_type
Definition: libpq-int.h:535
char * connect_timeout
Definition: libpq-int.h:384
int scram_sha_256_iterations
Definition: libpq-int.h:604
char * krbsrvname
Definition: libpq-int.h:419
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:469
char * gsslib
Definition: libpq-int.h:420
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:562
int outBufSize
Definition: libpq-int.h:575
uint8 allowed_enc_methods
Definition: libpq-int.h:606
bool options_valid
Definition: libpq-int.h:466
PGNoticeHooks noticeHooks
Definition: libpq-int.h:454
PGTargetServerType target_server_type
Definition: libpq-int.h:534
FILE * Pfdebug
Definition: libpq-int.h:450
void * sasl_state
Definition: libpq-int.h:603
size_t scram_server_key_len
Definition: libpq-int.h:546
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:489
SockAddr raddr
Definition: libpq-int.h:502
bool try_next_addr
Definition: libpq-int.h:537
int outCount
Definition: libpq-int.h:576
char * pgport
Definition: libpq-int.h:382
int be_cancel_key_len
Definition: libpq-int.h:553
char * pgservice
Definition: libpq-int.h:392
const pg_fe_sasl_mech * allowed_sasl_mechs[2]
Definition: libpq-int.h:519
int whichhost
Definition: libpq-int.h:481
PGContextVisibility show_context
Definition: libpq-int.h:561
char * keepalives_count
Definition: libpq-int.h:404
char * requirepeer
Definition: libpq-int.h:417
char * sslsni
Definition: libpq-int.h:416
pg_conn_host * connhost
Definition: libpq-int.h:482
bool ssl_in_use
Definition: libpq-int.h:611
PGEvent * events
Definition: libpq-int.h:457
bool password_needed
Definition: libpq-int.h:508
char * outBuffer
Definition: libpq-int.h:574
ConnStatusType status
Definition: libpq-int.h:462
void(* free)(void *state)
Definition: fe-auth-sasl.h:149
PGNoticeHooks noticeHooks
Definition: libpq-int.h:183
ExecStatusType resultStatus
Definition: libpq-int.h:174
unsigned short st_mode
Definition: win32_port.h:258
Definition: regguts.h:323
char * flag(int b)
Definition: test-ctype.c:33
static StringInfoData tmpbuf
Definition: walsender.c:178
#define stat
Definition: win32_port.h:274
#define S_IRWXG
Definition: win32_port.h:300
#define EINTR
Definition: win32_port.h:364
#define EWOULDBLOCK
Definition: win32_port.h:370
#define S_IRWXO
Definition: win32_port.h:312
#define EINPROGRESS
Definition: win32_port.h:376
int gid_t
Definition: win32_port.h:235
#define fstat
Definition: win32_port.h:273
#define S_ISREG(m)
Definition: win32_port.h:318
#define socket(af, type, protocol)
Definition: win32_port.h:498
#define connect(s, name, namelen)
Definition: win32_port.h:502
int uid_t
Definition: win32_port.h:234
int gettimeofday(struct timeval *tp, void *tzp)