libpq: Add pqReleaseConnHosts function
[pgsql.git] / src / interfaces / libpq / fe-connect.c
blob5add6f4ebb3b1ed0cb795f08287848a470005751
1 /*-------------------------------------------------------------------------
3 * fe-connect.c
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * src/interfaces/libpq/fe-connect.c
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <netdb.h>
22 #include <time.h>
23 #include <unistd.h>
25 #include "common/ip.h"
26 #include "common/link-canary.h"
27 #include "common/scram-common.h"
28 #include "common/string.h"
29 #include "fe-auth.h"
30 #include "libpq-fe.h"
31 #include "libpq-int.h"
32 #include "mb/pg_wchar.h"
33 #include "pg_config_paths.h"
34 #include "port/pg_bswap.h"
36 #ifdef WIN32
37 #include "win32.h"
38 #ifdef _WIN32_IE
39 #undef _WIN32_IE
40 #endif
41 #define _WIN32_IE 0x0500
42 #ifdef near
43 #undef near
44 #endif
45 #define near
46 #include <shlobj.h>
47 #include <mstcpip.h>
48 #else
49 #include <sys/socket.h>
50 #include <netdb.h>
51 #include <netinet/in.h>
52 #include <netinet/tcp.h>
53 #endif
55 #ifdef WIN32
56 #include "pthread-win32.h"
57 #else
58 #include <pthread.h>
59 #endif
61 #ifdef USE_LDAP
62 #ifdef WIN32
63 #include <winldap.h>
64 #else
65 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
66 #define LDAP_DEPRECATED 1
67 #include <ldap.h>
68 typedef struct timeval LDAP_TIMEVAL;
69 #endif
70 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
71 PQExpBuffer errorMessage);
72 #endif
74 #ifndef WIN32
75 #define PGPASSFILE ".pgpass"
76 #else
77 #define PGPASSFILE "pgpass.conf"
78 #endif
81 * Pre-9.0 servers will return this SQLSTATE if asked to set
82 * application_name in a startup packet. We hard-wire the value rather
83 * than looking into errcodes.h since it reflects historical behavior
84 * rather than that of the current code.
86 #define ERRCODE_APPNAME_UNKNOWN "42704"
88 /* This is part of the protocol so just define it */
89 #define ERRCODE_INVALID_PASSWORD "28P01"
90 /* This too */
91 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
94 * Cope with the various platform-specific ways to spell TCP keepalive socket
95 * options. This doesn't cover Windows, which as usual does its own thing.
97 #if defined(TCP_KEEPIDLE)
98 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
99 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
100 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
101 #elif defined(TCP_KEEPALIVE_THRESHOLD)
102 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
103 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
104 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
105 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
106 /* TCP_KEEPALIVE is the name of this option on macOS */
107 /* Caution: Solaris has this symbol but it means something different */
108 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
109 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
110 #endif
113 * fall back options if they are not specified by arguments or defined
114 * by environment variables
116 #define DefaultHost "localhost"
117 #define DefaultOption ""
118 #ifdef USE_SSL
119 #define DefaultChannelBinding "prefer"
120 #else
121 #define DefaultChannelBinding "disable"
122 #endif
123 #define DefaultTargetSessionAttrs "any"
124 #define DefaultLoadBalanceHosts "disable"
125 #ifdef USE_SSL
126 #define DefaultSSLMode "prefer"
127 #define DefaultSSLCertMode "allow"
128 #else
129 #define DefaultSSLMode "disable"
130 #define DefaultSSLCertMode "disable"
131 #endif
132 #ifdef ENABLE_GSS
133 #include "fe-gssapi-common.h"
134 #define DefaultGSSMode "prefer"
135 #else
136 #define DefaultGSSMode "disable"
137 #endif
139 /* ----------
140 * Definition of the conninfo parameters and their fallback resources.
142 * If Environment-Var and Compiled-in are specified as NULL, no
143 * fallback is available. If after all no value can be determined
144 * for an option, an error is returned.
146 * The value for the username is treated specially in conninfo_add_defaults.
147 * If the value is not obtained any other way, the username is determined
148 * by pg_fe_getauthname().
150 * The Label and Disp-Char entries are provided for applications that
151 * want to use PQconndefaults() to create a generic database connection
152 * dialog. Disp-Char is defined as follows:
153 * "" Normal input field
154 * "*" Password field - hide value
155 * "D" Debug option - don't show by default
157 * PQconninfoOptions[] is a constant static array that we use to initialize
158 * a dynamically allocated working copy. All the "val" fields in
159 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
160 * fields point to malloc'd strings that should be freed when the working
161 * array is freed (see PQconninfoFree).
163 * The first part of each struct is identical to the one in libpq-fe.h,
164 * which is required since we memcpy() data between the two!
165 * ----------
167 typedef struct _internalPQconninfoOption
169 char *keyword; /* The keyword of the option */
170 char *envvar; /* Fallback environment variable name */
171 char *compiled; /* Fallback compiled in default value */
172 char *val; /* Option's current value, or NULL */
173 char *label; /* Label for field in connect dialog */
174 char *dispchar; /* Indicates how to display this field in a
175 * connect dialog. Values are: "" Display
176 * entered value as is "*" Password field -
177 * hide value "D" Debug option - don't show
178 * by default */
179 int dispsize; /* Field size in characters for dialog */
180 /* ---
181 * Anything above this comment must be synchronized with
182 * PQconninfoOption in libpq-fe.h, since we memcpy() data
183 * between them!
184 * ---
186 off_t connofs; /* Offset into PGconn struct, -1 if not there */
187 } internalPQconninfoOption;
189 static const internalPQconninfoOption PQconninfoOptions[] = {
190 {"service", "PGSERVICE", NULL, NULL,
191 "Database-Service", "", 20, -1},
193 {"user", "PGUSER", NULL, NULL,
194 "Database-User", "", 20,
195 offsetof(struct pg_conn, pguser)},
197 {"password", "PGPASSWORD", NULL, NULL,
198 "Database-Password", "*", 20,
199 offsetof(struct pg_conn, pgpass)},
201 {"passfile", "PGPASSFILE", NULL, NULL,
202 "Database-Password-File", "", 64,
203 offsetof(struct pg_conn, pgpassfile)},
205 {"channel_binding", "PGCHANNELBINDING", DefaultChannelBinding, NULL,
206 "Channel-Binding", "", 8, /* sizeof("require") == 8 */
207 offsetof(struct pg_conn, channel_binding)},
209 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
210 "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
211 offsetof(struct pg_conn, connect_timeout)},
213 {"dbname", "PGDATABASE", NULL, NULL,
214 "Database-Name", "", 20,
215 offsetof(struct pg_conn, dbName)},
217 {"host", "PGHOST", NULL, NULL,
218 "Database-Host", "", 40,
219 offsetof(struct pg_conn, pghost)},
221 {"hostaddr", "PGHOSTADDR", NULL, NULL,
222 "Database-Host-IP-Address", "", 45,
223 offsetof(struct pg_conn, pghostaddr)},
225 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
226 "Database-Port", "", 6,
227 offsetof(struct pg_conn, pgport)},
229 {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
230 "Client-Encoding", "", 10,
231 offsetof(struct pg_conn, client_encoding_initial)},
233 {"options", "PGOPTIONS", DefaultOption, NULL,
234 "Backend-Options", "", 40,
235 offsetof(struct pg_conn, pgoptions)},
237 {"application_name", "PGAPPNAME", NULL, NULL,
238 "Application-Name", "", 64,
239 offsetof(struct pg_conn, appname)},
241 {"fallback_application_name", NULL, NULL, NULL,
242 "Fallback-Application-Name", "", 64,
243 offsetof(struct pg_conn, fbappname)},
245 {"keepalives", NULL, NULL, NULL,
246 "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
247 offsetof(struct pg_conn, keepalives)},
249 {"keepalives_idle", NULL, NULL, NULL,
250 "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
251 offsetof(struct pg_conn, keepalives_idle)},
253 {"keepalives_interval", NULL, NULL, NULL,
254 "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
255 offsetof(struct pg_conn, keepalives_interval)},
257 {"keepalives_count", NULL, NULL, NULL,
258 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
259 offsetof(struct pg_conn, keepalives_count)},
261 {"tcp_user_timeout", NULL, NULL, NULL,
262 "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
263 offsetof(struct pg_conn, pgtcp_user_timeout)},
266 * ssl options are allowed even without client SSL support because the
267 * client can still handle SSL modes "disable" and "allow". Other
268 * parameters have no effect on non-SSL connections, so there is no reason
269 * to exclude them since none of them are mandatory.
271 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
272 "SSL-Mode", "", 12, /* sizeof("verify-full") == 12 */
273 offsetof(struct pg_conn, sslmode)},
275 {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
276 "SSL-Compression", "", 1,
277 offsetof(struct pg_conn, sslcompression)},
279 {"sslcert", "PGSSLCERT", NULL, NULL,
280 "SSL-Client-Cert", "", 64,
281 offsetof(struct pg_conn, sslcert)},
283 {"sslkey", "PGSSLKEY", NULL, NULL,
284 "SSL-Client-Key", "", 64,
285 offsetof(struct pg_conn, sslkey)},
287 {"sslcertmode", "PGSSLCERTMODE", NULL, NULL,
288 "SSL-Client-Cert-Mode", "", 8, /* sizeof("disable") == 8 */
289 offsetof(struct pg_conn, sslcertmode)},
291 {"sslpassword", NULL, NULL, NULL,
292 "SSL-Client-Key-Password", "*", 20,
293 offsetof(struct pg_conn, sslpassword)},
295 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
296 "SSL-Root-Certificate", "", 64,
297 offsetof(struct pg_conn, sslrootcert)},
299 {"sslcrl", "PGSSLCRL", NULL, NULL,
300 "SSL-Revocation-List", "", 64,
301 offsetof(struct pg_conn, sslcrl)},
303 {"sslcrldir", "PGSSLCRLDIR", NULL, NULL,
304 "SSL-Revocation-List-Dir", "", 64,
305 offsetof(struct pg_conn, sslcrldir)},
307 {"sslsni", "PGSSLSNI", "1", NULL,
308 "SSL-SNI", "", 1,
309 offsetof(struct pg_conn, sslsni)},
311 {"requirepeer", "PGREQUIREPEER", NULL, NULL,
312 "Require-Peer", "", 10,
313 offsetof(struct pg_conn, requirepeer)},
315 {"require_auth", "PGREQUIREAUTH", NULL, NULL,
316 "Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */
317 offsetof(struct pg_conn, require_auth)},
319 {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL,
320 "SSL-Minimum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
321 offsetof(struct pg_conn, ssl_min_protocol_version)},
323 {"ssl_max_protocol_version", "PGSSLMAXPROTOCOLVERSION", NULL, NULL,
324 "SSL-Maximum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
325 offsetof(struct pg_conn, ssl_max_protocol_version)},
328 * As with SSL, all GSS options are exposed even in builds that don't have
329 * support.
331 {"gssencmode", "PGGSSENCMODE", DefaultGSSMode, NULL,
332 "GSSENC-Mode", "", 8, /* sizeof("disable") == 8 */
333 offsetof(struct pg_conn, gssencmode)},
335 /* Kerberos and GSSAPI authentication support specifying the service name */
336 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
337 "Kerberos-service-name", "", 20,
338 offsetof(struct pg_conn, krbsrvname)},
340 {"gsslib", "PGGSSLIB", NULL, NULL,
341 "GSS-library", "", 7, /* sizeof("gssapi") == 7 */
342 offsetof(struct pg_conn, gsslib)},
344 {"gssdelegation", "PGGSSDELEGATION", "0", NULL,
345 "GSS-delegation", "", 1,
346 offsetof(struct pg_conn, gssdelegation)},
348 {"replication", NULL, NULL, NULL,
349 "Replication", "D", 5,
350 offsetof(struct pg_conn, replication)},
352 {"target_session_attrs", "PGTARGETSESSIONATTRS",
353 DefaultTargetSessionAttrs, NULL,
354 "Target-Session-Attrs", "", 15, /* sizeof("prefer-standby") = 15 */
355 offsetof(struct pg_conn, target_session_attrs)},
357 {"load_balance_hosts", "PGLOADBALANCEHOSTS",
358 DefaultLoadBalanceHosts, NULL,
359 "Load-Balance-Hosts", "", 8, /* sizeof("disable") = 8 */
360 offsetof(struct pg_conn, load_balance_hosts)},
362 /* Terminating entry --- MUST BE LAST */
363 {NULL, NULL, NULL, NULL,
364 NULL, NULL, 0}
367 static const PQEnvironmentOption EnvironmentOptions[] =
369 /* common user-interface settings */
371 "PGDATESTYLE", "datestyle"
374 "PGTZ", "timezone"
376 /* internal performance-related settings */
378 "PGGEQO", "geqo"
381 NULL, NULL
385 /* The connection URI must start with either of the following designators: */
386 static const char uri_designator[] = "postgresql://";
387 static const char short_uri_designator[] = "postgres://";
389 static bool connectOptions1(PGconn *conn, const char *conninfo);
390 static bool connectOptions2(PGconn *conn);
391 static int connectDBStart(PGconn *conn);
392 static int connectDBComplete(PGconn *conn);
393 static PGPing internal_ping(PGconn *conn);
394 static PGconn *makeEmptyPGconn(void);
395 static void pqFreeCommandQueue(PGcmdQueueEntry *queue);
396 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
397 static void freePGconn(PGconn *conn);
398 static void closePGconn(PGconn *conn);
399 static void release_conn_addrinfo(PGconn *conn);
400 static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist);
401 static void sendTerminateConn(PGconn *conn);
402 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
403 static PQconninfoOption *parse_connection_string(const char *connstr,
404 PQExpBuffer errorMessage, bool use_defaults);
405 static int uri_prefix_length(const char *connstr);
406 static bool recognized_connection_string(const char *connstr);
407 static PQconninfoOption *conninfo_parse(const char *conninfo,
408 PQExpBuffer errorMessage, bool use_defaults);
409 static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
410 const char *const *values, PQExpBuffer errorMessage,
411 bool use_defaults, int expand_dbname);
412 static bool conninfo_add_defaults(PQconninfoOption *options,
413 PQExpBuffer errorMessage);
414 static PQconninfoOption *conninfo_uri_parse(const char *uri,
415 PQExpBuffer errorMessage, bool use_defaults);
416 static bool conninfo_uri_parse_options(PQconninfoOption *options,
417 const char *uri, PQExpBuffer errorMessage);
418 static bool conninfo_uri_parse_params(char *params,
419 PQconninfoOption *connOptions,
420 PQExpBuffer errorMessage);
421 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
422 static bool get_hexdigit(char digit, int *value);
423 static const char *conninfo_getval(PQconninfoOption *connOptions,
424 const char *keyword);
425 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
426 const char *keyword, const char *value,
427 PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
428 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
429 const char *keyword);
430 static void defaultNoticeReceiver(void *arg, const PGresult *res);
431 static void defaultNoticeProcessor(void *arg, const char *message);
432 static int parseServiceInfo(PQconninfoOption *options,
433 PQExpBuffer errorMessage);
434 static int parseServiceFile(const char *serviceFile,
435 const char *service,
436 PQconninfoOption *options,
437 PQExpBuffer errorMessage,
438 bool *group_found);
439 static char *pwdfMatchesString(char *buf, const char *token);
440 static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
441 const char *username, const char *pgpassfile);
442 static void pgpassfileWarning(PGconn *conn);
443 static void default_threadlock(int acquire);
444 static bool sslVerifyProtocolVersion(const char *version);
445 static bool sslVerifyProtocolRange(const char *min, const char *max);
448 /* global variable because fe-auth.c needs to access it */
449 pgthreadlock_t pg_g_threadlock = default_threadlock;
453 * pqDropConnection
455 * Close any physical connection to the server, and reset associated
456 * state inside the connection object. We don't release state that
457 * would be needed to reconnect, though, nor local state that might still
458 * be useful later.
460 * We can always flush the output buffer, since there's no longer any hope
461 * of sending that data. However, unprocessed input data might still be
462 * valuable, so the caller must tell us whether to flush that or not.
464 void
465 pqDropConnection(PGconn *conn, bool flushInput)
467 /* Drop any SSL state */
468 pqsecure_close(conn);
470 /* Close the socket itself */
471 if (conn->sock != PGINVALID_SOCKET)
472 closesocket(conn->sock);
473 conn->sock = PGINVALID_SOCKET;
475 /* Optionally discard any unread data */
476 if (flushInput)
477 conn->inStart = conn->inCursor = conn->inEnd = 0;
479 /* Always discard any unsent data */
480 conn->outCount = 0;
482 /* Likewise, discard any pending pipelined commands */
483 pqFreeCommandQueue(conn->cmd_queue_head);
484 conn->cmd_queue_head = conn->cmd_queue_tail = NULL;
485 pqFreeCommandQueue(conn->cmd_queue_recycle);
486 conn->cmd_queue_recycle = NULL;
488 /* Free authentication/encryption state */
489 #ifdef ENABLE_GSS
491 OM_uint32 min_s;
493 if (conn->gcred != GSS_C_NO_CREDENTIAL)
495 gss_release_cred(&min_s, &conn->gcred);
496 conn->gcred = GSS_C_NO_CREDENTIAL;
498 if (conn->gctx)
499 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
500 if (conn->gtarg_nam)
501 gss_release_name(&min_s, &conn->gtarg_nam);
502 if (conn->gss_SendBuffer)
504 free(conn->gss_SendBuffer);
505 conn->gss_SendBuffer = NULL;
507 if (conn->gss_RecvBuffer)
509 free(conn->gss_RecvBuffer);
510 conn->gss_RecvBuffer = NULL;
512 if (conn->gss_ResultBuffer)
514 free(conn->gss_ResultBuffer);
515 conn->gss_ResultBuffer = NULL;
517 conn->gssenc = false;
519 #endif
520 #ifdef ENABLE_SSPI
521 if (conn->sspitarget)
523 free(conn->sspitarget);
524 conn->sspitarget = NULL;
526 if (conn->sspicred)
528 FreeCredentialsHandle(conn->sspicred);
529 free(conn->sspicred);
530 conn->sspicred = NULL;
532 if (conn->sspictx)
534 DeleteSecurityContext(conn->sspictx);
535 free(conn->sspictx);
536 conn->sspictx = NULL;
538 conn->usesspi = 0;
539 #endif
540 if (conn->sasl_state)
542 conn->sasl->free(conn->sasl_state);
543 conn->sasl_state = NULL;
548 * pqFreeCommandQueue
549 * Free all the entries of PGcmdQueueEntry queue passed.
551 static void
552 pqFreeCommandQueue(PGcmdQueueEntry *queue)
554 while (queue != NULL)
556 PGcmdQueueEntry *cur = queue;
558 queue = cur->next;
559 free(cur->query);
560 free(cur);
565 * pqDropServerData
567 * Clear all connection state data that was received from (or deduced about)
568 * the server. This is essential to do between connection attempts to
569 * different servers, else we may incorrectly hold over some data from the
570 * old server.
572 * It would be better to merge this into pqDropConnection, perhaps, but
573 * right now we cannot because that function is called immediately on
574 * detection of connection loss (cf. pqReadData, for instance). This data
575 * should be kept until we are actually starting a new connection.
577 static void
578 pqDropServerData(PGconn *conn)
580 PGnotify *notify;
581 pgParameterStatus *pstatus;
583 /* Forget pending notifies */
584 notify = conn->notifyHead;
585 while (notify != NULL)
587 PGnotify *prev = notify;
589 notify = notify->next;
590 free(prev);
592 conn->notifyHead = conn->notifyTail = NULL;
594 /* Reset ParameterStatus data, as well as variables deduced from it */
595 pstatus = conn->pstatus;
596 while (pstatus != NULL)
598 pgParameterStatus *prev = pstatus;
600 pstatus = pstatus->next;
601 free(prev);
603 conn->pstatus = NULL;
604 conn->client_encoding = PG_SQL_ASCII;
605 conn->std_strings = false;
606 conn->default_transaction_read_only = PG_BOOL_UNKNOWN;
607 conn->in_hot_standby = PG_BOOL_UNKNOWN;
608 conn->scram_sha_256_iterations = SCRAM_SHA_256_DEFAULT_ITERATIONS;
609 conn->sversion = 0;
611 /* Drop large-object lookup data */
612 free(conn->lobjfuncs);
613 conn->lobjfuncs = NULL;
615 /* Reset assorted other per-connection state */
616 conn->last_sqlstate[0] = '\0';
617 conn->auth_req_received = false;
618 conn->client_finished_auth = false;
619 conn->password_needed = false;
620 conn->gssapi_used = false;
621 conn->write_failed = false;
622 free(conn->write_err_msg);
623 conn->write_err_msg = NULL;
624 conn->be_pid = 0;
625 conn->be_key = 0;
630 * Connecting to a Database
632 * There are now six different ways a user of this API can connect to the
633 * database. Two are not recommended for use in new code, because of their
634 * lack of extensibility with respect to the passing of options to the
635 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
636 * to the latter).
638 * If it is desired to connect in a synchronous (blocking) manner, use the
639 * function PQconnectdb or PQconnectdbParams. The former accepts a string of
640 * option = value pairs (or a URI) which must be parsed; the latter takes two
641 * NULL terminated arrays instead.
643 * To connect in an asynchronous (non-blocking) manner, use the functions
644 * PQconnectStart or PQconnectStartParams (which differ in the same way as
645 * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
647 * Internally, the static functions connectDBStart, connectDBComplete
648 * are part of the connection procedure.
652 * PQconnectdbParams
654 * establishes a connection to a postgres backend through the postmaster
655 * using connection information in two arrays.
657 * The keywords array is defined as
659 * const char *params[] = {"option1", "option2", NULL}
661 * The values array is defined as
663 * const char *values[] = {"value1", "value2", NULL}
665 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
666 * if a memory allocation failed.
667 * If the status field of the connection returned is CONNECTION_BAD,
668 * then some fields may be null'ed out instead of having valid values.
670 * You should call PQfinish (if conn is not NULL) regardless of whether this
671 * call succeeded.
673 PGconn *
674 PQconnectdbParams(const char *const *keywords,
675 const char *const *values,
676 int expand_dbname)
678 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
680 if (conn && conn->status != CONNECTION_BAD)
681 (void) connectDBComplete(conn);
683 return conn;
687 * PQpingParams
689 * check server status, accepting parameters identical to PQconnectdbParams
691 PGPing
692 PQpingParams(const char *const *keywords,
693 const char *const *values,
694 int expand_dbname)
696 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
697 PGPing ret;
699 ret = internal_ping(conn);
700 PQfinish(conn);
702 return ret;
706 * PQconnectdb
708 * establishes a connection to a postgres backend through the postmaster
709 * using connection information in a string.
711 * The conninfo string is either a whitespace-separated list of
713 * option = value
715 * definitions or a URI (refer to the documentation for details.) Value
716 * might be a single value containing no whitespaces or a single quoted
717 * string. If a single quote should appear anywhere in the value, it must be
718 * escaped with a backslash like \'
720 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
721 * if a memory allocation failed.
722 * If the status field of the connection returned is CONNECTION_BAD,
723 * then some fields may be null'ed out instead of having valid values.
725 * You should call PQfinish (if conn is not NULL) regardless of whether this
726 * call succeeded.
728 PGconn *
729 PQconnectdb(const char *conninfo)
731 PGconn *conn = PQconnectStart(conninfo);
733 if (conn && conn->status != CONNECTION_BAD)
734 (void) connectDBComplete(conn);
736 return conn;
740 * PQping
742 * check server status, accepting parameters identical to PQconnectdb
744 PGPing
745 PQping(const char *conninfo)
747 PGconn *conn = PQconnectStart(conninfo);
748 PGPing ret;
750 ret = internal_ping(conn);
751 PQfinish(conn);
753 return ret;
757 * PQconnectStartParams
759 * Begins the establishment of a connection to a postgres backend through the
760 * postmaster using connection information in a struct.
762 * See comment for PQconnectdbParams for the definition of the string format.
764 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
765 * you should not attempt to proceed with this connection. If the status
766 * field of the connection returned is CONNECTION_BAD, an error has
767 * occurred. In this case you should call PQfinish on the result, (perhaps
768 * inspecting the error message first). Other fields of the structure may not
769 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
770 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
771 * this is necessary.
773 * See PQconnectPoll for more info.
775 PGconn *
776 PQconnectStartParams(const char *const *keywords,
777 const char *const *values,
778 int expand_dbname)
780 PGconn *conn;
781 PQconninfoOption *connOptions;
784 * Allocate memory for the conn structure. Note that we also expect this
785 * to initialize conn->errorMessage to empty. All subsequent steps during
786 * connection initialization will only append to that buffer.
788 conn = makeEmptyPGconn();
789 if (conn == NULL)
790 return NULL;
793 * Parse the conninfo arrays
795 connOptions = conninfo_array_parse(keywords, values,
796 &conn->errorMessage,
797 true, expand_dbname);
798 if (connOptions == NULL)
800 conn->status = CONNECTION_BAD;
801 /* errorMessage is already set */
802 return conn;
806 * Move option values into conn structure
808 if (!fillPGconn(conn, connOptions))
810 PQconninfoFree(connOptions);
811 return conn;
815 * Free the option info - all is in conn now
817 PQconninfoFree(connOptions);
820 * Compute derived options
822 if (!connectOptions2(conn))
823 return conn;
826 * Connect to the database
828 if (!connectDBStart(conn))
830 /* Just in case we failed to set it in connectDBStart */
831 conn->status = CONNECTION_BAD;
834 return conn;
838 * PQconnectStart
840 * Begins the establishment of a connection to a postgres backend through the
841 * postmaster using connection information in a string.
843 * See comment for PQconnectdb for the definition of the string format.
845 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
846 * you should not attempt to proceed with this connection. If the status
847 * field of the connection returned is CONNECTION_BAD, an error has
848 * occurred. In this case you should call PQfinish on the result, (perhaps
849 * inspecting the error message first). Other fields of the structure may not
850 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
851 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
852 * this is necessary.
854 * See PQconnectPoll for more info.
856 PGconn *
857 PQconnectStart(const char *conninfo)
859 PGconn *conn;
862 * Allocate memory for the conn structure. Note that we also expect this
863 * to initialize conn->errorMessage to empty. All subsequent steps during
864 * connection initialization will only append to that buffer.
866 conn = makeEmptyPGconn();
867 if (conn == NULL)
868 return NULL;
871 * Parse the conninfo string
873 if (!connectOptions1(conn, conninfo))
874 return conn;
877 * Compute derived options
879 if (!connectOptions2(conn))
880 return conn;
883 * Connect to the database
885 if (!connectDBStart(conn))
887 /* Just in case we failed to set it in connectDBStart */
888 conn->status = CONNECTION_BAD;
891 return conn;
895 * Move option values into conn structure
897 * Don't put anything cute here --- intelligence should be in
898 * connectOptions2 ...
900 * Returns true on success. On failure, returns false and sets error message.
902 static bool
903 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
905 const internalPQconninfoOption *option;
907 for (option = PQconninfoOptions; option->keyword; option++)
909 if (option->connofs >= 0)
911 const char *tmp = conninfo_getval(connOptions, option->keyword);
913 if (tmp)
915 char **connmember = (char **) ((char *) conn + option->connofs);
917 free(*connmember);
918 *connmember = strdup(tmp);
919 if (*connmember == NULL)
921 libpq_append_conn_error(conn, "out of memory");
922 return false;
928 return true;
932 * connectOptions1
934 * Internal subroutine to set up connection parameters given an already-
935 * created PGconn and a conninfo string. Derived settings should be
936 * processed by calling connectOptions2 next. (We split them because
937 * PQsetdbLogin overrides defaults in between.)
939 * Returns true if OK, false if trouble (in which case errorMessage is set
940 * and so is conn->status).
942 static bool
943 connectOptions1(PGconn *conn, const char *conninfo)
945 PQconninfoOption *connOptions;
948 * Parse the conninfo string
950 connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
951 if (connOptions == NULL)
953 conn->status = CONNECTION_BAD;
954 /* errorMessage is already set */
955 return false;
959 * Move option values into conn structure
961 if (!fillPGconn(conn, connOptions))
963 conn->status = CONNECTION_BAD;
964 PQconninfoFree(connOptions);
965 return false;
969 * Free the option info - all is in conn now
971 PQconninfoFree(connOptions);
973 return true;
977 * Count the number of elements in a simple comma-separated list.
979 static int
980 count_comma_separated_elems(const char *input)
982 int n;
984 n = 1;
985 for (; *input != '\0'; input++)
987 if (*input == ',')
988 n++;
991 return n;
995 * Parse a simple comma-separated list.
997 * On each call, returns a malloc'd copy of the next element, and sets *more
998 * to indicate whether there are any more elements in the list after this,
999 * and updates *startptr to point to the next element, if any.
1001 * On out of memory, returns NULL.
1003 static char *
1004 parse_comma_separated_list(char **startptr, bool *more)
1006 char *p;
1007 char *s = *startptr;
1008 char *e;
1009 int len;
1012 * Search for the end of the current element; a comma or end-of-string
1013 * acts as a terminator.
1015 e = s;
1016 while (*e != '\0' && *e != ',')
1017 ++e;
1018 *more = (*e == ',');
1020 len = e - s;
1021 p = (char *) malloc(sizeof(char) * (len + 1));
1022 if (p)
1024 memcpy(p, s, len);
1025 p[len] = '\0';
1027 *startptr = e + 1;
1029 return p;
1033 * Initializes the prng_state field of the connection. We want something
1034 * unpredictable, so if possible, use high-quality random bits for the
1035 * seed. Otherwise, fall back to a seed based on the connection address,
1036 * timestamp and PID.
1038 static void
1039 libpq_prng_init(PGconn *conn)
1041 uint64 rseed;
1042 struct timeval tval = {0};
1044 if (pg_prng_strong_seed(&conn->prng_state))
1045 return;
1047 gettimeofday(&tval, NULL);
1049 rseed = ((uintptr_t) conn) ^
1050 ((uint64) getpid()) ^
1051 ((uint64) tval.tv_usec) ^
1052 ((uint64) tval.tv_sec);
1054 pg_prng_seed(&conn->prng_state, rseed);
1058 * connectOptions2
1060 * Compute derived connection options after absorbing all user-supplied info.
1062 * Returns true if OK, false if trouble (in which case errorMessage is set
1063 * and so is conn->status).
1065 static bool
1066 connectOptions2(PGconn *conn)
1068 int i;
1071 * Allocate memory for details about each host to which we might possibly
1072 * try to connect. For that, count the number of elements in the hostaddr
1073 * or host options. If neither is given, assume one host.
1075 conn->whichhost = 0;
1076 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1077 conn->nconnhost = count_comma_separated_elems(conn->pghostaddr);
1078 else if (conn->pghost && conn->pghost[0] != '\0')
1079 conn->nconnhost = count_comma_separated_elems(conn->pghost);
1080 else
1081 conn->nconnhost = 1;
1082 conn->connhost = (pg_conn_host *)
1083 calloc(conn->nconnhost, sizeof(pg_conn_host));
1084 if (conn->connhost == NULL)
1085 goto oom_error;
1088 * We now have one pg_conn_host structure per possible host. Fill in the
1089 * host and hostaddr fields for each, by splitting the parameter strings.
1091 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1093 char *s = conn->pghostaddr;
1094 bool more = true;
1096 for (i = 0; i < conn->nconnhost && more; i++)
1098 conn->connhost[i].hostaddr = parse_comma_separated_list(&s, &more);
1099 if (conn->connhost[i].hostaddr == NULL)
1100 goto oom_error;
1104 * If hostaddr was given, the array was allocated according to the
1105 * number of elements in the hostaddr list, so it really should be the
1106 * right size.
1108 Assert(!more);
1109 Assert(i == conn->nconnhost);
1112 if (conn->pghost != NULL && conn->pghost[0] != '\0')
1114 char *s = conn->pghost;
1115 bool more = true;
1117 for (i = 0; i < conn->nconnhost && more; i++)
1119 conn->connhost[i].host = parse_comma_separated_list(&s, &more);
1120 if (conn->connhost[i].host == NULL)
1121 goto oom_error;
1124 /* Check for wrong number of host items. */
1125 if (more || i != conn->nconnhost)
1127 conn->status = CONNECTION_BAD;
1128 libpq_append_conn_error(conn, "could not match %d host names to %d hostaddr values",
1129 count_comma_separated_elems(conn->pghost), conn->nconnhost);
1130 return false;
1135 * Now, for each host slot, identify the type of address spec, and fill in
1136 * the default address if nothing was given.
1138 for (i = 0; i < conn->nconnhost; i++)
1140 pg_conn_host *ch = &conn->connhost[i];
1142 if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1143 ch->type = CHT_HOST_ADDRESS;
1144 else if (ch->host != NULL && ch->host[0] != '\0')
1146 ch->type = CHT_HOST_NAME;
1147 if (is_unixsock_path(ch->host))
1148 ch->type = CHT_UNIX_SOCKET;
1150 else
1152 free(ch->host);
1155 * This bit selects the default host location. If you change
1156 * this, see also pg_regress.
1158 if (DEFAULT_PGSOCKET_DIR[0])
1160 ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1161 ch->type = CHT_UNIX_SOCKET;
1163 else
1165 ch->host = strdup(DefaultHost);
1166 ch->type = CHT_HOST_NAME;
1168 if (ch->host == NULL)
1169 goto oom_error;
1174 * Next, work out the port number corresponding to each host name.
1176 * Note: unlike the above for host names, this could leave the port fields
1177 * as null or empty strings. We will substitute DEF_PGPORT whenever we
1178 * read such a port field.
1180 if (conn->pgport != NULL && conn->pgport[0] != '\0')
1182 char *s = conn->pgport;
1183 bool more = true;
1185 for (i = 0; i < conn->nconnhost && more; i++)
1187 conn->connhost[i].port = parse_comma_separated_list(&s, &more);
1188 if (conn->connhost[i].port == NULL)
1189 goto oom_error;
1193 * If exactly one port was given, use it for every host. Otherwise,
1194 * there must be exactly as many ports as there were hosts.
1196 if (i == 1 && !more)
1198 for (i = 1; i < conn->nconnhost; i++)
1200 conn->connhost[i].port = strdup(conn->connhost[0].port);
1201 if (conn->connhost[i].port == NULL)
1202 goto oom_error;
1205 else if (more || i != conn->nconnhost)
1207 conn->status = CONNECTION_BAD;
1208 libpq_append_conn_error(conn, "could not match %d port numbers to %d hosts",
1209 count_comma_separated_elems(conn->pgport), conn->nconnhost);
1210 return false;
1215 * If user name was not given, fetch it. (Most likely, the fetch will
1216 * fail, since the only way we get here is if pg_fe_getauthname() failed
1217 * during conninfo_add_defaults(). But now we want an error message.)
1219 if (conn->pguser == NULL || conn->pguser[0] == '\0')
1221 free(conn->pguser);
1222 conn->pguser = pg_fe_getauthname(&conn->errorMessage);
1223 if (!conn->pguser)
1225 conn->status = CONNECTION_BAD;
1226 return false;
1231 * If database name was not given, default it to equal user name
1233 if (conn->dbName == NULL || conn->dbName[0] == '\0')
1235 free(conn->dbName);
1236 conn->dbName = strdup(conn->pguser);
1237 if (!conn->dbName)
1238 goto oom_error;
1242 * If password was not given, try to look it up in password file. Note
1243 * that the result might be different for each host/port pair.
1245 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1247 /* If password file wasn't specified, use ~/PGPASSFILE */
1248 if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1250 char homedir[MAXPGPATH];
1252 if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1254 free(conn->pgpassfile);
1255 conn->pgpassfile = malloc(MAXPGPATH);
1256 if (!conn->pgpassfile)
1257 goto oom_error;
1258 snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1259 homedir, PGPASSFILE);
1263 if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1265 for (i = 0; i < conn->nconnhost; i++)
1268 * Try to get a password for this host from file. We use host
1269 * for the hostname search key if given, else hostaddr (at
1270 * least one of them is guaranteed nonempty by now).
1272 const char *pwhost = conn->connhost[i].host;
1274 if (pwhost == NULL || pwhost[0] == '\0')
1275 pwhost = conn->connhost[i].hostaddr;
1277 conn->connhost[i].password =
1278 passwordFromFile(pwhost,
1279 conn->connhost[i].port,
1280 conn->dbName,
1281 conn->pguser,
1282 conn->pgpassfile);
1288 * parse and validate require_auth option
1290 if (conn->require_auth && conn->require_auth[0])
1292 char *s = conn->require_auth;
1293 bool first,
1294 more;
1295 bool negated = false;
1298 * By default, start from an empty set of allowed options and add to
1299 * it.
1301 conn->auth_required = true;
1302 conn->allowed_auth_methods = 0;
1304 for (first = true, more = true; more; first = false)
1306 char *method,
1307 *part;
1308 uint32 bits;
1310 part = parse_comma_separated_list(&s, &more);
1311 if (part == NULL)
1312 goto oom_error;
1315 * Check for negation, e.g. '!password'. If one element is
1316 * negated, they all have to be.
1318 method = part;
1319 if (*method == '!')
1321 if (first)
1324 * Switch to a permissive set of allowed options, and
1325 * subtract from it.
1327 conn->auth_required = false;
1328 conn->allowed_auth_methods = -1;
1330 else if (!negated)
1332 conn->status = CONNECTION_BAD;
1333 libpq_append_conn_error(conn, "negative require_auth method \"%s\" cannot be mixed with non-negative methods",
1334 method);
1336 free(part);
1337 return false;
1340 negated = true;
1341 method++;
1343 else if (negated)
1345 conn->status = CONNECTION_BAD;
1346 libpq_append_conn_error(conn, "require_auth method \"%s\" cannot be mixed with negative methods",
1347 method);
1349 free(part);
1350 return false;
1353 if (strcmp(method, "password") == 0)
1355 bits = (1 << AUTH_REQ_PASSWORD);
1357 else if (strcmp(method, "md5") == 0)
1359 bits = (1 << AUTH_REQ_MD5);
1361 else if (strcmp(method, "gss") == 0)
1363 bits = (1 << AUTH_REQ_GSS);
1364 bits |= (1 << AUTH_REQ_GSS_CONT);
1366 else if (strcmp(method, "sspi") == 0)
1368 bits = (1 << AUTH_REQ_SSPI);
1369 bits |= (1 << AUTH_REQ_GSS_CONT);
1371 else if (strcmp(method, "scram-sha-256") == 0)
1373 /* This currently assumes that SCRAM is the only SASL method. */
1374 bits = (1 << AUTH_REQ_SASL);
1375 bits |= (1 << AUTH_REQ_SASL_CONT);
1376 bits |= (1 << AUTH_REQ_SASL_FIN);
1378 else if (strcmp(method, "none") == 0)
1381 * Special case: let the user explicitly allow (or disallow)
1382 * connections where the server does not send an explicit
1383 * authentication challenge, such as "trust" and "cert" auth.
1385 if (negated) /* "!none" */
1387 if (conn->auth_required)
1388 goto duplicate;
1390 conn->auth_required = true;
1392 else /* "none" */
1394 if (!conn->auth_required)
1395 goto duplicate;
1397 conn->auth_required = false;
1400 free(part);
1401 continue; /* avoid the bitmask manipulation below */
1403 else
1405 conn->status = CONNECTION_BAD;
1406 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1407 "require_auth", method);
1409 free(part);
1410 return false;
1413 /* Update the bitmask. */
1414 if (negated)
1416 if ((conn->allowed_auth_methods & bits) == 0)
1417 goto duplicate;
1419 conn->allowed_auth_methods &= ~bits;
1421 else
1423 if ((conn->allowed_auth_methods & bits) == bits)
1424 goto duplicate;
1426 conn->allowed_auth_methods |= bits;
1429 free(part);
1430 continue;
1432 duplicate:
1435 * A duplicated method probably indicates a typo in a setting
1436 * where typos are extremely risky.
1438 conn->status = CONNECTION_BAD;
1439 libpq_append_conn_error(conn, "require_auth method \"%s\" is specified more than once",
1440 part);
1442 free(part);
1443 return false;
1448 * validate channel_binding option
1450 if (conn->channel_binding)
1452 if (strcmp(conn->channel_binding, "disable") != 0
1453 && strcmp(conn->channel_binding, "prefer") != 0
1454 && strcmp(conn->channel_binding, "require") != 0)
1456 conn->status = CONNECTION_BAD;
1457 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1458 "channel_binding", conn->channel_binding);
1459 return false;
1462 else
1464 conn->channel_binding = strdup(DefaultChannelBinding);
1465 if (!conn->channel_binding)
1466 goto oom_error;
1469 #ifndef USE_SSL
1472 * sslrootcert=system is not supported. Since setting this changes the
1473 * default sslmode, check this _before_ we validate sslmode, to avoid
1474 * confusing the user with errors for an option they may not have set.
1476 if (conn->sslrootcert
1477 && strcmp(conn->sslrootcert, "system") == 0)
1479 conn->status = CONNECTION_BAD;
1480 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1481 "sslrootcert", conn->sslrootcert);
1482 return false;
1484 #endif
1487 * validate sslmode option
1489 if (conn->sslmode)
1491 if (strcmp(conn->sslmode, "disable") != 0
1492 && strcmp(conn->sslmode, "allow") != 0
1493 && strcmp(conn->sslmode, "prefer") != 0
1494 && strcmp(conn->sslmode, "require") != 0
1495 && strcmp(conn->sslmode, "verify-ca") != 0
1496 && strcmp(conn->sslmode, "verify-full") != 0)
1498 conn->status = CONNECTION_BAD;
1499 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1500 "sslmode", conn->sslmode);
1501 return false;
1504 #ifndef USE_SSL
1505 switch (conn->sslmode[0])
1507 case 'a': /* "allow" */
1508 case 'p': /* "prefer" */
1511 * warn user that an SSL connection will never be negotiated
1512 * since SSL was not compiled in?
1514 break;
1516 case 'r': /* "require" */
1517 case 'v': /* "verify-ca" or "verify-full" */
1518 conn->status = CONNECTION_BAD;
1519 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1520 "sslmode", conn->sslmode);
1521 return false;
1523 #endif
1525 else
1527 conn->sslmode = strdup(DefaultSSLMode);
1528 if (!conn->sslmode)
1529 goto oom_error;
1532 #ifdef USE_SSL
1535 * If sslrootcert=system, make sure our chosen sslmode is compatible.
1537 if (conn->sslrootcert
1538 && strcmp(conn->sslrootcert, "system") == 0
1539 && strcmp(conn->sslmode, "verify-full") != 0)
1541 conn->status = CONNECTION_BAD;
1542 libpq_append_conn_error(conn, "weak sslmode \"%s\" may not be used with sslrootcert=system (use \"verify-full\")",
1543 conn->sslmode);
1544 return false;
1546 #endif
1549 * Validate TLS protocol versions for ssl_min_protocol_version and
1550 * ssl_max_protocol_version.
1552 if (!sslVerifyProtocolVersion(conn->ssl_min_protocol_version))
1554 conn->status = CONNECTION_BAD;
1555 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1556 "ssl_min_protocol_version",
1557 conn->ssl_min_protocol_version);
1558 return false;
1560 if (!sslVerifyProtocolVersion(conn->ssl_max_protocol_version))
1562 conn->status = CONNECTION_BAD;
1563 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1564 "ssl_max_protocol_version",
1565 conn->ssl_max_protocol_version);
1566 return false;
1570 * Check if the range of SSL protocols defined is correct. This is done
1571 * at this early step because this is independent of the SSL
1572 * implementation used, and this avoids unnecessary cycles with an
1573 * already-built SSL context when the connection is being established, as
1574 * it would be doomed anyway.
1576 if (!sslVerifyProtocolRange(conn->ssl_min_protocol_version,
1577 conn->ssl_max_protocol_version))
1579 conn->status = CONNECTION_BAD;
1580 libpq_append_conn_error(conn, "invalid SSL protocol version range");
1581 return false;
1585 * validate sslcertmode option
1587 if (conn->sslcertmode)
1589 if (strcmp(conn->sslcertmode, "disable") != 0 &&
1590 strcmp(conn->sslcertmode, "allow") != 0 &&
1591 strcmp(conn->sslcertmode, "require") != 0)
1593 conn->status = CONNECTION_BAD;
1594 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1595 "sslcertmode", conn->sslcertmode);
1596 return false;
1598 #ifndef USE_SSL
1599 if (strcmp(conn->sslcertmode, "require") == 0)
1601 conn->status = CONNECTION_BAD;
1602 libpq_append_conn_error(conn, "%s value \"%s\" invalid when SSL support is not compiled in",
1603 "sslcertmode", conn->sslcertmode);
1604 return false;
1606 #endif
1607 #ifndef HAVE_SSL_CTX_SET_CERT_CB
1610 * Without a certificate callback, the current implementation can't
1611 * figure out if a certificate was actually requested, so "require" is
1612 * useless.
1614 if (strcmp(conn->sslcertmode, "require") == 0)
1616 conn->status = CONNECTION_BAD;
1617 libpq_append_conn_error(conn, "%s value \"%s\" is not supported (check OpenSSL version)",
1618 "sslcertmode", conn->sslcertmode);
1619 return false;
1621 #endif
1623 else
1625 conn->sslcertmode = strdup(DefaultSSLCertMode);
1626 if (!conn->sslcertmode)
1627 goto oom_error;
1631 * validate gssencmode option
1633 if (conn->gssencmode)
1635 if (strcmp(conn->gssencmode, "disable") != 0 &&
1636 strcmp(conn->gssencmode, "prefer") != 0 &&
1637 strcmp(conn->gssencmode, "require") != 0)
1639 conn->status = CONNECTION_BAD;
1640 libpq_append_conn_error(conn, "invalid %s value: \"%s\"", "gssencmode", conn->gssencmode);
1641 return false;
1643 #ifndef ENABLE_GSS
1644 if (strcmp(conn->gssencmode, "require") == 0)
1646 conn->status = CONNECTION_BAD;
1647 libpq_append_conn_error(conn, "gssencmode value \"%s\" invalid when GSSAPI support is not compiled in",
1648 conn->gssencmode);
1649 return false;
1651 #endif
1653 else
1655 conn->gssencmode = strdup(DefaultGSSMode);
1656 if (!conn->gssencmode)
1657 goto oom_error;
1661 * validate target_session_attrs option, and set target_server_type
1663 if (conn->target_session_attrs)
1665 if (strcmp(conn->target_session_attrs, "any") == 0)
1666 conn->target_server_type = SERVER_TYPE_ANY;
1667 else if (strcmp(conn->target_session_attrs, "read-write") == 0)
1668 conn->target_server_type = SERVER_TYPE_READ_WRITE;
1669 else if (strcmp(conn->target_session_attrs, "read-only") == 0)
1670 conn->target_server_type = SERVER_TYPE_READ_ONLY;
1671 else if (strcmp(conn->target_session_attrs, "primary") == 0)
1672 conn->target_server_type = SERVER_TYPE_PRIMARY;
1673 else if (strcmp(conn->target_session_attrs, "standby") == 0)
1674 conn->target_server_type = SERVER_TYPE_STANDBY;
1675 else if (strcmp(conn->target_session_attrs, "prefer-standby") == 0)
1676 conn->target_server_type = SERVER_TYPE_PREFER_STANDBY;
1677 else
1679 conn->status = CONNECTION_BAD;
1680 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1681 "target_session_attrs",
1682 conn->target_session_attrs);
1683 return false;
1686 else
1687 conn->target_server_type = SERVER_TYPE_ANY;
1690 * validate load_balance_hosts option, and set load_balance_type
1692 if (conn->load_balance_hosts)
1694 if (strcmp(conn->load_balance_hosts, "disable") == 0)
1695 conn->load_balance_type = LOAD_BALANCE_DISABLE;
1696 else if (strcmp(conn->load_balance_hosts, "random") == 0)
1697 conn->load_balance_type = LOAD_BALANCE_RANDOM;
1698 else
1700 conn->status = CONNECTION_BAD;
1701 libpq_append_conn_error(conn, "invalid %s value: \"%s\"",
1702 "load_balance_hosts",
1703 conn->load_balance_hosts);
1704 return false;
1707 else
1708 conn->load_balance_type = LOAD_BALANCE_DISABLE;
1710 if (conn->load_balance_type == LOAD_BALANCE_RANDOM)
1712 libpq_prng_init(conn);
1715 * This is the "inside-out" variant of the Fisher-Yates shuffle
1716 * algorithm. Notionally, we append each new value to the array and
1717 * then swap it with a randomly-chosen array element (possibly
1718 * including itself, else we fail to generate permutations with the
1719 * last integer last). The swap step can be optimized by combining it
1720 * with the insertion.
1722 for (i = 1; i < conn->nconnhost; i++)
1724 int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
1725 pg_conn_host temp = conn->connhost[j];
1727 conn->connhost[j] = conn->connhost[i];
1728 conn->connhost[i] = temp;
1733 * Resolve special "auto" client_encoding from the locale
1735 if (conn->client_encoding_initial &&
1736 strcmp(conn->client_encoding_initial, "auto") == 0)
1738 free(conn->client_encoding_initial);
1739 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
1740 if (!conn->client_encoding_initial)
1741 goto oom_error;
1745 * Only if we get this far is it appropriate to try to connect. (We need a
1746 * state flag, rather than just the boolean result of this function, in
1747 * case someone tries to PQreset() the PGconn.)
1749 conn->options_valid = true;
1751 return true;
1753 oom_error:
1754 conn->status = CONNECTION_BAD;
1755 libpq_append_conn_error(conn, "out of memory");
1756 return false;
1760 * PQconndefaults
1762 * Construct a default connection options array, which identifies all the
1763 * available options and shows any default values that are available from the
1764 * environment etc. On error (eg out of memory), NULL is returned.
1766 * Using this function, an application may determine all possible options
1767 * and their current default values.
1769 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1770 * and should be freed when no longer needed via PQconninfoFree(). (In prior
1771 * versions, the returned array was static, but that's not thread-safe.)
1772 * Pre-7.0 applications that use this function will see a small memory leak
1773 * until they are updated to call PQconninfoFree.
1775 PQconninfoOption *
1776 PQconndefaults(void)
1778 PQExpBufferData errorBuf;
1779 PQconninfoOption *connOptions;
1781 /* We don't actually report any errors here, but callees want a buffer */
1782 initPQExpBuffer(&errorBuf);
1783 if (PQExpBufferDataBroken(errorBuf))
1784 return NULL; /* out of memory already :-( */
1786 connOptions = conninfo_init(&errorBuf);
1787 if (connOptions != NULL)
1789 /* pass NULL errorBuf to ignore errors */
1790 if (!conninfo_add_defaults(connOptions, NULL))
1792 PQconninfoFree(connOptions);
1793 connOptions = NULL;
1797 termPQExpBuffer(&errorBuf);
1798 return connOptions;
1801 /* ----------------
1802 * PQsetdbLogin
1804 * establishes a connection to a postgres backend through the postmaster
1805 * at the specified host and port.
1807 * returns a PGconn* which is needed for all subsequent libpq calls
1809 * if the status field of the connection returned is CONNECTION_BAD,
1810 * then only the errorMessage is likely to be useful.
1811 * ----------------
1813 PGconn *
1814 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1815 const char *pgtty, const char *dbName, const char *login,
1816 const char *pwd)
1818 PGconn *conn;
1821 * Allocate memory for the conn structure. Note that we also expect this
1822 * to initialize conn->errorMessage to empty. All subsequent steps during
1823 * connection initialization will only append to that buffer.
1825 conn = makeEmptyPGconn();
1826 if (conn == NULL)
1827 return NULL;
1830 * If the dbName parameter contains what looks like a connection string,
1831 * parse it into conn struct using connectOptions1.
1833 if (dbName && recognized_connection_string(dbName))
1835 if (!connectOptions1(conn, dbName))
1836 return conn;
1838 else
1841 * Old-style path: first, parse an empty conninfo string in order to
1842 * set up the same defaults that PQconnectdb() would use.
1844 if (!connectOptions1(conn, ""))
1845 return conn;
1847 /* Insert dbName parameter value into struct */
1848 if (dbName && dbName[0] != '\0')
1850 free(conn->dbName);
1851 conn->dbName = strdup(dbName);
1852 if (!conn->dbName)
1853 goto oom_error;
1858 * Insert remaining parameters into struct, overriding defaults (as well
1859 * as any conflicting data from dbName taken as a conninfo).
1861 if (pghost && pghost[0] != '\0')
1863 free(conn->pghost);
1864 conn->pghost = strdup(pghost);
1865 if (!conn->pghost)
1866 goto oom_error;
1869 if (pgport && pgport[0] != '\0')
1871 free(conn->pgport);
1872 conn->pgport = strdup(pgport);
1873 if (!conn->pgport)
1874 goto oom_error;
1877 if (pgoptions && pgoptions[0] != '\0')
1879 free(conn->pgoptions);
1880 conn->pgoptions = strdup(pgoptions);
1881 if (!conn->pgoptions)
1882 goto oom_error;
1885 if (login && login[0] != '\0')
1887 free(conn->pguser);
1888 conn->pguser = strdup(login);
1889 if (!conn->pguser)
1890 goto oom_error;
1893 if (pwd && pwd[0] != '\0')
1895 free(conn->pgpass);
1896 conn->pgpass = strdup(pwd);
1897 if (!conn->pgpass)
1898 goto oom_error;
1902 * Compute derived options
1904 if (!connectOptions2(conn))
1905 return conn;
1908 * Connect to the database
1910 if (connectDBStart(conn))
1911 (void) connectDBComplete(conn);
1913 return conn;
1915 oom_error:
1916 conn->status = CONNECTION_BAD;
1917 libpq_append_conn_error(conn, "out of memory");
1918 return conn;
1922 /* ----------
1923 * connectNoDelay -
1924 * Sets the TCP_NODELAY socket option.
1925 * Returns 1 if successful, 0 if not.
1926 * ----------
1928 static int
1929 connectNoDelay(PGconn *conn)
1931 #ifdef TCP_NODELAY
1932 int on = 1;
1934 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1935 (char *) &on,
1936 sizeof(on)) < 0)
1938 char sebuf[PG_STRERROR_R_BUFLEN];
1940 libpq_append_conn_error(conn, "could not set socket to TCP no delay mode: %s",
1941 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1942 return 0;
1944 #endif
1946 return 1;
1949 /* ----------
1950 * Write currently connected IP address into host_addr (of len host_addr_len).
1951 * If unable to, set it to the empty string.
1952 * ----------
1954 static void
1955 getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
1957 struct sockaddr_storage *addr = &conn->raddr.addr;
1959 if (addr->ss_family == AF_INET)
1961 if (pg_inet_net_ntop(AF_INET,
1962 &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1964 host_addr, host_addr_len) == NULL)
1965 host_addr[0] = '\0';
1967 else if (addr->ss_family == AF_INET6)
1969 if (pg_inet_net_ntop(AF_INET6,
1970 &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1971 128,
1972 host_addr, host_addr_len) == NULL)
1973 host_addr[0] = '\0';
1975 else
1976 host_addr[0] = '\0';
1980 * emitHostIdentityInfo -
1981 * Speculatively append "connection to server so-and-so failed: " to
1982 * conn->errorMessage once we've identified the current connection target
1983 * address. This ensures that any subsequent error message will be properly
1984 * attributed to the server we couldn't connect to. conn->raddr must be
1985 * valid, and the result of getHostaddr() must be supplied.
1987 static void
1988 emitHostIdentityInfo(PGconn *conn, const char *host_addr)
1990 if (conn->raddr.addr.ss_family == AF_UNIX)
1992 char service[NI_MAXHOST];
1994 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1995 NULL, 0,
1996 service, sizeof(service),
1997 NI_NUMERICSERV);
1998 appendPQExpBuffer(&conn->errorMessage,
1999 libpq_gettext("connection to server on socket \"%s\" failed: "),
2000 service);
2002 else
2004 const char *displayed_host;
2005 const char *displayed_port;
2007 /* To which host and port were we actually connecting? */
2008 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
2009 displayed_host = conn->connhost[conn->whichhost].hostaddr;
2010 else
2011 displayed_host = conn->connhost[conn->whichhost].host;
2012 displayed_port = conn->connhost[conn->whichhost].port;
2013 if (displayed_port == NULL || displayed_port[0] == '\0')
2014 displayed_port = DEF_PGPORT_STR;
2017 * If the user did not supply an IP address using 'hostaddr', and
2018 * 'host' was missing or does not match our lookup, display the
2019 * looked-up IP address.
2021 if (conn->connhost[conn->whichhost].type != CHT_HOST_ADDRESS &&
2022 host_addr[0] &&
2023 strcmp(displayed_host, host_addr) != 0)
2024 appendPQExpBuffer(&conn->errorMessage,
2025 libpq_gettext("connection to server at \"%s\" (%s), port %s failed: "),
2026 displayed_host, host_addr,
2027 displayed_port);
2028 else
2029 appendPQExpBuffer(&conn->errorMessage,
2030 libpq_gettext("connection to server at \"%s\", port %s failed: "),
2031 displayed_host,
2032 displayed_port);
2036 /* ----------
2037 * connectFailureMessage -
2038 * create a friendly error message on connection failure,
2039 * using the given errno value. Use this for error cases that
2040 * imply that there's no server there.
2041 * ----------
2043 static void
2044 connectFailureMessage(PGconn *conn, int errorno)
2046 char sebuf[PG_STRERROR_R_BUFLEN];
2048 appendPQExpBuffer(&conn->errorMessage,
2049 "%s\n",
2050 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2052 if (conn->raddr.addr.ss_family == AF_UNIX)
2053 libpq_append_conn_error(conn, "\tIs the server running locally and accepting connections on that socket?");
2054 else
2055 libpq_append_conn_error(conn, "\tIs the server running on that host and accepting TCP/IP connections?");
2059 * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
2060 * conn->keepalives is set to a value which is not parseable as an
2061 * integer.
2063 static int
2064 useKeepalives(PGconn *conn)
2066 char *ep;
2067 int val;
2069 if (conn->keepalives == NULL)
2070 return 1;
2071 val = strtol(conn->keepalives, &ep, 10);
2072 if (*ep)
2073 return -1;
2074 return val != 0 ? 1 : 0;
2077 #ifndef WIN32
2079 * Set the keepalive idle timer.
2081 static int
2082 setKeepalivesIdle(PGconn *conn)
2084 int idle;
2086 if (conn->keepalives_idle == NULL)
2087 return 1;
2089 if (!pqParseIntParam(conn->keepalives_idle, &idle, conn,
2090 "keepalives_idle"))
2091 return 0;
2092 if (idle < 0)
2093 idle = 0;
2095 #ifdef PG_TCP_KEEPALIVE_IDLE
2096 if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2097 (char *) &idle, sizeof(idle)) < 0)
2099 char sebuf[PG_STRERROR_R_BUFLEN];
2101 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2102 "setsockopt",
2103 PG_TCP_KEEPALIVE_IDLE_STR,
2104 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2105 return 0;
2107 #endif
2109 return 1;
2113 * Set the keepalive interval.
2115 static int
2116 setKeepalivesInterval(PGconn *conn)
2118 int interval;
2120 if (conn->keepalives_interval == NULL)
2121 return 1;
2123 if (!pqParseIntParam(conn->keepalives_interval, &interval, conn,
2124 "keepalives_interval"))
2125 return 0;
2126 if (interval < 0)
2127 interval = 0;
2129 #ifdef TCP_KEEPINTVL
2130 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
2131 (char *) &interval, sizeof(interval)) < 0)
2133 char sebuf[PG_STRERROR_R_BUFLEN];
2135 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2136 "setsockopt",
2137 "TCP_KEEPINTVL",
2138 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2139 return 0;
2141 #endif
2143 return 1;
2147 * Set the count of lost keepalive packets that will trigger a connection
2148 * break.
2150 static int
2151 setKeepalivesCount(PGconn *conn)
2153 int count;
2155 if (conn->keepalives_count == NULL)
2156 return 1;
2158 if (!pqParseIntParam(conn->keepalives_count, &count, conn,
2159 "keepalives_count"))
2160 return 0;
2161 if (count < 0)
2162 count = 0;
2164 #ifdef TCP_KEEPCNT
2165 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
2166 (char *) &count, sizeof(count)) < 0)
2168 char sebuf[PG_STRERROR_R_BUFLEN];
2170 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2171 "setsockopt",
2172 "TCP_KEEPCNT",
2173 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2174 return 0;
2176 #endif
2178 return 1;
2180 #else /* WIN32 */
2181 #ifdef SIO_KEEPALIVE_VALS
2183 * Enable keepalives and set the keepalive values on Win32,
2184 * where they are always set in one batch.
2186 * CAUTION: This needs to be signal safe, since it's used by PQcancel.
2189 pqSetKeepalivesWin32(pgsocket sock, int idle, int interval)
2191 struct tcp_keepalive ka;
2192 DWORD retsize;
2194 if (idle <= 0)
2195 idle = 2 * 60 * 60; /* 2 hours = default */
2196 if (interval <= 0)
2197 interval = 1; /* 1 second = default */
2199 ka.onoff = 1;
2200 ka.keepalivetime = idle * 1000;
2201 ka.keepaliveinterval = interval * 1000;
2203 if (WSAIoctl(sock,
2204 SIO_KEEPALIVE_VALS,
2205 (LPVOID) &ka,
2206 sizeof(ka),
2207 NULL,
2209 &retsize,
2210 NULL,
2211 NULL)
2212 != 0)
2213 return 0;
2214 return 1;
2217 static int
2218 prepKeepalivesWin32(PGconn *conn)
2220 int idle = -1;
2221 int interval = -1;
2223 if (conn->keepalives_idle &&
2224 !pqParseIntParam(conn->keepalives_idle, &idle, conn,
2225 "keepalives_idle"))
2226 return 0;
2227 if (conn->keepalives_interval &&
2228 !pqParseIntParam(conn->keepalives_interval, &interval, conn,
2229 "keepalives_interval"))
2230 return 0;
2232 if (!pqSetKeepalivesWin32(conn->sock, idle, interval))
2234 libpq_append_conn_error(conn, "%s(%s) failed: error code %d",
2235 "WSAIoctl", "SIO_KEEPALIVE_VALS",
2236 WSAGetLastError());
2237 return 0;
2239 return 1;
2241 #endif /* SIO_KEEPALIVE_VALS */
2242 #endif /* WIN32 */
2245 * Set the TCP user timeout.
2247 static int
2248 setTCPUserTimeout(PGconn *conn)
2250 int timeout;
2252 if (conn->pgtcp_user_timeout == NULL)
2253 return 1;
2255 if (!pqParseIntParam(conn->pgtcp_user_timeout, &timeout, conn,
2256 "tcp_user_timeout"))
2257 return 0;
2259 if (timeout < 0)
2260 timeout = 0;
2262 #ifdef TCP_USER_TIMEOUT
2263 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2264 (char *) &timeout, sizeof(timeout)) < 0)
2266 char sebuf[256];
2268 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2269 "setsockopt",
2270 "TCP_USER_TIMEOUT",
2271 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2272 return 0;
2274 #endif
2276 return 1;
2279 /* ----------
2280 * connectDBStart -
2281 * Begin the process of making a connection to the backend.
2283 * Returns 1 if successful, 0 if not.
2284 * ----------
2286 static int
2287 connectDBStart(PGconn *conn)
2289 if (!conn)
2290 return 0;
2292 if (!conn->options_valid)
2293 goto connect_errReturn;
2296 * Check for bad linking to backend-internal versions of src/common
2297 * functions (see comments in link-canary.c for the reason we need this).
2298 * Nobody but developers should see this message, so we don't bother
2299 * translating it.
2301 if (!pg_link_canary_is_frontend())
2303 appendPQExpBufferStr(&conn->errorMessage,
2304 "libpq is incorrectly linked to backend functions\n");
2305 goto connect_errReturn;
2308 /* Ensure our buffers are empty */
2309 conn->inStart = conn->inCursor = conn->inEnd = 0;
2310 conn->outCount = 0;
2313 * Set up to try to connect to the first host. (Setting whichhost = -1 is
2314 * a bit of a cheat, but PQconnectPoll will advance it to 0 before
2315 * anything else looks at it.)
2317 conn->whichhost = -1;
2318 conn->try_next_addr = false;
2319 conn->try_next_host = true;
2320 conn->status = CONNECTION_NEEDED;
2322 /* Also reset the target_server_type state if needed */
2323 if (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY_PASS2)
2324 conn->target_server_type = SERVER_TYPE_PREFER_STANDBY;
2327 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
2328 * so that it can easily be re-executed if needed again during the
2329 * asynchronous startup process. However, we must run it once here,
2330 * because callers expect a success return from this routine to mean that
2331 * we are in PGRES_POLLING_WRITING connection state.
2333 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
2334 return 1;
2336 connect_errReturn:
2339 * If we managed to open a socket, close it immediately rather than
2340 * waiting till PQfinish. (The application cannot have gotten the socket
2341 * from PQsocket yet, so this doesn't risk breaking anything.)
2343 pqDropConnection(conn, true);
2344 conn->status = CONNECTION_BAD;
2345 return 0;
2350 * connectDBComplete
2352 * Block and complete a connection.
2354 * Returns 1 on success, 0 on failure.
2356 static int
2357 connectDBComplete(PGconn *conn)
2359 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
2360 time_t finish_time = ((time_t) -1);
2361 int timeout = 0;
2362 int last_whichhost = -2; /* certainly different from whichhost */
2363 int last_whichaddr = -2; /* certainly different from whichaddr */
2365 if (conn == NULL || conn->status == CONNECTION_BAD)
2366 return 0;
2369 * Set up a time limit, if connect_timeout isn't zero.
2371 if (conn->connect_timeout != NULL)
2373 if (!pqParseIntParam(conn->connect_timeout, &timeout, conn,
2374 "connect_timeout"))
2376 /* mark the connection as bad to report the parsing failure */
2377 conn->status = CONNECTION_BAD;
2378 return 0;
2381 if (timeout > 0)
2384 * Rounding could cause connection to fail unexpectedly quickly;
2385 * to prevent possibly waiting hardly-at-all, insist on at least
2386 * two seconds.
2388 if (timeout < 2)
2389 timeout = 2;
2391 else /* negative means 0 */
2392 timeout = 0;
2395 for (;;)
2397 int ret = 0;
2400 * (Re)start the connect_timeout timer if it's active and we are
2401 * considering a different host than we were last time through. If
2402 * we've already succeeded, though, needn't recalculate.
2404 if (flag != PGRES_POLLING_OK &&
2405 timeout > 0 &&
2406 (conn->whichhost != last_whichhost ||
2407 conn->whichaddr != last_whichaddr))
2409 finish_time = time(NULL) + timeout;
2410 last_whichhost = conn->whichhost;
2411 last_whichaddr = conn->whichaddr;
2415 * Wait, if necessary. Note that the initial state (just after
2416 * PQconnectStart) is to wait for the socket to select for writing.
2418 switch (flag)
2420 case PGRES_POLLING_OK:
2421 return 1; /* success! */
2423 case PGRES_POLLING_READING:
2424 ret = pqWaitTimed(1, 0, conn, finish_time);
2425 if (ret == -1)
2427 /* hard failure, eg select() problem, aborts everything */
2428 conn->status = CONNECTION_BAD;
2429 return 0;
2431 break;
2433 case PGRES_POLLING_WRITING:
2434 ret = pqWaitTimed(0, 1, conn, finish_time);
2435 if (ret == -1)
2437 /* hard failure, eg select() problem, aborts everything */
2438 conn->status = CONNECTION_BAD;
2439 return 0;
2441 break;
2443 default:
2444 /* Just in case we failed to set it in PQconnectPoll */
2445 conn->status = CONNECTION_BAD;
2446 return 0;
2449 if (ret == 1) /* connect_timeout elapsed */
2452 * Give up on current server/address, try the next one.
2454 conn->try_next_addr = true;
2455 conn->status = CONNECTION_NEEDED;
2459 * Now try to advance the state machine.
2461 flag = PQconnectPoll(conn);
2465 /* ----------------
2466 * PQconnectPoll
2468 * Poll an asynchronous connection.
2470 * Returns a PostgresPollingStatusType.
2471 * Before calling this function, use select(2) to determine when data
2472 * has arrived..
2474 * You must call PQfinish whether or not this fails.
2476 * This function and PQconnectStart are intended to allow connections to be
2477 * made without blocking the execution of your program on remote I/O. However,
2478 * there are a number of caveats:
2480 * o If you call PQtrace, ensure that the stream object into which you trace
2481 * will not block.
2482 * o If you do not supply an IP address for the remote host (i.e. you
2483 * supply a host name instead) then PQconnectStart will block on
2484 * getaddrinfo. You will be fine if using Unix sockets (i.e. by
2485 * supplying neither a host name nor a host address).
2486 * o If your backend wants to use Kerberos authentication then you must
2487 * supply both a host name and a host address, otherwise this function
2488 * may block on gethostname.
2490 * ----------------
2492 PostgresPollingStatusType
2493 PQconnectPoll(PGconn *conn)
2495 bool reset_connection_state_machine = false;
2496 bool need_new_connection = false;
2497 PGresult *res;
2498 char sebuf[PG_STRERROR_R_BUFLEN];
2499 int optval;
2501 if (conn == NULL)
2502 return PGRES_POLLING_FAILED;
2504 /* Get the new data */
2505 switch (conn->status)
2508 * We really shouldn't have been polled in these two cases, but we
2509 * can handle it.
2511 case CONNECTION_BAD:
2512 return PGRES_POLLING_FAILED;
2513 case CONNECTION_OK:
2514 return PGRES_POLLING_OK;
2516 /* These are reading states */
2517 case CONNECTION_AWAITING_RESPONSE:
2518 case CONNECTION_AUTH_OK:
2519 case CONNECTION_CHECK_WRITABLE:
2520 case CONNECTION_CONSUME:
2521 case CONNECTION_CHECK_STANDBY:
2523 /* Load waiting data */
2524 int n = pqReadData(conn);
2526 if (n < 0)
2527 goto error_return;
2528 if (n == 0)
2529 return PGRES_POLLING_READING;
2531 break;
2534 /* These are writing states, so we just proceed. */
2535 case CONNECTION_STARTED:
2536 case CONNECTION_MADE:
2537 break;
2539 /* Special cases: proceed without waiting. */
2540 case CONNECTION_SSL_STARTUP:
2541 case CONNECTION_NEEDED:
2542 case CONNECTION_GSS_STARTUP:
2543 case CONNECTION_CHECK_TARGET:
2544 break;
2546 default:
2547 libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2548 goto error_return;
2552 keep_going: /* We will come back to here until there is
2553 * nothing left to do. */
2555 /* Time to advance to next address, or next host if no more addresses? */
2556 if (conn->try_next_addr)
2558 if (conn->whichaddr < conn->naddr)
2560 conn->whichaddr++;
2561 reset_connection_state_machine = true;
2563 else
2564 conn->try_next_host = true;
2565 conn->try_next_addr = false;
2568 /* Time to advance to next connhost[] entry? */
2569 if (conn->try_next_host)
2571 pg_conn_host *ch;
2572 struct addrinfo hint;
2573 struct addrinfo *addrlist;
2574 int thisport;
2575 int ret;
2576 char portstr[MAXPGPATH];
2578 if (conn->whichhost + 1 < conn->nconnhost)
2579 conn->whichhost++;
2580 else
2583 * Oops, no more hosts.
2585 * If we are trying to connect in "prefer-standby" mode, then drop
2586 * the standby requirement and start over.
2588 * Otherwise, an appropriate error message is already set up, so
2589 * we just need to set the right status.
2591 if (conn->target_server_type == SERVER_TYPE_PREFER_STANDBY &&
2592 conn->nconnhost > 0)
2594 conn->target_server_type = SERVER_TYPE_PREFER_STANDBY_PASS2;
2595 conn->whichhost = 0;
2597 else
2598 goto error_return;
2601 /* Drop any address info for previous host */
2602 release_conn_addrinfo(conn);
2605 * Look up info for the new host. On failure, log the problem in
2606 * conn->errorMessage, then loop around to try the next host. (Note
2607 * we don't clear try_next_host until we've succeeded.)
2609 ch = &conn->connhost[conn->whichhost];
2611 /* Initialize hint structure */
2612 MemSet(&hint, 0, sizeof(hint));
2613 hint.ai_socktype = SOCK_STREAM;
2614 hint.ai_family = AF_UNSPEC;
2616 /* Figure out the port number we're going to use. */
2617 if (ch->port == NULL || ch->port[0] == '\0')
2618 thisport = DEF_PGPORT;
2619 else
2621 if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
2622 goto error_return;
2624 if (thisport < 1 || thisport > 65535)
2626 libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2627 goto keep_going;
2630 snprintf(portstr, sizeof(portstr), "%d", thisport);
2632 /* Use pg_getaddrinfo_all() to resolve the address */
2633 switch (ch->type)
2635 case CHT_HOST_NAME:
2636 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2637 &addrlist);
2638 if (ret || !addrlist)
2640 libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2641 ch->host, gai_strerror(ret));
2642 goto keep_going;
2644 break;
2646 case CHT_HOST_ADDRESS:
2647 hint.ai_flags = AI_NUMERICHOST;
2648 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2649 &addrlist);
2650 if (ret || !addrlist)
2652 libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2653 ch->hostaddr, gai_strerror(ret));
2654 goto keep_going;
2656 break;
2658 case CHT_UNIX_SOCKET:
2659 hint.ai_family = AF_UNIX;
2660 UNIXSOCK_PATH(portstr, thisport, ch->host);
2661 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2663 libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2664 portstr,
2665 (int) (UNIXSOCK_PATH_BUFLEN - 1));
2666 goto keep_going;
2670 * NULL hostname tells pg_getaddrinfo_all to parse the service
2671 * name as a Unix-domain socket path.
2673 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2674 &addrlist);
2675 if (ret || !addrlist)
2677 libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2678 portstr, gai_strerror(ret));
2679 goto keep_going;
2681 break;
2685 * Store a copy of the addrlist in private memory so we can perform
2686 * randomization for load balancing.
2688 ret = store_conn_addrinfo(conn, addrlist);
2689 pg_freeaddrinfo_all(hint.ai_family, addrlist);
2690 if (ret)
2691 goto error_return; /* message already logged */
2694 * If random load balancing is enabled we shuffle the addresses.
2696 if (conn->load_balance_type == LOAD_BALANCE_RANDOM)
2699 * This is the "inside-out" variant of the Fisher-Yates shuffle
2700 * algorithm. Notionally, we append each new value to the array
2701 * and then swap it with a randomly-chosen array element (possibly
2702 * including itself, else we fail to generate permutations with
2703 * the last integer last). The swap step can be optimized by
2704 * combining it with the insertion.
2706 * We don't need to initialize conn->prng_state here, because that
2707 * already happened in connectOptions2.
2709 for (int i = 1; i < conn->naddr; i++)
2711 int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2712 AddrInfo temp = conn->addr[j];
2714 conn->addr[j] = conn->addr[i];
2715 conn->addr[i] = temp;
2719 reset_connection_state_machine = true;
2720 conn->try_next_host = false;
2723 /* Reset connection state machine? */
2724 if (reset_connection_state_machine)
2727 * (Re) initialize our connection control variables for a set of
2728 * connection attempts to a single server address. These variables
2729 * must persist across individual connection attempts, but we must
2730 * reset them when we start to consider a new server.
2732 conn->pversion = PG_PROTOCOL(3, 0);
2733 conn->send_appname = true;
2734 #ifdef USE_SSL
2735 /* initialize these values based on SSL mode */
2736 conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2737 conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2738 #endif
2739 #ifdef ENABLE_GSS
2740 conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2741 #endif
2743 reset_connection_state_machine = false;
2744 need_new_connection = true;
2747 /* Force a new connection (perhaps to the same server as before)? */
2748 if (need_new_connection)
2750 /* Drop any existing connection */
2751 pqDropConnection(conn, true);
2753 /* Reset all state obtained from old server */
2754 pqDropServerData(conn);
2756 /* Drop any PGresult we might have, too */
2757 conn->asyncStatus = PGASYNC_IDLE;
2758 conn->xactStatus = PQTRANS_IDLE;
2759 conn->pipelineStatus = PQ_PIPELINE_OFF;
2760 pqClearAsyncResult(conn);
2762 /* Reset conn->status to put the state machine in the right state */
2763 conn->status = CONNECTION_NEEDED;
2765 need_new_connection = false;
2768 /* Now try to advance the state machine for this connection */
2769 switch (conn->status)
2771 case CONNECTION_NEEDED:
2774 * Try to initiate a connection to one of the addresses
2775 * returned by pg_getaddrinfo_all(). conn->whichaddr is the
2776 * next one to try.
2778 * The extra level of braces here is historical. It's not
2779 * worth reindenting this whole switch case to remove 'em.
2782 char host_addr[NI_MAXHOST];
2783 int sock_type;
2784 AddrInfo *addr_cur;
2787 * Advance to next possible host, if we've tried all of
2788 * the addresses for the current host.
2790 if (conn->whichaddr == conn->naddr)
2792 conn->try_next_host = true;
2793 goto keep_going;
2795 addr_cur = &conn->addr[conn->whichaddr];
2797 /* Remember current address for possible use later */
2798 memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
2801 * Set connip, too. Note we purposely ignore strdup
2802 * failure; not a big problem if it fails.
2804 if (conn->connip != NULL)
2806 free(conn->connip);
2807 conn->connip = NULL;
2809 getHostaddr(conn, host_addr, NI_MAXHOST);
2810 if (host_addr[0])
2811 conn->connip = strdup(host_addr);
2813 /* Try to create the socket */
2814 sock_type = SOCK_STREAM;
2815 #ifdef SOCK_CLOEXEC
2818 * Atomically mark close-on-exec, if possible on this
2819 * platform, so that there isn't a window where a
2820 * subprogram executed by another thread inherits the
2821 * socket. See fallback code below.
2823 sock_type |= SOCK_CLOEXEC;
2824 #endif
2825 #ifdef SOCK_NONBLOCK
2828 * We might as well skip a system call for nonblocking
2829 * mode too, if we can.
2831 sock_type |= SOCK_NONBLOCK;
2832 #endif
2833 conn->sock = socket(addr_cur->family, sock_type, 0);
2834 if (conn->sock == PGINVALID_SOCKET)
2836 int errorno = SOCK_ERRNO;
2839 * Silently ignore socket() failure if we have more
2840 * addresses to try; this reduces useless chatter in
2841 * cases where the address list includes both IPv4 and
2842 * IPv6 but kernel only accepts one family.
2844 if (conn->whichaddr < conn->naddr ||
2845 conn->whichhost + 1 < conn->nconnhost)
2847 conn->try_next_addr = true;
2848 goto keep_going;
2850 emitHostIdentityInfo(conn, host_addr);
2851 libpq_append_conn_error(conn, "could not create socket: %s",
2852 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2853 goto error_return;
2857 * Once we've identified a target address, all errors
2858 * except the preceding socket()-failure case should be
2859 * prefixed with host-identity information. (If the
2860 * connection succeeds, the contents of conn->errorMessage
2861 * won't matter, so this is harmless.)
2863 emitHostIdentityInfo(conn, host_addr);
2866 * Select socket options: no delay of outgoing data for
2867 * TCP sockets, nonblock mode, close-on-exec. Try the
2868 * next address if any of this fails.
2870 if (addr_cur->family != AF_UNIX)
2872 if (!connectNoDelay(conn))
2874 /* error message already created */
2875 conn->try_next_addr = true;
2876 goto keep_going;
2879 #ifndef SOCK_NONBLOCK
2880 if (!pg_set_noblock(conn->sock))
2882 libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
2883 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2884 conn->try_next_addr = true;
2885 goto keep_going;
2887 #endif
2889 #ifndef SOCK_CLOEXEC
2890 #ifdef F_SETFD
2891 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2893 libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
2894 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2895 conn->try_next_addr = true;
2896 goto keep_going;
2898 #endif /* F_SETFD */
2899 #endif
2901 if (addr_cur->family != AF_UNIX)
2903 #ifndef WIN32
2904 int on = 1;
2905 #endif
2906 int usekeepalives = useKeepalives(conn);
2907 int err = 0;
2909 if (usekeepalives < 0)
2911 libpq_append_conn_error(conn, "keepalives parameter must be an integer");
2912 err = 1;
2914 else if (usekeepalives == 0)
2916 /* Do nothing */
2918 #ifndef WIN32
2919 else if (setsockopt(conn->sock,
2920 SOL_SOCKET, SO_KEEPALIVE,
2921 (char *) &on, sizeof(on)) < 0)
2923 libpq_append_conn_error(conn, "%s(%s) failed: %s",
2924 "setsockopt",
2925 "SO_KEEPALIVE",
2926 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2927 err = 1;
2929 else if (!setKeepalivesIdle(conn)
2930 || !setKeepalivesInterval(conn)
2931 || !setKeepalivesCount(conn))
2932 err = 1;
2933 #else /* WIN32 */
2934 #ifdef SIO_KEEPALIVE_VALS
2935 else if (!prepKeepalivesWin32(conn))
2936 err = 1;
2937 #endif /* SIO_KEEPALIVE_VALS */
2938 #endif /* WIN32 */
2939 else if (!setTCPUserTimeout(conn))
2940 err = 1;
2942 if (err)
2944 conn->try_next_addr = true;
2945 goto keep_going;
2949 /*----------
2950 * We have three methods of blocking SIGPIPE during
2951 * send() calls to this socket:
2953 * - setsockopt(sock, SO_NOSIGPIPE)
2954 * - send(sock, ..., MSG_NOSIGNAL)
2955 * - setting the signal mask to SIG_IGN during send()
2957 * The third method requires three syscalls per send,
2958 * so we prefer either of the first two, but they are
2959 * less portable. The state is tracked in the following
2960 * members of PGconn:
2962 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2963 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2965 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2966 * and we're done. Otherwise, set sigpipe_flag so that
2967 * we will try MSG_NOSIGNAL on sends. If we get an error
2968 * with MSG_NOSIGNAL, we'll clear that flag and revert to
2969 * signal masking.
2970 *----------
2972 conn->sigpipe_so = false;
2973 #ifdef MSG_NOSIGNAL
2974 conn->sigpipe_flag = true;
2975 #else
2976 conn->sigpipe_flag = false;
2977 #endif /* MSG_NOSIGNAL */
2979 #ifdef SO_NOSIGPIPE
2980 optval = 1;
2981 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2982 (char *) &optval, sizeof(optval)) == 0)
2984 conn->sigpipe_so = true;
2985 conn->sigpipe_flag = false;
2987 #endif /* SO_NOSIGPIPE */
2990 * Start/make connection. This should not block, since we
2991 * are in nonblock mode. If it does, well, too bad.
2993 if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
2994 addr_cur->addr.salen) < 0)
2996 if (SOCK_ERRNO == EINPROGRESS ||
2997 #ifdef WIN32
2998 SOCK_ERRNO == EWOULDBLOCK ||
2999 #endif
3000 SOCK_ERRNO == EINTR)
3003 * This is fine - we're in non-blocking mode, and
3004 * the connection is in progress. Tell caller to
3005 * wait for write-ready on socket.
3007 conn->status = CONNECTION_STARTED;
3008 return PGRES_POLLING_WRITING;
3010 /* otherwise, trouble */
3012 else
3015 * Hm, we're connected already --- seems the "nonblock
3016 * connection" wasn't. Advance the state machine and
3017 * go do the next stuff.
3019 conn->status = CONNECTION_STARTED;
3020 goto keep_going;
3024 * This connection failed. Add the error report to
3025 * conn->errorMessage, then try the next address if any.
3027 connectFailureMessage(conn, SOCK_ERRNO);
3028 conn->try_next_addr = true;
3029 goto keep_going;
3033 case CONNECTION_STARTED:
3035 socklen_t optlen = sizeof(optval);
3038 * Write ready, since we've made it here, so the connection
3039 * has been made ... or has failed.
3043 * Now check (using getsockopt) that there is not an error
3044 * state waiting for us on the socket.
3047 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3048 (char *) &optval, &optlen) == -1)
3050 libpq_append_conn_error(conn, "could not get socket error status: %s",
3051 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3052 goto error_return;
3054 else if (optval != 0)
3057 * When using a nonblocking connect, we will typically see
3058 * connect failures at this point, so provide a friendly
3059 * error message.
3061 connectFailureMessage(conn, optval);
3064 * Try the next address if any, just as in the case where
3065 * connect() returned failure immediately.
3067 conn->try_next_addr = true;
3068 goto keep_going;
3071 /* Fill in the client address */
3072 conn->laddr.salen = sizeof(conn->laddr.addr);
3073 if (getsockname(conn->sock,
3074 (struct sockaddr *) &conn->laddr.addr,
3075 &conn->laddr.salen) < 0)
3077 libpq_append_conn_error(conn, "could not get client address from socket: %s",
3078 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3079 goto error_return;
3083 * Make sure we can write before advancing to next step.
3085 conn->status = CONNECTION_MADE;
3086 return PGRES_POLLING_WRITING;
3089 case CONNECTION_MADE:
3091 char *startpacket;
3092 int packetlen;
3095 * Implement requirepeer check, if requested and it's a
3096 * Unix-domain socket.
3098 if (conn->requirepeer && conn->requirepeer[0] &&
3099 conn->raddr.addr.ss_family == AF_UNIX)
3101 #ifndef WIN32
3102 char *remote_username;
3103 #endif
3104 uid_t uid;
3105 gid_t gid;
3107 errno = 0;
3108 if (getpeereid(conn->sock, &uid, &gid) != 0)
3111 * Provide special error message if getpeereid is a
3112 * stub
3114 if (errno == ENOSYS)
3115 libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3116 else
3117 libpq_append_conn_error(conn, "could not get peer credentials: %s",
3118 strerror_r(errno, sebuf, sizeof(sebuf)));
3119 goto error_return;
3122 #ifndef WIN32
3123 remote_username = pg_fe_getusername(uid,
3124 &conn->errorMessage);
3125 if (remote_username == NULL)
3126 goto error_return; /* message already logged */
3128 if (strcmp(remote_username, conn->requirepeer) != 0)
3130 libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3131 conn->requirepeer, remote_username);
3132 free(remote_username);
3133 goto error_return;
3135 free(remote_username);
3136 #else /* WIN32 */
3137 /* should have failed with ENOSYS above */
3138 Assert(false);
3139 #endif /* WIN32 */
3142 if (conn->raddr.addr.ss_family == AF_UNIX)
3144 /* Don't request SSL or GSSAPI over Unix sockets */
3145 #ifdef USE_SSL
3146 conn->allow_ssl_try = false;
3147 #endif
3148 #ifdef ENABLE_GSS
3149 conn->try_gss = false;
3150 #endif
3153 #ifdef ENABLE_GSS
3156 * If GSSAPI encryption is enabled, then call
3157 * pg_GSS_have_cred_cache() which will return true if we can
3158 * acquire credentials (and give us a handle to use in
3159 * conn->gcred), and then send a packet to the server asking
3160 * for GSSAPI Encryption (and skip past SSL negotiation and
3161 * regular startup below).
3163 if (conn->try_gss && !conn->gctx)
3164 conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
3165 if (conn->try_gss && !conn->gctx)
3167 ProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);
3169 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3171 libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3172 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3173 goto error_return;
3176 /* Ok, wait for response */
3177 conn->status = CONNECTION_GSS_STARTUP;
3178 return PGRES_POLLING_READING;
3180 else if (!conn->gctx && conn->gssencmode[0] == 'r')
3182 libpq_append_conn_error(conn,
3183 "GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)");
3184 goto error_return;
3186 #endif
3188 #ifdef USE_SSL
3191 * Enable the libcrypto callbacks before checking if SSL needs
3192 * to be done. This is done before sending the startup packet
3193 * as depending on the type of authentication done, like MD5
3194 * or SCRAM that use cryptohashes, the callbacks would be
3195 * required even without a SSL connection
3197 if (pqsecure_initialize(conn, false, true) < 0)
3198 goto error_return;
3201 * If SSL is enabled and we haven't already got encryption of
3202 * some sort running, request SSL instead of sending the
3203 * startup message.
3205 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
3206 !conn->ssl_in_use
3207 #ifdef ENABLE_GSS
3208 && !conn->gssenc
3209 #endif
3212 ProtocolVersion pv;
3215 * Send the SSL request packet.
3217 * Theoretically, this could block, but it really
3218 * shouldn't since we only got here if the socket is
3219 * write-ready.
3221 pv = pg_hton32(NEGOTIATE_SSL_CODE);
3222 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3224 libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3225 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3226 goto error_return;
3228 /* Ok, wait for response */
3229 conn->status = CONNECTION_SSL_STARTUP;
3230 return PGRES_POLLING_READING;
3232 #endif /* USE_SSL */
3235 * Build the startup packet.
3237 startpacket = pqBuildStartupPacket3(conn, &packetlen,
3238 EnvironmentOptions);
3239 if (!startpacket)
3241 libpq_append_conn_error(conn, "out of memory");
3242 goto error_return;
3246 * Send the startup packet.
3248 * Theoretically, this could block, but it really shouldn't
3249 * since we only got here if the socket is write-ready.
3251 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3253 libpq_append_conn_error(conn, "could not send startup packet: %s",
3254 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3255 free(startpacket);
3256 goto error_return;
3259 free(startpacket);
3261 conn->status = CONNECTION_AWAITING_RESPONSE;
3262 return PGRES_POLLING_READING;
3266 * Handle SSL negotiation: wait for postmaster messages and
3267 * respond as necessary.
3269 case CONNECTION_SSL_STARTUP:
3271 #ifdef USE_SSL
3272 PostgresPollingStatusType pollres;
3275 * On first time through, get the postmaster's response to our
3276 * SSL negotiation packet.
3278 if (!conn->ssl_in_use)
3281 * We use pqReadData here since it has the logic to
3282 * distinguish no-data-yet from connection closure. Since
3283 * conn->ssl isn't set, a plain recv() will occur.
3285 char SSLok;
3286 int rdresult;
3288 rdresult = pqReadData(conn);
3289 if (rdresult < 0)
3291 /* errorMessage is already filled in */
3292 goto error_return;
3294 if (rdresult == 0)
3296 /* caller failed to wait for data */
3297 return PGRES_POLLING_READING;
3299 if (pqGetc(&SSLok, conn) < 0)
3301 /* should not happen really */
3302 return PGRES_POLLING_READING;
3304 if (SSLok == 'S')
3306 /* mark byte consumed */
3307 conn->inStart = conn->inCursor;
3310 * Set up global SSL state if required. The crypto
3311 * state has already been set if libpq took care of
3312 * doing that, so there is no need to make that happen
3313 * again.
3315 if (pqsecure_initialize(conn, true, false) != 0)
3316 goto error_return;
3318 else if (SSLok == 'N')
3320 /* mark byte consumed */
3321 conn->inStart = conn->inCursor;
3322 /* OK to do without SSL? */
3323 if (conn->sslmode[0] == 'r' || /* "require" */
3324 conn->sslmode[0] == 'v') /* "verify-ca" or
3325 * "verify-full" */
3327 /* Require SSL, but server does not want it */
3328 libpq_append_conn_error(conn, "server does not support SSL, but SSL was required");
3329 goto error_return;
3331 /* Otherwise, proceed with normal startup */
3332 conn->allow_ssl_try = false;
3333 /* We can proceed using this connection */
3334 conn->status = CONNECTION_MADE;
3335 return PGRES_POLLING_WRITING;
3337 else if (SSLok == 'E')
3340 * Server failure of some sort, such as failure to
3341 * fork a backend process. We need to process and
3342 * report the error message, which might be formatted
3343 * according to either protocol 2 or protocol 3.
3344 * Rather than duplicate the code for that, we flip
3345 * into AWAITING_RESPONSE state and let the code there
3346 * deal with it. Note we have *not* consumed the "E"
3347 * byte here.
3349 conn->status = CONNECTION_AWAITING_RESPONSE;
3350 goto keep_going;
3352 else
3354 libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3355 SSLok);
3356 goto error_return;
3361 * Begin or continue the SSL negotiation process.
3363 pollres = pqsecure_open_client(conn);
3364 if (pollres == PGRES_POLLING_OK)
3367 * At this point we should have no data already buffered.
3368 * If we do, it was received before we performed the SSL
3369 * handshake, so it wasn't encrypted and indeed may have
3370 * been injected by a man-in-the-middle.
3372 if (conn->inCursor != conn->inEnd)
3374 libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3375 goto error_return;
3378 /* SSL handshake done, ready to send startup packet */
3379 conn->status = CONNECTION_MADE;
3380 return PGRES_POLLING_WRITING;
3382 if (pollres == PGRES_POLLING_FAILED)
3385 * Failed ... if sslmode is "prefer" then do a non-SSL
3386 * retry
3388 if (conn->sslmode[0] == 'p' /* "prefer" */
3389 && conn->allow_ssl_try /* redundant? */
3390 && !conn->wait_ssl_try) /* redundant? */
3392 /* only retry once */
3393 conn->allow_ssl_try = false;
3394 need_new_connection = true;
3395 goto keep_going;
3397 /* Else it's a hard failure */
3398 goto error_return;
3400 /* Else, return POLLING_READING or POLLING_WRITING status */
3401 return pollres;
3402 #else /* !USE_SSL */
3403 /* can't get here */
3404 goto error_return;
3405 #endif /* USE_SSL */
3408 case CONNECTION_GSS_STARTUP:
3410 #ifdef ENABLE_GSS
3411 PostgresPollingStatusType pollres;
3414 * If we haven't yet, get the postmaster's response to our
3415 * negotiation packet
3417 if (conn->try_gss && !conn->gctx)
3419 char gss_ok;
3420 int rdresult = pqReadData(conn);
3422 if (rdresult < 0)
3423 /* pqReadData fills in error message */
3424 goto error_return;
3425 else if (rdresult == 0)
3426 /* caller failed to wait for data */
3427 return PGRES_POLLING_READING;
3428 if (pqGetc(&gss_ok, conn) < 0)
3429 /* shouldn't happen... */
3430 return PGRES_POLLING_READING;
3432 if (gss_ok == 'E')
3435 * Server failure of some sort. Assume it's a
3436 * protocol version support failure, and let's see if
3437 * we can't recover (if it's not, we'll get a better
3438 * error message on retry). Server gets fussy if we
3439 * don't hang up the socket, though.
3441 conn->try_gss = false;
3442 need_new_connection = true;
3443 goto keep_going;
3446 /* mark byte consumed */
3447 conn->inStart = conn->inCursor;
3449 if (gss_ok == 'N')
3451 /* Server doesn't want GSSAPI; fall back if we can */
3452 if (conn->gssencmode[0] == 'r')
3454 libpq_append_conn_error(conn, "server doesn't support GSSAPI encryption, but it was required");
3455 goto error_return;
3458 conn->try_gss = false;
3459 /* We can proceed using this connection */
3460 conn->status = CONNECTION_MADE;
3461 return PGRES_POLLING_WRITING;
3463 else if (gss_ok != 'G')
3465 libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3466 gss_ok);
3467 goto error_return;
3471 /* Begin or continue GSSAPI negotiation */
3472 pollres = pqsecure_open_gss(conn);
3473 if (pollres == PGRES_POLLING_OK)
3476 * At this point we should have no data already buffered.
3477 * If we do, it was received before we performed the GSS
3478 * handshake, so it wasn't encrypted and indeed may have
3479 * been injected by a man-in-the-middle.
3481 if (conn->inCursor != conn->inEnd)
3483 libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3484 goto error_return;
3487 /* All set for startup packet */
3488 conn->status = CONNECTION_MADE;
3489 return PGRES_POLLING_WRITING;
3491 else if (pollres == PGRES_POLLING_FAILED)
3493 if (conn->gssencmode[0] == 'p')
3496 * We failed, but we can retry on "prefer". Have to
3497 * drop the current connection to do so, though.
3499 conn->try_gss = false;
3500 need_new_connection = true;
3501 goto keep_going;
3503 /* Else it's a hard failure */
3504 goto error_return;
3506 /* Else, return POLLING_READING or POLLING_WRITING status */
3507 return pollres;
3508 #else /* !ENABLE_GSS */
3509 /* unreachable */
3510 goto error_return;
3511 #endif /* ENABLE_GSS */
3515 * Handle authentication exchange: wait for postmaster messages
3516 * and respond as necessary.
3518 case CONNECTION_AWAITING_RESPONSE:
3520 char beresp;
3521 int msgLength;
3522 int avail;
3523 AuthRequest areq;
3524 int res;
3527 * Scan the message from current point (note that if we find
3528 * the message is incomplete, we will return without advancing
3529 * inStart, and resume here next time).
3531 conn->inCursor = conn->inStart;
3533 /* Read type byte */
3534 if (pqGetc(&beresp, conn))
3536 /* We'll come back when there is more data */
3537 return PGRES_POLLING_READING;
3541 * Validate message type: we expect only an authentication
3542 * request, NegotiateProtocolVersion, or an error here.
3543 * Anything else probably means it's not Postgres on the other
3544 * end at all.
3546 if (beresp != PqMsg_AuthenticationRequest &&
3547 beresp != PqMsg_ErrorResponse &&
3548 beresp != PqMsg_NegotiateProtocolVersion)
3550 libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3551 beresp);
3552 goto error_return;
3555 /* Read message length word */
3556 if (pqGetInt(&msgLength, 4, conn))
3558 /* We'll come back when there is more data */
3559 return PGRES_POLLING_READING;
3563 * Try to validate message length before using it.
3565 * Authentication requests can't be very large, although GSS
3566 * auth requests may not be that small. Same for
3567 * NegotiateProtocolVersion.
3569 * Errors can be a little larger, but not huge. If we see a
3570 * large apparent length in an error, it means we're really
3571 * talking to a pre-3.0-protocol server; cope. (Before
3572 * version 14, the server also used the old protocol for
3573 * errors that happened before processing the startup packet.)
3575 if (beresp == PqMsg_AuthenticationRequest &&
3576 (msgLength < 8 || msgLength > 2000))
3578 libpq_append_conn_error(conn, "received invalid authentication request");
3579 goto error_return;
3581 if (beresp == PqMsg_NegotiateProtocolVersion &&
3582 (msgLength < 8 || msgLength > 2000))
3584 libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3585 goto error_return;
3588 #define MAX_ERRLEN 30000
3589 if (beresp == PqMsg_ErrorResponse &&
3590 (msgLength < 8 || msgLength > MAX_ERRLEN))
3592 /* Handle error from a pre-3.0 server */
3593 conn->inCursor = conn->inStart + 1; /* reread data */
3594 if (pqGets_append(&conn->errorMessage, conn))
3597 * We may not have authenticated the server yet, so
3598 * don't let the buffer grow forever.
3600 avail = conn->inEnd - conn->inCursor;
3601 if (avail > MAX_ERRLEN)
3603 libpq_append_conn_error(conn, "received invalid error message");
3604 goto error_return;
3607 /* We'll come back when there is more data */
3608 return PGRES_POLLING_READING;
3610 /* OK, we read the message; mark data consumed */
3611 conn->inStart = conn->inCursor;
3614 * Before 7.2, the postmaster didn't always end its
3615 * messages with a newline, so add one if needed to
3616 * conform to libpq conventions.
3618 if (conn->errorMessage.len == 0 ||
3619 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3621 appendPQExpBufferChar(&conn->errorMessage, '\n');
3624 goto error_return;
3626 #undef MAX_ERRLEN
3629 * Can't process if message body isn't all here yet.
3631 * After this check passes, any further EOF during parsing
3632 * implies that the server sent a bad/truncated message.
3633 * Reading more bytes won't help in that case, so don't return
3634 * PGRES_POLLING_READING after this point.
3636 msgLength -= 4;
3637 avail = conn->inEnd - conn->inCursor;
3638 if (avail < msgLength)
3641 * Before returning, try to enlarge the input buffer if
3642 * needed to hold the whole message; see notes in
3643 * pqParseInput3.
3645 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3646 conn))
3647 goto error_return;
3648 /* We'll come back when there is more data */
3649 return PGRES_POLLING_READING;
3652 /* Handle errors. */
3653 if (beresp == PqMsg_ErrorResponse)
3655 if (pqGetErrorNotice3(conn, true))
3657 libpq_append_conn_error(conn, "received invalid error message");
3658 goto error_return;
3660 /* OK, we read the message; mark data consumed */
3661 conn->inStart = conn->inCursor;
3664 * If error is "cannot connect now", try the next host if
3665 * any (but we don't want to consider additional addresses
3666 * for this host, nor is there much point in changing SSL
3667 * or GSS mode). This is helpful when dealing with
3668 * standby servers that might not be in hot-standby state.
3670 if (strcmp(conn->last_sqlstate,
3671 ERRCODE_CANNOT_CONNECT_NOW) == 0)
3673 conn->try_next_host = true;
3674 goto keep_going;
3677 /* Check to see if we should mention pgpassfile */
3678 pgpassfileWarning(conn);
3680 #ifdef ENABLE_GSS
3683 * If gssencmode is "prefer" and we're using GSSAPI, retry
3684 * without it.
3686 if (conn->gssenc && conn->gssencmode[0] == 'p')
3688 /* only retry once */
3689 conn->try_gss = false;
3690 need_new_connection = true;
3691 goto keep_going;
3693 #endif
3695 #ifdef USE_SSL
3698 * if sslmode is "allow" and we haven't tried an SSL
3699 * connection already, then retry with an SSL connection
3701 if (conn->sslmode[0] == 'a' /* "allow" */
3702 && !conn->ssl_in_use
3703 && conn->allow_ssl_try
3704 && conn->wait_ssl_try)
3706 /* only retry once */
3707 conn->wait_ssl_try = false;
3708 need_new_connection = true;
3709 goto keep_going;
3713 * if sslmode is "prefer" and we're in an SSL connection,
3714 * then do a non-SSL retry
3716 if (conn->sslmode[0] == 'p' /* "prefer" */
3717 && conn->ssl_in_use
3718 && conn->allow_ssl_try /* redundant? */
3719 && !conn->wait_ssl_try) /* redundant? */
3721 /* only retry once */
3722 conn->allow_ssl_try = false;
3723 need_new_connection = true;
3724 goto keep_going;
3726 #endif
3728 goto error_return;
3730 else if (beresp == PqMsg_NegotiateProtocolVersion)
3732 if (pqGetNegotiateProtocolVersion3(conn))
3734 libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3735 goto error_return;
3737 /* OK, we read the message; mark data consumed */
3738 conn->inStart = conn->inCursor;
3739 goto error_return;
3742 /* It is an authentication request. */
3743 conn->auth_req_received = true;
3745 /* Get the type of request. */
3746 if (pqGetInt((int *) &areq, 4, conn))
3748 /* can't happen because we checked the length already */
3749 libpq_append_conn_error(conn, "received invalid authentication request");
3750 goto error_return;
3752 msgLength -= 4;
3755 * Process the rest of the authentication request message, and
3756 * respond to it if necessary.
3758 * Note that conn->pghost must be non-NULL if we are going to
3759 * avoid the Kerberos code doing a hostname look-up.
3761 res = pg_fe_sendauth(areq, msgLength, conn);
3763 /* OK, we have processed the message; mark data consumed */
3764 conn->inStart = conn->inCursor;
3766 if (res != STATUS_OK)
3767 goto error_return;
3770 * Just make sure that any data sent by pg_fe_sendauth is
3771 * flushed out. Although this theoretically could block, it
3772 * really shouldn't since we don't send large auth responses.
3774 if (pqFlush(conn))
3775 goto error_return;
3777 if (areq == AUTH_REQ_OK)
3779 /* We are done with authentication exchange */
3780 conn->status = CONNECTION_AUTH_OK;
3783 * Set asyncStatus so that PQgetResult will think that
3784 * what comes back next is the result of a query. See
3785 * below.
3787 conn->asyncStatus = PGASYNC_BUSY;
3790 /* Look to see if we have more data yet. */
3791 goto keep_going;
3794 case CONNECTION_AUTH_OK:
3797 * Now we expect to hear from the backend. A ReadyForQuery
3798 * message indicates that startup is successful, but we might
3799 * also get an Error message indicating failure. (Notice
3800 * messages indicating nonfatal warnings are also allowed by
3801 * the protocol, as are ParameterStatus and BackendKeyData
3802 * messages.) Easiest way to handle this is to let
3803 * PQgetResult() read the messages. We just have to fake it
3804 * out about the state of the connection, by setting
3805 * asyncStatus = PGASYNC_BUSY (done above).
3808 if (PQisBusy(conn))
3809 return PGRES_POLLING_READING;
3811 res = PQgetResult(conn);
3814 * NULL return indicating we have gone to IDLE state is
3815 * expected
3817 if (res)
3819 if (res->resultStatus != PGRES_FATAL_ERROR)
3820 libpq_append_conn_error(conn, "unexpected message from server during startup");
3821 else if (conn->send_appname &&
3822 (conn->appname || conn->fbappname))
3825 * If we tried to send application_name, check to see
3826 * if the error is about that --- pre-9.0 servers will
3827 * reject it at this stage of the process. If so,
3828 * close the connection and retry without sending
3829 * application_name. We could possibly get a false
3830 * SQLSTATE match here and retry uselessly, but there
3831 * seems no great harm in that; we'll just get the
3832 * same error again if it's unrelated.
3834 const char *sqlstate;
3836 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
3837 if (sqlstate &&
3838 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3840 PQclear(res);
3841 conn->send_appname = false;
3842 need_new_connection = true;
3843 goto keep_going;
3848 * if the resultStatus is FATAL, then conn->errorMessage
3849 * already has a copy of the error; needn't copy it back.
3850 * But add a newline if it's not there already, since
3851 * postmaster error messages may not have one.
3853 if (conn->errorMessage.len <= 0 ||
3854 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3855 appendPQExpBufferChar(&conn->errorMessage, '\n');
3856 PQclear(res);
3857 goto error_return;
3860 /* Almost there now ... */
3861 conn->status = CONNECTION_CHECK_TARGET;
3862 goto keep_going;
3865 case CONNECTION_CHECK_TARGET:
3868 * If a read-write, read-only, primary, or standby connection
3869 * is required, see if we have one.
3871 if (conn->target_server_type == SERVER_TYPE_READ_WRITE ||
3872 conn->target_server_type == SERVER_TYPE_READ_ONLY)
3874 bool read_only_server;
3877 * If the server didn't report
3878 * "default_transaction_read_only" or "in_hot_standby" at
3879 * startup, we must determine its state by sending the
3880 * query "SHOW transaction_read_only". This GUC exists in
3881 * all server versions that support 3.0 protocol.
3883 if (conn->default_transaction_read_only == PG_BOOL_UNKNOWN ||
3884 conn->in_hot_standby == PG_BOOL_UNKNOWN)
3887 * We use PQsendQueryContinue so that
3888 * conn->errorMessage does not get cleared. We need
3889 * to preserve any error messages related to previous
3890 * hosts we have tried and failed to connect to.
3892 conn->status = CONNECTION_OK;
3893 if (!PQsendQueryContinue(conn,
3894 "SHOW transaction_read_only"))
3895 goto error_return;
3896 /* We'll return to this state when we have the answer */
3897 conn->status = CONNECTION_CHECK_WRITABLE;
3898 return PGRES_POLLING_READING;
3901 /* OK, we can make the test */
3902 read_only_server =
3903 (conn->default_transaction_read_only == PG_BOOL_YES ||
3904 conn->in_hot_standby == PG_BOOL_YES);
3906 if ((conn->target_server_type == SERVER_TYPE_READ_WRITE) ?
3907 read_only_server : !read_only_server)
3909 /* Wrong server state, reject and try the next host */
3910 if (conn->target_server_type == SERVER_TYPE_READ_WRITE)
3911 libpq_append_conn_error(conn, "session is read-only");
3912 else
3913 libpq_append_conn_error(conn, "session is not read-only");
3915 /* Close connection politely. */
3916 conn->status = CONNECTION_OK;
3917 sendTerminateConn(conn);
3920 * Try next host if any, but we don't want to consider
3921 * additional addresses for this host.
3923 conn->try_next_host = true;
3924 goto keep_going;
3927 else if (conn->target_server_type == SERVER_TYPE_PRIMARY ||
3928 conn->target_server_type == SERVER_TYPE_STANDBY ||
3929 conn->target_server_type == SERVER_TYPE_PREFER_STANDBY)
3932 * If the server didn't report "in_hot_standby" at
3933 * startup, we must determine its state by sending the
3934 * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
3935 * before 9.0 don't have that function, but by the same
3936 * token they don't have any standby mode, so we may just
3937 * assume the result.
3939 if (conn->sversion < 90000)
3940 conn->in_hot_standby = PG_BOOL_NO;
3942 if (conn->in_hot_standby == PG_BOOL_UNKNOWN)
3945 * We use PQsendQueryContinue so that
3946 * conn->errorMessage does not get cleared. We need
3947 * to preserve any error messages related to previous
3948 * hosts we have tried and failed to connect to.
3950 conn->status = CONNECTION_OK;
3951 if (!PQsendQueryContinue(conn,
3952 "SELECT pg_catalog.pg_is_in_recovery()"))
3953 goto error_return;
3954 /* We'll return to this state when we have the answer */
3955 conn->status = CONNECTION_CHECK_STANDBY;
3956 return PGRES_POLLING_READING;
3959 /* OK, we can make the test */
3960 if ((conn->target_server_type == SERVER_TYPE_PRIMARY) ?
3961 (conn->in_hot_standby == PG_BOOL_YES) :
3962 (conn->in_hot_standby == PG_BOOL_NO))
3964 /* Wrong server state, reject and try the next host */
3965 if (conn->target_server_type == SERVER_TYPE_PRIMARY)
3966 libpq_append_conn_error(conn, "server is in hot standby mode");
3967 else
3968 libpq_append_conn_error(conn, "server is not in hot standby mode");
3970 /* Close connection politely. */
3971 conn->status = CONNECTION_OK;
3972 sendTerminateConn(conn);
3975 * Try next host if any, but we don't want to consider
3976 * additional addresses for this host.
3978 conn->try_next_host = true;
3979 goto keep_going;
3983 /* We can release the address list now. */
3984 release_conn_addrinfo(conn);
3987 * Contents of conn->errorMessage are no longer interesting
3988 * (and it seems some clients expect it to be empty after a
3989 * successful connection).
3991 pqClearConnErrorState(conn);
3993 /* We are open for business! */
3994 conn->status = CONNECTION_OK;
3995 return PGRES_POLLING_OK;
3998 case CONNECTION_CONSUME:
4001 * This state just makes sure the connection is idle after
4002 * we've obtained the result of a SHOW or SELECT query. Once
4003 * we're clear, return to CONNECTION_CHECK_TARGET state to
4004 * decide what to do next. We must transiently set status =
4005 * CONNECTION_OK in order to use the result-consuming
4006 * subroutines.
4008 conn->status = CONNECTION_OK;
4009 if (!PQconsumeInput(conn))
4010 goto error_return;
4012 if (PQisBusy(conn))
4014 conn->status = CONNECTION_CONSUME;
4015 return PGRES_POLLING_READING;
4018 /* Call PQgetResult() again until we get a NULL result */
4019 res = PQgetResult(conn);
4020 if (res != NULL)
4022 PQclear(res);
4023 conn->status = CONNECTION_CONSUME;
4024 return PGRES_POLLING_READING;
4027 conn->status = CONNECTION_CHECK_TARGET;
4028 goto keep_going;
4031 case CONNECTION_CHECK_WRITABLE:
4034 * Waiting for result of "SHOW transaction_read_only". We
4035 * must transiently set status = CONNECTION_OK in order to use
4036 * the result-consuming subroutines.
4038 conn->status = CONNECTION_OK;
4039 if (!PQconsumeInput(conn))
4040 goto error_return;
4042 if (PQisBusy(conn))
4044 conn->status = CONNECTION_CHECK_WRITABLE;
4045 return PGRES_POLLING_READING;
4048 res = PQgetResult(conn);
4049 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4050 PQntuples(res) == 1)
4052 char *val = PQgetvalue(res, 0, 0);
4055 * "transaction_read_only = on" proves that at least one
4056 * of default_transaction_read_only and in_hot_standby is
4057 * on, but we don't actually know which. We don't care
4058 * though for the purpose of identifying a read-only
4059 * session, so satisfy the CONNECTION_CHECK_TARGET code by
4060 * claiming they are both on. On the other hand, if it's
4061 * a read-write session, they are certainly both off.
4063 if (strncmp(val, "on", 2) == 0)
4065 conn->default_transaction_read_only = PG_BOOL_YES;
4066 conn->in_hot_standby = PG_BOOL_YES;
4068 else
4070 conn->default_transaction_read_only = PG_BOOL_NO;
4071 conn->in_hot_standby = PG_BOOL_NO;
4073 PQclear(res);
4075 /* Finish reading messages before continuing */
4076 conn->status = CONNECTION_CONSUME;
4077 goto keep_going;
4080 /* Something went wrong with "SHOW transaction_read_only". */
4081 PQclear(res);
4083 /* Append error report to conn->errorMessage. */
4084 libpq_append_conn_error(conn, "\"%s\" failed",
4085 "SHOW transaction_read_only");
4087 /* Close connection politely. */
4088 conn->status = CONNECTION_OK;
4089 sendTerminateConn(conn);
4091 /* Try next host. */
4092 conn->try_next_host = true;
4093 goto keep_going;
4096 case CONNECTION_CHECK_STANDBY:
4099 * Waiting for result of "SELECT pg_is_in_recovery()". We
4100 * must transiently set status = CONNECTION_OK in order to use
4101 * the result-consuming subroutines.
4103 conn->status = CONNECTION_OK;
4104 if (!PQconsumeInput(conn))
4105 goto error_return;
4107 if (PQisBusy(conn))
4109 conn->status = CONNECTION_CHECK_STANDBY;
4110 return PGRES_POLLING_READING;
4113 res = PQgetResult(conn);
4114 if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4115 PQntuples(res) == 1)
4117 char *val = PQgetvalue(res, 0, 0);
4119 if (strncmp(val, "t", 1) == 0)
4120 conn->in_hot_standby = PG_BOOL_YES;
4121 else
4122 conn->in_hot_standby = PG_BOOL_NO;
4123 PQclear(res);
4125 /* Finish reading messages before continuing */
4126 conn->status = CONNECTION_CONSUME;
4127 goto keep_going;
4130 /* Something went wrong with "SELECT pg_is_in_recovery()". */
4131 PQclear(res);
4133 /* Append error report to conn->errorMessage. */
4134 libpq_append_conn_error(conn, "\"%s\" failed",
4135 "SELECT pg_is_in_recovery()");
4137 /* Close connection politely. */
4138 conn->status = CONNECTION_OK;
4139 sendTerminateConn(conn);
4141 /* Try next host. */
4142 conn->try_next_host = true;
4143 goto keep_going;
4146 default:
4147 libpq_append_conn_error(conn,
4148 "invalid connection state %d, probably indicative of memory corruption",
4149 conn->status);
4150 goto error_return;
4153 /* Unreachable */
4155 error_return:
4158 * We used to close the socket at this point, but that makes it awkward
4159 * for those above us if they wish to remove this socket from their own
4160 * records (an fd_set for example). We'll just have this socket closed
4161 * when PQfinish is called (which is compulsory even after an error, since
4162 * the connection structure must be freed).
4164 conn->status = CONNECTION_BAD;
4165 return PGRES_POLLING_FAILED;
4170 * internal_ping
4171 * Determine if a server is running and if we can connect to it.
4173 * The argument is a connection that's been started, but not completed.
4175 static PGPing
4176 internal_ping(PGconn *conn)
4178 /* Say "no attempt" if we never got to PQconnectPoll */
4179 if (!conn || !conn->options_valid)
4180 return PQPING_NO_ATTEMPT;
4182 /* Attempt to complete the connection */
4183 if (conn->status != CONNECTION_BAD)
4184 (void) connectDBComplete(conn);
4186 /* Definitely OK if we succeeded */
4187 if (conn->status != CONNECTION_BAD)
4188 return PQPING_OK;
4191 * Here begins the interesting part of "ping": determine the cause of the
4192 * failure in sufficient detail to decide what to return. We do not want
4193 * to report that the server is not up just because we didn't have a valid
4194 * password, for example. In fact, any sort of authentication request
4195 * implies the server is up. (We need this check since the libpq side of
4196 * things might have pulled the plug on the connection before getting an
4197 * error as such from the postmaster.)
4199 if (conn->auth_req_received)
4200 return PQPING_OK;
4203 * If we failed to get any ERROR response from the postmaster, report
4204 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
4205 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
4206 * out of support. Another corner case where the server could return a
4207 * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
4208 * isn't totally unreasonable for that anyway. We expect that every other
4209 * failure case in a modern server will produce a report with a SQLSTATE.
4211 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
4212 * client-side errors, we should either not store those into
4213 * last_sqlstate, or add an extra flag so we can tell client-side errors
4214 * apart from server-side ones.
4216 if (strlen(conn->last_sqlstate) != 5)
4217 return PQPING_NO_RESPONSE;
4220 * Report PQPING_REJECT if server says it's not accepting connections.
4222 if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
4223 return PQPING_REJECT;
4226 * Any other SQLSTATE can be taken to indicate that the server is up.
4227 * Presumably it didn't like our username, password, or database name; or
4228 * perhaps it had some transient failure, but that should not be taken as
4229 * meaning "it's down".
4231 return PQPING_OK;
4236 * makeEmptyPGconn
4237 * - create a PGconn data structure with (as yet) no interesting data
4239 static PGconn *
4240 makeEmptyPGconn(void)
4242 PGconn *conn;
4244 #ifdef WIN32
4247 * Make sure socket support is up and running in this process.
4249 * Note: the Windows documentation says that we should eventually do a
4250 * matching WSACleanup() call, but experience suggests that that is at
4251 * least as likely to cause problems as fix them. So we don't.
4253 static bool wsastartup_done = false;
4255 if (!wsastartup_done)
4257 WSADATA wsaData;
4259 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4260 return NULL;
4261 wsastartup_done = true;
4264 /* Forget any earlier error */
4265 WSASetLastError(0);
4266 #endif /* WIN32 */
4268 conn = (PGconn *) malloc(sizeof(PGconn));
4269 if (conn == NULL)
4270 return conn;
4272 /* Zero all pointers and booleans */
4273 MemSet(conn, 0, sizeof(PGconn));
4275 /* install default notice hooks */
4276 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
4277 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
4279 conn->status = CONNECTION_BAD;
4280 conn->asyncStatus = PGASYNC_IDLE;
4281 conn->pipelineStatus = PQ_PIPELINE_OFF;
4282 conn->xactStatus = PQTRANS_IDLE;
4283 conn->options_valid = false;
4284 conn->nonblocking = false;
4285 conn->client_encoding = PG_SQL_ASCII;
4286 conn->std_strings = false; /* unless server says differently */
4287 conn->default_transaction_read_only = PG_BOOL_UNKNOWN;
4288 conn->in_hot_standby = PG_BOOL_UNKNOWN;
4289 conn->scram_sha_256_iterations = SCRAM_SHA_256_DEFAULT_ITERATIONS;
4290 conn->verbosity = PQERRORS_DEFAULT;
4291 conn->show_context = PQSHOW_CONTEXT_ERRORS;
4292 conn->sock = PGINVALID_SOCKET;
4293 conn->Pfdebug = NULL;
4296 * We try to send at least 8K at a time, which is the usual size of pipe
4297 * buffers on Unix systems. That way, when we are sending a large amount
4298 * of data, we avoid incurring extra kernel context swaps for partial
4299 * bufferloads. The output buffer is initially made 16K in size, and we
4300 * try to dump it after accumulating 8K.
4302 * With the same goal of minimizing context swaps, the input buffer will
4303 * be enlarged anytime it has less than 8K free, so we initially allocate
4304 * twice that.
4306 conn->inBufSize = 16 * 1024;
4307 conn->inBuffer = (char *) malloc(conn->inBufSize);
4308 conn->outBufSize = 16 * 1024;
4309 conn->outBuffer = (char *) malloc(conn->outBufSize);
4310 conn->rowBufLen = 32;
4311 conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
4312 initPQExpBuffer(&conn->errorMessage);
4313 initPQExpBuffer(&conn->workBuffer);
4315 if (conn->inBuffer == NULL ||
4316 conn->outBuffer == NULL ||
4317 conn->rowBuf == NULL ||
4318 PQExpBufferBroken(&conn->errorMessage) ||
4319 PQExpBufferBroken(&conn->workBuffer))
4321 /* out of memory already :-( */
4322 freePGconn(conn);
4323 conn = NULL;
4326 return conn;
4330 * freePGconn
4331 * - free an idle (closed) PGconn data structure
4333 * NOTE: this should not overlap any functionality with closePGconn().
4334 * Clearing/resetting of transient state belongs there; what we do here is
4335 * release data that is to be held for the life of the PGconn structure.
4336 * If a value ought to be cleared/freed during PQreset(), do it there not here.
4338 static void
4339 freePGconn(PGconn *conn)
4341 /* let any event procs clean up their state data */
4342 for (int i = 0; i < conn->nEvents; i++)
4344 PGEventConnDestroy evt;
4346 evt.conn = conn;
4347 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
4348 conn->events[i].passThrough);
4349 free(conn->events[i].name);
4352 pqReleaseConnHosts(conn);
4354 free(conn->client_encoding_initial);
4355 free(conn->events);
4356 free(conn->pghost);
4357 free(conn->pghostaddr);
4358 free(conn->pgport);
4359 free(conn->connect_timeout);
4360 free(conn->pgtcp_user_timeout);
4361 free(conn->pgoptions);
4362 free(conn->appname);
4363 free(conn->fbappname);
4364 free(conn->dbName);
4365 free(conn->replication);
4366 free(conn->pguser);
4367 if (conn->pgpass)
4369 explicit_bzero(conn->pgpass, strlen(conn->pgpass));
4370 free(conn->pgpass);
4372 free(conn->pgpassfile);
4373 free(conn->channel_binding);
4374 free(conn->keepalives);
4375 free(conn->keepalives_idle);
4376 free(conn->keepalives_interval);
4377 free(conn->keepalives_count);
4378 free(conn->sslmode);
4379 free(conn->sslcert);
4380 free(conn->sslkey);
4381 if (conn->sslpassword)
4383 explicit_bzero(conn->sslpassword, strlen(conn->sslpassword));
4384 free(conn->sslpassword);
4386 free(conn->sslcertmode);
4387 free(conn->sslrootcert);
4388 free(conn->sslcrl);
4389 free(conn->sslcrldir);
4390 free(conn->sslcompression);
4391 free(conn->sslsni);
4392 free(conn->requirepeer);
4393 free(conn->require_auth);
4394 free(conn->ssl_min_protocol_version);
4395 free(conn->ssl_max_protocol_version);
4396 free(conn->gssencmode);
4397 free(conn->krbsrvname);
4398 free(conn->gsslib);
4399 free(conn->gssdelegation);
4400 free(conn->connip);
4401 /* Note that conn->Pfdebug is not ours to close or free */
4402 free(conn->write_err_msg);
4403 free(conn->inBuffer);
4404 free(conn->outBuffer);
4405 free(conn->rowBuf);
4406 free(conn->target_session_attrs);
4407 free(conn->load_balance_hosts);
4408 termPQExpBuffer(&conn->errorMessage);
4409 termPQExpBuffer(&conn->workBuffer);
4411 free(conn);
4415 * pqReleaseConnHosts
4416 * - Free the host list in the PGconn.
4418 void
4419 pqReleaseConnHosts(PGconn *conn)
4421 if (conn->connhost)
4423 for (int i = 0; i < conn->nconnhost; ++i)
4425 free(conn->connhost[i].host);
4426 free(conn->connhost[i].hostaddr);
4427 free(conn->connhost[i].port);
4428 if (conn->connhost[i].password != NULL)
4430 explicit_bzero(conn->connhost[i].password,
4431 strlen(conn->connhost[i].password));
4432 free(conn->connhost[i].password);
4435 free(conn->connhost);
4440 * store_conn_addrinfo
4441 * - copy addrinfo to PGconn object
4443 * Copies the addrinfos from addrlist to the PGconn object such that the
4444 * addrinfos can be manipulated by libpq. Returns a positive integer on
4445 * failure, otherwise zero.
4447 static int
4448 store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
4450 struct addrinfo *ai = addrlist;
4452 conn->whichaddr = 0;
4454 conn->naddr = 0;
4455 while (ai)
4457 ai = ai->ai_next;
4458 conn->naddr++;
4461 conn->addr = calloc(conn->naddr, sizeof(AddrInfo));
4462 if (conn->addr == NULL)
4464 libpq_append_conn_error(conn, "out of memory");
4465 return 1;
4468 ai = addrlist;
4469 for (int i = 0; i < conn->naddr; i++)
4471 conn->addr[i].family = ai->ai_family;
4473 memcpy(&conn->addr[i].addr.addr, ai->ai_addr,
4474 ai->ai_addrlen);
4475 conn->addr[i].addr.salen = ai->ai_addrlen;
4476 ai = ai->ai_next;
4479 return 0;
4483 * release_conn_addrinfo
4484 * - Free any addrinfo list in the PGconn.
4486 static void
4487 release_conn_addrinfo(PGconn *conn)
4489 if (conn->addr)
4491 free(conn->addr);
4492 conn->addr = NULL;
4497 * sendTerminateConn
4498 * - Send a terminate message to backend.
4500 static void
4501 sendTerminateConn(PGconn *conn)
4504 * Note that the protocol doesn't allow us to send Terminate messages
4505 * during the startup phase.
4507 if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
4510 * Try to send "close connection" message to backend. Ignore any
4511 * error.
4513 pqPutMsgStart(PqMsg_Terminate, conn);
4514 pqPutMsgEnd(conn);
4515 (void) pqFlush(conn);
4520 * closePGconn
4521 * - properly close a connection to the backend
4523 * This should reset or release all transient state, but NOT the connection
4524 * parameters. On exit, the PGconn should be in condition to start a fresh
4525 * connection with the same parameters (see PQreset()).
4527 static void
4528 closePGconn(PGconn *conn)
4531 * If possible, send Terminate message to close the connection politely.
4533 sendTerminateConn(conn);
4536 * Must reset the blocking status so a possible reconnect will work.
4538 * Don't call PQsetnonblocking() because it will fail if it's unable to
4539 * flush the connection.
4541 conn->nonblocking = false;
4544 * Close the connection, reset all transient state, flush I/O buffers.
4545 * Note that this includes clearing conn's error state; we're no longer
4546 * interested in any failures associated with the old connection, and we
4547 * want a clean slate for any new connection attempt.
4549 pqDropConnection(conn, true);
4550 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
4551 conn->asyncStatus = PGASYNC_IDLE;
4552 conn->xactStatus = PQTRANS_IDLE;
4553 conn->pipelineStatus = PQ_PIPELINE_OFF;
4554 pqClearAsyncResult(conn); /* deallocate result */
4555 pqClearConnErrorState(conn);
4556 release_conn_addrinfo(conn);
4558 /* Reset all state obtained from server, too */
4559 pqDropServerData(conn);
4563 * PQfinish: properly close a connection to the backend. Also frees
4564 * the PGconn data structure so it shouldn't be re-used after this.
4566 void
4567 PQfinish(PGconn *conn)
4569 if (conn)
4571 closePGconn(conn);
4572 freePGconn(conn);
4577 * PQreset: resets the connection to the backend by closing the
4578 * existing connection and creating a new one.
4580 void
4581 PQreset(PGconn *conn)
4583 if (conn)
4585 closePGconn(conn);
4587 if (connectDBStart(conn) && connectDBComplete(conn))
4590 * Notify event procs of successful reset.
4592 int i;
4594 for (i = 0; i < conn->nEvents; i++)
4596 PGEventConnReset evt;
4598 evt.conn = conn;
4599 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4600 conn->events[i].passThrough);
4608 * PQresetStart:
4609 * resets the connection to the backend
4610 * closes the existing connection and makes a new one
4611 * Returns 1 on success, 0 on failure.
4614 PQresetStart(PGconn *conn)
4616 if (conn)
4618 closePGconn(conn);
4620 return connectDBStart(conn);
4623 return 0;
4628 * PQresetPoll:
4629 * resets the connection to the backend
4630 * closes the existing connection and makes a new one
4632 PostgresPollingStatusType
4633 PQresetPoll(PGconn *conn)
4635 if (conn)
4637 PostgresPollingStatusType status = PQconnectPoll(conn);
4639 if (status == PGRES_POLLING_OK)
4642 * Notify event procs of successful reset.
4644 int i;
4646 for (i = 0; i < conn->nEvents; i++)
4648 PGEventConnReset evt;
4650 evt.conn = conn;
4651 (void) conn->events[i].proc(PGEVT_CONNRESET, &evt,
4652 conn->events[i].passThrough);
4656 return status;
4659 return PGRES_POLLING_FAILED;
4663 * pqPacketSend() -- convenience routine to send a message to server.
4665 * pack_type: the single-byte message type code. (Pass zero for startup
4666 * packets, which have no message type code.)
4668 * buf, buf_len: contents of message. The given length includes only what
4669 * is in buf; the message type and message length fields are added here.
4671 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4672 * SIDE_EFFECTS: may block.
4675 pqPacketSend(PGconn *conn, char pack_type,
4676 const void *buf, size_t buf_len)
4678 /* Start the message. */
4679 if (pqPutMsgStart(pack_type, conn))
4680 return STATUS_ERROR;
4682 /* Send the message body. */
4683 if (pqPutnchar(buf, buf_len, conn))
4684 return STATUS_ERROR;
4686 /* Finish the message. */
4687 if (pqPutMsgEnd(conn))
4688 return STATUS_ERROR;
4690 /* Flush to ensure backend gets it. */
4691 if (pqFlush(conn))
4692 return STATUS_ERROR;
4694 return STATUS_OK;
4697 #ifdef USE_LDAP
4699 #define LDAP_URL "ldap://"
4700 #define LDAP_DEF_PORT 389
4701 #define PGLDAP_TIMEOUT 2
4703 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4704 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4708 * ldapServiceLookup
4710 * Search the LDAP URL passed as first argument, treat the result as a
4711 * string of connection options that are parsed and added to the array of
4712 * options passed as second argument.
4714 * LDAP URLs must conform to RFC 1959 without escape sequences.
4715 * ldap://host:port/dn?attributes?scope?filter?extensions
4717 * Returns
4718 * 0 if the lookup was successful,
4719 * 1 if the connection to the LDAP server could be established but
4720 * the search was unsuccessful,
4721 * 2 if a connection could not be established, and
4722 * 3 if a fatal error occurred.
4724 * An error message is appended to *errorMessage for return codes 1 and 3.
4726 static int
4727 ldapServiceLookup(const char *purl, PQconninfoOption *options,
4728 PQExpBuffer errorMessage)
4730 int port = LDAP_DEF_PORT,
4731 scope,
4733 size,
4734 state,
4735 oldstate,
4737 #ifndef WIN32
4738 int msgid;
4739 #endif
4740 bool found_keyword;
4741 char *url,
4742 *hostname,
4743 *portstr,
4744 *endptr,
4745 *dn,
4746 *scopestr,
4747 *filter,
4748 *result,
4750 *p1 = NULL,
4751 *optname = NULL,
4752 *optval = NULL;
4753 char *attrs[2] = {NULL, NULL};
4754 LDAP *ld = NULL;
4755 LDAPMessage *res,
4756 *entry;
4757 struct berval **values;
4758 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4760 if ((url = strdup(purl)) == NULL)
4762 libpq_append_error(errorMessage, "out of memory");
4763 return 3;
4767 * Parse URL components, check for correctness. Basically, url has '\0'
4768 * placed at component boundaries and variables are pointed at each
4769 * component.
4772 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
4774 libpq_append_error(errorMessage,
4775 "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
4776 free(url);
4777 return 3;
4780 /* hostname */
4781 hostname = url + strlen(LDAP_URL);
4782 if (*hostname == '/') /* no hostname? */
4783 hostname = DefaultHost; /* the default */
4785 /* dn, "distinguished name" */
4786 p = strchr(url + strlen(LDAP_URL), '/');
4787 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4789 libpq_append_error(errorMessage,
4790 "invalid LDAP URL \"%s\": missing distinguished name",
4791 purl);
4792 free(url);
4793 return 3;
4795 *p = '\0'; /* terminate hostname */
4796 dn = p + 1;
4798 /* attribute */
4799 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4801 libpq_append_error(errorMessage,
4802 "invalid LDAP URL \"%s\": must have exactly one attribute",
4803 purl);
4804 free(url);
4805 return 3;
4807 *p = '\0';
4808 attrs[0] = p + 1;
4810 /* scope */
4811 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4813 libpq_append_error(errorMessage,
4814 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
4815 purl);
4816 free(url);
4817 return 3;
4819 *p = '\0';
4820 scopestr = p + 1;
4822 /* filter */
4823 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4825 libpq_append_error(errorMessage,
4826 "invalid LDAP URL \"%s\": no filter",
4827 purl);
4828 free(url);
4829 return 3;
4831 *p = '\0';
4832 filter = p + 1;
4833 if ((p = strchr(filter, '?')) != NULL)
4834 *p = '\0';
4836 /* port number? */
4837 if ((p1 = strchr(hostname, ':')) != NULL)
4839 long lport;
4841 *p1 = '\0';
4842 portstr = p1 + 1;
4843 errno = 0;
4844 lport = strtol(portstr, &endptr, 10);
4845 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
4847 libpq_append_error(errorMessage,
4848 "invalid LDAP URL \"%s\": invalid port number",
4849 purl);
4850 free(url);
4851 return 3;
4853 port = (int) lport;
4856 /* Allow only one attribute */
4857 if (strchr(attrs[0], ',') != NULL)
4859 libpq_append_error(errorMessage,
4860 "invalid LDAP URL \"%s\": must have exactly one attribute",
4861 purl);
4862 free(url);
4863 return 3;
4866 /* set scope */
4867 if (pg_strcasecmp(scopestr, "base") == 0)
4868 scope = LDAP_SCOPE_BASE;
4869 else if (pg_strcasecmp(scopestr, "one") == 0)
4870 scope = LDAP_SCOPE_ONELEVEL;
4871 else if (pg_strcasecmp(scopestr, "sub") == 0)
4872 scope = LDAP_SCOPE_SUBTREE;
4873 else
4875 libpq_append_error(errorMessage,
4876 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
4877 purl);
4878 free(url);
4879 return 3;
4882 /* initialize LDAP structure */
4883 if ((ld = ldap_init(hostname, port)) == NULL)
4885 libpq_append_error(errorMessage, "could not create LDAP structure");
4886 free(url);
4887 return 3;
4891 * Perform an explicit anonymous bind.
4893 * LDAP does not require that an anonymous bind is performed explicitly,
4894 * but we want to distinguish between the case where LDAP bind does not
4895 * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
4896 * service control file) and the case where querying the LDAP server fails
4897 * (return 1 to end parsing).
4899 * Unfortunately there is no way of setting a timeout that works for both
4900 * Windows and OpenLDAP.
4902 #ifdef WIN32
4903 /* the nonstandard ldap_connect function performs an anonymous bind */
4904 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
4906 /* error or timeout in ldap_connect */
4907 free(url);
4908 ldap_unbind(ld);
4909 return 2;
4911 #else /* !WIN32 */
4912 /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
4913 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4915 free(url);
4916 ldap_unbind(ld);
4917 return 3;
4920 /* anonymous bind */
4921 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
4923 /* error or network timeout */
4924 free(url);
4925 ldap_unbind(ld);
4926 return 2;
4929 /* wait some time for the connection to succeed */
4930 res = NULL;
4931 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
4932 res == NULL)
4934 /* error or timeout */
4935 if (res != NULL)
4936 ldap_msgfree(res);
4937 free(url);
4938 ldap_unbind(ld);
4939 return 2;
4941 ldap_msgfree(res);
4943 /* reset timeout */
4944 time.tv_sec = -1;
4945 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4947 free(url);
4948 ldap_unbind(ld);
4949 return 3;
4951 #endif /* WIN32 */
4953 /* search */
4954 res = NULL;
4955 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
4956 != LDAP_SUCCESS)
4958 if (res != NULL)
4959 ldap_msgfree(res);
4960 libpq_append_error(errorMessage, "lookup on LDAP server failed: %s", ldap_err2string(rc));
4961 ldap_unbind(ld);
4962 free(url);
4963 return 1;
4966 /* complain if there was not exactly one result */
4967 if ((rc = ldap_count_entries(ld, res)) != 1)
4969 if (rc > 1)
4970 libpq_append_error(errorMessage, "more than one entry found on LDAP lookup");
4971 else
4972 libpq_append_error(errorMessage, "no entry found on LDAP lookup");
4973 ldap_msgfree(res);
4974 ldap_unbind(ld);
4975 free(url);
4976 return 1;
4979 /* get entry */
4980 if ((entry = ldap_first_entry(ld, res)) == NULL)
4982 /* should never happen */
4983 libpq_append_error(errorMessage, "no entry found on LDAP lookup");
4984 ldap_msgfree(res);
4985 ldap_unbind(ld);
4986 free(url);
4987 return 1;
4990 /* get values */
4991 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
4993 libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
4994 ldap_msgfree(res);
4995 ldap_unbind(ld);
4996 free(url);
4997 return 1;
5000 ldap_msgfree(res);
5001 free(url);
5003 if (values[0] == NULL)
5005 libpq_append_error(errorMessage, "attribute has no values on LDAP lookup");
5006 ldap_value_free_len(values);
5007 ldap_unbind(ld);
5008 return 1;
5011 /* concatenate values into a single string with newline terminators */
5012 size = 1; /* for the trailing null */
5013 for (i = 0; values[i] != NULL; i++)
5014 size += values[i]->bv_len + 1;
5015 if ((result = malloc(size)) == NULL)
5017 libpq_append_error(errorMessage, "out of memory");
5018 ldap_value_free_len(values);
5019 ldap_unbind(ld);
5020 return 3;
5022 p = result;
5023 for (i = 0; values[i] != NULL; i++)
5025 memcpy(p, values[i]->bv_val, values[i]->bv_len);
5026 p += values[i]->bv_len;
5027 *(p++) = '\n';
5029 *p = '\0';
5031 ldap_value_free_len(values);
5032 ldap_unbind(ld);
5034 /* parse result string */
5035 oldstate = state = 0;
5036 for (p = result; *p != '\0'; ++p)
5038 switch (state)
5040 case 0: /* between entries */
5041 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
5043 optname = p;
5044 state = 1;
5046 break;
5047 case 1: /* in option name */
5048 if (ld_is_sp_tab(*p))
5050 *p = '\0';
5051 state = 2;
5053 else if (ld_is_nl_cr(*p))
5055 libpq_append_error(errorMessage,
5056 "missing \"=\" after \"%s\" in connection info string",
5057 optname);
5058 free(result);
5059 return 3;
5061 else if (*p == '=')
5063 *p = '\0';
5064 state = 3;
5066 break;
5067 case 2: /* after option name */
5068 if (*p == '=')
5070 state = 3;
5072 else if (!ld_is_sp_tab(*p))
5074 libpq_append_error(errorMessage,
5075 "missing \"=\" after \"%s\" in connection info string",
5076 optname);
5077 free(result);
5078 return 3;
5080 break;
5081 case 3: /* before option value */
5082 if (*p == '\'')
5084 optval = p + 1;
5085 p1 = p + 1;
5086 state = 5;
5088 else if (ld_is_nl_cr(*p))
5090 optval = optname + strlen(optname); /* empty */
5091 state = 0;
5093 else if (!ld_is_sp_tab(*p))
5095 optval = p;
5096 state = 4;
5098 break;
5099 case 4: /* in unquoted option value */
5100 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
5102 *p = '\0';
5103 state = 0;
5105 break;
5106 case 5: /* in quoted option value */
5107 if (*p == '\'')
5109 *p1 = '\0';
5110 state = 0;
5112 else if (*p == '\\')
5113 state = 6;
5114 else
5115 *(p1++) = *p;
5116 break;
5117 case 6: /* in quoted option value after escape */
5118 *(p1++) = *p;
5119 state = 5;
5120 break;
5123 if (state == 0 && oldstate != 0)
5125 found_keyword = false;
5126 for (i = 0; options[i].keyword; i++)
5128 if (strcmp(options[i].keyword, optname) == 0)
5130 if (options[i].val == NULL)
5132 options[i].val = strdup(optval);
5133 if (!options[i].val)
5135 libpq_append_error(errorMessage, "out of memory");
5136 free(result);
5137 return 3;
5140 found_keyword = true;
5141 break;
5144 if (!found_keyword)
5146 libpq_append_error(errorMessage, "invalid connection option \"%s\"", optname);
5147 free(result);
5148 return 1;
5150 optname = NULL;
5151 optval = NULL;
5153 oldstate = state;
5156 free(result);
5158 if (state == 5 || state == 6)
5160 libpq_append_error(errorMessage,
5161 "unterminated quoted string in connection info string");
5162 return 3;
5165 return 0;
5168 #endif /* USE_LDAP */
5171 * parseServiceInfo: if a service name has been given, look it up and absorb
5172 * connection options from it into *options.
5174 * Returns 0 on success, nonzero on failure. On failure, if errorMessage
5175 * isn't null, also store an error message there. (Note: the only reason
5176 * this function and related ones don't dump core on errorMessage == NULL
5177 * is the undocumented fact that appendPQExpBuffer does nothing when passed
5178 * a null PQExpBuffer pointer.)
5180 static int
5181 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
5183 const char *service = conninfo_getval(options, "service");
5184 char serviceFile[MAXPGPATH];
5185 char *env;
5186 bool group_found = false;
5187 int status;
5188 struct stat stat_buf;
5191 * We have to special-case the environment variable PGSERVICE here, since
5192 * this is and should be called before inserting environment defaults for
5193 * other connection options.
5195 if (service == NULL)
5196 service = getenv("PGSERVICE");
5198 /* If no service name given, nothing to do */
5199 if (service == NULL)
5200 return 0;
5203 * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
5204 * exists).
5206 if ((env = getenv("PGSERVICEFILE")) != NULL)
5207 strlcpy(serviceFile, env, sizeof(serviceFile));
5208 else
5210 char homedir[MAXPGPATH];
5212 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5213 goto next_file;
5214 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5215 if (stat(serviceFile, &stat_buf) != 0)
5216 goto next_file;
5219 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5220 if (group_found || status != 0)
5221 return status;
5223 next_file:
5226 * This could be used by any application so we can't use the binary
5227 * location to find our config files.
5229 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5230 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5231 if (stat(serviceFile, &stat_buf) != 0)
5232 goto last_file;
5234 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5235 if (status != 0)
5236 return status;
5238 last_file:
5239 if (!group_found)
5241 libpq_append_error(errorMessage, "definition of service \"%s\" not found", service);
5242 return 3;
5245 return 0;
5248 static int
5249 parseServiceFile(const char *serviceFile,
5250 const char *service,
5251 PQconninfoOption *options,
5252 PQExpBuffer errorMessage,
5253 bool *group_found)
5255 int result = 0,
5256 linenr = 0,
5258 FILE *f;
5259 char *line;
5260 char buf[1024];
5262 *group_found = false;
5264 f = fopen(serviceFile, "r");
5265 if (f == NULL)
5267 libpq_append_error(errorMessage, "service file \"%s\" not found", serviceFile);
5268 return 1;
5271 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
5273 int len;
5275 linenr++;
5277 if (strlen(line) >= sizeof(buf) - 1)
5279 libpq_append_error(errorMessage,
5280 "line %d too long in service file \"%s\"",
5281 linenr,
5282 serviceFile);
5283 result = 2;
5284 goto exit;
5287 /* ignore whitespace at end of line, especially the newline */
5288 len = strlen(line);
5289 while (len > 0 && isspace((unsigned char) line[len - 1]))
5290 line[--len] = '\0';
5292 /* ignore leading whitespace too */
5293 while (*line && isspace((unsigned char) line[0]))
5294 line++;
5296 /* ignore comments and empty lines */
5297 if (line[0] == '\0' || line[0] == '#')
5298 continue;
5300 /* Check for right groupname */
5301 if (line[0] == '[')
5303 if (*group_found)
5305 /* end of desired group reached; return success */
5306 goto exit;
5309 if (strncmp(line + 1, service, strlen(service)) == 0 &&
5310 line[strlen(service) + 1] == ']')
5311 *group_found = true;
5312 else
5313 *group_found = false;
5315 else
5317 if (*group_found)
5320 * Finally, we are in the right group and can parse the line
5322 char *key,
5323 *val;
5324 bool found_keyword;
5326 #ifdef USE_LDAP
5327 if (strncmp(line, "ldap", 4) == 0)
5329 int rc = ldapServiceLookup(line, options, errorMessage);
5331 /* if rc = 2, go on reading for fallback */
5332 switch (rc)
5334 case 0:
5335 goto exit;
5336 case 1:
5337 case 3:
5338 result = 3;
5339 goto exit;
5340 case 2:
5341 continue;
5344 #endif
5346 key = line;
5347 val = strchr(line, '=');
5348 if (val == NULL)
5350 libpq_append_error(errorMessage,
5351 "syntax error in service file \"%s\", line %d",
5352 serviceFile,
5353 linenr);
5354 result = 3;
5355 goto exit;
5357 *val++ = '\0';
5359 if (strcmp(key, "service") == 0)
5361 libpq_append_error(errorMessage,
5362 "nested service specifications not supported in service file \"%s\", line %d",
5363 serviceFile,
5364 linenr);
5365 result = 3;
5366 goto exit;
5370 * Set the parameter --- but don't override any previous
5371 * explicit setting.
5373 found_keyword = false;
5374 for (i = 0; options[i].keyword; i++)
5376 if (strcmp(options[i].keyword, key) == 0)
5378 if (options[i].val == NULL)
5379 options[i].val = strdup(val);
5380 if (!options[i].val)
5382 libpq_append_error(errorMessage, "out of memory");
5383 result = 3;
5384 goto exit;
5386 found_keyword = true;
5387 break;
5391 if (!found_keyword)
5393 libpq_append_error(errorMessage,
5394 "syntax error in service file \"%s\", line %d",
5395 serviceFile,
5396 linenr);
5397 result = 3;
5398 goto exit;
5404 exit:
5405 fclose(f);
5407 return result;
5412 * PQconninfoParse
5414 * Parse a string like PQconnectdb() would do and return the
5415 * resulting connection options array. NULL is returned on failure.
5416 * The result contains only options specified directly in the string,
5417 * not any possible default values.
5419 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
5420 * string on failure (use PQfreemem to free it). In out-of-memory conditions
5421 * both *errmsg and the result could be NULL.
5423 * NOTE: the returned array is dynamically allocated and should
5424 * be freed when no longer needed via PQconninfoFree().
5426 PQconninfoOption *
5427 PQconninfoParse(const char *conninfo, char **errmsg)
5429 PQExpBufferData errorBuf;
5430 PQconninfoOption *connOptions;
5432 if (errmsg)
5433 *errmsg = NULL; /* default */
5434 initPQExpBuffer(&errorBuf);
5435 if (PQExpBufferDataBroken(errorBuf))
5436 return NULL; /* out of memory already :-( */
5437 connOptions = parse_connection_string(conninfo, &errorBuf, false);
5438 if (connOptions == NULL && errmsg)
5439 *errmsg = errorBuf.data;
5440 else
5441 termPQExpBuffer(&errorBuf);
5442 return connOptions;
5446 * Build a working copy of the constant PQconninfoOptions array.
5448 static PQconninfoOption *
5449 conninfo_init(PQExpBuffer errorMessage)
5451 PQconninfoOption *options;
5452 PQconninfoOption *opt_dest;
5453 const internalPQconninfoOption *cur_opt;
5456 * Get enough memory for all options in PQconninfoOptions, even if some
5457 * end up being filtered out.
5459 options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
5460 if (options == NULL)
5462 libpq_append_error(errorMessage, "out of memory");
5463 return NULL;
5465 opt_dest = options;
5467 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
5469 /* Only copy the public part of the struct, not the full internal */
5470 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
5471 opt_dest++;
5473 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
5475 return options;
5479 * Connection string parser
5481 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
5482 * Otherwise, NULL is returned and an error message is added to errorMessage.
5484 * If use_defaults is true, default values are filled in (from a service file,
5485 * environment variables, etc).
5487 static PQconninfoOption *
5488 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
5489 bool use_defaults)
5491 /* Parse as URI if connection string matches URI prefix */
5492 if (uri_prefix_length(connstr) != 0)
5493 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
5495 /* Parse as default otherwise */
5496 return conninfo_parse(connstr, errorMessage, use_defaults);
5500 * Checks if connection string starts with either of the valid URI prefix
5501 * designators.
5503 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
5505 * XXX this is duplicated in psql/common.c.
5507 static int
5508 uri_prefix_length(const char *connstr)
5510 if (strncmp(connstr, uri_designator,
5511 sizeof(uri_designator) - 1) == 0)
5512 return sizeof(uri_designator) - 1;
5514 if (strncmp(connstr, short_uri_designator,
5515 sizeof(short_uri_designator) - 1) == 0)
5516 return sizeof(short_uri_designator) - 1;
5518 return 0;
5522 * Recognized connection string either starts with a valid URI prefix or
5523 * contains a "=" in it.
5525 * Must be consistent with parse_connection_string: anything for which this
5526 * returns true should at least look like it's parseable by that routine.
5528 * XXX this is duplicated in psql/common.c
5530 static bool
5531 recognized_connection_string(const char *connstr)
5533 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
5537 * Subroutine for parse_connection_string
5539 * Deal with a string containing key=value pairs.
5541 static PQconninfoOption *
5542 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
5543 bool use_defaults)
5545 char *pname;
5546 char *pval;
5547 char *buf;
5548 char *cp;
5549 char *cp2;
5550 PQconninfoOption *options;
5552 /* Make a working copy of PQconninfoOptions */
5553 options = conninfo_init(errorMessage);
5554 if (options == NULL)
5555 return NULL;
5557 /* Need a modifiable copy of the input string */
5558 if ((buf = strdup(conninfo)) == NULL)
5560 libpq_append_error(errorMessage, "out of memory");
5561 PQconninfoFree(options);
5562 return NULL;
5564 cp = buf;
5566 while (*cp)
5568 /* Skip blanks before the parameter name */
5569 if (isspace((unsigned char) *cp))
5571 cp++;
5572 continue;
5575 /* Get the parameter name */
5576 pname = cp;
5577 while (*cp)
5579 if (*cp == '=')
5580 break;
5581 if (isspace((unsigned char) *cp))
5583 *cp++ = '\0';
5584 while (*cp)
5586 if (!isspace((unsigned char) *cp))
5587 break;
5588 cp++;
5590 break;
5592 cp++;
5595 /* Check that there is a following '=' */
5596 if (*cp != '=')
5598 libpq_append_error(errorMessage,
5599 "missing \"=\" after \"%s\" in connection info string",
5600 pname);
5601 PQconninfoFree(options);
5602 free(buf);
5603 return NULL;
5605 *cp++ = '\0';
5607 /* Skip blanks after the '=' */
5608 while (*cp)
5610 if (!isspace((unsigned char) *cp))
5611 break;
5612 cp++;
5615 /* Get the parameter value */
5616 pval = cp;
5618 if (*cp != '\'')
5620 cp2 = pval;
5621 while (*cp)
5623 if (isspace((unsigned char) *cp))
5625 *cp++ = '\0';
5626 break;
5628 if (*cp == '\\')
5630 cp++;
5631 if (*cp != '\0')
5632 *cp2++ = *cp++;
5634 else
5635 *cp2++ = *cp++;
5637 *cp2 = '\0';
5639 else
5641 cp2 = pval;
5642 cp++;
5643 for (;;)
5645 if (*cp == '\0')
5647 libpq_append_error(errorMessage, "unterminated quoted string in connection info string");
5648 PQconninfoFree(options);
5649 free(buf);
5650 return NULL;
5652 if (*cp == '\\')
5654 cp++;
5655 if (*cp != '\0')
5656 *cp2++ = *cp++;
5657 continue;
5659 if (*cp == '\'')
5661 *cp2 = '\0';
5662 cp++;
5663 break;
5665 *cp2++ = *cp++;
5670 * Now that we have the name and the value, store the record.
5672 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5674 PQconninfoFree(options);
5675 free(buf);
5676 return NULL;
5680 /* Done with the modifiable input string */
5681 free(buf);
5684 * Add in defaults if the caller wants that.
5686 if (use_defaults)
5688 if (!conninfo_add_defaults(options, errorMessage))
5690 PQconninfoFree(options);
5691 return NULL;
5695 return options;
5699 * Conninfo array parser routine
5701 * If successful, a malloc'd PQconninfoOption array is returned.
5702 * If not successful, NULL is returned and an error message is
5703 * appended to errorMessage.
5704 * Defaults are supplied (from a service file, environment variables, etc)
5705 * for unspecified options, but only if use_defaults is true.
5707 * If expand_dbname is non-zero, and the value passed for the first occurrence
5708 * of "dbname" keyword is a connection string (as indicated by
5709 * recognized_connection_string) then parse and process it, overriding any
5710 * previously processed conflicting keywords. Subsequent keywords will take
5711 * precedence, however. In-tree programs generally specify expand_dbname=true,
5712 * so command-line arguments naming a database can use a connection string.
5713 * Some code acquires arbitrary database names from known-literal sources like
5714 * PQdb(), PQconninfoParse() and pg_database.datname. When connecting to such
5715 * a database, in-tree code first wraps the name in a connection string.
5717 static PQconninfoOption *
5718 conninfo_array_parse(const char *const *keywords, const char *const *values,
5719 PQExpBuffer errorMessage, bool use_defaults,
5720 int expand_dbname)
5722 PQconninfoOption *options;
5723 PQconninfoOption *dbname_options = NULL;
5724 PQconninfoOption *option;
5725 int i = 0;
5728 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
5729 * actually a recognized connection string.
5731 while (expand_dbname && keywords[i])
5733 const char *pname = keywords[i];
5734 const char *pvalue = values[i];
5736 /* first find "dbname" if any */
5737 if (strcmp(pname, "dbname") == 0 && pvalue)
5740 * If value is a connection string, parse it, but do not use
5741 * defaults here -- those get picked up later. We only want to
5742 * override for those parameters actually passed.
5744 if (recognized_connection_string(pvalue))
5746 dbname_options = parse_connection_string(pvalue, errorMessage, false);
5747 if (dbname_options == NULL)
5748 return NULL;
5750 break;
5752 ++i;
5755 /* Make a working copy of PQconninfoOptions */
5756 options = conninfo_init(errorMessage);
5757 if (options == NULL)
5759 PQconninfoFree(dbname_options);
5760 return NULL;
5763 /* Parse the keywords/values arrays */
5764 i = 0;
5765 while (keywords[i])
5767 const char *pname = keywords[i];
5768 const char *pvalue = values[i];
5770 if (pvalue != NULL && pvalue[0] != '\0')
5772 /* Search for the param record */
5773 for (option = options; option->keyword != NULL; option++)
5775 if (strcmp(option->keyword, pname) == 0)
5776 break;
5779 /* Check for invalid connection option */
5780 if (option->keyword == NULL)
5782 libpq_append_error(errorMessage, "invalid connection option \"%s\"", pname);
5783 PQconninfoFree(options);
5784 PQconninfoFree(dbname_options);
5785 return NULL;
5789 * If we are on the first dbname parameter, and we have a parsed
5790 * connection string, copy those parameters across, overriding any
5791 * existing previous settings.
5793 if (strcmp(pname, "dbname") == 0 && dbname_options)
5795 PQconninfoOption *str_option;
5797 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
5799 if (str_option->val != NULL)
5801 int k;
5803 for (k = 0; options[k].keyword; k++)
5805 if (strcmp(options[k].keyword, str_option->keyword) == 0)
5807 free(options[k].val);
5808 options[k].val = strdup(str_option->val);
5809 if (!options[k].val)
5811 libpq_append_error(errorMessage, "out of memory");
5812 PQconninfoFree(options);
5813 PQconninfoFree(dbname_options);
5814 return NULL;
5816 break;
5823 * Forget the parsed connection string, so that any subsequent
5824 * dbname parameters will not be expanded.
5826 PQconninfoFree(dbname_options);
5827 dbname_options = NULL;
5829 else
5832 * Store the value, overriding previous settings
5834 free(option->val);
5835 option->val = strdup(pvalue);
5836 if (!option->val)
5838 libpq_append_error(errorMessage, "out of memory");
5839 PQconninfoFree(options);
5840 PQconninfoFree(dbname_options);
5841 return NULL;
5845 ++i;
5847 PQconninfoFree(dbname_options);
5850 * Add in defaults if the caller wants that.
5852 if (use_defaults)
5854 if (!conninfo_add_defaults(options, errorMessage))
5856 PQconninfoFree(options);
5857 return NULL;
5861 return options;
5865 * Add the default values for any unspecified options to the connection
5866 * options array.
5868 * Defaults are obtained from a service file, environment variables, etc.
5870 * Returns true if successful, otherwise false; errorMessage, if supplied,
5871 * is filled in upon failure. Note that failure to locate a default value
5872 * is not an error condition here --- we just leave the option's value as
5873 * NULL.
5875 static bool
5876 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
5878 PQconninfoOption *option;
5879 PQconninfoOption *sslmode_default = NULL,
5880 *sslrootcert = NULL;
5881 char *tmp;
5884 * If there's a service spec, use it to obtain any not-explicitly-given
5885 * parameters. Ignore error if no error message buffer is passed because
5886 * there is no way to pass back the failure message.
5888 if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
5889 return false;
5892 * Get the fallback resources for parameters not specified in the conninfo
5893 * string nor the service.
5895 for (option = options; option->keyword != NULL; option++)
5897 if (strcmp(option->keyword, "sslrootcert") == 0)
5898 sslrootcert = option; /* save for later */
5900 if (option->val != NULL)
5901 continue; /* Value was in conninfo or service */
5904 * Try to get the environment variable fallback
5906 if (option->envvar != NULL)
5908 if ((tmp = getenv(option->envvar)) != NULL)
5910 option->val = strdup(tmp);
5911 if (!option->val)
5913 if (errorMessage)
5914 libpq_append_error(errorMessage, "out of memory");
5915 return false;
5917 continue;
5922 * Interpret the deprecated PGREQUIRESSL environment variable. Per
5923 * tradition, translate values starting with "1" to sslmode=require,
5924 * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
5925 * PGSSLMODE takes precedence; the opposite was true before v9.3.
5927 if (strcmp(option->keyword, "sslmode") == 0)
5929 const char *requiresslenv = getenv("PGREQUIRESSL");
5931 if (requiresslenv != NULL && requiresslenv[0] == '1')
5933 option->val = strdup("require");
5934 if (!option->val)
5936 if (errorMessage)
5937 libpq_append_error(errorMessage, "out of memory");
5938 return false;
5940 continue;
5944 * sslmode is not specified. Let it be filled in with the compiled
5945 * default for now, but if sslrootcert=system, we'll override the
5946 * default later before returning.
5948 sslmode_default = option;
5952 * No environment variable specified or the variable isn't set - try
5953 * compiled-in default
5955 if (option->compiled != NULL)
5957 option->val = strdup(option->compiled);
5958 if (!option->val)
5960 if (errorMessage)
5961 libpq_append_error(errorMessage, "out of memory");
5962 return false;
5964 continue;
5968 * Special handling for "user" option. Note that if pg_fe_getauthname
5969 * fails, we just leave the value as NULL; there's no need for this to
5970 * be an error condition if the caller provides a user name. The only
5971 * reason we do this now at all is so that callers of PQconndefaults
5972 * will see a correct default (barring error, of course).
5974 if (strcmp(option->keyword, "user") == 0)
5976 option->val = pg_fe_getauthname(NULL);
5977 continue;
5982 * Special handling for sslrootcert=system with no sslmode explicitly
5983 * defined. In this case we want to strengthen the default sslmode to
5984 * verify-full.
5986 if (sslmode_default && sslrootcert)
5988 if (sslrootcert->val && strcmp(sslrootcert->val, "system") == 0)
5990 free(sslmode_default->val);
5992 sslmode_default->val = strdup("verify-full");
5993 if (!sslmode_default->val)
5995 if (errorMessage)
5996 libpq_append_error(errorMessage, "out of memory");
5997 return false;
6002 return true;
6006 * Subroutine for parse_connection_string
6008 * Deal with a URI connection string.
6010 static PQconninfoOption *
6011 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
6012 bool use_defaults)
6014 PQconninfoOption *options;
6016 /* Make a working copy of PQconninfoOptions */
6017 options = conninfo_init(errorMessage);
6018 if (options == NULL)
6019 return NULL;
6021 if (!conninfo_uri_parse_options(options, uri, errorMessage))
6023 PQconninfoFree(options);
6024 return NULL;
6028 * Add in defaults if the caller wants that.
6030 if (use_defaults)
6032 if (!conninfo_add_defaults(options, errorMessage))
6034 PQconninfoFree(options);
6035 return NULL;
6039 return options;
6043 * conninfo_uri_parse_options
6044 * Actual URI parser.
6046 * If successful, returns true while the options array is filled with parsed
6047 * options from the URI.
6048 * If not successful, returns false and fills errorMessage accordingly.
6050 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
6051 * 3986):
6053 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
6055 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
6056 * by literal square brackets. As an extension, we also allow multiple
6057 * netloc[:port] specifications, separated by commas:
6059 * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
6061 * Any of the URI parts might use percent-encoding (%xy).
6063 static bool
6064 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
6065 PQExpBuffer errorMessage)
6067 int prefix_len;
6068 char *p;
6069 char *buf = NULL;
6070 char *start;
6071 char prevchar = '\0';
6072 char *user = NULL;
6073 char *host = NULL;
6074 bool retval = false;
6075 PQExpBufferData hostbuf;
6076 PQExpBufferData portbuf;
6078 initPQExpBuffer(&hostbuf);
6079 initPQExpBuffer(&portbuf);
6080 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6082 libpq_append_error(errorMessage, "out of memory");
6083 goto cleanup;
6086 /* need a modifiable copy of the input URI */
6087 buf = strdup(uri);
6088 if (buf == NULL)
6090 libpq_append_error(errorMessage, "out of memory");
6091 goto cleanup;
6093 start = buf;
6095 /* Skip the URI prefix */
6096 prefix_len = uri_prefix_length(uri);
6097 if (prefix_len == 0)
6099 /* Should never happen */
6100 libpq_append_error(errorMessage,
6101 "invalid URI propagated to internal parser routine: \"%s\"",
6102 uri);
6103 goto cleanup;
6105 start += prefix_len;
6106 p = start;
6108 /* Look ahead for possible user credentials designator */
6109 while (*p && *p != '@' && *p != '/')
6110 ++p;
6111 if (*p == '@')
6114 * Found username/password designator, so URI should be of the form
6115 * "scheme://user[:password]@[netloc]".
6117 user = start;
6119 p = user;
6120 while (*p != ':' && *p != '@')
6121 ++p;
6123 /* Save last char and cut off at end of user name */
6124 prevchar = *p;
6125 *p = '\0';
6127 if (*user &&
6128 !conninfo_storeval(options, "user", user,
6129 errorMessage, false, true))
6130 goto cleanup;
6132 if (prevchar == ':')
6134 const char *password = p + 1;
6136 while (*p != '@')
6137 ++p;
6138 *p = '\0';
6140 if (*password &&
6141 !conninfo_storeval(options, "password", password,
6142 errorMessage, false, true))
6143 goto cleanup;
6146 /* Advance past end of parsed user name or password token */
6147 ++p;
6149 else
6152 * No username/password designator found. Reset to start of URI.
6154 p = start;
6158 * There may be multiple netloc[:port] pairs, each separated from the next
6159 * by a comma. When we initially enter this loop, "p" has been
6160 * incremented past optional URI credential information at this point and
6161 * now points at the "netloc" part of the URI. On subsequent loop
6162 * iterations, "p" has been incremented past the comma separator and now
6163 * points at the start of the next "netloc".
6165 for (;;)
6168 * Look for IPv6 address.
6170 if (*p == '[')
6172 host = ++p;
6173 while (*p && *p != ']')
6174 ++p;
6175 if (!*p)
6177 libpq_append_error(errorMessage,
6178 "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
6179 uri);
6180 goto cleanup;
6182 if (p == host)
6184 libpq_append_error(errorMessage,
6185 "IPv6 host address may not be empty in URI: \"%s\"",
6186 uri);
6187 goto cleanup;
6190 /* Cut off the bracket and advance */
6191 *(p++) = '\0';
6194 * The address may be followed by a port specifier or a slash or a
6195 * query or a separator comma.
6197 if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6199 libpq_append_error(errorMessage,
6200 "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
6201 *p, (int) (p - buf + 1), uri);
6202 goto cleanup;
6205 else
6207 /* not an IPv6 address: DNS-named or IPv4 netloc */
6208 host = p;
6211 * Look for port specifier (colon) or end of host specifier
6212 * (slash) or query (question mark) or host separator (comma).
6214 while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6215 ++p;
6218 /* Save the hostname terminator before we null it */
6219 prevchar = *p;
6220 *p = '\0';
6222 appendPQExpBufferStr(&hostbuf, host);
6224 if (prevchar == ':')
6226 const char *port = ++p; /* advance past host terminator */
6228 while (*p && *p != '/' && *p != '?' && *p != ',')
6229 ++p;
6231 prevchar = *p;
6232 *p = '\0';
6234 appendPQExpBufferStr(&portbuf, port);
6237 if (prevchar != ',')
6238 break;
6239 ++p; /* advance past comma separator */
6240 appendPQExpBufferChar(&hostbuf, ',');
6241 appendPQExpBufferChar(&portbuf, ',');
6244 /* Save final values for host and port. */
6245 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6246 goto cleanup;
6247 if (hostbuf.data[0] &&
6248 !conninfo_storeval(options, "host", hostbuf.data,
6249 errorMessage, false, true))
6250 goto cleanup;
6251 if (portbuf.data[0] &&
6252 !conninfo_storeval(options, "port", portbuf.data,
6253 errorMessage, false, true))
6254 goto cleanup;
6256 if (prevchar && prevchar != '?')
6258 const char *dbname = ++p; /* advance past host terminator */
6260 /* Look for query parameters */
6261 while (*p && *p != '?')
6262 ++p;
6264 prevchar = *p;
6265 *p = '\0';
6268 * Avoid setting dbname to an empty string, as it forces the default
6269 * value (username) and ignores $PGDATABASE, as opposed to not setting
6270 * it at all.
6272 if (*dbname &&
6273 !conninfo_storeval(options, "dbname", dbname,
6274 errorMessage, false, true))
6275 goto cleanup;
6278 if (prevchar)
6280 ++p; /* advance past terminator */
6282 if (!conninfo_uri_parse_params(p, options, errorMessage))
6283 goto cleanup;
6286 /* everything parsed okay */
6287 retval = true;
6289 cleanup:
6290 termPQExpBuffer(&hostbuf);
6291 termPQExpBuffer(&portbuf);
6292 free(buf);
6293 return retval;
6297 * Connection URI parameters parser routine
6299 * If successful, returns true while connOptions is filled with parsed
6300 * parameters. Otherwise, returns false and fills errorMessage appropriately.
6302 * Destructively modifies 'params' buffer.
6304 static bool
6305 conninfo_uri_parse_params(char *params,
6306 PQconninfoOption *connOptions,
6307 PQExpBuffer errorMessage)
6309 while (*params)
6311 char *keyword = params;
6312 char *value = NULL;
6313 char *p = params;
6314 bool malloced = false;
6315 int oldmsglen;
6318 * Scan the params string for '=' and '&', marking the end of keyword
6319 * and value respectively.
6321 for (;;)
6323 if (*p == '=')
6325 /* Was there '=' already? */
6326 if (value != NULL)
6328 libpq_append_error(errorMessage,
6329 "extra key/value separator \"=\" in URI query parameter: \"%s\"",
6330 keyword);
6331 return false;
6333 /* Cut off keyword, advance to value */
6334 *p++ = '\0';
6335 value = p;
6337 else if (*p == '&' || *p == '\0')
6340 * If not at the end, cut off value and advance; leave p
6341 * pointing to start of the next parameter, if any.
6343 if (*p != '\0')
6344 *p++ = '\0';
6345 /* Was there '=' at all? */
6346 if (value == NULL)
6348 libpq_append_error(errorMessage,
6349 "missing key/value separator \"=\" in URI query parameter: \"%s\"",
6350 keyword);
6351 return false;
6353 /* Got keyword and value, go process them. */
6354 break;
6356 else
6357 ++p; /* Advance over all other bytes. */
6360 keyword = conninfo_uri_decode(keyword, errorMessage);
6361 if (keyword == NULL)
6363 /* conninfo_uri_decode already set an error message */
6364 return false;
6366 value = conninfo_uri_decode(value, errorMessage);
6367 if (value == NULL)
6369 /* conninfo_uri_decode already set an error message */
6370 free(keyword);
6371 return false;
6373 malloced = true;
6376 * Special keyword handling for improved JDBC compatibility.
6378 if (strcmp(keyword, "ssl") == 0 &&
6379 strcmp(value, "true") == 0)
6381 free(keyword);
6382 free(value);
6383 malloced = false;
6385 keyword = "sslmode";
6386 value = "require";
6390 * Store the value if the corresponding option exists; ignore
6391 * otherwise. At this point both keyword and value are not
6392 * URI-encoded.
6394 oldmsglen = errorMessage->len;
6395 if (!conninfo_storeval(connOptions, keyword, value,
6396 errorMessage, true, false))
6398 /* Insert generic message if conninfo_storeval didn't give one. */
6399 if (errorMessage->len == oldmsglen)
6400 libpq_append_error(errorMessage,
6401 "invalid URI query parameter: \"%s\"",
6402 keyword);
6403 /* And fail. */
6404 if (malloced)
6406 free(keyword);
6407 free(value);
6409 return false;
6412 if (malloced)
6414 free(keyword);
6415 free(value);
6418 /* Proceed to next key=value pair, if any */
6419 params = p;
6422 return true;
6426 * Connection URI decoder routine
6428 * If successful, returns the malloc'd decoded string.
6429 * If not successful, returns NULL and fills errorMessage accordingly.
6431 * The string is decoded by replacing any percent-encoded tokens with
6432 * corresponding characters, while preserving any non-encoded characters. A
6433 * percent-encoded token is a character triplet: a percent sign, followed by a
6434 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
6435 * treated identically.
6437 static char *
6438 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
6440 char *buf;
6441 char *p;
6442 const char *q = str;
6444 buf = malloc(strlen(str) + 1);
6445 if (buf == NULL)
6447 libpq_append_error(errorMessage, "out of memory");
6448 return NULL;
6450 p = buf;
6452 for (;;)
6454 if (*q != '%')
6456 /* copy and check for NUL terminator */
6457 if (!(*(p++) = *(q++)))
6458 break;
6460 else
6462 int hi;
6463 int lo;
6464 int c;
6466 ++q; /* skip the percent sign itself */
6469 * Possible EOL will be caught by the first call to
6470 * get_hexdigit(), so we never dereference an invalid q pointer.
6472 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
6474 libpq_append_error(errorMessage,
6475 "invalid percent-encoded token: \"%s\"",
6476 str);
6477 free(buf);
6478 return NULL;
6481 c = (hi << 4) | lo;
6482 if (c == 0)
6484 libpq_append_error(errorMessage,
6485 "forbidden value %%00 in percent-encoded value: \"%s\"",
6486 str);
6487 free(buf);
6488 return NULL;
6490 *(p++) = c;
6494 return buf;
6498 * Convert hexadecimal digit character to its integer value.
6500 * If successful, returns true and value is filled with digit's base 16 value.
6501 * If not successful, returns false.
6503 * Lower- and upper-case letters in the range A-F are treated identically.
6505 static bool
6506 get_hexdigit(char digit, int *value)
6508 if ('0' <= digit && digit <= '9')
6509 *value = digit - '0';
6510 else if ('A' <= digit && digit <= 'F')
6511 *value = digit - 'A' + 10;
6512 else if ('a' <= digit && digit <= 'f')
6513 *value = digit - 'a' + 10;
6514 else
6515 return false;
6517 return true;
6521 * Find an option value corresponding to the keyword in the connOptions array.
6523 * If successful, returns a pointer to the corresponding option's value.
6524 * If not successful, returns NULL.
6526 static const char *
6527 conninfo_getval(PQconninfoOption *connOptions,
6528 const char *keyword)
6530 PQconninfoOption *option;
6532 option = conninfo_find(connOptions, keyword);
6534 return option ? option->val : NULL;
6538 * Store a (new) value for an option corresponding to the keyword in
6539 * connOptions array.
6541 * If uri_decode is true, the value is URI-decoded. The keyword is always
6542 * assumed to be non URI-encoded.
6544 * If successful, returns a pointer to the corresponding PQconninfoOption,
6545 * which value is replaced with a strdup'd copy of the passed value string.
6546 * The existing value for the option is free'd before replacing, if any.
6548 * If not successful, returns NULL and fills errorMessage accordingly.
6549 * However, if the reason of failure is an invalid keyword being passed and
6550 * ignoreMissing is true, errorMessage will be left untouched.
6552 static PQconninfoOption *
6553 conninfo_storeval(PQconninfoOption *connOptions,
6554 const char *keyword, const char *value,
6555 PQExpBuffer errorMessage, bool ignoreMissing,
6556 bool uri_decode)
6558 PQconninfoOption *option;
6559 char *value_copy;
6562 * For backwards compatibility, requiressl=1 gets translated to
6563 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
6564 * (which is the default for sslmode).
6566 if (strcmp(keyword, "requiressl") == 0)
6568 keyword = "sslmode";
6569 if (value[0] == '1')
6570 value = "require";
6571 else
6572 value = "prefer";
6575 option = conninfo_find(connOptions, keyword);
6576 if (option == NULL)
6578 if (!ignoreMissing)
6579 libpq_append_error(errorMessage,
6580 "invalid connection option \"%s\"",
6581 keyword);
6582 return NULL;
6585 if (uri_decode)
6587 value_copy = conninfo_uri_decode(value, errorMessage);
6588 if (value_copy == NULL)
6589 /* conninfo_uri_decode already set an error message */
6590 return NULL;
6592 else
6594 value_copy = strdup(value);
6595 if (value_copy == NULL)
6597 libpq_append_error(errorMessage, "out of memory");
6598 return NULL;
6602 free(option->val);
6603 option->val = value_copy;
6605 return option;
6609 * Find a PQconninfoOption option corresponding to the keyword in the
6610 * connOptions array.
6612 * If successful, returns a pointer to the corresponding PQconninfoOption
6613 * structure.
6614 * If not successful, returns NULL.
6616 static PQconninfoOption *
6617 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
6619 PQconninfoOption *option;
6621 for (option = connOptions; option->keyword != NULL; option++)
6623 if (strcmp(option->keyword, keyword) == 0)
6624 return option;
6627 return NULL;
6632 * Return the connection options used for the connection
6634 PQconninfoOption *
6635 PQconninfo(PGconn *conn)
6637 PQExpBufferData errorBuf;
6638 PQconninfoOption *connOptions;
6640 if (conn == NULL)
6641 return NULL;
6644 * We don't actually report any errors here, but callees want a buffer,
6645 * and we prefer not to trash the conn's errorMessage.
6647 initPQExpBuffer(&errorBuf);
6648 if (PQExpBufferDataBroken(errorBuf))
6649 return NULL; /* out of memory already :-( */
6651 connOptions = conninfo_init(&errorBuf);
6653 if (connOptions != NULL)
6655 const internalPQconninfoOption *option;
6657 for (option = PQconninfoOptions; option->keyword; option++)
6659 char **connmember;
6661 if (option->connofs < 0)
6662 continue;
6664 connmember = (char **) ((char *) conn + option->connofs);
6666 if (*connmember)
6667 conninfo_storeval(connOptions, option->keyword, *connmember,
6668 &errorBuf, true, false);
6672 termPQExpBuffer(&errorBuf);
6674 return connOptions;
6678 void
6679 PQconninfoFree(PQconninfoOption *connOptions)
6681 if (connOptions == NULL)
6682 return;
6684 for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
6685 free(option->val);
6686 free(connOptions);
6690 /* =========== accessor functions for PGconn ========= */
6691 char *
6692 PQdb(const PGconn *conn)
6694 if (!conn)
6695 return NULL;
6696 return conn->dbName;
6699 char *
6700 PQuser(const PGconn *conn)
6702 if (!conn)
6703 return NULL;
6704 return conn->pguser;
6707 char *
6708 PQpass(const PGconn *conn)
6710 char *password = NULL;
6712 if (!conn)
6713 return NULL;
6714 if (conn->connhost != NULL)
6715 password = conn->connhost[conn->whichhost].password;
6716 if (password == NULL)
6717 password = conn->pgpass;
6718 /* Historically we've returned "" not NULL for no password specified */
6719 if (password == NULL)
6720 password = "";
6721 return password;
6724 char *
6725 PQhost(const PGconn *conn)
6727 if (!conn)
6728 return NULL;
6730 if (conn->connhost != NULL)
6733 * Return the verbatim host value provided by user, or hostaddr in its
6734 * lack.
6736 if (conn->connhost[conn->whichhost].host != NULL &&
6737 conn->connhost[conn->whichhost].host[0] != '\0')
6738 return conn->connhost[conn->whichhost].host;
6739 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
6740 conn->connhost[conn->whichhost].hostaddr[0] != '\0')
6741 return conn->connhost[conn->whichhost].hostaddr;
6744 return "";
6747 char *
6748 PQhostaddr(const PGconn *conn)
6750 if (!conn)
6751 return NULL;
6753 /* Return the parsed IP address */
6754 if (conn->connhost != NULL && conn->connip != NULL)
6755 return conn->connip;
6757 return "";
6760 char *
6761 PQport(const PGconn *conn)
6763 if (!conn)
6764 return NULL;
6766 if (conn->connhost != NULL)
6767 return conn->connhost[conn->whichhost].port;
6769 return "";
6773 * No longer does anything, but the function remains for API backwards
6774 * compatibility.
6776 char *
6777 PQtty(const PGconn *conn)
6779 if (!conn)
6780 return NULL;
6781 return "";
6784 char *
6785 PQoptions(const PGconn *conn)
6787 if (!conn)
6788 return NULL;
6789 return conn->pgoptions;
6792 ConnStatusType
6793 PQstatus(const PGconn *conn)
6795 if (!conn)
6796 return CONNECTION_BAD;
6797 return conn->status;
6800 PGTransactionStatusType
6801 PQtransactionStatus(const PGconn *conn)
6803 if (!conn || conn->status != CONNECTION_OK)
6804 return PQTRANS_UNKNOWN;
6805 if (conn->asyncStatus != PGASYNC_IDLE)
6806 return PQTRANS_ACTIVE;
6807 return conn->xactStatus;
6810 const char *
6811 PQparameterStatus(const PGconn *conn, const char *paramName)
6813 const pgParameterStatus *pstatus;
6815 if (!conn || !paramName)
6816 return NULL;
6817 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
6819 if (strcmp(pstatus->name, paramName) == 0)
6820 return pstatus->value;
6822 return NULL;
6826 PQprotocolVersion(const PGconn *conn)
6828 if (!conn)
6829 return 0;
6830 if (conn->status == CONNECTION_BAD)
6831 return 0;
6832 return PG_PROTOCOL_MAJOR(conn->pversion);
6836 PQserverVersion(const PGconn *conn)
6838 if (!conn)
6839 return 0;
6840 if (conn->status == CONNECTION_BAD)
6841 return 0;
6842 return conn->sversion;
6845 char *
6846 PQerrorMessage(const PGconn *conn)
6848 if (!conn)
6849 return libpq_gettext("connection pointer is NULL\n");
6852 * The errorMessage buffer might be marked "broken" due to having
6853 * previously failed to allocate enough memory for the message. In that
6854 * case, tell the application we ran out of memory.
6856 if (PQExpBufferBroken(&conn->errorMessage))
6857 return libpq_gettext("out of memory\n");
6859 return conn->errorMessage.data;
6863 * In Windows, socket values are unsigned, and an invalid socket value
6864 * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
6865 * warning). Ideally we would return an unsigned value for PQsocket() on
6866 * Windows, but that would cause the function's return value to differ from
6867 * Unix, so we just return -1 for invalid sockets.
6868 * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
6869 * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
6872 PQsocket(const PGconn *conn)
6874 if (!conn)
6875 return -1;
6876 return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
6880 PQbackendPID(const PGconn *conn)
6882 if (!conn || conn->status != CONNECTION_OK)
6883 return 0;
6884 return conn->be_pid;
6887 PGpipelineStatus
6888 PQpipelineStatus(const PGconn *conn)
6890 if (!conn)
6891 return PQ_PIPELINE_OFF;
6893 return conn->pipelineStatus;
6897 PQconnectionNeedsPassword(const PGconn *conn)
6899 char *password;
6901 if (!conn)
6902 return false;
6903 password = PQpass(conn);
6904 if (conn->password_needed &&
6905 (password == NULL || password[0] == '\0'))
6906 return true;
6907 else
6908 return false;
6912 PQconnectionUsedPassword(const PGconn *conn)
6914 if (!conn)
6915 return false;
6916 if (conn->password_needed)
6917 return true;
6918 else
6919 return false;
6923 PQconnectionUsedGSSAPI(const PGconn *conn)
6925 if (!conn)
6926 return false;
6927 if (conn->gssapi_used)
6928 return true;
6929 else
6930 return false;
6934 PQclientEncoding(const PGconn *conn)
6936 if (!conn || conn->status != CONNECTION_OK)
6937 return -1;
6938 return conn->client_encoding;
6942 PQsetClientEncoding(PGconn *conn, const char *encoding)
6944 char qbuf[128];
6945 static const char query[] = "set client_encoding to '%s'";
6946 PGresult *res;
6947 int status;
6949 if (!conn || conn->status != CONNECTION_OK)
6950 return -1;
6952 if (!encoding)
6953 return -1;
6955 /* Resolve special "auto" value from the locale */
6956 if (strcmp(encoding, "auto") == 0)
6957 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
6959 /* check query buffer overflow */
6960 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
6961 return -1;
6963 /* ok, now send a query */
6964 sprintf(qbuf, query, encoding);
6965 res = PQexec(conn, qbuf);
6967 if (res == NULL)
6968 return -1;
6969 if (res->resultStatus != PGRES_COMMAND_OK)
6970 status = -1;
6971 else
6974 * We rely on the backend to report the parameter value, and we'll
6975 * change state at that time.
6977 status = 0; /* everything is ok */
6979 PQclear(res);
6980 return status;
6983 PGVerbosity
6984 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
6986 PGVerbosity old;
6988 if (!conn)
6989 return PQERRORS_DEFAULT;
6990 old = conn->verbosity;
6991 conn->verbosity = verbosity;
6992 return old;
6995 PGContextVisibility
6996 PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
6998 PGContextVisibility old;
7000 if (!conn)
7001 return PQSHOW_CONTEXT_ERRORS;
7002 old = conn->show_context;
7003 conn->show_context = show_context;
7004 return old;
7007 PQnoticeReceiver
7008 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
7010 PQnoticeReceiver old;
7012 if (conn == NULL)
7013 return NULL;
7015 old = conn->noticeHooks.noticeRec;
7016 if (proc)
7018 conn->noticeHooks.noticeRec = proc;
7019 conn->noticeHooks.noticeRecArg = arg;
7021 return old;
7024 PQnoticeProcessor
7025 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
7027 PQnoticeProcessor old;
7029 if (conn == NULL)
7030 return NULL;
7032 old = conn->noticeHooks.noticeProc;
7033 if (proc)
7035 conn->noticeHooks.noticeProc = proc;
7036 conn->noticeHooks.noticeProcArg = arg;
7038 return old;
7042 * The default notice message receiver just gets the standard notice text
7043 * and sends it to the notice processor. This two-level setup exists
7044 * mostly for backwards compatibility; perhaps we should deprecate use of
7045 * PQsetNoticeProcessor?
7047 static void
7048 defaultNoticeReceiver(void *arg, const PGresult *res)
7050 (void) arg; /* not used */
7051 if (res->noticeHooks.noticeProc != NULL)
7052 res->noticeHooks.noticeProc(res->noticeHooks.noticeProcArg,
7053 PQresultErrorMessage(res));
7057 * The default notice message processor just prints the
7058 * message on stderr. Applications can override this if they
7059 * want the messages to go elsewhere (a window, for example).
7060 * Note that simply discarding notices is probably a bad idea.
7062 static void
7063 defaultNoticeProcessor(void *arg, const char *message)
7065 (void) arg; /* not used */
7066 /* Note: we expect the supplied string to end with a newline already. */
7067 fprintf(stderr, "%s", message);
7071 * returns a pointer to the next token or NULL if the current
7072 * token doesn't match
7074 static char *
7075 pwdfMatchesString(char *buf, const char *token)
7077 char *tbuf;
7078 const char *ttok;
7079 bool bslash = false;
7081 if (buf == NULL || token == NULL)
7082 return NULL;
7083 tbuf = buf;
7084 ttok = token;
7085 if (tbuf[0] == '*' && tbuf[1] == ':')
7086 return tbuf + 2;
7087 while (*tbuf != 0)
7089 if (*tbuf == '\\' && !bslash)
7091 tbuf++;
7092 bslash = true;
7094 if (*tbuf == ':' && *ttok == 0 && !bslash)
7095 return tbuf + 1;
7096 bslash = false;
7097 if (*ttok == 0)
7098 return NULL;
7099 if (*tbuf == *ttok)
7101 tbuf++;
7102 ttok++;
7104 else
7105 return NULL;
7107 return NULL;
7110 /* Get a password from the password file. Return value is malloc'd. */
7111 static char *
7112 passwordFromFile(const char *hostname, const char *port, const char *dbname,
7113 const char *username, const char *pgpassfile)
7115 FILE *fp;
7116 struct stat stat_buf;
7117 PQExpBufferData buf;
7119 if (dbname == NULL || dbname[0] == '\0')
7120 return NULL;
7122 if (username == NULL || username[0] == '\0')
7123 return NULL;
7125 /* 'localhost' matches pghost of '' or the default socket directory */
7126 if (hostname == NULL || hostname[0] == '\0')
7127 hostname = DefaultHost;
7128 else if (is_unixsock_path(hostname))
7131 * We should probably use canonicalize_path(), but then we have to
7132 * bring path.c into libpq, and it doesn't seem worth it.
7134 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
7135 hostname = DefaultHost;
7137 if (port == NULL || port[0] == '\0')
7138 port = DEF_PGPORT_STR;
7140 /* If password file cannot be opened, ignore it. */
7141 if (stat(pgpassfile, &stat_buf) != 0)
7142 return NULL;
7144 #ifndef WIN32
7145 if (!S_ISREG(stat_buf.st_mode))
7147 fprintf(stderr,
7148 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
7149 pgpassfile);
7150 return NULL;
7153 /* If password file is insecure, alert the user and ignore it. */
7154 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
7156 fprintf(stderr,
7157 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
7158 pgpassfile);
7159 return NULL;
7161 #else
7164 * On Win32, the directory is protected, so we don't have to check the
7165 * file.
7167 #endif
7169 fp = fopen(pgpassfile, "r");
7170 if (fp == NULL)
7171 return NULL;
7173 /* Use an expansible buffer to accommodate any reasonable line length */
7174 initPQExpBuffer(&buf);
7176 while (!feof(fp) && !ferror(fp))
7178 /* Make sure there's a reasonable amount of room in the buffer */
7179 if (!enlargePQExpBuffer(&buf, 128))
7180 break;
7182 /* Read some data, appending it to what we already have */
7183 if (fgets(buf.data + buf.len, buf.maxlen - buf.len, fp) == NULL)
7184 break;
7185 buf.len += strlen(buf.data + buf.len);
7187 /* If we don't yet have a whole line, loop around to read more */
7188 if (!(buf.len > 0 && buf.data[buf.len - 1] == '\n') && !feof(fp))
7189 continue;
7191 /* ignore comments */
7192 if (buf.data[0] != '#')
7194 char *t = buf.data;
7195 int len;
7197 /* strip trailing newline and carriage return */
7198 len = pg_strip_crlf(t);
7200 if (len > 0 &&
7201 (t = pwdfMatchesString(t, hostname)) != NULL &&
7202 (t = pwdfMatchesString(t, port)) != NULL &&
7203 (t = pwdfMatchesString(t, dbname)) != NULL &&
7204 (t = pwdfMatchesString(t, username)) != NULL)
7206 /* Found a match. */
7207 char *ret,
7208 *p1,
7209 *p2;
7211 ret = strdup(t);
7213 fclose(fp);
7214 explicit_bzero(buf.data, buf.maxlen);
7215 termPQExpBuffer(&buf);
7217 if (!ret)
7219 /* Out of memory. XXX: an error message would be nice. */
7220 return NULL;
7223 /* De-escape password. */
7224 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
7226 if (*p1 == '\\' && p1[1] != '\0')
7227 ++p1;
7228 *p2 = *p1;
7230 *p2 = '\0';
7232 return ret;
7236 /* No match, reset buffer to prepare for next line. */
7237 buf.len = 0;
7240 fclose(fp);
7241 explicit_bzero(buf.data, buf.maxlen);
7242 termPQExpBuffer(&buf);
7243 return NULL;
7248 * If the connection failed due to bad password, we should mention
7249 * if we got the password from the pgpassfile.
7251 static void
7252 pgpassfileWarning(PGconn *conn)
7254 /* If it was 'invalid authorization', add pgpassfile mention */
7255 /* only works with >= 9.0 servers */
7256 if (conn->password_needed &&
7257 conn->connhost[conn->whichhost].password != NULL &&
7258 conn->result)
7260 const char *sqlstate = PQresultErrorField(conn->result,
7261 PG_DIAG_SQLSTATE);
7263 if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
7264 libpq_append_conn_error(conn, "password retrieved from file \"%s\"",
7265 conn->pgpassfile);
7270 * Check if the SSL protocol value given in input is valid or not.
7271 * This is used as a sanity check routine for the connection parameters
7272 * ssl_min_protocol_version and ssl_max_protocol_version.
7274 static bool
7275 sslVerifyProtocolVersion(const char *version)
7278 * An empty string and a NULL value are considered valid as it is
7279 * equivalent to ignoring the parameter.
7281 if (!version || strlen(version) == 0)
7282 return true;
7284 if (pg_strcasecmp(version, "TLSv1") == 0 ||
7285 pg_strcasecmp(version, "TLSv1.1") == 0 ||
7286 pg_strcasecmp(version, "TLSv1.2") == 0 ||
7287 pg_strcasecmp(version, "TLSv1.3") == 0)
7288 return true;
7290 /* anything else is wrong */
7291 return false;
7296 * Ensure that the SSL protocol range given in input is correct. The check
7297 * is performed on the input string to keep it TLS backend agnostic. Input
7298 * to this function is expected verified with sslVerifyProtocolVersion().
7300 static bool
7301 sslVerifyProtocolRange(const char *min, const char *max)
7303 Assert(sslVerifyProtocolVersion(min) &&
7304 sslVerifyProtocolVersion(max));
7306 /* If at least one of the bounds is not set, the range is valid */
7307 if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
7308 return true;
7311 * If the minimum version is the lowest one we accept, then all options
7312 * for the maximum are valid.
7314 if (pg_strcasecmp(min, "TLSv1") == 0)
7315 return true;
7318 * The minimum bound is valid, and cannot be TLSv1, so using TLSv1 for the
7319 * maximum is incorrect.
7321 if (pg_strcasecmp(max, "TLSv1") == 0)
7322 return false;
7325 * At this point we know that we have a mix of TLSv1.1 through 1.3
7326 * versions.
7328 if (pg_strcasecmp(min, max) > 0)
7329 return false;
7331 return true;
7336 * Obtain user's home directory, return in given buffer
7338 * On Unix, this actually returns the user's home directory. On Windows
7339 * it returns the PostgreSQL-specific application data folder.
7341 * This is essentially the same as get_home_path(), but we don't use that
7342 * because we don't want to pull path.c into libpq (it pollutes application
7343 * namespace).
7345 * Returns true on success, false on failure to obtain the directory name.
7347 * CAUTION: although in most situations failure is unexpected, there are users
7348 * who like to run applications in a home-directory-less environment. On
7349 * failure, you almost certainly DO NOT want to report an error. Just act as
7350 * though whatever file you were hoping to find in the home directory isn't
7351 * there (which it isn't).
7353 bool
7354 pqGetHomeDirectory(char *buf, int bufsize)
7356 #ifndef WIN32
7357 const char *home;
7359 home = getenv("HOME");
7360 if (home == NULL || home[0] == '\0')
7361 return pg_get_user_home_dir(geteuid(), buf, bufsize);
7362 strlcpy(buf, home, bufsize);
7363 return true;
7364 #else
7365 char tmppath[MAX_PATH];
7367 ZeroMemory(tmppath, sizeof(tmppath));
7368 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7369 return false;
7370 snprintf(buf, bufsize, "%s/postgresql", tmppath);
7371 return true;
7372 #endif
7376 * Parse and try to interpret "value" as an integer value, and if successful,
7377 * store it in *result, complaining if there is any trailing garbage or an
7378 * overflow. This allows any number of leading and trailing whitespaces.
7380 bool
7381 pqParseIntParam(const char *value, int *result, PGconn *conn,
7382 const char *context)
7384 char *end;
7385 long numval;
7387 Assert(value != NULL);
7389 *result = 0;
7391 /* strtol(3) skips leading whitespaces */
7392 errno = 0;
7393 numval = strtol(value, &end, 10);
7396 * If no progress was done during the parsing or an error happened, fail.
7397 * This tests properly for overflows of the result.
7399 if (value == end || errno != 0 || numval != (int) numval)
7400 goto error;
7403 * Skip any trailing whitespace; if anything but whitespace remains before
7404 * the terminating character, fail
7406 while (*end != '\0' && isspace((unsigned char) *end))
7407 end++;
7409 if (*end != '\0')
7410 goto error;
7412 *result = numval;
7413 return true;
7415 error:
7416 libpq_append_conn_error(conn, "invalid integer value \"%s\" for connection option \"%s\"",
7417 value, context);
7418 return false;
7422 * To keep the API consistent, the locking stubs are always provided, even
7423 * if they are not required.
7425 * Since we neglected to provide any error-return convention in the
7426 * pgthreadlock_t API, we can't do much except Assert upon failure of any
7427 * mutex primitive. Fortunately, such failures appear to be nonexistent in
7428 * the field.
7431 static void
7432 default_threadlock(int acquire)
7434 #ifndef WIN32
7435 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
7436 #else
7437 static pthread_mutex_t singlethread_lock = NULL;
7438 static long mutex_initlock = 0;
7440 if (singlethread_lock == NULL)
7442 while (InterlockedExchange(&mutex_initlock, 1) == 1)
7443 /* loop, another thread own the lock */ ;
7444 if (singlethread_lock == NULL)
7446 if (pthread_mutex_init(&singlethread_lock, NULL))
7447 Assert(false);
7449 InterlockedExchange(&mutex_initlock, 0);
7451 #endif
7452 if (acquire)
7454 if (pthread_mutex_lock(&singlethread_lock))
7455 Assert(false);
7457 else
7459 if (pthread_mutex_unlock(&singlethread_lock))
7460 Assert(false);
7464 pgthreadlock_t
7465 PQregisterThreadLock(pgthreadlock_t newhandler)
7467 pgthreadlock_t prev = pg_g_threadlock;
7469 if (newhandler)
7470 pg_g_threadlock = newhandler;
7471 else
7472 pg_g_threadlock = default_threadlock;
7474 return prev;