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