Debian Codegraph @

src/interfaces/libpq/fe-connect.c

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