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