1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2013, 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"
18 #include <sys/types.h>
26 #include "libpq-int.h"
28 #include "pg_config_paths.h"
35 #define _WIN32_IE 0x0500
41 #ifdef WIN32_ONLY_COMPILER /* mstcpip.h is missing on mingw */
45 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #ifdef HAVE_NETINET_TCP_H
49 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
54 #ifdef ENABLE_THREAD_SAFETY
56 #include "pthread-win32.h"
66 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
67 #define LDAP_DEPRECATED 1
69 typedef struct timeval LDAP_TIMEVAL;
71 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
72 PQExpBuffer errorMessage);
76 #include "mb/pg_wchar.h"
84 #define PGPASSFILE ".pgpass"
86 #define PGPASSFILE "pgpass.conf"
90 * Pre-9.0 servers will return this SQLSTATE if asked to set
91 * application_name in a startup packet. We hard-wire the value rather
92 * than looking into errcodes.h since it reflects historical behavior
93 * rather than that of the current code.
95 #define ERRCODE_APPNAME_UNKNOWN "42704"
97 /* This is part of the protocol so just define it */
98 #define ERRCODE_INVALID_PASSWORD "28P01"
100 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
103 * fall back options if they are not specified by arguments or defined
104 * by environment variables
106 #define DefaultHost "localhost"
107 #define DefaultTty ""
108 #define DefaultOption ""
109 #define DefaultAuthtype ""
110 #define DefaultPassword ""
112 #define DefaultSSLMode "prefer"
114 #define DefaultSSLMode "disable"
118 * Definition of the conninfo parameters and their fallback resources.
120 * If Environment-Var and Compiled-in are specified as NULL, no
121 * fallback is available. If after all no value can be determined
122 * for an option, an error is returned.
124 * The value for the username is treated specially in conninfo_add_defaults.
125 * If the value is not obtained any other way, the username is determined
126 * by pg_fe_getauthname().
128 * The Label and Disp-Char entries are provided for applications that
129 * want to use PQconndefaults() to create a generic database connection
130 * dialog. Disp-Char is defined as follows:
131 * "" Normal input field
132 * "*" Password field - hide value
133 * "D" Debug option - don't show by default
135 * PQconninfoOptions[] is a constant static array that we use to initialize
136 * a dynamically allocated working copy. All the "val" fields in
137 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
138 * fields point to malloc'd strings that should be freed when the working
139 * array is freed (see PQconninfoFree).
141 * The first part of each struct is identical to the one in libpq-fe.h,
142 * which is required since we memcpy() data between the two!
145 typedef struct _internalPQconninfoOption
147 char *keyword; /* The keyword of the option */
148 char *envvar; /* Fallback environment variable name */
149 char *compiled; /* Fallback compiled in default value */
150 char *val; /* Option's current value, or NULL */
151 char *label; /* Label for field in connect dialog */
152 char *dispchar; /* Indicates how to display this field in a
153 * connect dialog. Values are: "" Display
154 * entered value as is "*" Password field -
155 * hide value "D" Debug option - don't show
157 int dispsize; /* Field size in characters for dialog */
159 * Anything above this comment must be synchronized with
160 * PQconninfoOption in libpq-fe.h, since we memcpy() data
164 off_t connofs; /* Offset into PGconn struct, -1 if not there */
165 } internalPQconninfoOption;
167 static const internalPQconninfoOption PQconninfoOptions[] = {
169 * "authtype" is no longer used, so mark it "don't show". We keep it in
170 * the array so as not to reject conninfo strings from old apps that might
171 * still try to set it.
173 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
174 "Database-Authtype", "D", 20, -1},
176 {"service", "PGSERVICE", NULL, NULL,
177 "Database-Service", "", 20, -1},
179 {"user", "PGUSER", NULL, NULL,
180 "Database-User", "", 20,
181 offsetof(struct pg_conn, pguser)},
183 {"password", "PGPASSWORD", NULL, NULL,
184 "Database-Password", "*", 20,
185 offsetof(struct pg_conn, pgpass)},
187 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
188 "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
189 offsetof(struct pg_conn, connect_timeout)},
191 {"dbname", "PGDATABASE", NULL, NULL,
192 "Database-Name", "", 20,
193 offsetof(struct pg_conn, dbName)},
195 {"host", "PGHOST", NULL, NULL,
196 "Database-Host", "", 40,
197 offsetof(struct pg_conn, pghost)},
199 {"hostaddr", "PGHOSTADDR", NULL, NULL,
200 "Database-Host-IP-Address", "", 45,
201 offsetof(struct pg_conn, pghostaddr)},
203 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
204 "Database-Port", "", 6,
205 offsetof(struct pg_conn, pgport)},
207 {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
208 "Client-Encoding", "", 10,
209 offsetof(struct pg_conn, client_encoding_initial)},
212 * "tty" is no longer used either, but keep it present for backwards
215 {"tty", "PGTTY", DefaultTty, NULL,
216 "Backend-Debug-TTY", "D", 40,
217 offsetof(struct pg_conn, pgtty)},
219 {"options", "PGOPTIONS", DefaultOption, NULL,
220 "Backend-Debug-Options", "D", 40,
221 offsetof(struct pg_conn, pgoptions)},
223 {"application_name", "PGAPPNAME", NULL, NULL,
224 "Application-Name", "", 64,
225 offsetof(struct pg_conn, appname)},
227 {"fallback_application_name", NULL, NULL, NULL,
228 "Fallback-Application-Name", "", 64,
229 offsetof(struct pg_conn, fbappname)},
231 {"keepalives", NULL, NULL, NULL,
232 "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
233 offsetof(struct pg_conn, keepalives)},
235 {"keepalives_idle", NULL, NULL, NULL,
236 "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
237 offsetof(struct pg_conn, keepalives_idle)},
239 {"keepalives_interval", NULL, NULL, NULL,
240 "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
241 offsetof(struct pg_conn, keepalives_interval)},
243 {"keepalives_count", NULL, NULL, NULL,
244 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
245 offsetof(struct pg_conn, keepalives_count)},
248 * ssl options are allowed even without client SSL support because the
249 * client can still handle SSL modes "disable" and "allow". Other
250 * parameters have no effect on non-SSL connections, so there is no reason
251 * to exclude them since none of them are mandatory.
253 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
254 "SSL-Mode", "", 8, /* sizeof("disable") == 8 */
255 offsetof(struct pg_conn, sslmode)},
257 {"sslcompression", "PGSSLCOMPRESSION", "1", NULL,
258 "SSL-Compression", "", 1,
259 offsetof(struct pg_conn, sslcompression)},
261 {"sslcert", "PGSSLCERT", NULL, NULL,
262 "SSL-Client-Cert", "", 64,
263 offsetof(struct pg_conn, sslcert)},
265 {"sslkey", "PGSSLKEY", NULL, NULL,
266 "SSL-Client-Key", "", 64,
267 offsetof(struct pg_conn, sslkey)},
269 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
270 "SSL-Root-Certificate", "", 64,
271 offsetof(struct pg_conn, sslrootcert)},
273 {"sslcrl", "PGSSLCRL", NULL, NULL,
274 "SSL-Revocation-List", "", 64,
275 offsetof(struct pg_conn, sslcrl)},
277 {"requirepeer", "PGREQUIREPEER", NULL, NULL,
278 "Require-Peer", "", 10,
279 offsetof(struct pg_conn, requirepeer)},
281 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
282 /* Kerberos and GSSAPI authentication support specifying the service name */
283 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
284 "Kerberos-service-name", "", 20,
285 offsetof(struct pg_conn, krbsrvname)},
288 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
291 * GSSAPI and SSPI both enabled, give a way to override which is used by
294 {"gsslib", "PGGSSLIB", NULL, NULL,
295 "GSS-library", "", 7, /* sizeof("gssapi") = 7 */
296 offsetof(struct pg_conn, gsslib)},
299 {"replication", NULL, NULL, NULL,
300 "Replication", "D", 5,
301 offsetof(struct pg_conn, replication)},
303 /* Terminating entry --- MUST BE LAST */
304 {NULL, NULL, NULL, NULL,
308 static const PQEnvironmentOption EnvironmentOptions[] =
310 /* common user-interface settings */
312 "PGDATESTYLE", "datestyle"
317 /* internal performance-related settings */
326 /* The connection URI must start with either of the following designators: */
327 static const char uri_designator[] = "postgresql://";
328 static const char short_uri_designator[] = "postgres://";
330 static bool connectOptions1(PGconn *conn, const char *conninfo);
331 static bool connectOptions2(PGconn *conn);
332 static int connectDBStart(PGconn *conn);
333 static int connectDBComplete(PGconn *conn);
334 static PGPing internal_ping(PGconn *conn);
335 static PGconn *makeEmptyPGconn(void);
336 static void fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
337 static void freePGconn(PGconn *conn);
338 static void closePGconn(PGconn *conn);
339 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
340 static PQconninfoOption *parse_connection_string(const char *conninfo,
341 PQExpBuffer errorMessage, bool use_defaults);
342 static int uri_prefix_length(const char *connstr);
343 static bool recognized_connection_string(const char *connstr);
344 static PQconninfoOption *conninfo_parse(const char *conninfo,
345 PQExpBuffer errorMessage, bool use_defaults);
346 static PQconninfoOption *conninfo_array_parse(const char *const * keywords,
347 const char *const * values, PQExpBuffer errorMessage,
348 bool use_defaults, int expand_dbname);
349 static bool conninfo_add_defaults(PQconninfoOption *options,
350 PQExpBuffer errorMessage);
351 static PQconninfoOption *conninfo_uri_parse(const char *uri,
352 PQExpBuffer errorMessage, bool use_defaults);
353 static bool conninfo_uri_parse_options(PQconninfoOption *options,
354 const char *uri, PQExpBuffer errorMessage);
355 static bool conninfo_uri_parse_params(char *params,
356 PQconninfoOption *connOptions,
357 PQExpBuffer errorMessage);
358 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
359 static bool get_hexdigit(char digit, int *value);
360 static const char *conninfo_getval(PQconninfoOption *connOptions,
361 const char *keyword);
362 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
363 const char *keyword, const char *value,
364 PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
365 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
366 const char *keyword);
367 static void defaultNoticeReceiver(void *arg, const PGresult *res);
368 static void defaultNoticeProcessor(void *arg, const char *message);
369 static int parseServiceInfo(PQconninfoOption *options,
370 PQExpBuffer errorMessage);
371 static int parseServiceFile(const char *serviceFile,
373 PQconninfoOption *options,
374 PQExpBuffer errorMessage,
376 static char *pwdfMatchesString(char *buf, char *token);
377 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
379 static bool getPgPassFilename(char *pgpassfile);
380 static void dot_pg_pass_warning(PGconn *conn);
381 static void default_threadlock(int acquire);
384 /* global variable because fe-auth.c needs to access it */
385 pgthreadlock_t pg_g_threadlock = default_threadlock;
391 * Close any physical connection to the server, and reset associated
392 * state inside the connection object. We don't release state that
393 * would be needed to reconnect, though.
396 pqDropConnection(PGconn *conn)
398 /* Drop any SSL state */
399 pqsecure_close(conn);
400 /* Close the socket itself */
402 closesocket(conn->sock);
404 /* Discard any unread/unsent data */
405 conn->inStart = conn->inCursor = conn->inEnd = 0;
411 * Connecting to a Database
413 * There are now six different ways a user of this API can connect to the
414 * database. Two are not recommended for use in new code, because of their
415 * lack of extensibility with respect to the passing of options to the
416 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
419 * If it is desired to connect in a synchronous (blocking) manner, use the
420 * function PQconnectdb or PQconnectdbParams. The former accepts a string of
421 * option = value pairs (or a URI) which must be parsed; the latter takes two
422 * NULL terminated arrays instead.
424 * To connect in an asynchronous (non-blocking) manner, use the functions
425 * PQconnectStart or PQconnectStartParams (which differ in the same way as
426 * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
428 * Internally, the static functions connectDBStart, connectDBComplete
429 * are part of the connection procedure.
435 * establishes a connection to a postgres backend through the postmaster
436 * using connection information in two arrays.
438 * The keywords array is defined as
440 * const char *params[] = {"option1", "option2", NULL}
442 * The values array is defined as
444 * const char *values[] = {"value1", "value2", NULL}
446 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
447 * if a memory allocation failed.
448 * If the status field of the connection returned is CONNECTION_BAD,
449 * then some fields may be null'ed out instead of having valid values.
451 * You should call PQfinish (if conn is not NULL) regardless of whether this
455 PQconnectdbParams(const char *const * keywords,
456 const char *const * values,
459 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
461 if (conn && conn->status != CONNECTION_BAD)
462 (void) connectDBComplete(conn);
471 * check server status, accepting parameters identical to PQconnectdbParams
474 PQpingParams(const char *const * keywords,
475 const char *const * values,
478 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
481 ret = internal_ping(conn);
490 * establishes a connection to a postgres backend through the postmaster
491 * using connection information in a string.
493 * The conninfo string is either a whitespace-separated list of
497 * definitions or a URI (refer to the documentation for details.) Value
498 * might be a single value containing no whitespaces or a single quoted
499 * string. If a single quote should appear anywhere in the value, it must be
500 * escaped with a backslash like \'
502 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
503 * if a memory allocation failed.
504 * If the status field of the connection returned is CONNECTION_BAD,
505 * then some fields may be null'ed out instead of having valid values.
507 * You should call PQfinish (if conn is not NULL) regardless of whether this
511 PQconnectdb(const char *conninfo)
513 PGconn *conn = PQconnectStart(conninfo);
515 if (conn && conn->status != CONNECTION_BAD)
516 (void) connectDBComplete(conn);
524 * check server status, accepting parameters identical to PQconnectdb
527 PQping(const char *conninfo)
529 PGconn *conn = PQconnectStart(conninfo);
532 ret = internal_ping(conn);
539 * PQconnectStartParams
541 * Begins the establishment of a connection to a postgres backend through the
542 * postmaster using connection information in a struct.
544 * See comment for PQconnectdbParams for the definition of the string format.
546 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
547 * you should not attempt to proceed with this connection. If the status
548 * field of the connection returned is CONNECTION_BAD, an error has
549 * occurred. In this case you should call PQfinish on the result, (perhaps
550 * inspecting the error message first). Other fields of the structure may not
551 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
552 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
555 * See PQconnectPoll for more info.
558 PQconnectStartParams(const char *const * keywords,
559 const char *const * values,
563 PQconninfoOption *connOptions;
566 * Allocate memory for the conn structure
568 conn = makeEmptyPGconn();
573 * Parse the conninfo arrays
575 connOptions = conninfo_array_parse(keywords, values,
577 true, expand_dbname);
578 if (connOptions == NULL)
580 conn->status = CONNECTION_BAD;
581 /* errorMessage is already set */
586 * Move option values into conn structure
588 fillPGconn(conn, connOptions);
591 * Free the option info - all is in conn now
593 PQconninfoFree(connOptions);
596 * Compute derived options
598 if (!connectOptions2(conn))
602 * Connect to the database
604 if (!connectDBStart(conn))
606 /* Just in case we failed to set it in connectDBStart */
607 conn->status = CONNECTION_BAD;
616 * Begins the establishment of a connection to a postgres backend through the
617 * postmaster using connection information in a string.
619 * See comment for PQconnectdb for the definition of the string format.
621 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
622 * you should not attempt to proceed with this connection. If the status
623 * field of the connection returned is CONNECTION_BAD, an error has
624 * occurred. In this case you should call PQfinish on the result, (perhaps
625 * inspecting the error message first). Other fields of the structure may not
626 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
627 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
630 * See PQconnectPoll for more info.
633 PQconnectStart(const char *conninfo)
638 * Allocate memory for the conn structure
640 conn = makeEmptyPGconn();
645 * Parse the conninfo string
647 if (!connectOptions1(conn, conninfo))
651 * Compute derived options
653 if (!connectOptions2(conn))
657 * Connect to the database
659 if (!connectDBStart(conn))
661 /* Just in case we failed to set it in connectDBStart */
662 conn->status = CONNECTION_BAD;
669 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
671 const internalPQconninfoOption *option;
674 * Move option values into conn structure
676 * Don't put anything cute here --- intelligence should be in
677 * connectOptions2 ...
679 * XXX: probably worth checking strdup() return value here...
681 for (option = PQconninfoOptions; option->keyword; option++)
683 const char *tmp = conninfo_getval(connOptions, option->keyword);
685 if (tmp && option->connofs >= 0)
687 char **connmember = (char **) ((char *) conn + option->connofs);
691 *connmember = tmp ? strdup(tmp) : NULL;
699 * Internal subroutine to set up connection parameters given an already-
700 * created PGconn and a conninfo string. Derived settings should be
701 * processed by calling connectOptions2 next. (We split them because
702 * PQsetdbLogin overrides defaults in between.)
704 * Returns true if OK, false if trouble (in which case errorMessage is set
705 * and so is conn->status).
708 connectOptions1(PGconn *conn, const char *conninfo)
710 PQconninfoOption *connOptions;
713 * Parse the conninfo string
715 connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
716 if (connOptions == NULL)
718 conn->status = CONNECTION_BAD;
719 /* errorMessage is already set */
724 * Move option values into conn structure
726 fillPGconn(conn, connOptions);
729 * Free the option info - all is in conn now
731 PQconninfoFree(connOptions);
739 * Compute derived connection options after absorbing all user-supplied info.
741 * Returns true if OK, false if trouble (in which case errorMessage is set
742 * and so is conn->status).
745 connectOptions2(PGconn *conn)
748 * If database name was not given, default it to equal user name
750 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
751 && conn->pguser != NULL)
755 conn->dbName = strdup(conn->pguser);
759 * Supply default password if none given
761 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
765 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
766 conn->dbName, conn->pguser);
767 if (conn->pgpass == NULL)
768 conn->pgpass = strdup(DefaultPassword);
770 conn->dot_pgpass_used = true;
774 * Allow unix socket specification in the host name
776 if (conn->pghost && is_absolute_path(conn->pghost))
778 if (conn->pgunixsocket)
779 free(conn->pgunixsocket);
780 conn->pgunixsocket = conn->pghost;
785 * validate sslmode option
789 if (strcmp(conn->sslmode, "disable") != 0
790 && strcmp(conn->sslmode, "allow") != 0
791 && strcmp(conn->sslmode, "prefer") != 0
792 && strcmp(conn->sslmode, "require") != 0
793 && strcmp(conn->sslmode, "verify-ca") != 0
794 && strcmp(conn->sslmode, "verify-full") != 0)
796 conn->status = CONNECTION_BAD;
797 printfPQExpBuffer(&conn->errorMessage,
798 libpq_gettext("invalid sslmode value: \"%s\"\n"),
804 switch (conn->sslmode[0])
806 case 'a': /* "allow" */
807 case 'p': /* "prefer" */
810 * warn user that an SSL connection will never be negotiated
811 * since SSL was not compiled in?
815 case 'r': /* "require" */
816 case 'v': /* "verify-ca" or "verify-full" */
817 conn->status = CONNECTION_BAD;
818 printfPQExpBuffer(&conn->errorMessage,
819 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
826 conn->sslmode = strdup(DefaultSSLMode);
829 * Resolve special "auto" client_encoding from the locale
831 if (conn->client_encoding_initial &&
832 strcmp(conn->client_encoding_initial, "auto") == 0)
834 free(conn->client_encoding_initial);
835 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
839 * Only if we get this far is it appropriate to try to connect. (We need a
840 * state flag, rather than just the boolean result of this function, in
841 * case someone tries to PQreset() the PGconn.)
843 conn->options_valid = true;
851 * Construct a default connection options array, which identifies all the
852 * available options and shows any default values that are available from the
853 * environment etc. On error (eg out of memory), NULL is returned.
855 * Using this function, an application may determine all possible options
856 * and their current default values.
858 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
859 * and should be freed when no longer needed via PQconninfoFree(). (In prior
860 * versions, the returned array was static, but that's not thread-safe.)
861 * Pre-7.0 applications that use this function will see a small memory leak
862 * until they are updated to call PQconninfoFree.
867 PQExpBufferData errorBuf;
868 PQconninfoOption *connOptions;
870 /* We don't actually report any errors here, but callees want a buffer */
871 initPQExpBuffer(&errorBuf);
872 if (PQExpBufferDataBroken(errorBuf))
873 return NULL; /* out of memory already :-( */
875 connOptions = conninfo_init(&errorBuf);
876 if (connOptions != NULL)
878 if (!conninfo_add_defaults(connOptions, &errorBuf))
880 PQconninfoFree(connOptions);
885 termPQExpBuffer(&errorBuf);
892 * establishes a connection to a postgres backend through the postmaster
893 * at the specified host and port.
895 * returns a PGconn* which is needed for all subsequent libpq calls
897 * if the status field of the connection returned is CONNECTION_BAD,
898 * then only the errorMessage is likely to be useful.
902 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
903 const char *pgtty, const char *dbName, const char *login,
909 * Allocate memory for the conn structure
911 conn = makeEmptyPGconn();
916 * If the dbName parameter contains what looks like a connection string,
917 * parse it into conn struct using connectOptions1.
919 if (dbName && recognized_connection_string(dbName))
921 if (!connectOptions1(conn, dbName))
927 * Old-style path: first, parse an empty conninfo string in order to
928 * set up the same defaults that PQconnectdb() would use.
930 if (!connectOptions1(conn, ""))
933 /* Insert dbName parameter value into struct */
934 if (dbName && dbName[0] != '\0')
938 conn->dbName = strdup(dbName);
943 * Insert remaining parameters into struct, overriding defaults (as well
944 * as any conflicting data from dbName taken as a conninfo).
946 if (pghost && pghost[0] != '\0')
950 conn->pghost = strdup(pghost);
953 if (pgport && pgport[0] != '\0')
957 conn->pgport = strdup(pgport);
960 if (pgoptions && pgoptions[0] != '\0')
963 free(conn->pgoptions);
964 conn->pgoptions = strdup(pgoptions);
967 if (pgtty && pgtty[0] != '\0')
971 conn->pgtty = strdup(pgtty);
974 if (login && login[0] != '\0')
978 conn->pguser = strdup(login);
981 if (pwd && pwd[0] != '\0')
985 conn->pgpass = strdup(pwd);
989 * Compute derived options
991 if (!connectOptions2(conn))
995 * Connect to the database
997 if (connectDBStart(conn))
998 (void) connectDBComplete(conn);
1006 * Sets the TCP_NODELAY socket option.
1007 * Returns 1 if successful, 0 if not.
1011 connectNoDelay(PGconn *conn)
1016 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1022 appendPQExpBuffer(&conn->errorMessage,
1023 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1024 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1034 * connectFailureMessage -
1035 * create a friendly error message on connection failure.
1039 connectFailureMessage(PGconn *conn, int errorno)
1043 #ifdef HAVE_UNIX_SOCKETS
1044 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1046 char service[NI_MAXHOST];
1048 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1050 service, sizeof(service),
1052 appendPQExpBuffer(&conn->errorMessage,
1053 libpq_gettext("could not connect to server: %s\n"
1054 "\tIs the server running locally and accepting\n"
1055 "\tconnections on Unix domain socket \"%s\"?\n"),
1056 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1060 #endif /* HAVE_UNIX_SOCKETS */
1062 char host_addr[NI_MAXHOST];
1063 const char *displayed_host;
1064 struct sockaddr_storage *addr = &conn->raddr.addr;
1067 * Optionally display the network address with the hostname. This is
1068 * useful to distinguish between IPv4 and IPv6 connections.
1070 if (conn->pghostaddr != NULL)
1071 strlcpy(host_addr, conn->pghostaddr, NI_MAXHOST);
1072 else if (addr->ss_family == AF_INET)
1074 if (inet_net_ntop(AF_INET,
1075 &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1077 host_addr, sizeof(host_addr)) == NULL)
1078 strcpy(host_addr, "???");
1081 else if (addr->ss_family == AF_INET6)
1083 if (inet_net_ntop(AF_INET6,
1084 &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1086 host_addr, sizeof(host_addr)) == NULL)
1087 strcpy(host_addr, "???");
1091 strcpy(host_addr, "???");
1093 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1094 displayed_host = conn->pghostaddr;
1095 else if (conn->pghost && conn->pghost[0] != '\0')
1096 displayed_host = conn->pghost;
1098 displayed_host = DefaultHost;
1101 * If the user did not supply an IP address using 'hostaddr', and
1102 * 'host' was missing or does not match our lookup, display the
1103 * looked-up IP address.
1105 if ((conn->pghostaddr == NULL) &&
1106 (conn->pghost == NULL || strcmp(conn->pghost, host_addr) != 0))
1107 appendPQExpBuffer(&conn->errorMessage,
1108 libpq_gettext("could not connect to server: %s\n"
1109 "\tIs the server running on host \"%s\" (%s) and accepting\n"
1110 "\tTCP/IP connections on port %s?\n"),
1111 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1116 appendPQExpBuffer(&conn->errorMessage,
1117 libpq_gettext("could not connect to server: %s\n"
1118 "\tIs the server running on host \"%s\" and accepting\n"
1119 "\tTCP/IP connections on port %s?\n"),
1120 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1127 * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
1128 * conn->keepalives is set to a value which is not parseable as an
1132 useKeepalives(PGconn *conn)
1137 if (conn->keepalives == NULL)
1139 val = strtol(conn->keepalives, &ep, 10);
1142 return val != 0 ? 1 : 0;
1147 * Set the keepalive idle timer.
1150 setKeepalivesIdle(PGconn *conn)
1154 if (conn->keepalives_idle == NULL)
1157 idle = atoi(conn->keepalives_idle);
1162 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1163 (char *) &idle, sizeof(idle)) < 0)
1167 appendPQExpBuffer(&conn->errorMessage,
1168 libpq_gettext("setsockopt(TCP_KEEPIDLE) failed: %s\n"),
1169 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1173 #ifdef TCP_KEEPALIVE
1174 /* Darwin uses TCP_KEEPALIVE rather than TCP_KEEPIDLE */
1175 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1176 (char *) &idle, sizeof(idle)) < 0)
1180 appendPQExpBuffer(&conn->errorMessage,
1181 libpq_gettext("setsockopt(TCP_KEEPALIVE) failed: %s\n"),
1182 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1192 * Set the keepalive interval.
1195 setKeepalivesInterval(PGconn *conn)
1199 if (conn->keepalives_interval == NULL)
1202 interval = atoi(conn->keepalives_interval);
1206 #ifdef TCP_KEEPINTVL
1207 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1208 (char *) &interval, sizeof(interval)) < 0)
1212 appendPQExpBuffer(&conn->errorMessage,
1213 libpq_gettext("setsockopt(TCP_KEEPINTVL) failed: %s\n"),
1214 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1223 * Set the count of lost keepalive packets that will trigger a connection
1227 setKeepalivesCount(PGconn *conn)
1231 if (conn->keepalives_count == NULL)
1234 count = atoi(conn->keepalives_count);
1239 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1240 (char *) &count, sizeof(count)) < 0)
1244 appendPQExpBuffer(&conn->errorMessage,
1245 libpq_gettext("setsockopt(TCP_KEEPCNT) failed: %s\n"),
1246 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1254 #ifdef SIO_KEEPALIVE_VALS
1256 * Enable keepalives and set the keepalive values on Win32,
1257 * where they are always set in one batch.
1260 setKeepalivesWin32(PGconn *conn)
1262 struct tcp_keepalive ka;
1267 if (conn->keepalives_idle)
1268 idle = atoi(conn->keepalives_idle);
1270 idle = 2 * 60 * 60; /* 2 hours = default */
1272 if (conn->keepalives_interval)
1273 interval = atoi(conn->keepalives_interval);
1275 interval = 1; /* 1 second = default */
1278 ka.keepalivetime = idle * 1000;
1279 ka.keepaliveinterval = interval * 1000;
1281 if (WSAIoctl(conn->sock,
1292 appendPQExpBuffer(&conn->errorMessage,
1293 libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1299 #endif /* SIO_KEEPALIVE_VALS */
1304 * Begin the process of making a connection to the backend.
1306 * Returns 1 if successful, 0 if not.
1310 connectDBStart(PGconn *conn)
1313 char portstr[MAXPGPATH];
1314 struct addrinfo *addrs = NULL;
1315 struct addrinfo hint;
1322 if (!conn->options_valid)
1323 goto connect_errReturn;
1325 /* Ensure our buffers are empty */
1326 conn->inStart = conn->inCursor = conn->inEnd = 0;
1330 * Determine the parameters to pass to pg_getaddrinfo_all.
1333 /* Initialize hint structure */
1334 MemSet(&hint, 0, sizeof(hint));
1335 hint.ai_socktype = SOCK_STREAM;
1336 hint.ai_family = AF_UNSPEC;
1338 /* Set up port number as a string */
1339 if (conn->pgport != NULL && conn->pgport[0] != '\0')
1341 portnum = atoi(conn->pgport);
1342 if (portnum < 1 || portnum > 65535)
1344 appendPQExpBuffer(&conn->errorMessage,
1345 libpq_gettext("invalid port number: \"%s\"\n"),
1347 conn->options_valid = false;
1348 goto connect_errReturn;
1352 portnum = DEF_PGPORT;
1353 snprintf(portstr, sizeof(portstr), "%d", portnum);
1355 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1357 /* Using pghostaddr avoids a hostname lookup */
1358 node = conn->pghostaddr;
1359 hint.ai_family = AF_UNSPEC;
1360 hint.ai_flags = AI_NUMERICHOST;
1362 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
1364 /* Using pghost, so we have to look-up the hostname */
1365 node = conn->pghost;
1366 hint.ai_family = AF_UNSPEC;
1370 #ifdef HAVE_UNIX_SOCKETS
1371 /* pghostaddr and pghost are NULL, so use Unix domain socket */
1373 hint.ai_family = AF_UNIX;
1374 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
1375 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
1377 appendPQExpBuffer(&conn->errorMessage,
1378 libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
1380 (int) (UNIXSOCK_PATH_BUFLEN - 1));
1381 conn->options_valid = false;
1382 goto connect_errReturn;
1385 /* Without Unix sockets, default to localhost instead */
1387 hint.ai_family = AF_UNSPEC;
1388 #endif /* HAVE_UNIX_SOCKETS */
1391 /* Use pg_getaddrinfo_all() to resolve the address */
1392 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
1396 appendPQExpBuffer(&conn->errorMessage,
1397 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
1398 node, gai_strerror(ret));
1400 appendPQExpBuffer(&conn->errorMessage,
1401 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
1402 portstr, gai_strerror(ret));
1404 pg_freeaddrinfo_all(hint.ai_family, addrs);
1405 conn->options_valid = false;
1406 goto connect_errReturn;
1410 /* setup values based on SSL mode */
1411 if (conn->sslmode[0] == 'd') /* "disable" */
1412 conn->allow_ssl_try = false;
1413 else if (conn->sslmode[0] == 'a') /* "allow" */
1414 conn->wait_ssl_try = true;
1418 * Set up to try to connect, with protocol 3.0 as the first attempt.
1420 conn->addrlist = addrs;
1421 conn->addr_cur = addrs;
1422 conn->addrlist_family = hint.ai_family;
1423 conn->pversion = PG_PROTOCOL(3, 0);
1424 conn->send_appname = true;
1425 conn->status = CONNECTION_NEEDED;
1428 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1429 * so that it can easily be re-executed if needed again during the
1430 * asynchronous startup process. However, we must run it once here,
1431 * because callers expect a success return from this routine to mean that
1432 * we are in PGRES_POLLING_WRITING connection state.
1434 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1438 pqDropConnection(conn);
1439 conn->status = CONNECTION_BAD;
1447 * Block and complete a connection.
1449 * Returns 1 on success, 0 on failure.
1452 connectDBComplete(PGconn *conn)
1454 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1455 time_t finish_time = ((time_t) -1);
1457 if (conn == NULL || conn->status == CONNECTION_BAD)
1461 * Set up a time limit, if connect_timeout isn't zero.
1463 if (conn->connect_timeout != NULL)
1465 int timeout = atoi(conn->connect_timeout);
1470 * Rounding could cause connection to fail; need at least 2 secs
1474 /* calculate the finish time based on start + timeout */
1475 finish_time = time(NULL) + timeout;
1482 * Wait, if necessary. Note that the initial state (just after
1483 * PQconnectStart) is to wait for the socket to select for writing.
1487 case PGRES_POLLING_OK:
1490 * Reset stored error messages since we now have a working
1493 resetPQExpBuffer(&conn->errorMessage);
1494 return 1; /* success! */
1496 case PGRES_POLLING_READING:
1497 if (pqWaitTimed(1, 0, conn, finish_time))
1499 conn->status = CONNECTION_BAD;
1504 case PGRES_POLLING_WRITING:
1505 if (pqWaitTimed(0, 1, conn, finish_time))
1507 conn->status = CONNECTION_BAD;
1513 /* Just in case we failed to set it in PQconnectPoll */
1514 conn->status = CONNECTION_BAD;
1519 * Now try to advance the state machine.
1521 flag = PQconnectPoll(conn);
1528 * Poll an asynchronous connection.
1530 * Returns a PostgresPollingStatusType.
1531 * Before calling this function, use select(2) to determine when data
1534 * You must call PQfinish whether or not this fails.
1536 * This function and PQconnectStart are intended to allow connections to be
1537 * made without blocking the execution of your program on remote I/O. However,
1538 * there are a number of caveats:
1540 * o If you call PQtrace, ensure that the stream object into which you trace
1542 * o If you do not supply an IP address for the remote host (i.e. you
1543 * supply a host name instead) then PQconnectStart will block on
1544 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1545 * supplying neither a host name nor a host address).
1546 * o If your backend wants to use Kerberos authentication then you must
1547 * supply both a host name and a host address, otherwise this function
1548 * may block on gethostname.
1552 PostgresPollingStatusType
1553 PQconnectPoll(PGconn *conn)
1560 return PGRES_POLLING_FAILED;
1562 /* Get the new data */
1563 switch (conn->status)
1566 * We really shouldn't have been polled in these two cases, but we
1569 case CONNECTION_BAD:
1570 return PGRES_POLLING_FAILED;
1572 return PGRES_POLLING_OK;
1574 /* These are reading states */
1575 case CONNECTION_AWAITING_RESPONSE:
1576 case CONNECTION_AUTH_OK:
1578 /* Load waiting data */
1579 int n = pqReadData(conn);
1584 return PGRES_POLLING_READING;
1589 /* These are writing states, so we just proceed. */
1590 case CONNECTION_STARTED:
1591 case CONNECTION_MADE:
1594 /* We allow pqSetenvPoll to decide whether to proceed. */
1595 case CONNECTION_SETENV:
1598 /* Special cases: proceed without waiting. */
1599 case CONNECTION_SSL_STARTUP:
1600 case CONNECTION_NEEDED:
1604 appendPQExpBuffer(&conn->errorMessage,
1606 "invalid connection state, "
1607 "probably indicative of memory corruption\n"
1613 keep_going: /* We will come back to here until there is
1614 * nothing left to do. */
1615 switch (conn->status)
1617 case CONNECTION_NEEDED:
1620 * Try to initiate a connection to one of the addresses
1621 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1622 * next one to try. We fail when we run out of addresses.
1624 while (conn->addr_cur != NULL)
1626 struct addrinfo *addr_cur = conn->addr_cur;
1628 /* Remember current address for possible error msg */
1629 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1630 addr_cur->ai_addrlen);
1631 conn->raddr.salen = addr_cur->ai_addrlen;
1634 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1638 * ignore socket() failure if we have more addresses
1641 if (addr_cur->ai_next != NULL)
1643 conn->addr_cur = addr_cur->ai_next;
1646 appendPQExpBuffer(&conn->errorMessage,
1647 libpq_gettext("could not create socket: %s\n"),
1648 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1653 * Select socket options: no delay of outgoing data for
1654 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1657 if (!IS_AF_UNIX(addr_cur->ai_family))
1659 if (!connectNoDelay(conn))
1661 pqDropConnection(conn);
1662 conn->addr_cur = addr_cur->ai_next;
1666 if (!pg_set_noblock(conn->sock))
1668 appendPQExpBuffer(&conn->errorMessage,
1669 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1670 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1671 pqDropConnection(conn);
1672 conn->addr_cur = addr_cur->ai_next;
1677 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1679 appendPQExpBuffer(&conn->errorMessage,
1680 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1681 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1682 pqDropConnection(conn);
1683 conn->addr_cur = addr_cur->ai_next;
1686 #endif /* F_SETFD */
1688 if (!IS_AF_UNIX(addr_cur->ai_family))
1693 int usekeepalives = useKeepalives(conn);
1696 if (usekeepalives < 0)
1698 appendPQExpBuffer(&conn->errorMessage,
1699 libpq_gettext("keepalives parameter must be an integer\n"));
1702 else if (usekeepalives == 0)
1707 else if (setsockopt(conn->sock,
1708 SOL_SOCKET, SO_KEEPALIVE,
1709 (char *) &on, sizeof(on)) < 0)
1711 appendPQExpBuffer(&conn->errorMessage,
1712 libpq_gettext("setsockopt(SO_KEEPALIVE) failed: %s\n"),
1713 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1716 else if (!setKeepalivesIdle(conn)
1717 || !setKeepalivesInterval(conn)
1718 || !setKeepalivesCount(conn))
1721 #ifdef SIO_KEEPALIVE_VALS
1722 else if (!setKeepalivesWin32(conn))
1724 #endif /* SIO_KEEPALIVE_VALS */
1729 pqDropConnection(conn);
1730 conn->addr_cur = addr_cur->ai_next;
1736 * We have three methods of blocking SIGPIPE during
1737 * send() calls to this socket:
1739 * - setsockopt(sock, SO_NOSIGPIPE)
1740 * - send(sock, ..., MSG_NOSIGNAL)
1741 * - setting the signal mask to SIG_IGN during send()
1743 * The third method requires three syscalls per send,
1744 * so we prefer either of the first two, but they are
1745 * less portable. The state is tracked in the following
1746 * members of PGconn:
1748 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
1749 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
1751 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
1752 * and we're done. Otherwise, set sigpipe_flag so that
1753 * we will try MSG_NOSIGNAL on sends. If we get an error
1754 * with MSG_NOSIGNAL, we'll clear that flag and revert to
1758 conn->sigpipe_so = false;
1760 conn->sigpipe_flag = true;
1762 conn->sigpipe_flag = false;
1763 #endif /* MSG_NOSIGNAL */
1767 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
1768 (char *) &optval, sizeof(optval)) == 0)
1770 conn->sigpipe_so = true;
1771 conn->sigpipe_flag = false;
1773 #endif /* SO_NOSIGPIPE */
1776 * Start/make connection. This should not block, since we
1777 * are in nonblock mode. If it does, well, too bad.
1779 if (connect(conn->sock, addr_cur->ai_addr,
1780 addr_cur->ai_addrlen) < 0)
1782 if (SOCK_ERRNO == EINPROGRESS ||
1783 SOCK_ERRNO == EWOULDBLOCK ||
1784 SOCK_ERRNO == EINTR ||
1788 * This is fine - we're in non-blocking mode, and
1789 * the connection is in progress. Tell caller to
1790 * wait for write-ready on socket.
1792 conn->status = CONNECTION_STARTED;
1793 return PGRES_POLLING_WRITING;
1795 /* otherwise, trouble */
1800 * Hm, we're connected already --- seems the "nonblock
1801 * connection" wasn't. Advance the state machine and
1802 * go do the next stuff.
1804 conn->status = CONNECTION_STARTED;
1809 * This connection failed --- set up error report, then
1810 * close socket (do it this way in case close() affects
1811 * the value of errno...). We will ignore the connect()
1812 * failure and keep going if there are more addresses.
1814 connectFailureMessage(conn, SOCK_ERRNO);
1815 pqDropConnection(conn);
1818 * Try the next address, if any.
1820 conn->addr_cur = addr_cur->ai_next;
1821 } /* loop over addresses */
1824 * Ooops, no more addresses. An appropriate error message is
1825 * already set up, so just set the right status.
1830 case CONNECTION_STARTED:
1832 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1835 * Write ready, since we've made it here, so the connection
1836 * has been made ... or has failed.
1840 * Now check (using getsockopt) that there is not an error
1841 * state waiting for us on the socket.
1844 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1845 (char *) &optval, &optlen) == -1)
1847 appendPQExpBuffer(&conn->errorMessage,
1848 libpq_gettext("could not get socket error status: %s\n"),
1849 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1852 else if (optval != 0)
1855 * When using a nonblocking connect, we will typically see
1856 * connect failures at this point, so provide a friendly
1859 connectFailureMessage(conn, optval);
1860 pqDropConnection(conn);
1863 * If more addresses remain, keep trying, just as in the
1864 * case where connect() returned failure immediately.
1866 if (conn->addr_cur->ai_next != NULL)
1868 conn->addr_cur = conn->addr_cur->ai_next;
1869 conn->status = CONNECTION_NEEDED;
1875 /* Fill in the client address */
1876 conn->laddr.salen = sizeof(conn->laddr.addr);
1877 if (getsockname(conn->sock,
1878 (struct sockaddr *) & conn->laddr.addr,
1879 &conn->laddr.salen) < 0)
1881 appendPQExpBuffer(&conn->errorMessage,
1882 libpq_gettext("could not get client address from socket: %s\n"),
1883 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1888 * Make sure we can write before advancing to next step.
1890 conn->status = CONNECTION_MADE;
1891 return PGRES_POLLING_WRITING;
1894 case CONNECTION_MADE:
1899 #ifdef HAVE_UNIX_SOCKETS
1902 * Implement requirepeer check, if requested and it's a
1903 * Unix-domain socket.
1905 if (conn->requirepeer && conn->requirepeer[0] &&
1906 IS_AF_UNIX(conn->raddr.addr.ss_family))
1908 char pwdbuf[BUFSIZ];
1909 struct passwd pass_buf;
1910 struct passwd *pass;
1915 if (getpeereid(conn->sock, &uid, &gid) != 0)
1918 * Provide special error message if getpeereid is a
1921 if (errno == ENOSYS)
1922 appendPQExpBuffer(&conn->errorMessage,
1923 libpq_gettext("requirepeer parameter is not supported on this platform\n"));
1925 appendPQExpBuffer(&conn->errorMessage,
1926 libpq_gettext("could not get peer credentials: %s\n"),
1927 pqStrerror(errno, sebuf, sizeof(sebuf)));
1931 pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
1935 appendPQExpBuffer(&conn->errorMessage,
1936 libpq_gettext("local user with ID %d does not exist\n"),
1941 if (strcmp(pass->pw_name, conn->requirepeer) != 0)
1943 appendPQExpBuffer(&conn->errorMessage,
1944 libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
1945 conn->requirepeer, pass->pw_name);
1949 #endif /* HAVE_UNIX_SOCKETS */
1954 * If SSL is enabled and we haven't already got it running,
1955 * request it instead of sending the startup message.
1957 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1959 /* Don't bother requesting SSL over a Unix socket */
1960 conn->allow_ssl_try = false;
1962 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1968 * Send the SSL request packet.
1970 * Theoretically, this could block, but it really
1971 * shouldn't since we only got here if the socket is
1974 pv = htonl(NEGOTIATE_SSL_CODE);
1975 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1977 appendPQExpBuffer(&conn->errorMessage,
1978 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1979 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1982 /* Ok, wait for response */
1983 conn->status = CONNECTION_SSL_STARTUP;
1984 return PGRES_POLLING_READING;
1986 #endif /* USE_SSL */
1989 * Build the startup packet.
1991 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1992 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1993 EnvironmentOptions);
1995 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1996 EnvironmentOptions);
2000 * will not appendbuffer here, since it's likely to also
2003 printfPQExpBuffer(&conn->errorMessage,
2004 libpq_gettext("out of memory\n"));
2009 * Send the startup packet.
2011 * Theoretically, this could block, but it really shouldn't
2012 * since we only got here if the socket is write-ready.
2014 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2016 appendPQExpBuffer(&conn->errorMessage,
2017 libpq_gettext("could not send startup packet: %s\n"),
2018 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2025 conn->status = CONNECTION_AWAITING_RESPONSE;
2026 return PGRES_POLLING_READING;
2030 * Handle SSL negotiation: wait for postmaster messages and
2031 * respond as necessary.
2033 case CONNECTION_SSL_STARTUP:
2036 PostgresPollingStatusType pollres;
2039 * On first time through, get the postmaster's response to our
2040 * SSL negotiation packet.
2042 if (conn->ssl == NULL)
2045 * We use pqReadData here since it has the logic to
2046 * distinguish no-data-yet from connection closure. Since
2047 * conn->ssl isn't set, a plain recv() will occur.
2052 rdresult = pqReadData(conn);
2055 /* errorMessage is already filled in */
2060 /* caller failed to wait for data */
2061 return PGRES_POLLING_READING;
2063 if (pqGetc(&SSLok, conn) < 0)
2065 /* should not happen really */
2066 return PGRES_POLLING_READING;
2070 /* mark byte consumed */
2071 conn->inStart = conn->inCursor;
2072 /* Set up global SSL state if required */
2073 if (pqsecure_initialize(conn) != 0)
2076 else if (SSLok == 'N')
2078 /* mark byte consumed */
2079 conn->inStart = conn->inCursor;
2080 /* OK to do without SSL? */
2081 if (conn->sslmode[0] == 'r' || /* "require" */
2082 conn->sslmode[0] == 'v') /* "verify-ca" or
2085 /* Require SSL, but server does not want it */
2086 appendPQExpBuffer(&conn->errorMessage,
2087 libpq_gettext("server does not support SSL, but SSL was required\n"));
2090 /* Otherwise, proceed with normal startup */
2091 conn->allow_ssl_try = false;
2092 conn->status = CONNECTION_MADE;
2093 return PGRES_POLLING_WRITING;
2095 else if (SSLok == 'E')
2098 * Server failure of some sort, such as failure to
2099 * fork a backend process. We need to process and
2100 * report the error message, which might be formatted
2101 * according to either protocol 2 or protocol 3.
2102 * Rather than duplicate the code for that, we flip
2103 * into AWAITING_RESPONSE state and let the code there
2104 * deal with it. Note we have *not* consumed the "E"
2107 conn->status = CONNECTION_AWAITING_RESPONSE;
2112 appendPQExpBuffer(&conn->errorMessage,
2113 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2120 * Begin or continue the SSL negotiation process.
2122 pollres = pqsecure_open_client(conn);
2123 if (pollres == PGRES_POLLING_OK)
2125 /* SSL handshake done, ready to send startup packet */
2126 conn->status = CONNECTION_MADE;
2127 return PGRES_POLLING_WRITING;
2129 if (pollres == PGRES_POLLING_FAILED)
2132 * Failed ... if sslmode is "prefer" then do a non-SSL
2135 if (conn->sslmode[0] == 'p' /* "prefer" */
2136 && conn->allow_ssl_try /* redundant? */
2137 && !conn->wait_ssl_try) /* redundant? */
2139 /* only retry once */
2140 conn->allow_ssl_try = false;
2141 /* Must drop the old connection */
2142 pqDropConnection(conn);
2143 conn->status = CONNECTION_NEEDED;
2148 #else /* !USE_SSL */
2149 /* can't get here */
2151 #endif /* USE_SSL */
2155 * Handle authentication exchange: wait for postmaster messages
2156 * and respond as necessary.
2158 case CONNECTION_AWAITING_RESPONSE:
2166 * Scan the message from current point (note that if we find
2167 * the message is incomplete, we will return without advancing
2168 * inStart, and resume here next time).
2170 conn->inCursor = conn->inStart;
2172 /* Read type byte */
2173 if (pqGetc(&beresp, conn))
2175 /* We'll come back when there is more data */
2176 return PGRES_POLLING_READING;
2180 * Validate message type: we expect only an authentication
2181 * request or an error here. Anything else probably means
2182 * it's not Postgres on the other end at all.
2184 if (!(beresp == 'R' || beresp == 'E'))
2186 appendPQExpBuffer(&conn->errorMessage,
2188 "expected authentication request from "
2189 "server, but received %c\n"),
2194 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2196 /* Read message length word */
2197 if (pqGetInt(&msgLength, 4, conn))
2199 /* We'll come back when there is more data */
2200 return PGRES_POLLING_READING;
2205 /* Set phony message length to disable checks below */
2210 * Try to validate message length before using it.
2211 * Authentication requests can't be very large, although GSS
2212 * auth requests may not be that small. Errors can be a
2213 * little larger, but not huge. If we see a large apparent
2214 * length in an error, it means we're really talking to a
2215 * pre-3.0-protocol server; cope.
2217 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2219 appendPQExpBuffer(&conn->errorMessage,
2221 "expected authentication request from "
2222 "server, but received %c\n"),
2227 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2229 /* Handle error from a pre-3.0 server */
2230 conn->inCursor = conn->inStart + 1; /* reread data */
2231 if (pqGets_append(&conn->errorMessage, conn))
2233 /* We'll come back when there is more data */
2234 return PGRES_POLLING_READING;
2236 /* OK, we read the message; mark data consumed */
2237 conn->inStart = conn->inCursor;
2240 * The postmaster typically won't end its message with a
2241 * newline, so add one to conform to libpq conventions.
2243 appendPQExpBufferChar(&conn->errorMessage, '\n');
2246 * If we tried to open the connection in 3.0 protocol,
2247 * fall back to 2.0 protocol.
2249 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2251 conn->pversion = PG_PROTOCOL(2, 0);
2252 /* Must drop the old connection */
2253 pqDropConnection(conn);
2254 conn->status = CONNECTION_NEEDED;
2262 * Can't process if message body isn't all here yet.
2264 * (In protocol 2.0 case, we are assuming messages carry at
2265 * least 4 bytes of data.)
2268 avail = conn->inEnd - conn->inCursor;
2269 if (avail < msgLength)
2272 * Before returning, try to enlarge the input buffer if
2273 * needed to hold the whole message; see notes in
2276 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2279 /* We'll come back when there is more data */
2280 return PGRES_POLLING_READING;
2283 /* Handle errors. */
2286 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2288 if (pqGetErrorNotice3(conn, true))
2290 /* We'll come back when there is more data */
2291 return PGRES_POLLING_READING;
2296 if (pqGets_append(&conn->errorMessage, conn))
2298 /* We'll come back when there is more data */
2299 return PGRES_POLLING_READING;
2302 /* OK, we read the message; mark data consumed */
2303 conn->inStart = conn->inCursor;
2308 * if sslmode is "allow" and we haven't tried an SSL
2309 * connection already, then retry with an SSL connection
2311 if (conn->sslmode[0] == 'a' /* "allow" */
2312 && conn->ssl == NULL
2313 && conn->allow_ssl_try
2314 && conn->wait_ssl_try)
2316 /* only retry once */
2317 conn->wait_ssl_try = false;
2318 /* Must drop the old connection */
2319 pqDropConnection(conn);
2320 conn->status = CONNECTION_NEEDED;
2325 * if sslmode is "prefer" and we're in an SSL connection,
2326 * then do a non-SSL retry
2328 if (conn->sslmode[0] == 'p' /* "prefer" */
2329 && conn->allow_ssl_try
2330 && !conn->wait_ssl_try) /* redundant? */
2332 /* only retry once */
2333 conn->allow_ssl_try = false;
2334 /* Must drop the old connection */
2335 pqDropConnection(conn);
2336 conn->status = CONNECTION_NEEDED;
2344 /* It is an authentication request. */
2345 conn->auth_req_received = true;
2347 /* Get the type of request. */
2348 if (pqGetInt((int *) &areq, 4, conn))
2350 /* We'll come back when there are more data */
2351 return PGRES_POLLING_READING;
2354 /* Get the password salt if there is one. */
2355 if (areq == AUTH_REQ_MD5)
2357 if (pqGetnchar(conn->md5Salt,
2358 sizeof(conn->md5Salt), conn))
2360 /* We'll come back when there are more data */
2361 return PGRES_POLLING_READING;
2364 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2367 * Continue GSSAPI/SSPI authentication
2369 if (areq == AUTH_REQ_GSS_CONT)
2371 int llen = msgLength - 4;
2374 * We can be called repeatedly for the same buffer. Avoid
2375 * re-allocating the buffer in this case - just re-use the
2378 if (llen != conn->ginbuf.length)
2380 if (conn->ginbuf.value)
2381 free(conn->ginbuf.value);
2383 conn->ginbuf.length = llen;
2384 conn->ginbuf.value = malloc(llen);
2385 if (!conn->ginbuf.value)
2387 printfPQExpBuffer(&conn->errorMessage,
2388 libpq_gettext("out of memory allocating GSSAPI buffer (%d)"),
2394 if (pqGetnchar(conn->ginbuf.value, llen, conn))
2396 /* We'll come back when there is more data. */
2397 return PGRES_POLLING_READING;
2403 * OK, we successfully read the message; mark data consumed
2405 conn->inStart = conn->inCursor;
2407 /* Respond to the request if necessary. */
2410 * Note that conn->pghost must be non-NULL if we are going to
2411 * avoid the Kerberos code doing a hostname look-up.
2414 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
2416 conn->errorMessage.len = strlen(conn->errorMessage.data);
2419 conn->errorMessage.len = strlen(conn->errorMessage.data);
2422 * Just make sure that any data sent by pg_fe_sendauth is
2423 * flushed out. Although this theoretically could block, it
2424 * really shouldn't since we don't send large auth responses.
2429 if (areq == AUTH_REQ_OK)
2431 /* We are done with authentication exchange */
2432 conn->status = CONNECTION_AUTH_OK;
2435 * Set asyncStatus so that PQgetResult will think that
2436 * what comes back next is the result of a query. See
2439 conn->asyncStatus = PGASYNC_BUSY;
2442 /* Look to see if we have more data yet. */
2446 case CONNECTION_AUTH_OK:
2449 * Now we expect to hear from the backend. A ReadyForQuery
2450 * message indicates that startup is successful, but we might
2451 * also get an Error message indicating failure. (Notice
2452 * messages indicating nonfatal warnings are also allowed by
2453 * the protocol, as are ParameterStatus and BackendKeyData
2454 * messages.) Easiest way to handle this is to let
2455 * PQgetResult() read the messages. We just have to fake it
2456 * out about the state of the connection, by setting
2457 * asyncStatus = PGASYNC_BUSY (done above).
2461 return PGRES_POLLING_READING;
2463 res = PQgetResult(conn);
2466 * NULL return indicating we have gone to IDLE state is
2471 if (res->resultStatus != PGRES_FATAL_ERROR)
2472 appendPQExpBuffer(&conn->errorMessage,
2473 libpq_gettext("unexpected message from server during startup\n"));
2474 else if (conn->send_appname &&
2475 (conn->appname || conn->fbappname))
2478 * If we tried to send application_name, check to see
2479 * if the error is about that --- pre-9.0 servers will
2480 * reject it at this stage of the process. If so,
2481 * close the connection and retry without sending
2482 * application_name. We could possibly get a false
2483 * SQLSTATE match here and retry uselessly, but there
2484 * seems no great harm in that; we'll just get the
2485 * same error again if it's unrelated.
2487 const char *sqlstate;
2489 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2491 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2494 conn->send_appname = false;
2495 /* Must drop the old connection */
2496 pqDropConnection(conn);
2497 conn->status = CONNECTION_NEEDED;
2503 * if the resultStatus is FATAL, then conn->errorMessage
2504 * already has a copy of the error; needn't copy it back.
2505 * But add a newline if it's not there already, since
2506 * postmaster error messages may not have one.
2508 if (conn->errorMessage.len <= 0 ||
2509 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2510 appendPQExpBufferChar(&conn->errorMessage, '\n');
2515 /* We can release the address list now. */
2516 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2517 conn->addrlist = NULL;
2518 conn->addr_cur = NULL;
2520 /* Fire up post-connection housekeeping if needed */
2521 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2523 conn->status = CONNECTION_SETENV;
2524 conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
2525 conn->next_eo = EnvironmentOptions;
2526 return PGRES_POLLING_WRITING;
2529 /* Otherwise, we are open for business! */
2530 conn->status = CONNECTION_OK;
2531 return PGRES_POLLING_OK;
2534 case CONNECTION_SETENV:
2537 * Do post-connection housekeeping (only needed in protocol 2.0).
2539 * We pretend that the connection is OK for the duration of these
2542 conn->status = CONNECTION_OK;
2544 switch (pqSetenvPoll(conn))
2546 case PGRES_POLLING_OK: /* Success */
2549 case PGRES_POLLING_READING: /* Still going */
2550 conn->status = CONNECTION_SETENV;
2551 return PGRES_POLLING_READING;
2553 case PGRES_POLLING_WRITING: /* Still going */
2554 conn->status = CONNECTION_SETENV;
2555 return PGRES_POLLING_WRITING;
2561 /* We are open for business! */
2562 conn->status = CONNECTION_OK;
2563 return PGRES_POLLING_OK;
2566 appendPQExpBuffer(&conn->errorMessage,
2567 libpq_gettext("invalid connection state %d, "
2568 "probably indicative of memory corruption\n"),
2577 dot_pg_pass_warning(conn);
2580 * We used to close the socket at this point, but that makes it awkward
2581 * for those above us if they wish to remove this socket from their own
2582 * records (an fd_set for example). We'll just have this socket closed
2583 * when PQfinish is called (which is compulsory even after an error, since
2584 * the connection structure must be freed).
2586 conn->status = CONNECTION_BAD;
2587 return PGRES_POLLING_FAILED;
2593 * Determine if a server is running and if we can connect to it.
2595 * The argument is a connection that's been started, but not completed.
2598 internal_ping(PGconn *conn)
2600 /* Say "no attempt" if we never got to PQconnectPoll */
2601 if (!conn || !conn->options_valid)
2602 return PQPING_NO_ATTEMPT;
2604 /* Attempt to complete the connection */
2605 if (conn->status != CONNECTION_BAD)
2606 (void) connectDBComplete(conn);
2608 /* Definitely OK if we succeeded */
2609 if (conn->status != CONNECTION_BAD)
2613 * Here begins the interesting part of "ping": determine the cause of the
2614 * failure in sufficient detail to decide what to return. We do not want
2615 * to report that the server is not up just because we didn't have a valid
2616 * password, for example. In fact, any sort of authentication request
2617 * implies the server is up. (We need this check since the libpq side of
2618 * things might have pulled the plug on the connection before getting an
2619 * error as such from the postmaster.)
2621 if (conn->auth_req_received)
2625 * If we failed to get any ERROR response from the postmaster, report
2626 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
2627 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
2628 * out of support. Another corner case where the server could return a
2629 * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
2630 * totally unreasonable for that anyway. We expect that every other
2631 * failure case in a modern server will produce a report with a SQLSTATE.
2633 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
2634 * client-side errors, we should either not store those into
2635 * last_sqlstate, or add an extra flag so we can tell client-side errors
2636 * apart from server-side ones.
2638 if (strlen(conn->last_sqlstate) != 5)
2639 return PQPING_NO_RESPONSE;
2642 * Report PQPING_REJECT if server says it's not accepting connections. (We
2643 * distinguish this case mainly for the convenience of pg_ctl.)
2645 if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
2646 return PQPING_REJECT;
2649 * Any other SQLSTATE can be taken to indicate that the server is up.
2650 * Presumably it didn't like our username, password, or database name; or
2651 * perhaps it had some transient failure, but that should not be taken as
2652 * meaning "it's down".
2660 * - create a PGconn data structure with (as yet) no interesting data
2663 makeEmptyPGconn(void)
2670 * Make sure socket support is up and running.
2674 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
2679 conn = (PGconn *) malloc(sizeof(PGconn));
2688 /* Zero all pointers and booleans */
2689 MemSet(conn, 0, sizeof(PGconn));
2691 /* install default notice hooks */
2692 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2693 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2695 conn->status = CONNECTION_BAD;
2696 conn->asyncStatus = PGASYNC_IDLE;
2697 conn->xactStatus = PQTRANS_IDLE;
2698 conn->options_valid = false;
2699 conn->nonblocking = false;
2700 conn->setenv_state = SETENV_STATE_IDLE;
2701 conn->client_encoding = PG_SQL_ASCII;
2702 conn->std_strings = false; /* unless server says differently */
2703 conn->verbosity = PQERRORS_DEFAULT;
2705 conn->auth_req_received = false;
2706 conn->password_needed = false;
2707 conn->dot_pgpass_used = false;
2709 conn->allow_ssl_try = true;
2710 conn->wait_ssl_try = false;
2714 * We try to send at least 8K at a time, which is the usual size of pipe
2715 * buffers on Unix systems. That way, when we are sending a large amount
2716 * of data, we avoid incurring extra kernel context swaps for partial
2717 * bufferloads. The output buffer is initially made 16K in size, and we
2718 * try to dump it after accumulating 8K.
2720 * With the same goal of minimizing context swaps, the input buffer will
2721 * be enlarged anytime it has less than 8K free, so we initially allocate
2724 conn->inBufSize = 16 * 1024;
2725 conn->inBuffer = (char *) malloc(conn->inBufSize);
2726 conn->outBufSize = 16 * 1024;
2727 conn->outBuffer = (char *) malloc(conn->outBufSize);
2728 conn->rowBufLen = 32;
2729 conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
2730 initPQExpBuffer(&conn->errorMessage);
2731 initPQExpBuffer(&conn->workBuffer);
2733 if (conn->inBuffer == NULL ||
2734 conn->outBuffer == NULL ||
2735 conn->rowBuf == NULL ||
2736 PQExpBufferBroken(&conn->errorMessage) ||
2737 PQExpBufferBroken(&conn->workBuffer))
2739 /* out of memory already :-( */
2749 * - free an idle (closed) PGconn data structure
2751 * NOTE: this should not overlap any functionality with closePGconn().
2752 * Clearing/resetting of transient state belongs there; what we do here is
2753 * release data that is to be held for the life of the PGconn structure.
2754 * If a value ought to be cleared/freed during PQreset(), do it there not here.
2757 freePGconn(PGconn *conn)
2761 /* let any event procs clean up their state data */
2762 for (i = 0; i < conn->nEvents; i++)
2764 PGEventConnDestroy evt;
2767 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2768 conn->events[i].passThrough);
2769 free(conn->events[i].name);
2772 if (conn->client_encoding_initial)
2773 free(conn->client_encoding_initial);
2778 if (conn->pghostaddr)
2779 free(conn->pghostaddr);
2782 if (conn->pgunixsocket)
2783 free(conn->pgunixsocket);
2786 if (conn->connect_timeout)
2787 free(conn->connect_timeout);
2788 if (conn->pgoptions)
2789 free(conn->pgoptions);
2791 free(conn->appname);
2792 if (conn->fbappname)
2793 free(conn->fbappname);
2796 if (conn->replication)
2797 free(conn->replication);
2802 if (conn->keepalives)
2803 free(conn->keepalives);
2804 if (conn->keepalives_idle)
2805 free(conn->keepalives_idle);
2806 if (conn->keepalives_interval)
2807 free(conn->keepalives_interval);
2808 if (conn->keepalives_count)
2809 free(conn->keepalives_count);
2811 free(conn->sslmode);
2813 free(conn->sslcert);
2816 if (conn->sslrootcert)
2817 free(conn->sslrootcert);
2820 if (conn->sslcompression)
2821 free(conn->sslcompression);
2822 if (conn->requirepeer)
2823 free(conn->requirepeer);
2824 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2825 if (conn->krbsrvname)
2826 free(conn->krbsrvname);
2828 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2832 /* Note that conn->Pfdebug is not ours to close or free */
2833 if (conn->last_query)
2834 free(conn->last_query);
2836 free(conn->inBuffer);
2837 if (conn->outBuffer)
2838 free(conn->outBuffer);
2841 termPQExpBuffer(&conn->errorMessage);
2842 termPQExpBuffer(&conn->workBuffer);
2853 * - properly close a connection to the backend
2855 * This should reset or release all transient state, but NOT the connection
2856 * parameters. On exit, the PGconn should be in condition to start a fresh
2857 * connection with the same parameters (see PQreset()).
2860 closePGconn(PGconn *conn)
2863 pgParameterStatus *pstatus;
2866 * Note that the protocol doesn't allow us to send Terminate messages
2867 * during the startup phase.
2869 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2872 * Try to send "close connection" message to backend. Ignore any
2875 pqPutMsgStart('X', false, conn);
2881 * Must reset the blocking status so a possible reconnect will work.
2883 * Don't call PQsetnonblocking() because it will fail if it's unable to
2884 * flush the connection.
2886 conn->nonblocking = FALSE;
2889 * Close the connection, reset all transient state, flush I/O buffers.
2891 pqDropConnection(conn);
2892 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2894 conn->asyncStatus = PGASYNC_IDLE;
2895 pqClearAsyncResult(conn); /* deallocate result */
2896 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2897 conn->addrlist = NULL;
2898 conn->addr_cur = NULL;
2899 notify = conn->notifyHead;
2900 while (notify != NULL)
2902 PGnotify *prev = notify;
2904 notify = notify->next;
2907 conn->notifyHead = conn->notifyTail = NULL;
2908 pstatus = conn->pstatus;
2909 while (pstatus != NULL)
2911 pgParameterStatus *prev = pstatus;
2913 pstatus = pstatus->next;
2916 conn->pstatus = NULL;
2917 if (conn->lobjfuncs)
2918 free(conn->lobjfuncs);
2919 conn->lobjfuncs = NULL;
2925 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2926 if (conn->gtarg_nam)
2927 gss_release_name(&min_s, &conn->gtarg_nam);
2928 if (conn->ginbuf.length)
2929 gss_release_buffer(&min_s, &conn->ginbuf);
2930 if (conn->goutbuf.length)
2931 gss_release_buffer(&min_s, &conn->goutbuf);
2935 if (conn->ginbuf.length)
2936 free(conn->ginbuf.value);
2937 conn->ginbuf.length = 0;
2938 conn->ginbuf.value = NULL;
2939 if (conn->sspitarget)
2940 free(conn->sspitarget);
2941 conn->sspitarget = NULL;
2944 FreeCredentialsHandle(conn->sspicred);
2945 free(conn->sspicred);
2946 conn->sspicred = NULL;
2950 DeleteSecurityContext(conn->sspictx);
2951 free(conn->sspictx);
2952 conn->sspictx = NULL;
2958 * PQfinish: properly close a connection to the backend. Also frees
2959 * the PGconn data structure so it shouldn't be re-used after this.
2962 PQfinish(PGconn *conn)
2972 * PQreset: resets the connection to the backend by closing the
2973 * existing connection and creating a new one.
2976 PQreset(PGconn *conn)
2982 if (connectDBStart(conn) && connectDBComplete(conn))
2985 * Notify event procs of successful reset. We treat an event proc
2986 * failure as disabling the connection ... good idea?
2990 for (i = 0; i < conn->nEvents; i++)
2992 PGEventConnReset evt;
2995 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2996 conn->events[i].passThrough))
2998 conn->status = CONNECTION_BAD;
2999 printfPQExpBuffer(&conn->errorMessage,
3000 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3001 conn->events[i].name);
3012 * resets the connection to the backend
3013 * closes the existing connection and makes a new one
3014 * Returns 1 on success, 0 on failure.
3017 PQresetStart(PGconn *conn)
3023 return connectDBStart(conn);
3032 * resets the connection to the backend
3033 * closes the existing connection and makes a new one
3035 PostgresPollingStatusType
3036 PQresetPoll(PGconn *conn)
3040 PostgresPollingStatusType status = PQconnectPoll(conn);
3042 if (status == PGRES_POLLING_OK)
3045 * Notify event procs of successful reset. We treat an event proc
3046 * failure as disabling the connection ... good idea?
3050 for (i = 0; i < conn->nEvents; i++)
3052 PGEventConnReset evt;
3055 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3056 conn->events[i].passThrough))
3058 conn->status = CONNECTION_BAD;
3059 printfPQExpBuffer(&conn->errorMessage,
3060 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3061 conn->events[i].name);
3062 return PGRES_POLLING_FAILED;
3070 return PGRES_POLLING_FAILED;
3074 * PQcancelGet: get a PGcancel structure corresponding to a connection.
3076 * A copy is needed to be able to cancel a running query from a different
3077 * thread. If the same structure is used all structure members would have
3078 * to be individually locked (if the entire structure was locked, it would
3079 * be impossible to cancel a synchronous query because the structure would
3080 * have to stay locked for the duration of the query).
3083 PQgetCancel(PGconn *conn)
3093 cancel = malloc(sizeof(PGcancel));
3097 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
3098 cancel->be_pid = conn->be_pid;
3099 cancel->be_key = conn->be_key;
3104 /* PQfreeCancel: free a cancel structure */
3106 PQfreeCancel(PGcancel *cancel)
3114 * PQcancel and PQrequestCancel: attempt to request cancellation of the
3115 * current operation.
3117 * The return value is TRUE if the cancel request was successfully
3118 * dispatched, FALSE if not (in which case an error message is available).
3119 * Note: successful dispatch is no guarantee that there will be any effect at
3120 * the backend. The application must read the operation result as usual.
3122 * CAUTION: we want this routine to be safely callable from a signal handler
3123 * (for example, an application might want to call it in a SIGINT handler).
3124 * This means we cannot use any C library routine that might be non-reentrant.
3125 * malloc/free are often non-reentrant, and anything that might call them is
3126 * just as dangerous. We avoid sprintf here for that reason. Building up
3127 * error messages with strcpy/strcat is tedious but should be quite safe.
3128 * We also save/restore errno in case the signal handler support doesn't.
3130 * internal_cancel() is an internal helper function to make code-sharing
3131 * between the two versions of the cancel function possible.
3134 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
3135 char *errbuf, int errbufsize)
3137 int save_errno = SOCK_ERRNO;
3144 CancelRequestPacket cp;
3148 * We need to open a temporary connection to the postmaster. Do this with
3149 * only kernel calls.
3151 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
3153 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
3154 goto cancel_errReturn;
3157 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
3160 if (SOCK_ERRNO == EINTR)
3161 /* Interrupted system call - we'll just try again */
3163 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
3164 goto cancel_errReturn;
3168 * We needn't set nonblocking I/O or NODELAY options here.
3171 /* Create and send the cancel request packet. */
3173 crp.packetlen = htonl((uint32) sizeof(crp));
3174 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
3175 crp.cp.backendPID = htonl(be_pid);
3176 crp.cp.cancelAuthCode = htonl(be_key);
3179 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
3181 if (SOCK_ERRNO == EINTR)
3182 /* Interrupted system call - we'll just try again */
3184 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
3185 goto cancel_errReturn;
3189 * Wait for the postmaster to close the connection, which indicates that
3190 * it's processed the request. Without this delay, we might issue another
3191 * command only to find that our cancel zaps that command instead of the
3192 * one we thought we were canceling. Note we don't actually expect this
3193 * read to obtain any data, we are just waiting for EOF to be signaled.
3196 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
3198 if (SOCK_ERRNO == EINTR)
3199 /* Interrupted system call - we'll just try again */
3201 /* we ignore other error conditions */
3205 closesocket(tmpsock);
3206 SOCK_ERRNO_SET(save_errno);
3212 * Make sure we don't overflow the error buffer. Leave space for the \n at
3213 * the end, and for the terminating zero.
3215 maxlen = errbufsize - strlen(errbuf) - 2;
3218 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
3220 strcat(errbuf, "\n");
3223 closesocket(tmpsock);
3224 SOCK_ERRNO_SET(save_errno);
3229 * PQcancel: request query cancel
3231 * Returns TRUE if able to send the cancel request, FALSE if not.
3233 * On failure, an error message is stored in *errbuf, which must be of size
3234 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
3238 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
3242 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3246 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3247 errbuf, errbufsize);
3251 * PQrequestCancel: old, not thread-safe function for requesting query cancel
3253 * Returns TRUE if able to send the cancel request, FALSE if not.
3255 * On failure, the error message is saved in conn->errorMessage; this means
3256 * that this can't be used when there might be other active operations on
3257 * the connection object.
3259 * NOTE: error messages will be cut off at the current size of the
3260 * error message buffer, since we dare not try to expand conn->errorMessage!
3263 PQrequestCancel(PGconn *conn)
3267 /* Check we have an open connection */
3273 strlcpy(conn->errorMessage.data,
3274 "PQrequestCancel() -- connection is not open\n",
3275 conn->errorMessage.maxlen);
3276 conn->errorMessage.len = strlen(conn->errorMessage.data);
3281 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
3282 conn->errorMessage.data, conn->errorMessage.maxlen);
3285 conn->errorMessage.len = strlen(conn->errorMessage.data);
3292 * pqPacketSend() -- convenience routine to send a message to server.
3294 * pack_type: the single-byte message type code. (Pass zero for startup
3295 * packets, which have no message type code.)
3297 * buf, buf_len: contents of message. The given length includes only what
3298 * is in buf; the message type and message length fields are added here.
3300 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
3301 * SIDE_EFFECTS: may block.
3303 * Note: all messages sent with this routine have a length word, whether
3304 * it's protocol 2.0 or 3.0.
3307 pqPacketSend(PGconn *conn, char pack_type,
3308 const void *buf, size_t buf_len)
3310 /* Start the message. */
3311 if (pqPutMsgStart(pack_type, true, conn))
3312 return STATUS_ERROR;
3314 /* Send the message body. */
3315 if (pqPutnchar(buf, buf_len, conn))
3316 return STATUS_ERROR;
3318 /* Finish the message. */
3319 if (pqPutMsgEnd(conn))
3320 return STATUS_ERROR;
3322 /* Flush to ensure backend gets it. */
3324 return STATUS_ERROR;
3331 #define LDAP_URL "ldap://"
3332 #define LDAP_DEF_PORT 389
3333 #define PGLDAP_TIMEOUT 2
3335 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
3336 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
3342 * Search the LDAP URL passed as first argument, treat the result as a
3343 * string of connection options that are parsed and added to the array of
3344 * options passed as second argument.
3346 * LDAP URLs must conform to RFC 1959 without escape sequences.
3347 * ldap://host:port/dn?attributes?scope?filter?extensions
3350 * 0 if the lookup was successful,
3351 * 1 if the connection to the LDAP server could be established but
3352 * the search was unsuccessful,
3353 * 2 if a connection could not be established, and
3354 * 3 if a fatal error occurred.
3356 * An error message is returned in the third argument for return codes 1 and 3.
3359 ldapServiceLookup(const char *purl, PQconninfoOption *options,
3360 PQExpBuffer errorMessage)
3362 int port = LDAP_DEF_PORT,
3383 char *attrs[2] = {NULL, NULL};
3387 struct berval **values;
3388 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
3390 if ((url = strdup(purl)) == NULL)
3392 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
3397 * Parse URL components, check for correctness. Basically, url has '\0'
3398 * placed at component boundaries and variables are pointed at each
3402 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
3404 printfPQExpBuffer(errorMessage,
3405 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
3411 hostname = url + strlen(LDAP_URL);
3412 if (*hostname == '/') /* no hostname? */
3413 hostname = DefaultHost; /* the default */
3415 /* dn, "distinguished name" */
3416 p = strchr(url + strlen(LDAP_URL), '/');
3417 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3419 printfPQExpBuffer(errorMessage, libpq_gettext(
3420 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
3424 *p = '\0'; /* terminate hostname */
3428 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3430 printfPQExpBuffer(errorMessage, libpq_gettext(
3431 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3439 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3441 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3449 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3451 printfPQExpBuffer(errorMessage,
3452 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
3458 if ((p = strchr(filter, '?')) != NULL)
3462 if ((p1 = strchr(hostname, ':')) != NULL)
3469 lport = strtol(portstr, &endptr, 10);
3470 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
3472 printfPQExpBuffer(errorMessage, libpq_gettext(
3473 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
3480 /* Allow only one attribute */
3481 if (strchr(attrs[0], ',') != NULL)
3483 printfPQExpBuffer(errorMessage, libpq_gettext(
3484 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3490 if (pg_strcasecmp(scopestr, "base") == 0)
3491 scope = LDAP_SCOPE_BASE;
3492 else if (pg_strcasecmp(scopestr, "one") == 0)
3493 scope = LDAP_SCOPE_ONELEVEL;
3494 else if (pg_strcasecmp(scopestr, "sub") == 0)
3495 scope = LDAP_SCOPE_SUBTREE;
3498 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3503 /* initialize LDAP structure */
3504 if ((ld = ldap_init(hostname, port)) == NULL)
3506 printfPQExpBuffer(errorMessage,
3507 libpq_gettext("could not create LDAP structure\n"));
3513 * Initialize connection to the server. We do an explicit bind because we
3514 * want to return 2 if the bind fails.
3516 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3518 /* error in ldap_simple_bind() */
3524 /* wait some time for the connection to succeed */
3526 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3534 /* error in ldap_result() */
3543 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3548 printfPQExpBuffer(errorMessage,
3549 libpq_gettext("lookup on LDAP server failed: %s\n"),
3550 ldap_err2string(rc));
3556 /* complain if there was not exactly one result */
3557 if ((rc = ldap_count_entries(ld, res)) != 1)
3559 printfPQExpBuffer(errorMessage,
3560 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3561 : libpq_gettext("no entry found on LDAP lookup\n"));
3569 if ((entry = ldap_first_entry(ld, res)) == NULL)
3571 /* should never happen */
3572 printfPQExpBuffer(errorMessage,
3573 libpq_gettext("no entry found on LDAP lookup\n"));
3581 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3583 printfPQExpBuffer(errorMessage,
3584 libpq_gettext("attribute has no values on LDAP lookup\n"));
3594 if (values[0] == NULL)
3596 printfPQExpBuffer(errorMessage,
3597 libpq_gettext("attribute has no values on LDAP lookup\n"));
3598 ldap_value_free_len(values);
3603 /* concatenate values into a single string with newline terminators */
3604 size = 1; /* for the trailing null */
3605 for (i = 0; values[i] != NULL; i++)
3606 size += values[i]->bv_len + 1;
3607 if ((result = malloc(size)) == NULL)
3609 printfPQExpBuffer(errorMessage,
3610 libpq_gettext("out of memory\n"));
3611 ldap_value_free_len(values);
3616 for (i = 0; values[i] != NULL; i++)
3618 memcpy(p, values[i]->bv_val, values[i]->bv_len);
3619 p += values[i]->bv_len;
3624 ldap_value_free_len(values);
3627 /* parse result string */
3628 oldstate = state = 0;
3629 for (p = result; *p != '\0'; ++p)
3633 case 0: /* between entries */
3634 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3640 case 1: /* in option name */
3641 if (ld_is_sp_tab(*p))
3646 else if (ld_is_nl_cr(*p))
3648 printfPQExpBuffer(errorMessage, libpq_gettext(
3649 "missing \"=\" after \"%s\" in connection info string\n"),
3660 case 2: /* after option name */
3665 else if (!ld_is_sp_tab(*p))
3667 printfPQExpBuffer(errorMessage, libpq_gettext(
3668 "missing \"=\" after \"%s\" in connection info string\n"),
3674 case 3: /* before option value */
3681 else if (ld_is_nl_cr(*p))
3683 optval = optname + strlen(optname); /* empty */
3686 else if (!ld_is_sp_tab(*p))
3692 case 4: /* in unquoted option value */
3693 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3699 case 5: /* in quoted option value */
3705 else if (*p == '\\')
3710 case 6: /* in quoted option value after escape */
3716 if (state == 0 && oldstate != 0)
3718 found_keyword = false;
3719 for (i = 0; options[i].keyword; i++)
3721 if (strcmp(options[i].keyword, optname) == 0)
3723 if (options[i].val == NULL)
3724 options[i].val = strdup(optval);
3725 found_keyword = true;
3731 printfPQExpBuffer(errorMessage,
3732 libpq_gettext("invalid connection option \"%s\"\n"),
3745 if (state == 5 || state == 6)
3747 printfPQExpBuffer(errorMessage, libpq_gettext(
3748 "unterminated quoted string in connection info string\n"));
3756 #define MAXBUFSIZE 256
3759 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3761 const char *service = conninfo_getval(options, "service");
3762 char serviceFile[MAXPGPATH];
3764 bool group_found = false;
3766 struct stat stat_buf;
3769 * We have to special-case the environment variable PGSERVICE here, since
3770 * this is and should be called before inserting environment defaults for
3771 * other connection options.
3773 if (service == NULL)
3774 service = getenv("PGSERVICE");
3776 if (service == NULL)
3779 if ((env = getenv("PGSERVICEFILE")) != NULL)
3780 strlcpy(serviceFile, env, sizeof(serviceFile));
3783 char homedir[MAXPGPATH];
3785 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3787 printfPQExpBuffer(errorMessage, libpq_gettext("could not get home directory to locate service definition file"));
3790 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
3792 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3796 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3797 if (group_found || status != 0)
3803 * This could be used by any application so we can't use the binary
3804 * location to find our config files.
3806 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3807 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3809 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3812 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3819 printfPQExpBuffer(errorMessage,
3820 libpq_gettext("definition of service \"%s\" not found\n"), service);
3828 parseServiceFile(const char *serviceFile,
3829 const char *service,
3830 PQconninfoOption *options,
3831 PQExpBuffer errorMessage,
3837 char buf[MAXBUFSIZE],
3840 f = fopen(serviceFile, "r");
3843 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3848 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3852 if (strlen(line) >= sizeof(buf) - 1)
3855 printfPQExpBuffer(errorMessage,
3856 libpq_gettext("line %d too long in service file \"%s\"\n"),
3862 /* ignore EOL at end of line */
3863 if (strlen(line) && line[strlen(line) - 1] == '\n')
3864 line[strlen(line) - 1] = 0;
3866 /* ignore leading blanks */
3867 while (*line && isspace((unsigned char) line[0]))
3870 /* ignore comments and empty lines */
3871 if (strlen(line) == 0 || line[0] == '#')
3874 /* Check for right groupname */
3879 /* group info already read */
3884 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3885 line[strlen(service) + 1] == ']')
3886 *group_found = true;
3888 *group_found = false;
3895 * Finally, we are in the right group and can parse the line
3902 if (strncmp(line, "ldap", 4) == 0)
3904 int rc = ldapServiceLookup(line, options, errorMessage);
3906 /* if rc = 2, go on reading for fallback */
3923 val = strchr(line, '=');
3926 printfPQExpBuffer(errorMessage,
3927 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3936 * Set the parameter --- but don't override any previous
3939 found_keyword = false;
3940 for (i = 0; options[i].keyword; i++)
3942 if (strcmp(options[i].keyword, key) == 0)
3944 if (options[i].val == NULL)
3945 options[i].val = strdup(val);
3946 found_keyword = true;
3953 printfPQExpBuffer(errorMessage,
3954 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3973 * Parse a string like PQconnectdb() would do and return the
3974 * resulting connection options array. NULL is returned on failure.
3975 * The result contains only options specified directly in the string,
3976 * not any possible default values.
3978 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3979 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3980 * both *errmsg and the result could be NULL.
3982 * NOTE: the returned array is dynamically allocated and should
3983 * be freed when no longer needed via PQconninfoFree().
3986 PQconninfoParse(const char *conninfo, char **errmsg)
3988 PQExpBufferData errorBuf;
3989 PQconninfoOption *connOptions;
3992 *errmsg = NULL; /* default */
3993 initPQExpBuffer(&errorBuf);
3994 if (PQExpBufferDataBroken(errorBuf))
3995 return NULL; /* out of memory already :-( */
3996 connOptions = parse_connection_string(conninfo, &errorBuf, false);
3997 if (connOptions == NULL && errmsg)
3998 *errmsg = errorBuf.data;
4000 termPQExpBuffer(&errorBuf);
4005 * Build a working copy of the constant PQconninfoOptions array.
4007 static PQconninfoOption *
4008 conninfo_init(PQExpBuffer errorMessage)
4010 PQconninfoOption *options;
4011 PQconninfoOption *opt_dest;
4012 const internalPQconninfoOption *cur_opt;
4015 * Get enough memory for all options in PQconninfoOptions, even if some
4016 * end up being filtered out.
4018 options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4019 if (options == NULL)
4021 printfPQExpBuffer(errorMessage,
4022 libpq_gettext("out of memory\n"));
4027 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4029 /* Only copy the public part of the struct, not the full internal */
4030 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4033 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4039 * Connection string parser
4041 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4042 * Otherwise, NULL is returned and an error message is left in errorMessage.
4044 * If use_defaults is TRUE, default values are filled in (from a service file,
4045 * environment variables, etc).
4047 static PQconninfoOption *
4048 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4051 /* Parse as URI if connection string matches URI prefix */
4052 if (uri_prefix_length(connstr) != 0)
4053 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4055 /* Parse as default otherwise */
4056 return conninfo_parse(connstr, errorMessage, use_defaults);
4060 * Checks if connection string starts with either of the valid URI prefix
4063 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4066 uri_prefix_length(const char *connstr)
4068 if (strncmp(connstr, uri_designator,
4069 sizeof(uri_designator) - 1) == 0)
4070 return sizeof(uri_designator) - 1;
4072 if (strncmp(connstr, short_uri_designator,
4073 sizeof(short_uri_designator) - 1) == 0)
4074 return sizeof(short_uri_designator) - 1;
4080 * Recognized connection string either starts with a valid URI prefix or
4081 * contains a "=" in it.
4083 * Must be consistent with parse_connection_string: anything for which this
4084 * returns true should at least look like it's parseable by that routine.
4087 recognized_connection_string(const char *connstr)
4089 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4093 * Subroutine for parse_connection_string
4095 * Deal with a string containing key=value pairs.
4097 static PQconninfoOption *
4098 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
4106 PQconninfoOption *options;
4108 /* Make a working copy of PQconninfoOptions */
4109 options = conninfo_init(errorMessage);
4110 if (options == NULL)
4113 /* Need a modifiable copy of the input string */
4114 if ((buf = strdup(conninfo)) == NULL)
4116 printfPQExpBuffer(errorMessage,
4117 libpq_gettext("out of memory\n"));
4118 PQconninfoFree(options);
4125 /* Skip blanks before the parameter name */
4126 if (isspace((unsigned char) *cp))
4132 /* Get the parameter name */
4138 if (isspace((unsigned char) *cp))
4143 if (!isspace((unsigned char) *cp))
4152 /* Check that there is a following '=' */
4155 printfPQExpBuffer(errorMessage,
4156 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4158 PQconninfoFree(options);
4164 /* Skip blanks after the '=' */
4167 if (!isspace((unsigned char) *cp))
4172 /* Get the parameter value */
4180 if (isspace((unsigned char) *cp))
4204 printfPQExpBuffer(errorMessage,
4205 libpq_gettext("unterminated quoted string in connection info string\n"));
4206 PQconninfoFree(options);
4228 * Now that we have the name and the value, store the record.
4230 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
4232 PQconninfoFree(options);
4238 /* Done with the modifiable input string */
4242 * Add in defaults if the caller wants that.
4246 if (!conninfo_add_defaults(options, errorMessage))
4248 PQconninfoFree(options);
4257 * Conninfo array parser routine
4259 * If successful, a malloc'd PQconninfoOption array is returned.
4260 * If not successful, NULL is returned and an error message is
4261 * left in errorMessage.
4262 * Defaults are supplied (from a service file, environment variables, etc)
4263 * for unspecified options, but only if use_defaults is TRUE.
4265 * If expand_dbname is non-zero, and the value passed for keyword "dbname" is a
4266 * connection string (as indicated by recognized_connection_string) then parse
4267 * and process it, overriding any previously processed conflicting
4268 * keywords. Subsequent keywords will take precedence, however.
4270 static PQconninfoOption *
4271 conninfo_array_parse(const char *const * keywords, const char *const * values,
4272 PQExpBuffer errorMessage, bool use_defaults,
4275 PQconninfoOption *options;
4276 PQconninfoOption *dbname_options = NULL;
4277 PQconninfoOption *option;
4281 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
4282 * actually a recognized connection string.
4284 while (expand_dbname && keywords[i])
4286 const char *pname = keywords[i];
4287 const char *pvalue = values[i];
4289 /* first find "dbname" if any */
4290 if (strcmp(pname, "dbname") == 0 && pvalue)
4293 * If value is a connection string, parse it, but do not use
4294 * defaults here -- those get picked up later. We only want to
4295 * override for those parameters actually passed.
4297 if (recognized_connection_string(pvalue))
4299 dbname_options = parse_connection_string(pvalue, errorMessage, false);
4300 if (dbname_options == NULL)
4308 /* Make a working copy of PQconninfoOptions */
4309 options = conninfo_init(errorMessage);
4310 if (options == NULL)
4312 PQconninfoFree(dbname_options);
4316 /* Parse the keywords/values arrays */
4320 const char *pname = keywords[i];
4321 const char *pvalue = values[i];
4325 /* Search for the param record */
4326 for (option = options; option->keyword != NULL; option++)
4328 if (strcmp(option->keyword, pname) == 0)
4332 /* Check for invalid connection option */
4333 if (option->keyword == NULL)
4335 printfPQExpBuffer(errorMessage,
4336 libpq_gettext("invalid connection option \"%s\"\n"),
4338 PQconninfoFree(options);
4339 PQconninfoFree(dbname_options);
4344 * If we are on the dbname parameter, and we have a parsed
4345 * connection string, copy those parameters across, overriding any
4346 * existing previous settings.
4348 if (strcmp(pname, "dbname") == 0 && dbname_options)
4350 PQconninfoOption *str_option;
4352 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
4354 if (str_option->val != NULL)
4358 for (k = 0; options[k].keyword; k++)
4360 if (strcmp(options[k].keyword, str_option->keyword) == 0)
4363 free(options[k].val);
4364 options[k].val = strdup(str_option->val);
4374 * Store the value, overriding previous settings
4378 option->val = strdup(pvalue);
4381 printfPQExpBuffer(errorMessage,
4382 libpq_gettext("out of memory\n"));
4383 PQconninfoFree(options);
4384 PQconninfoFree(dbname_options);
4391 PQconninfoFree(dbname_options);
4394 * Add in defaults if the caller wants that.
4398 if (!conninfo_add_defaults(options, errorMessage))
4400 PQconninfoFree(options);
4409 * Add the default values for any unspecified options to the connection
4412 * Defaults are obtained from a service file, environment variables, etc.
4414 * Returns TRUE if successful, otherwise FALSE; errorMessage is filled in
4415 * upon failure. Note that failure to locate a default value is not an
4416 * error condition here --- we just leave the option's value as NULL.
4419 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
4421 PQconninfoOption *option;
4425 * If there's a service spec, use it to obtain any not-explicitly-given
4428 if (parseServiceInfo(options, errorMessage) != 0)
4432 * Get the fallback resources for parameters not specified in the conninfo
4433 * string nor the service.
4435 for (option = options; option->keyword != NULL; option++)
4437 if (option->val != NULL)
4438 continue; /* Value was in conninfo or service */
4441 * Try to get the environment variable fallback
4443 if (option->envvar != NULL)
4445 if ((tmp = getenv(option->envvar)) != NULL)
4447 option->val = strdup(tmp);
4450 printfPQExpBuffer(errorMessage,
4451 libpq_gettext("out of memory\n"));
4459 * No environment variable specified or the variable isn't set - try
4460 * compiled-in default
4462 if (option->compiled != NULL)
4464 option->val = strdup(option->compiled);
4467 printfPQExpBuffer(errorMessage,
4468 libpq_gettext("out of memory\n"));
4475 * Special handling for "user" option
4477 if (strcmp(option->keyword, "user") == 0)
4479 option->val = pg_fe_getauthname(errorMessage);
4488 * Subroutine for parse_connection_string
4490 * Deal with a URI connection string.
4492 static PQconninfoOption *
4493 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
4496 PQconninfoOption *options;
4498 /* Make a working copy of PQconninfoOptions */
4499 options = conninfo_init(errorMessage);
4500 if (options == NULL)
4503 if (!conninfo_uri_parse_options(options, uri, errorMessage))
4505 PQconninfoFree(options);
4510 * Add in defaults if the caller wants that.
4514 if (!conninfo_add_defaults(options, errorMessage))
4516 PQconninfoFree(options);
4525 * conninfo_uri_parse_options
4526 * Actual URI parser.
4528 * If successful, returns true while the options array is filled with parsed
4529 * options from the URI.
4530 * If not successful, returns false and fills errorMessage accordingly.
4532 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
4535 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
4537 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
4538 * by literal square brackets.
4540 * Any of the URI parts might use percent-encoding (%xy).
4543 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
4544 PQExpBuffer errorMessage)
4548 char *buf = strdup(uri); /* need a modifiable copy of the input
4551 char prevchar = '\0';
4554 bool retval = false;
4558 printfPQExpBuffer(errorMessage,
4559 libpq_gettext("out of memory\n"));
4563 /* Skip the URI prefix */
4564 prefix_len = uri_prefix_length(uri);
4565 if (prefix_len == 0)
4567 /* Should never happen */
4568 printfPQExpBuffer(errorMessage,
4569 libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
4573 start += prefix_len;
4576 /* Look ahead for possible user credentials designator */
4577 while (*p && *p != '@' && *p != '/')
4582 * Found username/password designator, so URI should be of the form
4583 * "scheme://user[:password]@[netloc]".
4588 while (*p != ':' && *p != '@')
4591 /* Save last char and cut off at end of user name */
4596 !conninfo_storeval(options, "user", user,
4597 errorMessage, false, true))
4600 if (prevchar == ':')
4602 const char *password = p + 1;
4609 !conninfo_storeval(options, "password", password,
4610 errorMessage, false, true))
4614 /* Advance past end of parsed user name or password token */
4620 * No username/password designator found. Reset to start of URI.
4626 * "p" has been incremented past optional URI credential information at
4627 * this point and now points at the "netloc" part of the URI.
4629 * Look for IPv6 address.
4634 while (*p && *p != ']')
4638 printfPQExpBuffer(errorMessage,
4639 libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
4645 printfPQExpBuffer(errorMessage,
4646 libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
4651 /* Cut off the bracket and advance */
4655 * The address may be followed by a port specifier or a slash or a
4658 if (*p && *p != ':' && *p != '/' && *p != '?')
4660 printfPQExpBuffer(errorMessage,
4661 libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
4662 *p, (int) (p - buf + 1), uri);
4668 /* not an IPv6 address: DNS-named or IPv4 netloc */
4672 * Look for port specifier (colon) or end of host specifier (slash),
4673 * or query (question mark).
4675 while (*p && *p != ':' && *p != '/' && *p != '?')
4679 /* Save the hostname terminator before we null it */
4684 !conninfo_storeval(options, "host", host,
4685 errorMessage, false, true))
4689 if (prevchar == ':')
4691 const char *port = ++p; /* advance past host terminator */
4693 while (*p && *p != '/' && *p != '?')
4700 !conninfo_storeval(options, "port", port,
4701 errorMessage, false, true))
4705 if (prevchar && prevchar != '?')
4707 const char *dbname = ++p; /* advance past host terminator */
4709 /* Look for query parameters */
4710 while (*p && *p != '?')
4717 * Avoid setting dbname to an empty string, as it forces the default
4718 * value (username) and ignores $PGDATABASE, as opposed to not setting
4722 !conninfo_storeval(options, "dbname", dbname,
4723 errorMessage, false, true))
4729 ++p; /* advance past terminator */
4731 if (!conninfo_uri_parse_params(p, options, errorMessage))
4735 /* everything parsed okay */
4744 * Connection URI parameters parser routine
4746 * If successful, returns true while connOptions is filled with parsed
4747 * parameters. Otherwise, returns false and fills errorMessage appropriately.
4749 * Destructively modifies 'params' buffer.
4752 conninfo_uri_parse_params(char *params,
4753 PQconninfoOption *connOptions,
4754 PQExpBuffer errorMessage)
4758 char *keyword = params;
4761 bool malloced = false;
4764 * Scan the params string for '=' and '&', marking the end of keyword
4765 * and value respectively.
4771 /* Was there '=' already? */
4774 printfPQExpBuffer(errorMessage,
4775 libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4779 /* Cut off keyword, advance to value */
4783 else if (*p == '&' || *p == '\0')
4787 /* Cut off value, remember old value */
4791 /* Was there '=' at all? */
4794 printfPQExpBuffer(errorMessage,
4795 libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4801 * If not at the end, advance; now pointing to start of the
4802 * next parameter, if any.
4804 if (prevchar != '\0')
4809 /* Advance, NUL is checked in the 'if' above */
4813 keyword = conninfo_uri_decode(keyword, errorMessage);
4814 if (keyword == NULL)
4816 /* conninfo_uri_decode already set an error message */
4819 value = conninfo_uri_decode(value, errorMessage);
4822 /* conninfo_uri_decode already set an error message */
4829 * Special keyword handling for improved JDBC compatibility.
4831 if (strcmp(keyword, "ssl") == 0 &&
4832 strcmp(value, "true") == 0)
4838 keyword = "sslmode";
4843 * Store the value if the corresponding option exists; ignore
4844 * otherwise. At this point both keyword and value are not
4847 if (!conninfo_storeval(connOptions, keyword, value,
4848 errorMessage, true, false))
4851 * Check if there was a hard error when decoding or storing the
4854 if (errorMessage->len != 0)
4864 printfPQExpBuffer(errorMessage,
4866 "invalid URI query parameter: \"%s\"\n"),
4881 /* Proceed to next key=value pair */
4889 * Connection URI decoder routine
4891 * If successful, returns the malloc'd decoded string.
4892 * If not successful, returns NULL and fills errorMessage accordingly.
4894 * The string is decoded by replacing any percent-encoded tokens with
4895 * corresponding characters, while preserving any non-encoded characters. A
4896 * percent-encoded token is a character triplet: a percent sign, followed by a
4897 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
4898 * treated identically.
4901 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
4903 char *buf = malloc(strlen(str) + 1);
4905 const char *q = str;
4909 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4917 /* copy and check for NUL terminator */
4918 if (!(*(p++) = *(q++)))
4927 ++q; /* skip the percent sign itself */
4930 * Possible EOL will be caught by the first call to
4931 * get_hexdigit(), so we never dereference an invalid q pointer.
4933 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
4935 printfPQExpBuffer(errorMessage,
4936 libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
4945 printfPQExpBuffer(errorMessage,
4946 libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
4959 * Convert hexadecimal digit character to its integer value.
4961 * If successful, returns true and value is filled with digit's base 16 value.
4962 * If not successful, returns false.
4964 * Lower- and upper-case letters in the range A-F are treated identically.
4967 get_hexdigit(char digit, int *value)
4969 if ('0' <= digit && digit <= '9')
4970 *value = digit - '0';
4971 else if ('A' <= digit && digit <= 'F')
4972 *value = digit - 'A' + 10;
4973 else if ('a' <= digit && digit <= 'f')
4974 *value = digit - 'a' + 10;
4982 * Find an option value corresponding to the keyword in the connOptions array.
4984 * If successful, returns a pointer to the corresponding option's value.
4985 * If not successful, returns NULL.
4988 conninfo_getval(PQconninfoOption *connOptions,
4989 const char *keyword)
4991 PQconninfoOption *option;
4993 option = conninfo_find(connOptions, keyword);
4995 return option ? option->val : NULL;
4999 * Store a (new) value for an option corresponding to the keyword in
5000 * connOptions array.
5002 * If uri_decode is true, the value is URI-decoded. The keyword is always
5003 * assumed to be non URI-encoded.
5005 * If successful, returns a pointer to the corresponding PQconninfoOption,
5006 * which value is replaced with a strdup'd copy of the passed value string.
5007 * The existing value for the option is free'd before replacing, if any.
5009 * If not successful, returns NULL and fills errorMessage accordingly.
5010 * However, if the reason of failure is an invalid keyword being passed and
5011 * ignoreMissing is TRUE, errorMessage will be left untouched.
5013 static PQconninfoOption *
5014 conninfo_storeval(PQconninfoOption *connOptions,
5015 const char *keyword, const char *value,
5016 PQExpBuffer errorMessage, bool ignoreMissing,
5019 PQconninfoOption *option;
5023 * For backwards compatibility, requiressl=1 gets translated to
5024 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5025 * (which is the default for sslmode).
5027 if (strcmp(keyword, "requiressl") == 0)
5029 keyword = "sslmode";
5030 if (value[0] == '1')
5036 option = conninfo_find(connOptions, keyword);
5040 printfPQExpBuffer(errorMessage,
5041 libpq_gettext("invalid connection option \"%s\"\n"),
5048 value_copy = conninfo_uri_decode(value, errorMessage);
5049 if (value_copy == NULL)
5050 /* conninfo_uri_decode already set an error message */
5055 value_copy = strdup(value);
5057 if (value_copy == NULL)
5059 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5066 option->val = value_copy;
5072 * Find a PQconninfoOption option corresponding to the keyword in the
5073 * connOptions array.
5075 * If successful, returns a pointer to the corresponding PQconninfoOption
5077 * If not successful, returns NULL.
5079 static PQconninfoOption *
5080 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
5082 PQconninfoOption *option;
5084 for (option = connOptions; option->keyword != NULL; option++)
5086 if (strcmp(option->keyword, keyword) == 0)
5095 * Return the connection options used for the connection
5098 PQconninfo(PGconn *conn)
5100 PQExpBufferData errorBuf;
5101 PQconninfoOption *connOptions;
5106 /* We don't actually report any errors here, but callees want a buffer */
5107 initPQExpBuffer(&errorBuf);
5108 if (PQExpBufferDataBroken(errorBuf))
5109 return NULL; /* out of memory already :-( */
5111 connOptions = conninfo_init(&errorBuf);
5113 if (connOptions != NULL)
5115 const internalPQconninfoOption *option;
5117 for (option = PQconninfoOptions; option->keyword; option++)
5121 if (option->connofs < 0)
5124 connmember = (char **) ((char *) conn + option->connofs);
5127 conninfo_storeval(connOptions, option->keyword, *connmember,
5128 &errorBuf, true, false);
5132 termPQExpBuffer(&errorBuf);
5139 PQconninfoFree(PQconninfoOption *connOptions)
5141 PQconninfoOption *option;
5143 if (connOptions == NULL)
5146 for (option = connOptions; option->keyword != NULL; option++)
5148 if (option->val != NULL)
5155 /* =========== accessor functions for PGconn ========= */
5157 PQdb(const PGconn *conn)
5161 return conn->dbName;
5165 PQuser(const PGconn *conn)
5169 return conn->pguser;
5173 PQpass(const PGconn *conn)
5177 return conn->pgpass;
5181 PQhost(const PGconn *conn)
5185 return conn->pghost ? conn->pghost : conn->pgunixsocket;
5189 PQport(const PGconn *conn)
5193 return conn->pgport;
5197 PQtty(const PGconn *conn)
5205 PQoptions(const PGconn *conn)
5209 return conn->pgoptions;
5213 PQstatus(const PGconn *conn)
5216 return CONNECTION_BAD;
5217 return conn->status;
5220 PGTransactionStatusType
5221 PQtransactionStatus(const PGconn *conn)
5223 if (!conn || conn->status != CONNECTION_OK)
5224 return PQTRANS_UNKNOWN;
5225 if (conn->asyncStatus != PGASYNC_IDLE)
5226 return PQTRANS_ACTIVE;
5227 return conn->xactStatus;
5231 PQparameterStatus(const PGconn *conn, const char *paramName)
5233 const pgParameterStatus *pstatus;
5235 if (!conn || !paramName)
5237 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
5239 if (strcmp(pstatus->name, paramName) == 0)
5240 return pstatus->value;
5246 PQprotocolVersion(const PGconn *conn)
5250 if (conn->status == CONNECTION_BAD)
5252 return PG_PROTOCOL_MAJOR(conn->pversion);
5256 PQserverVersion(const PGconn *conn)
5260 if (conn->status == CONNECTION_BAD)
5262 return conn->sversion;
5266 PQerrorMessage(const PGconn *conn)
5269 return libpq_gettext("connection pointer is NULL\n");
5271 return conn->errorMessage.data;
5275 PQsocket(const PGconn *conn)
5283 PQbackendPID(const PGconn *conn)
5285 if (!conn || conn->status != CONNECTION_OK)
5287 return conn->be_pid;
5291 PQconnectionNeedsPassword(const PGconn *conn)
5295 if (conn->password_needed &&
5296 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
5303 PQconnectionUsedPassword(const PGconn *conn)
5307 if (conn->password_needed)
5314 PQclientEncoding(const PGconn *conn)
5316 if (!conn || conn->status != CONNECTION_OK)
5318 return conn->client_encoding;
5322 PQsetClientEncoding(PGconn *conn, const char *encoding)
5325 static const char query[] = "set client_encoding to '%s'";
5329 if (!conn || conn->status != CONNECTION_OK)
5335 /* Resolve special "auto" value from the locale */
5336 if (strcmp(encoding, "auto") == 0)
5337 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
5339 /* check query buffer overflow */
5340 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
5343 /* ok, now send a query */
5344 sprintf(qbuf, query, encoding);
5345 res = PQexec(conn, qbuf);
5349 if (res->resultStatus != PGRES_COMMAND_OK)
5354 * In protocol 2 we have to assume the setting will stick, and adjust
5355 * our state immediately. In protocol 3 and up we can rely on the
5356 * backend to report the parameter value, and we'll change state at
5359 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
5360 pqSaveParameterStatus(conn, "client_encoding", encoding);
5361 status = 0; /* everything is ok */
5368 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
5373 return PQERRORS_DEFAULT;
5374 old = conn->verbosity;
5375 conn->verbosity = verbosity;
5380 PQtrace(PGconn *conn, FILE *debug_port)
5385 conn->Pfdebug = debug_port;
5389 PQuntrace(PGconn *conn)
5395 fflush(conn->Pfdebug);
5396 conn->Pfdebug = NULL;
5401 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
5403 PQnoticeReceiver old;
5408 old = conn->noticeHooks.noticeRec;
5411 conn->noticeHooks.noticeRec = proc;
5412 conn->noticeHooks.noticeRecArg = arg;
5418 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
5420 PQnoticeProcessor old;
5425 old = conn->noticeHooks.noticeProc;
5428 conn->noticeHooks.noticeProc = proc;
5429 conn->noticeHooks.noticeProcArg = arg;
5435 * The default notice message receiver just gets the standard notice text
5436 * and sends it to the notice processor. This two-level setup exists
5437 * mostly for backwards compatibility; perhaps we should deprecate use of
5438 * PQsetNoticeProcessor?
5441 defaultNoticeReceiver(void *arg, const PGresult *res)
5443 (void) arg; /* not used */
5444 if (res->noticeHooks.noticeProc != NULL)
5445 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
5446 PQresultErrorMessage(res));
5450 * The default notice message processor just prints the
5451 * message on stderr. Applications can override this if they
5452 * want the messages to go elsewhere (a window, for example).
5453 * Note that simply discarding notices is probably a bad idea.
5456 defaultNoticeProcessor(void *arg, const char *message)
5458 (void) arg; /* not used */
5459 /* Note: we expect the supplied string to end with a newline already. */
5460 fprintf(stderr, "%s", message);
5464 * returns a pointer to the next token or NULL if the current
5465 * token doesn't match
5468 pwdfMatchesString(char *buf, char *token)
5472 bool bslash = false;
5474 if (buf == NULL || token == NULL)
5478 if (tbuf[0] == '*' && tbuf[1] == ':')
5482 if (*tbuf == '\\' && !bslash)
5487 if (*tbuf == ':' && *ttok == 0 && !bslash)
5503 /* Get a password from the password file. Return value is malloc'd. */
5505 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
5508 char pgpassfile[MAXPGPATH];
5509 struct stat stat_buf;
5511 #define LINELEN NAMEDATALEN*5
5514 if (dbname == NULL || strlen(dbname) == 0)
5517 if (username == NULL || strlen(username) == 0)
5520 /* 'localhost' matches pghost of '' or the default socket directory */
5521 if (hostname == NULL)
5522 hostname = DefaultHost;
5523 else if (is_absolute_path(hostname))
5526 * We should probably use canonicalize_path(), but then we have to
5527 * bring path.c into libpq, and it doesn't seem worth it.
5529 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
5530 hostname = DefaultHost;
5533 port = DEF_PGPORT_STR;
5535 if (!getPgPassFilename(pgpassfile))
5538 /* If password file cannot be opened, ignore it. */
5539 if (stat(pgpassfile, &stat_buf) != 0)
5543 if (!S_ISREG(stat_buf.st_mode))
5546 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
5551 /* If password file is insecure, alert the user and ignore it. */
5552 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
5555 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
5562 * On Win32, the directory is protected, so we don't have to check the
5567 fp = fopen(pgpassfile, "r");
5571 while (!feof(fp) && !ferror(fp))
5579 if (fgets(buf, sizeof(buf), fp) == NULL)
5586 /* Remove trailing newline */
5587 if (buf[len - 1] == '\n')
5590 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
5591 (t = pwdfMatchesString(t, port)) == NULL ||
5592 (t = pwdfMatchesString(t, dbname)) == NULL ||
5593 (t = pwdfMatchesString(t, username)) == NULL)
5598 /* De-escape password. */
5599 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
5601 if (*p1 == '\\' && p1[1] != '\0')
5618 getPgPassFilename(char *pgpassfile)
5622 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
5623 /* use the literal path from the environment, if set */
5624 strlcpy(pgpassfile, passfile_env, MAXPGPATH);
5627 char homedir[MAXPGPATH];
5629 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5631 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
5637 * If the connection failed, we should mention if
5638 * we got the password from .pgpass in case that
5639 * password is wrong.
5642 dot_pg_pass_warning(PGconn *conn)
5644 /* If it was 'invalid authorization', add .pgpass mention */
5645 /* only works with >= 9.0 servers */
5646 if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
5647 strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
5648 ERRCODE_INVALID_PASSWORD) == 0)
5650 char pgpassfile[MAXPGPATH];
5652 if (!getPgPassFilename(pgpassfile))
5654 appendPQExpBuffer(&conn->errorMessage,
5655 libpq_gettext("password retrieved from file \"%s\"\n"),
5662 * Obtain user's home directory, return in given buffer
5664 * On Unix, this actually returns the user's home directory. On Windows
5665 * it returns the PostgreSQL-specific application data folder.
5667 * This is essentially the same as get_home_path(), but we don't use that
5668 * because we don't want to pull path.c into libpq (it pollutes application
5672 pqGetHomeDirectory(char *buf, int bufsize)
5675 char pwdbuf[BUFSIZ];
5676 struct passwd pwdstr;
5677 struct passwd *pwd = NULL;
5679 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
5681 strlcpy(buf, pwd->pw_dir, bufsize);
5684 char tmppath[MAX_PATH];
5686 ZeroMemory(tmppath, sizeof(tmppath));
5687 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
5689 snprintf(buf, bufsize, "%s/postgresql", tmppath);
5695 * To keep the API consistent, the locking stubs are always provided, even
5696 * if they are not required.
5700 default_threadlock(int acquire)
5702 #ifdef ENABLE_THREAD_SAFETY
5704 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
5706 static pthread_mutex_t singlethread_lock = NULL;
5707 static long mutex_initlock = 0;
5709 if (singlethread_lock == NULL)
5711 while (InterlockedExchange(&mutex_initlock, 1) == 1)
5712 /* loop, another thread own the lock */ ;
5713 if (singlethread_lock == NULL)
5715 if (pthread_mutex_init(&singlethread_lock, NULL))
5716 PGTHREAD_ERROR("failed to initialize mutex");
5718 InterlockedExchange(&mutex_initlock, 0);
5723 if (pthread_mutex_lock(&singlethread_lock))
5724 PGTHREAD_ERROR("failed to lock mutex");
5728 if (pthread_mutex_unlock(&singlethread_lock))
5729 PGTHREAD_ERROR("failed to unlock mutex");
5735 PQregisterThreadLock(pgthreadlock_t newhandler)
5737 pgthreadlock_t prev = pg_g_threadlock;
5740 pg_g_threadlock = newhandler;
5742 pg_g_threadlock = default_threadlock;