1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2014, 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 /* pass NULL errorBuf to ignore errors */
879 if (!conninfo_add_defaults(connOptions, NULL))
881 PQconninfoFree(connOptions);
886 termPQExpBuffer(&errorBuf);
893 * establishes a connection to a postgres backend through the postmaster
894 * at the specified host and port.
896 * returns a PGconn* which is needed for all subsequent libpq calls
898 * if the status field of the connection returned is CONNECTION_BAD,
899 * then only the errorMessage is likely to be useful.
903 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
904 const char *pgtty, const char *dbName, const char *login,
910 * Allocate memory for the conn structure
912 conn = makeEmptyPGconn();
917 * If the dbName parameter contains what looks like a connection string,
918 * parse it into conn struct using connectOptions1.
920 if (dbName && recognized_connection_string(dbName))
922 if (!connectOptions1(conn, dbName))
928 * Old-style path: first, parse an empty conninfo string in order to
929 * set up the same defaults that PQconnectdb() would use.
931 if (!connectOptions1(conn, ""))
934 /* Insert dbName parameter value into struct */
935 if (dbName && dbName[0] != '\0')
939 conn->dbName = strdup(dbName);
944 * Insert remaining parameters into struct, overriding defaults (as well
945 * as any conflicting data from dbName taken as a conninfo).
947 if (pghost && pghost[0] != '\0')
951 conn->pghost = strdup(pghost);
954 if (pgport && pgport[0] != '\0')
958 conn->pgport = strdup(pgport);
961 if (pgoptions && pgoptions[0] != '\0')
964 free(conn->pgoptions);
965 conn->pgoptions = strdup(pgoptions);
968 if (pgtty && pgtty[0] != '\0')
972 conn->pgtty = strdup(pgtty);
975 if (login && login[0] != '\0')
979 conn->pguser = strdup(login);
982 if (pwd && pwd[0] != '\0')
986 conn->pgpass = strdup(pwd);
990 * Compute derived options
992 if (!connectOptions2(conn))
996 * Connect to the database
998 if (connectDBStart(conn))
999 (void) connectDBComplete(conn);
1007 * Sets the TCP_NODELAY socket option.
1008 * Returns 1 if successful, 0 if not.
1012 connectNoDelay(PGconn *conn)
1017 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1023 appendPQExpBuffer(&conn->errorMessage,
1024 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1025 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1035 * connectFailureMessage -
1036 * create a friendly error message on connection failure.
1040 connectFailureMessage(PGconn *conn, int errorno)
1044 #ifdef HAVE_UNIX_SOCKETS
1045 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1047 char service[NI_MAXHOST];
1049 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1051 service, sizeof(service),
1053 appendPQExpBuffer(&conn->errorMessage,
1054 libpq_gettext("could not connect to server: %s\n"
1055 "\tIs the server running locally and accepting\n"
1056 "\tconnections on Unix domain socket \"%s\"?\n"),
1057 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1061 #endif /* HAVE_UNIX_SOCKETS */
1063 char host_addr[NI_MAXHOST];
1064 const char *displayed_host;
1065 struct sockaddr_storage *addr = &conn->raddr.addr;
1068 * Optionally display the network address with the hostname. This is
1069 * useful to distinguish between IPv4 and IPv6 connections.
1071 if (conn->pghostaddr != NULL)
1072 strlcpy(host_addr, conn->pghostaddr, NI_MAXHOST);
1073 else if (addr->ss_family == AF_INET)
1075 if (inet_net_ntop(AF_INET,
1076 &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1078 host_addr, sizeof(host_addr)) == NULL)
1079 strcpy(host_addr, "???");
1082 else if (addr->ss_family == AF_INET6)
1084 if (inet_net_ntop(AF_INET6,
1085 &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1087 host_addr, sizeof(host_addr)) == NULL)
1088 strcpy(host_addr, "???");
1092 strcpy(host_addr, "???");
1094 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1095 displayed_host = conn->pghostaddr;
1096 else if (conn->pghost && conn->pghost[0] != '\0')
1097 displayed_host = conn->pghost;
1099 displayed_host = DefaultHost;
1102 * If the user did not supply an IP address using 'hostaddr', and
1103 * 'host' was missing or does not match our lookup, display the
1104 * looked-up IP address.
1106 if ((conn->pghostaddr == NULL) &&
1107 (conn->pghost == NULL || strcmp(conn->pghost, host_addr) != 0))
1108 appendPQExpBuffer(&conn->errorMessage,
1109 libpq_gettext("could not connect to server: %s\n"
1110 "\tIs the server running on host \"%s\" (%s) and accepting\n"
1111 "\tTCP/IP connections on port %s?\n"),
1112 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1117 appendPQExpBuffer(&conn->errorMessage,
1118 libpq_gettext("could not connect to server: %s\n"
1119 "\tIs the server running on host \"%s\" and accepting\n"
1120 "\tTCP/IP connections on port %s?\n"),
1121 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1128 * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
1129 * conn->keepalives is set to a value which is not parseable as an
1133 useKeepalives(PGconn *conn)
1138 if (conn->keepalives == NULL)
1140 val = strtol(conn->keepalives, &ep, 10);
1143 return val != 0 ? 1 : 0;
1148 * Set the keepalive idle timer.
1151 setKeepalivesIdle(PGconn *conn)
1155 if (conn->keepalives_idle == NULL)
1158 idle = atoi(conn->keepalives_idle);
1163 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1164 (char *) &idle, sizeof(idle)) < 0)
1168 appendPQExpBuffer(&conn->errorMessage,
1169 libpq_gettext("setsockopt(TCP_KEEPIDLE) failed: %s\n"),
1170 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1174 #ifdef TCP_KEEPALIVE
1175 /* Darwin uses TCP_KEEPALIVE rather than TCP_KEEPIDLE */
1176 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1177 (char *) &idle, sizeof(idle)) < 0)
1181 appendPQExpBuffer(&conn->errorMessage,
1182 libpq_gettext("setsockopt(TCP_KEEPALIVE) failed: %s\n"),
1183 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1193 * Set the keepalive interval.
1196 setKeepalivesInterval(PGconn *conn)
1200 if (conn->keepalives_interval == NULL)
1203 interval = atoi(conn->keepalives_interval);
1207 #ifdef TCP_KEEPINTVL
1208 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1209 (char *) &interval, sizeof(interval)) < 0)
1213 appendPQExpBuffer(&conn->errorMessage,
1214 libpq_gettext("setsockopt(TCP_KEEPINTVL) failed: %s\n"),
1215 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1224 * Set the count of lost keepalive packets that will trigger a connection
1228 setKeepalivesCount(PGconn *conn)
1232 if (conn->keepalives_count == NULL)
1235 count = atoi(conn->keepalives_count);
1240 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1241 (char *) &count, sizeof(count)) < 0)
1245 appendPQExpBuffer(&conn->errorMessage,
1246 libpq_gettext("setsockopt(TCP_KEEPCNT) failed: %s\n"),
1247 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1255 #ifdef SIO_KEEPALIVE_VALS
1257 * Enable keepalives and set the keepalive values on Win32,
1258 * where they are always set in one batch.
1261 setKeepalivesWin32(PGconn *conn)
1263 struct tcp_keepalive ka;
1268 if (conn->keepalives_idle)
1269 idle = atoi(conn->keepalives_idle);
1271 idle = 2 * 60 * 60; /* 2 hours = default */
1273 if (conn->keepalives_interval)
1274 interval = atoi(conn->keepalives_interval);
1276 interval = 1; /* 1 second = default */
1279 ka.keepalivetime = idle * 1000;
1280 ka.keepaliveinterval = interval * 1000;
1282 if (WSAIoctl(conn->sock,
1293 appendPQExpBuffer(&conn->errorMessage,
1294 libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1300 #endif /* SIO_KEEPALIVE_VALS */
1305 * Begin the process of making a connection to the backend.
1307 * Returns 1 if successful, 0 if not.
1311 connectDBStart(PGconn *conn)
1314 char portstr[MAXPGPATH];
1315 struct addrinfo *addrs = NULL;
1316 struct addrinfo hint;
1323 if (!conn->options_valid)
1324 goto connect_errReturn;
1326 /* Ensure our buffers are empty */
1327 conn->inStart = conn->inCursor = conn->inEnd = 0;
1331 * Determine the parameters to pass to pg_getaddrinfo_all.
1334 /* Initialize hint structure */
1335 MemSet(&hint, 0, sizeof(hint));
1336 hint.ai_socktype = SOCK_STREAM;
1337 hint.ai_family = AF_UNSPEC;
1339 /* Set up port number as a string */
1340 if (conn->pgport != NULL && conn->pgport[0] != '\0')
1342 portnum = atoi(conn->pgport);
1343 if (portnum < 1 || portnum > 65535)
1345 appendPQExpBuffer(&conn->errorMessage,
1346 libpq_gettext("invalid port number: \"%s\"\n"),
1348 conn->options_valid = false;
1349 goto connect_errReturn;
1353 portnum = DEF_PGPORT;
1354 snprintf(portstr, sizeof(portstr), "%d", portnum);
1356 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1358 /* Using pghostaddr avoids a hostname lookup */
1359 node = conn->pghostaddr;
1360 hint.ai_family = AF_UNSPEC;
1361 hint.ai_flags = AI_NUMERICHOST;
1363 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
1365 /* Using pghost, so we have to look-up the hostname */
1366 node = conn->pghost;
1367 hint.ai_family = AF_UNSPEC;
1371 #ifdef HAVE_UNIX_SOCKETS
1372 /* pghostaddr and pghost are NULL, so use Unix domain socket */
1374 hint.ai_family = AF_UNIX;
1375 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
1376 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
1378 appendPQExpBuffer(&conn->errorMessage,
1379 libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
1381 (int) (UNIXSOCK_PATH_BUFLEN - 1));
1382 conn->options_valid = false;
1383 goto connect_errReturn;
1386 /* Without Unix sockets, default to localhost instead */
1388 hint.ai_family = AF_UNSPEC;
1389 #endif /* HAVE_UNIX_SOCKETS */
1392 /* Use pg_getaddrinfo_all() to resolve the address */
1393 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
1397 appendPQExpBuffer(&conn->errorMessage,
1398 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
1399 node, gai_strerror(ret));
1401 appendPQExpBuffer(&conn->errorMessage,
1402 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
1403 portstr, gai_strerror(ret));
1405 pg_freeaddrinfo_all(hint.ai_family, addrs);
1406 conn->options_valid = false;
1407 goto connect_errReturn;
1411 /* setup values based on SSL mode */
1412 if (conn->sslmode[0] == 'd') /* "disable" */
1413 conn->allow_ssl_try = false;
1414 else if (conn->sslmode[0] == 'a') /* "allow" */
1415 conn->wait_ssl_try = true;
1419 * Set up to try to connect, with protocol 3.0 as the first attempt.
1421 conn->addrlist = addrs;
1422 conn->addr_cur = addrs;
1423 conn->addrlist_family = hint.ai_family;
1424 conn->pversion = PG_PROTOCOL(3, 0);
1425 conn->send_appname = true;
1426 conn->status = CONNECTION_NEEDED;
1429 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1430 * so that it can easily be re-executed if needed again during the
1431 * asynchronous startup process. However, we must run it once here,
1432 * because callers expect a success return from this routine to mean that
1433 * we are in PGRES_POLLING_WRITING connection state.
1435 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1439 pqDropConnection(conn);
1440 conn->status = CONNECTION_BAD;
1448 * Block and complete a connection.
1450 * Returns 1 on success, 0 on failure.
1453 connectDBComplete(PGconn *conn)
1455 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1456 time_t finish_time = ((time_t) -1);
1458 if (conn == NULL || conn->status == CONNECTION_BAD)
1462 * Set up a time limit, if connect_timeout isn't zero.
1464 if (conn->connect_timeout != NULL)
1466 int timeout = atoi(conn->connect_timeout);
1471 * Rounding could cause connection to fail; need at least 2 secs
1475 /* calculate the finish time based on start + timeout */
1476 finish_time = time(NULL) + timeout;
1483 * Wait, if necessary. Note that the initial state (just after
1484 * PQconnectStart) is to wait for the socket to select for writing.
1488 case PGRES_POLLING_OK:
1491 * Reset stored error messages since we now have a working
1494 resetPQExpBuffer(&conn->errorMessage);
1495 return 1; /* success! */
1497 case PGRES_POLLING_READING:
1498 if (pqWaitTimed(1, 0, conn, finish_time))
1500 conn->status = CONNECTION_BAD;
1505 case PGRES_POLLING_WRITING:
1506 if (pqWaitTimed(0, 1, conn, finish_time))
1508 conn->status = CONNECTION_BAD;
1514 /* Just in case we failed to set it in PQconnectPoll */
1515 conn->status = CONNECTION_BAD;
1520 * Now try to advance the state machine.
1522 flag = PQconnectPoll(conn);
1529 * Poll an asynchronous connection.
1531 * Returns a PostgresPollingStatusType.
1532 * Before calling this function, use select(2) to determine when data
1535 * You must call PQfinish whether or not this fails.
1537 * This function and PQconnectStart are intended to allow connections to be
1538 * made without blocking the execution of your program on remote I/O. However,
1539 * there are a number of caveats:
1541 * o If you call PQtrace, ensure that the stream object into which you trace
1543 * o If you do not supply an IP address for the remote host (i.e. you
1544 * supply a host name instead) then PQconnectStart will block on
1545 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1546 * supplying neither a host name nor a host address).
1547 * o If your backend wants to use Kerberos authentication then you must
1548 * supply both a host name and a host address, otherwise this function
1549 * may block on gethostname.
1553 PostgresPollingStatusType
1554 PQconnectPoll(PGconn *conn)
1561 return PGRES_POLLING_FAILED;
1563 /* Get the new data */
1564 switch (conn->status)
1567 * We really shouldn't have been polled in these two cases, but we
1570 case CONNECTION_BAD:
1571 return PGRES_POLLING_FAILED;
1573 return PGRES_POLLING_OK;
1575 /* These are reading states */
1576 case CONNECTION_AWAITING_RESPONSE:
1577 case CONNECTION_AUTH_OK:
1579 /* Load waiting data */
1580 int n = pqReadData(conn);
1585 return PGRES_POLLING_READING;
1590 /* These are writing states, so we just proceed. */
1591 case CONNECTION_STARTED:
1592 case CONNECTION_MADE:
1595 /* We allow pqSetenvPoll to decide whether to proceed. */
1596 case CONNECTION_SETENV:
1599 /* Special cases: proceed without waiting. */
1600 case CONNECTION_SSL_STARTUP:
1601 case CONNECTION_NEEDED:
1605 appendPQExpBufferStr(&conn->errorMessage,
1607 "invalid connection state, "
1608 "probably indicative of memory corruption\n"
1614 keep_going: /* We will come back to here until there is
1615 * nothing left to do. */
1616 switch (conn->status)
1618 case CONNECTION_NEEDED:
1621 * Try to initiate a connection to one of the addresses
1622 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1623 * next one to try. We fail when we run out of addresses.
1625 while (conn->addr_cur != NULL)
1627 struct addrinfo *addr_cur = conn->addr_cur;
1629 /* Remember current address for possible error msg */
1630 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1631 addr_cur->ai_addrlen);
1632 conn->raddr.salen = addr_cur->ai_addrlen;
1635 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1639 * ignore socket() failure if we have more addresses
1642 if (addr_cur->ai_next != NULL)
1644 conn->addr_cur = addr_cur->ai_next;
1647 appendPQExpBuffer(&conn->errorMessage,
1648 libpq_gettext("could not create socket: %s\n"),
1649 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1654 * Select socket options: no delay of outgoing data for
1655 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1658 if (!IS_AF_UNIX(addr_cur->ai_family))
1660 if (!connectNoDelay(conn))
1662 pqDropConnection(conn);
1663 conn->addr_cur = addr_cur->ai_next;
1667 if (!pg_set_noblock(conn->sock))
1669 appendPQExpBuffer(&conn->errorMessage,
1670 libpq_gettext("could not set socket to nonblocking mode: %s\n"),
1671 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1672 pqDropConnection(conn);
1673 conn->addr_cur = addr_cur->ai_next;
1678 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1680 appendPQExpBuffer(&conn->errorMessage,
1681 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1682 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1683 pqDropConnection(conn);
1684 conn->addr_cur = addr_cur->ai_next;
1687 #endif /* F_SETFD */
1689 if (!IS_AF_UNIX(addr_cur->ai_family))
1694 int usekeepalives = useKeepalives(conn);
1697 if (usekeepalives < 0)
1699 appendPQExpBufferStr(&conn->errorMessage,
1700 libpq_gettext("keepalives parameter must be an integer\n"));
1703 else if (usekeepalives == 0)
1708 else if (setsockopt(conn->sock,
1709 SOL_SOCKET, SO_KEEPALIVE,
1710 (char *) &on, sizeof(on)) < 0)
1712 appendPQExpBuffer(&conn->errorMessage,
1713 libpq_gettext("setsockopt(SO_KEEPALIVE) failed: %s\n"),
1714 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1717 else if (!setKeepalivesIdle(conn)
1718 || !setKeepalivesInterval(conn)
1719 || !setKeepalivesCount(conn))
1722 #ifdef SIO_KEEPALIVE_VALS
1723 else if (!setKeepalivesWin32(conn))
1725 #endif /* SIO_KEEPALIVE_VALS */
1730 pqDropConnection(conn);
1731 conn->addr_cur = addr_cur->ai_next;
1737 * We have three methods of blocking SIGPIPE during
1738 * send() calls to this socket:
1740 * - setsockopt(sock, SO_NOSIGPIPE)
1741 * - send(sock, ..., MSG_NOSIGNAL)
1742 * - setting the signal mask to SIG_IGN during send()
1744 * The third method requires three syscalls per send,
1745 * so we prefer either of the first two, but they are
1746 * less portable. The state is tracked in the following
1747 * members of PGconn:
1749 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
1750 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
1752 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
1753 * and we're done. Otherwise, set sigpipe_flag so that
1754 * we will try MSG_NOSIGNAL on sends. If we get an error
1755 * with MSG_NOSIGNAL, we'll clear that flag and revert to
1759 conn->sigpipe_so = false;
1761 conn->sigpipe_flag = true;
1763 conn->sigpipe_flag = false;
1764 #endif /* MSG_NOSIGNAL */
1768 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
1769 (char *) &optval, sizeof(optval)) == 0)
1771 conn->sigpipe_so = true;
1772 conn->sigpipe_flag = false;
1774 #endif /* SO_NOSIGPIPE */
1777 * Start/make connection. This should not block, since we
1778 * are in nonblock mode. If it does, well, too bad.
1780 if (connect(conn->sock, addr_cur->ai_addr,
1781 addr_cur->ai_addrlen) < 0)
1783 if (SOCK_ERRNO == EINPROGRESS ||
1785 SOCK_ERRNO == EWOULDBLOCK ||
1787 SOCK_ERRNO == EINTR)
1790 * This is fine - we're in non-blocking mode, and
1791 * the connection is in progress. Tell caller to
1792 * wait for write-ready on socket.
1794 conn->status = CONNECTION_STARTED;
1795 return PGRES_POLLING_WRITING;
1797 /* otherwise, trouble */
1802 * Hm, we're connected already --- seems the "nonblock
1803 * connection" wasn't. Advance the state machine and
1804 * go do the next stuff.
1806 conn->status = CONNECTION_STARTED;
1811 * This connection failed --- set up error report, then
1812 * close socket (do it this way in case close() affects
1813 * the value of errno...). We will ignore the connect()
1814 * failure and keep going if there are more addresses.
1816 connectFailureMessage(conn, SOCK_ERRNO);
1817 pqDropConnection(conn);
1820 * Try the next address, if any.
1822 conn->addr_cur = addr_cur->ai_next;
1823 } /* loop over addresses */
1826 * Ooops, no more addresses. An appropriate error message is
1827 * already set up, so just set the right status.
1832 case CONNECTION_STARTED:
1834 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1837 * Write ready, since we've made it here, so the connection
1838 * has been made ... or has failed.
1842 * Now check (using getsockopt) that there is not an error
1843 * state waiting for us on the socket.
1846 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1847 (char *) &optval, &optlen) == -1)
1849 appendPQExpBuffer(&conn->errorMessage,
1850 libpq_gettext("could not get socket error status: %s\n"),
1851 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1854 else if (optval != 0)
1857 * When using a nonblocking connect, we will typically see
1858 * connect failures at this point, so provide a friendly
1861 connectFailureMessage(conn, optval);
1862 pqDropConnection(conn);
1865 * If more addresses remain, keep trying, just as in the
1866 * case where connect() returned failure immediately.
1868 if (conn->addr_cur->ai_next != NULL)
1870 conn->addr_cur = conn->addr_cur->ai_next;
1871 conn->status = CONNECTION_NEEDED;
1877 /* Fill in the client address */
1878 conn->laddr.salen = sizeof(conn->laddr.addr);
1879 if (getsockname(conn->sock,
1880 (struct sockaddr *) & conn->laddr.addr,
1881 &conn->laddr.salen) < 0)
1883 appendPQExpBuffer(&conn->errorMessage,
1884 libpq_gettext("could not get client address from socket: %s\n"),
1885 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1890 * Make sure we can write before advancing to next step.
1892 conn->status = CONNECTION_MADE;
1893 return PGRES_POLLING_WRITING;
1896 case CONNECTION_MADE:
1901 #ifdef HAVE_UNIX_SOCKETS
1904 * Implement requirepeer check, if requested and it's a
1905 * Unix-domain socket.
1907 if (conn->requirepeer && conn->requirepeer[0] &&
1908 IS_AF_UNIX(conn->raddr.addr.ss_family))
1910 char pwdbuf[BUFSIZ];
1911 struct passwd pass_buf;
1912 struct passwd *pass;
1917 if (getpeereid(conn->sock, &uid, &gid) != 0)
1920 * Provide special error message if getpeereid is a
1923 if (errno == ENOSYS)
1924 appendPQExpBufferStr(&conn->errorMessage,
1925 libpq_gettext("requirepeer parameter is not supported on this platform\n"));
1927 appendPQExpBuffer(&conn->errorMessage,
1928 libpq_gettext("could not get peer credentials: %s\n"),
1929 pqStrerror(errno, sebuf, sizeof(sebuf)));
1933 pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
1937 appendPQExpBuffer(&conn->errorMessage,
1938 libpq_gettext("local user with ID %d does not exist\n"),
1943 if (strcmp(pass->pw_name, conn->requirepeer) != 0)
1945 appendPQExpBuffer(&conn->errorMessage,
1946 libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
1947 conn->requirepeer, pass->pw_name);
1951 #endif /* HAVE_UNIX_SOCKETS */
1956 * If SSL is enabled and we haven't already got it running,
1957 * request it instead of sending the startup message.
1959 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1961 /* Don't bother requesting SSL over a Unix socket */
1962 conn->allow_ssl_try = false;
1964 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1970 * Send the SSL request packet.
1972 * Theoretically, this could block, but it really
1973 * shouldn't since we only got here if the socket is
1976 pv = htonl(NEGOTIATE_SSL_CODE);
1977 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1979 appendPQExpBuffer(&conn->errorMessage,
1980 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1981 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1984 /* Ok, wait for response */
1985 conn->status = CONNECTION_SSL_STARTUP;
1986 return PGRES_POLLING_READING;
1988 #endif /* USE_SSL */
1991 * Build the startup packet.
1993 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1994 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1995 EnvironmentOptions);
1997 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1998 EnvironmentOptions);
2002 * will not appendbuffer here, since it's likely to also
2005 printfPQExpBuffer(&conn->errorMessage,
2006 libpq_gettext("out of memory\n"));
2011 * Send the startup packet.
2013 * Theoretically, this could block, but it really shouldn't
2014 * since we only got here if the socket is write-ready.
2016 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2018 appendPQExpBuffer(&conn->errorMessage,
2019 libpq_gettext("could not send startup packet: %s\n"),
2020 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2027 conn->status = CONNECTION_AWAITING_RESPONSE;
2028 return PGRES_POLLING_READING;
2032 * Handle SSL negotiation: wait for postmaster messages and
2033 * respond as necessary.
2035 case CONNECTION_SSL_STARTUP:
2038 PostgresPollingStatusType pollres;
2041 * On first time through, get the postmaster's response to our
2042 * SSL negotiation packet.
2044 if (conn->ssl == NULL)
2047 * We use pqReadData here since it has the logic to
2048 * distinguish no-data-yet from connection closure. Since
2049 * conn->ssl isn't set, a plain recv() will occur.
2054 rdresult = pqReadData(conn);
2057 /* errorMessage is already filled in */
2062 /* caller failed to wait for data */
2063 return PGRES_POLLING_READING;
2065 if (pqGetc(&SSLok, conn) < 0)
2067 /* should not happen really */
2068 return PGRES_POLLING_READING;
2072 /* mark byte consumed */
2073 conn->inStart = conn->inCursor;
2074 /* Set up global SSL state if required */
2075 if (pqsecure_initialize(conn) != 0)
2078 else if (SSLok == 'N')
2080 /* mark byte consumed */
2081 conn->inStart = conn->inCursor;
2082 /* OK to do without SSL? */
2083 if (conn->sslmode[0] == 'r' || /* "require" */
2084 conn->sslmode[0] == 'v') /* "verify-ca" or
2087 /* Require SSL, but server does not want it */
2088 appendPQExpBufferStr(&conn->errorMessage,
2089 libpq_gettext("server does not support SSL, but SSL was required\n"));
2092 /* Otherwise, proceed with normal startup */
2093 conn->allow_ssl_try = false;
2094 conn->status = CONNECTION_MADE;
2095 return PGRES_POLLING_WRITING;
2097 else if (SSLok == 'E')
2100 * Server failure of some sort, such as failure to
2101 * fork a backend process. We need to process and
2102 * report the error message, which might be formatted
2103 * according to either protocol 2 or protocol 3.
2104 * Rather than duplicate the code for that, we flip
2105 * into AWAITING_RESPONSE state and let the code there
2106 * deal with it. Note we have *not* consumed the "E"
2109 conn->status = CONNECTION_AWAITING_RESPONSE;
2114 appendPQExpBuffer(&conn->errorMessage,
2115 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2122 * Begin or continue the SSL negotiation process.
2124 pollres = pqsecure_open_client(conn);
2125 if (pollres == PGRES_POLLING_OK)
2127 /* SSL handshake done, ready to send startup packet */
2128 conn->status = CONNECTION_MADE;
2129 return PGRES_POLLING_WRITING;
2131 if (pollres == PGRES_POLLING_FAILED)
2134 * Failed ... if sslmode is "prefer" then do a non-SSL
2137 if (conn->sslmode[0] == 'p' /* "prefer" */
2138 && conn->allow_ssl_try /* redundant? */
2139 && !conn->wait_ssl_try) /* redundant? */
2141 /* only retry once */
2142 conn->allow_ssl_try = false;
2143 /* Must drop the old connection */
2144 pqDropConnection(conn);
2145 conn->status = CONNECTION_NEEDED;
2150 #else /* !USE_SSL */
2151 /* can't get here */
2153 #endif /* USE_SSL */
2157 * Handle authentication exchange: wait for postmaster messages
2158 * and respond as necessary.
2160 case CONNECTION_AWAITING_RESPONSE:
2168 * Scan the message from current point (note that if we find
2169 * the message is incomplete, we will return without advancing
2170 * inStart, and resume here next time).
2172 conn->inCursor = conn->inStart;
2174 /* Read type byte */
2175 if (pqGetc(&beresp, conn))
2177 /* We'll come back when there is more data */
2178 return PGRES_POLLING_READING;
2182 * Validate message type: we expect only an authentication
2183 * request or an error here. Anything else probably means
2184 * it's not Postgres on the other end at all.
2186 if (!(beresp == 'R' || beresp == 'E'))
2188 appendPQExpBuffer(&conn->errorMessage,
2190 "expected authentication request from "
2191 "server, but received %c\n"),
2196 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2198 /* Read message length word */
2199 if (pqGetInt(&msgLength, 4, conn))
2201 /* We'll come back when there is more data */
2202 return PGRES_POLLING_READING;
2207 /* Set phony message length to disable checks below */
2212 * Try to validate message length before using it.
2213 * Authentication requests can't be very large, although GSS
2214 * auth requests may not be that small. Errors can be a
2215 * little larger, but not huge. If we see a large apparent
2216 * length in an error, it means we're really talking to a
2217 * pre-3.0-protocol server; cope.
2219 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2221 appendPQExpBuffer(&conn->errorMessage,
2223 "expected authentication request from "
2224 "server, but received %c\n"),
2229 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2231 /* Handle error from a pre-3.0 server */
2232 conn->inCursor = conn->inStart + 1; /* reread data */
2233 if (pqGets_append(&conn->errorMessage, conn))
2235 /* We'll come back when there is more data */
2236 return PGRES_POLLING_READING;
2238 /* OK, we read the message; mark data consumed */
2239 conn->inStart = conn->inCursor;
2242 * The postmaster typically won't end its message with a
2243 * newline, so add one to conform to libpq conventions.
2245 appendPQExpBufferChar(&conn->errorMessage, '\n');
2248 * If we tried to open the connection in 3.0 protocol,
2249 * fall back to 2.0 protocol.
2251 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2253 conn->pversion = PG_PROTOCOL(2, 0);
2254 /* Must drop the old connection */
2255 pqDropConnection(conn);
2256 conn->status = CONNECTION_NEEDED;
2264 * Can't process if message body isn't all here yet.
2266 * (In protocol 2.0 case, we are assuming messages carry at
2267 * least 4 bytes of data.)
2270 avail = conn->inEnd - conn->inCursor;
2271 if (avail < msgLength)
2274 * Before returning, try to enlarge the input buffer if
2275 * needed to hold the whole message; see notes in
2278 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2281 /* We'll come back when there is more data */
2282 return PGRES_POLLING_READING;
2285 /* Handle errors. */
2288 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2290 if (pqGetErrorNotice3(conn, true))
2292 /* We'll come back when there is more data */
2293 return PGRES_POLLING_READING;
2298 if (pqGets_append(&conn->errorMessage, conn))
2300 /* We'll come back when there is more data */
2301 return PGRES_POLLING_READING;
2304 /* OK, we read the message; mark data consumed */
2305 conn->inStart = conn->inCursor;
2310 * if sslmode is "allow" and we haven't tried an SSL
2311 * connection already, then retry with an SSL connection
2313 if (conn->sslmode[0] == 'a' /* "allow" */
2314 && conn->ssl == NULL
2315 && conn->allow_ssl_try
2316 && conn->wait_ssl_try)
2318 /* only retry once */
2319 conn->wait_ssl_try = false;
2320 /* Must drop the old connection */
2321 pqDropConnection(conn);
2322 conn->status = CONNECTION_NEEDED;
2327 * if sslmode is "prefer" and we're in an SSL connection,
2328 * then do a non-SSL retry
2330 if (conn->sslmode[0] == 'p' /* "prefer" */
2331 && conn->allow_ssl_try
2332 && !conn->wait_ssl_try) /* redundant? */
2334 /* only retry once */
2335 conn->allow_ssl_try = false;
2336 /* Must drop the old connection */
2337 pqDropConnection(conn);
2338 conn->status = CONNECTION_NEEDED;
2346 /* It is an authentication request. */
2347 conn->auth_req_received = true;
2349 /* Get the type of request. */
2350 if (pqGetInt((int *) &areq, 4, conn))
2352 /* We'll come back when there are more data */
2353 return PGRES_POLLING_READING;
2356 /* Get the password salt if there is one. */
2357 if (areq == AUTH_REQ_MD5)
2359 if (pqGetnchar(conn->md5Salt,
2360 sizeof(conn->md5Salt), conn))
2362 /* We'll come back when there are more data */
2363 return PGRES_POLLING_READING;
2366 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2369 * Continue GSSAPI/SSPI authentication
2371 if (areq == AUTH_REQ_GSS_CONT)
2373 int llen = msgLength - 4;
2376 * We can be called repeatedly for the same buffer. Avoid
2377 * re-allocating the buffer in this case - just re-use the
2380 if (llen != conn->ginbuf.length)
2382 if (conn->ginbuf.value)
2383 free(conn->ginbuf.value);
2385 conn->ginbuf.length = llen;
2386 conn->ginbuf.value = malloc(llen);
2387 if (!conn->ginbuf.value)
2389 printfPQExpBuffer(&conn->errorMessage,
2390 libpq_gettext("out of memory allocating GSSAPI buffer (%d)"),
2396 if (pqGetnchar(conn->ginbuf.value, llen, conn))
2398 /* We'll come back when there is more data. */
2399 return PGRES_POLLING_READING;
2405 * OK, we successfully read the message; mark data consumed
2407 conn->inStart = conn->inCursor;
2409 /* Respond to the request if necessary. */
2412 * Note that conn->pghost must be non-NULL if we are going to
2413 * avoid the Kerberos code doing a hostname look-up.
2416 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
2418 conn->errorMessage.len = strlen(conn->errorMessage.data);
2421 conn->errorMessage.len = strlen(conn->errorMessage.data);
2424 * Just make sure that any data sent by pg_fe_sendauth is
2425 * flushed out. Although this theoretically could block, it
2426 * really shouldn't since we don't send large auth responses.
2431 if (areq == AUTH_REQ_OK)
2433 /* We are done with authentication exchange */
2434 conn->status = CONNECTION_AUTH_OK;
2437 * Set asyncStatus so that PQgetResult will think that
2438 * what comes back next is the result of a query. See
2441 conn->asyncStatus = PGASYNC_BUSY;
2444 /* Look to see if we have more data yet. */
2448 case CONNECTION_AUTH_OK:
2451 * Now we expect to hear from the backend. A ReadyForQuery
2452 * message indicates that startup is successful, but we might
2453 * also get an Error message indicating failure. (Notice
2454 * messages indicating nonfatal warnings are also allowed by
2455 * the protocol, as are ParameterStatus and BackendKeyData
2456 * messages.) Easiest way to handle this is to let
2457 * PQgetResult() read the messages. We just have to fake it
2458 * out about the state of the connection, by setting
2459 * asyncStatus = PGASYNC_BUSY (done above).
2463 return PGRES_POLLING_READING;
2465 res = PQgetResult(conn);
2468 * NULL return indicating we have gone to IDLE state is
2473 if (res->resultStatus != PGRES_FATAL_ERROR)
2474 appendPQExpBufferStr(&conn->errorMessage,
2475 libpq_gettext("unexpected message from server during startup\n"));
2476 else if (conn->send_appname &&
2477 (conn->appname || conn->fbappname))
2480 * If we tried to send application_name, check to see
2481 * if the error is about that --- pre-9.0 servers will
2482 * reject it at this stage of the process. If so,
2483 * close the connection and retry without sending
2484 * application_name. We could possibly get a false
2485 * SQLSTATE match here and retry uselessly, but there
2486 * seems no great harm in that; we'll just get the
2487 * same error again if it's unrelated.
2489 const char *sqlstate;
2491 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2493 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2496 conn->send_appname = false;
2497 /* Must drop the old connection */
2498 pqDropConnection(conn);
2499 conn->status = CONNECTION_NEEDED;
2505 * if the resultStatus is FATAL, then conn->errorMessage
2506 * already has a copy of the error; needn't copy it back.
2507 * But add a newline if it's not there already, since
2508 * postmaster error messages may not have one.
2510 if (conn->errorMessage.len <= 0 ||
2511 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2512 appendPQExpBufferChar(&conn->errorMessage, '\n');
2517 /* We can release the address list now. */
2518 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2519 conn->addrlist = NULL;
2520 conn->addr_cur = NULL;
2522 /* Fire up post-connection housekeeping if needed */
2523 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2525 conn->status = CONNECTION_SETENV;
2526 conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
2527 conn->next_eo = EnvironmentOptions;
2528 return PGRES_POLLING_WRITING;
2531 /* Otherwise, we are open for business! */
2532 conn->status = CONNECTION_OK;
2533 return PGRES_POLLING_OK;
2536 case CONNECTION_SETENV:
2539 * Do post-connection housekeeping (only needed in protocol 2.0).
2541 * We pretend that the connection is OK for the duration of these
2544 conn->status = CONNECTION_OK;
2546 switch (pqSetenvPoll(conn))
2548 case PGRES_POLLING_OK: /* Success */
2551 case PGRES_POLLING_READING: /* Still going */
2552 conn->status = CONNECTION_SETENV;
2553 return PGRES_POLLING_READING;
2555 case PGRES_POLLING_WRITING: /* Still going */
2556 conn->status = CONNECTION_SETENV;
2557 return PGRES_POLLING_WRITING;
2563 /* We are open for business! */
2564 conn->status = CONNECTION_OK;
2565 return PGRES_POLLING_OK;
2568 appendPQExpBuffer(&conn->errorMessage,
2569 libpq_gettext("invalid connection state %d, "
2570 "probably indicative of memory corruption\n"),
2579 dot_pg_pass_warning(conn);
2582 * We used to close the socket at this point, but that makes it awkward
2583 * for those above us if they wish to remove this socket from their own
2584 * records (an fd_set for example). We'll just have this socket closed
2585 * when PQfinish is called (which is compulsory even after an error, since
2586 * the connection structure must be freed).
2588 conn->status = CONNECTION_BAD;
2589 return PGRES_POLLING_FAILED;
2595 * Determine if a server is running and if we can connect to it.
2597 * The argument is a connection that's been started, but not completed.
2600 internal_ping(PGconn *conn)
2602 /* Say "no attempt" if we never got to PQconnectPoll */
2603 if (!conn || !conn->options_valid)
2604 return PQPING_NO_ATTEMPT;
2606 /* Attempt to complete the connection */
2607 if (conn->status != CONNECTION_BAD)
2608 (void) connectDBComplete(conn);
2610 /* Definitely OK if we succeeded */
2611 if (conn->status != CONNECTION_BAD)
2615 * Here begins the interesting part of "ping": determine the cause of the
2616 * failure in sufficient detail to decide what to return. We do not want
2617 * to report that the server is not up just because we didn't have a valid
2618 * password, for example. In fact, any sort of authentication request
2619 * implies the server is up. (We need this check since the libpq side of
2620 * things might have pulled the plug on the connection before getting an
2621 * error as such from the postmaster.)
2623 if (conn->auth_req_received)
2627 * If we failed to get any ERROR response from the postmaster, report
2628 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
2629 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
2630 * out of support. Another corner case where the server could return a
2631 * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
2632 * totally unreasonable for that anyway. We expect that every other
2633 * failure case in a modern server will produce a report with a SQLSTATE.
2635 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
2636 * client-side errors, we should either not store those into
2637 * last_sqlstate, or add an extra flag so we can tell client-side errors
2638 * apart from server-side ones.
2640 if (strlen(conn->last_sqlstate) != 5)
2641 return PQPING_NO_RESPONSE;
2644 * Report PQPING_REJECT if server says it's not accepting connections. (We
2645 * distinguish this case mainly for the convenience of pg_ctl.)
2647 if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
2648 return PQPING_REJECT;
2651 * Any other SQLSTATE can be taken to indicate that the server is up.
2652 * Presumably it didn't like our username, password, or database name; or
2653 * perhaps it had some transient failure, but that should not be taken as
2654 * meaning "it's down".
2662 * - create a PGconn data structure with (as yet) no interesting data
2665 makeEmptyPGconn(void)
2672 * Make sure socket support is up and running.
2676 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
2681 conn = (PGconn *) malloc(sizeof(PGconn));
2690 /* Zero all pointers and booleans */
2691 MemSet(conn, 0, sizeof(PGconn));
2693 /* install default notice hooks */
2694 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2695 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2697 conn->status = CONNECTION_BAD;
2698 conn->asyncStatus = PGASYNC_IDLE;
2699 conn->xactStatus = PQTRANS_IDLE;
2700 conn->options_valid = false;
2701 conn->nonblocking = false;
2702 conn->setenv_state = SETENV_STATE_IDLE;
2703 conn->client_encoding = PG_SQL_ASCII;
2704 conn->std_strings = false; /* unless server says differently */
2705 conn->verbosity = PQERRORS_DEFAULT;
2707 conn->auth_req_received = false;
2708 conn->password_needed = false;
2709 conn->dot_pgpass_used = false;
2711 conn->allow_ssl_try = true;
2712 conn->wait_ssl_try = false;
2716 * We try to send at least 8K at a time, which is the usual size of pipe
2717 * buffers on Unix systems. That way, when we are sending a large amount
2718 * of data, we avoid incurring extra kernel context swaps for partial
2719 * bufferloads. The output buffer is initially made 16K in size, and we
2720 * try to dump it after accumulating 8K.
2722 * With the same goal of minimizing context swaps, the input buffer will
2723 * be enlarged anytime it has less than 8K free, so we initially allocate
2726 conn->inBufSize = 16 * 1024;
2727 conn->inBuffer = (char *) malloc(conn->inBufSize);
2728 conn->outBufSize = 16 * 1024;
2729 conn->outBuffer = (char *) malloc(conn->outBufSize);
2730 conn->rowBufLen = 32;
2731 conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
2732 initPQExpBuffer(&conn->errorMessage);
2733 initPQExpBuffer(&conn->workBuffer);
2735 if (conn->inBuffer == NULL ||
2736 conn->outBuffer == NULL ||
2737 conn->rowBuf == NULL ||
2738 PQExpBufferBroken(&conn->errorMessage) ||
2739 PQExpBufferBroken(&conn->workBuffer))
2741 /* out of memory already :-( */
2751 * - free an idle (closed) PGconn data structure
2753 * NOTE: this should not overlap any functionality with closePGconn().
2754 * Clearing/resetting of transient state belongs there; what we do here is
2755 * release data that is to be held for the life of the PGconn structure.
2756 * If a value ought to be cleared/freed during PQreset(), do it there not here.
2759 freePGconn(PGconn *conn)
2763 /* let any event procs clean up their state data */
2764 for (i = 0; i < conn->nEvents; i++)
2766 PGEventConnDestroy evt;
2769 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2770 conn->events[i].passThrough);
2771 free(conn->events[i].name);
2774 if (conn->client_encoding_initial)
2775 free(conn->client_encoding_initial);
2780 if (conn->pghostaddr)
2781 free(conn->pghostaddr);
2784 if (conn->pgunixsocket)
2785 free(conn->pgunixsocket);
2788 if (conn->connect_timeout)
2789 free(conn->connect_timeout);
2790 if (conn->pgoptions)
2791 free(conn->pgoptions);
2793 free(conn->appname);
2794 if (conn->fbappname)
2795 free(conn->fbappname);
2798 if (conn->replication)
2799 free(conn->replication);
2804 if (conn->keepalives)
2805 free(conn->keepalives);
2806 if (conn->keepalives_idle)
2807 free(conn->keepalives_idle);
2808 if (conn->keepalives_interval)
2809 free(conn->keepalives_interval);
2810 if (conn->keepalives_count)
2811 free(conn->keepalives_count);
2813 free(conn->sslmode);
2815 free(conn->sslcert);
2818 if (conn->sslrootcert)
2819 free(conn->sslrootcert);
2822 if (conn->sslcompression)
2823 free(conn->sslcompression);
2824 if (conn->requirepeer)
2825 free(conn->requirepeer);
2826 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2827 if (conn->krbsrvname)
2828 free(conn->krbsrvname);
2830 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2834 /* Note that conn->Pfdebug is not ours to close or free */
2835 if (conn->last_query)
2836 free(conn->last_query);
2838 free(conn->inBuffer);
2839 if (conn->outBuffer)
2840 free(conn->outBuffer);
2843 termPQExpBuffer(&conn->errorMessage);
2844 termPQExpBuffer(&conn->workBuffer);
2855 * - properly close a connection to the backend
2857 * This should reset or release all transient state, but NOT the connection
2858 * parameters. On exit, the PGconn should be in condition to start a fresh
2859 * connection with the same parameters (see PQreset()).
2862 closePGconn(PGconn *conn)
2865 pgParameterStatus *pstatus;
2868 * Note that the protocol doesn't allow us to send Terminate messages
2869 * during the startup phase.
2871 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2874 * Try to send "close connection" message to backend. Ignore any
2877 pqPutMsgStart('X', false, conn);
2883 * Must reset the blocking status so a possible reconnect will work.
2885 * Don't call PQsetnonblocking() because it will fail if it's unable to
2886 * flush the connection.
2888 conn->nonblocking = FALSE;
2891 * Close the connection, reset all transient state, flush I/O buffers.
2893 pqDropConnection(conn);
2894 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2896 conn->asyncStatus = PGASYNC_IDLE;
2897 pqClearAsyncResult(conn); /* deallocate result */
2898 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2899 conn->addrlist = NULL;
2900 conn->addr_cur = NULL;
2901 notify = conn->notifyHead;
2902 while (notify != NULL)
2904 PGnotify *prev = notify;
2906 notify = notify->next;
2909 conn->notifyHead = conn->notifyTail = NULL;
2910 pstatus = conn->pstatus;
2911 while (pstatus != NULL)
2913 pgParameterStatus *prev = pstatus;
2915 pstatus = pstatus->next;
2918 conn->pstatus = NULL;
2919 if (conn->lobjfuncs)
2920 free(conn->lobjfuncs);
2921 conn->lobjfuncs = NULL;
2927 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2928 if (conn->gtarg_nam)
2929 gss_release_name(&min_s, &conn->gtarg_nam);
2930 if (conn->ginbuf.length)
2931 gss_release_buffer(&min_s, &conn->ginbuf);
2932 if (conn->goutbuf.length)
2933 gss_release_buffer(&min_s, &conn->goutbuf);
2937 if (conn->ginbuf.length)
2938 free(conn->ginbuf.value);
2939 conn->ginbuf.length = 0;
2940 conn->ginbuf.value = NULL;
2941 if (conn->sspitarget)
2942 free(conn->sspitarget);
2943 conn->sspitarget = NULL;
2946 FreeCredentialsHandle(conn->sspicred);
2947 free(conn->sspicred);
2948 conn->sspicred = NULL;
2952 DeleteSecurityContext(conn->sspictx);
2953 free(conn->sspictx);
2954 conn->sspictx = NULL;
2960 * PQfinish: properly close a connection to the backend. Also frees
2961 * the PGconn data structure so it shouldn't be re-used after this.
2964 PQfinish(PGconn *conn)
2974 * PQreset: resets the connection to the backend by closing the
2975 * existing connection and creating a new one.
2978 PQreset(PGconn *conn)
2984 if (connectDBStart(conn) && connectDBComplete(conn))
2987 * Notify event procs of successful reset. We treat an event proc
2988 * failure as disabling the connection ... good idea?
2992 for (i = 0; i < conn->nEvents; i++)
2994 PGEventConnReset evt;
2997 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2998 conn->events[i].passThrough))
3000 conn->status = CONNECTION_BAD;
3001 printfPQExpBuffer(&conn->errorMessage,
3002 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3003 conn->events[i].name);
3014 * resets the connection to the backend
3015 * closes the existing connection and makes a new one
3016 * Returns 1 on success, 0 on failure.
3019 PQresetStart(PGconn *conn)
3025 return connectDBStart(conn);
3034 * resets the connection to the backend
3035 * closes the existing connection and makes a new one
3037 PostgresPollingStatusType
3038 PQresetPoll(PGconn *conn)
3042 PostgresPollingStatusType status = PQconnectPoll(conn);
3044 if (status == PGRES_POLLING_OK)
3047 * Notify event procs of successful reset. We treat an event proc
3048 * failure as disabling the connection ... good idea?
3052 for (i = 0; i < conn->nEvents; i++)
3054 PGEventConnReset evt;
3057 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3058 conn->events[i].passThrough))
3060 conn->status = CONNECTION_BAD;
3061 printfPQExpBuffer(&conn->errorMessage,
3062 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3063 conn->events[i].name);
3064 return PGRES_POLLING_FAILED;
3072 return PGRES_POLLING_FAILED;
3076 * PQcancelGet: get a PGcancel structure corresponding to a connection.
3078 * A copy is needed to be able to cancel a running query from a different
3079 * thread. If the same structure is used all structure members would have
3080 * to be individually locked (if the entire structure was locked, it would
3081 * be impossible to cancel a synchronous query because the structure would
3082 * have to stay locked for the duration of the query).
3085 PQgetCancel(PGconn *conn)
3095 cancel = malloc(sizeof(PGcancel));
3099 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
3100 cancel->be_pid = conn->be_pid;
3101 cancel->be_key = conn->be_key;
3106 /* PQfreeCancel: free a cancel structure */
3108 PQfreeCancel(PGcancel *cancel)
3116 * PQcancel and PQrequestCancel: attempt to request cancellation of the
3117 * current operation.
3119 * The return value is TRUE if the cancel request was successfully
3120 * dispatched, FALSE if not (in which case an error message is available).
3121 * Note: successful dispatch is no guarantee that there will be any effect at
3122 * the backend. The application must read the operation result as usual.
3124 * CAUTION: we want this routine to be safely callable from a signal handler
3125 * (for example, an application might want to call it in a SIGINT handler).
3126 * This means we cannot use any C library routine that might be non-reentrant.
3127 * malloc/free are often non-reentrant, and anything that might call them is
3128 * just as dangerous. We avoid sprintf here for that reason. Building up
3129 * error messages with strcpy/strcat is tedious but should be quite safe.
3130 * We also save/restore errno in case the signal handler support doesn't.
3132 * internal_cancel() is an internal helper function to make code-sharing
3133 * between the two versions of the cancel function possible.
3136 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
3137 char *errbuf, int errbufsize)
3139 int save_errno = SOCK_ERRNO;
3146 CancelRequestPacket cp;
3150 * We need to open a temporary connection to the postmaster. Do this with
3151 * only kernel calls.
3153 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
3155 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
3156 goto cancel_errReturn;
3159 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
3162 if (SOCK_ERRNO == EINTR)
3163 /* Interrupted system call - we'll just try again */
3165 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
3166 goto cancel_errReturn;
3170 * We needn't set nonblocking I/O or NODELAY options here.
3173 /* Create and send the cancel request packet. */
3175 crp.packetlen = htonl((uint32) sizeof(crp));
3176 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
3177 crp.cp.backendPID = htonl(be_pid);
3178 crp.cp.cancelAuthCode = htonl(be_key);
3181 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
3183 if (SOCK_ERRNO == EINTR)
3184 /* Interrupted system call - we'll just try again */
3186 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
3187 goto cancel_errReturn;
3191 * Wait for the postmaster to close the connection, which indicates that
3192 * it's processed the request. Without this delay, we might issue another
3193 * command only to find that our cancel zaps that command instead of the
3194 * one we thought we were canceling. Note we don't actually expect this
3195 * read to obtain any data, we are just waiting for EOF to be signaled.
3198 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
3200 if (SOCK_ERRNO == EINTR)
3201 /* Interrupted system call - we'll just try again */
3203 /* we ignore other error conditions */
3207 closesocket(tmpsock);
3208 SOCK_ERRNO_SET(save_errno);
3214 * Make sure we don't overflow the error buffer. Leave space for the \n at
3215 * the end, and for the terminating zero.
3217 maxlen = errbufsize - strlen(errbuf) - 2;
3220 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
3222 strcat(errbuf, "\n");
3225 closesocket(tmpsock);
3226 SOCK_ERRNO_SET(save_errno);
3231 * PQcancel: request query cancel
3233 * Returns TRUE if able to send the cancel request, FALSE if not.
3235 * On failure, an error message is stored in *errbuf, which must be of size
3236 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
3240 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
3244 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3248 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3249 errbuf, errbufsize);
3253 * PQrequestCancel: old, not thread-safe function for requesting query cancel
3255 * Returns TRUE if able to send the cancel request, FALSE if not.
3257 * On failure, the error message is saved in conn->errorMessage; this means
3258 * that this can't be used when there might be other active operations on
3259 * the connection object.
3261 * NOTE: error messages will be cut off at the current size of the
3262 * error message buffer, since we dare not try to expand conn->errorMessage!
3265 PQrequestCancel(PGconn *conn)
3269 /* Check we have an open connection */
3275 strlcpy(conn->errorMessage.data,
3276 "PQrequestCancel() -- connection is not open\n",
3277 conn->errorMessage.maxlen);
3278 conn->errorMessage.len = strlen(conn->errorMessage.data);
3283 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
3284 conn->errorMessage.data, conn->errorMessage.maxlen);
3287 conn->errorMessage.len = strlen(conn->errorMessage.data);
3294 * pqPacketSend() -- convenience routine to send a message to server.
3296 * pack_type: the single-byte message type code. (Pass zero for startup
3297 * packets, which have no message type code.)
3299 * buf, buf_len: contents of message. The given length includes only what
3300 * is in buf; the message type and message length fields are added here.
3302 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
3303 * SIDE_EFFECTS: may block.
3305 * Note: all messages sent with this routine have a length word, whether
3306 * it's protocol 2.0 or 3.0.
3309 pqPacketSend(PGconn *conn, char pack_type,
3310 const void *buf, size_t buf_len)
3312 /* Start the message. */
3313 if (pqPutMsgStart(pack_type, true, conn))
3314 return STATUS_ERROR;
3316 /* Send the message body. */
3317 if (pqPutnchar(buf, buf_len, conn))
3318 return STATUS_ERROR;
3320 /* Finish the message. */
3321 if (pqPutMsgEnd(conn))
3322 return STATUS_ERROR;
3324 /* Flush to ensure backend gets it. */
3326 return STATUS_ERROR;
3333 #define LDAP_URL "ldap://"
3334 #define LDAP_DEF_PORT 389
3335 #define PGLDAP_TIMEOUT 2
3337 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
3338 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
3344 * Search the LDAP URL passed as first argument, treat the result as a
3345 * string of connection options that are parsed and added to the array of
3346 * options passed as second argument.
3348 * LDAP URLs must conform to RFC 1959 without escape sequences.
3349 * ldap://host:port/dn?attributes?scope?filter?extensions
3352 * 0 if the lookup was successful,
3353 * 1 if the connection to the LDAP server could be established but
3354 * the search was unsuccessful,
3355 * 2 if a connection could not be established, and
3356 * 3 if a fatal error occurred.
3358 * An error message is returned in the third argument for return codes 1 and 3.
3361 ldapServiceLookup(const char *purl, PQconninfoOption *options,
3362 PQExpBuffer errorMessage)
3364 int port = LDAP_DEF_PORT,
3385 char *attrs[2] = {NULL, NULL};
3389 struct berval **values;
3390 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
3392 if ((url = strdup(purl)) == NULL)
3394 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
3399 * Parse URL components, check for correctness. Basically, url has '\0'
3400 * placed at component boundaries and variables are pointed at each
3404 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
3406 printfPQExpBuffer(errorMessage,
3407 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
3413 hostname = url + strlen(LDAP_URL);
3414 if (*hostname == '/') /* no hostname? */
3415 hostname = DefaultHost; /* the default */
3417 /* dn, "distinguished name" */
3418 p = strchr(url + strlen(LDAP_URL), '/');
3419 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3421 printfPQExpBuffer(errorMessage, libpq_gettext(
3422 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
3426 *p = '\0'; /* terminate hostname */
3430 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3432 printfPQExpBuffer(errorMessage, libpq_gettext(
3433 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3441 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3443 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3451 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3453 printfPQExpBuffer(errorMessage,
3454 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
3460 if ((p = strchr(filter, '?')) != NULL)
3464 if ((p1 = strchr(hostname, ':')) != NULL)
3471 lport = strtol(portstr, &endptr, 10);
3472 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
3474 printfPQExpBuffer(errorMessage, libpq_gettext(
3475 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
3482 /* Allow only one attribute */
3483 if (strchr(attrs[0], ',') != NULL)
3485 printfPQExpBuffer(errorMessage, libpq_gettext(
3486 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3492 if (pg_strcasecmp(scopestr, "base") == 0)
3493 scope = LDAP_SCOPE_BASE;
3494 else if (pg_strcasecmp(scopestr, "one") == 0)
3495 scope = LDAP_SCOPE_ONELEVEL;
3496 else if (pg_strcasecmp(scopestr, "sub") == 0)
3497 scope = LDAP_SCOPE_SUBTREE;
3500 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3505 /* initialize LDAP structure */
3506 if ((ld = ldap_init(hostname, port)) == NULL)
3508 printfPQExpBuffer(errorMessage,
3509 libpq_gettext("could not create LDAP structure\n"));
3515 * Initialize connection to the server. We do an explicit bind because we
3516 * want to return 2 if the bind fails.
3518 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3520 /* error in ldap_simple_bind() */
3526 /* wait some time for the connection to succeed */
3528 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3536 /* error in ldap_result() */
3545 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3550 printfPQExpBuffer(errorMessage,
3551 libpq_gettext("lookup on LDAP server failed: %s\n"),
3552 ldap_err2string(rc));
3558 /* complain if there was not exactly one result */
3559 if ((rc = ldap_count_entries(ld, res)) != 1)
3561 printfPQExpBuffer(errorMessage,
3562 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3563 : libpq_gettext("no entry found on LDAP lookup\n"));
3571 if ((entry = ldap_first_entry(ld, res)) == NULL)
3573 /* should never happen */
3574 printfPQExpBuffer(errorMessage,
3575 libpq_gettext("no entry found on LDAP lookup\n"));
3583 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3585 printfPQExpBuffer(errorMessage,
3586 libpq_gettext("attribute has no values on LDAP lookup\n"));
3596 if (values[0] == NULL)
3598 printfPQExpBuffer(errorMessage,
3599 libpq_gettext("attribute has no values on LDAP lookup\n"));
3600 ldap_value_free_len(values);
3605 /* concatenate values into a single string with newline terminators */
3606 size = 1; /* for the trailing null */
3607 for (i = 0; values[i] != NULL; i++)
3608 size += values[i]->bv_len + 1;
3609 if ((result = malloc(size)) == NULL)
3611 printfPQExpBuffer(errorMessage,
3612 libpq_gettext("out of memory\n"));
3613 ldap_value_free_len(values);
3618 for (i = 0; values[i] != NULL; i++)
3620 memcpy(p, values[i]->bv_val, values[i]->bv_len);
3621 p += values[i]->bv_len;
3626 ldap_value_free_len(values);
3629 /* parse result string */
3630 oldstate = state = 0;
3631 for (p = result; *p != '\0'; ++p)
3635 case 0: /* between entries */
3636 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3642 case 1: /* in option name */
3643 if (ld_is_sp_tab(*p))
3648 else if (ld_is_nl_cr(*p))
3650 printfPQExpBuffer(errorMessage, libpq_gettext(
3651 "missing \"=\" after \"%s\" in connection info string\n"),
3662 case 2: /* after option name */
3667 else if (!ld_is_sp_tab(*p))
3669 printfPQExpBuffer(errorMessage, libpq_gettext(
3670 "missing \"=\" after \"%s\" in connection info string\n"),
3676 case 3: /* before option value */
3683 else if (ld_is_nl_cr(*p))
3685 optval = optname + strlen(optname); /* empty */
3688 else if (!ld_is_sp_tab(*p))
3694 case 4: /* in unquoted option value */
3695 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3701 case 5: /* in quoted option value */
3707 else if (*p == '\\')
3712 case 6: /* in quoted option value after escape */
3718 if (state == 0 && oldstate != 0)
3720 found_keyword = false;
3721 for (i = 0; options[i].keyword; i++)
3723 if (strcmp(options[i].keyword, optname) == 0)
3725 if (options[i].val == NULL)
3726 options[i].val = strdup(optval);
3727 found_keyword = true;
3733 printfPQExpBuffer(errorMessage,
3734 libpq_gettext("invalid connection option \"%s\"\n"),
3747 if (state == 5 || state == 6)
3749 printfPQExpBuffer(errorMessage, libpq_gettext(
3750 "unterminated quoted string in connection info string\n"));
3758 #define MAXBUFSIZE 256
3761 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3763 const char *service = conninfo_getval(options, "service");
3764 char serviceFile[MAXPGPATH];
3766 bool group_found = false;
3768 struct stat stat_buf;
3771 * We have to special-case the environment variable PGSERVICE here, since
3772 * this is and should be called before inserting environment defaults for
3773 * other connection options.
3775 if (service == NULL)
3776 service = getenv("PGSERVICE");
3778 if (service == NULL)
3781 if ((env = getenv("PGSERVICEFILE")) != NULL)
3782 strlcpy(serviceFile, env, sizeof(serviceFile));
3785 char homedir[MAXPGPATH];
3787 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3789 printfPQExpBuffer(errorMessage, libpq_gettext("could not get home directory to locate service definition file"));
3792 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
3794 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3798 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3799 if (group_found || status != 0)
3805 * This could be used by any application so we can't use the binary
3806 * location to find our config files.
3808 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3809 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3811 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3814 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3821 printfPQExpBuffer(errorMessage,
3822 libpq_gettext("definition of service \"%s\" not found\n"), service);
3830 parseServiceFile(const char *serviceFile,
3831 const char *service,
3832 PQconninfoOption *options,
3833 PQExpBuffer errorMessage,
3839 char buf[MAXBUFSIZE],
3842 f = fopen(serviceFile, "r");
3845 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3850 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3854 if (strlen(line) >= sizeof(buf) - 1)
3857 printfPQExpBuffer(errorMessage,
3858 libpq_gettext("line %d too long in service file \"%s\"\n"),
3864 /* ignore EOL at end of line */
3865 if (strlen(line) && line[strlen(line) - 1] == '\n')
3866 line[strlen(line) - 1] = 0;
3868 /* ignore leading blanks */
3869 while (*line && isspace((unsigned char) line[0]))
3872 /* ignore comments and empty lines */
3873 if (strlen(line) == 0 || line[0] == '#')
3876 /* Check for right groupname */
3881 /* group info already read */
3886 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3887 line[strlen(service) + 1] == ']')
3888 *group_found = true;
3890 *group_found = false;
3897 * Finally, we are in the right group and can parse the line
3904 if (strncmp(line, "ldap", 4) == 0)
3906 int rc = ldapServiceLookup(line, options, errorMessage);
3908 /* if rc = 2, go on reading for fallback */
3925 val = strchr(line, '=');
3928 printfPQExpBuffer(errorMessage,
3929 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3938 * Set the parameter --- but don't override any previous
3941 found_keyword = false;
3942 for (i = 0; options[i].keyword; i++)
3944 if (strcmp(options[i].keyword, key) == 0)
3946 if (options[i].val == NULL)
3947 options[i].val = strdup(val);
3948 found_keyword = true;
3955 printfPQExpBuffer(errorMessage,
3956 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3975 * Parse a string like PQconnectdb() would do and return the
3976 * resulting connection options array. NULL is returned on failure.
3977 * The result contains only options specified directly in the string,
3978 * not any possible default values.
3980 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3981 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3982 * both *errmsg and the result could be NULL.
3984 * NOTE: the returned array is dynamically allocated and should
3985 * be freed when no longer needed via PQconninfoFree().
3988 PQconninfoParse(const char *conninfo, char **errmsg)
3990 PQExpBufferData errorBuf;
3991 PQconninfoOption *connOptions;
3994 *errmsg = NULL; /* default */
3995 initPQExpBuffer(&errorBuf);
3996 if (PQExpBufferDataBroken(errorBuf))
3997 return NULL; /* out of memory already :-( */
3998 connOptions = parse_connection_string(conninfo, &errorBuf, false);
3999 if (connOptions == NULL && errmsg)
4000 *errmsg = errorBuf.data;
4002 termPQExpBuffer(&errorBuf);
4007 * Build a working copy of the constant PQconninfoOptions array.
4009 static PQconninfoOption *
4010 conninfo_init(PQExpBuffer errorMessage)
4012 PQconninfoOption *options;
4013 PQconninfoOption *opt_dest;
4014 const internalPQconninfoOption *cur_opt;
4017 * Get enough memory for all options in PQconninfoOptions, even if some
4018 * end up being filtered out.
4020 options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4021 if (options == NULL)
4023 printfPQExpBuffer(errorMessage,
4024 libpq_gettext("out of memory\n"));
4029 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4031 /* Only copy the public part of the struct, not the full internal */
4032 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4035 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4041 * Connection string parser
4043 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4044 * Otherwise, NULL is returned and an error message is left in errorMessage.
4046 * If use_defaults is TRUE, default values are filled in (from a service file,
4047 * environment variables, etc).
4049 static PQconninfoOption *
4050 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4053 /* Parse as URI if connection string matches URI prefix */
4054 if (uri_prefix_length(connstr) != 0)
4055 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4057 /* Parse as default otherwise */
4058 return conninfo_parse(connstr, errorMessage, use_defaults);
4062 * Checks if connection string starts with either of the valid URI prefix
4065 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4068 uri_prefix_length(const char *connstr)
4070 if (strncmp(connstr, uri_designator,
4071 sizeof(uri_designator) - 1) == 0)
4072 return sizeof(uri_designator) - 1;
4074 if (strncmp(connstr, short_uri_designator,
4075 sizeof(short_uri_designator) - 1) == 0)
4076 return sizeof(short_uri_designator) - 1;
4082 * Recognized connection string either starts with a valid URI prefix or
4083 * contains a "=" in it.
4085 * Must be consistent with parse_connection_string: anything for which this
4086 * returns true should at least look like it's parseable by that routine.
4089 recognized_connection_string(const char *connstr)
4091 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4095 * Subroutine for parse_connection_string
4097 * Deal with a string containing key=value pairs.
4099 static PQconninfoOption *
4100 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
4108 PQconninfoOption *options;
4110 /* Make a working copy of PQconninfoOptions */
4111 options = conninfo_init(errorMessage);
4112 if (options == NULL)
4115 /* Need a modifiable copy of the input string */
4116 if ((buf = strdup(conninfo)) == NULL)
4118 printfPQExpBuffer(errorMessage,
4119 libpq_gettext("out of memory\n"));
4120 PQconninfoFree(options);
4127 /* Skip blanks before the parameter name */
4128 if (isspace((unsigned char) *cp))
4134 /* Get the parameter name */
4140 if (isspace((unsigned char) *cp))
4145 if (!isspace((unsigned char) *cp))
4154 /* Check that there is a following '=' */
4157 printfPQExpBuffer(errorMessage,
4158 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4160 PQconninfoFree(options);
4166 /* Skip blanks after the '=' */
4169 if (!isspace((unsigned char) *cp))
4174 /* Get the parameter value */
4182 if (isspace((unsigned char) *cp))
4206 printfPQExpBuffer(errorMessage,
4207 libpq_gettext("unterminated quoted string in connection info string\n"));
4208 PQconninfoFree(options);
4230 * Now that we have the name and the value, store the record.
4232 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
4234 PQconninfoFree(options);
4240 /* Done with the modifiable input string */
4244 * Add in defaults if the caller wants that.
4248 if (!conninfo_add_defaults(options, errorMessage))
4250 PQconninfoFree(options);
4259 * Conninfo array parser routine
4261 * If successful, a malloc'd PQconninfoOption array is returned.
4262 * If not successful, NULL is returned and an error message is
4263 * left in errorMessage.
4264 * Defaults are supplied (from a service file, environment variables, etc)
4265 * for unspecified options, but only if use_defaults is TRUE.
4267 * If expand_dbname is non-zero, and the value passed for keyword "dbname" is a
4268 * connection string (as indicated by recognized_connection_string) then parse
4269 * and process it, overriding any previously processed conflicting
4270 * keywords. Subsequent keywords will take precedence, however.
4272 static PQconninfoOption *
4273 conninfo_array_parse(const char *const * keywords, const char *const * values,
4274 PQExpBuffer errorMessage, bool use_defaults,
4277 PQconninfoOption *options;
4278 PQconninfoOption *dbname_options = NULL;
4279 PQconninfoOption *option;
4283 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
4284 * actually a recognized connection string.
4286 while (expand_dbname && keywords[i])
4288 const char *pname = keywords[i];
4289 const char *pvalue = values[i];
4291 /* first find "dbname" if any */
4292 if (strcmp(pname, "dbname") == 0 && pvalue)
4295 * If value is a connection string, parse it, but do not use
4296 * defaults here -- those get picked up later. We only want to
4297 * override for those parameters actually passed.
4299 if (recognized_connection_string(pvalue))
4301 dbname_options = parse_connection_string(pvalue, errorMessage, false);
4302 if (dbname_options == NULL)
4310 /* Make a working copy of PQconninfoOptions */
4311 options = conninfo_init(errorMessage);
4312 if (options == NULL)
4314 PQconninfoFree(dbname_options);
4318 /* Parse the keywords/values arrays */
4322 const char *pname = keywords[i];
4323 const char *pvalue = values[i];
4327 /* Search for the param record */
4328 for (option = options; option->keyword != NULL; option++)
4330 if (strcmp(option->keyword, pname) == 0)
4334 /* Check for invalid connection option */
4335 if (option->keyword == NULL)
4337 printfPQExpBuffer(errorMessage,
4338 libpq_gettext("invalid connection option \"%s\"\n"),
4340 PQconninfoFree(options);
4341 PQconninfoFree(dbname_options);
4346 * If we are on the dbname parameter, and we have a parsed
4347 * connection string, copy those parameters across, overriding any
4348 * existing previous settings.
4350 if (strcmp(pname, "dbname") == 0 && dbname_options)
4352 PQconninfoOption *str_option;
4354 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
4356 if (str_option->val != NULL)
4360 for (k = 0; options[k].keyword; k++)
4362 if (strcmp(options[k].keyword, str_option->keyword) == 0)
4365 free(options[k].val);
4366 options[k].val = strdup(str_option->val);
4376 * Store the value, overriding previous settings
4380 option->val = strdup(pvalue);
4383 printfPQExpBuffer(errorMessage,
4384 libpq_gettext("out of memory\n"));
4385 PQconninfoFree(options);
4386 PQconninfoFree(dbname_options);
4393 PQconninfoFree(dbname_options);
4396 * Add in defaults if the caller wants that.
4400 if (!conninfo_add_defaults(options, errorMessage))
4402 PQconninfoFree(options);
4411 * Add the default values for any unspecified options to the connection
4414 * Defaults are obtained from a service file, environment variables, etc.
4416 * Returns TRUE if successful, otherwise FALSE; errorMessage, if supplied,
4417 * is filled in upon failure. Note that failure to locate a default value
4418 * is not an error condition here --- we just leave the option's value as
4422 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
4424 PQconninfoOption *option;
4428 * If there's a service spec, use it to obtain any not-explicitly-given
4429 * parameters. Ignore error if no error message buffer is passed
4430 * because there is no way to pass back the failure message.
4432 if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
4436 * Get the fallback resources for parameters not specified in the conninfo
4437 * string nor the service.
4439 for (option = options; option->keyword != NULL; option++)
4441 if (option->val != NULL)
4442 continue; /* Value was in conninfo or service */
4445 * Try to get the environment variable fallback
4447 if (option->envvar != NULL)
4449 if ((tmp = getenv(option->envvar)) != NULL)
4451 option->val = strdup(tmp);
4455 printfPQExpBuffer(errorMessage,
4456 libpq_gettext("out of memory\n"));
4464 * No environment variable specified or the variable isn't set - try
4465 * compiled-in default
4467 if (option->compiled != NULL)
4469 option->val = strdup(option->compiled);
4473 printfPQExpBuffer(errorMessage,
4474 libpq_gettext("out of memory\n"));
4481 * Special handling for "user" option
4483 if (strcmp(option->keyword, "user") == 0)
4485 option->val = pg_fe_getauthname();
4494 * Subroutine for parse_connection_string
4496 * Deal with a URI connection string.
4498 static PQconninfoOption *
4499 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
4502 PQconninfoOption *options;
4504 /* Make a working copy of PQconninfoOptions */
4505 options = conninfo_init(errorMessage);
4506 if (options == NULL)
4509 if (!conninfo_uri_parse_options(options, uri, errorMessage))
4511 PQconninfoFree(options);
4516 * Add in defaults if the caller wants that.
4520 if (!conninfo_add_defaults(options, errorMessage))
4522 PQconninfoFree(options);
4531 * conninfo_uri_parse_options
4532 * Actual URI parser.
4534 * If successful, returns true while the options array is filled with parsed
4535 * options from the URI.
4536 * If not successful, returns false and fills errorMessage accordingly.
4538 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
4541 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
4543 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
4544 * by literal square brackets.
4546 * Any of the URI parts might use percent-encoding (%xy).
4549 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
4550 PQExpBuffer errorMessage)
4554 char *buf = strdup(uri); /* need a modifiable copy of the input
4557 char prevchar = '\0';
4560 bool retval = false;
4564 printfPQExpBuffer(errorMessage,
4565 libpq_gettext("out of memory\n"));
4569 /* Skip the URI prefix */
4570 prefix_len = uri_prefix_length(uri);
4571 if (prefix_len == 0)
4573 /* Should never happen */
4574 printfPQExpBuffer(errorMessage,
4575 libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
4579 start += prefix_len;
4582 /* Look ahead for possible user credentials designator */
4583 while (*p && *p != '@' && *p != '/')
4588 * Found username/password designator, so URI should be of the form
4589 * "scheme://user[:password]@[netloc]".
4594 while (*p != ':' && *p != '@')
4597 /* Save last char and cut off at end of user name */
4602 !conninfo_storeval(options, "user", user,
4603 errorMessage, false, true))
4606 if (prevchar == ':')
4608 const char *password = p + 1;
4615 !conninfo_storeval(options, "password", password,
4616 errorMessage, false, true))
4620 /* Advance past end of parsed user name or password token */
4626 * No username/password designator found. Reset to start of URI.
4632 * "p" has been incremented past optional URI credential information at
4633 * this point and now points at the "netloc" part of the URI.
4635 * Look for IPv6 address.
4640 while (*p && *p != ']')
4644 printfPQExpBuffer(errorMessage,
4645 libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
4651 printfPQExpBuffer(errorMessage,
4652 libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
4657 /* Cut off the bracket and advance */
4661 * The address may be followed by a port specifier or a slash or a
4664 if (*p && *p != ':' && *p != '/' && *p != '?')
4666 printfPQExpBuffer(errorMessage,
4667 libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
4668 *p, (int) (p - buf + 1), uri);
4674 /* not an IPv6 address: DNS-named or IPv4 netloc */
4678 * Look for port specifier (colon) or end of host specifier (slash),
4679 * or query (question mark).
4681 while (*p && *p != ':' && *p != '/' && *p != '?')
4685 /* Save the hostname terminator before we null it */
4690 !conninfo_storeval(options, "host", host,
4691 errorMessage, false, true))
4695 if (prevchar == ':')
4697 const char *port = ++p; /* advance past host terminator */
4699 while (*p && *p != '/' && *p != '?')
4706 !conninfo_storeval(options, "port", port,
4707 errorMessage, false, true))
4711 if (prevchar && prevchar != '?')
4713 const char *dbname = ++p; /* advance past host terminator */
4715 /* Look for query parameters */
4716 while (*p && *p != '?')
4723 * Avoid setting dbname to an empty string, as it forces the default
4724 * value (username) and ignores $PGDATABASE, as opposed to not setting
4728 !conninfo_storeval(options, "dbname", dbname,
4729 errorMessage, false, true))
4735 ++p; /* advance past terminator */
4737 if (!conninfo_uri_parse_params(p, options, errorMessage))
4741 /* everything parsed okay */
4750 * Connection URI parameters parser routine
4752 * If successful, returns true while connOptions is filled with parsed
4753 * parameters. Otherwise, returns false and fills errorMessage appropriately.
4755 * Destructively modifies 'params' buffer.
4758 conninfo_uri_parse_params(char *params,
4759 PQconninfoOption *connOptions,
4760 PQExpBuffer errorMessage)
4764 char *keyword = params;
4767 bool malloced = false;
4770 * Scan the params string for '=' and '&', marking the end of keyword
4771 * and value respectively.
4777 /* Was there '=' already? */
4780 printfPQExpBuffer(errorMessage,
4781 libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4785 /* Cut off keyword, advance to value */
4789 else if (*p == '&' || *p == '\0')
4793 /* Cut off value, remember old value */
4797 /* Was there '=' at all? */
4800 printfPQExpBuffer(errorMessage,
4801 libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4807 * If not at the end, advance; now pointing to start of the
4808 * next parameter, if any.
4810 if (prevchar != '\0')
4815 /* Advance, NUL is checked in the 'if' above */
4819 keyword = conninfo_uri_decode(keyword, errorMessage);
4820 if (keyword == NULL)
4822 /* conninfo_uri_decode already set an error message */
4825 value = conninfo_uri_decode(value, errorMessage);
4828 /* conninfo_uri_decode already set an error message */
4835 * Special keyword handling for improved JDBC compatibility.
4837 if (strcmp(keyword, "ssl") == 0 &&
4838 strcmp(value, "true") == 0)
4844 keyword = "sslmode";
4849 * Store the value if the corresponding option exists; ignore
4850 * otherwise. At this point both keyword and value are not
4853 if (!conninfo_storeval(connOptions, keyword, value,
4854 errorMessage, true, false))
4857 * Check if there was a hard error when decoding or storing the
4860 if (errorMessage->len != 0)
4870 printfPQExpBuffer(errorMessage,
4872 "invalid URI query parameter: \"%s\"\n"),
4887 /* Proceed to next key=value pair */
4895 * Connection URI decoder routine
4897 * If successful, returns the malloc'd decoded string.
4898 * If not successful, returns NULL and fills errorMessage accordingly.
4900 * The string is decoded by replacing any percent-encoded tokens with
4901 * corresponding characters, while preserving any non-encoded characters. A
4902 * percent-encoded token is a character triplet: a percent sign, followed by a
4903 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
4904 * treated identically.
4907 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
4909 char *buf = malloc(strlen(str) + 1);
4911 const char *q = str;
4915 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4923 /* copy and check for NUL terminator */
4924 if (!(*(p++) = *(q++)))
4933 ++q; /* skip the percent sign itself */
4936 * Possible EOL will be caught by the first call to
4937 * get_hexdigit(), so we never dereference an invalid q pointer.
4939 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
4941 printfPQExpBuffer(errorMessage,
4942 libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
4951 printfPQExpBuffer(errorMessage,
4952 libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
4965 * Convert hexadecimal digit character to its integer value.
4967 * If successful, returns true and value is filled with digit's base 16 value.
4968 * If not successful, returns false.
4970 * Lower- and upper-case letters in the range A-F are treated identically.
4973 get_hexdigit(char digit, int *value)
4975 if ('0' <= digit && digit <= '9')
4976 *value = digit - '0';
4977 else if ('A' <= digit && digit <= 'F')
4978 *value = digit - 'A' + 10;
4979 else if ('a' <= digit && digit <= 'f')
4980 *value = digit - 'a' + 10;
4988 * Find an option value corresponding to the keyword in the connOptions array.
4990 * If successful, returns a pointer to the corresponding option's value.
4991 * If not successful, returns NULL.
4994 conninfo_getval(PQconninfoOption *connOptions,
4995 const char *keyword)
4997 PQconninfoOption *option;
4999 option = conninfo_find(connOptions, keyword);
5001 return option ? option->val : NULL;
5005 * Store a (new) value for an option corresponding to the keyword in
5006 * connOptions array.
5008 * If uri_decode is true, the value is URI-decoded. The keyword is always
5009 * assumed to be non URI-encoded.
5011 * If successful, returns a pointer to the corresponding PQconninfoOption,
5012 * which value is replaced with a strdup'd copy of the passed value string.
5013 * The existing value for the option is free'd before replacing, if any.
5015 * If not successful, returns NULL and fills errorMessage accordingly.
5016 * However, if the reason of failure is an invalid keyword being passed and
5017 * ignoreMissing is TRUE, errorMessage will be left untouched.
5019 static PQconninfoOption *
5020 conninfo_storeval(PQconninfoOption *connOptions,
5021 const char *keyword, const char *value,
5022 PQExpBuffer errorMessage, bool ignoreMissing,
5025 PQconninfoOption *option;
5029 * For backwards compatibility, requiressl=1 gets translated to
5030 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5031 * (which is the default for sslmode).
5033 if (strcmp(keyword, "requiressl") == 0)
5035 keyword = "sslmode";
5036 if (value[0] == '1')
5042 option = conninfo_find(connOptions, keyword);
5046 printfPQExpBuffer(errorMessage,
5047 libpq_gettext("invalid connection option \"%s\"\n"),
5054 value_copy = conninfo_uri_decode(value, errorMessage);
5055 if (value_copy == NULL)
5056 /* conninfo_uri_decode already set an error message */
5061 value_copy = strdup(value);
5063 if (value_copy == NULL)
5065 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5072 option->val = value_copy;
5078 * Find a PQconninfoOption option corresponding to the keyword in the
5079 * connOptions array.
5081 * If successful, returns a pointer to the corresponding PQconninfoOption
5083 * If not successful, returns NULL.
5085 static PQconninfoOption *
5086 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
5088 PQconninfoOption *option;
5090 for (option = connOptions; option->keyword != NULL; option++)
5092 if (strcmp(option->keyword, keyword) == 0)
5101 * Return the connection options used for the connection
5104 PQconninfo(PGconn *conn)
5106 PQExpBufferData errorBuf;
5107 PQconninfoOption *connOptions;
5112 /* We don't actually report any errors here, but callees want a buffer */
5113 initPQExpBuffer(&errorBuf);
5114 if (PQExpBufferDataBroken(errorBuf))
5115 return NULL; /* out of memory already :-( */
5117 connOptions = conninfo_init(&errorBuf);
5119 if (connOptions != NULL)
5121 const internalPQconninfoOption *option;
5123 for (option = PQconninfoOptions; option->keyword; option++)
5127 if (option->connofs < 0)
5130 connmember = (char **) ((char *) conn + option->connofs);
5133 conninfo_storeval(connOptions, option->keyword, *connmember,
5134 &errorBuf, true, false);
5138 termPQExpBuffer(&errorBuf);
5145 PQconninfoFree(PQconninfoOption *connOptions)
5147 PQconninfoOption *option;
5149 if (connOptions == NULL)
5152 for (option = connOptions; option->keyword != NULL; option++)
5154 if (option->val != NULL)
5161 /* =========== accessor functions for PGconn ========= */
5163 PQdb(const PGconn *conn)
5167 return conn->dbName;
5171 PQuser(const PGconn *conn)
5175 return conn->pguser;
5179 PQpass(const PGconn *conn)
5183 return conn->pgpass;
5187 PQhost(const PGconn *conn)
5191 return conn->pghost ? conn->pghost : conn->pgunixsocket;
5195 PQport(const PGconn *conn)
5199 return conn->pgport;
5203 PQtty(const PGconn *conn)
5211 PQoptions(const PGconn *conn)
5215 return conn->pgoptions;
5219 PQstatus(const PGconn *conn)
5222 return CONNECTION_BAD;
5223 return conn->status;
5226 PGTransactionStatusType
5227 PQtransactionStatus(const PGconn *conn)
5229 if (!conn || conn->status != CONNECTION_OK)
5230 return PQTRANS_UNKNOWN;
5231 if (conn->asyncStatus != PGASYNC_IDLE)
5232 return PQTRANS_ACTIVE;
5233 return conn->xactStatus;
5237 PQparameterStatus(const PGconn *conn, const char *paramName)
5239 const pgParameterStatus *pstatus;
5241 if (!conn || !paramName)
5243 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
5245 if (strcmp(pstatus->name, paramName) == 0)
5246 return pstatus->value;
5252 PQprotocolVersion(const PGconn *conn)
5256 if (conn->status == CONNECTION_BAD)
5258 return PG_PROTOCOL_MAJOR(conn->pversion);
5262 PQserverVersion(const PGconn *conn)
5266 if (conn->status == CONNECTION_BAD)
5268 return conn->sversion;
5272 PQerrorMessage(const PGconn *conn)
5275 return libpq_gettext("connection pointer is NULL\n");
5277 return conn->errorMessage.data;
5281 PQsocket(const PGconn *conn)
5289 PQbackendPID(const PGconn *conn)
5291 if (!conn || conn->status != CONNECTION_OK)
5293 return conn->be_pid;
5297 PQconnectionNeedsPassword(const PGconn *conn)
5301 if (conn->password_needed &&
5302 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
5309 PQconnectionUsedPassword(const PGconn *conn)
5313 if (conn->password_needed)
5320 PQclientEncoding(const PGconn *conn)
5322 if (!conn || conn->status != CONNECTION_OK)
5324 return conn->client_encoding;
5328 PQsetClientEncoding(PGconn *conn, const char *encoding)
5331 static const char query[] = "set client_encoding to '%s'";
5335 if (!conn || conn->status != CONNECTION_OK)
5341 /* Resolve special "auto" value from the locale */
5342 if (strcmp(encoding, "auto") == 0)
5343 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
5345 /* check query buffer overflow */
5346 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
5349 /* ok, now send a query */
5350 sprintf(qbuf, query, encoding);
5351 res = PQexec(conn, qbuf);
5355 if (res->resultStatus != PGRES_COMMAND_OK)
5360 * In protocol 2 we have to assume the setting will stick, and adjust
5361 * our state immediately. In protocol 3 and up we can rely on the
5362 * backend to report the parameter value, and we'll change state at
5365 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
5366 pqSaveParameterStatus(conn, "client_encoding", encoding);
5367 status = 0; /* everything is ok */
5374 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
5379 return PQERRORS_DEFAULT;
5380 old = conn->verbosity;
5381 conn->verbosity = verbosity;
5386 PQtrace(PGconn *conn, FILE *debug_port)
5391 conn->Pfdebug = debug_port;
5395 PQuntrace(PGconn *conn)
5401 fflush(conn->Pfdebug);
5402 conn->Pfdebug = NULL;
5407 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
5409 PQnoticeReceiver old;
5414 old = conn->noticeHooks.noticeRec;
5417 conn->noticeHooks.noticeRec = proc;
5418 conn->noticeHooks.noticeRecArg = arg;
5424 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
5426 PQnoticeProcessor old;
5431 old = conn->noticeHooks.noticeProc;
5434 conn->noticeHooks.noticeProc = proc;
5435 conn->noticeHooks.noticeProcArg = arg;
5441 * The default notice message receiver just gets the standard notice text
5442 * and sends it to the notice processor. This two-level setup exists
5443 * mostly for backwards compatibility; perhaps we should deprecate use of
5444 * PQsetNoticeProcessor?
5447 defaultNoticeReceiver(void *arg, const PGresult *res)
5449 (void) arg; /* not used */
5450 if (res->noticeHooks.noticeProc != NULL)
5451 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
5452 PQresultErrorMessage(res));
5456 * The default notice message processor just prints the
5457 * message on stderr. Applications can override this if they
5458 * want the messages to go elsewhere (a window, for example).
5459 * Note that simply discarding notices is probably a bad idea.
5462 defaultNoticeProcessor(void *arg, const char *message)
5464 (void) arg; /* not used */
5465 /* Note: we expect the supplied string to end with a newline already. */
5466 fprintf(stderr, "%s", message);
5470 * returns a pointer to the next token or NULL if the current
5471 * token doesn't match
5474 pwdfMatchesString(char *buf, char *token)
5478 bool bslash = false;
5480 if (buf == NULL || token == NULL)
5484 if (tbuf[0] == '*' && tbuf[1] == ':')
5488 if (*tbuf == '\\' && !bslash)
5493 if (*tbuf == ':' && *ttok == 0 && !bslash)
5509 /* Get a password from the password file. Return value is malloc'd. */
5511 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
5514 char pgpassfile[MAXPGPATH];
5515 struct stat stat_buf;
5517 #define LINELEN NAMEDATALEN*5
5520 if (dbname == NULL || strlen(dbname) == 0)
5523 if (username == NULL || strlen(username) == 0)
5526 /* 'localhost' matches pghost of '' or the default socket directory */
5527 if (hostname == NULL)
5528 hostname = DefaultHost;
5529 else if (is_absolute_path(hostname))
5532 * We should probably use canonicalize_path(), but then we have to
5533 * bring path.c into libpq, and it doesn't seem worth it.
5535 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
5536 hostname = DefaultHost;
5539 port = DEF_PGPORT_STR;
5541 if (!getPgPassFilename(pgpassfile))
5544 /* If password file cannot be opened, ignore it. */
5545 if (stat(pgpassfile, &stat_buf) != 0)
5549 if (!S_ISREG(stat_buf.st_mode))
5552 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
5557 /* If password file is insecure, alert the user and ignore it. */
5558 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
5561 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
5568 * On Win32, the directory is protected, so we don't have to check the
5573 fp = fopen(pgpassfile, "r");
5577 while (!feof(fp) && !ferror(fp))
5585 if (fgets(buf, sizeof(buf), fp) == NULL)
5592 /* Remove trailing newline */
5593 if (buf[len - 1] == '\n')
5596 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
5597 (t = pwdfMatchesString(t, port)) == NULL ||
5598 (t = pwdfMatchesString(t, dbname)) == NULL ||
5599 (t = pwdfMatchesString(t, username)) == NULL)
5604 /* De-escape password. */
5605 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
5607 if (*p1 == '\\' && p1[1] != '\0')
5624 getPgPassFilename(char *pgpassfile)
5628 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
5629 /* use the literal path from the environment, if set */
5630 strlcpy(pgpassfile, passfile_env, MAXPGPATH);
5633 char homedir[MAXPGPATH];
5635 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5637 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
5643 * If the connection failed, we should mention if
5644 * we got the password from .pgpass in case that
5645 * password is wrong.
5648 dot_pg_pass_warning(PGconn *conn)
5650 /* If it was 'invalid authorization', add .pgpass mention */
5651 /* only works with >= 9.0 servers */
5652 if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
5653 strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
5654 ERRCODE_INVALID_PASSWORD) == 0)
5656 char pgpassfile[MAXPGPATH];
5658 if (!getPgPassFilename(pgpassfile))
5660 appendPQExpBuffer(&conn->errorMessage,
5661 libpq_gettext("password retrieved from file \"%s\"\n"),
5668 * Obtain user's home directory, return in given buffer
5670 * On Unix, this actually returns the user's home directory. On Windows
5671 * it returns the PostgreSQL-specific application data folder.
5673 * This is essentially the same as get_home_path(), but we don't use that
5674 * because we don't want to pull path.c into libpq (it pollutes application
5678 pqGetHomeDirectory(char *buf, int bufsize)
5681 char pwdbuf[BUFSIZ];
5682 struct passwd pwdstr;
5683 struct passwd *pwd = NULL;
5685 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
5687 strlcpy(buf, pwd->pw_dir, bufsize);
5690 char tmppath[MAX_PATH];
5692 ZeroMemory(tmppath, sizeof(tmppath));
5693 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
5695 snprintf(buf, bufsize, "%s/postgresql", tmppath);
5701 * To keep the API consistent, the locking stubs are always provided, even
5702 * if they are not required.
5706 default_threadlock(int acquire)
5708 #ifdef ENABLE_THREAD_SAFETY
5710 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
5712 static pthread_mutex_t singlethread_lock = NULL;
5713 static long mutex_initlock = 0;
5715 if (singlethread_lock == NULL)
5717 while (InterlockedExchange(&mutex_initlock, 1) == 1)
5718 /* loop, another thread own the lock */ ;
5719 if (singlethread_lock == NULL)
5721 if (pthread_mutex_init(&singlethread_lock, NULL))
5722 PGTHREAD_ERROR("failed to initialize mutex");
5724 InterlockedExchange(&mutex_initlock, 0);
5729 if (pthread_mutex_lock(&singlethread_lock))
5730 PGTHREAD_ERROR("failed to lock mutex");
5734 if (pthread_mutex_unlock(&singlethread_lock))
5735 PGTHREAD_ERROR("failed to unlock mutex");
5741 PQregisterThreadLock(pgthreadlock_t newhandler)
5743 pgthreadlock_t prev = pg_g_threadlock;
5746 pg_g_threadlock = newhandler;
5748 pg_g_threadlock = default_threadlock;