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", "", 12, /* sizeof("verify-full") == 12 */
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(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 */
401 if (conn->sock != PGINVALID_SOCKET)
402 closesocket(conn->sock);
403 conn->sock = PGINVALID_SOCKET;
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;
1634 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1635 if (conn->sock == PGINVALID_SOCKET)
1638 * ignore socket() failure if we have more addresses
1641 if (addr_cur->ai_next != NULL)
1643 conn->addr_cur = addr_cur->ai_next;
1646 appendPQExpBuffer(&conn->errorMessage,
1647 libpq_gettext("could not create socket: %s\n"),
1648 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1653 * Select socket options: no delay of outgoing data for
1654 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1657 if (!IS_AF_UNIX(addr_cur->ai_family))
1659 if (!connectNoDelay(conn))
1661 pqDropConnection(conn);
1662 conn->addr_cur = addr_cur->ai_next;
1666 if (!pg_set_noblock(conn->sock))
1668 appendPQExpBuffer(&conn->errorMessage,
1669 libpq_gettext("could not set socket to nonblocking mode: %s\n"),
1670 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1671 pqDropConnection(conn);
1672 conn->addr_cur = addr_cur->ai_next;
1677 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1679 appendPQExpBuffer(&conn->errorMessage,
1680 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1681 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1682 pqDropConnection(conn);
1683 conn->addr_cur = addr_cur->ai_next;
1686 #endif /* F_SETFD */
1688 if (!IS_AF_UNIX(addr_cur->ai_family))
1693 int usekeepalives = useKeepalives(conn);
1696 if (usekeepalives < 0)
1698 appendPQExpBufferStr(&conn->errorMessage,
1699 libpq_gettext("keepalives parameter must be an integer\n"));
1702 else if (usekeepalives == 0)
1707 else if (setsockopt(conn->sock,
1708 SOL_SOCKET, SO_KEEPALIVE,
1709 (char *) &on, sizeof(on)) < 0)
1711 appendPQExpBuffer(&conn->errorMessage,
1712 libpq_gettext("setsockopt(SO_KEEPALIVE) failed: %s\n"),
1713 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1716 else if (!setKeepalivesIdle(conn)
1717 || !setKeepalivesInterval(conn)
1718 || !setKeepalivesCount(conn))
1721 #ifdef SIO_KEEPALIVE_VALS
1722 else if (!setKeepalivesWin32(conn))
1724 #endif /* SIO_KEEPALIVE_VALS */
1729 pqDropConnection(conn);
1730 conn->addr_cur = addr_cur->ai_next;
1736 * We have three methods of blocking SIGPIPE during
1737 * send() calls to this socket:
1739 * - setsockopt(sock, SO_NOSIGPIPE)
1740 * - send(sock, ..., MSG_NOSIGNAL)
1741 * - setting the signal mask to SIG_IGN during send()
1743 * The third method requires three syscalls per send,
1744 * so we prefer either of the first two, but they are
1745 * less portable. The state is tracked in the following
1746 * members of PGconn:
1748 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
1749 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
1751 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
1752 * and we're done. Otherwise, set sigpipe_flag so that
1753 * we will try MSG_NOSIGNAL on sends. If we get an error
1754 * with MSG_NOSIGNAL, we'll clear that flag and revert to
1758 conn->sigpipe_so = false;
1760 conn->sigpipe_flag = true;
1762 conn->sigpipe_flag = false;
1763 #endif /* MSG_NOSIGNAL */
1767 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
1768 (char *) &optval, sizeof(optval)) == 0)
1770 conn->sigpipe_so = true;
1771 conn->sigpipe_flag = false;
1773 #endif /* SO_NOSIGPIPE */
1776 * Start/make connection. This should not block, since we
1777 * are in nonblock mode. If it does, well, too bad.
1779 if (connect(conn->sock, addr_cur->ai_addr,
1780 addr_cur->ai_addrlen) < 0)
1782 if (SOCK_ERRNO == EINPROGRESS ||
1784 SOCK_ERRNO == EWOULDBLOCK ||
1786 SOCK_ERRNO == EINTR)
1789 * This is fine - we're in non-blocking mode, and
1790 * the connection is in progress. Tell caller to
1791 * wait for write-ready on socket.
1793 conn->status = CONNECTION_STARTED;
1794 return PGRES_POLLING_WRITING;
1796 /* otherwise, trouble */
1801 * Hm, we're connected already --- seems the "nonblock
1802 * connection" wasn't. Advance the state machine and
1803 * go do the next stuff.
1805 conn->status = CONNECTION_STARTED;
1810 * This connection failed --- set up error report, then
1811 * close socket (do it this way in case close() affects
1812 * the value of errno...). We will ignore the connect()
1813 * failure and keep going if there are more addresses.
1815 connectFailureMessage(conn, SOCK_ERRNO);
1816 pqDropConnection(conn);
1819 * Try the next address, if any.
1821 conn->addr_cur = addr_cur->ai_next;
1822 } /* loop over addresses */
1825 * Ooops, no more addresses. An appropriate error message is
1826 * already set up, so just set the right status.
1831 case CONNECTION_STARTED:
1833 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1836 * Write ready, since we've made it here, so the connection
1837 * has been made ... or has failed.
1841 * Now check (using getsockopt) that there is not an error
1842 * state waiting for us on the socket.
1845 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1846 (char *) &optval, &optlen) == -1)
1848 appendPQExpBuffer(&conn->errorMessage,
1849 libpq_gettext("could not get socket error status: %s\n"),
1850 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1853 else if (optval != 0)
1856 * When using a nonblocking connect, we will typically see
1857 * connect failures at this point, so provide a friendly
1860 connectFailureMessage(conn, optval);
1861 pqDropConnection(conn);
1864 * If more addresses remain, keep trying, just as in the
1865 * case where connect() returned failure immediately.
1867 if (conn->addr_cur->ai_next != NULL)
1869 conn->addr_cur = conn->addr_cur->ai_next;
1870 conn->status = CONNECTION_NEEDED;
1876 /* Fill in the client address */
1877 conn->laddr.salen = sizeof(conn->laddr.addr);
1878 if (getsockname(conn->sock,
1879 (struct sockaddr *) & conn->laddr.addr,
1880 &conn->laddr.salen) < 0)
1882 appendPQExpBuffer(&conn->errorMessage,
1883 libpq_gettext("could not get client address from socket: %s\n"),
1884 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1889 * Make sure we can write before advancing to next step.
1891 conn->status = CONNECTION_MADE;
1892 return PGRES_POLLING_WRITING;
1895 case CONNECTION_MADE:
1900 #ifdef HAVE_UNIX_SOCKETS
1903 * Implement requirepeer check, if requested and it's a
1904 * Unix-domain socket.
1906 if (conn->requirepeer && conn->requirepeer[0] &&
1907 IS_AF_UNIX(conn->raddr.addr.ss_family))
1909 char pwdbuf[BUFSIZ];
1910 struct passwd pass_buf;
1911 struct passwd *pass;
1916 if (getpeereid(conn->sock, &uid, &gid) != 0)
1919 * Provide special error message if getpeereid is a
1922 if (errno == ENOSYS)
1923 appendPQExpBufferStr(&conn->errorMessage,
1924 libpq_gettext("requirepeer parameter is not supported on this platform\n"));
1926 appendPQExpBuffer(&conn->errorMessage,
1927 libpq_gettext("could not get peer credentials: %s\n"),
1928 pqStrerror(errno, sebuf, sizeof(sebuf)));
1932 pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
1936 appendPQExpBuffer(&conn->errorMessage,
1937 libpq_gettext("local user with ID %d does not exist\n"),
1942 if (strcmp(pass->pw_name, conn->requirepeer) != 0)
1944 appendPQExpBuffer(&conn->errorMessage,
1945 libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
1946 conn->requirepeer, pass->pw_name);
1950 #endif /* HAVE_UNIX_SOCKETS */
1955 * If SSL is enabled and we haven't already got it running,
1956 * request it instead of sending the startup message.
1958 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1960 /* Don't bother requesting SSL over a Unix socket */
1961 conn->allow_ssl_try = false;
1963 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1969 * Send the SSL request packet.
1971 * Theoretically, this could block, but it really
1972 * shouldn't since we only got here if the socket is
1975 pv = htonl(NEGOTIATE_SSL_CODE);
1976 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1978 appendPQExpBuffer(&conn->errorMessage,
1979 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1980 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1983 /* Ok, wait for response */
1984 conn->status = CONNECTION_SSL_STARTUP;
1985 return PGRES_POLLING_READING;
1987 #endif /* USE_SSL */
1990 * Build the startup packet.
1992 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1993 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1994 EnvironmentOptions);
1996 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1997 EnvironmentOptions);
2001 * will not appendbuffer here, since it's likely to also
2004 printfPQExpBuffer(&conn->errorMessage,
2005 libpq_gettext("out of memory\n"));
2010 * Send the startup packet.
2012 * Theoretically, this could block, but it really shouldn't
2013 * since we only got here if the socket is write-ready.
2015 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2017 appendPQExpBuffer(&conn->errorMessage,
2018 libpq_gettext("could not send startup packet: %s\n"),
2019 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2026 conn->status = CONNECTION_AWAITING_RESPONSE;
2027 return PGRES_POLLING_READING;
2031 * Handle SSL negotiation: wait for postmaster messages and
2032 * respond as necessary.
2034 case CONNECTION_SSL_STARTUP:
2037 PostgresPollingStatusType pollres;
2040 * On first time through, get the postmaster's response to our
2041 * SSL negotiation packet.
2043 if (conn->ssl == NULL)
2046 * We use pqReadData here since it has the logic to
2047 * distinguish no-data-yet from connection closure. Since
2048 * conn->ssl isn't set, a plain recv() will occur.
2053 rdresult = pqReadData(conn);
2056 /* errorMessage is already filled in */
2061 /* caller failed to wait for data */
2062 return PGRES_POLLING_READING;
2064 if (pqGetc(&SSLok, conn) < 0)
2066 /* should not happen really */
2067 return PGRES_POLLING_READING;
2071 /* mark byte consumed */
2072 conn->inStart = conn->inCursor;
2073 /* Set up global SSL state if required */
2074 if (pqsecure_initialize(conn) != 0)
2077 else if (SSLok == 'N')
2079 /* mark byte consumed */
2080 conn->inStart = conn->inCursor;
2081 /* OK to do without SSL? */
2082 if (conn->sslmode[0] == 'r' || /* "require" */
2083 conn->sslmode[0] == 'v') /* "verify-ca" or
2086 /* Require SSL, but server does not want it */
2087 appendPQExpBufferStr(&conn->errorMessage,
2088 libpq_gettext("server does not support SSL, but SSL was required\n"));
2091 /* Otherwise, proceed with normal startup */
2092 conn->allow_ssl_try = false;
2093 conn->status = CONNECTION_MADE;
2094 return PGRES_POLLING_WRITING;
2096 else if (SSLok == 'E')
2099 * Server failure of some sort, such as failure to
2100 * fork a backend process. We need to process and
2101 * report the error message, which might be formatted
2102 * according to either protocol 2 or protocol 3.
2103 * Rather than duplicate the code for that, we flip
2104 * into AWAITING_RESPONSE state and let the code there
2105 * deal with it. Note we have *not* consumed the "E"
2108 conn->status = CONNECTION_AWAITING_RESPONSE;
2113 appendPQExpBuffer(&conn->errorMessage,
2114 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2121 * Begin or continue the SSL negotiation process.
2123 pollres = pqsecure_open_client(conn);
2124 if (pollres == PGRES_POLLING_OK)
2126 /* SSL handshake done, ready to send startup packet */
2127 conn->status = CONNECTION_MADE;
2128 return PGRES_POLLING_WRITING;
2130 if (pollres == PGRES_POLLING_FAILED)
2133 * Failed ... if sslmode is "prefer" then do a non-SSL
2136 if (conn->sslmode[0] == 'p' /* "prefer" */
2137 && conn->allow_ssl_try /* redundant? */
2138 && !conn->wait_ssl_try) /* redundant? */
2140 /* only retry once */
2141 conn->allow_ssl_try = false;
2142 /* Must drop the old connection */
2143 pqDropConnection(conn);
2144 conn->status = CONNECTION_NEEDED;
2149 #else /* !USE_SSL */
2150 /* can't get here */
2152 #endif /* USE_SSL */
2156 * Handle authentication exchange: wait for postmaster messages
2157 * and respond as necessary.
2159 case CONNECTION_AWAITING_RESPONSE:
2167 * Scan the message from current point (note that if we find
2168 * the message is incomplete, we will return without advancing
2169 * inStart, and resume here next time).
2171 conn->inCursor = conn->inStart;
2173 /* Read type byte */
2174 if (pqGetc(&beresp, conn))
2176 /* We'll come back when there is more data */
2177 return PGRES_POLLING_READING;
2181 * Validate message type: we expect only an authentication
2182 * request or an error here. Anything else probably means
2183 * it's not Postgres on the other end at all.
2185 if (!(beresp == 'R' || beresp == 'E'))
2187 appendPQExpBuffer(&conn->errorMessage,
2189 "expected authentication request from "
2190 "server, but received %c\n"),
2195 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2197 /* Read message length word */
2198 if (pqGetInt(&msgLength, 4, conn))
2200 /* We'll come back when there is more data */
2201 return PGRES_POLLING_READING;
2206 /* Set phony message length to disable checks below */
2211 * Try to validate message length before using it.
2212 * Authentication requests can't be very large, although GSS
2213 * auth requests may not be that small. Errors can be a
2214 * little larger, but not huge. If we see a large apparent
2215 * length in an error, it means we're really talking to a
2216 * pre-3.0-protocol server; cope.
2218 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2220 appendPQExpBuffer(&conn->errorMessage,
2222 "expected authentication request from "
2223 "server, but received %c\n"),
2228 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2230 /* Handle error from a pre-3.0 server */
2231 conn->inCursor = conn->inStart + 1; /* reread data */
2232 if (pqGets_append(&conn->errorMessage, conn))
2234 /* We'll come back when there is more data */
2235 return PGRES_POLLING_READING;
2237 /* OK, we read the message; mark data consumed */
2238 conn->inStart = conn->inCursor;
2241 * The postmaster typically won't end its message with a
2242 * newline, so add one to conform to libpq conventions.
2244 appendPQExpBufferChar(&conn->errorMessage, '\n');
2247 * If we tried to open the connection in 3.0 protocol,
2248 * fall back to 2.0 protocol.
2250 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2252 conn->pversion = PG_PROTOCOL(2, 0);
2253 /* Must drop the old connection */
2254 pqDropConnection(conn);
2255 conn->status = CONNECTION_NEEDED;
2263 * Can't process if message body isn't all here yet.
2265 * (In protocol 2.0 case, we are assuming messages carry at
2266 * least 4 bytes of data.)
2269 avail = conn->inEnd - conn->inCursor;
2270 if (avail < msgLength)
2273 * Before returning, try to enlarge the input buffer if
2274 * needed to hold the whole message; see notes in
2277 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2280 /* We'll come back when there is more data */
2281 return PGRES_POLLING_READING;
2284 /* Handle errors. */
2287 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2289 if (pqGetErrorNotice3(conn, true))
2291 /* We'll come back when there is more data */
2292 return PGRES_POLLING_READING;
2297 if (pqGets_append(&conn->errorMessage, conn))
2299 /* We'll come back when there is more data */
2300 return PGRES_POLLING_READING;
2303 /* OK, we read the message; mark data consumed */
2304 conn->inStart = conn->inCursor;
2309 * if sslmode is "allow" and we haven't tried an SSL
2310 * connection already, then retry with an SSL connection
2312 if (conn->sslmode[0] == 'a' /* "allow" */
2313 && conn->ssl == NULL
2314 && conn->allow_ssl_try
2315 && conn->wait_ssl_try)
2317 /* only retry once */
2318 conn->wait_ssl_try = false;
2319 /* Must drop the old connection */
2320 pqDropConnection(conn);
2321 conn->status = CONNECTION_NEEDED;
2326 * if sslmode is "prefer" and we're in an SSL connection,
2327 * then do a non-SSL retry
2329 if (conn->sslmode[0] == 'p' /* "prefer" */
2330 && conn->allow_ssl_try
2331 && !conn->wait_ssl_try) /* redundant? */
2333 /* only retry once */
2334 conn->allow_ssl_try = false;
2335 /* Must drop the old connection */
2336 pqDropConnection(conn);
2337 conn->status = CONNECTION_NEEDED;
2345 /* It is an authentication request. */
2346 conn->auth_req_received = true;
2348 /* Get the type of request. */
2349 if (pqGetInt((int *) &areq, 4, conn))
2351 /* We'll come back when there are more data */
2352 return PGRES_POLLING_READING;
2355 /* Get the password salt if there is one. */
2356 if (areq == AUTH_REQ_MD5)
2358 if (pqGetnchar(conn->md5Salt,
2359 sizeof(conn->md5Salt), conn))
2361 /* We'll come back when there are more data */
2362 return PGRES_POLLING_READING;
2365 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2368 * Continue GSSAPI/SSPI authentication
2370 if (areq == AUTH_REQ_GSS_CONT)
2372 int llen = msgLength - 4;
2375 * We can be called repeatedly for the same buffer. Avoid
2376 * re-allocating the buffer in this case - just re-use the
2379 if (llen != conn->ginbuf.length)
2381 if (conn->ginbuf.value)
2382 free(conn->ginbuf.value);
2384 conn->ginbuf.length = llen;
2385 conn->ginbuf.value = malloc(llen);
2386 if (!conn->ginbuf.value)
2388 printfPQExpBuffer(&conn->errorMessage,
2389 libpq_gettext("out of memory allocating GSSAPI buffer (%d)"),
2395 if (pqGetnchar(conn->ginbuf.value, llen, conn))
2397 /* We'll come back when there is more data. */
2398 return PGRES_POLLING_READING;
2404 * OK, we successfully read the message; mark data consumed
2406 conn->inStart = conn->inCursor;
2408 /* Respond to the request if necessary. */
2411 * Note that conn->pghost must be non-NULL if we are going to
2412 * avoid the Kerberos code doing a hostname look-up.
2415 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
2417 conn->errorMessage.len = strlen(conn->errorMessage.data);
2420 conn->errorMessage.len = strlen(conn->errorMessage.data);
2423 * Just make sure that any data sent by pg_fe_sendauth is
2424 * flushed out. Although this theoretically could block, it
2425 * really shouldn't since we don't send large auth responses.
2430 if (areq == AUTH_REQ_OK)
2432 /* We are done with authentication exchange */
2433 conn->status = CONNECTION_AUTH_OK;
2436 * Set asyncStatus so that PQgetResult will think that
2437 * what comes back next is the result of a query. See
2440 conn->asyncStatus = PGASYNC_BUSY;
2443 /* Look to see if we have more data yet. */
2447 case CONNECTION_AUTH_OK:
2450 * Now we expect to hear from the backend. A ReadyForQuery
2451 * message indicates that startup is successful, but we might
2452 * also get an Error message indicating failure. (Notice
2453 * messages indicating nonfatal warnings are also allowed by
2454 * the protocol, as are ParameterStatus and BackendKeyData
2455 * messages.) Easiest way to handle this is to let
2456 * PQgetResult() read the messages. We just have to fake it
2457 * out about the state of the connection, by setting
2458 * asyncStatus = PGASYNC_BUSY (done above).
2462 return PGRES_POLLING_READING;
2464 res = PQgetResult(conn);
2467 * NULL return indicating we have gone to IDLE state is
2472 if (res->resultStatus != PGRES_FATAL_ERROR)
2473 appendPQExpBufferStr(&conn->errorMessage,
2474 libpq_gettext("unexpected message from server during startup\n"));
2475 else if (conn->send_appname &&
2476 (conn->appname || conn->fbappname))
2479 * If we tried to send application_name, check to see
2480 * if the error is about that --- pre-9.0 servers will
2481 * reject it at this stage of the process. If so,
2482 * close the connection and retry without sending
2483 * application_name. We could possibly get a false
2484 * SQLSTATE match here and retry uselessly, but there
2485 * seems no great harm in that; we'll just get the
2486 * same error again if it's unrelated.
2488 const char *sqlstate;
2490 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2492 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2495 conn->send_appname = false;
2496 /* Must drop the old connection */
2497 pqDropConnection(conn);
2498 conn->status = CONNECTION_NEEDED;
2504 * if the resultStatus is FATAL, then conn->errorMessage
2505 * already has a copy of the error; needn't copy it back.
2506 * But add a newline if it's not there already, since
2507 * postmaster error messages may not have one.
2509 if (conn->errorMessage.len <= 0 ||
2510 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2511 appendPQExpBufferChar(&conn->errorMessage, '\n');
2516 /* We can release the address list now. */
2517 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2518 conn->addrlist = NULL;
2519 conn->addr_cur = NULL;
2521 /* Fire up post-connection housekeeping if needed */
2522 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2524 conn->status = CONNECTION_SETENV;
2525 conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
2526 conn->next_eo = EnvironmentOptions;
2527 return PGRES_POLLING_WRITING;
2530 /* Otherwise, we are open for business! */
2531 conn->status = CONNECTION_OK;
2532 return PGRES_POLLING_OK;
2535 case CONNECTION_SETENV:
2538 * Do post-connection housekeeping (only needed in protocol 2.0).
2540 * We pretend that the connection is OK for the duration of these
2543 conn->status = CONNECTION_OK;
2545 switch (pqSetenvPoll(conn))
2547 case PGRES_POLLING_OK: /* Success */
2550 case PGRES_POLLING_READING: /* Still going */
2551 conn->status = CONNECTION_SETENV;
2552 return PGRES_POLLING_READING;
2554 case PGRES_POLLING_WRITING: /* Still going */
2555 conn->status = CONNECTION_SETENV;
2556 return PGRES_POLLING_WRITING;
2562 /* We are open for business! */
2563 conn->status = CONNECTION_OK;
2564 return PGRES_POLLING_OK;
2567 appendPQExpBuffer(&conn->errorMessage,
2568 libpq_gettext("invalid connection state %d, "
2569 "probably indicative of memory corruption\n"),
2578 dot_pg_pass_warning(conn);
2581 * We used to close the socket at this point, but that makes it awkward
2582 * for those above us if they wish to remove this socket from their own
2583 * records (an fd_set for example). We'll just have this socket closed
2584 * when PQfinish is called (which is compulsory even after an error, since
2585 * the connection structure must be freed).
2587 conn->status = CONNECTION_BAD;
2588 return PGRES_POLLING_FAILED;
2594 * Determine if a server is running and if we can connect to it.
2596 * The argument is a connection that's been started, but not completed.
2599 internal_ping(PGconn *conn)
2601 /* Say "no attempt" if we never got to PQconnectPoll */
2602 if (!conn || !conn->options_valid)
2603 return PQPING_NO_ATTEMPT;
2605 /* Attempt to complete the connection */
2606 if (conn->status != CONNECTION_BAD)
2607 (void) connectDBComplete(conn);
2609 /* Definitely OK if we succeeded */
2610 if (conn->status != CONNECTION_BAD)
2614 * Here begins the interesting part of "ping": determine the cause of the
2615 * failure in sufficient detail to decide what to return. We do not want
2616 * to report that the server is not up just because we didn't have a valid
2617 * password, for example. In fact, any sort of authentication request
2618 * implies the server is up. (We need this check since the libpq side of
2619 * things might have pulled the plug on the connection before getting an
2620 * error as such from the postmaster.)
2622 if (conn->auth_req_received)
2626 * If we failed to get any ERROR response from the postmaster, report
2627 * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
2628 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
2629 * out of support. Another corner case where the server could return a
2630 * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
2631 * totally unreasonable for that anyway. We expect that every other
2632 * failure case in a modern server will produce a report with a SQLSTATE.
2634 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
2635 * client-side errors, we should either not store those into
2636 * last_sqlstate, or add an extra flag so we can tell client-side errors
2637 * apart from server-side ones.
2639 if (strlen(conn->last_sqlstate) != 5)
2640 return PQPING_NO_RESPONSE;
2643 * Report PQPING_REJECT if server says it's not accepting connections. (We
2644 * distinguish this case mainly for the convenience of pg_ctl.)
2646 if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
2647 return PQPING_REJECT;
2650 * Any other SQLSTATE can be taken to indicate that the server is up.
2651 * Presumably it didn't like our username, password, or database name; or
2652 * perhaps it had some transient failure, but that should not be taken as
2653 * meaning "it's down".
2661 * - create a PGconn data structure with (as yet) no interesting data
2664 makeEmptyPGconn(void)
2670 * Make sure socket support is up and running.
2674 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
2679 conn = (PGconn *) malloc(sizeof(PGconn));
2688 /* Zero all pointers and booleans */
2689 MemSet(conn, 0, sizeof(PGconn));
2691 /* install default notice hooks */
2692 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2693 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2695 conn->status = CONNECTION_BAD;
2696 conn->asyncStatus = PGASYNC_IDLE;
2697 conn->xactStatus = PQTRANS_IDLE;
2698 conn->options_valid = false;
2699 conn->nonblocking = false;
2700 conn->setenv_state = SETENV_STATE_IDLE;
2701 conn->client_encoding = PG_SQL_ASCII;
2702 conn->std_strings = false; /* unless server says differently */
2703 conn->verbosity = PQERRORS_DEFAULT;
2704 conn->sock = PGINVALID_SOCKET;
2705 conn->auth_req_received = false;
2706 conn->password_needed = false;
2707 conn->dot_pgpass_used = false;
2709 conn->allow_ssl_try = true;
2710 conn->wait_ssl_try = false;
2714 * We try to send at least 8K at a time, which is the usual size of pipe
2715 * buffers on Unix systems. That way, when we are sending a large amount
2716 * of data, we avoid incurring extra kernel context swaps for partial
2717 * bufferloads. The output buffer is initially made 16K in size, and we
2718 * try to dump it after accumulating 8K.
2720 * With the same goal of minimizing context swaps, the input buffer will
2721 * be enlarged anytime it has less than 8K free, so we initially allocate
2724 conn->inBufSize = 16 * 1024;
2725 conn->inBuffer = (char *) malloc(conn->inBufSize);
2726 conn->outBufSize = 16 * 1024;
2727 conn->outBuffer = (char *) malloc(conn->outBufSize);
2728 conn->rowBufLen = 32;
2729 conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
2730 initPQExpBuffer(&conn->errorMessage);
2731 initPQExpBuffer(&conn->workBuffer);
2733 if (conn->inBuffer == NULL ||
2734 conn->outBuffer == NULL ||
2735 conn->rowBuf == NULL ||
2736 PQExpBufferBroken(&conn->errorMessage) ||
2737 PQExpBufferBroken(&conn->workBuffer))
2739 /* out of memory already :-( */
2749 * - free an idle (closed) PGconn data structure
2751 * NOTE: this should not overlap any functionality with closePGconn().
2752 * Clearing/resetting of transient state belongs there; what we do here is
2753 * release data that is to be held for the life of the PGconn structure.
2754 * If a value ought to be cleared/freed during PQreset(), do it there not here.
2757 freePGconn(PGconn *conn)
2761 /* let any event procs clean up their state data */
2762 for (i = 0; i < conn->nEvents; i++)
2764 PGEventConnDestroy evt;
2767 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2768 conn->events[i].passThrough);
2769 free(conn->events[i].name);
2772 if (conn->client_encoding_initial)
2773 free(conn->client_encoding_initial);
2778 if (conn->pghostaddr)
2779 free(conn->pghostaddr);
2782 if (conn->pgunixsocket)
2783 free(conn->pgunixsocket);
2786 if (conn->connect_timeout)
2787 free(conn->connect_timeout);
2788 if (conn->pgoptions)
2789 free(conn->pgoptions);
2791 free(conn->appname);
2792 if (conn->fbappname)
2793 free(conn->fbappname);
2796 if (conn->replication)
2797 free(conn->replication);
2802 if (conn->keepalives)
2803 free(conn->keepalives);
2804 if (conn->keepalives_idle)
2805 free(conn->keepalives_idle);
2806 if (conn->keepalives_interval)
2807 free(conn->keepalives_interval);
2808 if (conn->keepalives_count)
2809 free(conn->keepalives_count);
2811 free(conn->sslmode);
2813 free(conn->sslcert);
2816 if (conn->sslrootcert)
2817 free(conn->sslrootcert);
2820 if (conn->sslcompression)
2821 free(conn->sslcompression);
2822 if (conn->requirepeer)
2823 free(conn->requirepeer);
2824 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2825 if (conn->krbsrvname)
2826 free(conn->krbsrvname);
2828 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2832 /* Note that conn->Pfdebug is not ours to close or free */
2833 if (conn->last_query)
2834 free(conn->last_query);
2836 free(conn->inBuffer);
2837 if (conn->outBuffer)
2838 free(conn->outBuffer);
2841 termPQExpBuffer(&conn->errorMessage);
2842 termPQExpBuffer(&conn->workBuffer);
2853 * - properly close a connection to the backend
2855 * This should reset or release all transient state, but NOT the connection
2856 * parameters. On exit, the PGconn should be in condition to start a fresh
2857 * connection with the same parameters (see PQreset()).
2860 closePGconn(PGconn *conn)
2863 pgParameterStatus *pstatus;
2866 * Note that the protocol doesn't allow us to send Terminate messages
2867 * during the startup phase.
2869 if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
2872 * Try to send "close connection" message to backend. Ignore any
2875 pqPutMsgStart('X', false, conn);
2877 (void) pqFlush(conn);
2881 * Must reset the blocking status so a possible reconnect will work.
2883 * Don't call PQsetnonblocking() because it will fail if it's unable to
2884 * flush the connection.
2886 conn->nonblocking = FALSE;
2889 * Close the connection, reset all transient state, flush I/O buffers.
2891 pqDropConnection(conn);
2892 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2894 conn->asyncStatus = PGASYNC_IDLE;
2895 pqClearAsyncResult(conn); /* deallocate result */
2896 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2897 conn->addrlist = NULL;
2898 conn->addr_cur = NULL;
2899 notify = conn->notifyHead;
2900 while (notify != NULL)
2902 PGnotify *prev = notify;
2904 notify = notify->next;
2907 conn->notifyHead = conn->notifyTail = NULL;
2908 pstatus = conn->pstatus;
2909 while (pstatus != NULL)
2911 pgParameterStatus *prev = pstatus;
2913 pstatus = pstatus->next;
2916 conn->pstatus = NULL;
2917 if (conn->lobjfuncs)
2918 free(conn->lobjfuncs);
2919 conn->lobjfuncs = NULL;
2925 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2926 if (conn->gtarg_nam)
2927 gss_release_name(&min_s, &conn->gtarg_nam);
2928 if (conn->ginbuf.length)
2929 gss_release_buffer(&min_s, &conn->ginbuf);
2930 if (conn->goutbuf.length)
2931 gss_release_buffer(&min_s, &conn->goutbuf);
2935 if (conn->ginbuf.length)
2936 free(conn->ginbuf.value);
2937 conn->ginbuf.length = 0;
2938 conn->ginbuf.value = NULL;
2939 if (conn->sspitarget)
2940 free(conn->sspitarget);
2941 conn->sspitarget = NULL;
2944 FreeCredentialsHandle(conn->sspicred);
2945 free(conn->sspicred);
2946 conn->sspicred = NULL;
2950 DeleteSecurityContext(conn->sspictx);
2951 free(conn->sspictx);
2952 conn->sspictx = NULL;
2958 * PQfinish: properly close a connection to the backend. Also frees
2959 * the PGconn data structure so it shouldn't be re-used after this.
2962 PQfinish(PGconn *conn)
2972 * PQreset: resets the connection to the backend by closing the
2973 * existing connection and creating a new one.
2976 PQreset(PGconn *conn)
2982 if (connectDBStart(conn) && connectDBComplete(conn))
2985 * Notify event procs of successful reset. We treat an event proc
2986 * failure as disabling the connection ... good idea?
2990 for (i = 0; i < conn->nEvents; i++)
2992 PGEventConnReset evt;
2995 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2996 conn->events[i].passThrough))
2998 conn->status = CONNECTION_BAD;
2999 printfPQExpBuffer(&conn->errorMessage,
3000 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3001 conn->events[i].name);
3012 * resets the connection to the backend
3013 * closes the existing connection and makes a new one
3014 * Returns 1 on success, 0 on failure.
3017 PQresetStart(PGconn *conn)
3023 return connectDBStart(conn);
3032 * resets the connection to the backend
3033 * closes the existing connection and makes a new one
3035 PostgresPollingStatusType
3036 PQresetPoll(PGconn *conn)
3040 PostgresPollingStatusType status = PQconnectPoll(conn);
3042 if (status == PGRES_POLLING_OK)
3045 * Notify event procs of successful reset. We treat an event proc
3046 * failure as disabling the connection ... good idea?
3050 for (i = 0; i < conn->nEvents; i++)
3052 PGEventConnReset evt;
3055 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3056 conn->events[i].passThrough))
3058 conn->status = CONNECTION_BAD;
3059 printfPQExpBuffer(&conn->errorMessage,
3060 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3061 conn->events[i].name);
3062 return PGRES_POLLING_FAILED;
3070 return PGRES_POLLING_FAILED;
3074 * PQcancelGet: get a PGcancel structure corresponding to a connection.
3076 * A copy is needed to be able to cancel a running query from a different
3077 * thread. If the same structure is used all structure members would have
3078 * to be individually locked (if the entire structure was locked, it would
3079 * be impossible to cancel a synchronous query because the structure would
3080 * have to stay locked for the duration of the query).
3083 PQgetCancel(PGconn *conn)
3090 if (conn->sock == PGINVALID_SOCKET)
3093 cancel = malloc(sizeof(PGcancel));
3097 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
3098 cancel->be_pid = conn->be_pid;
3099 cancel->be_key = conn->be_key;
3104 /* PQfreeCancel: free a cancel structure */
3106 PQfreeCancel(PGcancel *cancel)
3114 * PQcancel and PQrequestCancel: attempt to request cancellation of the
3115 * current operation.
3117 * The return value is TRUE if the cancel request was successfully
3118 * dispatched, FALSE if not (in which case an error message is available).
3119 * Note: successful dispatch is no guarantee that there will be any effect at
3120 * the backend. The application must read the operation result as usual.
3122 * CAUTION: we want this routine to be safely callable from a signal handler
3123 * (for example, an application might want to call it in a SIGINT handler).
3124 * This means we cannot use any C library routine that might be non-reentrant.
3125 * malloc/free are often non-reentrant, and anything that might call them is
3126 * just as dangerous. We avoid sprintf here for that reason. Building up
3127 * error messages with strcpy/strcat is tedious but should be quite safe.
3128 * We also save/restore errno in case the signal handler support doesn't.
3130 * internal_cancel() is an internal helper function to make code-sharing
3131 * between the two versions of the cancel function possible.
3134 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
3135 char *errbuf, int errbufsize)
3137 int save_errno = SOCK_ERRNO;
3138 pgsocket tmpsock = PGINVALID_SOCKET;
3144 CancelRequestPacket cp;
3148 * We need to open a temporary connection to the postmaster. Do this with
3149 * only kernel calls.
3151 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
3153 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
3154 goto cancel_errReturn;
3157 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
3160 if (SOCK_ERRNO == EINTR)
3161 /* Interrupted system call - we'll just try again */
3163 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
3164 goto cancel_errReturn;
3168 * We needn't set nonblocking I/O or NODELAY options here.
3171 /* Create and send the cancel request packet. */
3173 crp.packetlen = htonl((uint32) sizeof(crp));
3174 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
3175 crp.cp.backendPID = htonl(be_pid);
3176 crp.cp.cancelAuthCode = htonl(be_key);
3179 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
3181 if (SOCK_ERRNO == EINTR)
3182 /* Interrupted system call - we'll just try again */
3184 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
3185 goto cancel_errReturn;
3189 * Wait for the postmaster to close the connection, which indicates that
3190 * it's processed the request. Without this delay, we might issue another
3191 * command only to find that our cancel zaps that command instead of the
3192 * one we thought we were canceling. Note we don't actually expect this
3193 * read to obtain any data, we are just waiting for EOF to be signaled.
3196 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
3198 if (SOCK_ERRNO == EINTR)
3199 /* Interrupted system call - we'll just try again */
3201 /* we ignore other error conditions */
3205 closesocket(tmpsock);
3206 SOCK_ERRNO_SET(save_errno);
3212 * Make sure we don't overflow the error buffer. Leave space for the \n at
3213 * the end, and for the terminating zero.
3215 maxlen = errbufsize - strlen(errbuf) - 2;
3218 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
3220 strcat(errbuf, "\n");
3222 if (tmpsock != PGINVALID_SOCKET)
3223 closesocket(tmpsock);
3224 SOCK_ERRNO_SET(save_errno);
3229 * PQcancel: request query cancel
3231 * Returns TRUE if able to send the cancel request, FALSE if not.
3233 * On failure, an error message is stored in *errbuf, which must be of size
3234 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
3238 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
3242 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3246 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3247 errbuf, errbufsize);
3251 * PQrequestCancel: old, not thread-safe function for requesting query cancel
3253 * Returns TRUE if able to send the cancel request, FALSE if not.
3255 * On failure, the error message is saved in conn->errorMessage; this means
3256 * that this can't be used when there might be other active operations on
3257 * the connection object.
3259 * NOTE: error messages will be cut off at the current size of the
3260 * error message buffer, since we dare not try to expand conn->errorMessage!
3263 PQrequestCancel(PGconn *conn)
3267 /* Check we have an open connection */
3271 if (conn->sock == PGINVALID_SOCKET)
3273 strlcpy(conn->errorMessage.data,
3274 "PQrequestCancel() -- connection is not open\n",
3275 conn->errorMessage.maxlen);
3276 conn->errorMessage.len = strlen(conn->errorMessage.data);
3281 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
3282 conn->errorMessage.data, conn->errorMessage.maxlen);
3285 conn->errorMessage.len = strlen(conn->errorMessage.data);
3292 * pqPacketSend() -- convenience routine to send a message to server.
3294 * pack_type: the single-byte message type code. (Pass zero for startup
3295 * packets, which have no message type code.)
3297 * buf, buf_len: contents of message. The given length includes only what
3298 * is in buf; the message type and message length fields are added here.
3300 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
3301 * SIDE_EFFECTS: may block.
3303 * Note: all messages sent with this routine have a length word, whether
3304 * it's protocol 2.0 or 3.0.
3307 pqPacketSend(PGconn *conn, char pack_type,
3308 const void *buf, size_t buf_len)
3310 /* Start the message. */
3311 if (pqPutMsgStart(pack_type, true, conn))
3312 return STATUS_ERROR;
3314 /* Send the message body. */
3315 if (pqPutnchar(buf, buf_len, conn))
3316 return STATUS_ERROR;
3318 /* Finish the message. */
3319 if (pqPutMsgEnd(conn))
3320 return STATUS_ERROR;
3322 /* Flush to ensure backend gets it. */
3324 return STATUS_ERROR;
3331 #define LDAP_URL "ldap://"
3332 #define LDAP_DEF_PORT 389
3333 #define PGLDAP_TIMEOUT 2
3335 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
3336 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
3342 * Search the LDAP URL passed as first argument, treat the result as a
3343 * string of connection options that are parsed and added to the array of
3344 * options passed as second argument.
3346 * LDAP URLs must conform to RFC 1959 without escape sequences.
3347 * ldap://host:port/dn?attributes?scope?filter?extensions
3350 * 0 if the lookup was successful,
3351 * 1 if the connection to the LDAP server could be established but
3352 * the search was unsuccessful,
3353 * 2 if a connection could not be established, and
3354 * 3 if a fatal error occurred.
3356 * An error message is returned in the third argument for return codes 1 and 3.
3359 ldapServiceLookup(const char *purl, PQconninfoOption *options,
3360 PQExpBuffer errorMessage)
3362 int port = LDAP_DEF_PORT,
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 * Perform an explicit anonymous bind.
3517 * LDAP does not require that an anonymous bind is performed explicitly,
3518 * but we want to distinguish between the case where LDAP bind does not
3519 * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing
3520 * the service control file) and the case where querying the LDAP server
3521 * fails (return 1 to end parsing).
3523 * Unfortunately there is no way of setting a timeout that works for
3524 * both Windows and OpenLDAP.
3527 /* the nonstandard ldap_connect function performs an anonymous bind */
3528 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
3530 /* error or timeout in ldap_connect */
3536 /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
3537 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
3544 /* anonymous bind */
3545 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3547 /* error or network timeout */
3553 /* wait some time for the connection to succeed */
3555 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3558 /* error or timeout */
3569 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
3579 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3584 printfPQExpBuffer(errorMessage,
3585 libpq_gettext("lookup on LDAP server failed: %s\n"),
3586 ldap_err2string(rc));
3592 /* complain if there was not exactly one result */
3593 if ((rc = ldap_count_entries(ld, res)) != 1)
3595 printfPQExpBuffer(errorMessage,
3596 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3597 : libpq_gettext("no entry found on LDAP lookup\n"));
3605 if ((entry = ldap_first_entry(ld, res)) == NULL)
3607 /* should never happen */
3608 printfPQExpBuffer(errorMessage,
3609 libpq_gettext("no entry found on LDAP lookup\n"));
3617 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3619 printfPQExpBuffer(errorMessage,
3620 libpq_gettext("attribute has no values on LDAP lookup\n"));
3630 if (values[0] == NULL)
3632 printfPQExpBuffer(errorMessage,
3633 libpq_gettext("attribute has no values on LDAP lookup\n"));
3634 ldap_value_free_len(values);
3639 /* concatenate values into a single string with newline terminators */
3640 size = 1; /* for the trailing null */
3641 for (i = 0; values[i] != NULL; i++)
3642 size += values[i]->bv_len + 1;
3643 if ((result = malloc(size)) == NULL)
3645 printfPQExpBuffer(errorMessage,
3646 libpq_gettext("out of memory\n"));
3647 ldap_value_free_len(values);
3652 for (i = 0; values[i] != NULL; i++)
3654 memcpy(p, values[i]->bv_val, values[i]->bv_len);
3655 p += values[i]->bv_len;
3660 ldap_value_free_len(values);
3663 /* parse result string */
3664 oldstate = state = 0;
3665 for (p = result; *p != '\0'; ++p)
3669 case 0: /* between entries */
3670 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3676 case 1: /* in option name */
3677 if (ld_is_sp_tab(*p))
3682 else if (ld_is_nl_cr(*p))
3684 printfPQExpBuffer(errorMessage, libpq_gettext(
3685 "missing \"=\" after \"%s\" in connection info string\n"),
3696 case 2: /* after option name */
3701 else if (!ld_is_sp_tab(*p))
3703 printfPQExpBuffer(errorMessage, libpq_gettext(
3704 "missing \"=\" after \"%s\" in connection info string\n"),
3710 case 3: /* before option value */
3717 else if (ld_is_nl_cr(*p))
3719 optval = optname + strlen(optname); /* empty */
3722 else if (!ld_is_sp_tab(*p))
3728 case 4: /* in unquoted option value */
3729 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3735 case 5: /* in quoted option value */
3741 else if (*p == '\\')
3746 case 6: /* in quoted option value after escape */
3752 if (state == 0 && oldstate != 0)
3754 found_keyword = false;
3755 for (i = 0; options[i].keyword; i++)
3757 if (strcmp(options[i].keyword, optname) == 0)
3759 if (options[i].val == NULL)
3760 options[i].val = strdup(optval);
3761 found_keyword = true;
3767 printfPQExpBuffer(errorMessage,
3768 libpq_gettext("invalid connection option \"%s\"\n"),
3781 if (state == 5 || state == 6)
3783 printfPQExpBuffer(errorMessage, libpq_gettext(
3784 "unterminated quoted string in connection info string\n"));
3791 #endif /* USE_LDAP */
3793 #define MAXBUFSIZE 256
3796 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3798 const char *service = conninfo_getval(options, "service");
3799 char serviceFile[MAXPGPATH];
3801 bool group_found = false;
3803 struct stat stat_buf;
3806 * We have to special-case the environment variable PGSERVICE here, since
3807 * this is and should be called before inserting environment defaults for
3808 * other connection options.
3810 if (service == NULL)
3811 service = getenv("PGSERVICE");
3813 if (service == NULL)
3816 if ((env = getenv("PGSERVICEFILE")) != NULL)
3817 strlcpy(serviceFile, env, sizeof(serviceFile));
3820 char homedir[MAXPGPATH];
3822 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3824 printfPQExpBuffer(errorMessage, libpq_gettext("could not get home directory to locate service definition file"));
3827 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
3829 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3833 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3834 if (group_found || status != 0)
3840 * This could be used by any application so we can't use the binary
3841 * location to find our config files.
3843 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3844 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3846 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3849 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3856 printfPQExpBuffer(errorMessage,
3857 libpq_gettext("definition of service \"%s\" not found\n"), service);
3865 parseServiceFile(const char *serviceFile,
3866 const char *service,
3867 PQconninfoOption *options,
3868 PQExpBuffer errorMessage,
3874 char buf[MAXBUFSIZE],
3877 f = fopen(serviceFile, "r");
3880 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3885 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3889 if (strlen(line) >= sizeof(buf) - 1)
3892 printfPQExpBuffer(errorMessage,
3893 libpq_gettext("line %d too long in service file \"%s\"\n"),
3899 /* ignore EOL at end of line */
3900 if (strlen(line) && line[strlen(line) - 1] == '\n')
3901 line[strlen(line) - 1] = 0;
3903 /* ignore leading blanks */
3904 while (*line && isspace((unsigned char) line[0]))
3907 /* ignore comments and empty lines */
3908 if (strlen(line) == 0 || line[0] == '#')
3911 /* Check for right groupname */
3916 /* group info already read */
3921 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3922 line[strlen(service) + 1] == ']')
3923 *group_found = true;
3925 *group_found = false;
3932 * Finally, we are in the right group and can parse the line
3939 if (strncmp(line, "ldap", 4) == 0)
3941 int rc = ldapServiceLookup(line, options, errorMessage);
3943 /* if rc = 2, go on reading for fallback */
3960 val = strchr(line, '=');
3963 printfPQExpBuffer(errorMessage,
3964 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3973 * Set the parameter --- but don't override any previous
3976 found_keyword = false;
3977 for (i = 0; options[i].keyword; i++)
3979 if (strcmp(options[i].keyword, key) == 0)
3981 if (options[i].val == NULL)
3982 options[i].val = strdup(val);
3983 found_keyword = true;
3990 printfPQExpBuffer(errorMessage,
3991 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
4010 * Parse a string like PQconnectdb() would do and return the
4011 * resulting connection options array. NULL is returned on failure.
4012 * The result contains only options specified directly in the string,
4013 * not any possible default values.
4015 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
4016 * string on failure (use PQfreemem to free it). In out-of-memory conditions
4017 * both *errmsg and the result could be NULL.
4019 * NOTE: the returned array is dynamically allocated and should
4020 * be freed when no longer needed via PQconninfoFree().
4023 PQconninfoParse(const char *conninfo, char **errmsg)
4025 PQExpBufferData errorBuf;
4026 PQconninfoOption *connOptions;
4029 *errmsg = NULL; /* default */
4030 initPQExpBuffer(&errorBuf);
4031 if (PQExpBufferDataBroken(errorBuf))
4032 return NULL; /* out of memory already :-( */
4033 connOptions = parse_connection_string(conninfo, &errorBuf, false);
4034 if (connOptions == NULL && errmsg)
4035 *errmsg = errorBuf.data;
4037 termPQExpBuffer(&errorBuf);
4042 * Build a working copy of the constant PQconninfoOptions array.
4044 static PQconninfoOption *
4045 conninfo_init(PQExpBuffer errorMessage)
4047 PQconninfoOption *options;
4048 PQconninfoOption *opt_dest;
4049 const internalPQconninfoOption *cur_opt;
4052 * Get enough memory for all options in PQconninfoOptions, even if some
4053 * end up being filtered out.
4055 options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4056 if (options == NULL)
4058 printfPQExpBuffer(errorMessage,
4059 libpq_gettext("out of memory\n"));
4064 for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4066 /* Only copy the public part of the struct, not the full internal */
4067 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4070 MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4076 * Connection string parser
4078 * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4079 * Otherwise, NULL is returned and an error message is left in errorMessage.
4081 * If use_defaults is TRUE, default values are filled in (from a service file,
4082 * environment variables, etc).
4084 static PQconninfoOption *
4085 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4088 /* Parse as URI if connection string matches URI prefix */
4089 if (uri_prefix_length(connstr) != 0)
4090 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4092 /* Parse as default otherwise */
4093 return conninfo_parse(connstr, errorMessage, use_defaults);
4097 * Checks if connection string starts with either of the valid URI prefix
4100 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4103 uri_prefix_length(const char *connstr)
4105 if (strncmp(connstr, uri_designator,
4106 sizeof(uri_designator) - 1) == 0)
4107 return sizeof(uri_designator) - 1;
4109 if (strncmp(connstr, short_uri_designator,
4110 sizeof(short_uri_designator) - 1) == 0)
4111 return sizeof(short_uri_designator) - 1;
4117 * Recognized connection string either starts with a valid URI prefix or
4118 * contains a "=" in it.
4120 * Must be consistent with parse_connection_string: anything for which this
4121 * returns true should at least look like it's parseable by that routine.
4124 recognized_connection_string(const char *connstr)
4126 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4130 * Subroutine for parse_connection_string
4132 * Deal with a string containing key=value pairs.
4134 static PQconninfoOption *
4135 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
4143 PQconninfoOption *options;
4145 /* Make a working copy of PQconninfoOptions */
4146 options = conninfo_init(errorMessage);
4147 if (options == NULL)
4150 /* Need a modifiable copy of the input string */
4151 if ((buf = strdup(conninfo)) == NULL)
4153 printfPQExpBuffer(errorMessage,
4154 libpq_gettext("out of memory\n"));
4155 PQconninfoFree(options);
4162 /* Skip blanks before the parameter name */
4163 if (isspace((unsigned char) *cp))
4169 /* Get the parameter name */
4175 if (isspace((unsigned char) *cp))
4180 if (!isspace((unsigned char) *cp))
4189 /* Check that there is a following '=' */
4192 printfPQExpBuffer(errorMessage,
4193 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4195 PQconninfoFree(options);
4201 /* Skip blanks after the '=' */
4204 if (!isspace((unsigned char) *cp))
4209 /* Get the parameter value */
4217 if (isspace((unsigned char) *cp))
4241 printfPQExpBuffer(errorMessage,
4242 libpq_gettext("unterminated quoted string in connection info string\n"));
4243 PQconninfoFree(options);
4265 * Now that we have the name and the value, store the record.
4267 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
4269 PQconninfoFree(options);
4275 /* Done with the modifiable input string */
4279 * Add in defaults if the caller wants that.
4283 if (!conninfo_add_defaults(options, errorMessage))
4285 PQconninfoFree(options);
4294 * Conninfo array parser routine
4296 * If successful, a malloc'd PQconninfoOption array is returned.
4297 * If not successful, NULL is returned and an error message is
4298 * left in errorMessage.
4299 * Defaults are supplied (from a service file, environment variables, etc)
4300 * for unspecified options, but only if use_defaults is TRUE.
4302 * If expand_dbname is non-zero, and the value passed for keyword "dbname" is a
4303 * connection string (as indicated by recognized_connection_string) then parse
4304 * and process it, overriding any previously processed conflicting
4305 * keywords. Subsequent keywords will take precedence, however.
4307 static PQconninfoOption *
4308 conninfo_array_parse(const char *const * keywords, const char *const * values,
4309 PQExpBuffer errorMessage, bool use_defaults,
4312 PQconninfoOption *options;
4313 PQconninfoOption *dbname_options = NULL;
4314 PQconninfoOption *option;
4318 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
4319 * actually a recognized connection string.
4321 while (expand_dbname && keywords[i])
4323 const char *pname = keywords[i];
4324 const char *pvalue = values[i];
4326 /* first find "dbname" if any */
4327 if (strcmp(pname, "dbname") == 0 && pvalue)
4330 * If value is a connection string, parse it, but do not use
4331 * defaults here -- those get picked up later. We only want to
4332 * override for those parameters actually passed.
4334 if (recognized_connection_string(pvalue))
4336 dbname_options = parse_connection_string(pvalue, errorMessage, false);
4337 if (dbname_options == NULL)
4345 /* Make a working copy of PQconninfoOptions */
4346 options = conninfo_init(errorMessage);
4347 if (options == NULL)
4349 PQconninfoFree(dbname_options);
4353 /* Parse the keywords/values arrays */
4357 const char *pname = keywords[i];
4358 const char *pvalue = values[i];
4360 if (pvalue != NULL && pvalue[0] != '\0')
4362 /* Search for the param record */
4363 for (option = options; option->keyword != NULL; option++)
4365 if (strcmp(option->keyword, pname) == 0)
4369 /* Check for invalid connection option */
4370 if (option->keyword == NULL)
4372 printfPQExpBuffer(errorMessage,
4373 libpq_gettext("invalid connection option \"%s\"\n"),
4375 PQconninfoFree(options);
4376 PQconninfoFree(dbname_options);
4381 * If we are on the dbname parameter, and we have a parsed
4382 * connection string, copy those parameters across, overriding any
4383 * existing previous settings.
4385 if (strcmp(pname, "dbname") == 0 && dbname_options)
4387 PQconninfoOption *str_option;
4389 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
4391 if (str_option->val != NULL)
4395 for (k = 0; options[k].keyword; k++)
4397 if (strcmp(options[k].keyword, str_option->keyword) == 0)
4400 free(options[k].val);
4401 options[k].val = strdup(str_option->val);
4411 * Store the value, overriding previous settings
4415 option->val = strdup(pvalue);
4418 printfPQExpBuffer(errorMessage,
4419 libpq_gettext("out of memory\n"));
4420 PQconninfoFree(options);
4421 PQconninfoFree(dbname_options);
4428 PQconninfoFree(dbname_options);
4431 * Add in defaults if the caller wants that.
4435 if (!conninfo_add_defaults(options, errorMessage))
4437 PQconninfoFree(options);
4446 * Add the default values for any unspecified options to the connection
4449 * Defaults are obtained from a service file, environment variables, etc.
4451 * Returns TRUE if successful, otherwise FALSE; errorMessage, if supplied,
4452 * is filled in upon failure. Note that failure to locate a default value
4453 * is not an error condition here --- we just leave the option's value as
4457 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
4459 PQconninfoOption *option;
4463 * If there's a service spec, use it to obtain any not-explicitly-given
4464 * parameters. Ignore error if no error message buffer is passed
4465 * because there is no way to pass back the failure message.
4467 if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
4471 * Get the fallback resources for parameters not specified in the conninfo
4472 * string nor the service.
4474 for (option = options; option->keyword != NULL; option++)
4476 if (option->val != NULL)
4477 continue; /* Value was in conninfo or service */
4480 * Try to get the environment variable fallback
4482 if (option->envvar != NULL)
4484 if ((tmp = getenv(option->envvar)) != NULL)
4486 option->val = strdup(tmp);
4490 printfPQExpBuffer(errorMessage,
4491 libpq_gettext("out of memory\n"));
4499 * No environment variable specified or the variable isn't set - try
4500 * compiled-in default
4502 if (option->compiled != NULL)
4504 option->val = strdup(option->compiled);
4508 printfPQExpBuffer(errorMessage,
4509 libpq_gettext("out of memory\n"));
4516 * Special handling for "user" option
4518 if (strcmp(option->keyword, "user") == 0)
4520 option->val = pg_fe_getauthname();
4524 printfPQExpBuffer(errorMessage,
4525 libpq_gettext("out of memory\n"));
4536 * Subroutine for parse_connection_string
4538 * Deal with a URI connection string.
4540 static PQconninfoOption *
4541 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
4544 PQconninfoOption *options;
4546 /* Make a working copy of PQconninfoOptions */
4547 options = conninfo_init(errorMessage);
4548 if (options == NULL)
4551 if (!conninfo_uri_parse_options(options, uri, errorMessage))
4553 PQconninfoFree(options);
4558 * Add in defaults if the caller wants that.
4562 if (!conninfo_add_defaults(options, errorMessage))
4564 PQconninfoFree(options);
4573 * conninfo_uri_parse_options
4574 * Actual URI parser.
4576 * If successful, returns true while the options array is filled with parsed
4577 * options from the URI.
4578 * If not successful, returns false and fills errorMessage accordingly.
4580 * Parses the connection URI string in 'uri' according to the URI syntax (RFC
4583 * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
4585 * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
4586 * by literal square brackets.
4588 * Any of the URI parts might use percent-encoding (%xy).
4591 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
4592 PQExpBuffer errorMessage)
4596 char *buf = strdup(uri); /* need a modifiable copy of the input
4599 char prevchar = '\0';
4602 bool retval = false;
4606 printfPQExpBuffer(errorMessage,
4607 libpq_gettext("out of memory\n"));
4611 /* Skip the URI prefix */
4612 prefix_len = uri_prefix_length(uri);
4613 if (prefix_len == 0)
4615 /* Should never happen */
4616 printfPQExpBuffer(errorMessage,
4617 libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
4621 start += prefix_len;
4624 /* Look ahead for possible user credentials designator */
4625 while (*p && *p != '@' && *p != '/')
4630 * Found username/password designator, so URI should be of the form
4631 * "scheme://user[:password]@[netloc]".
4636 while (*p != ':' && *p != '@')
4639 /* Save last char and cut off at end of user name */
4644 !conninfo_storeval(options, "user", user,
4645 errorMessage, false, true))
4648 if (prevchar == ':')
4650 const char *password = p + 1;
4657 !conninfo_storeval(options, "password", password,
4658 errorMessage, false, true))
4662 /* Advance past end of parsed user name or password token */
4668 * No username/password designator found. Reset to start of URI.
4674 * "p" has been incremented past optional URI credential information at
4675 * this point and now points at the "netloc" part of the URI.
4677 * Look for IPv6 address.
4682 while (*p && *p != ']')
4686 printfPQExpBuffer(errorMessage,
4687 libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
4693 printfPQExpBuffer(errorMessage,
4694 libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
4699 /* Cut off the bracket and advance */
4703 * The address may be followed by a port specifier or a slash or a
4706 if (*p && *p != ':' && *p != '/' && *p != '?')
4708 printfPQExpBuffer(errorMessage,
4709 libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
4710 *p, (int) (p - buf + 1), uri);
4716 /* not an IPv6 address: DNS-named or IPv4 netloc */
4720 * Look for port specifier (colon) or end of host specifier (slash),
4721 * or query (question mark).
4723 while (*p && *p != ':' && *p != '/' && *p != '?')
4727 /* Save the hostname terminator before we null it */
4732 !conninfo_storeval(options, "host", host,
4733 errorMessage, false, true))
4737 if (prevchar == ':')
4739 const char *port = ++p; /* advance past host terminator */
4741 while (*p && *p != '/' && *p != '?')
4748 !conninfo_storeval(options, "port", port,
4749 errorMessage, false, true))
4753 if (prevchar && prevchar != '?')
4755 const char *dbname = ++p; /* advance past host terminator */
4757 /* Look for query parameters */
4758 while (*p && *p != '?')
4765 * Avoid setting dbname to an empty string, as it forces the default
4766 * value (username) and ignores $PGDATABASE, as opposed to not setting
4770 !conninfo_storeval(options, "dbname", dbname,
4771 errorMessage, false, true))
4777 ++p; /* advance past terminator */
4779 if (!conninfo_uri_parse_params(p, options, errorMessage))
4783 /* everything parsed okay */
4792 * Connection URI parameters parser routine
4794 * If successful, returns true while connOptions is filled with parsed
4795 * parameters. Otherwise, returns false and fills errorMessage appropriately.
4797 * Destructively modifies 'params' buffer.
4800 conninfo_uri_parse_params(char *params,
4801 PQconninfoOption *connOptions,
4802 PQExpBuffer errorMessage)
4806 char *keyword = params;
4809 bool malloced = false;
4812 * Scan the params string for '=' and '&', marking the end of keyword
4813 * and value respectively.
4819 /* Was there '=' already? */
4822 printfPQExpBuffer(errorMessage,
4823 libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4827 /* Cut off keyword, advance to value */
4831 else if (*p == '&' || *p == '\0')
4835 /* Cut off value, remember old value */
4839 /* Was there '=' at all? */
4842 printfPQExpBuffer(errorMessage,
4843 libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4849 * If not at the end, advance; now pointing to start of the
4850 * next parameter, if any.
4852 if (prevchar != '\0')
4857 /* Advance, NUL is checked in the 'if' above */
4861 keyword = conninfo_uri_decode(keyword, errorMessage);
4862 if (keyword == NULL)
4864 /* conninfo_uri_decode already set an error message */
4867 value = conninfo_uri_decode(value, errorMessage);
4870 /* conninfo_uri_decode already set an error message */
4877 * Special keyword handling for improved JDBC compatibility.
4879 if (strcmp(keyword, "ssl") == 0 &&
4880 strcmp(value, "true") == 0)
4886 keyword = "sslmode";
4891 * Store the value if the corresponding option exists; ignore
4892 * otherwise. At this point both keyword and value are not
4895 if (!conninfo_storeval(connOptions, keyword, value,
4896 errorMessage, true, false))
4899 * Check if there was a hard error when decoding or storing the
4902 if (errorMessage->len != 0)
4912 printfPQExpBuffer(errorMessage,
4914 "invalid URI query parameter: \"%s\"\n"),
4929 /* Proceed to next key=value pair */
4937 * Connection URI decoder routine
4939 * If successful, returns the malloc'd decoded string.
4940 * If not successful, returns NULL and fills errorMessage accordingly.
4942 * The string is decoded by replacing any percent-encoded tokens with
4943 * corresponding characters, while preserving any non-encoded characters. A
4944 * percent-encoded token is a character triplet: a percent sign, followed by a
4945 * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
4946 * treated identically.
4949 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
4951 char *buf = malloc(strlen(str) + 1);
4953 const char *q = str;
4957 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4965 /* copy and check for NUL terminator */
4966 if (!(*(p++) = *(q++)))
4975 ++q; /* skip the percent sign itself */
4978 * Possible EOL will be caught by the first call to
4979 * get_hexdigit(), so we never dereference an invalid q pointer.
4981 if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
4983 printfPQExpBuffer(errorMessage,
4984 libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
4993 printfPQExpBuffer(errorMessage,
4994 libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
5007 * Convert hexadecimal digit character to its integer value.
5009 * If successful, returns true and value is filled with digit's base 16 value.
5010 * If not successful, returns false.
5012 * Lower- and upper-case letters in the range A-F are treated identically.
5015 get_hexdigit(char digit, int *value)
5017 if ('0' <= digit && digit <= '9')
5018 *value = digit - '0';
5019 else if ('A' <= digit && digit <= 'F')
5020 *value = digit - 'A' + 10;
5021 else if ('a' <= digit && digit <= 'f')
5022 *value = digit - 'a' + 10;
5030 * Find an option value corresponding to the keyword in the connOptions array.
5032 * If successful, returns a pointer to the corresponding option's value.
5033 * If not successful, returns NULL.
5036 conninfo_getval(PQconninfoOption *connOptions,
5037 const char *keyword)
5039 PQconninfoOption *option;
5041 option = conninfo_find(connOptions, keyword);
5043 return option ? option->val : NULL;
5047 * Store a (new) value for an option corresponding to the keyword in
5048 * connOptions array.
5050 * If uri_decode is true, the value is URI-decoded. The keyword is always
5051 * assumed to be non URI-encoded.
5053 * If successful, returns a pointer to the corresponding PQconninfoOption,
5054 * which value is replaced with a strdup'd copy of the passed value string.
5055 * The existing value for the option is free'd before replacing, if any.
5057 * If not successful, returns NULL and fills errorMessage accordingly.
5058 * However, if the reason of failure is an invalid keyword being passed and
5059 * ignoreMissing is TRUE, errorMessage will be left untouched.
5061 static PQconninfoOption *
5062 conninfo_storeval(PQconninfoOption *connOptions,
5063 const char *keyword, const char *value,
5064 PQExpBuffer errorMessage, bool ignoreMissing,
5067 PQconninfoOption *option;
5071 * For backwards compatibility, requiressl=1 gets translated to
5072 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5073 * (which is the default for sslmode).
5075 if (strcmp(keyword, "requiressl") == 0)
5077 keyword = "sslmode";
5078 if (value[0] == '1')
5084 option = conninfo_find(connOptions, keyword);
5088 printfPQExpBuffer(errorMessage,
5089 libpq_gettext("invalid connection option \"%s\"\n"),
5096 value_copy = conninfo_uri_decode(value, errorMessage);
5097 if (value_copy == NULL)
5098 /* conninfo_uri_decode already set an error message */
5103 value_copy = strdup(value);
5105 if (value_copy == NULL)
5107 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5114 option->val = value_copy;
5120 * Find a PQconninfoOption option corresponding to the keyword in the
5121 * connOptions array.
5123 * If successful, returns a pointer to the corresponding PQconninfoOption
5125 * If not successful, returns NULL.
5127 static PQconninfoOption *
5128 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
5130 PQconninfoOption *option;
5132 for (option = connOptions; option->keyword != NULL; option++)
5134 if (strcmp(option->keyword, keyword) == 0)
5143 * Return the connection options used for the connection
5146 PQconninfo(PGconn *conn)
5148 PQExpBufferData errorBuf;
5149 PQconninfoOption *connOptions;
5154 /* We don't actually report any errors here, but callees want a buffer */
5155 initPQExpBuffer(&errorBuf);
5156 if (PQExpBufferDataBroken(errorBuf))
5157 return NULL; /* out of memory already :-( */
5159 connOptions = conninfo_init(&errorBuf);
5161 if (connOptions != NULL)
5163 const internalPQconninfoOption *option;
5165 for (option = PQconninfoOptions; option->keyword; option++)
5169 if (option->connofs < 0)
5172 connmember = (char **) ((char *) conn + option->connofs);
5175 conninfo_storeval(connOptions, option->keyword, *connmember,
5176 &errorBuf, true, false);
5180 termPQExpBuffer(&errorBuf);
5187 PQconninfoFree(PQconninfoOption *connOptions)
5189 PQconninfoOption *option;
5191 if (connOptions == NULL)
5194 for (option = connOptions; option->keyword != NULL; option++)
5196 if (option->val != NULL)
5203 /* =========== accessor functions for PGconn ========= */
5205 PQdb(const PGconn *conn)
5209 return conn->dbName;
5213 PQuser(const PGconn *conn)
5217 return conn->pguser;
5221 PQpass(const PGconn *conn)
5225 return conn->pgpass;
5229 PQhost(const PGconn *conn)
5233 if (conn->pghost != NULL && conn->pghost[0] != '\0')
5234 return conn->pghost;
5237 #ifdef HAVE_UNIX_SOCKETS
5238 return conn->pgunixsocket;
5246 PQhostaddr(const PGconn *conn)
5250 return conn->pghostaddr;
5254 PQport(const PGconn *conn)
5258 return conn->pgport;
5262 PQtty(const PGconn *conn)
5270 PQoptions(const PGconn *conn)
5274 return conn->pgoptions;
5278 PQstatus(const PGconn *conn)
5281 return CONNECTION_BAD;
5282 return conn->status;
5285 PGTransactionStatusType
5286 PQtransactionStatus(const PGconn *conn)
5288 if (!conn || conn->status != CONNECTION_OK)
5289 return PQTRANS_UNKNOWN;
5290 if (conn->asyncStatus != PGASYNC_IDLE)
5291 return PQTRANS_ACTIVE;
5292 return conn->xactStatus;
5296 PQparameterStatus(const PGconn *conn, const char *paramName)
5298 const pgParameterStatus *pstatus;
5300 if (!conn || !paramName)
5302 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
5304 if (strcmp(pstatus->name, paramName) == 0)
5305 return pstatus->value;
5311 PQprotocolVersion(const PGconn *conn)
5315 if (conn->status == CONNECTION_BAD)
5317 return PG_PROTOCOL_MAJOR(conn->pversion);
5321 PQserverVersion(const PGconn *conn)
5325 if (conn->status == CONNECTION_BAD)
5327 return conn->sversion;
5331 PQerrorMessage(const PGconn *conn)
5334 return libpq_gettext("connection pointer is NULL\n");
5336 return conn->errorMessage.data;
5340 * In Windows, socket values are unsigned, and an invalid socket value
5341 * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
5342 * warning). Ideally we would return an unsigned value for PQsocket() on
5343 * Windows, but that would cause the function's return value to differ from
5344 * Unix, so we just return -1 for invalid sockets.
5345 * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
5346 * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
5349 PQsocket(const PGconn *conn)
5353 return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
5357 PQbackendPID(const PGconn *conn)
5359 if (!conn || conn->status != CONNECTION_OK)
5361 return conn->be_pid;
5365 PQconnectionNeedsPassword(const PGconn *conn)
5369 if (conn->password_needed &&
5370 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
5377 PQconnectionUsedPassword(const PGconn *conn)
5381 if (conn->password_needed)
5388 PQclientEncoding(const PGconn *conn)
5390 if (!conn || conn->status != CONNECTION_OK)
5392 return conn->client_encoding;
5396 PQsetClientEncoding(PGconn *conn, const char *encoding)
5399 static const char query[] = "set client_encoding to '%s'";
5403 if (!conn || conn->status != CONNECTION_OK)
5409 /* Resolve special "auto" value from the locale */
5410 if (strcmp(encoding, "auto") == 0)
5411 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
5413 /* check query buffer overflow */
5414 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
5417 /* ok, now send a query */
5418 sprintf(qbuf, query, encoding);
5419 res = PQexec(conn, qbuf);
5423 if (res->resultStatus != PGRES_COMMAND_OK)
5428 * In protocol 2 we have to assume the setting will stick, and adjust
5429 * our state immediately. In protocol 3 and up we can rely on the
5430 * backend to report the parameter value, and we'll change state at
5433 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
5434 pqSaveParameterStatus(conn, "client_encoding", encoding);
5435 status = 0; /* everything is ok */
5442 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
5447 return PQERRORS_DEFAULT;
5448 old = conn->verbosity;
5449 conn->verbosity = verbosity;
5454 PQtrace(PGconn *conn, FILE *debug_port)
5459 conn->Pfdebug = debug_port;
5463 PQuntrace(PGconn *conn)
5469 fflush(conn->Pfdebug);
5470 conn->Pfdebug = NULL;
5475 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
5477 PQnoticeReceiver old;
5482 old = conn->noticeHooks.noticeRec;
5485 conn->noticeHooks.noticeRec = proc;
5486 conn->noticeHooks.noticeRecArg = arg;
5492 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
5494 PQnoticeProcessor old;
5499 old = conn->noticeHooks.noticeProc;
5502 conn->noticeHooks.noticeProc = proc;
5503 conn->noticeHooks.noticeProcArg = arg;
5509 * The default notice message receiver just gets the standard notice text
5510 * and sends it to the notice processor. This two-level setup exists
5511 * mostly for backwards compatibility; perhaps we should deprecate use of
5512 * PQsetNoticeProcessor?
5515 defaultNoticeReceiver(void *arg, const PGresult *res)
5517 (void) arg; /* not used */
5518 if (res->noticeHooks.noticeProc != NULL)
5519 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
5520 PQresultErrorMessage(res));
5524 * The default notice message processor just prints the
5525 * message on stderr. Applications can override this if they
5526 * want the messages to go elsewhere (a window, for example).
5527 * Note that simply discarding notices is probably a bad idea.
5530 defaultNoticeProcessor(void *arg, const char *message)
5532 (void) arg; /* not used */
5533 /* Note: we expect the supplied string to end with a newline already. */
5534 fprintf(stderr, "%s", message);
5538 * returns a pointer to the next token or NULL if the current
5539 * token doesn't match
5542 pwdfMatchesString(char *buf, char *token)
5546 bool bslash = false;
5548 if (buf == NULL || token == NULL)
5552 if (tbuf[0] == '*' && tbuf[1] == ':')
5556 if (*tbuf == '\\' && !bslash)
5561 if (*tbuf == ':' && *ttok == 0 && !bslash)
5577 /* Get a password from the password file. Return value is malloc'd. */
5579 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
5582 char pgpassfile[MAXPGPATH];
5583 struct stat stat_buf;
5585 #define LINELEN NAMEDATALEN*5
5588 if (dbname == NULL || strlen(dbname) == 0)
5591 if (username == NULL || strlen(username) == 0)
5594 /* 'localhost' matches pghost of '' or the default socket directory */
5595 if (hostname == NULL)
5596 hostname = DefaultHost;
5597 else if (is_absolute_path(hostname))
5600 * We should probably use canonicalize_path(), but then we have to
5601 * bring path.c into libpq, and it doesn't seem worth it.
5603 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
5604 hostname = DefaultHost;
5607 port = DEF_PGPORT_STR;
5609 if (!getPgPassFilename(pgpassfile))
5612 /* If password file cannot be opened, ignore it. */
5613 if (stat(pgpassfile, &stat_buf) != 0)
5617 if (!S_ISREG(stat_buf.st_mode))
5620 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
5625 /* If password file is insecure, alert the user and ignore it. */
5626 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
5629 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
5636 * On Win32, the directory is protected, so we don't have to check the
5641 fp = fopen(pgpassfile, "r");
5645 while (!feof(fp) && !ferror(fp))
5653 if (fgets(buf, sizeof(buf), fp) == NULL)
5660 /* Remove trailing newline */
5661 if (buf[len - 1] == '\n')
5664 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
5665 (t = pwdfMatchesString(t, port)) == NULL ||
5666 (t = pwdfMatchesString(t, dbname)) == NULL ||
5667 (t = pwdfMatchesString(t, username)) == NULL)
5672 /* De-escape password. */
5673 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
5675 if (*p1 == '\\' && p1[1] != '\0')
5692 getPgPassFilename(char *pgpassfile)
5696 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
5697 /* use the literal path from the environment, if set */
5698 strlcpy(pgpassfile, passfile_env, MAXPGPATH);
5701 char homedir[MAXPGPATH];
5703 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5705 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
5711 * If the connection failed, we should mention if
5712 * we got the password from .pgpass in case that
5713 * password is wrong.
5716 dot_pg_pass_warning(PGconn *conn)
5718 /* If it was 'invalid authorization', add .pgpass mention */
5719 /* only works with >= 9.0 servers */
5720 if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
5721 strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
5722 ERRCODE_INVALID_PASSWORD) == 0)
5724 char pgpassfile[MAXPGPATH];
5726 if (!getPgPassFilename(pgpassfile))
5728 appendPQExpBuffer(&conn->errorMessage,
5729 libpq_gettext("password retrieved from file \"%s\"\n"),
5736 * Obtain user's home directory, return in given buffer
5738 * On Unix, this actually returns the user's home directory. On Windows
5739 * it returns the PostgreSQL-specific application data folder.
5741 * This is essentially the same as get_home_path(), but we don't use that
5742 * because we don't want to pull path.c into libpq (it pollutes application
5746 pqGetHomeDirectory(char *buf, int bufsize)
5749 char pwdbuf[BUFSIZ];
5750 struct passwd pwdstr;
5751 struct passwd *pwd = NULL;
5753 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
5755 strlcpy(buf, pwd->pw_dir, bufsize);
5758 char tmppath[MAX_PATH];
5760 ZeroMemory(tmppath, sizeof(tmppath));
5761 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
5763 snprintf(buf, bufsize, "%s/postgresql", tmppath);
5769 * To keep the API consistent, the locking stubs are always provided, even
5770 * if they are not required.
5774 default_threadlock(int acquire)
5776 #ifdef ENABLE_THREAD_SAFETY
5778 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
5780 static pthread_mutex_t singlethread_lock = NULL;
5781 static long mutex_initlock = 0;
5783 if (singlethread_lock == NULL)
5785 while (InterlockedExchange(&mutex_initlock, 1) == 1)
5786 /* loop, another thread own the lock */ ;
5787 if (singlethread_lock == NULL)
5789 if (pthread_mutex_init(&singlethread_lock, NULL))
5790 PGTHREAD_ERROR("failed to initialize mutex");
5792 InterlockedExchange(&mutex_initlock, 0);
5797 if (pthread_mutex_lock(&singlethread_lock))
5798 PGTHREAD_ERROR("failed to lock mutex");
5802 if (pthread_mutex_unlock(&singlethread_lock))
5803 PGTHREAD_ERROR("failed to unlock mutex");
5809 PQregisterThreadLock(pgthreadlock_t newhandler)
5811 pgthreadlock_t prev = pg_g_threadlock;
5814 pg_g_threadlock = newhandler;
5816 pg_g_threadlock = default_threadlock;