1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/interfaces/libpq/fe-connect.c
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
24 #include "common/ip.h"
25 #include "common/link-canary.h"
26 #include "common/scram-common.h"
27 #include "common/string.h"
30 #include "libpq-int.h"
31 #include "mb/pg_wchar.h"
32 #include "pg_config_paths.h"
33 #include "port/pg_bswap.h"
40 #define _WIN32_IE 0x0500
46 #ifdef _MSC_VER /* mstcpip.h is missing on mingw */
50 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #ifdef HAVE_NETINET_TCP_H
54 #include <netinet/tcp.h>
58 #ifdef ENABLE_THREAD_SAFETY
60 #include "pthread-win32.h"
70 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
71 #define LDAP_DEPRECATED 1
73 typedef struct timeval LDAP_TIMEVAL;
75 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
76 PQExpBuffer errorMessage);
80 #define PGPASSFILE ".pgpass"
82 #define PGPASSFILE "pgpass.conf"
86 * Pre-9.0 servers will return this SQLSTATE if asked to set
87 * application_name in a startup packet. We hard-wire the value rather
88 * than looking into errcodes.h since it reflects historical behavior
89 * rather than that of the current code.
91 #define ERRCODE_APPNAME_UNKNOWN "42704"
93 /* This is part of the protocol so just define it */
94 #define ERRCODE_INVALID_PASSWORD "28P01"
96 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
99 * Cope with the various platform-specific ways to spell TCP keepalive socket
100 * options. This doesn't cover Windows, which as usual does its own thing.
102 #if defined(TCP_KEEPIDLE)
103 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
104 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
105 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
106 #elif defined(TCP_KEEPALIVE_THRESHOLD)
107 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
108 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
109 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
110 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
111 /* TCP_KEEPALIVE is the name of this option on macOS */
112 /* Caution: Solaris has this symbol but it means something different */
113 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
114 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
118 * fall back options if they are not specified by arguments or defined
119 * by environment variables
121 #define DefaultHost "localhost"
122 #define DefaultTty ""
123 #define DefaultOption ""
124 #define DefaultAuthtype ""
126 #define DefaultChannelBinding "prefer"
128 #define DefaultChannelBinding "disable"
130 #define DefaultTargetSessionAttrs "any"
132 #define DefaultSSLMode "prefer"
134 #define DefaultSSLMode "disable"
137 #include "fe-gssapi-common.h"
138 #define DefaultGSSMode "prefer"
140 #define DefaultGSSMode "disable"
144 * Definition of the conninfo parameters and their fallback resources.
146 * If Environment-Var and Compiled-in are specified as NULL, no
147 * fallback is available. If after all no value can be determined
148 * for an option, an error is returned.
150 * The value for the username is treated specially in conninfo_add_defaults.
151 * If the value is not obtained any other way, the username is determined
152 * by pg_fe_getauthname().
154 * The Label and Disp-Char entries are provided for applications that
155 * want to use PQconndefaults() to create a generic database connection
156 * dialog. Disp-Char is defined as follows:
157 * "" Normal input field
158 * "*" Password field - hide value
159 * "D" Debug option - don't show by default
161 * PQconninfoOptions[] is a constant static array that we use to initialize
162 * a dynamically allocated working copy. All the "val" fields in
163 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
164 * fields point to malloc'd strings that should be freed when the working
165 * array is freed (see PQconninfoFree).
167 * The first part of each struct is identical to the one in libpq-fe.h,
168 * which is required since we memcpy() data between the two!
171 typedef struct _internalPQconninfoOption
173 char *keyword; /* The keyword of the option */
174 char *envvar; /* Fallback environment variable name */
175 char *compiled; /* Fallback compiled in default value */
176 char *val; /* Option's current value, or NULL */
177 char *label; /* Label for field in connect dialog */
178 char *dispchar; /* Indicates how to display this field in a
179 * connect dialog. Values are: "" Display
180 * entered value as is "*" Password field -
181 * hide value "D" Debug option - don't show
183 int dispsize; /* Field size in characters for dialog */
185 * Anything above this comment must be synchronized with
186 * PQconninfoOption in libpq-fe.h, since we memcpy() data
190 off_t connofs; /* Offset into PGconn struct, -1 if not there */
191 } internalPQconninfoOption;
193 static const internalPQconninfoOption PQconninfoOptions[] = {
195 * "authtype" is no longer used, so mark it "don't show". We keep it in
196 * the array so as not to reject conninfo strings from old apps that might
197 * still try to set it.
199 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
200 "Database-Authtype", "D", 20, -1},
202 {"service", "PGSERVICE", NULL, NULL,
203 "Database-Service", "", 20, -1},
205 {"user", "PGUSER", NULL, NULL,
206 "Database-User", "", 20,
207 offsetof(struct pg_conn, pguser)},
209 {"password", "PGPASSWORD", NULL, NULL,
210 "Database-Password", "*", 20,
211 offsetof(struct pg_conn, pgpass)},
213 {"passfile", "PGPASSFILE", NULL, NULL,
214 "Database-Password-File", "", 64,
215 offsetof(struct pg_conn, pgpassfile)},
217 {"channel_binding", "PGCHANNELBINDING", NULL, NULL,
218 "Channel-Binding", "", 7, /* sizeof("require") */
219 offsetof(struct pg_conn, channel_binding)},
221 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
222 "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
223 offsetof(struct pg_conn, connect_timeout)},
225 {"dbname", "PGDATABASE", NULL, NULL,
226 "Database-Name", "", 20,
227 offsetof(struct pg_conn, dbName)},
229 {"host", "PGHOST", NULL, NULL,
230 "Database-Host", "", 40,
231 offsetof(struct pg_conn, pghost)},
233 {"hostaddr", "PGHOSTADDR", NULL, NULL,
234 "Database-Host-IP-Address", "", 45,
235 offsetof(struct pg_conn, pghostaddr)},
237 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
238 "Database-Port", "", 6,
239 offsetof(struct pg_conn, pgport)},
241 {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
242 "Client-Encoding", "", 10,
243 offsetof(struct pg_conn, client_encoding_initial)},
246 * "tty" is no longer used either, but keep it present for backwards
249 {"tty", "PGTTY", DefaultTty, NULL,
250 "Backend-Debug-TTY", "D", 40,
251 offsetof(struct pg_conn, pgtty)},
253 {"options", "PGOPTIONS", DefaultOption, NULL,
254 "Backend-Options", "", 40,
255 offsetof(struct pg_conn, pgoptions)},
257 {"application_name", "PGAPPNAME", NULL, NULL,
258 "Application-Name", "", 64,
259 offsetof(struct pg_conn, appname)},
261 {"fallback_application_name", NULL, NULL, NULL,
262 "Fallback-Application-Name", "", 64,
263 offsetof(struct pg_conn, fbappname)},
265 {"keepalives", NULL, NULL, NULL,
266 "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
267 offsetof(struct pg_conn, keepalives)},
269 {"keepalives_idle", NULL, NULL, NULL,
270 "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
271 offsetof(struct pg_conn, keepalives_idle)},
273 {"keepalives_interval", NULL, NULL, NULL,
274 "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
275 offsetof(struct pg_conn, keepalives_interval)},
277 {"keepalives_count", NULL, NULL, NULL,
278 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
279 offsetof(struct pg_conn, keepalives_count)},
281 {"tcp_user_timeout", NULL, NULL, NULL,
282 "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
283 offsetof(struct pg_conn, pgtcp_user_timeout)},
286 * ssl options are allowed even without client SSL support because the
287 * client can still handle SSL modes "disable" and "allow". Other
288 * parameters have no effect on non-SSL connections, so there is no reason
289 * to exclude them since none of them are mandatory.
291 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
292 "SSL-Mode", "", 12, /* sizeof("verify-full") == 12 */
293 offsetof(struct pg_conn, sslmode)},
295 {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
296 "SSL-Compression", "", 1,
297 offsetof(struct pg_conn, sslcompression)},
299 {"sslcert", "PGSSLCERT", NULL, NULL,
300 "SSL-Client-Cert", "", 64,
301 offsetof(struct pg_conn, sslcert)},
303 {"sslkey", "PGSSLKEY", NULL, NULL,
304 "SSL-Client-Key", "", 64,
305 offsetof(struct pg_conn, sslkey)},
307 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
308 "SSL-Root-Certificate", "", 64,
309 offsetof(struct pg_conn, sslrootcert)},
311 {"sslcrl", "PGSSLCRL", NULL, NULL,
312 "SSL-Revocation-List", "", 64,
313 offsetof(struct pg_conn, sslcrl)},
315 {"requirepeer", "PGREQUIREPEER", NULL, NULL,
316 "Require-Peer", "", 10,
317 offsetof(struct pg_conn, requirepeer)},
320 * Expose gssencmode similarly to sslmode - we can still handle "disable"
323 {"gssencmode", "PGGSSENCMODE", DefaultGSSMode, NULL,
324 "GSSENC-Mode", "", 7, /* sizeof("disable") == 7 */
325 offsetof(struct pg_conn, gssencmode)},
327 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
328 /* Kerberos and GSSAPI authentication support specifying the service name */
329 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
330 "Kerberos-service-name", "", 20,
331 offsetof(struct pg_conn, krbsrvname)},
334 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
337 * GSSAPI and SSPI both enabled, give a way to override which is used by
340 {"gsslib", "PGGSSLIB", NULL, NULL,
341 "GSS-library", "", 7, /* sizeof("gssapi") = 7 */
342 offsetof(struct pg_conn, gsslib)},
345 {"replication", NULL, NULL, NULL,
346 "Replication", "D", 5,
347 offsetof(struct pg_conn, replication)},
349 {"target_session_attrs", "PGTARGETSESSIONATTRS",
350 DefaultTargetSessionAttrs, NULL,
351 "Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */
352 offsetof(struct pg_conn, target_session_attrs)},
354 /* Terminating entry --- MUST BE LAST */
355 {NULL, NULL, NULL, NULL,
359 static const PQEnvironmentOption EnvironmentOptions[] =
361 /* common user-interface settings */
363 "PGDATESTYLE", "datestyle"
368 /* internal performance-related settings */
377 /* The connection URI must start with either of the following designators: */
378 static const char uri_designator[] = "postgresql://";
379 static const char short_uri_designator[] = "postgres://";
381 static bool connectOptions1(PGconn *conn, const char *conninfo);
382 static bool connectOptions2(PGconn *conn);
383 static int connectDBStart(PGconn *conn);
384 static int connectDBComplete(PGconn *conn);
385 static PGPing internal_ping(PGconn *conn);
386 static PGconn *makeEmptyPGconn(void);
387 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
388 static void freePGconn(PGconn *conn);
389 static void closePGconn(PGconn *conn);
390 static void release_conn_addrinfo(PGconn *conn);
391 static void sendTerminateConn(PGconn *conn);
392 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
393 static PQconninfoOption *parse_connection_string(const char *conninfo,
394 PQExpBuffer errorMessage, bool use_defaults);
395 static int uri_prefix_length(const char *connstr);
396 static bool recognized_connection_string(const char *connstr);
397 static PQconninfoOption *conninfo_parse(const char *conninfo,
398 PQExpBuffer errorMessage, bool use_defaults);
399 static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
400 const char *const *values, PQExpBuffer errorMessage,
401 bool use_defaults, int expand_dbname);
402 static bool conninfo_add_defaults(PQconninfoOption *options,
403 PQExpBuffer errorMessage);
404 static PQconninfoOption *conninfo_uri_parse(const char *uri,
405 PQExpBuffer errorMessage, bool use_defaults);
406 static bool conninfo_uri_parse_options(PQconninfoOption *options,
407 const char *uri, PQExpBuffer errorMessage);
408 static bool conninfo_uri_parse_params(char *params,
409 PQconninfoOption *connOptions,
410 PQExpBuffer errorMessage);
411 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
412 static bool get_hexdigit(char digit, int *value);
413 static const char *conninfo_getval(PQconninfoOption *connOptions,
414 const char *keyword);
415 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
416 const char *keyword, const char *value,
417 PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
418 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
419 const char *keyword);
420 static void defaultNoticeReceiver(void *arg, const PGresult *res);
421 static void defaultNoticeProcessor(void *arg, const char *message);
422 static int parseServiceInfo(PQconninfoOption *options,
423 PQExpBuffer errorMessage);
424 static int parseServiceFile(const char *serviceFile,
426 PQconninfoOption *options,
427 PQExpBuffer errorMessage,
429 static char *pwdfMatchesString(char *buf, const char *token);
430 static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
431 const char *username, const char *pgpassfile);
432 static void pgpassfileWarning(PGconn *conn);
433 static void default_threadlock(int acquire);
436 /* global variable because fe-auth.c needs to access it */
437 pgthreadlock_t pg_g_threadlock = default_threadlock;
443 * Close any physical connection to the server, and reset associated
444 * state inside the connection object. We don't release state that
445 * would be needed to reconnect, though, nor local state that might still
448 * We can always flush the output buffer, since there's no longer any hope
449 * of sending that data. However, unprocessed input data might still be
450 * valuable, so the caller must tell us whether to flush that or not.
453 pqDropConnection(PGconn *conn, bool flushInput)
455 /* Drop any SSL state */
456 pqsecure_close(conn);
458 /* Close the socket itself */
459 if (conn->sock != PGINVALID_SOCKET)
460 closesocket(conn->sock);
461 conn->sock = PGINVALID_SOCKET;
463 /* Optionally discard any unread data */
465 conn->inStart = conn->inCursor = conn->inEnd = 0;
467 /* Always discard any unsent data */
470 /* Free authentication state */
476 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
478 gss_release_name(&min_s, &conn->gtarg_nam);
482 if (conn->sspitarget)
484 free(conn->sspitarget);
485 conn->sspitarget = NULL;
489 FreeCredentialsHandle(conn->sspicred);
490 free(conn->sspicred);
491 conn->sspicred = NULL;
495 DeleteSecurityContext(conn->sspictx);
497 conn->sspictx = NULL;
501 if (conn->sasl_state)
504 * XXX: if support for more authentication mechanisms is added, this
505 * needs to call the right 'free' function.
507 pg_fe_scram_free(conn->sasl_state);
508 conn->sasl_state = NULL;
516 * Clear all connection state data that was received from (or deduced about)
517 * the server. This is essential to do between connection attempts to
518 * different servers, else we may incorrectly hold over some data from the
521 * It would be better to merge this into pqDropConnection, perhaps, but
522 * right now we cannot because that function is called immediately on
523 * detection of connection loss (cf. pqReadData, for instance). This data
524 * should be kept until we are actually starting a new connection.
527 pqDropServerData(PGconn *conn)
530 pgParameterStatus *pstatus;
532 /* Forget pending notifies */
533 notify = conn->notifyHead;
534 while (notify != NULL)
536 PGnotify *prev = notify;
538 notify = notify->next;
541 conn->notifyHead = conn->notifyTail = NULL;
543 /* Reset ParameterStatus data, as well as variables deduced from it */
544 pstatus = conn->pstatus;
545 while (pstatus != NULL)
547 pgParameterStatus *prev = pstatus;
549 pstatus = pstatus->next;
552 conn->pstatus = NULL;
553 conn->client_encoding = PG_SQL_ASCII;
554 conn->std_strings = false;
557 /* Drop large-object lookup data */
559 free(conn->lobjfuncs);
560 conn->lobjfuncs = NULL;
562 /* Reset assorted other per-connection state */
563 conn->last_sqlstate[0] = '\0';
564 conn->auth_req_received = false;
565 conn->password_needed = false;
566 conn->write_failed = false;
567 if (conn->write_err_msg)
568 free(conn->write_err_msg);
569 conn->write_err_msg = NULL;
576 * Connecting to a Database
578 * There are now six different ways a user of this API can connect to the
579 * database. Two are not recommended for use in new code, because of their
580 * lack of extensibility with respect to the passing of options to the
581 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
584 * If it is desired to connect in a synchronous (blocking) manner, use the
585 * function PQconnectdb or PQconnectdbParams. The former accepts a string of
586 * option = value pairs (or a URI) which must be parsed; the latter takes two
587 * NULL terminated arrays instead.
589 * To connect in an asynchronous (non-blocking) manner, use the functions
590 * PQconnectStart or PQconnectStartParams (which differ in the same way as
591 * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
593 * Internally, the static functions connectDBStart, connectDBComplete
594 * are part of the connection procedure.
600 * establishes a connection to a postgres backend through the postmaster
601 * using connection information in two arrays.
603 * The keywords array is defined as
605 * const char *params[] = {"option1", "option2", NULL}
607 * The values array is defined as
609 * const char *values[] = {"value1", "value2", NULL}
611 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
612 * if a memory allocation failed.
613 * If the status field of the connection returned is CONNECTION_BAD,
614 * then some fields may be null'ed out instead of having valid values.
616 * You should call PQfinish (if conn is not NULL) regardless of whether this
620 PQconnectdbParams(const char *const *keywords,
621 const char *const *values,
624 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
626 if (conn && conn->status != CONNECTION_BAD)
627 (void) connectDBComplete(conn);
636 * check server status, accepting parameters identical to PQconnectdbParams
639 PQpingParams(const char *const *keywords,
640 const char *const *values,
643 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
646 ret = internal_ping(conn);
655 * establishes a connection to a postgres backend through the postmaster
656 * using connection information in a string.
658 * The conninfo string is either a whitespace-separated list of
662 * definitions or a URI (refer to the documentation for details.) Value
663 * might be a single value containing no whitespaces or a single quoted
664 * string. If a single quote should appear anywhere in the value, it must be
665 * escaped with a backslash like \'
667 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
668 * if a memory allocation failed.
669 * If the status field of the connection returned is CONNECTION_BAD,
670 * then some fields may be null'ed out instead of having valid values.
672 * You should call PQfinish (if conn is not NULL) regardless of whether this
676 PQconnectdb(const char *conninfo)
678 PGconn *conn = PQconnectStart(conninfo);
680 if (conn && conn->status != CONNECTION_BAD)
681 (void) connectDBComplete(conn);
689 * check server status, accepting parameters identical to PQconnectdb
692 PQping(const char *conninfo)
694 PGconn *conn = PQconnectStart(conninfo);
697 ret = internal_ping(conn);
704 * PQconnectStartParams
706 * Begins the establishment of a connection to a postgres backend through the
707 * postmaster using connection information in a struct.
709 * See comment for PQconnectdbParams for the definition of the string format.
711 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
712 * you should not attempt to proceed with this connection. If the status
713 * field of the connection returned is CONNECTION_BAD, an error has
714 * occurred. In this case you should call PQfinish on the result, (perhaps
715 * inspecting the error message first). Other fields of the structure may not
716 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
717 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
720 * See PQconnectPoll for more info.
723 PQconnectStartParams(const char *const *keywords,
724 const char *const *values,
728 PQconninfoOption *connOptions;
731 * Allocate memory for the conn structure
733 conn = makeEmptyPGconn();
738 * Parse the conninfo arrays
740 connOptions = conninfo_array_parse(keywords, values,
742 true, expand_dbname);
743 if (connOptions == NULL)
745 conn->status = CONNECTION_BAD;
746 /* errorMessage is already set */
751 * Move option values into conn structure
753 if (!fillPGconn(conn, connOptions))
755 PQconninfoFree(connOptions);
760 * Free the option info - all is in conn now
762 PQconninfoFree(connOptions);
765 * Compute derived options
767 if (!connectOptions2(conn))
771 * Connect to the database
773 if (!connectDBStart(conn))
775 /* Just in case we failed to set it in connectDBStart */
776 conn->status = CONNECTION_BAD;
785 * Begins the establishment of a connection to a postgres backend through the
786 * postmaster using connection information in a string.
788 * See comment for PQconnectdb for the definition of the string format.
790 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
791 * you should not attempt to proceed with this connection. If the status
792 * field of the connection returned is CONNECTION_BAD, an error has
793 * occurred. In this case you should call PQfinish on the result, (perhaps
794 * inspecting the error message first). Other fields of the structure may not
795 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
796 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
799 * See PQconnectPoll for more info.
802 PQconnectStart(const char *conninfo)
807 * Allocate memory for the conn structure
809 conn = makeEmptyPGconn();
814 * Parse the conninfo string
816 if (!connectOptions1(conn, conninfo))
820 * Compute derived options
822 if (!connectOptions2(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;
838 * Move option values into conn structure
840 * Don't put anything cute here --- intelligence should be in
841 * connectOptions2 ...
843 * Returns true on success. On failure, returns false and sets error message.
846 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
848 const internalPQconninfoOption *option;
850 for (option = PQconninfoOptions; option->keyword; option++)
852 if (option->connofs >= 0)
854 const char *tmp = conninfo_getval(connOptions, option->keyword);
858 char **connmember = (char **) ((char *) conn + option->connofs);
862 *connmember = strdup(tmp);
863 if (*connmember == NULL)
865 printfPQExpBuffer(&conn->errorMessage,
866 libpq_gettext("out of memory\n"));
879 * Internal subroutine to set up connection parameters given an already-
880 * created PGconn and a conninfo string. Derived settings should be
881 * processed by calling connectOptions2 next. (We split them because
882 * PQsetdbLogin overrides defaults in between.)
884 * Returns true if OK, false if trouble (in which case errorMessage is set
885 * and so is conn->status).
888 connectOptions1(PGconn *conn, const char *conninfo)
890 PQconninfoOption *connOptions;
893 * Parse the conninfo string
895 connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
896 if (connOptions == NULL)
898 conn->status = CONNECTION_BAD;
899 /* errorMessage is already set */
904 * Move option values into conn structure
906 if (!fillPGconn(conn, connOptions))
908 conn->status = CONNECTION_BAD;
909 PQconninfoFree(connOptions);
914 * Free the option info - all is in conn now
916 PQconninfoFree(connOptions);
922 * Count the number of elements in a simple comma-separated list.
925 count_comma_separated_elems(const char *input)
930 for (; *input != '\0'; input++)
940 * Parse a simple comma-separated list.
942 * On each call, returns a malloc'd copy of the next element, and sets *more
943 * to indicate whether there are any more elements in the list after this,
944 * and updates *startptr to point to the next element, if any.
946 * On out of memory, returns NULL.
949 parse_comma_separated_list(char **startptr, bool *more)
957 * Search for the end of the current element; a comma or end-of-string
958 * acts as a terminator.
961 while (*e != '\0' && *e != ',')
966 p = (char *) malloc(sizeof(char) * (len + 1));
980 * Compute derived connection options after absorbing all user-supplied info.
982 * Returns true if OK, false if trouble (in which case errorMessage is set
983 * and so is conn->status).
986 connectOptions2(PGconn *conn)
991 * Allocate memory for details about each host to which we might possibly
992 * try to connect. For that, count the number of elements in the hostaddr
993 * or host options. If neither is given, assume one host.
996 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
997 conn->nconnhost = count_comma_separated_elems(conn->pghostaddr);
998 else if (conn->pghost && conn->pghost[0] != '\0')
999 conn->nconnhost = count_comma_separated_elems(conn->pghost);
1001 conn->nconnhost = 1;
1002 conn->connhost = (pg_conn_host *)
1003 calloc(conn->nconnhost, sizeof(pg_conn_host));
1004 if (conn->connhost == NULL)
1008 * We now have one pg_conn_host structure per possible host. Fill in the
1009 * host and hostaddr fields for each, by splitting the parameter strings.
1011 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1013 char *s = conn->pghostaddr;
1016 for (i = 0; i < conn->nconnhost && more; i++)
1018 conn->connhost[i].hostaddr = parse_comma_separated_list(&s, &more);
1019 if (conn->connhost[i].hostaddr == NULL)
1024 * If hostaddr was given, the array was allocated according to the
1025 * number of elements in the hostaddr list, so it really should be the
1029 Assert(i == conn->nconnhost);
1032 if (conn->pghost != NULL && conn->pghost[0] != '\0')
1034 char *s = conn->pghost;
1037 for (i = 0; i < conn->nconnhost && more; i++)
1039 conn->connhost[i].host = parse_comma_separated_list(&s, &more);
1040 if (conn->connhost[i].host == NULL)
1044 /* Check for wrong number of host items. */
1045 if (more || i != conn->nconnhost)
1047 conn->status = CONNECTION_BAD;
1048 printfPQExpBuffer(&conn->errorMessage,
1049 libpq_gettext("could not match %d host names to %d hostaddr values\n"),
1050 count_comma_separated_elems(conn->pghost), conn->nconnhost);
1056 * Now, for each host slot, identify the type of address spec, and fill in
1057 * the default address if nothing was given.
1059 for (i = 0; i < conn->nconnhost; i++)
1061 pg_conn_host *ch = &conn->connhost[i];
1063 if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1064 ch->type = CHT_HOST_ADDRESS;
1065 else if (ch->host != NULL && ch->host[0] != '\0')
1067 ch->type = CHT_HOST_NAME;
1068 #ifdef HAVE_UNIX_SOCKETS
1069 if (is_absolute_path(ch->host))
1070 ch->type = CHT_UNIX_SOCKET;
1077 #ifdef HAVE_UNIX_SOCKETS
1078 ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1079 ch->type = CHT_UNIX_SOCKET;
1081 ch->host = strdup(DefaultHost);
1082 ch->type = CHT_HOST_NAME;
1084 if (ch->host == NULL)
1090 * Next, work out the port number corresponding to each host name.
1092 * Note: unlike the above for host names, this could leave the port fields
1093 * as null or empty strings. We will substitute DEF_PGPORT whenever we
1094 * read such a port field.
1096 if (conn->pgport != NULL && conn->pgport[0] != '\0')
1098 char *s = conn->pgport;
1101 for (i = 0; i < conn->nconnhost && more; i++)
1103 conn->connhost[i].port = parse_comma_separated_list(&s, &more);
1104 if (conn->connhost[i].port == NULL)
1109 * If exactly one port was given, use it for every host. Otherwise,
1110 * there must be exactly as many ports as there were hosts.
1112 if (i == 1 && !more)
1114 for (i = 1; i < conn->nconnhost; i++)
1116 conn->connhost[i].port = strdup(conn->connhost[0].port);
1117 if (conn->connhost[i].port == NULL)
1121 else if (more || i != conn->nconnhost)
1123 conn->status = CONNECTION_BAD;
1124 printfPQExpBuffer(&conn->errorMessage,
1125 libpq_gettext("could not match %d port numbers to %d hosts\n"),
1126 count_comma_separated_elems(conn->pgport), conn->nconnhost);
1132 * If user name was not given, fetch it. (Most likely, the fetch will
1133 * fail, since the only way we get here is if pg_fe_getauthname() failed
1134 * during conninfo_add_defaults(). But now we want an error message.)
1136 if (conn->pguser == NULL || conn->pguser[0] == '\0')
1140 conn->pguser = pg_fe_getauthname(&conn->errorMessage);
1143 conn->status = CONNECTION_BAD;
1149 * If database name was not given, default it to equal user name
1151 if (conn->dbName == NULL || conn->dbName[0] == '\0')
1155 conn->dbName = strdup(conn->pguser);
1161 * If password was not given, try to look it up in password file. Note
1162 * that the result might be different for each host/port pair.
1164 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1166 /* If password file wasn't specified, use ~/PGPASSFILE */
1167 if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1169 char homedir[MAXPGPATH];
1171 if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1173 if (conn->pgpassfile)
1174 free(conn->pgpassfile);
1175 conn->pgpassfile = malloc(MAXPGPATH);
1176 if (!conn->pgpassfile)
1178 snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1179 homedir, PGPASSFILE);
1183 if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1185 for (i = 0; i < conn->nconnhost; i++)
1188 * Try to get a password for this host from file. We use host
1189 * for the hostname search key if given, else hostaddr (at
1190 * least one of them is guaranteed nonempty by now).
1192 const char *pwhost = conn->connhost[i].host;
1194 if (pwhost == NULL || pwhost[0] == '\0')
1195 pwhost = conn->connhost[i].hostaddr;
1197 conn->connhost[i].password =
1198 passwordFromFile(pwhost,
1199 conn->connhost[i].port,
1208 * validate channel_binding option
1210 if (conn->channel_binding)
1212 if (strcmp(conn->channel_binding, "disable") != 0
1213 && strcmp(conn->channel_binding, "prefer") != 0
1214 && strcmp(conn->channel_binding, "require") != 0)
1216 conn->status = CONNECTION_BAD;
1217 printfPQExpBuffer(&conn->errorMessage,
1218 libpq_gettext("invalid channel_binding value: \"%s\"\n"),
1219 conn->channel_binding);
1225 conn->channel_binding = strdup(DefaultChannelBinding);
1226 if (!conn->channel_binding)
1231 * validate sslmode option
1235 if (strcmp(conn->sslmode, "disable") != 0
1236 && strcmp(conn->sslmode, "allow") != 0
1237 && strcmp(conn->sslmode, "prefer") != 0
1238 && strcmp(conn->sslmode, "require") != 0
1239 && strcmp(conn->sslmode, "verify-ca") != 0
1240 && strcmp(conn->sslmode, "verify-full") != 0)
1242 conn->status = CONNECTION_BAD;
1243 printfPQExpBuffer(&conn->errorMessage,
1244 libpq_gettext("invalid sslmode value: \"%s\"\n"),
1250 switch (conn->sslmode[0])
1252 case 'a': /* "allow" */
1253 case 'p': /* "prefer" */
1256 * warn user that an SSL connection will never be negotiated
1257 * since SSL was not compiled in?
1261 case 'r': /* "require" */
1262 case 'v': /* "verify-ca" or "verify-full" */
1263 conn->status = CONNECTION_BAD;
1264 printfPQExpBuffer(&conn->errorMessage,
1265 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
1273 conn->sslmode = strdup(DefaultSSLMode);
1279 * validate gssencmode option
1281 if (conn->gssencmode)
1283 if (strcmp(conn->gssencmode, "disable") != 0 &&
1284 strcmp(conn->gssencmode, "prefer") != 0 &&
1285 strcmp(conn->gssencmode, "require") != 0)
1287 conn->status = CONNECTION_BAD;
1288 printfPQExpBuffer(&conn->errorMessage,
1289 libpq_gettext("invalid gssencmode value: \"%s\"\n"),
1294 if (strcmp(conn->gssencmode, "require") == 0)
1296 conn->status = CONNECTION_BAD;
1297 printfPQExpBuffer(&conn->errorMessage,
1298 libpq_gettext("gssencmode value \"%s\" invalid when GSSAPI support is not compiled in\n"),
1306 conn->gssencmode = strdup(DefaultGSSMode);
1307 if (!conn->gssencmode)
1312 * Resolve special "auto" client_encoding from the locale
1314 if (conn->client_encoding_initial &&
1315 strcmp(conn->client_encoding_initial, "auto") == 0)
1317 free(conn->client_encoding_initial);
1318 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
1319 if (!conn->client_encoding_initial)
1324 * Validate target_session_attrs option.
1326 if (conn->target_session_attrs)
1328 if (strcmp(conn->target_session_attrs, "any") != 0
1329 && strcmp(conn->target_session_attrs, "read-write") != 0)
1331 conn->status = CONNECTION_BAD;
1332 printfPQExpBuffer(&conn->errorMessage,
1333 libpq_gettext("invalid target_session_attrs value: \"%s\"\n"),
1334 conn->target_session_attrs);
1340 * Only if we get this far is it appropriate to try to connect. (We need a
1341 * state flag, rather than just the boolean result of this function, in
1342 * case someone tries to PQreset() the PGconn.)
1344 conn->options_valid = true;
1349 conn->status = CONNECTION_BAD;
1350 printfPQExpBuffer(&conn->errorMessage,
1351 libpq_gettext("out of memory\n"));
1358 * Construct a default connection options array, which identifies all the
1359 * available options and shows any default values that are available from the
1360 * environment etc. On error (eg out of memory), NULL is returned.
1362 * Using this function, an application may determine all possible options
1363 * and their current default values.
1365 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1366 * and should be freed when no longer needed via PQconninfoFree(). (In prior
1367 * versions, the returned array was static, but that's not thread-safe.)
1368 * Pre-7.0 applications that use this function will see a small memory leak
1369 * until they are updated to call PQconninfoFree.
1372 PQconndefaults(void)
1374 PQExpBufferData errorBuf;
1375 PQconninfoOption *connOptions;
1377 /* We don't actually report any errors here, but callees want a buffer */
1378 initPQExpBuffer(&errorBuf);
1379 if (PQExpBufferDataBroken(errorBuf))
1380 return NULL; /* out of memory already :-( */
1382 connOptions = conninfo_init(&errorBuf);
1383 if (connOptions != NULL)
1385 /* pass NULL errorBuf to ignore errors */
1386 if (!conninfo_add_defaults(connOptions, NULL))
1388 PQconninfoFree(connOptions);
1393 termPQExpBuffer(&errorBuf);
1400 * establishes a connection to a postgres backend through the postmaster
1401 * at the specified host and port.
1403 * returns a PGconn* which is needed for all subsequent libpq calls
1405 * if the status field of the connection returned is CONNECTION_BAD,
1406 * then only the errorMessage is likely to be useful.
1410 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1411 const char *pgtty, const char *dbName, const char *login,
1417 * Allocate memory for the conn structure
1419 conn = makeEmptyPGconn();
1424 * If the dbName parameter contains what looks like a connection string,
1425 * parse it into conn struct using connectOptions1.
1427 if (dbName && recognized_connection_string(dbName))
1429 if (!connectOptions1(conn, dbName))
1435 * Old-style path: first, parse an empty conninfo string in order to
1436 * set up the same defaults that PQconnectdb() would use.
1438 if (!connectOptions1(conn, ""))
1441 /* Insert dbName parameter value into struct */
1442 if (dbName && dbName[0] != '\0')
1446 conn->dbName = strdup(dbName);
1453 * Insert remaining parameters into struct, overriding defaults (as well
1454 * as any conflicting data from dbName taken as a conninfo).
1456 if (pghost && pghost[0] != '\0')
1460 conn->pghost = strdup(pghost);
1465 if (pgport && pgport[0] != '\0')
1469 conn->pgport = strdup(pgport);
1474 if (pgoptions && pgoptions[0] != '\0')
1476 if (conn->pgoptions)
1477 free(conn->pgoptions);
1478 conn->pgoptions = strdup(pgoptions);
1479 if (!conn->pgoptions)
1483 if (pgtty && pgtty[0] != '\0')
1487 conn->pgtty = strdup(pgtty);
1492 if (login && login[0] != '\0')
1496 conn->pguser = strdup(login);
1501 if (pwd && pwd[0] != '\0')
1505 conn->pgpass = strdup(pwd);
1511 * Compute derived options
1513 if (!connectOptions2(conn))
1517 * Connect to the database
1519 if (connectDBStart(conn))
1520 (void) connectDBComplete(conn);
1525 conn->status = CONNECTION_BAD;
1526 printfPQExpBuffer(&conn->errorMessage,
1527 libpq_gettext("out of memory\n"));
1534 * Sets the TCP_NODELAY socket option.
1535 * Returns 1 if successful, 0 if not.
1539 connectNoDelay(PGconn *conn)
1544 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1548 char sebuf[PG_STRERROR_R_BUFLEN];
1550 appendPQExpBuffer(&conn->errorMessage,
1551 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1552 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1561 * Write currently connected IP address into host_addr (of len host_addr_len).
1562 * If unable to, set it to the empty string.
1566 getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
1568 struct sockaddr_storage *addr = &conn->raddr.addr;
1570 if (addr->ss_family == AF_INET)
1572 if (pg_inet_net_ntop(AF_INET,
1573 &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1575 host_addr, host_addr_len) == NULL)
1576 host_addr[0] = '\0';
1579 else if (addr->ss_family == AF_INET6)
1581 if (pg_inet_net_ntop(AF_INET6,
1582 &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1584 host_addr, host_addr_len) == NULL)
1585 host_addr[0] = '\0';
1589 host_addr[0] = '\0';
1593 * connectFailureMessage -
1594 * create a friendly error message on connection failure.
1598 connectFailureMessage(PGconn *conn, int errorno)
1600 char sebuf[PG_STRERROR_R_BUFLEN];
1602 #ifdef HAVE_UNIX_SOCKETS
1603 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1605 char service[NI_MAXHOST];
1607 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1609 service, sizeof(service),
1611 appendPQExpBuffer(&conn->errorMessage,
1612 libpq_gettext("could not connect to server: %s\n"
1613 "\tIs the server running locally and accepting\n"
1614 "\tconnections on Unix domain socket \"%s\"?\n"),
1615 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1619 #endif /* HAVE_UNIX_SOCKETS */
1621 char host_addr[NI_MAXHOST];
1622 const char *displayed_host;
1623 const char *displayed_port;
1626 * Optionally display the network address with the hostname. This is
1627 * useful to distinguish between IPv4 and IPv6 connections.
1629 getHostaddr(conn, host_addr, NI_MAXHOST);
1631 /* To which host and port were we actually connecting? */
1632 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
1633 displayed_host = conn->connhost[conn->whichhost].hostaddr;
1635 displayed_host = conn->connhost[conn->whichhost].host;
1636 displayed_port = conn->connhost[conn->whichhost].port;
1637 if (displayed_port == NULL || displayed_port[0] == '\0')
1638 displayed_port = DEF_PGPORT_STR;
1641 * If the user did not supply an IP address using 'hostaddr', and
1642 * 'host' was missing or does not match our lookup, display the
1643 * looked-up IP address.
1645 if (conn->connhost[conn->whichhost].type != CHT_HOST_ADDRESS &&
1646 strlen(host_addr) > 0 &&
1647 strcmp(displayed_host, host_addr) != 0)
1648 appendPQExpBuffer(&conn->errorMessage,
1649 libpq_gettext("could not connect to server: %s\n"
1650 "\tIs the server running on host \"%s\" (%s) and accepting\n"
1651 "\tTCP/IP connections on port %s?\n"),
1652 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1653 displayed_host, host_addr,
1656 appendPQExpBuffer(&conn->errorMessage,
1657 libpq_gettext("could not connect to server: %s\n"
1658 "\tIs the server running on host \"%s\" and accepting\n"
1659 "\tTCP/IP connections on port %s?\n"),
1660 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1667 * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
1668 * conn->keepalives is set to a value which is not parseable as an
1672 useKeepalives(PGconn *conn)
1677 if (conn->keepalives == NULL)
1679 val = strtol(conn->keepalives, &ep, 10);
1682 return val != 0 ? 1 : 0;
1686 * Parse and try to interpret "value" as an integer value, and if successful,
1687 * store it in *result, complaining if there is any trailing garbage or an
1688 * overflow. This allows any number of leading and trailing whitespaces.
1691 parse_int_param(const char *value, int *result, PGconn *conn,
1692 const char *context)
1697 Assert(value != NULL);
1701 /* strtol(3) skips leading whitespaces */
1703 numval = strtol(value, &end, 10);
1706 * If no progress was done during the parsing or an error happened, fail.
1707 * This tests properly for overflows of the result.
1709 if (value == end || errno != 0 || numval != (int) numval)
1713 * Skip any trailing whitespace; if anything but whitespace remains before
1714 * the terminating character, fail
1716 while (*end != '\0' && isspace((unsigned char) *end))
1726 appendPQExpBuffer(&conn->errorMessage,
1727 libpq_gettext("invalid integer value \"%s\" for connection option \"%s\"\n"),
1734 * Set the keepalive idle timer.
1737 setKeepalivesIdle(PGconn *conn)
1741 if (conn->keepalives_idle == NULL)
1744 if (!parse_int_param(conn->keepalives_idle, &idle, conn,
1750 #ifdef PG_TCP_KEEPALIVE_IDLE
1751 if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1752 (char *) &idle, sizeof(idle)) < 0)
1754 char sebuf[PG_STRERROR_R_BUFLEN];
1756 appendPQExpBuffer(&conn->errorMessage,
1757 libpq_gettext("setsockopt(%s) failed: %s\n"),
1758 PG_TCP_KEEPALIVE_IDLE_STR,
1759 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1768 * Set the keepalive interval.
1771 setKeepalivesInterval(PGconn *conn)
1775 if (conn->keepalives_interval == NULL)
1778 if (!parse_int_param(conn->keepalives_interval, &interval, conn,
1779 "keepalives_interval"))
1784 #ifdef TCP_KEEPINTVL
1785 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1786 (char *) &interval, sizeof(interval)) < 0)
1788 char sebuf[PG_STRERROR_R_BUFLEN];
1790 appendPQExpBuffer(&conn->errorMessage,
1791 libpq_gettext("setsockopt(%s) failed: %s\n"),
1793 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1802 * Set the count of lost keepalive packets that will trigger a connection
1806 setKeepalivesCount(PGconn *conn)
1810 if (conn->keepalives_count == NULL)
1813 if (!parse_int_param(conn->keepalives_count, &count, conn,
1814 "keepalives_count"))
1820 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1821 (char *) &count, sizeof(count)) < 0)
1823 char sebuf[PG_STRERROR_R_BUFLEN];
1825 appendPQExpBuffer(&conn->errorMessage,
1826 libpq_gettext("setsockopt(%s) failed: %s\n"),
1828 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1836 #ifdef SIO_KEEPALIVE_VALS
1838 * Enable keepalives and set the keepalive values on Win32,
1839 * where they are always set in one batch.
1842 setKeepalivesWin32(PGconn *conn)
1844 struct tcp_keepalive ka;
1849 if (conn->keepalives_idle &&
1850 !parse_int_param(conn->keepalives_idle, &idle, conn,
1854 idle = 2 * 60 * 60; /* 2 hours = default */
1856 if (conn->keepalives_interval &&
1857 !parse_int_param(conn->keepalives_interval, &interval, conn,
1858 "keepalives_interval"))
1861 interval = 1; /* 1 second = default */
1864 ka.keepalivetime = idle * 1000;
1865 ka.keepaliveinterval = interval * 1000;
1867 if (WSAIoctl(conn->sock,
1878 appendPQExpBuffer(&conn->errorMessage,
1879 libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1885 #endif /* SIO_KEEPALIVE_VALS */
1889 * Set the TCP user timeout.
1892 setTCPUserTimeout(PGconn *conn)
1896 if (conn->pgtcp_user_timeout == NULL)
1899 if (!parse_int_param(conn->pgtcp_user_timeout, &timeout, conn,
1900 "tcp_user_timeout"))
1906 #ifdef TCP_USER_TIMEOUT
1907 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1908 (char *) &timeout, sizeof(timeout)) < 0)
1912 appendPQExpBuffer(&conn->errorMessage,
1913 libpq_gettext("setsockopt(%s) failed: %s\n"),
1915 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1925 * Begin the process of making a connection to the backend.
1927 * Returns 1 if successful, 0 if not.
1931 connectDBStart(PGconn *conn)
1936 if (!conn->options_valid)
1937 goto connect_errReturn;
1940 * Check for bad linking to backend-internal versions of src/common
1941 * functions (see comments in link-canary.c for the reason we need this).
1942 * Nobody but developers should see this message, so we don't bother
1945 if (!pg_link_canary_is_frontend())
1947 printfPQExpBuffer(&conn->errorMessage,
1948 "libpq is incorrectly linked to backend functions\n");
1949 goto connect_errReturn;
1952 /* Ensure our buffers are empty */
1953 conn->inStart = conn->inCursor = conn->inEnd = 0;
1957 * Ensure errorMessage is empty, too. PQconnectPoll will append messages
1958 * to it in the process of scanning for a working server. Thus, if we
1959 * fail to connect to multiple hosts, the final error message will include
1960 * details about each failure.
1962 resetPQExpBuffer(&conn->errorMessage);
1965 if (conn->gssencmode[0] == 'd') /* "disable" */
1966 conn->try_gss = false;
1970 * Set up to try to connect to the first host. (Setting whichhost = -1 is
1971 * a bit of a cheat, but PQconnectPoll will advance it to 0 before
1972 * anything else looks at it.)
1974 conn->whichhost = -1;
1975 conn->try_next_addr = false;
1976 conn->try_next_host = true;
1977 conn->status = CONNECTION_NEEDED;
1980 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1981 * so that it can easily be re-executed if needed again during the
1982 * asynchronous startup process. However, we must run it once here,
1983 * because callers expect a success return from this routine to mean that
1984 * we are in PGRES_POLLING_WRITING connection state.
1986 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1992 * If we managed to open a socket, close it immediately rather than
1993 * waiting till PQfinish. (The application cannot have gotten the socket
1994 * from PQsocket yet, so this doesn't risk breaking anything.)
1996 pqDropConnection(conn, true);
1997 conn->status = CONNECTION_BAD;
2005 * Block and complete a connection.
2007 * Returns 1 on success, 0 on failure.
2010 connectDBComplete(PGconn *conn)
2012 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
2013 time_t finish_time = ((time_t) -1);
2015 int last_whichhost = -2; /* certainly different from whichhost */
2016 struct addrinfo *last_addr_cur = NULL;
2018 if (conn == NULL || conn->status == CONNECTION_BAD)
2022 * Set up a time limit, if connect_timeout isn't zero.
2024 if (conn->connect_timeout != NULL)
2026 if (!parse_int_param(conn->connect_timeout, &timeout, conn,
2029 /* mark the connection as bad to report the parsing failure */
2030 conn->status = CONNECTION_BAD;
2037 * Rounding could cause connection to fail unexpectedly quickly;
2038 * to prevent possibly waiting hardly-at-all, insist on at least
2044 else /* negative means 0 */
2053 * (Re)start the connect_timeout timer if it's active and we are
2054 * considering a different host than we were last time through. If
2055 * we've already succeeded, though, needn't recalculate.
2057 if (flag != PGRES_POLLING_OK &&
2059 (conn->whichhost != last_whichhost ||
2060 conn->addr_cur != last_addr_cur))
2062 finish_time = time(NULL) + timeout;
2063 last_whichhost = conn->whichhost;
2064 last_addr_cur = conn->addr_cur;
2068 * Wait, if necessary. Note that the initial state (just after
2069 * PQconnectStart) is to wait for the socket to select for writing.
2073 case PGRES_POLLING_OK:
2076 * Reset stored error messages since we now have a working
2079 resetPQExpBuffer(&conn->errorMessage);
2080 return 1; /* success! */
2082 case PGRES_POLLING_READING:
2083 ret = pqWaitTimed(1, 0, conn, finish_time);
2086 /* hard failure, eg select() problem, aborts everything */
2087 conn->status = CONNECTION_BAD;
2092 case PGRES_POLLING_WRITING:
2093 ret = pqWaitTimed(0, 1, conn, finish_time);
2096 /* hard failure, eg select() problem, aborts everything */
2097 conn->status = CONNECTION_BAD;
2103 /* Just in case we failed to set it in PQconnectPoll */
2104 conn->status = CONNECTION_BAD;
2108 if (ret == 1) /* connect_timeout elapsed */
2111 * Give up on current server/address, try the next one.
2113 conn->try_next_addr = true;
2114 conn->status = CONNECTION_NEEDED;
2118 * Now try to advance the state machine.
2120 flag = PQconnectPoll(conn);
2125 * This subroutine saves conn->errorMessage, which will be restored back by
2126 * restoreErrorMessage subroutine. Returns false on OOM failure.
2129 saveErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
2131 initPQExpBuffer(savedMessage);
2132 appendPQExpBufferStr(savedMessage,
2133 conn->errorMessage.data);
2134 if (PQExpBufferBroken(savedMessage))
2136 printfPQExpBuffer(&conn->errorMessage,
2137 libpq_gettext("out of memory\n"));
2140 /* Clear whatever is in errorMessage now */
2141 resetPQExpBuffer(&conn->errorMessage);
2146 * Restores saved error messages back to conn->errorMessage, prepending them
2147 * to whatever is in conn->errorMessage already. (This does the right thing
2148 * if anything's been added to conn->errorMessage since saveErrorMessage.)
2151 restoreErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
2153 appendPQExpBufferStr(savedMessage, conn->errorMessage.data);
2154 resetPQExpBuffer(&conn->errorMessage);
2155 appendPQExpBufferStr(&conn->errorMessage, savedMessage->data);
2156 /* If any step above hit OOM, just report that */
2157 if (PQExpBufferBroken(savedMessage) ||
2158 PQExpBufferBroken(&conn->errorMessage))
2159 printfPQExpBuffer(&conn->errorMessage,
2160 libpq_gettext("out of memory\n"));
2161 termPQExpBuffer(savedMessage);
2167 * Poll an asynchronous connection.
2169 * Returns a PostgresPollingStatusType.
2170 * Before calling this function, use select(2) to determine when data
2173 * You must call PQfinish whether or not this fails.
2175 * This function and PQconnectStart are intended to allow connections to be
2176 * made without blocking the execution of your program on remote I/O. However,
2177 * there are a number of caveats:
2179 * o If you call PQtrace, ensure that the stream object into which you trace
2181 * o If you do not supply an IP address for the remote host (i.e. you
2182 * supply a host name instead) then PQconnectStart will block on
2183 * gethostbyname. You will be fine if using Unix sockets (i.e. by
2184 * supplying neither a host name nor a host address).
2185 * o If your backend wants to use Kerberos authentication then you must
2186 * supply both a host name and a host address, otherwise this function
2187 * may block on gethostname.
2191 PostgresPollingStatusType
2192 PQconnectPoll(PGconn *conn)
2194 bool reset_connection_state_machine = false;
2195 bool need_new_connection = false;
2197 char sebuf[PG_STRERROR_R_BUFLEN];
2199 PQExpBufferData savedMessage;
2202 return PGRES_POLLING_FAILED;
2204 /* Get the new data */
2205 switch (conn->status)
2208 * We really shouldn't have been polled in these two cases, but we
2211 case CONNECTION_BAD:
2212 return PGRES_POLLING_FAILED;
2214 return PGRES_POLLING_OK;
2216 /* These are reading states */
2217 case CONNECTION_AWAITING_RESPONSE:
2218 case CONNECTION_AUTH_OK:
2220 /* Load waiting data */
2221 int n = pqReadData(conn);
2226 return PGRES_POLLING_READING;
2231 /* These are writing states, so we just proceed. */
2232 case CONNECTION_STARTED:
2233 case CONNECTION_MADE:
2236 /* We allow pqSetenvPoll to decide whether to proceed. */
2237 case CONNECTION_SETENV:
2240 /* Special cases: proceed without waiting. */
2241 case CONNECTION_SSL_STARTUP:
2242 case CONNECTION_NEEDED:
2243 case CONNECTION_CHECK_WRITABLE:
2244 case CONNECTION_CONSUME:
2245 case CONNECTION_GSS_STARTUP:
2249 appendPQExpBufferStr(&conn->errorMessage,
2251 "invalid connection state, "
2252 "probably indicative of memory corruption\n"
2258 keep_going: /* We will come back to here until there is
2259 * nothing left to do. */
2261 /* Time to advance to next address, or next host if no more addresses? */
2262 if (conn->try_next_addr)
2264 if (conn->addr_cur && conn->addr_cur->ai_next)
2266 conn->addr_cur = conn->addr_cur->ai_next;
2267 reset_connection_state_machine = true;
2270 conn->try_next_host = true;
2271 conn->try_next_addr = false;
2274 /* Time to advance to next connhost[] entry? */
2275 if (conn->try_next_host)
2278 struct addrinfo hint;
2281 char portstr[MAXPGPATH];
2283 if (conn->whichhost + 1 >= conn->nconnhost)
2286 * Oops, no more hosts. An appropriate error message is already
2287 * set up, so just set the right status.
2293 /* Drop any address info for previous host */
2294 release_conn_addrinfo(conn);
2297 * Look up info for the new host. On failure, log the problem in
2298 * conn->errorMessage, then loop around to try the next host. (Note
2299 * we don't clear try_next_host until we've succeeded.)
2301 ch = &conn->connhost[conn->whichhost];
2303 /* Initialize hint structure */
2304 MemSet(&hint, 0, sizeof(hint));
2305 hint.ai_socktype = SOCK_STREAM;
2306 conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2308 /* Figure out the port number we're going to use. */
2309 if (ch->port == NULL || ch->port[0] == '\0')
2310 thisport = DEF_PGPORT;
2313 if (!parse_int_param(ch->port, &thisport, conn, "port"))
2316 if (thisport < 1 || thisport > 65535)
2318 appendPQExpBuffer(&conn->errorMessage,
2319 libpq_gettext("invalid port number: \"%s\"\n"),
2324 snprintf(portstr, sizeof(portstr), "%d", thisport);
2326 /* Use pg_getaddrinfo_all() to resolve the address */
2330 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2332 if (ret || !conn->addrlist)
2334 appendPQExpBuffer(&conn->errorMessage,
2335 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
2336 ch->host, gai_strerror(ret));
2341 case CHT_HOST_ADDRESS:
2342 hint.ai_flags = AI_NUMERICHOST;
2343 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2345 if (ret || !conn->addrlist)
2347 appendPQExpBuffer(&conn->errorMessage,
2348 libpq_gettext("could not parse network address \"%s\": %s\n"),
2349 ch->hostaddr, gai_strerror(ret));
2354 case CHT_UNIX_SOCKET:
2355 #ifdef HAVE_UNIX_SOCKETS
2356 conn->addrlist_family = hint.ai_family = AF_UNIX;
2357 UNIXSOCK_PATH(portstr, thisport, ch->host);
2358 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2360 appendPQExpBuffer(&conn->errorMessage,
2361 libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
2363 (int) (UNIXSOCK_PATH_BUFLEN - 1));
2368 * NULL hostname tells pg_getaddrinfo_all to parse the service
2369 * name as a Unix-domain socket path.
2371 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2373 if (ret || !conn->addrlist)
2375 appendPQExpBuffer(&conn->errorMessage,
2376 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
2377 portstr, gai_strerror(ret));
2386 /* OK, scan this addrlist for a working server address */
2387 conn->addr_cur = conn->addrlist;
2388 reset_connection_state_machine = true;
2389 conn->try_next_host = false;
2392 /* Reset connection state machine? */
2393 if (reset_connection_state_machine)
2396 * (Re) initialize our connection control variables for a set of
2397 * connection attempts to a single server address. These variables
2398 * must persist across individual connection attempts, but we must
2399 * reset them when we start to consider a new server.
2401 conn->pversion = PG_PROTOCOL(3, 0);
2402 conn->send_appname = true;
2404 /* initialize these values based on SSL mode */
2405 conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2406 conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2409 reset_connection_state_machine = false;
2410 need_new_connection = true;
2413 /* Force a new connection (perhaps to the same server as before)? */
2414 if (need_new_connection)
2416 /* Drop any existing connection */
2417 pqDropConnection(conn, true);
2419 /* Reset all state obtained from old server */
2420 pqDropServerData(conn);
2422 /* Drop any PGresult we might have, too */
2423 conn->asyncStatus = PGASYNC_IDLE;
2424 conn->xactStatus = PQTRANS_IDLE;
2425 pqClearAsyncResult(conn);
2427 /* Reset conn->status to put the state machine in the right state */
2428 conn->status = CONNECTION_NEEDED;
2430 need_new_connection = false;
2433 /* Now try to advance the state machine for this connection */
2434 switch (conn->status)
2436 case CONNECTION_NEEDED:
2439 * Try to initiate a connection to one of the addresses
2440 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
2443 * The extra level of braces here is historical. It's not
2444 * worth reindenting this whole switch case to remove 'em.
2447 struct addrinfo *addr_cur = conn->addr_cur;
2448 char host_addr[NI_MAXHOST];
2451 * Advance to next possible host, if we've tried all of
2452 * the addresses for the current host.
2454 if (addr_cur == NULL)
2456 conn->try_next_host = true;
2460 /* Remember current address for possible error msg */
2461 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2462 addr_cur->ai_addrlen);
2463 conn->raddr.salen = addr_cur->ai_addrlen;
2466 if (conn->connip != NULL)
2469 conn->connip = NULL;
2472 getHostaddr(conn, host_addr, NI_MAXHOST);
2473 if (strlen(host_addr) > 0)
2474 conn->connip = strdup(host_addr);
2477 * purposely ignore strdup failure; not a big problem if
2481 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
2482 if (conn->sock == PGINVALID_SOCKET)
2485 * Silently ignore socket() failure if we have more
2486 * addresses to try; this reduces useless chatter in
2487 * cases where the address list includes both IPv4 and
2488 * IPv6 but kernel only accepts one family.
2490 if (addr_cur->ai_next != NULL ||
2491 conn->whichhost + 1 < conn->nconnhost)
2493 conn->try_next_addr = true;
2496 appendPQExpBuffer(&conn->errorMessage,
2497 libpq_gettext("could not create socket: %s\n"),
2498 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2503 * Select socket options: no delay of outgoing data for
2504 * TCP sockets, nonblock mode, close-on-exec. Try the
2505 * next address if any of this fails.
2507 if (!IS_AF_UNIX(addr_cur->ai_family))
2509 if (!connectNoDelay(conn))
2511 /* error message already created */
2512 conn->try_next_addr = true;
2516 if (!pg_set_noblock(conn->sock))
2518 appendPQExpBuffer(&conn->errorMessage,
2519 libpq_gettext("could not set socket to nonblocking mode: %s\n"),
2520 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2521 conn->try_next_addr = true;
2526 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2528 appendPQExpBuffer(&conn->errorMessage,
2529 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
2530 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2531 conn->try_next_addr = true;
2534 #endif /* F_SETFD */
2536 if (!IS_AF_UNIX(addr_cur->ai_family))
2541 int usekeepalives = useKeepalives(conn);
2544 if (usekeepalives < 0)
2546 appendPQExpBufferStr(&conn->errorMessage,
2547 libpq_gettext("keepalives parameter must be an integer\n"));
2550 else if (usekeepalives == 0)
2555 else if (setsockopt(conn->sock,
2556 SOL_SOCKET, SO_KEEPALIVE,
2557 (char *) &on, sizeof(on)) < 0)
2559 appendPQExpBuffer(&conn->errorMessage,
2560 libpq_gettext("setsockopt(%s) failed: %s\n"),
2562 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2565 else if (!setKeepalivesIdle(conn)
2566 || !setKeepalivesInterval(conn)
2567 || !setKeepalivesCount(conn))
2570 #ifdef SIO_KEEPALIVE_VALS
2571 else if (!setKeepalivesWin32(conn))
2573 #endif /* SIO_KEEPALIVE_VALS */
2575 else if (!setTCPUserTimeout(conn))
2580 conn->try_next_addr = true;
2586 * We have three methods of blocking SIGPIPE during
2587 * send() calls to this socket:
2589 * - setsockopt(sock, SO_NOSIGPIPE)
2590 * - send(sock, ..., MSG_NOSIGNAL)
2591 * - setting the signal mask to SIG_IGN during send()
2593 * The third method requires three syscalls per send,
2594 * so we prefer either of the first two, but they are
2595 * less portable. The state is tracked in the following
2596 * members of PGconn:
2598 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2599 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2601 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2602 * and we're done. Otherwise, set sigpipe_flag so that
2603 * we will try MSG_NOSIGNAL on sends. If we get an error
2604 * with MSG_NOSIGNAL, we'll clear that flag and revert to
2608 conn->sigpipe_so = false;
2610 conn->sigpipe_flag = true;
2612 conn->sigpipe_flag = false;
2613 #endif /* MSG_NOSIGNAL */
2617 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2618 (char *) &optval, sizeof(optval)) == 0)
2620 conn->sigpipe_so = true;
2621 conn->sigpipe_flag = false;
2623 #endif /* SO_NOSIGPIPE */
2626 * Start/make connection. This should not block, since we
2627 * are in nonblock mode. If it does, well, too bad.
2629 if (connect(conn->sock, addr_cur->ai_addr,
2630 addr_cur->ai_addrlen) < 0)
2632 if (SOCK_ERRNO == EINPROGRESS ||
2634 SOCK_ERRNO == EWOULDBLOCK ||
2636 SOCK_ERRNO == EINTR)
2639 * This is fine - we're in non-blocking mode, and
2640 * the connection is in progress. Tell caller to
2641 * wait for write-ready on socket.
2643 conn->status = CONNECTION_STARTED;
2644 return PGRES_POLLING_WRITING;
2646 /* otherwise, trouble */
2651 * Hm, we're connected already --- seems the "nonblock
2652 * connection" wasn't. Advance the state machine and
2653 * go do the next stuff.
2655 conn->status = CONNECTION_STARTED;
2660 * This connection failed. Add the error report to
2661 * conn->errorMessage, then try the next address if any.
2663 connectFailureMessage(conn, SOCK_ERRNO);
2664 conn->try_next_addr = true;
2669 case CONNECTION_STARTED:
2671 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2674 * Write ready, since we've made it here, so the connection
2675 * has been made ... or has failed.
2679 * Now check (using getsockopt) that there is not an error
2680 * state waiting for us on the socket.
2683 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2684 (char *) &optval, &optlen) == -1)
2686 appendPQExpBuffer(&conn->errorMessage,
2687 libpq_gettext("could not get socket error status: %s\n"),
2688 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2691 else if (optval != 0)
2694 * When using a nonblocking connect, we will typically see
2695 * connect failures at this point, so provide a friendly
2698 connectFailureMessage(conn, optval);
2701 * Try the next address if any, just as in the case where
2702 * connect() returned failure immediately.
2704 conn->try_next_addr = true;
2708 /* Fill in the client address */
2709 conn->laddr.salen = sizeof(conn->laddr.addr);
2710 if (getsockname(conn->sock,
2711 (struct sockaddr *) &conn->laddr.addr,
2712 &conn->laddr.salen) < 0)
2714 appendPQExpBuffer(&conn->errorMessage,
2715 libpq_gettext("could not get client address from socket: %s\n"),
2716 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2721 * Make sure we can write before advancing to next step.
2723 conn->status = CONNECTION_MADE;
2724 return PGRES_POLLING_WRITING;
2727 case CONNECTION_MADE:
2732 #ifdef HAVE_UNIX_SOCKETS
2735 * Implement requirepeer check, if requested and it's a
2736 * Unix-domain socket.
2738 if (conn->requirepeer && conn->requirepeer[0] &&
2739 IS_AF_UNIX(conn->raddr.addr.ss_family))
2741 char pwdbuf[BUFSIZ];
2742 struct passwd pass_buf;
2743 struct passwd *pass;
2749 if (getpeereid(conn->sock, &uid, &gid) != 0)
2752 * Provide special error message if getpeereid is a
2755 if (errno == ENOSYS)
2756 appendPQExpBufferStr(&conn->errorMessage,
2757 libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2759 appendPQExpBuffer(&conn->errorMessage,
2760 libpq_gettext("could not get peer credentials: %s\n"),
2761 strerror_r(errno, sebuf, sizeof(sebuf)));
2765 passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2769 appendPQExpBuffer(&conn->errorMessage,
2770 libpq_gettext("could not look up local user ID %d: %s\n"),
2772 strerror_r(passerr, sebuf, sizeof(sebuf)));
2774 appendPQExpBuffer(&conn->errorMessage,
2775 libpq_gettext("local user with ID %d does not exist\n"),
2780 if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2782 appendPQExpBuffer(&conn->errorMessage,
2783 libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2784 conn->requirepeer, pass->pw_name);
2788 #endif /* HAVE_UNIX_SOCKETS */
2790 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2792 /* Don't request SSL or GSSAPI over Unix sockets */
2794 conn->allow_ssl_try = false;
2797 conn->try_gss = false;
2804 * If GSSAPI is enabled and we have a credential cache, try to
2805 * set it up before sending startup messages. If it's already
2806 * operating, don't try SSL and instead just build the startup
2809 if (conn->try_gss && !conn->gctx)
2810 conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
2811 if (conn->try_gss && !conn->gctx)
2813 ProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);
2815 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2817 appendPQExpBuffer(&conn->errorMessage,
2818 libpq_gettext("could not send GSSAPI negotiation packet: %s\n"),
2819 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2823 /* Ok, wait for response */
2824 conn->status = CONNECTION_GSS_STARTUP;
2825 return PGRES_POLLING_READING;
2827 else if (!conn->gctx && conn->gssencmode[0] == 'r')
2829 appendPQExpBufferStr(&conn->errorMessage,
2830 libpq_gettext("GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\n"));
2838 * If SSL is enabled and we haven't already got it running,
2839 * request it instead of sending the startup message.
2841 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2847 * Send the SSL request packet.
2849 * Theoretically, this could block, but it really
2850 * shouldn't since we only got here if the socket is
2853 pv = pg_hton32(NEGOTIATE_SSL_CODE);
2854 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2856 appendPQExpBuffer(&conn->errorMessage,
2857 libpq_gettext("could not send SSL negotiation packet: %s\n"),
2858 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2861 /* Ok, wait for response */
2862 conn->status = CONNECTION_SSL_STARTUP;
2863 return PGRES_POLLING_READING;
2865 #endif /* USE_SSL */
2868 * Build the startup packet.
2870 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2871 startpacket = pqBuildStartupPacket3(conn, &packetlen,
2872 EnvironmentOptions);
2874 startpacket = pqBuildStartupPacket2(conn, &packetlen,
2875 EnvironmentOptions);
2879 * will not appendbuffer here, since it's likely to also
2882 printfPQExpBuffer(&conn->errorMessage,
2883 libpq_gettext("out of memory\n"));
2888 * Send the startup packet.
2890 * Theoretically, this could block, but it really shouldn't
2891 * since we only got here if the socket is write-ready.
2893 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2895 appendPQExpBuffer(&conn->errorMessage,
2896 libpq_gettext("could not send startup packet: %s\n"),
2897 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2904 conn->status = CONNECTION_AWAITING_RESPONSE;
2905 return PGRES_POLLING_READING;
2909 * Handle SSL negotiation: wait for postmaster messages and
2910 * respond as necessary.
2912 case CONNECTION_SSL_STARTUP:
2915 PostgresPollingStatusType pollres;
2918 * On first time through, get the postmaster's response to our
2919 * SSL negotiation packet.
2921 if (!conn->ssl_in_use)
2924 * We use pqReadData here since it has the logic to
2925 * distinguish no-data-yet from connection closure. Since
2926 * conn->ssl isn't set, a plain recv() will occur.
2931 rdresult = pqReadData(conn);
2934 /* errorMessage is already filled in */
2939 /* caller failed to wait for data */
2940 return PGRES_POLLING_READING;
2942 if (pqGetc(&SSLok, conn) < 0)
2944 /* should not happen really */
2945 return PGRES_POLLING_READING;
2949 /* mark byte consumed */
2950 conn->inStart = conn->inCursor;
2951 /* Set up global SSL state if required */
2952 if (pqsecure_initialize(conn) != 0)
2955 else if (SSLok == 'N')
2957 /* mark byte consumed */
2958 conn->inStart = conn->inCursor;
2959 /* OK to do without SSL? */
2960 if (conn->sslmode[0] == 'r' || /* "require" */
2961 conn->sslmode[0] == 'v') /* "verify-ca" or
2964 /* Require SSL, but server does not want it */
2965 appendPQExpBufferStr(&conn->errorMessage,
2966 libpq_gettext("server does not support SSL, but SSL was required\n"));
2969 /* Otherwise, proceed with normal startup */
2970 conn->allow_ssl_try = false;
2971 conn->status = CONNECTION_MADE;
2972 return PGRES_POLLING_WRITING;
2974 else if (SSLok == 'E')
2977 * Server failure of some sort, such as failure to
2978 * fork a backend process. We need to process and
2979 * report the error message, which might be formatted
2980 * according to either protocol 2 or protocol 3.
2981 * Rather than duplicate the code for that, we flip
2982 * into AWAITING_RESPONSE state and let the code there
2983 * deal with it. Note we have *not* consumed the "E"
2986 conn->status = CONNECTION_AWAITING_RESPONSE;
2991 appendPQExpBuffer(&conn->errorMessage,
2992 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2999 * Begin or continue the SSL negotiation process.
3001 pollres = pqsecure_open_client(conn);
3002 if (pollres == PGRES_POLLING_OK)
3004 /* SSL handshake done, ready to send startup packet */
3005 conn->status = CONNECTION_MADE;
3006 return PGRES_POLLING_WRITING;
3008 if (pollres == PGRES_POLLING_FAILED)
3011 * Failed ... if sslmode is "prefer" then do a non-SSL
3014 if (conn->sslmode[0] == 'p' /* "prefer" */
3015 && conn->allow_ssl_try /* redundant? */
3016 && !conn->wait_ssl_try) /* redundant? */
3018 /* only retry once */
3019 conn->allow_ssl_try = false;
3020 need_new_connection = true;
3023 /* Else it's a hard failure */
3026 /* Else, return POLLING_READING or POLLING_WRITING status */
3028 #else /* !USE_SSL */
3029 /* can't get here */
3031 #endif /* USE_SSL */
3034 case CONNECTION_GSS_STARTUP:
3037 PostgresPollingStatusType pollres;
3040 * If we haven't yet, get the postmaster's response to our
3041 * negotiation packet
3043 if (conn->try_gss && !conn->gctx)
3046 int rdresult = pqReadData(conn);
3049 /* pqReadData fills in error message */
3051 else if (rdresult == 0)
3052 /* caller failed to wait for data */
3053 return PGRES_POLLING_READING;
3054 if (pqGetc(&gss_ok, conn) < 0)
3055 /* shouldn't happen... */
3056 return PGRES_POLLING_READING;
3061 * Server failure of some sort. Assume it's a
3062 * protocol version support failure, and let's see if
3063 * we can't recover (if it's not, we'll get a better
3064 * error message on retry). Server gets fussy if we
3065 * don't hang up the socket, though.
3067 conn->try_gss = false;
3068 pqDropConnection(conn, true);
3069 conn->status = CONNECTION_NEEDED;
3073 /* mark byte consumed */
3074 conn->inStart = conn->inCursor;
3078 /* Server doesn't want GSSAPI; fall back if we can */
3079 if (conn->gssencmode[0] == 'r')
3081 appendPQExpBufferStr(&conn->errorMessage,
3082 libpq_gettext("server doesn't support GSSAPI encryption, but it was required\n"));
3086 conn->try_gss = false;
3087 conn->status = CONNECTION_MADE;
3088 return PGRES_POLLING_WRITING;
3090 else if (gss_ok != 'G')
3092 appendPQExpBuffer(&conn->errorMessage,
3093 libpq_gettext("received invalid response to GSSAPI negotiation: %c\n"),
3099 /* Begin or continue GSSAPI negotiation */
3100 pollres = pqsecure_open_gss(conn);
3101 if (pollres == PGRES_POLLING_OK)
3103 /* All set for startup packet */
3104 conn->status = CONNECTION_MADE;
3105 return PGRES_POLLING_WRITING;
3107 else if (pollres == PGRES_POLLING_FAILED &&
3108 conn->gssencmode[0] == 'p')
3111 * We failed, but we can retry on "prefer". Have to drop
3112 * the current connection to do so, though.
3114 conn->try_gss = false;
3115 pqDropConnection(conn, true);
3116 conn->status = CONNECTION_NEEDED;
3120 #else /* !ENABLE_GSS */
3123 #endif /* ENABLE_GSS */
3127 * Handle authentication exchange: wait for postmaster messages
3128 * and respond as necessary.
3130 case CONNECTION_AWAITING_RESPONSE:
3139 * Scan the message from current point (note that if we find
3140 * the message is incomplete, we will return without advancing
3141 * inStart, and resume here next time).
3143 conn->inCursor = conn->inStart;
3145 /* Read type byte */
3146 if (pqGetc(&beresp, conn))
3148 /* We'll come back when there is more data */
3149 return PGRES_POLLING_READING;
3153 * Validate message type: we expect only an authentication
3154 * request or an error here. Anything else probably means
3155 * it's not Postgres on the other end at all.
3157 if (!(beresp == 'R' || beresp == 'E'))
3159 appendPQExpBuffer(&conn->errorMessage,
3161 "expected authentication request from "
3162 "server, but received %c\n"),
3167 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3169 /* Read message length word */
3170 if (pqGetInt(&msgLength, 4, conn))
3172 /* We'll come back when there is more data */
3173 return PGRES_POLLING_READING;
3178 /* Set phony message length to disable checks below */
3183 * Try to validate message length before using it.
3184 * Authentication requests can't be very large, although GSS
3185 * auth requests may not be that small. Errors can be a
3186 * little larger, but not huge. If we see a large apparent
3187 * length in an error, it means we're really talking to a
3188 * pre-3.0-protocol server; cope.
3190 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
3192 appendPQExpBuffer(&conn->errorMessage,
3194 "expected authentication request from "
3195 "server, but received %c\n"),
3200 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
3202 /* Handle error from a pre-3.0 server */
3203 conn->inCursor = conn->inStart + 1; /* reread data */
3204 if (pqGets_append(&conn->errorMessage, conn))
3206 /* We'll come back when there is more data */
3207 return PGRES_POLLING_READING;
3209 /* OK, we read the message; mark data consumed */
3210 conn->inStart = conn->inCursor;
3213 * The postmaster typically won't end its message with a
3214 * newline, so add one to conform to libpq conventions.
3216 appendPQExpBufferChar(&conn->errorMessage, '\n');
3219 * If we tried to open the connection in 3.0 protocol,
3220 * fall back to 2.0 protocol.
3222 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3224 conn->pversion = PG_PROTOCOL(2, 0);
3225 need_new_connection = true;
3233 * Can't process if message body isn't all here yet.
3235 * (In protocol 2.0 case, we are assuming messages carry at
3236 * least 4 bytes of data.)
3239 avail = conn->inEnd - conn->inCursor;
3240 if (avail < msgLength)
3243 * Before returning, try to enlarge the input buffer if
3244 * needed to hold the whole message; see notes in
3247 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3250 /* We'll come back when there is more data */
3251 return PGRES_POLLING_READING;
3254 /* Handle errors. */
3257 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3259 if (pqGetErrorNotice3(conn, true))
3261 /* We'll come back when there is more data */
3262 return PGRES_POLLING_READING;
3267 if (pqGets_append(&conn->errorMessage, conn))
3269 /* We'll come back when there is more data */
3270 return PGRES_POLLING_READING;
3273 /* OK, we read the message; mark data consumed */
3274 conn->inStart = conn->inCursor;
3276 /* Check to see if we should mention pgpassfile */
3277 pgpassfileWarning(conn);
3282 * If gssencmode is "prefer" and we're using GSSAPI, retry
3285 if (conn->gssenc && conn->gssencmode[0] == 'p')
3289 /* postmaster expects us to drop the connection */
3290 conn->try_gss = false;
3291 conn->gssenc = false;
3292 gss_delete_sec_context(&minor, &conn->gctx, NULL);
3293 pqDropConnection(conn, true);
3294 conn->status = CONNECTION_NEEDED;
3302 * if sslmode is "allow" and we haven't tried an SSL
3303 * connection already, then retry with an SSL connection
3305 if (conn->sslmode[0] == 'a' /* "allow" */
3306 && !conn->ssl_in_use
3307 && conn->allow_ssl_try
3308 && conn->wait_ssl_try)
3310 /* only retry once */
3311 conn->wait_ssl_try = false;
3312 need_new_connection = true;
3317 * if sslmode is "prefer" and we're in an SSL connection,
3318 * then do a non-SSL retry
3320 if (conn->sslmode[0] == 'p' /* "prefer" */
3322 && conn->allow_ssl_try /* redundant? */
3323 && !conn->wait_ssl_try) /* redundant? */
3325 /* only retry once */
3326 conn->allow_ssl_try = false;
3327 need_new_connection = true;
3335 /* It is an authentication request. */
3336 conn->auth_req_received = true;
3338 /* Get the type of request. */
3339 if (pqGetInt((int *) &areq, 4, conn))
3341 /* We'll come back when there are more data */
3342 return PGRES_POLLING_READING;
3347 * Ensure the password salt is in the input buffer, if it's an
3348 * MD5 request. All the other authentication methods that
3349 * contain extra data in the authentication request are only
3350 * supported in protocol version 3, in which case we already
3351 * read the whole message above.
3353 if (areq == AUTH_REQ_MD5 && PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3357 avail = conn->inEnd - conn->inCursor;
3361 * Before returning, try to enlarge the input buffer
3362 * if needed to hold the whole message; see notes in
3365 if (pqCheckInBufferSpace(conn->inCursor + (size_t) 4,
3368 /* We'll come back when there is more data */
3369 return PGRES_POLLING_READING;
3374 * Process the rest of the authentication request message, and
3375 * respond to it if necessary.
3377 * Note that conn->pghost must be non-NULL if we are going to
3378 * avoid the Kerberos code doing a hostname look-up.
3380 res = pg_fe_sendauth(areq, msgLength, conn);
3381 conn->errorMessage.len = strlen(conn->errorMessage.data);
3383 /* OK, we have processed the message; mark data consumed */
3384 conn->inStart = conn->inCursor;
3386 if (res != STATUS_OK)
3390 * Just make sure that any data sent by pg_fe_sendauth is
3391 * flushed out. Although this theoretically could block, it
3392 * really shouldn't since we don't send large auth responses.
3397 if (areq == AUTH_REQ_OK)
3399 /* We are done with authentication exchange */
3400 conn->status = CONNECTION_AUTH_OK;
3403 * Set asyncStatus so that PQgetResult will think that
3404 * what comes back next is the result of a query. See
3407 conn->asyncStatus = PGASYNC_BUSY;
3410 /* Look to see if we have more data yet. */
3414 case CONNECTION_AUTH_OK:
3417 * Now we expect to hear from the backend. A ReadyForQuery
3418 * message indicates that startup is successful, but we might
3419 * also get an Error message indicating failure. (Notice
3420 * messages indicating nonfatal warnings are also allowed by
3421 * the protocol, as are ParameterStatus and BackendKeyData
3422 * messages.) Easiest way to handle this is to let
3423 * PQgetResult() read the messages. We just have to fake it
3424 * out about the state of the connection, by setting
3425 * asyncStatus = PGASYNC_BUSY (done above).
3429 return PGRES_POLLING_READING;
3431 res = PQgetResult(conn);
3434 * NULL return indicating we have gone to IDLE state is
3439 if (res->resultStatus != PGRES_FATAL_ERROR)
3440 appendPQExpBufferStr(&conn->errorMessage,
3441 libpq_gettext("unexpected message from server during startup\n"));
3442 else if (conn->send_appname &&
3443 (conn->appname || conn->fbappname))
3446 * If we tried to send application_name, check to see
3447 * if the error is about that --- pre-9.0 servers will
3448 * reject it at this stage of the process. If so,
3449 * close the connection and retry without sending
3450 * application_name. We could possibly get a false
3451 * SQLSTATE match here and retry uselessly, but there
3452 * seems no great harm in that; we'll just get the
3453 * same error again if it's unrelated.
3455 const char *sqlstate;
3457 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
3459 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3462 conn->send_appname = false;
3463 need_new_connection = true;
3469 * if the resultStatus is FATAL, then conn->errorMessage
3470 * already has a copy of the error; needn't copy it back.
3471 * But add a newline if it's not there already, since
3472 * postmaster error messages may not have one.
3474 if (conn->errorMessage.len <= 0 ||
3475 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3476 appendPQExpBufferChar(&conn->errorMessage, '\n');
3481 /* Fire up post-connection housekeeping if needed */
3482 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3484 conn->status = CONNECTION_SETENV;
3485 conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
3486 conn->next_eo = EnvironmentOptions;
3487 return PGRES_POLLING_WRITING;
3490 /* Almost there now ... */
3491 conn->status = CONNECTION_CHECK_TARGET;
3495 case CONNECTION_CHECK_TARGET:
3498 * If a read-write connection is required, see if we have one.
3500 * Servers before 7.4 lack the transaction_read_only GUC, but
3501 * by the same token they don't have any read-only mode, so we
3502 * may just skip the test in that case.
3504 if (conn->sversion >= 70400 &&
3505 conn->target_session_attrs != NULL &&
3506 strcmp(conn->target_session_attrs, "read-write") == 0)
3509 * Save existing error messages across the PQsendQuery
3510 * attempt. This is necessary because PQsendQuery is
3511 * going to reset conn->errorMessage, so we would lose
3512 * error messages related to previous hosts we have tried
3513 * and failed to connect to.
3515 if (!saveErrorMessage(conn, &savedMessage))
3518 conn->status = CONNECTION_OK;
3519 if (!PQsendQuery(conn,
3520 "SHOW transaction_read_only"))
3522 restoreErrorMessage(conn, &savedMessage);
3525 conn->status = CONNECTION_CHECK_WRITABLE;
3526 restoreErrorMessage(conn, &savedMessage);
3527 return PGRES_POLLING_READING;
3530 /* We can release the address list now. */
3531 release_conn_addrinfo(conn);
3533 /* We are open for business! */
3534 conn->status = CONNECTION_OK;
3535 return PGRES_POLLING_OK;
3538 case CONNECTION_SETENV:
3541 * Do post-connection housekeeping (only needed in protocol
3544 * We pretend that the connection is OK for the duration of
3547 conn->status = CONNECTION_OK;
3549 switch (pqSetenvPoll(conn))
3551 case PGRES_POLLING_OK: /* Success */
3554 case PGRES_POLLING_READING: /* Still going */
3555 conn->status = CONNECTION_SETENV;
3556 return PGRES_POLLING_READING;
3558 case PGRES_POLLING_WRITING: /* Still going */
3559 conn->status = CONNECTION_SETENV;
3560 return PGRES_POLLING_WRITING;
3566 /* Almost there now ... */
3567 conn->status = CONNECTION_CHECK_TARGET;
3571 case CONNECTION_CONSUME:
3573 conn->status = CONNECTION_OK;
3574 if (!PQconsumeInput(conn))
3579 conn->status = CONNECTION_CONSUME;
3580 return PGRES_POLLING_READING;
3584 * Call PQgetResult() again to consume NULL result.
3586 res = PQgetResult(conn);
3590 conn->status = CONNECTION_CONSUME;
3594 /* We can release the address list now. */
3595 release_conn_addrinfo(conn);
3597 /* We are open for business! */
3598 conn->status = CONNECTION_OK;
3599 return PGRES_POLLING_OK;
3601 case CONNECTION_CHECK_WRITABLE:
3603 const char *displayed_host;
3604 const char *displayed_port;
3606 if (!saveErrorMessage(conn, &savedMessage))
3609 conn->status = CONNECTION_OK;
3610 if (!PQconsumeInput(conn))
3612 restoreErrorMessage(conn, &savedMessage);
3618 conn->status = CONNECTION_CHECK_WRITABLE;
3619 restoreErrorMessage(conn, &savedMessage);
3620 return PGRES_POLLING_READING;
3623 res = PQgetResult(conn);
3624 if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) &&
3625 PQntuples(res) == 1)
3629 val = PQgetvalue(res, 0, 0);
3630 if (strncmp(val, "on", 2) == 0)
3632 /* Not writable; fail this connection. */
3634 restoreErrorMessage(conn, &savedMessage);
3636 /* Append error report to conn->errorMessage. */
3637 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3638 displayed_host = conn->connhost[conn->whichhost].hostaddr;
3640 displayed_host = conn->connhost[conn->whichhost].host;
3641 displayed_port = conn->connhost[conn->whichhost].port;
3642 if (displayed_port == NULL || displayed_port[0] == '\0')
3643 displayed_port = DEF_PGPORT_STR;
3645 appendPQExpBuffer(&conn->errorMessage,
3646 libpq_gettext("could not make a writable "
3647 "connection to server "
3649 displayed_host, displayed_port);
3651 /* Close connection politely. */
3652 conn->status = CONNECTION_OK;
3653 sendTerminateConn(conn);
3656 * Try next host if any, but we don't want to consider
3657 * additional addresses for this host.
3659 conn->try_next_host = true;
3663 /* Session is read-write, so we're good. */
3665 termPQExpBuffer(&savedMessage);
3668 * Finish reading any remaining messages before being
3669 * considered as ready.
3671 conn->status = CONNECTION_CONSUME;
3676 * Something went wrong with "SHOW transaction_read_only". We
3677 * should try next addresses.
3681 restoreErrorMessage(conn, &savedMessage);
3683 /* Append error report to conn->errorMessage. */
3684 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3685 displayed_host = conn->connhost[conn->whichhost].hostaddr;
3687 displayed_host = conn->connhost[conn->whichhost].host;
3688 displayed_port = conn->connhost[conn->whichhost].port;
3689 if (displayed_port == NULL || displayed_port[0] == '\0')
3690 displayed_port = DEF_PGPORT_STR;
3691 appendPQExpBuffer(&conn->errorMessage,
3692 libpq_gettext("test \"SHOW transaction_read_only\" failed "
3693 "on server \"%s:%s\"\n"),
3694 displayed_host, displayed_port);
3696 /* Close connection politely. */
3697 conn->status = CONNECTION_OK;
3698 sendTerminateConn(conn);
3700 /* Try next address */
3701 conn->try_next_addr = true;
3706 appendPQExpBuffer(&conn->errorMessage,
3707 libpq_gettext("invalid connection state %d, "
3708 "probably indicative of memory corruption\n"),
3718 * We used to close the socket at this point, but that makes it awkward
3719 * for those above us if they wish to remove this socket from their own
3720 * records (an fd_set for example). We'll just have this socket closed
3721 * when PQfinish is called (which is compulsory even after an error, since
3722 * the connection structure must be freed).
3724 conn->status = CONNECTION_BAD;
3725 return PGRES_POLLING_FAILED;
3731 * Determine if a server is running and if we can connect to it.
3733 * The argument is a connection that's been started, but not completed.
3736 internal_ping(PGconn *conn)
3738 /* Say "no attempt" if we never got to PQconnectPoll */
3739 if (!conn || !conn->options_valid)
3740 return PQPING_NO_ATTEMPT;
3742 /* Attempt to complete the connection */
3743 if (conn->status != CONNECTION_BAD)
3744 (void) connectDBComplete(conn);
3746 /* Definitely OK if we succeeded */
3747 if (conn->status != CONNECTION_BAD)
3751 * Here begins the interesting part of "ping": determine the cause of the
3752 * failure in sufficient detail to decide what to return. We do not want
3753 * to report that the server is not up just because we didn't have a valid
3754 * password, for example. In fact, any sort of authentication request
3755 * implies the server is up. (We need this check since the libpq side of
3756 * things might have pulled the plug on the connection before getting an
3757 * error as such from the postmaster.)
3759 if (conn->auth_req_received)
3763 * If we failed to get any ERROR response from the postmaster, report
3764 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
3765 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
3766 * out of support. Another corner case where the server could return a
3767 * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
3768 * isn't totally unreasonable for that anyway. We expect that every other
3769 * failure case in a modern server will produce a report with a SQLSTATE.
3771 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
3772 * client-side errors, we should either not store those into
3773 * last_sqlstate, or add an extra flag so we can tell client-side errors
3774 * apart from server-side ones.
3776 if (strlen(conn->last_sqlstate) != 5)
3777 return PQPING_NO_RESPONSE;
3780 * Report PQPING_REJECT if server says it's not accepting connections. (We
3781 * distinguish this case mainly for the convenience of pg_ctl.)
3783 if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
3784 return PQPING_REJECT;
3787 * Any other SQLSTATE can be taken to indicate that the server is up.
3788 * Presumably it didn't like our username, password, or database name; or
3789 * perhaps it had some transient failure, but that should not be taken as
3790 * meaning "it's down".
3798 * - create a PGconn data structure with (as yet) no interesting data
3801 makeEmptyPGconn(void)
3808 * Make sure socket support is up and running.
3812 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
3817 conn = (PGconn *) malloc(sizeof(PGconn));
3826 /* Zero all pointers and booleans */
3827 MemSet(conn, 0, sizeof(PGconn));
3829 /* install default notice hooks */
3830 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
3831 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
3833 conn->status = CONNECTION_BAD;
3834 conn->asyncStatus = PGASYNC_IDLE;
3835 conn->xactStatus = PQTRANS_IDLE;
3836 conn->options_valid = false;
3837 conn->nonblocking = false;
3838 conn->setenv_state = SETENV_STATE_IDLE;
3839 conn->client_encoding = PG_SQL_ASCII;
3840 conn->std_strings = false; /* unless server says differently */
3841 conn->verbosity = PQERRORS_DEFAULT;
3842 conn->show_context = PQSHOW_CONTEXT_ERRORS;
3843 conn->sock = PGINVALID_SOCKET;
3845 conn->try_gss = true;
3849 * We try to send at least 8K at a time, which is the usual size of pipe
3850 * buffers on Unix systems. That way, when we are sending a large amount
3851 * of data, we avoid incurring extra kernel context swaps for partial
3852 * bufferloads. The output buffer is initially made 16K in size, and we
3853 * try to dump it after accumulating 8K.
3855 * With the same goal of minimizing context swaps, the input buffer will
3856 * be enlarged anytime it has less than 8K free, so we initially allocate
3859 conn->inBufSize = 16 * 1024;
3860 conn->inBuffer = (char *) malloc(conn->inBufSize);
3861 conn->outBufSize = 16 * 1024;
3862 conn->outBuffer = (char *) malloc(conn->outBufSize);
3863 conn->rowBufLen = 32;
3864 conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
3865 initPQExpBuffer(&conn->errorMessage);
3866 initPQExpBuffer(&conn->workBuffer);
3868 if (conn->inBuffer == NULL ||
3869 conn->outBuffer == NULL ||
3870 conn->rowBuf == NULL ||
3871 PQExpBufferBroken(&conn->errorMessage) ||
3872 PQExpBufferBroken(&conn->workBuffer))
3874 /* out of memory already :-( */
3884 * - free an idle (closed) PGconn data structure
3886 * NOTE: this should not overlap any functionality with closePGconn().
3887 * Clearing/resetting of transient state belongs there; what we do here is
3888 * release data that is to be held for the life of the PGconn structure.
3889 * If a value ought to be cleared/freed during PQreset(), do it there not here.
3892 freePGconn(PGconn *conn)
3896 /* let any event procs clean up their state data */
3897 for (i = 0; i < conn->nEvents; i++)
3899 PGEventConnDestroy evt;
3902 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
3903 conn->events[i].passThrough);
3904 free(conn->events[i].name);
3907 /* clean up pg_conn_host structures */
3908 if (conn->connhost != NULL)
3910 for (i = 0; i < conn->nconnhost; ++i)
3912 if (conn->connhost[i].host != NULL)
3913 free(conn->connhost[i].host);
3914 if (conn->connhost[i].hostaddr != NULL)
3915 free(conn->connhost[i].hostaddr);
3916 if (conn->connhost[i].port != NULL)
3917 free(conn->connhost[i].port);
3918 if (conn->connhost[i].password != NULL)
3920 explicit_bzero(conn->connhost[i].password, strlen(conn->connhost[i].password));
3921 free(conn->connhost[i].password);
3924 free(conn->connhost);
3927 if (conn->client_encoding_initial)
3928 free(conn->client_encoding_initial);
3933 if (conn->pghostaddr)
3934 free(conn->pghostaddr);
3939 if (conn->connect_timeout)
3940 free(conn->connect_timeout);
3941 if (conn->pgtcp_user_timeout)
3942 free(conn->pgtcp_user_timeout);
3943 if (conn->pgoptions)
3944 free(conn->pgoptions);
3946 free(conn->appname);
3947 if (conn->fbappname)
3948 free(conn->fbappname);
3951 if (conn->replication)
3952 free(conn->replication);
3957 explicit_bzero(conn->pgpass, strlen(conn->pgpass));
3960 if (conn->pgpassfile)
3961 free(conn->pgpassfile);
3962 if (conn->channel_binding)
3963 free(conn->channel_binding);
3964 if (conn->keepalives)
3965 free(conn->keepalives);
3966 if (conn->keepalives_idle)
3967 free(conn->keepalives_idle);
3968 if (conn->keepalives_interval)
3969 free(conn->keepalives_interval);
3970 if (conn->keepalives_count)
3971 free(conn->keepalives_count);
3973 free(conn->sslmode);
3975 free(conn->sslcert);
3978 if (conn->sslrootcert)
3979 free(conn->sslrootcert);
3982 if (conn->sslcompression)
3983 free(conn->sslcompression);
3984 if (conn->requirepeer)
3985 free(conn->requirepeer);
3988 if (conn->gssencmode)
3989 free(conn->gssencmode);
3990 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3991 if (conn->krbsrvname)
3992 free(conn->krbsrvname);
3995 if (conn->gcred != GSS_C_NO_CREDENTIAL)
3999 gss_release_cred(&minor, &conn->gcred);
4000 conn->gcred = GSS_C_NO_CREDENTIAL;
4006 gss_delete_sec_context(&minor, &conn->gctx, GSS_C_NO_BUFFER);
4010 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
4014 /* Note that conn->Pfdebug is not ours to close or free */
4015 if (conn->last_query)
4016 free(conn->last_query);
4017 if (conn->write_err_msg)
4018 free(conn->write_err_msg);
4020 free(conn->inBuffer);
4021 if (conn->outBuffer)
4022 free(conn->outBuffer);
4025 if (conn->target_session_attrs)
4026 free(conn->target_session_attrs);
4027 termPQExpBuffer(&conn->errorMessage);
4028 termPQExpBuffer(&conn->workBuffer);
4038 * release_conn_addrinfo
4039 * - Free any addrinfo list in the PGconn.
4042 release_conn_addrinfo(PGconn *conn)
4046 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
4047 conn->addrlist = NULL;
4048 conn->addr_cur = NULL; /* for safety */
4054 * - Send a terminate message to backend.
4057 sendTerminateConn(PGconn *conn)
4060 * Note that the protocol doesn't allow us to send Terminate messages
4061 * during the startup phase.
4063 if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
4066 * Try to send "close connection" message to backend. Ignore any
4069 pqPutMsgStart('X', false, conn);
4071 (void) pqFlush(conn);
4077 * - properly close a connection to the backend
4079 * This should reset or release all transient state, but NOT the connection
4080 * parameters. On exit, the PGconn should be in condition to start a fresh
4081 * connection with the same parameters (see PQreset()).
4084 closePGconn(PGconn *conn)
4087 * If possible, send Terminate message to close the connection politely.
4089 sendTerminateConn(conn);
4092 * Must reset the blocking status so a possible reconnect will work.
4094 * Don't call PQsetnonblocking() because it will fail if it's unable to
4095 * flush the connection.
4097 conn->nonblocking = false;
4100 * Close the connection, reset all transient state, flush I/O buffers.
4102 pqDropConnection(conn, true);
4103 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
4104 conn->asyncStatus = PGASYNC_IDLE;
4105 conn->xactStatus = PQTRANS_IDLE;
4106 pqClearAsyncResult(conn); /* deallocate result */
4107 resetPQExpBuffer(&conn->errorMessage);
4108 release_conn_addrinfo(conn);
4110 /* Reset all state obtained from server, too */
4111 pqDropServerData(conn);
4115 * PQfinish: properly close a connection to the backend. Also frees
4116 * the PGconn data structure so it shouldn't be re-used after this.
4119 PQfinish(PGconn *conn)
4129 * PQreset: resets the connection to the backend by closing the
4130 * existing connection and creating a new one.
4133 PQreset(PGconn *conn)
4139 if (connectDBStart(conn) && connectDBComplete(conn))
4142 * Notify event procs of successful reset. We treat an event proc
4143 * failure as disabling the connection ... good idea?
4147 for (i = 0; i < conn->nEvents; i++)
4149 PGEventConnReset evt;
4152 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4153 conn->events[i].passThrough))
4155 conn->status = CONNECTION_BAD;
4156 printfPQExpBuffer(&conn->errorMessage,
4157 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4158 conn->events[i].name);
4169 * resets the connection to the backend
4170 * closes the existing connection and makes a new one
4171 * Returns 1 on success, 0 on failure.
4174 PQresetStart(PGconn *conn)
4180 return connectDBStart(conn);
4189 * resets the connection to the backend
4190 * closes the existing connection and makes a new one
4192 PostgresPollingStatusType
4193 PQresetPoll(PGconn *conn)
4197 PostgresPollingStatusType status = PQconnectPoll(conn);
4199 if (status == PGRES_POLLING_OK)
4202 * Notify event procs of successful reset. We treat an event proc
4203 * failure as disabling the connection ... good idea?
4207 for (i = 0; i < conn->nEvents; i++)
4209 PGEventConnReset evt;
4212 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4213 conn->events[i].passThrough))
4215 conn->status = CONNECTION_BAD;
4216 printfPQExpBuffer(&conn->errorMessage,
4217 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4218 conn->events[i].name);
4219 return PGRES_POLLING_FAILED;
4227 return PGRES_POLLING_FAILED;
4231 * PQgetCancel: get a PGcancel structure corresponding to a connection.
4233 * A copy is needed to be able to cancel a running query from a different
4234 * thread. If the same structure is used all structure members would have
4235 * to be individually locked (if the entire structure was locked, it would
4236 * be impossible to cancel a synchronous query because the structure would
4237 * have to stay locked for the duration of the query).
4240 PQgetCancel(PGconn *conn)
4247 if (conn->sock == PGINVALID_SOCKET)
4250 cancel = malloc(sizeof(PGcancel));
4254 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
4255 cancel->be_pid = conn->be_pid;
4256 cancel->be_key = conn->be_key;
4261 /* PQfreeCancel: free a cancel structure */
4263 PQfreeCancel(PGcancel *cancel)
4271 * PQcancel and PQrequestCancel: attempt to request cancellation of the
4272 * current operation.
4274 * The return value is true if the cancel request was successfully
4275 * dispatched, false if not (in which case an error message is available).
4276 * Note: successful dispatch is no guarantee that there will be any effect at
4277 * the backend. The application must read the operation result as usual.
4279 * CAUTION: we want this routine to be safely callable from a signal handler
4280 * (for example, an application might want to call it in a SIGINT handler).
4281 * This means we cannot use any C library routine that might be non-reentrant.
4282 * malloc/free are often non-reentrant, and anything that might call them is
4283 * just as dangerous. We avoid sprintf here for that reason. Building up
4284 * error messages with strcpy/strcat is tedious but should be quite safe.
4285 * We also save/restore errno in case the signal handler support doesn't.
4287 * internal_cancel() is an internal helper function to make code-sharing
4288 * between the two versions of the cancel function possible.
4291 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
4292 char *errbuf, int errbufsize)
4294 int save_errno = SOCK_ERRNO;
4295 pgsocket tmpsock = PGINVALID_SOCKET;
4296 char sebuf[PG_STRERROR_R_BUFLEN];
4301 CancelRequestPacket cp;
4305 * We need to open a temporary connection to the postmaster. Do this with
4306 * only kernel calls.
4308 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4310 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4311 goto cancel_errReturn;
4314 if (connect(tmpsock, (struct sockaddr *) &raddr->addr,
4317 if (SOCK_ERRNO == EINTR)
4318 /* Interrupted system call - we'll just try again */
4320 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4321 goto cancel_errReturn;
4325 * We needn't set nonblocking I/O or NODELAY options here.
4328 /* Create and send the cancel request packet. */
4330 crp.packetlen = pg_hton32((uint32) sizeof(crp));
4331 crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4332 crp.cp.backendPID = pg_hton32(be_pid);
4333 crp.cp.cancelAuthCode = pg_hton32(be_key);
4336 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4338 if (SOCK_ERRNO == EINTR)
4339 /* Interrupted system call - we'll just try again */
4341 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4342 goto cancel_errReturn;
4346 * Wait for the postmaster to close the connection, which indicates that
4347 * it's processed the request. Without this delay, we might issue another
4348 * command only to find that our cancel zaps that command instead of the
4349 * one we thought we were canceling. Note we don't actually expect this
4350 * read to obtain any data, we are just waiting for EOF to be signaled.
4353 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4355 if (SOCK_ERRNO == EINTR)
4356 /* Interrupted system call - we'll just try again */
4358 /* we ignore other error conditions */
4362 closesocket(tmpsock);
4363 SOCK_ERRNO_SET(save_errno);
4369 * Make sure we don't overflow the error buffer. Leave space for the \n at
4370 * the end, and for the terminating zero.
4372 maxlen = errbufsize - strlen(errbuf) - 2;
4375 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
4377 strcat(errbuf, "\n");
4379 if (tmpsock != PGINVALID_SOCKET)
4380 closesocket(tmpsock);
4381 SOCK_ERRNO_SET(save_errno);
4386 * PQcancel: request query cancel
4388 * Returns true if able to send the cancel request, false if not.
4390 * On failure, an error message is stored in *errbuf, which must be of size
4391 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
4395 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
4399 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4403 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
4404 errbuf, errbufsize);
4408 * PQrequestCancel: old, not thread-safe function for requesting query cancel
4410 * Returns true if able to send the cancel request, false if not.
4412 * On failure, the error message is saved in conn->errorMessage; this means
4413 * that this can't be used when there might be other active operations on
4414 * the connection object.
4416 * NOTE: error messages will be cut off at the current size of the
4417 * error message buffer, since we dare not try to expand conn->errorMessage!
4420 PQrequestCancel(PGconn *conn)
4424 /* Check we have an open connection */
4428 if (conn->sock == PGINVALID_SOCKET)
4430 strlcpy(conn->errorMessage.data,
4431 "PQrequestCancel() -- connection is not open\n",
4432 conn->errorMessage.maxlen);
4433 conn->errorMessage.len = strlen(conn->errorMessage.data);
4438 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
4439 conn->errorMessage.data, conn->errorMessage.maxlen);
4442 conn->errorMessage.len = strlen(conn->errorMessage.data);
4449 * pqPacketSend() -- convenience routine to send a message to server.
4451 * pack_type: the single-byte message type code. (Pass zero for startup
4452 * packets, which have no message type code.)
4454 * buf, buf_len: contents of message. The given length includes only what
4455 * is in buf; the message type and message length fields are added here.
4457 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4458 * SIDE_EFFECTS: may block.
4460 * Note: all messages sent with this routine have a length word, whether
4461 * it's protocol 2.0 or 3.0.
4464 pqPacketSend(PGconn *conn, char pack_type,
4465 const void *buf, size_t buf_len)
4467 /* Start the message. */
4468 if (pqPutMsgStart(pack_type, true, conn))
4469 return STATUS_ERROR;
4471 /* Send the message body. */
4472 if (pqPutnchar(buf, buf_len, conn))
4473 return STATUS_ERROR;
4475 /* Finish the message. */
4476 if (pqPutMsgEnd(conn))
4477 return STATUS_ERROR;
4479 /* Flush to ensure backend gets it. */
4481 return STATUS_ERROR;
4488 #define LDAP_URL "ldap://"
4489 #define LDAP_DEF_PORT 389
4490 #define PGLDAP_TIMEOUT 2
4492 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4493 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4499 * Search the LDAP URL passed as first argument, treat the result as a
4500 * string of connection options that are parsed and added to the array of
4501 * options passed as second argument.
4503 * LDAP URLs must conform to RFC 1959 without escape sequences.
4504 * ldap://host:port/dn?attributes?scope?filter?extensions
4507 * 0 if the lookup was successful,
4508 * 1 if the connection to the LDAP server could be established but
4509 * the search was unsuccessful,
4510 * 2 if a connection could not be established, and
4511 * 3 if a fatal error occurred.
4513 * An error message is returned in the third argument for return codes 1 and 3.
4516 ldapServiceLookup(const char *purl, PQconninfoOption *options,
4517 PQExpBuffer errorMessage)
4519 int port = LDAP_DEF_PORT,
4542 char *attrs[2] = {NULL, NULL};
4546 struct berval **values;
4547 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4549 if ((url = strdup(purl)) == NULL)
4551 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4556 * Parse URL components, check for correctness. Basically, url has '\0'
4557 * placed at component boundaries and variables are pointed at each
4561 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
4563 printfPQExpBuffer(errorMessage,
4564 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
4570 hostname = url + strlen(LDAP_URL);
4571 if (*hostname == '/') /* no hostname? */
4572 hostname = DefaultHost; /* the default */
4574 /* dn, "distinguished name" */
4575 p = strchr(url + strlen(LDAP_URL), '/');
4576 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4578 printfPQExpBuffer(errorMessage, libpq_gettext(
4579 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
4583 *p = '\0'; /* terminate hostname */
4587 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4589 printfPQExpBuffer(errorMessage, libpq_gettext(
4590 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
4598 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4600 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4608 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4610 printfPQExpBuffer(errorMessage,
4611 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
4617 if ((p = strchr(filter, '?')) != NULL)
4621 if ((p1 = strchr(hostname, ':')) != NULL)
4628 lport = strtol(portstr, &endptr, 10);
4629 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
4631 printfPQExpBuffer(errorMessage, libpq_gettext(
4632 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
4639 /* Allow only one attribute */
4640 if (strchr(attrs[0], ',') != NULL)
4642 printfPQExpBuffer(errorMessage, libpq_gettext(
4643 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
4649 if (pg_strcasecmp(scopestr, "base") == 0)
4650 scope = LDAP_SCOPE_BASE;
4651 else if (pg_strcasecmp(scopestr, "one") == 0)
4652 scope = LDAP_SCOPE_ONELEVEL;
4653 else if (pg_strcasecmp(scopestr, "sub") == 0)
4654 scope = LDAP_SCOPE_SUBTREE;
4657 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4662 /* initialize LDAP structure */
4663 if ((ld = ldap_init(hostname, port)) == NULL)
4665 printfPQExpBuffer(errorMessage,
4666 libpq_gettext("could not create LDAP structure\n"));
4672 * Perform an explicit anonymous bind.
4674 * LDAP does not require that an anonymous bind is performed explicitly,
4675 * but we want to distinguish between the case where LDAP bind does not
4676 * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
4677 * service control file) and the case where querying the LDAP server fails
4678 * (return 1 to end parsing).
4680 * Unfortunately there is no way of setting a timeout that works for both
4681 * Windows and OpenLDAP.
4684 /* the nonstandard ldap_connect function performs an anonymous bind */
4685 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
4687 /* error or timeout in ldap_connect */
4693 /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
4694 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4701 /* anonymous bind */
4702 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
4704 /* error or network timeout */
4710 /* wait some time for the connection to succeed */
4712 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
4715 /* error or timeout */
4726 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4736 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
4741 printfPQExpBuffer(errorMessage,
4742 libpq_gettext("lookup on LDAP server failed: %s\n"),
4743 ldap_err2string(rc));
4749 /* complain if there was not exactly one result */
4750 if ((rc = ldap_count_entries(ld, res)) != 1)
4752 printfPQExpBuffer(errorMessage,
4753 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
4754 : libpq_gettext("no entry found on LDAP lookup\n"));
4762 if ((entry = ldap_first_entry(ld, res)) == NULL)
4764 /* should never happen */
4765 printfPQExpBuffer(errorMessage,
4766 libpq_gettext("no entry found on LDAP lookup\n"));
4774 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
4776 printfPQExpBuffer(errorMessage,
4777 libpq_gettext("attribute has no values on LDAP lookup\n"));
4787 if (values[0] == NULL)
4789 printfPQExpBuffer(errorMessage,
4790 libpq_gettext("attribute has no values on LDAP lookup\n"));
4791 ldap_value_free_len(values);
4796 /* concatenate values into a single string with newline terminators */
4797 size = 1; /* for the trailing null */
4798 for (i = 0; values[i] != NULL; i++)
4799 size += values[i]->bv_len + 1;
4800 if ((result = malloc(size)) == NULL)
4802 printfPQExpBuffer(errorMessage,
4803 libpq_gettext("out of memory\n"));
4804 ldap_value_free_len(values);
4809 for (i = 0; values[i] != NULL; i++)
4811 memcpy(p, values[i]->bv_val, values[i]->bv_len);
4812 p += values[i]->bv_len;
4817 ldap_value_free_len(values);
4820 /* parse result string */
4821 oldstate = state = 0;
4822 for (p = result; *p != '\0'; ++p)
4826 case 0: /* between entries */
4827 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
4833 case 1: /* in option name */
4834 if (ld_is_sp_tab(*p))
4839 else if (ld_is_nl_cr(*p))
4841 printfPQExpBuffer(errorMessage, libpq_gettext(
4842 "missing \"=\" after \"%s\" in connection info string\n"),
4853 case 2: /* after option name */
4858 else if (!ld_is_sp_tab(*p))
4860 printfPQExpBuffer(errorMessage, libpq_gettext(
4861 "missing \"=\" after \"%s\" in connection info string\n"),
4867 case 3: /* before option value */
4874 else if (ld_is_nl_cr(*p))
4876 optval = optname + strlen(optname); /* empty */
4879 else if (!ld_is_sp_tab(*p))
4885 case 4: /* in unquoted option value */
4886 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
4892 case 5: /* in quoted option value */
4898 else if (*p == '\\')
4903 case 6: /* in quoted option value after escape */
4909 if (state == 0 && oldstate != 0)
4911 found_keyword = false;
4912 for (i = 0; options[i].keyword; i++)
4914 if (strcmp(options[i].keyword, optname) == 0)
4916 if (options[i].val == NULL)
4918 options[i].val = strdup(optval);
4919 if (!options[i].val)
4921 printfPQExpBuffer(errorMessage,
4922 libpq_gettext("out of memory\n"));
4927 found_keyword = true;
4933 printfPQExpBuffer(errorMessage,
4934 libpq_gettext("invalid connection option \"%s\"\n"),
4947 if (state == 5 || state == 6)
4949 printfPQExpBuffer(errorMessage, libpq_gettext(
4950 "unterminated quoted string in connection info string\n"));
4957 #endif /* USE_LDAP */
4959 #define MAXBUFSIZE 256
4962 * parseServiceInfo: if a service name has been given, look it up and absorb
4963 * connection options from it into *options.
4965 * Returns 0 on success, nonzero on failure. On failure, if errorMessage
4966 * isn't null, also store an error message there. (Note: the only reason
4967 * this function and related ones don't dump core on errorMessage == NULL
4968 * is the undocumented fact that printfPQExpBuffer does nothing when passed
4969 * a null PQExpBuffer pointer.)
4972 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
4974 const char *service = conninfo_getval(options, "service");
4975 char serviceFile[MAXPGPATH];
4977 bool group_found = false;
4979 struct stat stat_buf;
4982 * We have to special-case the environment variable PGSERVICE here, since
4983 * this is and should be called before inserting environment defaults for
4984 * other connection options.
4986 if (service == NULL)
4987 service = getenv("PGSERVICE");
4989 /* If no service name given, nothing to do */
4990 if (service == NULL)
4994 * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
4997 if ((env = getenv("PGSERVICEFILE")) != NULL)
4998 strlcpy(serviceFile, env, sizeof(serviceFile));
5001 char homedir[MAXPGPATH];
5003 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5005 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5006 if (stat(serviceFile, &stat_buf) != 0)
5010 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5011 if (group_found || status != 0)
5017 * This could be used by any application so we can't use the binary
5018 * location to find our config files.
5020 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5021 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5022 if (stat(serviceFile, &stat_buf) != 0)
5025 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5032 printfPQExpBuffer(errorMessage,
5033 libpq_gettext("definition of service \"%s\" not found\n"), service);
5041 parseServiceFile(const char *serviceFile,
5042 const char *service,
5043 PQconninfoOption *options,
5044 PQExpBuffer errorMessage,
5050 char buf[MAXBUFSIZE],
5053 f = fopen(serviceFile, "r");
5056 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
5061 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
5067 if (strlen(line) >= sizeof(buf) - 1)
5070 printfPQExpBuffer(errorMessage,
5071 libpq_gettext("line %d too long in service file \"%s\"\n"),
5077 /* ignore whitespace at end of line, especially the newline */
5079 while (len > 0 && isspace((unsigned char) line[len - 1]))
5082 /* ignore leading whitespace too */
5083 while (*line && isspace((unsigned char) line[0]))
5086 /* ignore comments and empty lines */
5087 if (line[0] == '\0' || line[0] == '#')
5090 /* Check for right groupname */
5095 /* group info already read */
5100 if (strncmp(line + 1, service, strlen(service)) == 0 &&
5101 line[strlen(service) + 1] == ']')
5102 *group_found = true;
5104 *group_found = false;
5111 * Finally, we are in the right group and can parse the line
5118 if (strncmp(line, "ldap", 4) == 0)
5120 int rc = ldapServiceLookup(line, options, errorMessage);
5122 /* if rc = 2, go on reading for fallback */
5139 val = strchr(line, '=');
5142 printfPQExpBuffer(errorMessage,
5143 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5151 if (strcmp(key, "service") == 0)
5153 printfPQExpBuffer(errorMessage,
5154 libpq_gettext("nested service specifications not supported in service file \"%s\", line %d\n"),
5162 * Set the parameter --- but don't override any previous
5165 found_keyword = false;
5166 for (i = 0; options[i].keyword; i++)
5168 if (strcmp(options[i].keyword, key) == 0)
5170 if (options[i].val == NULL)
5171 options[i].val = strdup(val);
5172 if (!options[i].val)
5174 printfPQExpBuffer(errorMessage,
5175 libpq_gettext("out of memory\n"));
5179 found_keyword = true;
5186 printfPQExpBuffer(errorMessage,
5187 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5206 * Parse a string like PQconnectdb() would do and return the
5207 * resulting connection options array. NULL is returned on failure.
5208 * The result contains only options specified directly in the string,
5209 * not any possible default values.
5211 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
5212 * string on failure (use PQfreemem to free it). In out-of-memory conditions
5213 * both *errmsg and the result could be NULL.
5215 * NOTE: the returned array is dynamically allocated and should
5216 * be freed when no longer needed via PQconninfoFree().
5219 PQconninfoParse(const char *conninfo, char **errmsg)
5221 PQExpBufferData errorBuf;
5222 PQconninfoOption *connOptions;
5225 *errmsg = NULL; /* default */
5226 initPQExpBuffer(&errorBuf);
5227 if (PQExpBufferDataBroken(errorBuf))
5228 return NULL; /* out of memory already :-( */
5229 connOptions = parse_connection_string(conninfo, &errorBuf, false);
5230 if (connOptions == NULL && errmsg)
5231 *errmsg = errorBuf.data;
5233 termPQExpBuffer(&errorBuf);
5238 * Build a working copy of the constant PQconninfoOptions array.
5240 static PQconninfoOption *
5241 conninfo_init(PQExpBuffer errorMessage)
5243 PQconninfoOption *options;
5244 PQconninfoOption *opt_dest;
5245 const internalPQconninfoOption *cur_opt;
5248 * Get enough memory for all options in PQconninfoOptions, even if some
5249 * end up being filtered out.
5251 options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
5252 if (options == NULL)
5254 printfPQExpBuffer(errorMessage,
5255 libpq_gettext("out of memory\n"));
5260 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
5262 /* Only copy the public part of the struct, not the full internal */
5263 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
5266 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
5272 * Connection string parser
5274 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
5275 * Otherwise, NULL is returned and an error message is left in errorMessage.
5277 * If use_defaults is true, default values are filled in (from a service file,
5278 * environment variables, etc).
5280 static PQconninfoOption *
5281 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
5284 /* Parse as URI if connection string matches URI prefix */
5285 if (uri_prefix_length(connstr) != 0)
5286 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
5288 /* Parse as default otherwise */
5289 return conninfo_parse(connstr, errorMessage, use_defaults);
5293 * Checks if connection string starts with either of the valid URI prefix
5296 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
5298 * XXX this is duplicated in psql/common.c.
5301 uri_prefix_length(const char *connstr)
5303 if (strncmp(connstr, uri_designator,
5304 sizeof(uri_designator) - 1) == 0)
5305 return sizeof(uri_designator) - 1;
5307 if (strncmp(connstr, short_uri_designator,
5308 sizeof(short_uri_designator) - 1) == 0)
5309 return sizeof(short_uri_designator) - 1;
5315 * Recognized connection string either starts with a valid URI prefix or
5316 * contains a "=" in it.
5318 * Must be consistent with parse_connection_string: anything for which this
5319 * returns true should at least look like it's parseable by that routine.
5321 * XXX this is duplicated in psql/common.c
5324 recognized_connection_string(const char *connstr)
5326 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
5330 * Subroutine for parse_connection_string
5332 * Deal with a string containing key=value pairs.
5334 static PQconninfoOption *
5335 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
5343 PQconninfoOption *options;
5345 /* Make a working copy of PQconninfoOptions */
5346 options = conninfo_init(errorMessage);
5347 if (options == NULL)
5350 /* Need a modifiable copy of the input string */
5351 if ((buf = strdup(conninfo)) == NULL)
5353 printfPQExpBuffer(errorMessage,
5354 libpq_gettext("out of memory\n"));
5355 PQconninfoFree(options);
5362 /* Skip blanks before the parameter name */
5363 if (isspace((unsigned char) *cp))
5369 /* Get the parameter name */
5375 if (isspace((unsigned char) *cp))
5380 if (!isspace((unsigned char) *cp))
5389 /* Check that there is a following '=' */
5392 printfPQExpBuffer(errorMessage,
5393 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
5395 PQconninfoFree(options);
5401 /* Skip blanks after the '=' */
5404 if (!isspace((unsigned char) *cp))
5409 /* Get the parameter value */
5417 if (isspace((unsigned char) *cp))
5441 printfPQExpBuffer(errorMessage,
5442 libpq_gettext("unterminated quoted string in connection info string\n"));
5443 PQconninfoFree(options);
5465 * Now that we have the name and the value, store the record.
5467 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5469 PQconninfoFree(options);
5475 /* Done with the modifiable input string */
5479 * Add in defaults if the caller wants that.
5483 if (!conninfo_add_defaults(options, errorMessage))
5485 PQconninfoFree(options);
5494 * Conninfo array parser routine
5496 * If successful, a malloc'd PQconninfoOption array is returned.
5497 * If not successful, NULL is returned and an error message is
5498 * left in errorMessage.
5499 * Defaults are supplied (from a service file, environment variables, etc)
5500 * for unspecified options, but only if use_defaults is true.
5502 * If expand_dbname is non-zero, and the value passed for the first occurrence
5503 * of "dbname" keyword is a connection string (as indicated by
5504 * recognized_connection_string) then parse and process it, overriding any
5505 * previously processed conflicting keywords. Subsequent keywords will take
5506 * precedence, however. In-tree programs generally specify expand_dbname=true,
5507 * so command-line arguments naming a database can use a connection string.
5508 * Some code acquires arbitrary database names from known-literal sources like
5509 * PQdb(), PQconninfoParse() and pg_database.datname. When connecting to such
5510 * a database, in-tree code first wraps the name in a connection string.
5512 static PQconninfoOption *
5513 conninfo_array_parse(const char *const *keywords, const char *const *values,
5514 PQExpBuffer errorMessage, bool use_defaults,
5517 PQconninfoOption *options;
5518 PQconninfoOption *dbname_options = NULL;
5519 PQconninfoOption *option;
5523 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
5524 * actually a recognized connection string.
5526 while (expand_dbname && keywords[i])
5528 const char *pname = keywords[i];
5529 const char *pvalue = values[i];
5531 /* first find "dbname" if any */
5532 if (strcmp(pname, "dbname") == 0 && pvalue)
5535 * If value is a connection string, parse it, but do not use
5536 * defaults here -- those get picked up later. We only want to
5537 * override for those parameters actually passed.
5539 if (recognized_connection_string(pvalue))
5541 dbname_options = parse_connection_string(pvalue, errorMessage, false);
5542 if (dbname_options == NULL)
5550 /* Make a working copy of PQconninfoOptions */
5551 options = conninfo_init(errorMessage);
5552 if (options == NULL)
5554 PQconninfoFree(dbname_options);
5558 /* Parse the keywords/values arrays */
5562 const char *pname = keywords[i];
5563 const char *pvalue = values[i];
5565 if (pvalue != NULL && pvalue[0] != '\0')
5567 /* Search for the param record */
5568 for (option = options; option->keyword != NULL; option++)
5570 if (strcmp(option->keyword, pname) == 0)
5574 /* Check for invalid connection option */
5575 if (option->keyword == NULL)
5577 printfPQExpBuffer(errorMessage,
5578 libpq_gettext("invalid connection option \"%s\"\n"),
5580 PQconninfoFree(options);
5581 PQconninfoFree(dbname_options);
5586 * If we are on the first dbname parameter, and we have a parsed
5587 * connection string, copy those parameters across, overriding any
5588 * existing previous settings.
5590 if (strcmp(pname, "dbname") == 0 && dbname_options)
5592 PQconninfoOption *str_option;
5594 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
5596 if (str_option->val != NULL)
5600 for (k = 0; options[k].keyword; k++)
5602 if (strcmp(options[k].keyword, str_option->keyword) == 0)
5605 free(options[k].val);
5606 options[k].val = strdup(str_option->val);
5607 if (!options[k].val)
5609 printfPQExpBuffer(errorMessage,
5610 libpq_gettext("out of memory\n"));
5611 PQconninfoFree(options);
5612 PQconninfoFree(dbname_options);
5622 * Forget the parsed connection string, so that any subsequent
5623 * dbname parameters will not be expanded.
5625 PQconninfoFree(dbname_options);
5626 dbname_options = NULL;
5631 * Store the value, overriding previous settings
5635 option->val = strdup(pvalue);
5638 printfPQExpBuffer(errorMessage,
5639 libpq_gettext("out of memory\n"));
5640 PQconninfoFree(options);
5641 PQconninfoFree(dbname_options);
5648 PQconninfoFree(dbname_options);
5651 * Add in defaults if the caller wants that.
5655 if (!conninfo_add_defaults(options, errorMessage))
5657 PQconninfoFree(options);
5666 * Add the default values for any unspecified options to the connection
5669 * Defaults are obtained from a service file, environment variables, etc.
5671 * Returns true if successful, otherwise false; errorMessage, if supplied,
5672 * is filled in upon failure. Note that failure to locate a default value
5673 * is not an error condition here --- we just leave the option's value as
5677 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
5679 PQconninfoOption *option;
5683 * If there's a service spec, use it to obtain any not-explicitly-given
5684 * parameters. Ignore error if no error message buffer is passed because
5685 * there is no way to pass back the failure message.
5687 if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
5691 * Get the fallback resources for parameters not specified in the conninfo
5692 * string nor the service.
5694 for (option = options; option->keyword != NULL; option++)
5696 if (option->val != NULL)
5697 continue; /* Value was in conninfo or service */
5700 * Try to get the environment variable fallback
5702 if (option->envvar != NULL)
5704 if ((tmp = getenv(option->envvar)) != NULL)
5706 option->val = strdup(tmp);
5710 printfPQExpBuffer(errorMessage,
5711 libpq_gettext("out of memory\n"));
5719 * Interpret the deprecated PGREQUIRESSL environment variable. Per
5720 * tradition, translate values starting with "1" to sslmode=require,
5721 * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
5722 * PGSSLMODE takes precedence; the opposite was true before v9.3.
5724 if (strcmp(option->keyword, "sslmode") == 0)
5726 const char *requiresslenv = getenv("PGREQUIRESSL");
5728 if (requiresslenv != NULL && requiresslenv[0] == '1')
5730 option->val = strdup("require");
5734 printfPQExpBuffer(errorMessage,
5735 libpq_gettext("out of memory\n"));
5743 * No environment variable specified or the variable isn't set - try
5744 * compiled-in default
5746 if (option->compiled != NULL)
5748 option->val = strdup(option->compiled);
5752 printfPQExpBuffer(errorMessage,
5753 libpq_gettext("out of memory\n"));
5760 * Special handling for "user" option. Note that if pg_fe_getauthname
5761 * fails, we just leave the value as NULL; there's no need for this to
5762 * be an error condition if the caller provides a user name. The only
5763 * reason we do this now at all is so that callers of PQconndefaults
5764 * will see a correct default (barring error, of course).
5766 if (strcmp(option->keyword, "user") == 0)
5768 option->val = pg_fe_getauthname(NULL);
5777 * Subroutine for parse_connection_string
5779 * Deal with a URI connection string.
5781 static PQconninfoOption *
5782 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
5785 PQconninfoOption *options;
5787 /* Make a working copy of PQconninfoOptions */
5788 options = conninfo_init(errorMessage);
5789 if (options == NULL)
5792 if (!conninfo_uri_parse_options(options, uri, errorMessage))
5794 PQconninfoFree(options);
5799 * Add in defaults if the caller wants that.
5803 if (!conninfo_add_defaults(options, errorMessage))
5805 PQconninfoFree(options);
5814 * conninfo_uri_parse_options
5815 * Actual URI parser.
5817 * If successful, returns true while the options array is filled with parsed
5818 * options from the URI.
5819 * If not successful, returns false and fills errorMessage accordingly.
5821 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
5824 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
5826 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
5827 * by literal square brackets. As an extension, we also allow multiple
5828 * netloc[:port] specifications, separated by commas:
5830 * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
5832 * Any of the URI parts might use percent-encoding (%xy).
5835 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
5836 PQExpBuffer errorMessage)
5842 char prevchar = '\0';
5845 bool retval = false;
5846 PQExpBufferData hostbuf;
5847 PQExpBufferData portbuf;
5849 initPQExpBuffer(&hostbuf);
5850 initPQExpBuffer(&portbuf);
5851 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
5853 printfPQExpBuffer(errorMessage,
5854 libpq_gettext("out of memory\n"));
5858 /* need a modifiable copy of the input URI */
5862 printfPQExpBuffer(errorMessage,
5863 libpq_gettext("out of memory\n"));
5868 /* Skip the URI prefix */
5869 prefix_len = uri_prefix_length(uri);
5870 if (prefix_len == 0)
5872 /* Should never happen */
5873 printfPQExpBuffer(errorMessage,
5874 libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
5878 start += prefix_len;
5881 /* Look ahead for possible user credentials designator */
5882 while (*p && *p != '@' && *p != '/')
5887 * Found username/password designator, so URI should be of the form
5888 * "scheme://user[:password]@[netloc]".
5893 while (*p != ':' && *p != '@')
5896 /* Save last char and cut off at end of user name */
5901 !conninfo_storeval(options, "user", user,
5902 errorMessage, false, true))
5905 if (prevchar == ':')
5907 const char *password = p + 1;
5914 !conninfo_storeval(options, "password", password,
5915 errorMessage, false, true))
5919 /* Advance past end of parsed user name or password token */
5925 * No username/password designator found. Reset to start of URI.
5931 * There may be multiple netloc[:port] pairs, each separated from the next
5932 * by a comma. When we initially enter this loop, "p" has been
5933 * incremented past optional URI credential information at this point and
5934 * now points at the "netloc" part of the URI. On subsequent loop
5935 * iterations, "p" has been incremented past the comma separator and now
5936 * points at the start of the next "netloc".
5941 * Look for IPv6 address.
5946 while (*p && *p != ']')
5950 printfPQExpBuffer(errorMessage,
5951 libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
5957 printfPQExpBuffer(errorMessage,
5958 libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
5963 /* Cut off the bracket and advance */
5967 * The address may be followed by a port specifier or a slash or a
5968 * query or a separator comma.
5970 if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
5972 printfPQExpBuffer(errorMessage,
5973 libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
5974 *p, (int) (p - buf + 1), uri);
5980 /* not an IPv6 address: DNS-named or IPv4 netloc */
5984 * Look for port specifier (colon) or end of host specifier
5985 * (slash) or query (question mark) or host separator (comma).
5987 while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
5991 /* Save the hostname terminator before we null it */
5995 appendPQExpBufferStr(&hostbuf, host);
5997 if (prevchar == ':')
5999 const char *port = ++p; /* advance past host terminator */
6001 while (*p && *p != '/' && *p != '?' && *p != ',')
6007 appendPQExpBufferStr(&portbuf, port);
6010 if (prevchar != ',')
6012 ++p; /* advance past comma separator */
6013 appendPQExpBufferChar(&hostbuf, ',');
6014 appendPQExpBufferChar(&portbuf, ',');
6017 /* Save final values for host and port. */
6018 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6020 if (hostbuf.data[0] &&
6021 !conninfo_storeval(options, "host", hostbuf.data,
6022 errorMessage, false, true))
6024 if (portbuf.data[0] &&
6025 !conninfo_storeval(options, "port", portbuf.data,
6026 errorMessage, false, true))
6029 if (prevchar && prevchar != '?')
6031 const char *dbname = ++p; /* advance past host terminator */
6033 /* Look for query parameters */
6034 while (*p && *p != '?')
6041 * Avoid setting dbname to an empty string, as it forces the default
6042 * value (username) and ignores $PGDATABASE, as opposed to not setting
6046 !conninfo_storeval(options, "dbname", dbname,
6047 errorMessage, false, true))
6053 ++p; /* advance past terminator */
6055 if (!conninfo_uri_parse_params(p, options, errorMessage))
6059 /* everything parsed okay */
6063 termPQExpBuffer(&hostbuf);
6064 termPQExpBuffer(&portbuf);
6071 * Connection URI parameters parser routine
6073 * If successful, returns true while connOptions is filled with parsed
6074 * parameters. Otherwise, returns false and fills errorMessage appropriately.
6076 * Destructively modifies 'params' buffer.
6079 conninfo_uri_parse_params(char *params,
6080 PQconninfoOption *connOptions,
6081 PQExpBuffer errorMessage)
6085 char *keyword = params;
6088 bool malloced = false;
6091 * Scan the params string for '=' and '&', marking the end of keyword
6092 * and value respectively.
6098 /* Was there '=' already? */
6101 printfPQExpBuffer(errorMessage,
6102 libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
6106 /* Cut off keyword, advance to value */
6110 else if (*p == '&' || *p == '\0')
6113 * If not at the end, cut off value and advance; leave p
6114 * pointing to start of the next parameter, if any.
6118 /* Was there '=' at all? */
6121 printfPQExpBuffer(errorMessage,
6122 libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
6126 /* Got keyword and value, go process them. */
6130 ++p; /* Advance over all other bytes. */
6133 keyword = conninfo_uri_decode(keyword, errorMessage);
6134 if (keyword == NULL)
6136 /* conninfo_uri_decode already set an error message */
6139 value = conninfo_uri_decode(value, errorMessage);
6142 /* conninfo_uri_decode already set an error message */
6149 * Special keyword handling for improved JDBC compatibility.
6151 if (strcmp(keyword, "ssl") == 0 &&
6152 strcmp(value, "true") == 0)
6158 keyword = "sslmode";
6163 * Store the value if the corresponding option exists; ignore
6164 * otherwise. At this point both keyword and value are not
6167 if (!conninfo_storeval(connOptions, keyword, value,
6168 errorMessage, true, false))
6170 /* Insert generic message if conninfo_storeval didn't give one. */
6171 if (errorMessage->len == 0)
6172 printfPQExpBuffer(errorMessage,
6173 libpq_gettext("invalid URI query parameter: \"%s\"\n"),
6190 /* Proceed to next key=value pair, if any */
6198 * Connection URI decoder routine
6200 * If successful, returns the malloc'd decoded string.
6201 * If not successful, returns NULL and fills errorMessage accordingly.
6203 * The string is decoded by replacing any percent-encoded tokens with
6204 * corresponding characters, while preserving any non-encoded characters. A
6205 * percent-encoded token is a character triplet: a percent sign, followed by a
6206 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
6207 * treated identically.
6210 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
6214 const char *q = str;
6216 buf = malloc(strlen(str) + 1);
6219 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
6228 /* copy and check for NUL terminator */
6229 if (!(*(p++) = *(q++)))
6238 ++q; /* skip the percent sign itself */
6241 * Possible EOL will be caught by the first call to
6242 * get_hexdigit(), so we never dereference an invalid q pointer.
6244 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
6246 printfPQExpBuffer(errorMessage,
6247 libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
6256 printfPQExpBuffer(errorMessage,
6257 libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
6270 * Convert hexadecimal digit character to its integer value.
6272 * If successful, returns true and value is filled with digit's base 16 value.
6273 * If not successful, returns false.
6275 * Lower- and upper-case letters in the range A-F are treated identically.
6278 get_hexdigit(char digit, int *value)
6280 if ('0' <= digit && digit <= '9')
6281 *value = digit - '0';
6282 else if ('A' <= digit && digit <= 'F')
6283 *value = digit - 'A' + 10;
6284 else if ('a' <= digit && digit <= 'f')
6285 *value = digit - 'a' + 10;
6293 * Find an option value corresponding to the keyword in the connOptions array.
6295 * If successful, returns a pointer to the corresponding option's value.
6296 * If not successful, returns NULL.
6299 conninfo_getval(PQconninfoOption *connOptions,
6300 const char *keyword)
6302 PQconninfoOption *option;
6304 option = conninfo_find(connOptions, keyword);
6306 return option ? option->val : NULL;
6310 * Store a (new) value for an option corresponding to the keyword in
6311 * connOptions array.
6313 * If uri_decode is true, the value is URI-decoded. The keyword is always
6314 * assumed to be non URI-encoded.
6316 * If successful, returns a pointer to the corresponding PQconninfoOption,
6317 * which value is replaced with a strdup'd copy of the passed value string.
6318 * The existing value for the option is free'd before replacing, if any.
6320 * If not successful, returns NULL and fills errorMessage accordingly.
6321 * However, if the reason of failure is an invalid keyword being passed and
6322 * ignoreMissing is true, errorMessage will be left untouched.
6324 static PQconninfoOption *
6325 conninfo_storeval(PQconninfoOption *connOptions,
6326 const char *keyword, const char *value,
6327 PQExpBuffer errorMessage, bool ignoreMissing,
6330 PQconninfoOption *option;
6334 * For backwards compatibility, requiressl=1 gets translated to
6335 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
6336 * (which is the default for sslmode).
6338 if (strcmp(keyword, "requiressl") == 0)
6340 keyword = "sslmode";
6341 if (value[0] == '1')
6347 option = conninfo_find(connOptions, keyword);
6351 printfPQExpBuffer(errorMessage,
6352 libpq_gettext("invalid connection option \"%s\"\n"),
6359 value_copy = conninfo_uri_decode(value, errorMessage);
6360 if (value_copy == NULL)
6361 /* conninfo_uri_decode already set an error message */
6366 value_copy = strdup(value);
6367 if (value_copy == NULL)
6369 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
6376 option->val = value_copy;
6382 * Find a PQconninfoOption option corresponding to the keyword in the
6383 * connOptions array.
6385 * If successful, returns a pointer to the corresponding PQconninfoOption
6387 * If not successful, returns NULL.
6389 static PQconninfoOption *
6390 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
6392 PQconninfoOption *option;
6394 for (option = connOptions; option->keyword != NULL; option++)
6396 if (strcmp(option->keyword, keyword) == 0)
6405 * Return the connection options used for the connection
6408 PQconninfo(PGconn *conn)
6410 PQExpBufferData errorBuf;
6411 PQconninfoOption *connOptions;
6416 /* We don't actually report any errors here, but callees want a buffer */
6417 initPQExpBuffer(&errorBuf);
6418 if (PQExpBufferDataBroken(errorBuf))
6419 return NULL; /* out of memory already :-( */
6421 connOptions = conninfo_init(&errorBuf);
6423 if (connOptions != NULL)
6425 const internalPQconninfoOption *option;
6427 for (option = PQconninfoOptions; option->keyword; option++)
6431 if (option->connofs < 0)
6434 connmember = (char **) ((char *) conn + option->connofs);
6437 conninfo_storeval(connOptions, option->keyword, *connmember,
6438 &errorBuf, true, false);
6442 termPQExpBuffer(&errorBuf);
6449 PQconninfoFree(PQconninfoOption *connOptions)
6451 PQconninfoOption *option;
6453 if (connOptions == NULL)
6456 for (option = connOptions; option->keyword != NULL; option++)
6458 if (option->val != NULL)
6465 /* =========== accessor functions for PGconn ========= */
6467 PQdb(const PGconn *conn)
6471 return conn->dbName;
6475 PQuser(const PGconn *conn)
6479 return conn->pguser;
6483 PQpass(const PGconn *conn)
6485 char *password = NULL;
6489 if (conn->connhost != NULL)
6490 password = conn->connhost[conn->whichhost].password;
6491 if (password == NULL)
6492 password = conn->pgpass;
6493 /* Historically we've returned "" not NULL for no password specified */
6494 if (password == NULL)
6500 PQhost(const PGconn *conn)
6505 if (conn->connhost != NULL)
6508 * Return the verbatim host value provided by user, or hostaddr in its
6511 if (conn->connhost[conn->whichhost].host != NULL &&
6512 conn->connhost[conn->whichhost].host[0] != '\0')
6513 return conn->connhost[conn->whichhost].host;
6514 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
6515 conn->connhost[conn->whichhost].hostaddr[0] != '\0')
6516 return conn->connhost[conn->whichhost].hostaddr;
6523 PQhostaddr(const PGconn *conn)
6528 /* Return the parsed IP address */
6529 if (conn->connhost != NULL && conn->connip != NULL)
6530 return conn->connip;
6536 PQport(const PGconn *conn)
6541 if (conn->connhost != NULL)
6542 return conn->connhost[conn->whichhost].port;
6548 PQtty(const PGconn *conn)
6556 PQoptions(const PGconn *conn)
6560 return conn->pgoptions;
6564 PQstatus(const PGconn *conn)
6567 return CONNECTION_BAD;
6568 return conn->status;
6571 PGTransactionStatusType
6572 PQtransactionStatus(const PGconn *conn)
6574 if (!conn || conn->status != CONNECTION_OK)
6575 return PQTRANS_UNKNOWN;
6576 if (conn->asyncStatus != PGASYNC_IDLE)
6577 return PQTRANS_ACTIVE;
6578 return conn->xactStatus;
6582 PQparameterStatus(const PGconn *conn, const char *paramName)
6584 const pgParameterStatus *pstatus;
6586 if (!conn || !paramName)
6588 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
6590 if (strcmp(pstatus->name, paramName) == 0)
6591 return pstatus->value;
6597 PQprotocolVersion(const PGconn *conn)
6601 if (conn->status == CONNECTION_BAD)
6603 return PG_PROTOCOL_MAJOR(conn->pversion);
6607 PQserverVersion(const PGconn *conn)
6611 if (conn->status == CONNECTION_BAD)
6613 return conn->sversion;
6617 PQerrorMessage(const PGconn *conn)
6620 return libpq_gettext("connection pointer is NULL\n");
6622 return conn->errorMessage.data;
6626 * In Windows, socket values are unsigned, and an invalid socket value
6627 * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
6628 * warning). Ideally we would return an unsigned value for PQsocket() on
6629 * Windows, but that would cause the function's return value to differ from
6630 * Unix, so we just return -1 for invalid sockets.
6631 * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
6632 * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
6635 PQsocket(const PGconn *conn)
6639 return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
6643 PQbackendPID(const PGconn *conn)
6645 if (!conn || conn->status != CONNECTION_OK)
6647 return conn->be_pid;
6651 PQconnectionNeedsPassword(const PGconn *conn)
6657 password = PQpass(conn);
6658 if (conn->password_needed &&
6659 (password == NULL || password[0] == '\0'))
6666 PQconnectionUsedPassword(const PGconn *conn)
6670 if (conn->password_needed)
6677 PQclientEncoding(const PGconn *conn)
6679 if (!conn || conn->status != CONNECTION_OK)
6681 return conn->client_encoding;
6685 PQsetClientEncoding(PGconn *conn, const char *encoding)
6688 static const char query[] = "set client_encoding to '%s'";
6692 if (!conn || conn->status != CONNECTION_OK)
6698 /* Resolve special "auto" value from the locale */
6699 if (strcmp(encoding, "auto") == 0)
6700 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
6702 /* check query buffer overflow */
6703 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
6706 /* ok, now send a query */
6707 sprintf(qbuf, query, encoding);
6708 res = PQexec(conn, qbuf);
6712 if (res->resultStatus != PGRES_COMMAND_OK)
6717 * In protocol 2 we have to assume the setting will stick, and adjust
6718 * our state immediately. In protocol 3 and up we can rely on the
6719 * backend to report the parameter value, and we'll change state at
6722 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
6723 pqSaveParameterStatus(conn, "client_encoding", encoding);
6724 status = 0; /* everything is ok */
6731 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
6736 return PQERRORS_DEFAULT;
6737 old = conn->verbosity;
6738 conn->verbosity = verbosity;
6743 PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
6745 PGContextVisibility old;
6748 return PQSHOW_CONTEXT_ERRORS;
6749 old = conn->show_context;
6750 conn->show_context = show_context;
6755 PQtrace(PGconn *conn, FILE *debug_port)
6760 conn->Pfdebug = debug_port;
6764 PQuntrace(PGconn *conn)
6770 fflush(conn->Pfdebug);
6771 conn->Pfdebug = NULL;
6776 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
6778 PQnoticeReceiver old;
6783 old = conn->noticeHooks.noticeRec;
6786 conn->noticeHooks.noticeRec = proc;
6787 conn->noticeHooks.noticeRecArg = arg;
6793 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
6795 PQnoticeProcessor old;
6800 old = conn->noticeHooks.noticeProc;
6803 conn->noticeHooks.noticeProc = proc;
6804 conn->noticeHooks.noticeProcArg = arg;
6810 * The default notice message receiver just gets the standard notice text
6811 * and sends it to the notice processor. This two-level setup exists
6812 * mostly for backwards compatibility; perhaps we should deprecate use of
6813 * PQsetNoticeProcessor?
6816 defaultNoticeReceiver(void *arg, const PGresult *res)
6818 (void) arg; /* not used */
6819 if (res->noticeHooks.noticeProc != NULL)
6820 res->noticeHooks.noticeProc(res->noticeHooks.noticeProcArg,
6821 PQresultErrorMessage(res));
6825 * The default notice message processor just prints the
6826 * message on stderr. Applications can override this if they
6827 * want the messages to go elsewhere (a window, for example).
6828 * Note that simply discarding notices is probably a bad idea.
6831 defaultNoticeProcessor(void *arg, const char *message)
6833 (void) arg; /* not used */
6834 /* Note: we expect the supplied string to end with a newline already. */
6835 fprintf(stderr, "%s", message);
6839 * returns a pointer to the next token or NULL if the current
6840 * token doesn't match
6843 pwdfMatchesString(char *buf, const char *token)
6847 bool bslash = false;
6849 if (buf == NULL || token == NULL)
6853 if (tbuf[0] == '*' && tbuf[1] == ':')
6857 if (*tbuf == '\\' && !bslash)
6862 if (*tbuf == ':' && *ttok == 0 && !bslash)
6878 /* Get a password from the password file. Return value is malloc'd. */
6880 passwordFromFile(const char *hostname, const char *port, const char *dbname,
6881 const char *username, const char *pgpassfile)
6884 struct stat stat_buf;
6886 #define LINELEN NAMEDATALEN*5
6889 if (dbname == NULL || dbname[0] == '\0')
6892 if (username == NULL || username[0] == '\0')
6895 /* 'localhost' matches pghost of '' or the default socket directory */
6896 if (hostname == NULL || hostname[0] == '\0')
6897 hostname = DefaultHost;
6898 else if (is_absolute_path(hostname))
6901 * We should probably use canonicalize_path(), but then we have to
6902 * bring path.c into libpq, and it doesn't seem worth it.
6904 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
6905 hostname = DefaultHost;
6907 if (port == NULL || port[0] == '\0')
6908 port = DEF_PGPORT_STR;
6910 /* If password file cannot be opened, ignore it. */
6911 if (stat(pgpassfile, &stat_buf) != 0)
6915 if (!S_ISREG(stat_buf.st_mode))
6918 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
6923 /* If password file is insecure, alert the user and ignore it. */
6924 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
6927 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
6934 * On Win32, the directory is protected, so we don't have to check the
6939 fp = fopen(pgpassfile, "r");
6943 while (!feof(fp) && !ferror(fp))
6951 if (fgets(buf, sizeof(buf), fp) == NULL)
6954 /* strip trailing newline and carriage return */
6955 len = pg_strip_crlf(buf);
6960 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
6961 (t = pwdfMatchesString(t, port)) == NULL ||
6962 (t = pwdfMatchesString(t, dbname)) == NULL ||
6963 (t = pwdfMatchesString(t, username)) == NULL)
6966 /* Found a match. */
6972 /* Out of memory. XXX: an error message would be nice. */
6973 explicit_bzero(buf, sizeof(buf));
6977 /* De-escape password. */
6978 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
6980 if (*p1 == '\\' && p1[1] != '\0')
6990 explicit_bzero(buf, sizeof(buf));
6998 * If the connection failed due to bad password, we should mention
6999 * if we got the password from the pgpassfile.
7002 pgpassfileWarning(PGconn *conn)
7004 /* If it was 'invalid authorization', add pgpassfile mention */
7005 /* only works with >= 9.0 servers */
7006 if (conn->password_needed &&
7007 conn->connhost[conn->whichhost].password != NULL &&
7010 const char *sqlstate = PQresultErrorField(conn->result,
7013 if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
7014 appendPQExpBuffer(&conn->errorMessage,
7015 libpq_gettext("password retrieved from file \"%s\"\n"),
7022 * Obtain user's home directory, return in given buffer
7024 * On Unix, this actually returns the user's home directory. On Windows
7025 * it returns the PostgreSQL-specific application data folder.
7027 * This is essentially the same as get_home_path(), but we don't use that
7028 * because we don't want to pull path.c into libpq (it pollutes application
7031 * Returns true on success, false on failure to obtain the directory name.
7033 * CAUTION: although in most situations failure is unexpected, there are users
7034 * who like to run applications in a home-directory-less environment. On
7035 * failure, you almost certainly DO NOT want to report an error. Just act as
7036 * though whatever file you were hoping to find in the home directory isn't
7037 * there (which it isn't).
7040 pqGetHomeDirectory(char *buf, int bufsize)
7043 char pwdbuf[BUFSIZ];
7044 struct passwd pwdstr;
7045 struct passwd *pwd = NULL;
7047 (void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
7050 strlcpy(buf, pwd->pw_dir, bufsize);
7053 char tmppath[MAX_PATH];
7055 ZeroMemory(tmppath, sizeof(tmppath));
7056 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7058 snprintf(buf, bufsize, "%s/postgresql", tmppath);
7064 * To keep the API consistent, the locking stubs are always provided, even
7065 * if they are not required.
7069 default_threadlock(int acquire)
7071 #ifdef ENABLE_THREAD_SAFETY
7073 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
7075 static pthread_mutex_t singlethread_lock = NULL;
7076 static long mutex_initlock = 0;
7078 if (singlethread_lock == NULL)
7080 while (InterlockedExchange(&mutex_initlock, 1) == 1)
7081 /* loop, another thread own the lock */ ;
7082 if (singlethread_lock == NULL)
7084 if (pthread_mutex_init(&singlethread_lock, NULL))
7085 PGTHREAD_ERROR("failed to initialize mutex");
7087 InterlockedExchange(&mutex_initlock, 0);
7092 if (pthread_mutex_lock(&singlethread_lock))
7093 PGTHREAD_ERROR("failed to lock mutex");
7097 if (pthread_mutex_unlock(&singlethread_lock))
7098 PGTHREAD_ERROR("failed to unlock mutex");
7104 PQregisterThreadLock(pgthreadlock_t newhandler)
7106 pgthreadlock_t prev = pg_g_threadlock;
7109 pg_g_threadlock = newhandler;
7111 pg_g_threadlock = default_threadlock;