1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2018, 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"
25 #include "libpq-int.h"
27 #include "pg_config_paths.h"
34 #define _WIN32_IE 0x0500
40 #ifdef _MSC_VER /* mstcpip.h is missing on mingw */
44 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #ifdef HAVE_NETINET_TCP_H
48 #include <netinet/tcp.h>
52 #ifdef ENABLE_THREAD_SAFETY
54 #include "pthread-win32.h"
64 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
65 #define LDAP_DEPRECATED 1
67 typedef struct timeval LDAP_TIMEVAL;
69 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
70 PQExpBuffer errorMessage);
73 #include "common/ip.h"
74 #include "common/link-canary.h"
75 #include "common/scram-common.h"
76 #include "mb/pg_wchar.h"
77 #include "port/pg_bswap.h"
81 #define PGPASSFILE ".pgpass"
83 #define PGPASSFILE "pgpass.conf"
87 * Pre-9.0 servers will return this SQLSTATE if asked to set
88 * application_name in a startup packet. We hard-wire the value rather
89 * than looking into errcodes.h since it reflects historical behavior
90 * rather than that of the current code.
92 #define ERRCODE_APPNAME_UNKNOWN "42704"
94 /* This is part of the protocol so just define it */
95 #define ERRCODE_INVALID_PASSWORD "28P01"
97 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
100 * Cope with the various platform-specific ways to spell TCP keepalive socket
101 * options. This doesn't cover Windows, which as usual does its own thing.
103 #if defined(TCP_KEEPIDLE)
104 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
105 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
106 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
107 #elif defined(TCP_KEEPALIVE_THRESHOLD)
108 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
109 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
110 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
111 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
112 /* TCP_KEEPALIVE is the name of this option on macOS */
113 /* Caution: Solaris has this symbol but it means something different */
114 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
115 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
119 * fall back options if they are not specified by arguments or defined
120 * by environment variables
122 #define DefaultHost "localhost"
123 #define DefaultTty ""
124 #define DefaultOption ""
125 #define DefaultAuthtype ""
126 #define DefaultTargetSessionAttrs "any"
128 #define DefaultSSLMode "prefer"
130 #define DefaultSSLMode "disable"
134 * Definition of the conninfo parameters and their fallback resources.
136 * If Environment-Var and Compiled-in are specified as NULL, no
137 * fallback is available. If after all no value can be determined
138 * for an option, an error is returned.
140 * The value for the username is treated specially in conninfo_add_defaults.
141 * If the value is not obtained any other way, the username is determined
142 * by pg_fe_getauthname().
144 * The Label and Disp-Char entries are provided for applications that
145 * want to use PQconndefaults() to create a generic database connection
146 * dialog. Disp-Char is defined as follows:
147 * "" Normal input field
148 * "*" Password field - hide value
149 * "D" Debug option - don't show by default
151 * PQconninfoOptions[] is a constant static array that we use to initialize
152 * a dynamically allocated working copy. All the "val" fields in
153 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
154 * fields point to malloc'd strings that should be freed when the working
155 * array is freed (see PQconninfoFree).
157 * The first part of each struct is identical to the one in libpq-fe.h,
158 * which is required since we memcpy() data between the two!
161 typedef struct _internalPQconninfoOption
163 char *keyword; /* The keyword of the option */
164 char *envvar; /* Fallback environment variable name */
165 char *compiled; /* Fallback compiled in default value */
166 char *val; /* Option's current value, or NULL */
167 char *label; /* Label for field in connect dialog */
168 char *dispchar; /* Indicates how to display this field in a
169 * connect dialog. Values are: "" Display
170 * entered value as is "*" Password field -
171 * hide value "D" Debug option - don't show
173 int dispsize; /* Field size in characters for dialog */
175 * Anything above this comment must be synchronized with
176 * PQconninfoOption in libpq-fe.h, since we memcpy() data
180 off_t connofs; /* Offset into PGconn struct, -1 if not there */
181 } internalPQconninfoOption;
183 static const internalPQconninfoOption PQconninfoOptions[] = {
185 * "authtype" is no longer used, so mark it "don't show". We keep it in
186 * the array so as not to reject conninfo strings from old apps that might
187 * still try to set it.
189 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
190 "Database-Authtype", "D", 20, -1},
192 {"service", "PGSERVICE", NULL, NULL,
193 "Database-Service", "", 20, -1},
195 {"user", "PGUSER", NULL, NULL,
196 "Database-User", "", 20,
197 offsetof(struct pg_conn, pguser)},
199 {"password", "PGPASSWORD", NULL, NULL,
200 "Database-Password", "*", 20,
201 offsetof(struct pg_conn, pgpass)},
203 {"passfile", "PGPASSFILE", NULL, NULL,
204 "Database-Password-File", "", 64,
205 offsetof(struct pg_conn, pgpassfile)},
207 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
208 "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
209 offsetof(struct pg_conn, connect_timeout)},
211 {"dbname", "PGDATABASE", NULL, NULL,
212 "Database-Name", "", 20,
213 offsetof(struct pg_conn, dbName)},
215 {"host", "PGHOST", NULL, NULL,
216 "Database-Host", "", 40,
217 offsetof(struct pg_conn, pghost)},
219 {"hostaddr", "PGHOSTADDR", NULL, NULL,
220 "Database-Host-IP-Address", "", 45,
221 offsetof(struct pg_conn, pghostaddr)},
223 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
224 "Database-Port", "", 6,
225 offsetof(struct pg_conn, pgport)},
227 {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
228 "Client-Encoding", "", 10,
229 offsetof(struct pg_conn, client_encoding_initial)},
232 * "tty" is no longer used either, but keep it present for backwards
235 {"tty", "PGTTY", DefaultTty, NULL,
236 "Backend-Debug-TTY", "D", 40,
237 offsetof(struct pg_conn, pgtty)},
239 {"options", "PGOPTIONS", DefaultOption, NULL,
240 "Backend-Options", "", 40,
241 offsetof(struct pg_conn, pgoptions)},
243 {"application_name", "PGAPPNAME", NULL, NULL,
244 "Application-Name", "", 64,
245 offsetof(struct pg_conn, appname)},
247 {"fallback_application_name", NULL, NULL, NULL,
248 "Fallback-Application-Name", "", 64,
249 offsetof(struct pg_conn, fbappname)},
251 {"keepalives", NULL, NULL, NULL,
252 "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
253 offsetof(struct pg_conn, keepalives)},
255 {"keepalives_idle", NULL, NULL, NULL,
256 "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
257 offsetof(struct pg_conn, keepalives_idle)},
259 {"keepalives_interval", NULL, NULL, NULL,
260 "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
261 offsetof(struct pg_conn, keepalives_interval)},
263 {"keepalives_count", NULL, NULL, NULL,
264 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
265 offsetof(struct pg_conn, keepalives_count)},
268 * ssl options are allowed even without client SSL support because the
269 * client can still handle SSL modes "disable" and "allow". Other
270 * parameters have no effect on non-SSL connections, so there is no reason
271 * to exclude them since none of them are mandatory.
273 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
274 "SSL-Mode", "", 12, /* sizeof("verify-full") == 12 */
275 offsetof(struct pg_conn, sslmode)},
277 {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
278 "SSL-Compression", "", 1,
279 offsetof(struct pg_conn, sslcompression)},
281 {"sslcert", "PGSSLCERT", NULL, NULL,
282 "SSL-Client-Cert", "", 64,
283 offsetof(struct pg_conn, sslcert)},
285 {"sslkey", "PGSSLKEY", NULL, NULL,
286 "SSL-Client-Key", "", 64,
287 offsetof(struct pg_conn, sslkey)},
289 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
290 "SSL-Root-Certificate", "", 64,
291 offsetof(struct pg_conn, sslrootcert)},
293 {"sslcrl", "PGSSLCRL", NULL, NULL,
294 "SSL-Revocation-List", "", 64,
295 offsetof(struct pg_conn, sslcrl)},
297 {"requirepeer", "PGREQUIREPEER", NULL, NULL,
298 "Require-Peer", "", 10,
299 offsetof(struct pg_conn, requirepeer)},
301 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
302 /* Kerberos and GSSAPI authentication support specifying the service name */
303 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
304 "Kerberos-service-name", "", 20,
305 offsetof(struct pg_conn, krbsrvname)},
308 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
311 * GSSAPI and SSPI both enabled, give a way to override which is used by
314 {"gsslib", "PGGSSLIB", NULL, NULL,
315 "GSS-library", "", 7, /* sizeof("gssapi") = 7 */
316 offsetof(struct pg_conn, gsslib)},
319 {"replication", NULL, NULL, NULL,
320 "Replication", "D", 5,
321 offsetof(struct pg_conn, replication)},
323 {"target_session_attrs", "PGTARGETSESSIONATTRS",
324 DefaultTargetSessionAttrs, NULL,
325 "Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */
326 offsetof(struct pg_conn, target_session_attrs)},
328 /* Terminating entry --- MUST BE LAST */
329 {NULL, NULL, NULL, NULL,
333 static const PQEnvironmentOption EnvironmentOptions[] =
335 /* common user-interface settings */
337 "PGDATESTYLE", "datestyle"
342 /* internal performance-related settings */
351 /* The connection URI must start with either of the following designators: */
352 static const char uri_designator[] = "postgresql://";
353 static const char short_uri_designator[] = "postgres://";
355 static bool connectOptions1(PGconn *conn, const char *conninfo);
356 static bool connectOptions2(PGconn *conn);
357 static int connectDBStart(PGconn *conn);
358 static int connectDBComplete(PGconn *conn);
359 static PGPing internal_ping(PGconn *conn);
360 static PGconn *makeEmptyPGconn(void);
361 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
362 static void freePGconn(PGconn *conn);
363 static void closePGconn(PGconn *conn);
364 static void release_conn_addrinfo(PGconn *conn);
365 static void sendTerminateConn(PGconn *conn);
366 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
367 static PQconninfoOption *parse_connection_string(const char *conninfo,
368 PQExpBuffer errorMessage, bool use_defaults);
369 static int uri_prefix_length(const char *connstr);
370 static bool recognized_connection_string(const char *connstr);
371 static PQconninfoOption *conninfo_parse(const char *conninfo,
372 PQExpBuffer errorMessage, bool use_defaults);
373 static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
374 const char *const *values, PQExpBuffer errorMessage,
375 bool use_defaults, int expand_dbname);
376 static bool conninfo_add_defaults(PQconninfoOption *options,
377 PQExpBuffer errorMessage);
378 static PQconninfoOption *conninfo_uri_parse(const char *uri,
379 PQExpBuffer errorMessage, bool use_defaults);
380 static bool conninfo_uri_parse_options(PQconninfoOption *options,
381 const char *uri, PQExpBuffer errorMessage);
382 static bool conninfo_uri_parse_params(char *params,
383 PQconninfoOption *connOptions,
384 PQExpBuffer errorMessage);
385 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
386 static bool get_hexdigit(char digit, int *value);
387 static const char *conninfo_getval(PQconninfoOption *connOptions,
388 const char *keyword);
389 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
390 const char *keyword, const char *value,
391 PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
392 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
393 const char *keyword);
394 static void defaultNoticeReceiver(void *arg, const PGresult *res);
395 static void defaultNoticeProcessor(void *arg, const char *message);
396 static int parseServiceInfo(PQconninfoOption *options,
397 PQExpBuffer errorMessage);
398 static int parseServiceFile(const char *serviceFile,
400 PQconninfoOption *options,
401 PQExpBuffer errorMessage,
403 static char *pwdfMatchesString(char *buf, const char *token);
404 static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
405 const char *username, const char *pgpassfile);
406 static void pgpassfileWarning(PGconn *conn);
407 static void default_threadlock(int acquire);
410 /* global variable because fe-auth.c needs to access it */
411 pgthreadlock_t pg_g_threadlock = default_threadlock;
417 * Close any physical connection to the server, and reset associated
418 * state inside the connection object. We don't release state that
419 * would be needed to reconnect, though, nor local state that might still
422 * We can always flush the output buffer, since there's no longer any hope
423 * of sending that data. However, unprocessed input data might still be
424 * valuable, so the caller must tell us whether to flush that or not.
427 pqDropConnection(PGconn *conn, bool flushInput)
429 /* Drop any SSL state */
430 pqsecure_close(conn);
432 /* Close the socket itself */
433 if (conn->sock != PGINVALID_SOCKET)
434 closesocket(conn->sock);
435 conn->sock = PGINVALID_SOCKET;
437 /* Optionally discard any unread data */
439 conn->inStart = conn->inCursor = conn->inEnd = 0;
441 /* Always discard any unsent data */
444 /* Free authentication state */
450 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
452 gss_release_name(&min_s, &conn->gtarg_nam);
456 if (conn->sspitarget)
458 free(conn->sspitarget);
459 conn->sspitarget = NULL;
463 FreeCredentialsHandle(conn->sspicred);
464 free(conn->sspicred);
465 conn->sspicred = NULL;
469 DeleteSecurityContext(conn->sspictx);
471 conn->sspictx = NULL;
475 if (conn->sasl_state)
478 * XXX: if support for more authentication mechanisms is added, this
479 * needs to call the right 'free' function.
481 pg_fe_scram_free(conn->sasl_state);
482 conn->sasl_state = NULL;
490 * Clear all connection state data that was received from (or deduced about)
491 * the server. This is essential to do between connection attempts to
492 * different servers, else we may incorrectly hold over some data from the
495 * It would be better to merge this into pqDropConnection, perhaps, but
496 * right now we cannot because that function is called immediately on
497 * detection of connection loss (cf. pqReadData, for instance). This data
498 * should be kept until we are actually starting a new connection.
501 pqDropServerData(PGconn *conn)
504 pgParameterStatus *pstatus;
506 /* Forget pending notifies */
507 notify = conn->notifyHead;
508 while (notify != NULL)
510 PGnotify *prev = notify;
512 notify = notify->next;
515 conn->notifyHead = conn->notifyTail = NULL;
517 /* Reset ParameterStatus data, as well as variables deduced from it */
518 pstatus = conn->pstatus;
519 while (pstatus != NULL)
521 pgParameterStatus *prev = pstatus;
523 pstatus = pstatus->next;
526 conn->pstatus = NULL;
527 conn->client_encoding = PG_SQL_ASCII;
528 conn->std_strings = false;
531 /* Drop large-object lookup data */
533 free(conn->lobjfuncs);
534 conn->lobjfuncs = NULL;
536 /* Reset assorted other per-connection state */
537 conn->last_sqlstate[0] = '\0';
538 conn->auth_req_received = false;
539 conn->password_needed = false;
546 * Connecting to a Database
548 * There are now six different ways a user of this API can connect to the
549 * database. Two are not recommended for use in new code, because of their
550 * lack of extensibility with respect to the passing of options to the
551 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
554 * If it is desired to connect in a synchronous (blocking) manner, use the
555 * function PQconnectdb or PQconnectdbParams. The former accepts a string of
556 * option = value pairs (or a URI) which must be parsed; the latter takes two
557 * NULL terminated arrays instead.
559 * To connect in an asynchronous (non-blocking) manner, use the functions
560 * PQconnectStart or PQconnectStartParams (which differ in the same way as
561 * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
563 * Internally, the static functions connectDBStart, connectDBComplete
564 * are part of the connection procedure.
570 * establishes a connection to a postgres backend through the postmaster
571 * using connection information in two arrays.
573 * The keywords array is defined as
575 * const char *params[] = {"option1", "option2", NULL}
577 * The values array is defined as
579 * const char *values[] = {"value1", "value2", NULL}
581 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
582 * if a memory allocation failed.
583 * If the status field of the connection returned is CONNECTION_BAD,
584 * then some fields may be null'ed out instead of having valid values.
586 * You should call PQfinish (if conn is not NULL) regardless of whether this
590 PQconnectdbParams(const char *const *keywords,
591 const char *const *values,
594 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
596 if (conn && conn->status != CONNECTION_BAD)
597 (void) connectDBComplete(conn);
606 * check server status, accepting parameters identical to PQconnectdbParams
609 PQpingParams(const char *const *keywords,
610 const char *const *values,
613 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
616 ret = internal_ping(conn);
625 * establishes a connection to a postgres backend through the postmaster
626 * using connection information in a string.
628 * The conninfo string is either a whitespace-separated list of
632 * definitions or a URI (refer to the documentation for details.) Value
633 * might be a single value containing no whitespaces or a single quoted
634 * string. If a single quote should appear anywhere in the value, it must be
635 * escaped with a backslash like \'
637 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
638 * if a memory allocation failed.
639 * If the status field of the connection returned is CONNECTION_BAD,
640 * then some fields may be null'ed out instead of having valid values.
642 * You should call PQfinish (if conn is not NULL) regardless of whether this
646 PQconnectdb(const char *conninfo)
648 PGconn *conn = PQconnectStart(conninfo);
650 if (conn && conn->status != CONNECTION_BAD)
651 (void) connectDBComplete(conn);
659 * check server status, accepting parameters identical to PQconnectdb
662 PQping(const char *conninfo)
664 PGconn *conn = PQconnectStart(conninfo);
667 ret = internal_ping(conn);
674 * PQconnectStartParams
676 * Begins the establishment of a connection to a postgres backend through the
677 * postmaster using connection information in a struct.
679 * See comment for PQconnectdbParams for the definition of the string format.
681 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
682 * you should not attempt to proceed with this connection. If the status
683 * field of the connection returned is CONNECTION_BAD, an error has
684 * occurred. In this case you should call PQfinish on the result, (perhaps
685 * inspecting the error message first). Other fields of the structure may not
686 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
687 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
690 * See PQconnectPoll for more info.
693 PQconnectStartParams(const char *const *keywords,
694 const char *const *values,
698 PQconninfoOption *connOptions;
701 * Allocate memory for the conn structure
703 conn = makeEmptyPGconn();
708 * Parse the conninfo arrays
710 connOptions = conninfo_array_parse(keywords, values,
712 true, expand_dbname);
713 if (connOptions == NULL)
715 conn->status = CONNECTION_BAD;
716 /* errorMessage is already set */
721 * Move option values into conn structure
723 if (!fillPGconn(conn, connOptions))
725 PQconninfoFree(connOptions);
730 * Free the option info - all is in conn now
732 PQconninfoFree(connOptions);
735 * Compute derived options
737 if (!connectOptions2(conn))
741 * Connect to the database
743 if (!connectDBStart(conn))
745 /* Just in case we failed to set it in connectDBStart */
746 conn->status = CONNECTION_BAD;
755 * Begins the establishment of a connection to a postgres backend through the
756 * postmaster using connection information in a string.
758 * See comment for PQconnectdb for the definition of the string format.
760 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
761 * you should not attempt to proceed with this connection. If the status
762 * field of the connection returned is CONNECTION_BAD, an error has
763 * occurred. In this case you should call PQfinish on the result, (perhaps
764 * inspecting the error message first). Other fields of the structure may not
765 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
766 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
769 * See PQconnectPoll for more info.
772 PQconnectStart(const char *conninfo)
777 * Allocate memory for the conn structure
779 conn = makeEmptyPGconn();
784 * Parse the conninfo string
786 if (!connectOptions1(conn, conninfo))
790 * Compute derived options
792 if (!connectOptions2(conn))
796 * Connect to the database
798 if (!connectDBStart(conn))
800 /* Just in case we failed to set it in connectDBStart */
801 conn->status = CONNECTION_BAD;
808 * Move option values into conn structure
810 * Don't put anything cute here --- intelligence should be in
811 * connectOptions2 ...
813 * Returns true on success. On failure, returns false and sets error message.
816 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
818 const internalPQconninfoOption *option;
820 for (option = PQconninfoOptions; option->keyword; option++)
822 if (option->connofs >= 0)
824 const char *tmp = conninfo_getval(connOptions, option->keyword);
828 char **connmember = (char **) ((char *) conn + option->connofs);
832 *connmember = strdup(tmp);
833 if (*connmember == NULL)
835 printfPQExpBuffer(&conn->errorMessage,
836 libpq_gettext("out of memory\n"));
849 * Internal subroutine to set up connection parameters given an already-
850 * created PGconn and a conninfo string. Derived settings should be
851 * processed by calling connectOptions2 next. (We split them because
852 * PQsetdbLogin overrides defaults in between.)
854 * Returns true if OK, false if trouble (in which case errorMessage is set
855 * and so is conn->status).
858 connectOptions1(PGconn *conn, const char *conninfo)
860 PQconninfoOption *connOptions;
863 * Parse the conninfo string
865 connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
866 if (connOptions == NULL)
868 conn->status = CONNECTION_BAD;
869 /* errorMessage is already set */
874 * Move option values into conn structure
876 if (!fillPGconn(conn, connOptions))
878 conn->status = CONNECTION_BAD;
879 PQconninfoFree(connOptions);
884 * Free the option info - all is in conn now
886 PQconninfoFree(connOptions);
892 * Count the number of elements in a simple comma-separated list.
895 count_comma_separated_elems(const char *input)
900 for (; *input != '\0'; input++)
910 * Parse a simple comma-separated list.
912 * On each call, returns a malloc'd copy of the next element, and sets *more
913 * to indicate whether there are any more elements in the list after this,
914 * and updates *startptr to point to the next element, if any.
916 * On out of memory, returns NULL.
919 parse_comma_separated_list(char **startptr, bool *more)
927 * Search for the end of the current element; a comma or end-of-string
928 * acts as a terminator.
931 while (*e != '\0' && *e != ',')
936 p = (char *) malloc(sizeof(char) * (len + 1));
950 * Compute derived connection options after absorbing all user-supplied info.
952 * Returns true if OK, false if trouble (in which case errorMessage is set
953 * and so is conn->status).
956 connectOptions2(PGconn *conn)
961 * Allocate memory for details about each host to which we might possibly
962 * try to connect. For that, count the number of elements in the hostaddr
963 * or host options. If neither is given, assume one host.
966 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
967 conn->nconnhost = count_comma_separated_elems(conn->pghostaddr);
968 else if (conn->pghost && conn->pghost[0] != '\0')
969 conn->nconnhost = count_comma_separated_elems(conn->pghost);
972 conn->connhost = (pg_conn_host *)
973 calloc(conn->nconnhost, sizeof(pg_conn_host));
974 if (conn->connhost == NULL)
978 * We now have one pg_conn_host structure per possible host. Fill in the
979 * host and hostaddr fields for each, by splitting the parameter strings.
981 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
983 char *s = conn->pghostaddr;
986 for (i = 0; i < conn->nconnhost && more; i++)
988 conn->connhost[i].hostaddr = parse_comma_separated_list(&s, &more);
989 if (conn->connhost[i].hostaddr == NULL)
994 * If hostaddr was given, the array was allocated according to the
995 * number of elements in the hostaddr list, so it really should be the
999 Assert(i == conn->nconnhost);
1002 if (conn->pghost != NULL && conn->pghost[0] != '\0')
1004 char *s = conn->pghost;
1007 for (i = 0; i < conn->nconnhost && more; i++)
1009 conn->connhost[i].host = parse_comma_separated_list(&s, &more);
1010 if (conn->connhost[i].host == NULL)
1014 /* Check for wrong number of host items. */
1015 if (more || i != conn->nconnhost)
1017 conn->status = CONNECTION_BAD;
1018 printfPQExpBuffer(&conn->errorMessage,
1019 libpq_gettext("could not match %d host names to %d hostaddr values\n"),
1020 count_comma_separated_elems(conn->pghost), conn->nconnhost);
1026 * Now, for each host slot, identify the type of address spec, and fill in
1027 * the default address if nothing was given.
1029 for (i = 0; i < conn->nconnhost; i++)
1031 pg_conn_host *ch = &conn->connhost[i];
1033 if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1034 ch->type = CHT_HOST_ADDRESS;
1035 else if (ch->host != NULL && ch->host[0] != '\0')
1037 ch->type = CHT_HOST_NAME;
1038 #ifdef HAVE_UNIX_SOCKETS
1039 if (is_absolute_path(ch->host))
1040 ch->type = CHT_UNIX_SOCKET;
1047 #ifdef HAVE_UNIX_SOCKETS
1048 ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1049 ch->type = CHT_UNIX_SOCKET;
1051 ch->host = strdup(DefaultHost);
1052 ch->type = CHT_HOST_NAME;
1054 if (ch->host == NULL)
1060 * Next, work out the port number corresponding to each host name.
1062 * Note: unlike the above for host names, this could leave the port fields
1063 * as null or empty strings. We will substitute DEF_PGPORT whenever we
1064 * read such a port field.
1066 if (conn->pgport != NULL && conn->pgport[0] != '\0')
1068 char *s = conn->pgport;
1071 for (i = 0; i < conn->nconnhost && more; i++)
1073 conn->connhost[i].port = parse_comma_separated_list(&s, &more);
1074 if (conn->connhost[i].port == NULL)
1079 * If exactly one port was given, use it for every host. Otherwise,
1080 * there must be exactly as many ports as there were hosts.
1082 if (i == 1 && !more)
1084 for (i = 1; i < conn->nconnhost; i++)
1086 conn->connhost[i].port = strdup(conn->connhost[0].port);
1087 if (conn->connhost[i].port == NULL)
1091 else if (more || i != conn->nconnhost)
1093 conn->status = CONNECTION_BAD;
1094 printfPQExpBuffer(&conn->errorMessage,
1095 libpq_gettext("could not match %d port numbers to %d hosts\n"),
1096 count_comma_separated_elems(conn->pgport), conn->nconnhost);
1102 * If user name was not given, fetch it. (Most likely, the fetch will
1103 * fail, since the only way we get here is if pg_fe_getauthname() failed
1104 * during conninfo_add_defaults(). But now we want an error message.)
1106 if (conn->pguser == NULL || conn->pguser[0] == '\0')
1110 conn->pguser = pg_fe_getauthname(&conn->errorMessage);
1113 conn->status = CONNECTION_BAD;
1119 * If database name was not given, default it to equal user name
1121 if (conn->dbName == NULL || conn->dbName[0] == '\0')
1125 conn->dbName = strdup(conn->pguser);
1131 * If password was not given, try to look it up in password file. Note
1132 * that the result might be different for each host/port pair.
1134 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1136 /* If password file wasn't specified, use ~/PGPASSFILE */
1137 if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1139 char homedir[MAXPGPATH];
1141 if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1143 if (conn->pgpassfile)
1144 free(conn->pgpassfile);
1145 conn->pgpassfile = malloc(MAXPGPATH);
1146 if (!conn->pgpassfile)
1148 snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1149 homedir, PGPASSFILE);
1153 if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1155 for (i = 0; i < conn->nconnhost; i++)
1158 * Try to get a password for this host from file. We use host
1159 * for the hostname search key if given, else hostaddr (at
1160 * least one of them is guaranteed nonempty by now).
1162 const char *pwhost = conn->connhost[i].host;
1164 if (pwhost == NULL || pwhost[0] == '\0')
1165 pwhost = conn->connhost[i].hostaddr;
1167 conn->connhost[i].password =
1168 passwordFromFile(pwhost,
1169 conn->connhost[i].port,
1178 * validate sslmode option
1182 if (strcmp(conn->sslmode, "disable") != 0
1183 && strcmp(conn->sslmode, "allow") != 0
1184 && strcmp(conn->sslmode, "prefer") != 0
1185 && strcmp(conn->sslmode, "require") != 0
1186 && strcmp(conn->sslmode, "verify-ca") != 0
1187 && strcmp(conn->sslmode, "verify-full") != 0)
1189 conn->status = CONNECTION_BAD;
1190 printfPQExpBuffer(&conn->errorMessage,
1191 libpq_gettext("invalid sslmode value: \"%s\"\n"),
1197 switch (conn->sslmode[0])
1199 case 'a': /* "allow" */
1200 case 'p': /* "prefer" */
1203 * warn user that an SSL connection will never be negotiated
1204 * since SSL was not compiled in?
1208 case 'r': /* "require" */
1209 case 'v': /* "verify-ca" or "verify-full" */
1210 conn->status = CONNECTION_BAD;
1211 printfPQExpBuffer(&conn->errorMessage,
1212 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
1220 conn->sslmode = strdup(DefaultSSLMode);
1226 * Resolve special "auto" client_encoding from the locale
1228 if (conn->client_encoding_initial &&
1229 strcmp(conn->client_encoding_initial, "auto") == 0)
1231 free(conn->client_encoding_initial);
1232 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
1233 if (!conn->client_encoding_initial)
1238 * Validate target_session_attrs option.
1240 if (conn->target_session_attrs)
1242 if (strcmp(conn->target_session_attrs, "any") != 0
1243 && strcmp(conn->target_session_attrs, "read-write") != 0)
1245 conn->status = CONNECTION_BAD;
1246 printfPQExpBuffer(&conn->errorMessage,
1247 libpq_gettext("invalid target_session_attrs value: \"%s\"\n"),
1248 conn->target_session_attrs);
1254 * Only if we get this far is it appropriate to try to connect. (We need a
1255 * state flag, rather than just the boolean result of this function, in
1256 * case someone tries to PQreset() the PGconn.)
1258 conn->options_valid = true;
1263 conn->status = CONNECTION_BAD;
1264 printfPQExpBuffer(&conn->errorMessage,
1265 libpq_gettext("out of memory\n"));
1272 * Construct a default connection options array, which identifies all the
1273 * available options and shows any default values that are available from the
1274 * environment etc. On error (eg out of memory), NULL is returned.
1276 * Using this function, an application may determine all possible options
1277 * and their current default values.
1279 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1280 * and should be freed when no longer needed via PQconninfoFree(). (In prior
1281 * versions, the returned array was static, but that's not thread-safe.)
1282 * Pre-7.0 applications that use this function will see a small memory leak
1283 * until they are updated to call PQconninfoFree.
1286 PQconndefaults(void)
1288 PQExpBufferData errorBuf;
1289 PQconninfoOption *connOptions;
1291 /* We don't actually report any errors here, but callees want a buffer */
1292 initPQExpBuffer(&errorBuf);
1293 if (PQExpBufferDataBroken(errorBuf))
1294 return NULL; /* out of memory already :-( */
1296 connOptions = conninfo_init(&errorBuf);
1297 if (connOptions != NULL)
1299 /* pass NULL errorBuf to ignore errors */
1300 if (!conninfo_add_defaults(connOptions, NULL))
1302 PQconninfoFree(connOptions);
1307 termPQExpBuffer(&errorBuf);
1314 * establishes a connection to a postgres backend through the postmaster
1315 * at the specified host and port.
1317 * returns a PGconn* which is needed for all subsequent libpq calls
1319 * if the status field of the connection returned is CONNECTION_BAD,
1320 * then only the errorMessage is likely to be useful.
1324 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1325 const char *pgtty, const char *dbName, const char *login,
1331 * Allocate memory for the conn structure
1333 conn = makeEmptyPGconn();
1338 * If the dbName parameter contains what looks like a connection string,
1339 * parse it into conn struct using connectOptions1.
1341 if (dbName && recognized_connection_string(dbName))
1343 if (!connectOptions1(conn, dbName))
1349 * Old-style path: first, parse an empty conninfo string in order to
1350 * set up the same defaults that PQconnectdb() would use.
1352 if (!connectOptions1(conn, ""))
1355 /* Insert dbName parameter value into struct */
1356 if (dbName && dbName[0] != '\0')
1360 conn->dbName = strdup(dbName);
1367 * Insert remaining parameters into struct, overriding defaults (as well
1368 * as any conflicting data from dbName taken as a conninfo).
1370 if (pghost && pghost[0] != '\0')
1374 conn->pghost = strdup(pghost);
1379 if (pgport && pgport[0] != '\0')
1383 conn->pgport = strdup(pgport);
1388 if (pgoptions && pgoptions[0] != '\0')
1390 if (conn->pgoptions)
1391 free(conn->pgoptions);
1392 conn->pgoptions = strdup(pgoptions);
1393 if (!conn->pgoptions)
1397 if (pgtty && pgtty[0] != '\0')
1401 conn->pgtty = strdup(pgtty);
1406 if (login && login[0] != '\0')
1410 conn->pguser = strdup(login);
1415 if (pwd && pwd[0] != '\0')
1419 conn->pgpass = strdup(pwd);
1425 * Compute derived options
1427 if (!connectOptions2(conn))
1431 * Connect to the database
1433 if (connectDBStart(conn))
1434 (void) connectDBComplete(conn);
1439 conn->status = CONNECTION_BAD;
1440 printfPQExpBuffer(&conn->errorMessage,
1441 libpq_gettext("out of memory\n"));
1448 * Sets the TCP_NODELAY socket option.
1449 * Returns 1 if successful, 0 if not.
1453 connectNoDelay(PGconn *conn)
1458 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1462 char sebuf[PG_STRERROR_R_BUFLEN];
1464 appendPQExpBuffer(&conn->errorMessage,
1465 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1466 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1476 * connectFailureMessage -
1477 * create a friendly error message on connection failure.
1481 connectFailureMessage(PGconn *conn, int errorno)
1483 char sebuf[PG_STRERROR_R_BUFLEN];
1485 #ifdef HAVE_UNIX_SOCKETS
1486 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1488 char service[NI_MAXHOST];
1490 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1492 service, sizeof(service),
1494 appendPQExpBuffer(&conn->errorMessage,
1495 libpq_gettext("could not connect to server: %s\n"
1496 "\tIs the server running locally and accepting\n"
1497 "\tconnections on Unix domain socket \"%s\"?\n"),
1498 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1502 #endif /* HAVE_UNIX_SOCKETS */
1504 char host_addr[NI_MAXHOST];
1505 const char *displayed_host;
1506 const char *displayed_port;
1507 struct sockaddr_storage *addr = &conn->raddr.addr;
1510 * Optionally display the network address with the hostname. This is
1511 * useful to distinguish between IPv4 and IPv6 connections.
1513 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
1514 strlcpy(host_addr, conn->connhost[conn->whichhost].hostaddr, NI_MAXHOST);
1515 else if (addr->ss_family == AF_INET)
1517 if (inet_net_ntop(AF_INET,
1518 &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1520 host_addr, sizeof(host_addr)) == NULL)
1521 strcpy(host_addr, "???");
1524 else if (addr->ss_family == AF_INET6)
1526 if (inet_net_ntop(AF_INET6,
1527 &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1529 host_addr, sizeof(host_addr)) == NULL)
1530 strcpy(host_addr, "???");
1534 strcpy(host_addr, "???");
1536 /* To which host and port were we actually connecting? */
1537 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
1538 displayed_host = conn->connhost[conn->whichhost].hostaddr;
1540 displayed_host = conn->connhost[conn->whichhost].host;
1541 displayed_port = conn->connhost[conn->whichhost].port;
1542 if (displayed_port == NULL || displayed_port[0] == '\0')
1543 displayed_port = DEF_PGPORT_STR;
1546 * If the user did not supply an IP address using 'hostaddr', and
1547 * 'host' was missing or does not match our lookup, display the
1548 * looked-up IP address.
1550 if (conn->connhost[conn->whichhost].type != CHT_HOST_ADDRESS &&
1551 strcmp(displayed_host, host_addr) != 0)
1552 appendPQExpBuffer(&conn->errorMessage,
1553 libpq_gettext("could not connect to server: %s\n"
1554 "\tIs the server running on host \"%s\" (%s) and accepting\n"
1555 "\tTCP/IP connections on port %s?\n"),
1556 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1561 appendPQExpBuffer(&conn->errorMessage,
1562 libpq_gettext("could not connect to server: %s\n"
1563 "\tIs the server running on host \"%s\" and accepting\n"
1564 "\tTCP/IP connections on port %s?\n"),
1565 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1572 * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
1573 * conn->keepalives is set to a value which is not parseable as an
1577 useKeepalives(PGconn *conn)
1582 if (conn->keepalives == NULL)
1584 val = strtol(conn->keepalives, &ep, 10);
1587 return val != 0 ? 1 : 0;
1591 * Parse and try to interpret "value" as an integer value, and if successful,
1592 * store it in *result, complaining if there is any trailing garbage or an
1596 parse_int_param(const char *value, int *result, PGconn *conn,
1597 const char *context)
1605 numval = strtol(value, &end, 10);
1606 if (errno == 0 && *end == '\0' && numval == (int) numval)
1612 appendPQExpBuffer(&conn->errorMessage,
1613 libpq_gettext("invalid integer value \"%s\" for keyword \"%s\"\n"),
1620 * Set the keepalive idle timer.
1623 setKeepalivesIdle(PGconn *conn)
1627 if (conn->keepalives_idle == NULL)
1630 if (!parse_int_param(conn->keepalives_idle, &idle, conn,
1636 #ifdef PG_TCP_KEEPALIVE_IDLE
1637 if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1638 (char *) &idle, sizeof(idle)) < 0)
1640 char sebuf[PG_STRERROR_R_BUFLEN];
1642 appendPQExpBuffer(&conn->errorMessage,
1643 libpq_gettext("setsockopt(%s) failed: %s\n"),
1644 PG_TCP_KEEPALIVE_IDLE_STR,
1645 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1654 * Set the keepalive interval.
1657 setKeepalivesInterval(PGconn *conn)
1661 if (conn->keepalives_interval == NULL)
1664 if (!parse_int_param(conn->keepalives_interval, &interval, conn,
1665 "keepalives_interval"))
1670 #ifdef TCP_KEEPINTVL
1671 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1672 (char *) &interval, sizeof(interval)) < 0)
1674 char sebuf[PG_STRERROR_R_BUFLEN];
1676 appendPQExpBuffer(&conn->errorMessage,
1677 libpq_gettext("setsockopt(%s) failed: %s\n"),
1679 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1688 * Set the count of lost keepalive packets that will trigger a connection
1692 setKeepalivesCount(PGconn *conn)
1696 if (conn->keepalives_count == NULL)
1699 if (!parse_int_param(conn->keepalives_count, &count, conn,
1700 "keepalives_count"))
1706 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1707 (char *) &count, sizeof(count)) < 0)
1709 char sebuf[PG_STRERROR_R_BUFLEN];
1711 appendPQExpBuffer(&conn->errorMessage,
1712 libpq_gettext("setsockopt(%s) failed: %s\n"),
1714 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1722 #ifdef SIO_KEEPALIVE_VALS
1724 * Enable keepalives and set the keepalive values on Win32,
1725 * where they are always set in one batch.
1728 setKeepalivesWin32(PGconn *conn)
1730 struct tcp_keepalive ka;
1735 if (conn->keepalives_idle &&
1736 !parse_int_param(conn->keepalives_idle, &idle, conn,
1740 idle = 2 * 60 * 60; /* 2 hours = default */
1742 if (conn->keepalives_interval &&
1743 !parse_int_param(conn->keepalives_interval, &interval, conn,
1744 "keepalives_interval"))
1747 interval = 1; /* 1 second = default */
1750 ka.keepalivetime = idle * 1000;
1751 ka.keepaliveinterval = interval * 1000;
1753 if (WSAIoctl(conn->sock,
1764 appendPQExpBuffer(&conn->errorMessage,
1765 libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1771 #endif /* SIO_KEEPALIVE_VALS */
1776 * Begin the process of making a connection to the backend.
1778 * Returns 1 if successful, 0 if not.
1782 connectDBStart(PGconn *conn)
1787 if (!conn->options_valid)
1788 goto connect_errReturn;
1791 * Check for bad linking to backend-internal versions of src/common
1792 * functions (see comments in link-canary.c for the reason we need this).
1793 * Nobody but developers should see this message, so we don't bother
1796 if (!pg_link_canary_is_frontend())
1798 printfPQExpBuffer(&conn->errorMessage,
1799 "libpq is incorrectly linked to backend functions\n");
1800 goto connect_errReturn;
1803 /* Ensure our buffers are empty */
1804 conn->inStart = conn->inCursor = conn->inEnd = 0;
1808 * Ensure errorMessage is empty, too. PQconnectPoll will append messages
1809 * to it in the process of scanning for a working server. Thus, if we
1810 * fail to connect to multiple hosts, the final error message will include
1811 * details about each failure.
1813 resetPQExpBuffer(&conn->errorMessage);
1816 * Set up to try to connect to the first host. (Setting whichhost = -1 is
1817 * a bit of a cheat, but PQconnectPoll will advance it to 0 before
1818 * anything else looks at it.)
1820 conn->whichhost = -1;
1821 conn->try_next_addr = false;
1822 conn->try_next_host = true;
1823 conn->status = CONNECTION_NEEDED;
1826 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1827 * so that it can easily be re-executed if needed again during the
1828 * asynchronous startup process. However, we must run it once here,
1829 * because callers expect a success return from this routine to mean that
1830 * we are in PGRES_POLLING_WRITING connection state.
1832 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1838 * If we managed to open a socket, close it immediately rather than
1839 * waiting till PQfinish. (The application cannot have gotten the socket
1840 * from PQsocket yet, so this doesn't risk breaking anything.)
1842 pqDropConnection(conn, true);
1843 conn->status = CONNECTION_BAD;
1851 * Block and complete a connection.
1853 * Returns 1 on success, 0 on failure.
1856 connectDBComplete(PGconn *conn)
1858 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1859 time_t finish_time = ((time_t) -1);
1861 int last_whichhost = -2; /* certainly different from whichhost */
1862 struct addrinfo *last_addr_cur = NULL;
1864 if (conn == NULL || conn->status == CONNECTION_BAD)
1868 * Set up a time limit, if connect_timeout isn't zero.
1870 if (conn->connect_timeout != NULL)
1872 if (!parse_int_param(conn->connect_timeout, &timeout, conn,
1879 * Rounding could cause connection to fail unexpectedly quickly;
1880 * to prevent possibly waiting hardly-at-all, insist on at least
1886 else /* negative means 0 */
1895 * (Re)start the connect_timeout timer if it's active and we are
1896 * considering a different host than we were last time through. If
1897 * we've already succeeded, though, needn't recalculate.
1899 if (flag != PGRES_POLLING_OK &&
1901 (conn->whichhost != last_whichhost ||
1902 conn->addr_cur != last_addr_cur))
1904 finish_time = time(NULL) + timeout;
1905 last_whichhost = conn->whichhost;
1906 last_addr_cur = conn->addr_cur;
1910 * Wait, if necessary. Note that the initial state (just after
1911 * PQconnectStart) is to wait for the socket to select for writing.
1915 case PGRES_POLLING_OK:
1918 * Reset stored error messages since we now have a working
1921 resetPQExpBuffer(&conn->errorMessage);
1922 return 1; /* success! */
1924 case PGRES_POLLING_READING:
1925 ret = pqWaitTimed(1, 0, conn, finish_time);
1928 /* hard failure, eg select() problem, aborts everything */
1929 conn->status = CONNECTION_BAD;
1934 case PGRES_POLLING_WRITING:
1935 ret = pqWaitTimed(0, 1, conn, finish_time);
1938 /* hard failure, eg select() problem, aborts everything */
1939 conn->status = CONNECTION_BAD;
1945 /* Just in case we failed to set it in PQconnectPoll */
1946 conn->status = CONNECTION_BAD;
1950 if (ret == 1) /* connect_timeout elapsed */
1953 * Give up on current server/address, try the next one.
1955 conn->try_next_addr = true;
1956 conn->status = CONNECTION_NEEDED;
1960 * Now try to advance the state machine.
1962 flag = PQconnectPoll(conn);
1967 * This subroutine saves conn->errorMessage, which will be restored back by
1968 * restoreErrorMessage subroutine. Returns false on OOM failure.
1971 saveErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
1973 initPQExpBuffer(savedMessage);
1974 appendPQExpBufferStr(savedMessage,
1975 conn->errorMessage.data);
1976 if (PQExpBufferBroken(savedMessage))
1978 printfPQExpBuffer(&conn->errorMessage,
1979 libpq_gettext("out of memory\n"));
1982 /* Clear whatever is in errorMessage now */
1983 resetPQExpBuffer(&conn->errorMessage);
1988 * Restores saved error messages back to conn->errorMessage, prepending them
1989 * to whatever is in conn->errorMessage already. (This does the right thing
1990 * if anything's been added to conn->errorMessage since saveErrorMessage.)
1993 restoreErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
1995 appendPQExpBufferStr(savedMessage, conn->errorMessage.data);
1996 resetPQExpBuffer(&conn->errorMessage);
1997 appendPQExpBufferStr(&conn->errorMessage, savedMessage->data);
1998 /* If any step above hit OOM, just report that */
1999 if (PQExpBufferBroken(savedMessage) ||
2000 PQExpBufferBroken(&conn->errorMessage))
2001 printfPQExpBuffer(&conn->errorMessage,
2002 libpq_gettext("out of memory\n"));
2003 termPQExpBuffer(savedMessage);
2009 * Poll an asynchronous connection.
2011 * Returns a PostgresPollingStatusType.
2012 * Before calling this function, use select(2) to determine when data
2015 * You must call PQfinish whether or not this fails.
2017 * This function and PQconnectStart are intended to allow connections to be
2018 * made without blocking the execution of your program on remote I/O. However,
2019 * there are a number of caveats:
2021 * o If you call PQtrace, ensure that the stream object into which you trace
2023 * o If you do not supply an IP address for the remote host (i.e. you
2024 * supply a host name instead) then PQconnectStart will block on
2025 * gethostbyname. You will be fine if using Unix sockets (i.e. by
2026 * supplying neither a host name nor a host address).
2027 * o If your backend wants to use Kerberos authentication then you must
2028 * supply both a host name and a host address, otherwise this function
2029 * may block on gethostname.
2033 PostgresPollingStatusType
2034 PQconnectPoll(PGconn *conn)
2036 bool reset_connection_state_machine = false;
2037 bool need_new_connection = false;
2039 char sebuf[PG_STRERROR_R_BUFLEN];
2041 PQExpBufferData savedMessage;
2044 return PGRES_POLLING_FAILED;
2046 /* Get the new data */
2047 switch (conn->status)
2050 * We really shouldn't have been polled in these two cases, but we
2053 case CONNECTION_BAD:
2054 return PGRES_POLLING_FAILED;
2056 return PGRES_POLLING_OK;
2058 /* These are reading states */
2059 case CONNECTION_AWAITING_RESPONSE:
2060 case CONNECTION_AUTH_OK:
2062 /* Load waiting data */
2063 int n = pqReadData(conn);
2068 return PGRES_POLLING_READING;
2073 /* These are writing states, so we just proceed. */
2074 case CONNECTION_STARTED:
2075 case CONNECTION_MADE:
2078 /* We allow pqSetenvPoll to decide whether to proceed. */
2079 case CONNECTION_SETENV:
2082 /* Special cases: proceed without waiting. */
2083 case CONNECTION_SSL_STARTUP:
2084 case CONNECTION_NEEDED:
2085 case CONNECTION_CHECK_WRITABLE:
2086 case CONNECTION_CONSUME:
2090 appendPQExpBufferStr(&conn->errorMessage,
2092 "invalid connection state, "
2093 "probably indicative of memory corruption\n"
2099 keep_going: /* We will come back to here until there is
2100 * nothing left to do. */
2102 /* Time to advance to next address, or next host if no more addresses? */
2103 if (conn->try_next_addr)
2105 if (conn->addr_cur && conn->addr_cur->ai_next)
2107 conn->addr_cur = conn->addr_cur->ai_next;
2108 reset_connection_state_machine = true;
2111 conn->try_next_host = true;
2112 conn->try_next_addr = false;
2115 /* Time to advance to next connhost[] entry? */
2116 if (conn->try_next_host)
2119 struct addrinfo hint;
2122 char portstr[MAXPGPATH];
2124 if (conn->whichhost + 1 >= conn->nconnhost)
2127 * Oops, no more hosts. An appropriate error message is already
2128 * set up, so just set the right status.
2134 /* Drop any address info for previous host */
2135 release_conn_addrinfo(conn);
2138 * Look up info for the new host. On failure, log the problem in
2139 * conn->errorMessage, then loop around to try the next host. (Note
2140 * we don't clear try_next_host until we've succeeded.)
2142 ch = &conn->connhost[conn->whichhost];
2144 /* Initialize hint structure */
2145 MemSet(&hint, 0, sizeof(hint));
2146 hint.ai_socktype = SOCK_STREAM;
2147 conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2149 /* Figure out the port number we're going to use. */
2150 if (ch->port == NULL || ch->port[0] == '\0')
2151 thisport = DEF_PGPORT;
2154 if (!parse_int_param(ch->port, &thisport, conn, "port"))
2157 if (thisport < 1 || thisport > 65535)
2159 appendPQExpBuffer(&conn->errorMessage,
2160 libpq_gettext("invalid port number: \"%s\"\n"),
2165 snprintf(portstr, sizeof(portstr), "%d", thisport);
2167 /* Use pg_getaddrinfo_all() to resolve the address */
2171 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2173 if (ret || !conn->addrlist)
2175 appendPQExpBuffer(&conn->errorMessage,
2176 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
2177 ch->host, gai_strerror(ret));
2182 case CHT_HOST_ADDRESS:
2183 hint.ai_flags = AI_NUMERICHOST;
2184 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2186 if (ret || !conn->addrlist)
2188 appendPQExpBuffer(&conn->errorMessage,
2189 libpq_gettext("could not parse network address \"%s\": %s\n"),
2190 ch->hostaddr, gai_strerror(ret));
2195 case CHT_UNIX_SOCKET:
2196 #ifdef HAVE_UNIX_SOCKETS
2197 conn->addrlist_family = hint.ai_family = AF_UNIX;
2198 UNIXSOCK_PATH(portstr, thisport, ch->host);
2199 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2201 appendPQExpBuffer(&conn->errorMessage,
2202 libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
2204 (int) (UNIXSOCK_PATH_BUFLEN - 1));
2209 * NULL hostname tells pg_getaddrinfo_all to parse the service
2210 * name as a Unix-domain socket path.
2212 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2214 if (ret || !conn->addrlist)
2216 appendPQExpBuffer(&conn->errorMessage,
2217 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
2218 portstr, gai_strerror(ret));
2227 /* OK, scan this addrlist for a working server address */
2228 conn->addr_cur = conn->addrlist;
2229 reset_connection_state_machine = true;
2230 conn->try_next_host = false;
2233 /* Reset connection state machine? */
2234 if (reset_connection_state_machine)
2237 * (Re) initialize our connection control variables for a set of
2238 * connection attempts to a single server address. These variables
2239 * must persist across individual connection attempts, but we must
2240 * reset them when we start to consider a new server.
2242 conn->pversion = PG_PROTOCOL(3, 0);
2243 conn->send_appname = true;
2245 /* initialize these values based on SSL mode */
2246 conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2247 conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2250 reset_connection_state_machine = false;
2251 need_new_connection = true;
2254 /* Force a new connection (perhaps to the same server as before)? */
2255 if (need_new_connection)
2257 /* Drop any existing connection */
2258 pqDropConnection(conn, true);
2260 /* Reset all state obtained from old server */
2261 pqDropServerData(conn);
2263 /* Drop any PGresult we might have, too */
2264 conn->asyncStatus = PGASYNC_IDLE;
2265 conn->xactStatus = PQTRANS_IDLE;
2266 pqClearAsyncResult(conn);
2268 /* Reset conn->status to put the state machine in the right state */
2269 conn->status = CONNECTION_NEEDED;
2271 need_new_connection = false;
2274 /* Now try to advance the state machine for this connection */
2275 switch (conn->status)
2277 case CONNECTION_NEEDED:
2280 * Try to initiate a connection to one of the addresses
2281 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
2284 * The extra level of braces here is historical. It's not
2285 * worth reindenting this whole switch case to remove 'em.
2288 struct addrinfo *addr_cur = conn->addr_cur;
2291 * Advance to next possible host, if we've tried all of
2292 * the addresses for the current host.
2294 if (addr_cur == NULL)
2296 conn->try_next_host = true;
2300 /* Remember current address for possible error msg */
2301 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2302 addr_cur->ai_addrlen);
2303 conn->raddr.salen = addr_cur->ai_addrlen;
2305 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
2306 if (conn->sock == PGINVALID_SOCKET)
2309 * Silently ignore socket() failure if we have more
2310 * addresses to try; this reduces useless chatter in
2311 * cases where the address list includes both IPv4 and
2312 * IPv6 but kernel only accepts one family.
2314 if (addr_cur->ai_next != NULL ||
2315 conn->whichhost + 1 < conn->nconnhost)
2317 conn->try_next_addr = true;
2320 appendPQExpBuffer(&conn->errorMessage,
2321 libpq_gettext("could not create socket: %s\n"),
2322 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2327 * Select socket options: no delay of outgoing data for
2328 * TCP sockets, nonblock mode, close-on-exec. Try the
2329 * next address if any of this fails.
2331 if (!IS_AF_UNIX(addr_cur->ai_family))
2333 if (!connectNoDelay(conn))
2335 /* error message already created */
2336 conn->try_next_addr = true;
2340 if (!pg_set_noblock(conn->sock))
2342 appendPQExpBuffer(&conn->errorMessage,
2343 libpq_gettext("could not set socket to nonblocking mode: %s\n"),
2344 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2345 conn->try_next_addr = true;
2350 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2352 appendPQExpBuffer(&conn->errorMessage,
2353 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
2354 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2355 conn->try_next_addr = true;
2358 #endif /* F_SETFD */
2360 if (!IS_AF_UNIX(addr_cur->ai_family))
2365 int usekeepalives = useKeepalives(conn);
2368 if (usekeepalives < 0)
2370 appendPQExpBufferStr(&conn->errorMessage,
2371 libpq_gettext("keepalives parameter must be an integer\n"));
2374 else if (usekeepalives == 0)
2379 else if (setsockopt(conn->sock,
2380 SOL_SOCKET, SO_KEEPALIVE,
2381 (char *) &on, sizeof(on)) < 0)
2383 appendPQExpBuffer(&conn->errorMessage,
2384 libpq_gettext("setsockopt(%s) failed: %s\n"),
2386 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2389 else if (!setKeepalivesIdle(conn)
2390 || !setKeepalivesInterval(conn)
2391 || !setKeepalivesCount(conn))
2394 #ifdef SIO_KEEPALIVE_VALS
2395 else if (!setKeepalivesWin32(conn))
2397 #endif /* SIO_KEEPALIVE_VALS */
2402 conn->try_next_addr = true;
2408 * We have three methods of blocking SIGPIPE during
2409 * send() calls to this socket:
2411 * - setsockopt(sock, SO_NOSIGPIPE)
2412 * - send(sock, ..., MSG_NOSIGNAL)
2413 * - setting the signal mask to SIG_IGN during send()
2415 * The third method requires three syscalls per send,
2416 * so we prefer either of the first two, but they are
2417 * less portable. The state is tracked in the following
2418 * members of PGconn:
2420 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2421 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2423 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2424 * and we're done. Otherwise, set sigpipe_flag so that
2425 * we will try MSG_NOSIGNAL on sends. If we get an error
2426 * with MSG_NOSIGNAL, we'll clear that flag and revert to
2430 conn->sigpipe_so = false;
2432 conn->sigpipe_flag = true;
2434 conn->sigpipe_flag = false;
2435 #endif /* MSG_NOSIGNAL */
2439 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2440 (char *) &optval, sizeof(optval)) == 0)
2442 conn->sigpipe_so = true;
2443 conn->sigpipe_flag = false;
2445 #endif /* SO_NOSIGPIPE */
2448 * Start/make connection. This should not block, since we
2449 * are in nonblock mode. If it does, well, too bad.
2451 if (connect(conn->sock, addr_cur->ai_addr,
2452 addr_cur->ai_addrlen) < 0)
2454 if (SOCK_ERRNO == EINPROGRESS ||
2456 SOCK_ERRNO == EWOULDBLOCK ||
2458 SOCK_ERRNO == EINTR)
2461 * This is fine - we're in non-blocking mode, and
2462 * the connection is in progress. Tell caller to
2463 * wait for write-ready on socket.
2465 conn->status = CONNECTION_STARTED;
2466 return PGRES_POLLING_WRITING;
2468 /* otherwise, trouble */
2473 * Hm, we're connected already --- seems the "nonblock
2474 * connection" wasn't. Advance the state machine and
2475 * go do the next stuff.
2477 conn->status = CONNECTION_STARTED;
2482 * This connection failed. Add the error report to
2483 * conn->errorMessage, then try the next address if any.
2485 connectFailureMessage(conn, SOCK_ERRNO);
2486 conn->try_next_addr = true;
2491 case CONNECTION_STARTED:
2493 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2496 * Write ready, since we've made it here, so the connection
2497 * has been made ... or has failed.
2501 * Now check (using getsockopt) that there is not an error
2502 * state waiting for us on the socket.
2505 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2506 (char *) &optval, &optlen) == -1)
2508 appendPQExpBuffer(&conn->errorMessage,
2509 libpq_gettext("could not get socket error status: %s\n"),
2510 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2513 else if (optval != 0)
2516 * When using a nonblocking connect, we will typically see
2517 * connect failures at this point, so provide a friendly
2520 connectFailureMessage(conn, optval);
2523 * Try the next address if any, just as in the case where
2524 * connect() returned failure immediately.
2526 conn->try_next_addr = true;
2530 /* Fill in the client address */
2531 conn->laddr.salen = sizeof(conn->laddr.addr);
2532 if (getsockname(conn->sock,
2533 (struct sockaddr *) &conn->laddr.addr,
2534 &conn->laddr.salen) < 0)
2536 appendPQExpBuffer(&conn->errorMessage,
2537 libpq_gettext("could not get client address from socket: %s\n"),
2538 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2543 * Make sure we can write before advancing to next step.
2545 conn->status = CONNECTION_MADE;
2546 return PGRES_POLLING_WRITING;
2549 case CONNECTION_MADE:
2554 #ifdef HAVE_UNIX_SOCKETS
2557 * Implement requirepeer check, if requested and it's a
2558 * Unix-domain socket.
2560 if (conn->requirepeer && conn->requirepeer[0] &&
2561 IS_AF_UNIX(conn->raddr.addr.ss_family))
2563 char pwdbuf[BUFSIZ];
2564 struct passwd pass_buf;
2565 struct passwd *pass;
2571 if (getpeereid(conn->sock, &uid, &gid) != 0)
2574 * Provide special error message if getpeereid is a
2577 if (errno == ENOSYS)
2578 appendPQExpBufferStr(&conn->errorMessage,
2579 libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2581 appendPQExpBuffer(&conn->errorMessage,
2582 libpq_gettext("could not get peer credentials: %s\n"),
2583 strerror_r(errno, sebuf, sizeof(sebuf)));
2587 passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2591 appendPQExpBuffer(&conn->errorMessage,
2592 libpq_gettext("could not look up local user ID %d: %s\n"),
2594 strerror_r(passerr, sebuf, sizeof(sebuf)));
2596 appendPQExpBuffer(&conn->errorMessage,
2597 libpq_gettext("local user with ID %d does not exist\n"),
2602 if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2604 appendPQExpBuffer(&conn->errorMessage,
2605 libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2606 conn->requirepeer, pass->pw_name);
2610 #endif /* HAVE_UNIX_SOCKETS */
2615 * If SSL is enabled and we haven't already got it running,
2616 * request it instead of sending the startup message.
2618 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2620 /* Don't bother requesting SSL over a Unix socket */
2621 conn->allow_ssl_try = false;
2623 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2629 * Send the SSL request packet.
2631 * Theoretically, this could block, but it really
2632 * shouldn't since we only got here if the socket is
2635 pv = pg_hton32(NEGOTIATE_SSL_CODE);
2636 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2638 appendPQExpBuffer(&conn->errorMessage,
2639 libpq_gettext("could not send SSL negotiation packet: %s\n"),
2640 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2643 /* Ok, wait for response */
2644 conn->status = CONNECTION_SSL_STARTUP;
2645 return PGRES_POLLING_READING;
2647 #endif /* USE_SSL */
2650 * Build the startup packet.
2652 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2653 startpacket = pqBuildStartupPacket3(conn, &packetlen,
2654 EnvironmentOptions);
2656 startpacket = pqBuildStartupPacket2(conn, &packetlen,
2657 EnvironmentOptions);
2661 * will not appendbuffer here, since it's likely to also
2664 printfPQExpBuffer(&conn->errorMessage,
2665 libpq_gettext("out of memory\n"));
2670 * Send the startup packet.
2672 * Theoretically, this could block, but it really shouldn't
2673 * since we only got here if the socket is write-ready.
2675 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2677 appendPQExpBuffer(&conn->errorMessage,
2678 libpq_gettext("could not send startup packet: %s\n"),
2679 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2686 conn->status = CONNECTION_AWAITING_RESPONSE;
2687 return PGRES_POLLING_READING;
2691 * Handle SSL negotiation: wait for postmaster messages and
2692 * respond as necessary.
2694 case CONNECTION_SSL_STARTUP:
2697 PostgresPollingStatusType pollres;
2700 * On first time through, get the postmaster's response to our
2701 * SSL negotiation packet.
2703 if (!conn->ssl_in_use)
2706 * We use pqReadData here since it has the logic to
2707 * distinguish no-data-yet from connection closure. Since
2708 * conn->ssl isn't set, a plain recv() will occur.
2713 rdresult = pqReadData(conn);
2716 /* errorMessage is already filled in */
2721 /* caller failed to wait for data */
2722 return PGRES_POLLING_READING;
2724 if (pqGetc(&SSLok, conn) < 0)
2726 /* should not happen really */
2727 return PGRES_POLLING_READING;
2731 /* mark byte consumed */
2732 conn->inStart = conn->inCursor;
2733 /* Set up global SSL state if required */
2734 if (pqsecure_initialize(conn) != 0)
2737 else if (SSLok == 'N')
2739 /* mark byte consumed */
2740 conn->inStart = conn->inCursor;
2741 /* OK to do without SSL? */
2742 if (conn->sslmode[0] == 'r' || /* "require" */
2743 conn->sslmode[0] == 'v') /* "verify-ca" or
2746 /* Require SSL, but server does not want it */
2747 appendPQExpBufferStr(&conn->errorMessage,
2748 libpq_gettext("server does not support SSL, but SSL was required\n"));
2751 /* Otherwise, proceed with normal startup */
2752 conn->allow_ssl_try = false;
2753 conn->status = CONNECTION_MADE;
2754 return PGRES_POLLING_WRITING;
2756 else if (SSLok == 'E')
2759 * Server failure of some sort, such as failure to
2760 * fork a backend process. We need to process and
2761 * report the error message, which might be formatted
2762 * according to either protocol 2 or protocol 3.
2763 * Rather than duplicate the code for that, we flip
2764 * into AWAITING_RESPONSE state and let the code there
2765 * deal with it. Note we have *not* consumed the "E"
2768 conn->status = CONNECTION_AWAITING_RESPONSE;
2773 appendPQExpBuffer(&conn->errorMessage,
2774 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2781 * Begin or continue the SSL negotiation process.
2783 pollres = pqsecure_open_client(conn);
2784 if (pollres == PGRES_POLLING_OK)
2786 /* SSL handshake done, ready to send startup packet */
2787 conn->status = CONNECTION_MADE;
2788 return PGRES_POLLING_WRITING;
2790 if (pollres == PGRES_POLLING_FAILED)
2793 * Failed ... if sslmode is "prefer" then do a non-SSL
2796 if (conn->sslmode[0] == 'p' /* "prefer" */
2797 && conn->allow_ssl_try /* redundant? */
2798 && !conn->wait_ssl_try) /* redundant? */
2800 /* only retry once */
2801 conn->allow_ssl_try = false;
2802 need_new_connection = true;
2805 /* Else it's a hard failure */
2808 /* Else, return POLLING_READING or POLLING_WRITING status */
2810 #else /* !USE_SSL */
2811 /* can't get here */
2813 #endif /* USE_SSL */
2817 * Handle authentication exchange: wait for postmaster messages
2818 * and respond as necessary.
2820 case CONNECTION_AWAITING_RESPONSE:
2829 * Scan the message from current point (note that if we find
2830 * the message is incomplete, we will return without advancing
2831 * inStart, and resume here next time).
2833 conn->inCursor = conn->inStart;
2835 /* Read type byte */
2836 if (pqGetc(&beresp, conn))
2838 /* We'll come back when there is more data */
2839 return PGRES_POLLING_READING;
2843 * Validate message type: we expect only an authentication
2844 * request or an error here. Anything else probably means
2845 * it's not Postgres on the other end at all.
2847 if (!(beresp == 'R' || beresp == 'E'))
2849 appendPQExpBuffer(&conn->errorMessage,
2851 "expected authentication request from "
2852 "server, but received %c\n"),
2857 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2859 /* Read message length word */
2860 if (pqGetInt(&msgLength, 4, conn))
2862 /* We'll come back when there is more data */
2863 return PGRES_POLLING_READING;
2868 /* Set phony message length to disable checks below */
2873 * Try to validate message length before using it.
2874 * Authentication requests can't be very large, although GSS
2875 * auth requests may not be that small. Errors can be a
2876 * little larger, but not huge. If we see a large apparent
2877 * length in an error, it means we're really talking to a
2878 * pre-3.0-protocol server; cope.
2880 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2882 appendPQExpBuffer(&conn->errorMessage,
2884 "expected authentication request from "
2885 "server, but received %c\n"),
2890 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2892 /* Handle error from a pre-3.0 server */
2893 conn->inCursor = conn->inStart + 1; /* reread data */
2894 if (pqGets_append(&conn->errorMessage, conn))
2896 /* We'll come back when there is more data */
2897 return PGRES_POLLING_READING;
2899 /* OK, we read the message; mark data consumed */
2900 conn->inStart = conn->inCursor;
2903 * The postmaster typically won't end its message with a
2904 * newline, so add one to conform to libpq conventions.
2906 appendPQExpBufferChar(&conn->errorMessage, '\n');
2909 * If we tried to open the connection in 3.0 protocol,
2910 * fall back to 2.0 protocol.
2912 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2914 conn->pversion = PG_PROTOCOL(2, 0);
2915 need_new_connection = true;
2923 * Can't process if message body isn't all here yet.
2925 * (In protocol 2.0 case, we are assuming messages carry at
2926 * least 4 bytes of data.)
2929 avail = conn->inEnd - conn->inCursor;
2930 if (avail < msgLength)
2933 * Before returning, try to enlarge the input buffer if
2934 * needed to hold the whole message; see notes in
2937 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2940 /* We'll come back when there is more data */
2941 return PGRES_POLLING_READING;
2944 /* Handle errors. */
2947 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2949 if (pqGetErrorNotice3(conn, true))
2951 /* We'll come back when there is more data */
2952 return PGRES_POLLING_READING;
2957 if (pqGets_append(&conn->errorMessage, conn))
2959 /* We'll come back when there is more data */
2960 return PGRES_POLLING_READING;
2963 /* OK, we read the message; mark data consumed */
2964 conn->inStart = conn->inCursor;
2966 /* Check to see if we should mention pgpassfile */
2967 pgpassfileWarning(conn);
2972 * if sslmode is "allow" and we haven't tried an SSL
2973 * connection already, then retry with an SSL connection
2975 if (conn->sslmode[0] == 'a' /* "allow" */
2976 && !conn->ssl_in_use
2977 && conn->allow_ssl_try
2978 && conn->wait_ssl_try)
2980 /* only retry once */
2981 conn->wait_ssl_try = false;
2982 need_new_connection = true;
2987 * if sslmode is "prefer" and we're in an SSL connection,
2988 * then do a non-SSL retry
2990 if (conn->sslmode[0] == 'p' /* "prefer" */
2992 && conn->allow_ssl_try /* redundant? */
2993 && !conn->wait_ssl_try) /* redundant? */
2995 /* only retry once */
2996 conn->allow_ssl_try = false;
2997 need_new_connection = true;
3005 /* It is an authentication request. */
3006 conn->auth_req_received = true;
3008 /* Get the type of request. */
3009 if (pqGetInt((int *) &areq, 4, conn))
3011 /* We'll come back when there are more data */
3012 return PGRES_POLLING_READING;
3017 * Ensure the password salt is in the input buffer, if it's an
3018 * MD5 request. All the other authentication methods that
3019 * contain extra data in the authentication request are only
3020 * supported in protocol version 3, in which case we already
3021 * read the whole message above.
3023 if (areq == AUTH_REQ_MD5 && PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3027 avail = conn->inEnd - conn->inCursor;
3031 * Before returning, try to enlarge the input buffer
3032 * if needed to hold the whole message; see notes in
3035 if (pqCheckInBufferSpace(conn->inCursor + (size_t) 4,
3038 /* We'll come back when there is more data */
3039 return PGRES_POLLING_READING;
3044 * Process the rest of the authentication request message, and
3045 * respond to it if necessary.
3047 * Note that conn->pghost must be non-NULL if we are going to
3048 * avoid the Kerberos code doing a hostname look-up.
3050 res = pg_fe_sendauth(areq, msgLength, conn);
3051 conn->errorMessage.len = strlen(conn->errorMessage.data);
3053 /* OK, we have processed the message; mark data consumed */
3054 conn->inStart = conn->inCursor;
3056 if (res != STATUS_OK)
3060 * Just make sure that any data sent by pg_fe_sendauth is
3061 * flushed out. Although this theoretically could block, it
3062 * really shouldn't since we don't send large auth responses.
3067 if (areq == AUTH_REQ_OK)
3069 /* We are done with authentication exchange */
3070 conn->status = CONNECTION_AUTH_OK;
3073 * Set asyncStatus so that PQgetResult will think that
3074 * what comes back next is the result of a query. See
3077 conn->asyncStatus = PGASYNC_BUSY;
3080 /* Look to see if we have more data yet. */
3084 case CONNECTION_AUTH_OK:
3087 * Now we expect to hear from the backend. A ReadyForQuery
3088 * message indicates that startup is successful, but we might
3089 * also get an Error message indicating failure. (Notice
3090 * messages indicating nonfatal warnings are also allowed by
3091 * the protocol, as are ParameterStatus and BackendKeyData
3092 * messages.) Easiest way to handle this is to let
3093 * PQgetResult() read the messages. We just have to fake it
3094 * out about the state of the connection, by setting
3095 * asyncStatus = PGASYNC_BUSY (done above).
3099 return PGRES_POLLING_READING;
3101 res = PQgetResult(conn);
3104 * NULL return indicating we have gone to IDLE state is
3109 if (res->resultStatus != PGRES_FATAL_ERROR)
3110 appendPQExpBufferStr(&conn->errorMessage,
3111 libpq_gettext("unexpected message from server during startup\n"));
3112 else if (conn->send_appname &&
3113 (conn->appname || conn->fbappname))
3116 * If we tried to send application_name, check to see
3117 * if the error is about that --- pre-9.0 servers will
3118 * reject it at this stage of the process. If so,
3119 * close the connection and retry without sending
3120 * application_name. We could possibly get a false
3121 * SQLSTATE match here and retry uselessly, but there
3122 * seems no great harm in that; we'll just get the
3123 * same error again if it's unrelated.
3125 const char *sqlstate;
3127 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
3129 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3132 conn->send_appname = false;
3133 need_new_connection = true;
3139 * if the resultStatus is FATAL, then conn->errorMessage
3140 * already has a copy of the error; needn't copy it back.
3141 * But add a newline if it's not there already, since
3142 * postmaster error messages may not have one.
3144 if (conn->errorMessage.len <= 0 ||
3145 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3146 appendPQExpBufferChar(&conn->errorMessage, '\n');
3151 /* Fire up post-connection housekeeping if needed */
3152 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3154 conn->status = CONNECTION_SETENV;
3155 conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
3156 conn->next_eo = EnvironmentOptions;
3157 return PGRES_POLLING_WRITING;
3161 * If a read-write connection is required, see if we have one.
3163 * Servers before 7.4 lack the transaction_read_only GUC, but
3164 * by the same token they don't have any read-only mode, so we
3165 * may just skip the test in that case.
3167 if (conn->sversion >= 70400 &&
3168 conn->target_session_attrs != NULL &&
3169 strcmp(conn->target_session_attrs, "read-write") == 0)
3172 * Save existing error messages across the PQsendQuery
3173 * attempt. This is necessary because PQsendQuery is
3174 * going to reset conn->errorMessage, so we would lose
3175 * error messages related to previous hosts we have tried
3176 * and failed to connect to.
3178 if (!saveErrorMessage(conn, &savedMessage))
3181 conn->status = CONNECTION_OK;
3182 if (!PQsendQuery(conn,
3183 "SHOW transaction_read_only"))
3185 restoreErrorMessage(conn, &savedMessage);
3188 conn->status = CONNECTION_CHECK_WRITABLE;
3189 restoreErrorMessage(conn, &savedMessage);
3190 return PGRES_POLLING_READING;
3193 /* We can release the address list now. */
3194 release_conn_addrinfo(conn);
3196 /* We are open for business! */
3197 conn->status = CONNECTION_OK;
3198 return PGRES_POLLING_OK;
3201 case CONNECTION_SETENV:
3204 * Do post-connection housekeeping (only needed in protocol 2.0).
3206 * We pretend that the connection is OK for the duration of these
3209 conn->status = CONNECTION_OK;
3211 switch (pqSetenvPoll(conn))
3213 case PGRES_POLLING_OK: /* Success */
3216 case PGRES_POLLING_READING: /* Still going */
3217 conn->status = CONNECTION_SETENV;
3218 return PGRES_POLLING_READING;
3220 case PGRES_POLLING_WRITING: /* Still going */
3221 conn->status = CONNECTION_SETENV;
3222 return PGRES_POLLING_WRITING;
3229 * If a read-write connection is required, see if we have one.
3230 * (This should match the stanza in the CONNECTION_AUTH_OK case
3233 * Servers before 7.4 lack the transaction_read_only GUC, but by
3234 * the same token they don't have any read-only mode, so we may
3235 * just skip the test in that case.
3237 if (conn->sversion >= 70400 &&
3238 conn->target_session_attrs != NULL &&
3239 strcmp(conn->target_session_attrs, "read-write") == 0)
3241 if (!saveErrorMessage(conn, &savedMessage))
3244 conn->status = CONNECTION_OK;
3245 if (!PQsendQuery(conn,
3246 "SHOW transaction_read_only"))
3248 restoreErrorMessage(conn, &savedMessage);
3251 conn->status = CONNECTION_CHECK_WRITABLE;
3252 restoreErrorMessage(conn, &savedMessage);
3253 return PGRES_POLLING_READING;
3256 /* We can release the address list now. */
3257 release_conn_addrinfo(conn);
3259 /* We are open for business! */
3260 conn->status = CONNECTION_OK;
3261 return PGRES_POLLING_OK;
3263 case CONNECTION_CONSUME:
3265 conn->status = CONNECTION_OK;
3266 if (!PQconsumeInput(conn))
3271 conn->status = CONNECTION_CONSUME;
3272 return PGRES_POLLING_READING;
3276 * Call PQgetResult() again to consume NULL result.
3278 res = PQgetResult(conn);
3282 conn->status = CONNECTION_CONSUME;
3286 /* We can release the address list now. */
3287 release_conn_addrinfo(conn);
3289 /* We are open for business! */
3290 conn->status = CONNECTION_OK;
3291 return PGRES_POLLING_OK;
3293 case CONNECTION_CHECK_WRITABLE:
3295 const char *displayed_host;
3296 const char *displayed_port;
3298 if (!saveErrorMessage(conn, &savedMessage))
3301 conn->status = CONNECTION_OK;
3302 if (!PQconsumeInput(conn))
3304 restoreErrorMessage(conn, &savedMessage);
3310 conn->status = CONNECTION_CHECK_WRITABLE;
3311 restoreErrorMessage(conn, &savedMessage);
3312 return PGRES_POLLING_READING;
3315 res = PQgetResult(conn);
3316 if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) &&
3317 PQntuples(res) == 1)
3321 val = PQgetvalue(res, 0, 0);
3322 if (strncmp(val, "on", 2) == 0)
3324 /* Not writable; fail this connection. */
3325 const char *displayed_host;
3326 const char *displayed_port;
3329 restoreErrorMessage(conn, &savedMessage);
3331 /* Append error report to conn->errorMessage. */
3332 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3333 displayed_host = conn->connhost[conn->whichhost].hostaddr;
3335 displayed_host = conn->connhost[conn->whichhost].host;
3336 displayed_port = conn->connhost[conn->whichhost].port;
3337 if (displayed_port == NULL || displayed_port[0] == '\0')
3338 displayed_port = DEF_PGPORT_STR;
3340 appendPQExpBuffer(&conn->errorMessage,
3341 libpq_gettext("could not make a writable "
3342 "connection to server "
3344 displayed_host, displayed_port);
3346 /* Close connection politely. */
3347 conn->status = CONNECTION_OK;
3348 sendTerminateConn(conn);
3351 * Try next host if any, but we don't want to consider
3352 * additional addresses for this host.
3354 conn->try_next_host = true;
3358 /* Session is read-write, so we're good. */
3360 termPQExpBuffer(&savedMessage);
3363 * Finish reading any remaining messages before being
3364 * considered as ready.
3366 conn->status = CONNECTION_CONSUME;
3371 * Something went wrong with "SHOW transaction_read_only". We
3372 * should try next addresses.
3376 restoreErrorMessage(conn, &savedMessage);
3378 /* Append error report to conn->errorMessage. */
3379 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3380 displayed_host = conn->connhost[conn->whichhost].hostaddr;
3382 displayed_host = conn->connhost[conn->whichhost].host;
3383 displayed_port = conn->connhost[conn->whichhost].port;
3384 if (displayed_port == NULL || displayed_port[0] == '\0')
3385 displayed_port = DEF_PGPORT_STR;
3386 appendPQExpBuffer(&conn->errorMessage,
3387 libpq_gettext("test \"SHOW transaction_read_only\" failed "
3388 "on server \"%s:%s\"\n"),
3389 displayed_host, displayed_port);
3391 /* Close connection politely. */
3392 conn->status = CONNECTION_OK;
3393 sendTerminateConn(conn);
3395 /* Try next address */
3396 conn->try_next_addr = true;
3401 appendPQExpBuffer(&conn->errorMessage,
3402 libpq_gettext("invalid connection state %d, "
3403 "probably indicative of memory corruption\n"),
3413 * We used to close the socket at this point, but that makes it awkward
3414 * for those above us if they wish to remove this socket from their own
3415 * records (an fd_set for example). We'll just have this socket closed
3416 * when PQfinish is called (which is compulsory even after an error, since
3417 * the connection structure must be freed).
3419 conn->status = CONNECTION_BAD;
3420 return PGRES_POLLING_FAILED;
3426 * Determine if a server is running and if we can connect to it.
3428 * The argument is a connection that's been started, but not completed.
3431 internal_ping(PGconn *conn)
3433 /* Say "no attempt" if we never got to PQconnectPoll */
3434 if (!conn || !conn->options_valid)
3435 return PQPING_NO_ATTEMPT;
3437 /* Attempt to complete the connection */
3438 if (conn->status != CONNECTION_BAD)
3439 (void) connectDBComplete(conn);
3441 /* Definitely OK if we succeeded */
3442 if (conn->status != CONNECTION_BAD)
3446 * Here begins the interesting part of "ping": determine the cause of the
3447 * failure in sufficient detail to decide what to return. We do not want
3448 * to report that the server is not up just because we didn't have a valid
3449 * password, for example. In fact, any sort of authentication request
3450 * implies the server is up. (We need this check since the libpq side of
3451 * things might have pulled the plug on the connection before getting an
3452 * error as such from the postmaster.)
3454 if (conn->auth_req_received)
3458 * If we failed to get any ERROR response from the postmaster, report
3459 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
3460 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
3461 * out of support. Another corner case where the server could return a
3462 * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
3463 * totally unreasonable for that anyway. We expect that every other
3464 * failure case in a modern server will produce a report with a SQLSTATE.
3466 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
3467 * client-side errors, we should either not store those into
3468 * last_sqlstate, or add an extra flag so we can tell client-side errors
3469 * apart from server-side ones.
3471 if (strlen(conn->last_sqlstate) != 5)
3472 return PQPING_NO_RESPONSE;
3475 * Report PQPING_REJECT if server says it's not accepting connections. (We
3476 * distinguish this case mainly for the convenience of pg_ctl.)
3478 if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
3479 return PQPING_REJECT;
3482 * Any other SQLSTATE can be taken to indicate that the server is up.
3483 * Presumably it didn't like our username, password, or database name; or
3484 * perhaps it had some transient failure, but that should not be taken as
3485 * meaning "it's down".
3493 * - create a PGconn data structure with (as yet) no interesting data
3496 makeEmptyPGconn(void)
3503 * Make sure socket support is up and running.
3507 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
3512 conn = (PGconn *) malloc(sizeof(PGconn));
3521 /* Zero all pointers and booleans */
3522 MemSet(conn, 0, sizeof(PGconn));
3524 /* install default notice hooks */
3525 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
3526 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
3528 conn->status = CONNECTION_BAD;
3529 conn->asyncStatus = PGASYNC_IDLE;
3530 conn->xactStatus = PQTRANS_IDLE;
3531 conn->options_valid = false;
3532 conn->nonblocking = false;
3533 conn->setenv_state = SETENV_STATE_IDLE;
3534 conn->client_encoding = PG_SQL_ASCII;
3535 conn->std_strings = false; /* unless server says differently */
3536 conn->verbosity = PQERRORS_DEFAULT;
3537 conn->show_context = PQSHOW_CONTEXT_ERRORS;
3538 conn->sock = PGINVALID_SOCKET;
3541 * We try to send at least 8K at a time, which is the usual size of pipe
3542 * buffers on Unix systems. That way, when we are sending a large amount
3543 * of data, we avoid incurring extra kernel context swaps for partial
3544 * bufferloads. The output buffer is initially made 16K in size, and we
3545 * try to dump it after accumulating 8K.
3547 * With the same goal of minimizing context swaps, the input buffer will
3548 * be enlarged anytime it has less than 8K free, so we initially allocate
3551 conn->inBufSize = 16 * 1024;
3552 conn->inBuffer = (char *) malloc(conn->inBufSize);
3553 conn->outBufSize = 16 * 1024;
3554 conn->outBuffer = (char *) malloc(conn->outBufSize);
3555 conn->rowBufLen = 32;
3556 conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
3557 initPQExpBuffer(&conn->errorMessage);
3558 initPQExpBuffer(&conn->workBuffer);
3560 if (conn->inBuffer == NULL ||
3561 conn->outBuffer == NULL ||
3562 conn->rowBuf == NULL ||
3563 PQExpBufferBroken(&conn->errorMessage) ||
3564 PQExpBufferBroken(&conn->workBuffer))
3566 /* out of memory already :-( */
3576 * - free an idle (closed) PGconn data structure
3578 * NOTE: this should not overlap any functionality with closePGconn().
3579 * Clearing/resetting of transient state belongs there; what we do here is
3580 * release data that is to be held for the life of the PGconn structure.
3581 * If a value ought to be cleared/freed during PQreset(), do it there not here.
3584 freePGconn(PGconn *conn)
3588 /* let any event procs clean up their state data */
3589 for (i = 0; i < conn->nEvents; i++)
3591 PGEventConnDestroy evt;
3594 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
3595 conn->events[i].passThrough);
3596 free(conn->events[i].name);
3599 /* clean up pg_conn_host structures */
3600 if (conn->connhost != NULL)
3602 for (i = 0; i < conn->nconnhost; ++i)
3604 if (conn->connhost[i].host != NULL)
3605 free(conn->connhost[i].host);
3606 if (conn->connhost[i].hostaddr != NULL)
3607 free(conn->connhost[i].hostaddr);
3608 if (conn->connhost[i].port != NULL)
3609 free(conn->connhost[i].port);
3610 if (conn->connhost[i].password != NULL)
3611 free(conn->connhost[i].password);
3613 free(conn->connhost);
3616 if (conn->client_encoding_initial)
3617 free(conn->client_encoding_initial);
3622 if (conn->pghostaddr)
3623 free(conn->pghostaddr);
3628 if (conn->connect_timeout)
3629 free(conn->connect_timeout);
3630 if (conn->pgoptions)
3631 free(conn->pgoptions);
3633 free(conn->appname);
3634 if (conn->fbappname)
3635 free(conn->fbappname);
3638 if (conn->replication)
3639 free(conn->replication);
3644 if (conn->pgpassfile)
3645 free(conn->pgpassfile);
3646 if (conn->keepalives)
3647 free(conn->keepalives);
3648 if (conn->keepalives_idle)
3649 free(conn->keepalives_idle);
3650 if (conn->keepalives_interval)
3651 free(conn->keepalives_interval);
3652 if (conn->keepalives_count)
3653 free(conn->keepalives_count);
3655 free(conn->sslmode);
3657 free(conn->sslcert);
3660 if (conn->sslrootcert)
3661 free(conn->sslrootcert);
3664 if (conn->sslcompression)
3665 free(conn->sslcompression);
3666 if (conn->requirepeer)
3667 free(conn->requirepeer);
3668 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3669 if (conn->krbsrvname)
3670 free(conn->krbsrvname);
3672 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
3676 /* Note that conn->Pfdebug is not ours to close or free */
3677 if (conn->last_query)
3678 free(conn->last_query);
3680 free(conn->inBuffer);
3681 if (conn->outBuffer)
3682 free(conn->outBuffer);
3685 if (conn->target_session_attrs)
3686 free(conn->target_session_attrs);
3687 termPQExpBuffer(&conn->errorMessage);
3688 termPQExpBuffer(&conn->workBuffer);
3698 * release_conn_addrinfo
3699 * - Free any addrinfo list in the PGconn.
3702 release_conn_addrinfo(PGconn *conn)
3706 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
3707 conn->addrlist = NULL;
3708 conn->addr_cur = NULL; /* for safety */
3714 * - Send a terminate message to backend.
3717 sendTerminateConn(PGconn *conn)
3720 * Note that the protocol doesn't allow us to send Terminate messages
3721 * during the startup phase.
3723 if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
3726 * Try to send "close connection" message to backend. Ignore any
3729 pqPutMsgStart('X', false, conn);
3731 (void) pqFlush(conn);
3737 * - properly close a connection to the backend
3739 * This should reset or release all transient state, but NOT the connection
3740 * parameters. On exit, the PGconn should be in condition to start a fresh
3741 * connection with the same parameters (see PQreset()).
3744 closePGconn(PGconn *conn)
3747 * If possible, send Terminate message to close the connection politely.
3749 sendTerminateConn(conn);
3752 * Must reset the blocking status so a possible reconnect will work.
3754 * Don't call PQsetnonblocking() because it will fail if it's unable to
3755 * flush the connection.
3757 conn->nonblocking = false;
3760 * Close the connection, reset all transient state, flush I/O buffers.
3762 pqDropConnection(conn, true);
3763 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
3764 conn->asyncStatus = PGASYNC_IDLE;
3765 conn->xactStatus = PQTRANS_IDLE;
3766 pqClearAsyncResult(conn); /* deallocate result */
3767 resetPQExpBuffer(&conn->errorMessage);
3768 release_conn_addrinfo(conn);
3770 /* Reset all state obtained from server, too */
3771 pqDropServerData(conn);
3775 * PQfinish: properly close a connection to the backend. Also frees
3776 * the PGconn data structure so it shouldn't be re-used after this.
3779 PQfinish(PGconn *conn)
3789 * PQreset: resets the connection to the backend by closing the
3790 * existing connection and creating a new one.
3793 PQreset(PGconn *conn)
3799 if (connectDBStart(conn) && connectDBComplete(conn))
3802 * Notify event procs of successful reset. We treat an event proc
3803 * failure as disabling the connection ... good idea?
3807 for (i = 0; i < conn->nEvents; i++)
3809 PGEventConnReset evt;
3812 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3813 conn->events[i].passThrough))
3815 conn->status = CONNECTION_BAD;
3816 printfPQExpBuffer(&conn->errorMessage,
3817 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3818 conn->events[i].name);
3829 * resets the connection to the backend
3830 * closes the existing connection and makes a new one
3831 * Returns 1 on success, 0 on failure.
3834 PQresetStart(PGconn *conn)
3840 return connectDBStart(conn);
3849 * resets the connection to the backend
3850 * closes the existing connection and makes a new one
3852 PostgresPollingStatusType
3853 PQresetPoll(PGconn *conn)
3857 PostgresPollingStatusType status = PQconnectPoll(conn);
3859 if (status == PGRES_POLLING_OK)
3862 * Notify event procs of successful reset. We treat an event proc
3863 * failure as disabling the connection ... good idea?
3867 for (i = 0; i < conn->nEvents; i++)
3869 PGEventConnReset evt;
3872 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3873 conn->events[i].passThrough))
3875 conn->status = CONNECTION_BAD;
3876 printfPQExpBuffer(&conn->errorMessage,
3877 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3878 conn->events[i].name);
3879 return PGRES_POLLING_FAILED;
3887 return PGRES_POLLING_FAILED;
3891 * PQgetCancel: get a PGcancel structure corresponding to a connection.
3893 * A copy is needed to be able to cancel a running query from a different
3894 * thread. If the same structure is used all structure members would have
3895 * to be individually locked (if the entire structure was locked, it would
3896 * be impossible to cancel a synchronous query because the structure would
3897 * have to stay locked for the duration of the query).
3900 PQgetCancel(PGconn *conn)
3907 if (conn->sock == PGINVALID_SOCKET)
3910 cancel = malloc(sizeof(PGcancel));
3914 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
3915 cancel->be_pid = conn->be_pid;
3916 cancel->be_key = conn->be_key;
3921 /* PQfreeCancel: free a cancel structure */
3923 PQfreeCancel(PGcancel *cancel)
3931 * PQcancel and PQrequestCancel: attempt to request cancellation of the
3932 * current operation.
3934 * The return value is true if the cancel request was successfully
3935 * dispatched, false if not (in which case an error message is available).
3936 * Note: successful dispatch is no guarantee that there will be any effect at
3937 * the backend. The application must read the operation result as usual.
3939 * CAUTION: we want this routine to be safely callable from a signal handler
3940 * (for example, an application might want to call it in a SIGINT handler).
3941 * This means we cannot use any C library routine that might be non-reentrant.
3942 * malloc/free are often non-reentrant, and anything that might call them is
3943 * just as dangerous. We avoid sprintf here for that reason. Building up
3944 * error messages with strcpy/strcat is tedious but should be quite safe.
3945 * We also save/restore errno in case the signal handler support doesn't.
3947 * internal_cancel() is an internal helper function to make code-sharing
3948 * between the two versions of the cancel function possible.
3951 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
3952 char *errbuf, int errbufsize)
3954 int save_errno = SOCK_ERRNO;
3955 pgsocket tmpsock = PGINVALID_SOCKET;
3956 char sebuf[PG_STRERROR_R_BUFLEN];
3961 CancelRequestPacket cp;
3965 * We need to open a temporary connection to the postmaster. Do this with
3966 * only kernel calls.
3968 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
3970 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
3971 goto cancel_errReturn;
3974 if (connect(tmpsock, (struct sockaddr *) &raddr->addr,
3977 if (SOCK_ERRNO == EINTR)
3978 /* Interrupted system call - we'll just try again */
3980 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
3981 goto cancel_errReturn;
3985 * We needn't set nonblocking I/O or NODELAY options here.
3988 /* Create and send the cancel request packet. */
3990 crp.packetlen = pg_hton32((uint32) sizeof(crp));
3991 crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
3992 crp.cp.backendPID = pg_hton32(be_pid);
3993 crp.cp.cancelAuthCode = pg_hton32(be_key);
3996 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
3998 if (SOCK_ERRNO == EINTR)
3999 /* Interrupted system call - we'll just try again */
4001 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4002 goto cancel_errReturn;
4006 * Wait for the postmaster to close the connection, which indicates that
4007 * it's processed the request. Without this delay, we might issue another
4008 * command only to find that our cancel zaps that command instead of the
4009 * one we thought we were canceling. Note we don't actually expect this
4010 * read to obtain any data, we are just waiting for EOF to be signaled.
4013 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4015 if (SOCK_ERRNO == EINTR)
4016 /* Interrupted system call - we'll just try again */
4018 /* we ignore other error conditions */
4022 closesocket(tmpsock);
4023 SOCK_ERRNO_SET(save_errno);
4029 * Make sure we don't overflow the error buffer. Leave space for the \n at
4030 * the end, and for the terminating zero.
4032 maxlen = errbufsize - strlen(errbuf) - 2;
4035 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
4037 strcat(errbuf, "\n");
4039 if (tmpsock != PGINVALID_SOCKET)
4040 closesocket(tmpsock);
4041 SOCK_ERRNO_SET(save_errno);
4046 * PQcancel: request query cancel
4048 * Returns true if able to send the cancel request, false if not.
4050 * On failure, an error message is stored in *errbuf, which must be of size
4051 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
4055 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
4059 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4063 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
4064 errbuf, errbufsize);
4068 * PQrequestCancel: old, not thread-safe function for requesting query cancel
4070 * Returns true if able to send the cancel request, false if not.
4072 * On failure, the error message is saved in conn->errorMessage; this means
4073 * that this can't be used when there might be other active operations on
4074 * the connection object.
4076 * NOTE: error messages will be cut off at the current size of the
4077 * error message buffer, since we dare not try to expand conn->errorMessage!
4080 PQrequestCancel(PGconn *conn)
4084 /* Check we have an open connection */
4088 if (conn->sock == PGINVALID_SOCKET)
4090 strlcpy(conn->errorMessage.data,
4091 "PQrequestCancel() -- connection is not open\n",
4092 conn->errorMessage.maxlen);
4093 conn->errorMessage.len = strlen(conn->errorMessage.data);
4098 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
4099 conn->errorMessage.data, conn->errorMessage.maxlen);
4102 conn->errorMessage.len = strlen(conn->errorMessage.data);
4109 * pqPacketSend() -- convenience routine to send a message to server.
4111 * pack_type: the single-byte message type code. (Pass zero for startup
4112 * packets, which have no message type code.)
4114 * buf, buf_len: contents of message. The given length includes only what
4115 * is in buf; the message type and message length fields are added here.
4117 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4118 * SIDE_EFFECTS: may block.
4120 * Note: all messages sent with this routine have a length word, whether
4121 * it's protocol 2.0 or 3.0.
4124 pqPacketSend(PGconn *conn, char pack_type,
4125 const void *buf, size_t buf_len)
4127 /* Start the message. */
4128 if (pqPutMsgStart(pack_type, true, conn))
4129 return STATUS_ERROR;
4131 /* Send the message body. */
4132 if (pqPutnchar(buf, buf_len, conn))
4133 return STATUS_ERROR;
4135 /* Finish the message. */
4136 if (pqPutMsgEnd(conn))
4137 return STATUS_ERROR;
4139 /* Flush to ensure backend gets it. */
4141 return STATUS_ERROR;
4148 #define LDAP_URL "ldap://"
4149 #define LDAP_DEF_PORT 389
4150 #define PGLDAP_TIMEOUT 2
4152 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4153 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4159 * Search the LDAP URL passed as first argument, treat the result as a
4160 * string of connection options that are parsed and added to the array of
4161 * options passed as second argument.
4163 * LDAP URLs must conform to RFC 1959 without escape sequences.
4164 * ldap://host:port/dn?attributes?scope?filter?extensions
4167 * 0 if the lookup was successful,
4168 * 1 if the connection to the LDAP server could be established but
4169 * the search was unsuccessful,
4170 * 2 if a connection could not be established, and
4171 * 3 if a fatal error occurred.
4173 * An error message is returned in the third argument for return codes 1 and 3.
4176 ldapServiceLookup(const char *purl, PQconninfoOption *options,
4177 PQExpBuffer errorMessage)
4179 int port = LDAP_DEF_PORT,
4202 char *attrs[2] = {NULL, NULL};
4206 struct berval **values;
4207 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4209 if ((url = strdup(purl)) == NULL)
4211 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4216 * Parse URL components, check for correctness. Basically, url has '\0'
4217 * placed at component boundaries and variables are pointed at each
4221 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
4223 printfPQExpBuffer(errorMessage,
4224 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
4230 hostname = url + strlen(LDAP_URL);
4231 if (*hostname == '/') /* no hostname? */
4232 hostname = DefaultHost; /* the default */
4234 /* dn, "distinguished name" */
4235 p = strchr(url + strlen(LDAP_URL), '/');
4236 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4238 printfPQExpBuffer(errorMessage, libpq_gettext(
4239 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
4243 *p = '\0'; /* terminate hostname */
4247 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4249 printfPQExpBuffer(errorMessage, libpq_gettext(
4250 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
4258 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4260 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4268 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4270 printfPQExpBuffer(errorMessage,
4271 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
4277 if ((p = strchr(filter, '?')) != NULL)
4281 if ((p1 = strchr(hostname, ':')) != NULL)
4288 lport = strtol(portstr, &endptr, 10);
4289 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
4291 printfPQExpBuffer(errorMessage, libpq_gettext(
4292 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
4299 /* Allow only one attribute */
4300 if (strchr(attrs[0], ',') != NULL)
4302 printfPQExpBuffer(errorMessage, libpq_gettext(
4303 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
4309 if (pg_strcasecmp(scopestr, "base") == 0)
4310 scope = LDAP_SCOPE_BASE;
4311 else if (pg_strcasecmp(scopestr, "one") == 0)
4312 scope = LDAP_SCOPE_ONELEVEL;
4313 else if (pg_strcasecmp(scopestr, "sub") == 0)
4314 scope = LDAP_SCOPE_SUBTREE;
4317 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4322 /* initialize LDAP structure */
4323 if ((ld = ldap_init(hostname, port)) == NULL)
4325 printfPQExpBuffer(errorMessage,
4326 libpq_gettext("could not create LDAP structure\n"));
4332 * Perform an explicit anonymous bind.
4334 * LDAP does not require that an anonymous bind is performed explicitly,
4335 * but we want to distinguish between the case where LDAP bind does not
4336 * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
4337 * service control file) and the case where querying the LDAP server fails
4338 * (return 1 to end parsing).
4340 * Unfortunately there is no way of setting a timeout that works for both
4341 * Windows and OpenLDAP.
4344 /* the nonstandard ldap_connect function performs an anonymous bind */
4345 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
4347 /* error or timeout in ldap_connect */
4353 /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
4354 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4361 /* anonymous bind */
4362 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
4364 /* error or network timeout */
4370 /* wait some time for the connection to succeed */
4372 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
4375 /* error or timeout */
4386 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4396 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
4401 printfPQExpBuffer(errorMessage,
4402 libpq_gettext("lookup on LDAP server failed: %s\n"),
4403 ldap_err2string(rc));
4409 /* complain if there was not exactly one result */
4410 if ((rc = ldap_count_entries(ld, res)) != 1)
4412 printfPQExpBuffer(errorMessage,
4413 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
4414 : libpq_gettext("no entry found on LDAP lookup\n"));
4422 if ((entry = ldap_first_entry(ld, res)) == NULL)
4424 /* should never happen */
4425 printfPQExpBuffer(errorMessage,
4426 libpq_gettext("no entry found on LDAP lookup\n"));
4434 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
4436 printfPQExpBuffer(errorMessage,
4437 libpq_gettext("attribute has no values on LDAP lookup\n"));
4447 if (values[0] == NULL)
4449 printfPQExpBuffer(errorMessage,
4450 libpq_gettext("attribute has no values on LDAP lookup\n"));
4451 ldap_value_free_len(values);
4456 /* concatenate values into a single string with newline terminators */
4457 size = 1; /* for the trailing null */
4458 for (i = 0; values[i] != NULL; i++)
4459 size += values[i]->bv_len + 1;
4460 if ((result = malloc(size)) == NULL)
4462 printfPQExpBuffer(errorMessage,
4463 libpq_gettext("out of memory\n"));
4464 ldap_value_free_len(values);
4469 for (i = 0; values[i] != NULL; i++)
4471 memcpy(p, values[i]->bv_val, values[i]->bv_len);
4472 p += values[i]->bv_len;
4477 ldap_value_free_len(values);
4480 /* parse result string */
4481 oldstate = state = 0;
4482 for (p = result; *p != '\0'; ++p)
4486 case 0: /* between entries */
4487 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
4493 case 1: /* in option name */
4494 if (ld_is_sp_tab(*p))
4499 else if (ld_is_nl_cr(*p))
4501 printfPQExpBuffer(errorMessage, libpq_gettext(
4502 "missing \"=\" after \"%s\" in connection info string\n"),
4513 case 2: /* after option name */
4518 else if (!ld_is_sp_tab(*p))
4520 printfPQExpBuffer(errorMessage, libpq_gettext(
4521 "missing \"=\" after \"%s\" in connection info string\n"),
4527 case 3: /* before option value */
4534 else if (ld_is_nl_cr(*p))
4536 optval = optname + strlen(optname); /* empty */
4539 else if (!ld_is_sp_tab(*p))
4545 case 4: /* in unquoted option value */
4546 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
4552 case 5: /* in quoted option value */
4558 else if (*p == '\\')
4563 case 6: /* in quoted option value after escape */
4569 if (state == 0 && oldstate != 0)
4571 found_keyword = false;
4572 for (i = 0; options[i].keyword; i++)
4574 if (strcmp(options[i].keyword, optname) == 0)
4576 if (options[i].val == NULL)
4578 options[i].val = strdup(optval);
4579 if (!options[i].val)
4581 printfPQExpBuffer(errorMessage,
4582 libpq_gettext("out of memory\n"));
4587 found_keyword = true;
4593 printfPQExpBuffer(errorMessage,
4594 libpq_gettext("invalid connection option \"%s\"\n"),
4607 if (state == 5 || state == 6)
4609 printfPQExpBuffer(errorMessage, libpq_gettext(
4610 "unterminated quoted string in connection info string\n"));
4617 #endif /* USE_LDAP */
4619 #define MAXBUFSIZE 256
4622 * parseServiceInfo: if a service name has been given, look it up and absorb
4623 * connection options from it into *options.
4625 * Returns 0 on success, nonzero on failure. On failure, if errorMessage
4626 * isn't null, also store an error message there. (Note: the only reason
4627 * this function and related ones don't dump core on errorMessage == NULL
4628 * is the undocumented fact that printfPQExpBuffer does nothing when passed
4629 * a null PQExpBuffer pointer.)
4632 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
4634 const char *service = conninfo_getval(options, "service");
4635 char serviceFile[MAXPGPATH];
4637 bool group_found = false;
4639 struct stat stat_buf;
4642 * We have to special-case the environment variable PGSERVICE here, since
4643 * this is and should be called before inserting environment defaults for
4644 * other connection options.
4646 if (service == NULL)
4647 service = getenv("PGSERVICE");
4649 /* If no service name given, nothing to do */
4650 if (service == NULL)
4654 * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
4657 if ((env = getenv("PGSERVICEFILE")) != NULL)
4658 strlcpy(serviceFile, env, sizeof(serviceFile));
4661 char homedir[MAXPGPATH];
4663 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
4665 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
4666 if (stat(serviceFile, &stat_buf) != 0)
4670 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
4671 if (group_found || status != 0)
4677 * This could be used by any application so we can't use the binary
4678 * location to find our config files.
4680 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
4681 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
4682 if (stat(serviceFile, &stat_buf) != 0)
4685 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
4692 printfPQExpBuffer(errorMessage,
4693 libpq_gettext("definition of service \"%s\" not found\n"), service);
4701 parseServiceFile(const char *serviceFile,
4702 const char *service,
4703 PQconninfoOption *options,
4704 PQExpBuffer errorMessage,
4710 char buf[MAXBUFSIZE],
4713 f = fopen(serviceFile, "r");
4716 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
4721 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
4725 if (strlen(line) >= sizeof(buf) - 1)
4728 printfPQExpBuffer(errorMessage,
4729 libpq_gettext("line %d too long in service file \"%s\"\n"),
4735 /* ignore EOL at end of line */
4736 if (strlen(line) && line[strlen(line) - 1] == '\n')
4737 line[strlen(line) - 1] = 0;
4739 /* ignore leading blanks */
4740 while (*line && isspace((unsigned char) line[0]))
4743 /* ignore comments and empty lines */
4744 if (strlen(line) == 0 || line[0] == '#')
4747 /* Check for right groupname */
4752 /* group info already read */
4757 if (strncmp(line + 1, service, strlen(service)) == 0 &&
4758 line[strlen(service) + 1] == ']')
4759 *group_found = true;
4761 *group_found = false;
4768 * Finally, we are in the right group and can parse the line
4775 if (strncmp(line, "ldap", 4) == 0)
4777 int rc = ldapServiceLookup(line, options, errorMessage);
4779 /* if rc = 2, go on reading for fallback */
4796 val = strchr(line, '=');
4799 printfPQExpBuffer(errorMessage,
4800 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
4808 if (strcmp(key, "service") == 0)
4810 printfPQExpBuffer(errorMessage,
4811 libpq_gettext("nested service specifications not supported in service file \"%s\", line %d\n"),
4819 * Set the parameter --- but don't override any previous
4822 found_keyword = false;
4823 for (i = 0; options[i].keyword; i++)
4825 if (strcmp(options[i].keyword, key) == 0)
4827 if (options[i].val == NULL)
4828 options[i].val = strdup(val);
4829 if (!options[i].val)
4831 printfPQExpBuffer(errorMessage,
4832 libpq_gettext("out of memory\n"));
4836 found_keyword = true;
4843 printfPQExpBuffer(errorMessage,
4844 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
4863 * Parse a string like PQconnectdb() would do and return the
4864 * resulting connection options array. NULL is returned on failure.
4865 * The result contains only options specified directly in the string,
4866 * not any possible default values.
4868 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
4869 * string on failure (use PQfreemem to free it). In out-of-memory conditions
4870 * both *errmsg and the result could be NULL.
4872 * NOTE: the returned array is dynamically allocated and should
4873 * be freed when no longer needed via PQconninfoFree().
4876 PQconninfoParse(const char *conninfo, char **errmsg)
4878 PQExpBufferData errorBuf;
4879 PQconninfoOption *connOptions;
4882 *errmsg = NULL; /* default */
4883 initPQExpBuffer(&errorBuf);
4884 if (PQExpBufferDataBroken(errorBuf))
4885 return NULL; /* out of memory already :-( */
4886 connOptions = parse_connection_string(conninfo, &errorBuf, false);
4887 if (connOptions == NULL && errmsg)
4888 *errmsg = errorBuf.data;
4890 termPQExpBuffer(&errorBuf);
4895 * Build a working copy of the constant PQconninfoOptions array.
4897 static PQconninfoOption *
4898 conninfo_init(PQExpBuffer errorMessage)
4900 PQconninfoOption *options;
4901 PQconninfoOption *opt_dest;
4902 const internalPQconninfoOption *cur_opt;
4905 * Get enough memory for all options in PQconninfoOptions, even if some
4906 * end up being filtered out.
4908 options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4909 if (options == NULL)
4911 printfPQExpBuffer(errorMessage,
4912 libpq_gettext("out of memory\n"));
4917 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4919 /* Only copy the public part of the struct, not the full internal */
4920 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4923 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4929 * Connection string parser
4931 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4932 * Otherwise, NULL is returned and an error message is left in errorMessage.
4934 * If use_defaults is true, default values are filled in (from a service file,
4935 * environment variables, etc).
4937 static PQconninfoOption *
4938 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4941 /* Parse as URI if connection string matches URI prefix */
4942 if (uri_prefix_length(connstr) != 0)
4943 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4945 /* Parse as default otherwise */
4946 return conninfo_parse(connstr, errorMessage, use_defaults);
4950 * Checks if connection string starts with either of the valid URI prefix
4953 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4955 * XXX this is duplicated in psql/common.c.
4958 uri_prefix_length(const char *connstr)
4960 if (strncmp(connstr, uri_designator,
4961 sizeof(uri_designator) - 1) == 0)
4962 return sizeof(uri_designator) - 1;
4964 if (strncmp(connstr, short_uri_designator,
4965 sizeof(short_uri_designator) - 1) == 0)
4966 return sizeof(short_uri_designator) - 1;
4972 * Recognized connection string either starts with a valid URI prefix or
4973 * contains a "=" in it.
4975 * Must be consistent with parse_connection_string: anything for which this
4976 * returns true should at least look like it's parseable by that routine.
4978 * XXX this is duplicated in psql/common.c
4981 recognized_connection_string(const char *connstr)
4983 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4987 * Subroutine for parse_connection_string
4989 * Deal with a string containing key=value pairs.
4991 static PQconninfoOption *
4992 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
5000 PQconninfoOption *options;
5002 /* Make a working copy of PQconninfoOptions */
5003 options = conninfo_init(errorMessage);
5004 if (options == NULL)
5007 /* Need a modifiable copy of the input string */
5008 if ((buf = strdup(conninfo)) == NULL)
5010 printfPQExpBuffer(errorMessage,
5011 libpq_gettext("out of memory\n"));
5012 PQconninfoFree(options);
5019 /* Skip blanks before the parameter name */
5020 if (isspace((unsigned char) *cp))
5026 /* Get the parameter name */
5032 if (isspace((unsigned char) *cp))
5037 if (!isspace((unsigned char) *cp))
5046 /* Check that there is a following '=' */
5049 printfPQExpBuffer(errorMessage,
5050 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
5052 PQconninfoFree(options);
5058 /* Skip blanks after the '=' */
5061 if (!isspace((unsigned char) *cp))
5066 /* Get the parameter value */
5074 if (isspace((unsigned char) *cp))
5098 printfPQExpBuffer(errorMessage,
5099 libpq_gettext("unterminated quoted string in connection info string\n"));
5100 PQconninfoFree(options);
5122 * Now that we have the name and the value, store the record.
5124 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5126 PQconninfoFree(options);
5132 /* Done with the modifiable input string */
5136 * Add in defaults if the caller wants that.
5140 if (!conninfo_add_defaults(options, errorMessage))
5142 PQconninfoFree(options);
5151 * Conninfo array parser routine
5153 * If successful, a malloc'd PQconninfoOption array is returned.
5154 * If not successful, NULL is returned and an error message is
5155 * left in errorMessage.
5156 * Defaults are supplied (from a service file, environment variables, etc)
5157 * for unspecified options, but only if use_defaults is true.
5159 * If expand_dbname is non-zero, and the value passed for the first occurrence
5160 * of "dbname" keyword is a connection string (as indicated by
5161 * recognized_connection_string) then parse and process it, overriding any
5162 * previously processed conflicting keywords. Subsequent keywords will take
5163 * precedence, however. In-tree programs generally specify expand_dbname=true,
5164 * so command-line arguments naming a database can use a connection string.
5165 * Some code acquires arbitrary database names from known-literal sources like
5166 * PQdb(), PQconninfoParse() and pg_database.datname. When connecting to such
5167 * a database, in-tree code first wraps the name in a connection string.
5169 static PQconninfoOption *
5170 conninfo_array_parse(const char *const *keywords, const char *const *values,
5171 PQExpBuffer errorMessage, bool use_defaults,
5174 PQconninfoOption *options;
5175 PQconninfoOption *dbname_options = NULL;
5176 PQconninfoOption *option;
5180 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
5181 * actually a recognized connection string.
5183 while (expand_dbname && keywords[i])
5185 const char *pname = keywords[i];
5186 const char *pvalue = values[i];
5188 /* first find "dbname" if any */
5189 if (strcmp(pname, "dbname") == 0 && pvalue)
5192 * If value is a connection string, parse it, but do not use
5193 * defaults here -- those get picked up later. We only want to
5194 * override for those parameters actually passed.
5196 if (recognized_connection_string(pvalue))
5198 dbname_options = parse_connection_string(pvalue, errorMessage, false);
5199 if (dbname_options == NULL)
5207 /* Make a working copy of PQconninfoOptions */
5208 options = conninfo_init(errorMessage);
5209 if (options == NULL)
5211 PQconninfoFree(dbname_options);
5215 /* Parse the keywords/values arrays */
5219 const char *pname = keywords[i];
5220 const char *pvalue = values[i];
5222 if (pvalue != NULL && pvalue[0] != '\0')
5224 /* Search for the param record */
5225 for (option = options; option->keyword != NULL; option++)
5227 if (strcmp(option->keyword, pname) == 0)
5231 /* Check for invalid connection option */
5232 if (option->keyword == NULL)
5234 printfPQExpBuffer(errorMessage,
5235 libpq_gettext("invalid connection option \"%s\"\n"),
5237 PQconninfoFree(options);
5238 PQconninfoFree(dbname_options);
5243 * If we are on the first dbname parameter, and we have a parsed
5244 * connection string, copy those parameters across, overriding any
5245 * existing previous settings.
5247 if (strcmp(pname, "dbname") == 0 && dbname_options)
5249 PQconninfoOption *str_option;
5251 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
5253 if (str_option->val != NULL)
5257 for (k = 0; options[k].keyword; k++)
5259 if (strcmp(options[k].keyword, str_option->keyword) == 0)
5262 free(options[k].val);
5263 options[k].val = strdup(str_option->val);
5264 if (!options[k].val)
5266 printfPQExpBuffer(errorMessage,
5267 libpq_gettext("out of memory\n"));
5268 PQconninfoFree(options);
5269 PQconninfoFree(dbname_options);
5279 * Forget the parsed connection string, so that any subsequent
5280 * dbname parameters will not be expanded.
5282 PQconninfoFree(dbname_options);
5283 dbname_options = NULL;
5288 * Store the value, overriding previous settings
5292 option->val = strdup(pvalue);
5295 printfPQExpBuffer(errorMessage,
5296 libpq_gettext("out of memory\n"));
5297 PQconninfoFree(options);
5298 PQconninfoFree(dbname_options);
5305 PQconninfoFree(dbname_options);
5308 * Add in defaults if the caller wants that.
5312 if (!conninfo_add_defaults(options, errorMessage))
5314 PQconninfoFree(options);
5323 * Add the default values for any unspecified options to the connection
5326 * Defaults are obtained from a service file, environment variables, etc.
5328 * Returns true if successful, otherwise false; errorMessage, if supplied,
5329 * is filled in upon failure. Note that failure to locate a default value
5330 * is not an error condition here --- we just leave the option's value as
5334 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
5336 PQconninfoOption *option;
5340 * If there's a service spec, use it to obtain any not-explicitly-given
5341 * parameters. Ignore error if no error message buffer is passed because
5342 * there is no way to pass back the failure message.
5344 if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
5348 * Get the fallback resources for parameters not specified in the conninfo
5349 * string nor the service.
5351 for (option = options; option->keyword != NULL; option++)
5353 if (option->val != NULL)
5354 continue; /* Value was in conninfo or service */
5357 * Try to get the environment variable fallback
5359 if (option->envvar != NULL)
5361 if ((tmp = getenv(option->envvar)) != NULL)
5363 option->val = strdup(tmp);
5367 printfPQExpBuffer(errorMessage,
5368 libpq_gettext("out of memory\n"));
5376 * Interpret the deprecated PGREQUIRESSL environment variable. Per
5377 * tradition, translate values starting with "1" to sslmode=require,
5378 * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
5379 * PGSSLMODE takes precedence; the opposite was true before v9.3.
5381 if (strcmp(option->keyword, "sslmode") == 0)
5383 const char *requiresslenv = getenv("PGREQUIRESSL");
5385 if (requiresslenv != NULL && requiresslenv[0] == '1')
5387 option->val = strdup("require");
5391 printfPQExpBuffer(errorMessage,
5392 libpq_gettext("out of memory\n"));
5400 * No environment variable specified or the variable isn't set - try
5401 * compiled-in default
5403 if (option->compiled != NULL)
5405 option->val = strdup(option->compiled);
5409 printfPQExpBuffer(errorMessage,
5410 libpq_gettext("out of memory\n"));
5417 * Special handling for "user" option. Note that if pg_fe_getauthname
5418 * fails, we just leave the value as NULL; there's no need for this to
5419 * be an error condition if the caller provides a user name. The only
5420 * reason we do this now at all is so that callers of PQconndefaults
5421 * will see a correct default (barring error, of course).
5423 if (strcmp(option->keyword, "user") == 0)
5425 option->val = pg_fe_getauthname(NULL);
5434 * Subroutine for parse_connection_string
5436 * Deal with a URI connection string.
5438 static PQconninfoOption *
5439 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
5442 PQconninfoOption *options;
5444 /* Make a working copy of PQconninfoOptions */
5445 options = conninfo_init(errorMessage);
5446 if (options == NULL)
5449 if (!conninfo_uri_parse_options(options, uri, errorMessage))
5451 PQconninfoFree(options);
5456 * Add in defaults if the caller wants that.
5460 if (!conninfo_add_defaults(options, errorMessage))
5462 PQconninfoFree(options);
5471 * conninfo_uri_parse_options
5472 * Actual URI parser.
5474 * If successful, returns true while the options array is filled with parsed
5475 * options from the URI.
5476 * If not successful, returns false and fills errorMessage accordingly.
5478 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
5481 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
5483 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
5484 * by literal square brackets. As an extension, we also allow multiple
5485 * netloc[:port] specifications, separated by commas:
5487 * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
5489 * Any of the URI parts might use percent-encoding (%xy).
5492 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
5493 PQExpBuffer errorMessage)
5499 char prevchar = '\0';
5502 bool retval = false;
5503 PQExpBufferData hostbuf;
5504 PQExpBufferData portbuf;
5506 initPQExpBuffer(&hostbuf);
5507 initPQExpBuffer(&portbuf);
5508 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
5510 printfPQExpBuffer(errorMessage,
5511 libpq_gettext("out of memory\n"));
5515 /* need a modifiable copy of the input URI */
5519 printfPQExpBuffer(errorMessage,
5520 libpq_gettext("out of memory\n"));
5525 /* Skip the URI prefix */
5526 prefix_len = uri_prefix_length(uri);
5527 if (prefix_len == 0)
5529 /* Should never happen */
5530 printfPQExpBuffer(errorMessage,
5531 libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
5535 start += prefix_len;
5538 /* Look ahead for possible user credentials designator */
5539 while (*p && *p != '@' && *p != '/')
5544 * Found username/password designator, so URI should be of the form
5545 * "scheme://user[:password]@[netloc]".
5550 while (*p != ':' && *p != '@')
5553 /* Save last char and cut off at end of user name */
5558 !conninfo_storeval(options, "user", user,
5559 errorMessage, false, true))
5562 if (prevchar == ':')
5564 const char *password = p + 1;
5571 !conninfo_storeval(options, "password", password,
5572 errorMessage, false, true))
5576 /* Advance past end of parsed user name or password token */
5582 * No username/password designator found. Reset to start of URI.
5588 * There may be multiple netloc[:port] pairs, each separated from the next
5589 * by a comma. When we initially enter this loop, "p" has been
5590 * incremented past optional URI credential information at this point and
5591 * now points at the "netloc" part of the URI. On subsequent loop
5592 * iterations, "p" has been incremented past the comma separator and now
5593 * points at the start of the next "netloc".
5598 * Look for IPv6 address.
5603 while (*p && *p != ']')
5607 printfPQExpBuffer(errorMessage,
5608 libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
5614 printfPQExpBuffer(errorMessage,
5615 libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
5620 /* Cut off the bracket and advance */
5624 * The address may be followed by a port specifier or a slash or a
5625 * query or a separator comma.
5627 if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
5629 printfPQExpBuffer(errorMessage,
5630 libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
5631 *p, (int) (p - buf + 1), uri);
5637 /* not an IPv6 address: DNS-named or IPv4 netloc */
5641 * Look for port specifier (colon) or end of host specifier
5642 * (slash) or query (question mark) or host separator (comma).
5644 while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
5648 /* Save the hostname terminator before we null it */
5652 appendPQExpBufferStr(&hostbuf, host);
5654 if (prevchar == ':')
5656 const char *port = ++p; /* advance past host terminator */
5658 while (*p && *p != '/' && *p != '?' && *p != ',')
5664 appendPQExpBufferStr(&portbuf, port);
5667 if (prevchar != ',')
5669 ++p; /* advance past comma separator */
5670 appendPQExpBufferChar(&hostbuf, ',');
5671 appendPQExpBufferChar(&portbuf, ',');
5674 /* Save final values for host and port. */
5675 if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
5677 if (hostbuf.data[0] &&
5678 !conninfo_storeval(options, "host", hostbuf.data,
5679 errorMessage, false, true))
5681 if (portbuf.data[0] &&
5682 !conninfo_storeval(options, "port", portbuf.data,
5683 errorMessage, false, true))
5686 if (prevchar && prevchar != '?')
5688 const char *dbname = ++p; /* advance past host terminator */
5690 /* Look for query parameters */
5691 while (*p && *p != '?')
5698 * Avoid setting dbname to an empty string, as it forces the default
5699 * value (username) and ignores $PGDATABASE, as opposed to not setting
5703 !conninfo_storeval(options, "dbname", dbname,
5704 errorMessage, false, true))
5710 ++p; /* advance past terminator */
5712 if (!conninfo_uri_parse_params(p, options, errorMessage))
5716 /* everything parsed okay */
5720 termPQExpBuffer(&hostbuf);
5721 termPQExpBuffer(&portbuf);
5728 * Connection URI parameters parser routine
5730 * If successful, returns true while connOptions is filled with parsed
5731 * parameters. Otherwise, returns false and fills errorMessage appropriately.
5733 * Destructively modifies 'params' buffer.
5736 conninfo_uri_parse_params(char *params,
5737 PQconninfoOption *connOptions,
5738 PQExpBuffer errorMessage)
5742 char *keyword = params;
5745 bool malloced = false;
5748 * Scan the params string for '=' and '&', marking the end of keyword
5749 * and value respectively.
5755 /* Was there '=' already? */
5758 printfPQExpBuffer(errorMessage,
5759 libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
5763 /* Cut off keyword, advance to value */
5767 else if (*p == '&' || *p == '\0')
5770 * If not at the end, cut off value and advance; leave p
5771 * pointing to start of the next parameter, if any.
5775 /* Was there '=' at all? */
5778 printfPQExpBuffer(errorMessage,
5779 libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
5783 /* Got keyword and value, go process them. */
5787 ++p; /* Advance over all other bytes. */
5790 keyword = conninfo_uri_decode(keyword, errorMessage);
5791 if (keyword == NULL)
5793 /* conninfo_uri_decode already set an error message */
5796 value = conninfo_uri_decode(value, errorMessage);
5799 /* conninfo_uri_decode already set an error message */
5806 * Special keyword handling for improved JDBC compatibility.
5808 if (strcmp(keyword, "ssl") == 0 &&
5809 strcmp(value, "true") == 0)
5815 keyword = "sslmode";
5820 * Store the value if the corresponding option exists; ignore
5821 * otherwise. At this point both keyword and value are not
5824 if (!conninfo_storeval(connOptions, keyword, value,
5825 errorMessage, true, false))
5827 /* Insert generic message if conninfo_storeval didn't give one. */
5828 if (errorMessage->len == 0)
5829 printfPQExpBuffer(errorMessage,
5830 libpq_gettext("invalid URI query parameter: \"%s\"\n"),
5847 /* Proceed to next key=value pair, if any */
5855 * Connection URI decoder routine
5857 * If successful, returns the malloc'd decoded string.
5858 * If not successful, returns NULL and fills errorMessage accordingly.
5860 * The string is decoded by replacing any percent-encoded tokens with
5861 * corresponding characters, while preserving any non-encoded characters. A
5862 * percent-encoded token is a character triplet: a percent sign, followed by a
5863 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
5864 * treated identically.
5867 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
5871 const char *q = str;
5873 buf = malloc(strlen(str) + 1);
5876 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5885 /* copy and check for NUL terminator */
5886 if (!(*(p++) = *(q++)))
5895 ++q; /* skip the percent sign itself */
5898 * Possible EOL will be caught by the first call to
5899 * get_hexdigit(), so we never dereference an invalid q pointer.
5901 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
5903 printfPQExpBuffer(errorMessage,
5904 libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
5913 printfPQExpBuffer(errorMessage,
5914 libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
5927 * Convert hexadecimal digit character to its integer value.
5929 * If successful, returns true and value is filled with digit's base 16 value.
5930 * If not successful, returns false.
5932 * Lower- and upper-case letters in the range A-F are treated identically.
5935 get_hexdigit(char digit, int *value)
5937 if ('0' <= digit && digit <= '9')
5938 *value = digit - '0';
5939 else if ('A' <= digit && digit <= 'F')
5940 *value = digit - 'A' + 10;
5941 else if ('a' <= digit && digit <= 'f')
5942 *value = digit - 'a' + 10;
5950 * Find an option value corresponding to the keyword in the connOptions array.
5952 * If successful, returns a pointer to the corresponding option's value.
5953 * If not successful, returns NULL.
5956 conninfo_getval(PQconninfoOption *connOptions,
5957 const char *keyword)
5959 PQconninfoOption *option;
5961 option = conninfo_find(connOptions, keyword);
5963 return option ? option->val : NULL;
5967 * Store a (new) value for an option corresponding to the keyword in
5968 * connOptions array.
5970 * If uri_decode is true, the value is URI-decoded. The keyword is always
5971 * assumed to be non URI-encoded.
5973 * If successful, returns a pointer to the corresponding PQconninfoOption,
5974 * which value is replaced with a strdup'd copy of the passed value string.
5975 * The existing value for the option is free'd before replacing, if any.
5977 * If not successful, returns NULL and fills errorMessage accordingly.
5978 * However, if the reason of failure is an invalid keyword being passed and
5979 * ignoreMissing is true, errorMessage will be left untouched.
5981 static PQconninfoOption *
5982 conninfo_storeval(PQconninfoOption *connOptions,
5983 const char *keyword, const char *value,
5984 PQExpBuffer errorMessage, bool ignoreMissing,
5987 PQconninfoOption *option;
5991 * For backwards compatibility, requiressl=1 gets translated to
5992 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5993 * (which is the default for sslmode).
5995 if (strcmp(keyword, "requiressl") == 0)
5997 keyword = "sslmode";
5998 if (value[0] == '1')
6004 option = conninfo_find(connOptions, keyword);
6008 printfPQExpBuffer(errorMessage,
6009 libpq_gettext("invalid connection option \"%s\"\n"),
6016 value_copy = conninfo_uri_decode(value, errorMessage);
6017 if (value_copy == NULL)
6018 /* conninfo_uri_decode already set an error message */
6023 value_copy = strdup(value);
6024 if (value_copy == NULL)
6026 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
6033 option->val = value_copy;
6039 * Find a PQconninfoOption option corresponding to the keyword in the
6040 * connOptions array.
6042 * If successful, returns a pointer to the corresponding PQconninfoOption
6044 * If not successful, returns NULL.
6046 static PQconninfoOption *
6047 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
6049 PQconninfoOption *option;
6051 for (option = connOptions; option->keyword != NULL; option++)
6053 if (strcmp(option->keyword, keyword) == 0)
6062 * Return the connection options used for the connection
6065 PQconninfo(PGconn *conn)
6067 PQExpBufferData errorBuf;
6068 PQconninfoOption *connOptions;
6073 /* We don't actually report any errors here, but callees want a buffer */
6074 initPQExpBuffer(&errorBuf);
6075 if (PQExpBufferDataBroken(errorBuf))
6076 return NULL; /* out of memory already :-( */
6078 connOptions = conninfo_init(&errorBuf);
6080 if (connOptions != NULL)
6082 const internalPQconninfoOption *option;
6084 for (option = PQconninfoOptions; option->keyword; option++)
6088 if (option->connofs < 0)
6091 connmember = (char **) ((char *) conn + option->connofs);
6094 conninfo_storeval(connOptions, option->keyword, *connmember,
6095 &errorBuf, true, false);
6099 termPQExpBuffer(&errorBuf);
6106 PQconninfoFree(PQconninfoOption *connOptions)
6108 PQconninfoOption *option;
6110 if (connOptions == NULL)
6113 for (option = connOptions; option->keyword != NULL; option++)
6115 if (option->val != NULL)
6122 /* =========== accessor functions for PGconn ========= */
6124 PQdb(const PGconn *conn)
6128 return conn->dbName;
6132 PQuser(const PGconn *conn)
6136 return conn->pguser;
6140 PQpass(const PGconn *conn)
6142 char *password = NULL;
6146 if (conn->connhost != NULL)
6147 password = conn->connhost[conn->whichhost].password;
6148 if (password == NULL)
6149 password = conn->pgpass;
6150 /* Historically we've returned "" not NULL for no password specified */
6151 if (password == NULL)
6157 PQhost(const PGconn *conn)
6162 if (conn->connhost != NULL)
6164 if (conn->connhost[conn->whichhost].host != NULL &&
6165 conn->connhost[conn->whichhost].host[0] != '\0')
6166 return conn->connhost[conn->whichhost].host;
6167 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
6168 conn->connhost[conn->whichhost].hostaddr[0] != '\0')
6169 return conn->connhost[conn->whichhost].hostaddr;
6176 PQport(const PGconn *conn)
6181 if (conn->connhost != NULL)
6182 return conn->connhost[conn->whichhost].port;
6188 PQtty(const PGconn *conn)
6196 PQoptions(const PGconn *conn)
6200 return conn->pgoptions;
6204 PQstatus(const PGconn *conn)
6207 return CONNECTION_BAD;
6208 return conn->status;
6211 PGTransactionStatusType
6212 PQtransactionStatus(const PGconn *conn)
6214 if (!conn || conn->status != CONNECTION_OK)
6215 return PQTRANS_UNKNOWN;
6216 if (conn->asyncStatus != PGASYNC_IDLE)
6217 return PQTRANS_ACTIVE;
6218 return conn->xactStatus;
6222 PQparameterStatus(const PGconn *conn, const char *paramName)
6224 const pgParameterStatus *pstatus;
6226 if (!conn || !paramName)
6228 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
6230 if (strcmp(pstatus->name, paramName) == 0)
6231 return pstatus->value;
6237 PQprotocolVersion(const PGconn *conn)
6241 if (conn->status == CONNECTION_BAD)
6243 return PG_PROTOCOL_MAJOR(conn->pversion);
6247 PQserverVersion(const PGconn *conn)
6251 if (conn->status == CONNECTION_BAD)
6253 return conn->sversion;
6257 PQerrorMessage(const PGconn *conn)
6260 return libpq_gettext("connection pointer is NULL\n");
6262 return conn->errorMessage.data;
6266 * In Windows, socket values are unsigned, and an invalid socket value
6267 * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
6268 * warning). Ideally we would return an unsigned value for PQsocket() on
6269 * Windows, but that would cause the function's return value to differ from
6270 * Unix, so we just return -1 for invalid sockets.
6271 * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
6272 * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
6275 PQsocket(const PGconn *conn)
6279 return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
6283 PQbackendPID(const PGconn *conn)
6285 if (!conn || conn->status != CONNECTION_OK)
6287 return conn->be_pid;
6291 PQconnectionNeedsPassword(const PGconn *conn)
6297 password = PQpass(conn);
6298 if (conn->password_needed &&
6299 (password == NULL || password[0] == '\0'))
6306 PQconnectionUsedPassword(const PGconn *conn)
6310 if (conn->password_needed)
6317 PQclientEncoding(const PGconn *conn)
6319 if (!conn || conn->status != CONNECTION_OK)
6321 return conn->client_encoding;
6325 PQsetClientEncoding(PGconn *conn, const char *encoding)
6328 static const char query[] = "set client_encoding to '%s'";
6332 if (!conn || conn->status != CONNECTION_OK)
6338 /* Resolve special "auto" value from the locale */
6339 if (strcmp(encoding, "auto") == 0)
6340 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
6342 /* check query buffer overflow */
6343 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
6346 /* ok, now send a query */
6347 sprintf(qbuf, query, encoding);
6348 res = PQexec(conn, qbuf);
6352 if (res->resultStatus != PGRES_COMMAND_OK)
6357 * In protocol 2 we have to assume the setting will stick, and adjust
6358 * our state immediately. In protocol 3 and up we can rely on the
6359 * backend to report the parameter value, and we'll change state at
6362 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
6363 pqSaveParameterStatus(conn, "client_encoding", encoding);
6364 status = 0; /* everything is ok */
6371 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
6376 return PQERRORS_DEFAULT;
6377 old = conn->verbosity;
6378 conn->verbosity = verbosity;
6383 PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
6385 PGContextVisibility old;
6388 return PQSHOW_CONTEXT_ERRORS;
6389 old = conn->show_context;
6390 conn->show_context = show_context;
6395 PQtrace(PGconn *conn, FILE *debug_port)
6400 conn->Pfdebug = debug_port;
6404 PQuntrace(PGconn *conn)
6410 fflush(conn->Pfdebug);
6411 conn->Pfdebug = NULL;
6416 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
6418 PQnoticeReceiver old;
6423 old = conn->noticeHooks.noticeRec;
6426 conn->noticeHooks.noticeRec = proc;
6427 conn->noticeHooks.noticeRecArg = arg;
6433 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
6435 PQnoticeProcessor old;
6440 old = conn->noticeHooks.noticeProc;
6443 conn->noticeHooks.noticeProc = proc;
6444 conn->noticeHooks.noticeProcArg = arg;
6450 * The default notice message receiver just gets the standard notice text
6451 * and sends it to the notice processor. This two-level setup exists
6452 * mostly for backwards compatibility; perhaps we should deprecate use of
6453 * PQsetNoticeProcessor?
6456 defaultNoticeReceiver(void *arg, const PGresult *res)
6458 (void) arg; /* not used */
6459 if (res->noticeHooks.noticeProc != NULL)
6460 res->noticeHooks.noticeProc(res->noticeHooks.noticeProcArg,
6461 PQresultErrorMessage(res));
6465 * The default notice message processor just prints the
6466 * message on stderr. Applications can override this if they
6467 * want the messages to go elsewhere (a window, for example).
6468 * Note that simply discarding notices is probably a bad idea.
6471 defaultNoticeProcessor(void *arg, const char *message)
6473 (void) arg; /* not used */
6474 /* Note: we expect the supplied string to end with a newline already. */
6475 fprintf(stderr, "%s", message);
6479 * returns a pointer to the next token or NULL if the current
6480 * token doesn't match
6483 pwdfMatchesString(char *buf, const char *token)
6487 bool bslash = false;
6489 if (buf == NULL || token == NULL)
6493 if (tbuf[0] == '*' && tbuf[1] == ':')
6497 if (*tbuf == '\\' && !bslash)
6502 if (*tbuf == ':' && *ttok == 0 && !bslash)
6518 /* Get a password from the password file. Return value is malloc'd. */
6520 passwordFromFile(const char *hostname, const char *port, const char *dbname,
6521 const char *username, const char *pgpassfile)
6524 struct stat stat_buf;
6526 #define LINELEN NAMEDATALEN*5
6529 if (dbname == NULL || dbname[0] == '\0')
6532 if (username == NULL || username[0] == '\0')
6535 /* 'localhost' matches pghost of '' or the default socket directory */
6536 if (hostname == NULL || hostname[0] == '\0')
6537 hostname = DefaultHost;
6538 else if (is_absolute_path(hostname))
6541 * We should probably use canonicalize_path(), but then we have to
6542 * bring path.c into libpq, and it doesn't seem worth it.
6544 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
6545 hostname = DefaultHost;
6547 if (port == NULL || port[0] == '\0')
6548 port = DEF_PGPORT_STR;
6550 /* If password file cannot be opened, ignore it. */
6551 if (stat(pgpassfile, &stat_buf) != 0)
6555 if (!S_ISREG(stat_buf.st_mode))
6558 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
6563 /* If password file is insecure, alert the user and ignore it. */
6564 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
6567 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
6574 * On Win32, the directory is protected, so we don't have to check the
6579 fp = fopen(pgpassfile, "r");
6583 while (!feof(fp) && !ferror(fp))
6591 if (fgets(buf, sizeof(buf), fp) == NULL)
6596 /* Remove trailing newline */
6597 if (len > 0 && buf[len - 1] == '\n')
6600 /* Handle DOS-style line endings, too, even when not on Windows */
6601 if (len > 0 && buf[len - 1] == '\r')
6608 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
6609 (t = pwdfMatchesString(t, port)) == NULL ||
6610 (t = pwdfMatchesString(t, dbname)) == NULL ||
6611 (t = pwdfMatchesString(t, username)) == NULL)
6614 /* Found a match. */
6620 /* Out of memory. XXX: an error message would be nice. */
6624 /* De-escape password. */
6625 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
6627 if (*p1 == '\\' && p1[1] != '\0')
6644 * If the connection failed due to bad password, we should mention
6645 * if we got the password from the pgpassfile.
6648 pgpassfileWarning(PGconn *conn)
6650 /* If it was 'invalid authorization', add pgpassfile mention */
6651 /* only works with >= 9.0 servers */
6652 if (conn->password_needed &&
6653 conn->connhost[conn->whichhost].password != NULL &&
6656 const char *sqlstate = PQresultErrorField(conn->result,
6659 if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
6660 appendPQExpBuffer(&conn->errorMessage,
6661 libpq_gettext("password retrieved from file \"%s\"\n"),
6668 * Obtain user's home directory, return in given buffer
6670 * On Unix, this actually returns the user's home directory. On Windows
6671 * it returns the PostgreSQL-specific application data folder.
6673 * This is essentially the same as get_home_path(), but we don't use that
6674 * because we don't want to pull path.c into libpq (it pollutes application
6677 * Returns true on success, false on failure to obtain the directory name.
6679 * CAUTION: although in most situations failure is unexpected, there are users
6680 * who like to run applications in a home-directory-less environment. On
6681 * failure, you almost certainly DO NOT want to report an error. Just act as
6682 * though whatever file you were hoping to find in the home directory isn't
6683 * there (which it isn't).
6686 pqGetHomeDirectory(char *buf, int bufsize)
6689 char pwdbuf[BUFSIZ];
6690 struct passwd pwdstr;
6691 struct passwd *pwd = NULL;
6693 (void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
6696 strlcpy(buf, pwd->pw_dir, bufsize);
6699 char tmppath[MAX_PATH];
6701 ZeroMemory(tmppath, sizeof(tmppath));
6702 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
6704 snprintf(buf, bufsize, "%s/postgresql", tmppath);
6710 * To keep the API consistent, the locking stubs are always provided, even
6711 * if they are not required.
6715 default_threadlock(int acquire)
6717 #ifdef ENABLE_THREAD_SAFETY
6719 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
6721 static pthread_mutex_t singlethread_lock = NULL;
6722 static long mutex_initlock = 0;
6724 if (singlethread_lock == NULL)
6726 while (InterlockedExchange(&mutex_initlock, 1) == 1)
6727 /* loop, another thread own the lock */ ;
6728 if (singlethread_lock == NULL)
6730 if (pthread_mutex_init(&singlethread_lock, NULL))
6731 PGTHREAD_ERROR("failed to initialize mutex");
6733 InterlockedExchange(&mutex_initlock, 0);
6738 if (pthread_mutex_lock(&singlethread_lock))
6739 PGTHREAD_ERROR("failed to lock mutex");
6743 if (pthread_mutex_unlock(&singlethread_lock))
6744 PGTHREAD_ERROR("failed to unlock mutex");
6750 PQregisterThreadLock(pgthreadlock_t newhandler)
6752 pgthreadlock_t prev = pg_g_threadlock;
6755 pg_g_threadlock = newhandler;
6757 pg_g_threadlock = default_threadlock;