1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/interfaces/libpq/fe-connect.c,v 1.356 2008/01/29 02:06:30 tgl Exp $
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
42 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #ifdef HAVE_NETINET_TCP_H
46 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
51 #ifdef ENABLE_THREAD_SAFETY
53 #include "pthread-win32.h"
63 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
64 #define LDAP_DEPRECATED 1
66 typedef struct timeval LDAP_TIMEVAL;
68 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
69 PQExpBuffer errorMessage);
73 #include "mb/pg_wchar.h"
81 #define PGPASSFILE ".pgpass"
83 #define PGPASSFILE "pgpass.conf"
86 /* fall back options if they are not specified by arguments or defined
87 by environment variables */
88 #define DefaultHost "localhost"
90 #define DefaultOption ""
91 #define DefaultAuthtype ""
92 #define DefaultPassword ""
94 #define DefaultSSLMode "prefer"
96 #define DefaultSSLMode "disable"
100 * Definition of the conninfo parameters and their fallback resources.
102 * If Environment-Var and Compiled-in are specified as NULL, no
103 * fallback is available. If after all no value can be determined
104 * for an option, an error is returned.
106 * The value for the username is treated specially in conninfo_parse.
107 * If the Compiled-in resource is specified as a NULL value, the
108 * user is determined by pg_fe_getauthname().
110 * The Label and Disp-Char entries are provided for applications that
111 * want to use PQconndefaults() to create a generic database connection
112 * dialog. Disp-Char is defined as follows:
113 * "" Normal input field
114 * "*" Password field - hide value
115 * "D" Debug option - don't show by default
117 * PQconninfoOptions[] is a constant static array that we use to initialize
118 * a dynamically allocated working copy. All the "val" fields in
119 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
120 * fields point to malloc'd strings that should be freed when the working
121 * array is freed (see PQconninfoFree).
124 static const PQconninfoOption PQconninfoOptions[] = {
126 * "authtype" is no longer used, so mark it "don't show". We keep it in
127 * the array so as not to reject conninfo strings from old apps that might
128 * still try to set it.
130 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
131 "Database-Authtype", "D", 20},
133 {"service", "PGSERVICE", NULL, NULL,
134 "Database-Service", "", 20},
136 {"user", "PGUSER", NULL, NULL,
137 "Database-User", "", 20},
139 {"password", "PGPASSWORD", NULL, NULL,
140 "Database-Password", "*", 20},
142 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
143 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
145 {"dbname", "PGDATABASE", NULL, NULL,
146 "Database-Name", "", 20},
148 {"host", "PGHOST", NULL, NULL,
149 "Database-Host", "", 40},
151 {"hostaddr", "PGHOSTADDR", NULL, NULL,
152 "Database-Host-IP-Address", "", 45},
154 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
155 "Database-Port", "", 6},
158 * "tty" is no longer used either, but keep it present for backwards
161 {"tty", "PGTTY", DefaultTty, NULL,
162 "Backend-Debug-TTY", "D", 40},
164 {"options", "PGOPTIONS", DefaultOption, NULL,
165 "Backend-Debug-Options", "D", 40},
170 * "requiressl" is deprecated, its purpose having been taken over by
171 * "sslmode". It remains for backwards compatibility.
173 {"requiressl", "PGREQUIRESSL", "0", NULL,
174 "Require-SSL", "D", 1},
178 * "sslmode" option is allowed even without client SSL support because the
179 * client can still handle SSL modes "disable" and "allow".
181 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
182 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
184 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
185 /* Kerberos and GSSAPI authentication support specifying the service name */
186 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
187 "Kerberos-service-name", "", 20},
190 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
193 * GSSAPI and SSPI both enabled, give a way to override which is used by
196 {"gsslib", "PGGSSLIB", NULL, NULL,
197 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
200 /* Terminating entry --- MUST BE LAST */
201 {NULL, NULL, NULL, NULL,
205 static const PQEnvironmentOption EnvironmentOptions[] =
207 /* common user-interface settings */
209 "PGDATESTYLE", "datestyle"
215 "PGCLIENTENCODING", "client_encoding"
217 /* internal performance-related settings */
227 static bool connectOptions1(PGconn *conn, const char *conninfo);
228 static bool connectOptions2(PGconn *conn);
229 static int connectDBStart(PGconn *conn);
230 static int connectDBComplete(PGconn *conn);
231 static PGconn *makeEmptyPGconn(void);
232 static void freePGconn(PGconn *conn);
233 static void closePGconn(PGconn *conn);
234 static PQconninfoOption *conninfo_parse(const char *conninfo,
235 PQExpBuffer errorMessage, bool *password_from_string);
236 static char *conninfo_getval(PQconninfoOption *connOptions,
237 const char *keyword);
238 static void defaultNoticeReceiver(void *arg, const PGresult *res);
239 static void defaultNoticeProcessor(void *arg, const char *message);
240 static int parseServiceInfo(PQconninfoOption *options,
241 PQExpBuffer errorMessage);
242 static char *pwdfMatchesString(char *buf, char *token);
243 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
245 static void default_threadlock(int acquire);
248 /* global variable because fe-auth.c needs to access it */
249 pgthreadlock_t pg_g_threadlock = default_threadlock;
253 * Connecting to a Database
255 * There are now four different ways a user of this API can connect to the
256 * database. Two are not recommended for use in new code, because of their
257 * lack of extensibility with respect to the passing of options to the
258 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
261 * If it is desired to connect in a synchronous (blocking) manner, use the
262 * function PQconnectdb.
264 * To connect in an asynchronous (non-blocking) manner, use the functions
265 * PQconnectStart, and PQconnectPoll.
267 * Internally, the static functions connectDBStart, connectDBComplete
268 * are part of the connection procedure.
274 * establishes a connection to a postgres backend through the postmaster
275 * using connection information in a string.
277 * The conninfo string is a white-separated list of
281 * definitions. Value might be a single value containing no whitespaces or
282 * a single quoted string. If a single quote should appear anywhere in
283 * the value, it must be escaped with a backslash like \'
285 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
286 * if a memory allocation failed.
287 * If the status field of the connection returned is CONNECTION_BAD,
288 * then some fields may be null'ed out instead of having valid values.
290 * You should call PQfinish (if conn is not NULL) regardless of whether this
294 PQconnectdb(const char *conninfo)
296 PGconn *conn = PQconnectStart(conninfo);
298 if (conn && conn->status != CONNECTION_BAD)
299 (void) connectDBComplete(conn);
307 * Begins the establishment of a connection to a postgres backend through the
308 * postmaster using connection information in a string.
310 * See comment for PQconnectdb for the definition of the string format.
312 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
313 * you should not attempt to proceed with this connection. If the status
314 * field of the connection returned is CONNECTION_BAD, an error has
315 * occurred. In this case you should call PQfinish on the result, (perhaps
316 * inspecting the error message first). Other fields of the structure may not
317 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
318 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
321 * See PQconnectPoll for more info.
324 PQconnectStart(const char *conninfo)
329 * Allocate memory for the conn structure
331 conn = makeEmptyPGconn();
336 * Parse the conninfo string
338 if (!connectOptions1(conn, conninfo))
342 * Compute derived options
344 if (!connectOptions2(conn))
348 * Connect to the database
350 if (!connectDBStart(conn))
352 /* Just in case we failed to set it in connectDBStart */
353 conn->status = CONNECTION_BAD;
362 * Internal subroutine to set up connection parameters given an already-
363 * created PGconn and a conninfo string. Derived settings should be
364 * processed by calling connectOptions2 next. (We split them because
365 * PQsetdbLogin overrides defaults in between.)
367 * Returns true if OK, false if trouble (in which case errorMessage is set
368 * and so is conn->status).
371 connectOptions1(PGconn *conn, const char *conninfo)
373 PQconninfoOption *connOptions;
377 * Parse the conninfo string
379 connOptions = conninfo_parse(conninfo, &conn->errorMessage,
380 &conn->pgpass_from_client);
381 if (connOptions == NULL)
383 conn->status = CONNECTION_BAD;
384 /* errorMessage is already set */
389 * Move option values into conn structure
391 * Don't put anything cute here --- intelligence should be in
392 * connectOptions2 ...
394 * XXX: probably worth checking strdup() return value here...
396 tmp = conninfo_getval(connOptions, "hostaddr");
397 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
398 tmp = conninfo_getval(connOptions, "host");
399 conn->pghost = tmp ? strdup(tmp) : NULL;
400 tmp = conninfo_getval(connOptions, "port");
401 conn->pgport = tmp ? strdup(tmp) : NULL;
402 tmp = conninfo_getval(connOptions, "tty");
403 conn->pgtty = tmp ? strdup(tmp) : NULL;
404 tmp = conninfo_getval(connOptions, "options");
405 conn->pgoptions = tmp ? strdup(tmp) : NULL;
406 tmp = conninfo_getval(connOptions, "dbname");
407 conn->dbName = tmp ? strdup(tmp) : NULL;
408 tmp = conninfo_getval(connOptions, "user");
409 conn->pguser = tmp ? strdup(tmp) : NULL;
410 tmp = conninfo_getval(connOptions, "password");
411 conn->pgpass = tmp ? strdup(tmp) : NULL;
412 tmp = conninfo_getval(connOptions, "connect_timeout");
413 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
414 tmp = conninfo_getval(connOptions, "sslmode");
415 conn->sslmode = tmp ? strdup(tmp) : NULL;
417 tmp = conninfo_getval(connOptions, "requiressl");
418 if (tmp && tmp[0] == '1')
420 /* here warn that the requiressl option is deprecated? */
423 conn->sslmode = strdup("require");
426 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
427 tmp = conninfo_getval(connOptions, "krbsrvname");
428 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
430 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
431 tmp = conninfo_getval(connOptions, "gsslib");
432 conn->gsslib = tmp ? strdup(tmp) : NULL;
436 * Free the option info - all is in conn now
438 PQconninfoFree(connOptions);
446 * Compute derived connection options after absorbing all user-supplied info.
448 * Returns true if OK, false if trouble (in which case errorMessage is set
449 * and so is conn->status).
452 connectOptions2(PGconn *conn)
455 * If database name was not given, default it to equal user name
457 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
458 && conn->pguser != NULL)
462 conn->dbName = strdup(conn->pguser);
466 * Supply default password if none given
468 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
472 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
473 conn->dbName, conn->pguser);
474 if (conn->pgpass == NULL)
475 conn->pgpass = strdup(DefaultPassword);
476 conn->pgpass_from_client = false;
480 * Allow unix socket specification in the host name
482 if (conn->pghost && is_absolute_path(conn->pghost))
484 if (conn->pgunixsocket)
485 free(conn->pgunixsocket);
486 conn->pgunixsocket = conn->pghost;
491 * validate sslmode option
495 if (strcmp(conn->sslmode, "disable") != 0
496 && strcmp(conn->sslmode, "allow") != 0
497 && strcmp(conn->sslmode, "prefer") != 0
498 && strcmp(conn->sslmode, "require") != 0)
500 conn->status = CONNECTION_BAD;
501 printfPQExpBuffer(&conn->errorMessage,
502 libpq_gettext("invalid sslmode value: \"%s\"\n"),
508 switch (conn->sslmode[0])
510 case 'a': /* "allow" */
511 case 'p': /* "prefer" */
514 * warn user that an SSL connection will never be negotiated
515 * since SSL was not compiled in?
519 case 'r': /* "require" */
520 conn->status = CONNECTION_BAD;
521 printfPQExpBuffer(&conn->errorMessage,
522 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
529 conn->sslmode = strdup(DefaultSSLMode);
532 * Only if we get this far is it appropriate to try to connect. (We need a
533 * state flag, rather than just the boolean result of this function, in
534 * case someone tries to PQreset() the PGconn.)
536 conn->options_valid = true;
544 * Parse an empty string like PQconnectdb() would do and return the
545 * working connection options array.
547 * Using this function, an application may determine all possible options
548 * and their current default values.
550 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
551 * and should be freed when no longer needed via PQconninfoFree(). (In prior
552 * versions, the returned array was static, but that's not thread-safe.)
553 * Pre-7.0 applications that use this function will see a small memory leak
554 * until they are updated to call PQconninfoFree.
559 PQExpBufferData errorBuf;
560 bool password_from_string;
561 PQconninfoOption *connOptions;
563 initPQExpBuffer(&errorBuf);
564 connOptions = conninfo_parse("", &errorBuf, &password_from_string);
565 termPQExpBuffer(&errorBuf);
572 * establishes a connection to a postgres backend through the postmaster
573 * at the specified host and port.
575 * returns a PGconn* which is needed for all subsequent libpq calls
577 * if the status field of the connection returned is CONNECTION_BAD,
578 * then only the errorMessage is likely to be useful.
582 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
583 const char *pgtty, const char *dbName, const char *login,
589 * Allocate memory for the conn structure
591 conn = makeEmptyPGconn();
596 * If the dbName parameter contains '=', assume it's a conninfo string.
598 if (dbName && strchr(dbName, '='))
600 if (!connectOptions1(conn, dbName))
606 * Old-style path: first, parse an empty conninfo string in order to
607 * set up the same defaults that PQconnectdb() would use.
609 if (!connectOptions1(conn, ""))
612 /* Insert dbName parameter value into struct */
613 if (dbName && dbName[0] != '\0')
617 conn->dbName = strdup(dbName);
622 * Insert remaining parameters into struct, overriding defaults (as well
623 * as any conflicting data from dbName taken as a conninfo).
625 if (pghost && pghost[0] != '\0')
629 conn->pghost = strdup(pghost);
632 if (pgport && pgport[0] != '\0')
636 conn->pgport = strdup(pgport);
639 if (pgoptions && pgoptions[0] != '\0')
642 free(conn->pgoptions);
643 conn->pgoptions = strdup(pgoptions);
646 if (pgtty && pgtty[0] != '\0')
650 conn->pgtty = strdup(pgtty);
653 if (login && login[0] != '\0')
657 conn->pguser = strdup(login);
660 if (pwd && pwd[0] != '\0')
664 conn->pgpass = strdup(pwd);
665 conn->pgpass_from_client = true;
669 * Compute derived options
671 if (!connectOptions2(conn))
675 * Connect to the database
677 if (connectDBStart(conn))
678 (void) connectDBComplete(conn);
686 * Sets the TCP_NODELAY socket option.
687 * Returns 1 if successful, 0 if not.
691 connectNoDelay(PGconn *conn)
696 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
702 printfPQExpBuffer(&conn->errorMessage,
703 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
704 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
714 * connectFailureMessage -
715 * create a friendly error message on connection failure.
719 connectFailureMessage(PGconn *conn, int errorno)
723 #ifdef HAVE_UNIX_SOCKETS
724 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
726 char service[NI_MAXHOST];
728 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
730 service, sizeof(service),
732 printfPQExpBuffer(&conn->errorMessage,
733 libpq_gettext("could not connect to server: %s\n"
734 "\tIs the server running locally and accepting\n"
735 "\tconnections on Unix domain socket \"%s\"?\n"),
736 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
740 #endif /* HAVE_UNIX_SOCKETS */
742 printfPQExpBuffer(&conn->errorMessage,
743 libpq_gettext("could not connect to server: %s\n"
744 "\tIs the server running on host \"%s\" and accepting\n"
745 "\tTCP/IP connections on port %s?\n"),
746 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
759 * Begin the process of making a connection to the backend.
761 * Returns 1 if successful, 0 if not.
765 connectDBStart(PGconn *conn)
769 struct addrinfo *addrs = NULL;
770 struct addrinfo hint;
777 if (!conn->options_valid)
778 goto connect_errReturn;
780 /* Ensure our buffers are empty */
781 conn->inStart = conn->inCursor = conn->inEnd = 0;
785 * Determine the parameters to pass to pg_getaddrinfo_all.
788 /* Initialize hint structure */
789 MemSet(&hint, 0, sizeof(hint));
790 hint.ai_socktype = SOCK_STREAM;
791 hint.ai_family = AF_UNSPEC;
793 /* Set up port number as a string */
794 if (conn->pgport != NULL && conn->pgport[0] != '\0')
795 portnum = atoi(conn->pgport);
797 portnum = DEF_PGPORT;
798 snprintf(portstr, sizeof(portstr), "%d", portnum);
800 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
802 /* Using pghostaddr avoids a hostname lookup */
803 node = conn->pghostaddr;
804 hint.ai_family = AF_UNSPEC;
805 hint.ai_flags = AI_NUMERICHOST;
807 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
809 /* Using pghost, so we have to look-up the hostname */
811 hint.ai_family = AF_UNSPEC;
815 #ifdef HAVE_UNIX_SOCKETS
816 /* pghostaddr and pghost are NULL, so use Unix domain socket */
818 hint.ai_family = AF_UNIX;
819 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
821 /* Without Unix sockets, default to localhost instead */
823 hint.ai_family = AF_UNSPEC;
824 #endif /* HAVE_UNIX_SOCKETS */
827 /* Use pg_getaddrinfo_all() to resolve the address */
828 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
832 printfPQExpBuffer(&conn->errorMessage,
833 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
834 node, gai_strerror(ret));
836 printfPQExpBuffer(&conn->errorMessage,
837 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
838 portstr, gai_strerror(ret));
840 pg_freeaddrinfo_all(hint.ai_family, addrs);
841 goto connect_errReturn;
845 /* setup values based on SSL mode */
846 if (conn->sslmode[0] == 'd') /* "disable" */
847 conn->allow_ssl_try = false;
848 else if (conn->sslmode[0] == 'a') /* "allow" */
849 conn->wait_ssl_try = true;
853 * Set up to try to connect, with protocol 3.0 as the first attempt.
855 conn->addrlist = addrs;
856 conn->addr_cur = addrs;
857 conn->addrlist_family = hint.ai_family;
858 conn->pversion = PG_PROTOCOL(3, 0);
859 conn->status = CONNECTION_NEEDED;
862 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
863 * so that it can easily be re-executed if needed again during the
864 * asynchronous startup process. However, we must run it once here,
865 * because callers expect a success return from this routine to mean that
866 * we are in PGRES_POLLING_WRITING connection state.
868 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
874 pqsecure_close(conn);
875 closesocket(conn->sock);
878 conn->status = CONNECTION_BAD;
886 * Block and complete a connection.
888 * Returns 1 on success, 0 on failure.
891 connectDBComplete(PGconn *conn)
893 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
894 time_t finish_time = ((time_t) -1);
896 if (conn == NULL || conn->status == CONNECTION_BAD)
900 * Set up a time limit, if connect_timeout isn't zero.
902 if (conn->connect_timeout != NULL)
904 int timeout = atoi(conn->connect_timeout);
909 * Rounding could cause connection to fail; need at least 2 secs
913 /* calculate the finish time based on start + timeout */
914 finish_time = time(NULL) + timeout;
921 * Wait, if necessary. Note that the initial state (just after
922 * PQconnectStart) is to wait for the socket to select for writing.
926 case PGRES_POLLING_OK:
927 return 1; /* success! */
929 case PGRES_POLLING_READING:
930 if (pqWaitTimed(1, 0, conn, finish_time))
932 conn->status = CONNECTION_BAD;
937 case PGRES_POLLING_WRITING:
938 if (pqWaitTimed(0, 1, conn, finish_time))
940 conn->status = CONNECTION_BAD;
946 /* Just in case we failed to set it in PQconnectPoll */
947 conn->status = CONNECTION_BAD;
952 * Now try to advance the state machine.
954 flag = PQconnectPoll(conn);
961 * Poll an asynchronous connection.
963 * Returns a PostgresPollingStatusType.
964 * Before calling this function, use select(2) to determine when data
967 * You must call PQfinish whether or not this fails.
969 * This function and PQconnectStart are intended to allow connections to be
970 * made without blocking the execution of your program on remote I/O. However,
971 * there are a number of caveats:
973 * o If you call PQtrace, ensure that the stream object into which you trace
975 * o If you do not supply an IP address for the remote host (i.e. you
976 * supply a host name instead) then PQconnectStart will block on
977 * gethostbyname. You will be fine if using Unix sockets (i.e. by
978 * supplying neither a host name nor a host address).
979 * o If your backend wants to use Kerberos authentication then you must
980 * supply both a host name and a host address, otherwise this function
981 * may block on gethostname.
985 PostgresPollingStatusType
986 PQconnectPoll(PGconn *conn)
992 return PGRES_POLLING_FAILED;
994 /* Get the new data */
995 switch (conn->status)
998 * We really shouldn't have been polled in these two cases, but we
1001 case CONNECTION_BAD:
1002 return PGRES_POLLING_FAILED;
1004 return PGRES_POLLING_OK;
1006 /* These are reading states */
1007 case CONNECTION_AWAITING_RESPONSE:
1008 case CONNECTION_AUTH_OK:
1010 /* Load waiting data */
1011 int n = pqReadData(conn);
1016 return PGRES_POLLING_READING;
1021 /* These are writing states, so we just proceed. */
1022 case CONNECTION_STARTED:
1023 case CONNECTION_MADE:
1026 /* We allow pqSetenvPoll to decide whether to proceed. */
1027 case CONNECTION_SETENV:
1030 /* Special cases: proceed without waiting. */
1031 case CONNECTION_SSL_STARTUP:
1032 case CONNECTION_NEEDED:
1036 printfPQExpBuffer(&conn->errorMessage,
1038 "invalid connection state, "
1039 "probably indicative of memory corruption\n"
1045 keep_going: /* We will come back to here until there is
1046 * nothing left to do. */
1047 switch (conn->status)
1049 case CONNECTION_NEEDED:
1052 * Try to initiate a connection to one of the addresses
1053 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1054 * next one to try. We fail when we run out of addresses
1055 * (reporting the error returned for the *last* alternative,
1056 * which may not be what users expect :-().
1058 while (conn->addr_cur != NULL)
1060 struct addrinfo *addr_cur = conn->addr_cur;
1062 /* Remember current address for possible error msg */
1063 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1064 addr_cur->ai_addrlen);
1065 conn->raddr.salen = addr_cur->ai_addrlen;
1068 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1072 * ignore socket() failure if we have more addresses
1075 if (addr_cur->ai_next != NULL)
1077 conn->addr_cur = addr_cur->ai_next;
1080 printfPQExpBuffer(&conn->errorMessage,
1081 libpq_gettext("could not create socket: %s\n"),
1082 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1087 * Select socket options: no delay of outgoing data for
1088 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1091 if (!IS_AF_UNIX(addr_cur->ai_family))
1093 if (!connectNoDelay(conn))
1095 closesocket(conn->sock);
1097 conn->addr_cur = addr_cur->ai_next;
1101 if (!pg_set_noblock(conn->sock))
1103 printfPQExpBuffer(&conn->errorMessage,
1104 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1105 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1106 closesocket(conn->sock);
1108 conn->addr_cur = addr_cur->ai_next;
1113 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1115 printfPQExpBuffer(&conn->errorMessage,
1116 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1117 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1118 closesocket(conn->sock);
1120 conn->addr_cur = addr_cur->ai_next;
1123 #endif /* F_SETFD */
1126 * Start/make connection. This should not block, since we
1127 * are in nonblock mode. If it does, well, too bad.
1129 if (connect(conn->sock, addr_cur->ai_addr,
1130 addr_cur->ai_addrlen) < 0)
1132 if (SOCK_ERRNO == EINPROGRESS ||
1133 SOCK_ERRNO == EWOULDBLOCK ||
1134 SOCK_ERRNO == EINTR ||
1138 * This is fine - we're in non-blocking mode, and
1139 * the connection is in progress. Tell caller to
1140 * wait for write-ready on socket.
1142 conn->status = CONNECTION_STARTED;
1143 return PGRES_POLLING_WRITING;
1145 /* otherwise, trouble */
1150 * Hm, we're connected already --- seems the "nonblock
1151 * connection" wasn't. Advance the state machine and
1152 * go do the next stuff.
1154 conn->status = CONNECTION_STARTED;
1159 * This connection failed --- set up error report, then
1160 * close socket (do it this way in case close() affects
1161 * the value of errno...). We will ignore the connect()
1162 * failure and keep going if there are more addresses.
1164 connectFailureMessage(conn, SOCK_ERRNO);
1165 if (conn->sock >= 0)
1167 closesocket(conn->sock);
1172 * Try the next address, if any.
1174 conn->addr_cur = addr_cur->ai_next;
1175 } /* loop over addresses */
1178 * Ooops, no more addresses. An appropriate error message is
1179 * already set up, so just set the right status.
1184 case CONNECTION_STARTED:
1187 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1190 * Write ready, since we've made it here, so the connection
1191 * has been made ... or has failed.
1195 * Now check (using getsockopt) that there is not an error
1196 * state waiting for us on the socket.
1199 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1200 (char *) &optval, &optlen) == -1)
1202 printfPQExpBuffer(&conn->errorMessage,
1203 libpq_gettext("could not get socket error status: %s\n"),
1204 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1207 else if (optval != 0)
1210 * When using a nonblocking connect, we will typically see
1211 * connect failures at this point, so provide a friendly
1214 connectFailureMessage(conn, optval);
1217 * If more addresses remain, keep trying, just as in the
1218 * case where connect() returned failure immediately.
1220 if (conn->addr_cur->ai_next != NULL)
1222 if (conn->sock >= 0)
1224 closesocket(conn->sock);
1227 conn->addr_cur = conn->addr_cur->ai_next;
1228 conn->status = CONNECTION_NEEDED;
1234 /* Fill in the client address */
1235 conn->laddr.salen = sizeof(conn->laddr.addr);
1236 if (getsockname(conn->sock,
1237 (struct sockaddr *) & conn->laddr.addr,
1238 &conn->laddr.salen) < 0)
1240 printfPQExpBuffer(&conn->errorMessage,
1241 libpq_gettext("could not get client address from socket: %s\n"),
1242 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1247 * Make sure we can write before advancing to next step.
1249 conn->status = CONNECTION_MADE;
1250 return PGRES_POLLING_WRITING;
1253 case CONNECTION_MADE:
1261 * If SSL is enabled and we haven't already got it running,
1262 * request it instead of sending the startup message.
1264 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1266 /* Don't bother requesting SSL over a Unix socket */
1267 conn->allow_ssl_try = false;
1269 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1275 * Send the SSL request packet.
1277 * Theoretically, this could block, but it really
1278 * shouldn't since we only got here if the socket is
1281 pv = htonl(NEGOTIATE_SSL_CODE);
1282 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1284 printfPQExpBuffer(&conn->errorMessage,
1285 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1286 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1289 /* Ok, wait for response */
1290 conn->status = CONNECTION_SSL_STARTUP;
1291 return PGRES_POLLING_READING;
1293 #endif /* USE_SSL */
1296 * Build the startup packet.
1298 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1299 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1300 EnvironmentOptions);
1302 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1303 EnvironmentOptions);
1306 printfPQExpBuffer(&conn->errorMessage,
1307 libpq_gettext("out of memory\n"));
1312 * Send the startup packet.
1314 * Theoretically, this could block, but it really shouldn't
1315 * since we only got here if the socket is write-ready.
1317 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1319 printfPQExpBuffer(&conn->errorMessage,
1320 libpq_gettext("could not send startup packet: %s\n"),
1321 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1328 conn->status = CONNECTION_AWAITING_RESPONSE;
1329 return PGRES_POLLING_READING;
1333 * Handle SSL negotiation: wait for postmaster messages and
1334 * respond as necessary.
1336 case CONNECTION_SSL_STARTUP:
1339 PostgresPollingStatusType pollres;
1342 * On first time through, get the postmaster's response to our
1343 * SSL negotiation packet.
1345 if (conn->ssl == NULL)
1348 * We use pqReadData here since it has the logic to
1349 * distinguish no-data-yet from connection closure. Since
1350 * conn->ssl isn't set, a plain recv() will occur.
1355 rdresult = pqReadData(conn);
1358 /* errorMessage is already filled in */
1363 /* caller failed to wait for data */
1364 return PGRES_POLLING_READING;
1366 if (pqGetc(&SSLok, conn) < 0)
1368 /* should not happen really */
1369 return PGRES_POLLING_READING;
1371 /* mark byte consumed */
1372 conn->inStart = conn->inCursor;
1375 /* Do one-time setup; this creates conn->ssl */
1376 if (pqsecure_initialize(conn) == -1)
1379 else if (SSLok == 'N')
1381 if (conn->sslmode[0] == 'r') /* "require" */
1383 /* Require SSL, but server does not want it */
1384 printfPQExpBuffer(&conn->errorMessage,
1385 libpq_gettext("server does not support SSL, but SSL was required\n"));
1388 /* Otherwise, proceed with normal startup */
1389 conn->allow_ssl_try = false;
1390 conn->status = CONNECTION_MADE;
1391 return PGRES_POLLING_WRITING;
1393 else if (SSLok == 'E')
1395 /* Received error - probably protocol mismatch */
1397 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1398 if (conn->sslmode[0] == 'r') /* "require" */
1400 /* Require SSL, but server is too old */
1401 printfPQExpBuffer(&conn->errorMessage,
1402 libpq_gettext("server does not support SSL, but SSL was required\n"));
1405 /* Otherwise, try again without SSL */
1406 conn->allow_ssl_try = false;
1407 /* Assume it ain't gonna handle protocol 3, either */
1408 conn->pversion = PG_PROTOCOL(2, 0);
1409 /* Must drop the old connection */
1410 closesocket(conn->sock);
1412 conn->status = CONNECTION_NEEDED;
1417 printfPQExpBuffer(&conn->errorMessage,
1418 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1425 * Begin or continue the SSL negotiation process.
1427 pollres = pqsecure_open_client(conn);
1428 if (pollres == PGRES_POLLING_OK)
1430 /* SSL handshake done, ready to send startup packet */
1431 conn->status = CONNECTION_MADE;
1432 return PGRES_POLLING_WRITING;
1434 if (pollres == PGRES_POLLING_FAILED)
1437 * Failed ... if sslmode is "prefer" then do a non-SSL
1440 if (conn->sslmode[0] == 'p' /* "prefer" */
1441 && conn->allow_ssl_try /* redundant? */
1442 && !conn->wait_ssl_try) /* redundant? */
1444 /* only retry once */
1445 conn->allow_ssl_try = false;
1446 /* Must drop the old connection */
1447 closesocket(conn->sock);
1449 conn->status = CONNECTION_NEEDED;
1454 #else /* !USE_SSL */
1455 /* can't get here */
1457 #endif /* USE_SSL */
1461 * Handle authentication exchange: wait for postmaster messages
1462 * and respond as necessary.
1464 case CONNECTION_AWAITING_RESPONSE:
1472 * Scan the message from current point (note that if we find
1473 * the message is incomplete, we will return without advancing
1474 * inStart, and resume here next time).
1476 conn->inCursor = conn->inStart;
1478 /* Read type byte */
1479 if (pqGetc(&beresp, conn))
1481 /* We'll come back when there is more data */
1482 return PGRES_POLLING_READING;
1486 * Validate message type: we expect only an authentication
1487 * request or an error here. Anything else probably means
1488 * it's not Postgres on the other end at all.
1490 if (!(beresp == 'R' || beresp == 'E'))
1492 printfPQExpBuffer(&conn->errorMessage,
1494 "expected authentication request from "
1495 "server, but received %c\n"),
1500 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1502 /* Read message length word */
1503 if (pqGetInt(&msgLength, 4, conn))
1505 /* We'll come back when there is more data */
1506 return PGRES_POLLING_READING;
1511 /* Set phony message length to disable checks below */
1516 * Try to validate message length before using it.
1517 * Authentication requests can't be very large, although GSS
1518 * auth requests may not be that small. Errors can be a
1519 * little larger, but not huge. If we see a large apparent
1520 * length in an error, it means we're really talking to a
1521 * pre-3.0-protocol server; cope.
1523 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1525 printfPQExpBuffer(&conn->errorMessage,
1527 "expected authentication request from "
1528 "server, but received %c\n"),
1533 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1535 /* Handle error from a pre-3.0 server */
1536 conn->inCursor = conn->inStart + 1; /* reread data */
1537 if (pqGets(&conn->errorMessage, conn))
1539 /* We'll come back when there is more data */
1540 return PGRES_POLLING_READING;
1542 /* OK, we read the message; mark data consumed */
1543 conn->inStart = conn->inCursor;
1546 * The postmaster typically won't end its message with a
1547 * newline, so add one to conform to libpq conventions.
1549 appendPQExpBufferChar(&conn->errorMessage, '\n');
1552 * If we tried to open the connection in 3.0 protocol,
1553 * fall back to 2.0 protocol.
1555 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1557 conn->pversion = PG_PROTOCOL(2, 0);
1558 /* Must drop the old connection */
1559 pqsecure_close(conn);
1560 closesocket(conn->sock);
1562 conn->status = CONNECTION_NEEDED;
1570 * Can't process if message body isn't all here yet.
1572 * (In protocol 2.0 case, we are assuming messages carry at
1573 * least 4 bytes of data.)
1576 avail = conn->inEnd - conn->inCursor;
1577 if (avail < msgLength)
1580 * Before returning, try to enlarge the input buffer if
1581 * needed to hold the whole message; see notes in
1584 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1586 /* We'll come back when there is more data */
1587 return PGRES_POLLING_READING;
1590 /* Handle errors. */
1593 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1595 if (pqGetErrorNotice3(conn, true))
1597 /* We'll come back when there is more data */
1598 return PGRES_POLLING_READING;
1603 if (pqGets(&conn->errorMessage, conn))
1605 /* We'll come back when there is more data */
1606 return PGRES_POLLING_READING;
1609 /* OK, we read the message; mark data consumed */
1610 conn->inStart = conn->inCursor;
1615 * if sslmode is "allow" and we haven't tried an SSL
1616 * connection already, then retry with an SSL connection
1618 if (conn->sslmode[0] == 'a' /* "allow" */
1619 && conn->ssl == NULL
1620 && conn->allow_ssl_try
1621 && conn->wait_ssl_try)
1623 /* only retry once */
1624 conn->wait_ssl_try = false;
1625 /* Must drop the old connection */
1626 closesocket(conn->sock);
1628 conn->status = CONNECTION_NEEDED;
1633 * if sslmode is "prefer" and we're in an SSL connection,
1634 * then do a non-SSL retry
1636 if (conn->sslmode[0] == 'p' /* "prefer" */
1638 && conn->allow_ssl_try /* redundant? */
1639 && !conn->wait_ssl_try) /* redundant? */
1641 /* only retry once */
1642 conn->allow_ssl_try = false;
1643 /* Must drop the old connection */
1644 pqsecure_close(conn);
1645 closesocket(conn->sock);
1647 conn->status = CONNECTION_NEEDED;
1655 /* It is an authentication request. */
1656 /* Get the type of request. */
1657 if (pqGetInt((int *) &areq, 4, conn))
1659 /* We'll come back when there are more data */
1660 return PGRES_POLLING_READING;
1663 /* Get the password salt if there is one. */
1664 if (areq == AUTH_REQ_MD5)
1666 if (pqGetnchar(conn->md5Salt,
1667 sizeof(conn->md5Salt), conn))
1669 /* We'll come back when there are more data */
1670 return PGRES_POLLING_READING;
1673 if (areq == AUTH_REQ_CRYPT)
1675 if (pqGetnchar(conn->cryptSalt,
1676 sizeof(conn->cryptSalt), conn))
1678 /* We'll come back when there are more data */
1679 return PGRES_POLLING_READING;
1682 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1685 * Continue GSSAPI/SSPI authentication
1687 if (areq == AUTH_REQ_GSS_CONT)
1689 int llen = msgLength - 4;
1692 * We can be called repeatedly for the same buffer. Avoid
1693 * re-allocating the buffer in this case - just re-use the
1696 if (llen != conn->ginbuf.length)
1698 if (conn->ginbuf.value)
1699 free(conn->ginbuf.value);
1701 conn->ginbuf.length = llen;
1702 conn->ginbuf.value = malloc(llen);
1703 if (!conn->ginbuf.value)
1705 printfPQExpBuffer(&conn->errorMessage,
1706 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1712 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1714 /* We'll come back when there is more data. */
1715 return PGRES_POLLING_READING;
1721 * OK, we successfully read the message; mark data consumed
1723 conn->inStart = conn->inCursor;
1725 /* Respond to the request if necessary. */
1728 * Note that conn->pghost must be non-NULL if we are going to
1729 * avoid the Kerberos code doing a hostname look-up.
1732 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1734 conn->errorMessage.len = strlen(conn->errorMessage.data);
1737 conn->errorMessage.len = strlen(conn->errorMessage.data);
1740 * Just make sure that any data sent by pg_fe_sendauth is
1741 * flushed out. Although this theoretically could block, it
1742 * really shouldn't since we don't send large auth responses.
1747 if (areq == AUTH_REQ_OK)
1749 /* We are done with authentication exchange */
1750 conn->status = CONNECTION_AUTH_OK;
1753 * Set asyncStatus so that PQsetResult will think that
1754 * what comes back next is the result of a query. See
1757 conn->asyncStatus = PGASYNC_BUSY;
1760 /* Look to see if we have more data yet. */
1764 case CONNECTION_AUTH_OK:
1767 * Now we expect to hear from the backend. A ReadyForQuery
1768 * message indicates that startup is successful, but we might
1769 * also get an Error message indicating failure. (Notice
1770 * messages indicating nonfatal warnings are also allowed by
1771 * the protocol, as are ParameterStatus and BackendKeyData
1772 * messages.) Easiest way to handle this is to let
1773 * PQgetResult() read the messages. We just have to fake it
1774 * out about the state of the connection, by setting
1775 * asyncStatus = PGASYNC_BUSY (done above).
1779 return PGRES_POLLING_READING;
1781 res = PQgetResult(conn);
1784 * NULL return indicating we have gone to IDLE state is
1789 if (res->resultStatus != PGRES_FATAL_ERROR)
1790 printfPQExpBuffer(&conn->errorMessage,
1791 libpq_gettext("unexpected message from server during startup\n"));
1794 * if the resultStatus is FATAL, then conn->errorMessage
1795 * already has a copy of the error; needn't copy it back.
1796 * But add a newline if it's not there already, since
1797 * postmaster error messages may not have one.
1799 if (conn->errorMessage.len <= 0 ||
1800 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1801 appendPQExpBufferChar(&conn->errorMessage, '\n');
1806 /* We can release the address list now. */
1807 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1808 conn->addrlist = NULL;
1809 conn->addr_cur = NULL;
1811 /* Fire up post-connection housekeeping if needed */
1812 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1814 conn->status = CONNECTION_SETENV;
1815 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1816 conn->next_eo = EnvironmentOptions;
1817 return PGRES_POLLING_WRITING;
1820 /* Otherwise, we are open for business! */
1821 conn->status = CONNECTION_OK;
1822 return PGRES_POLLING_OK;
1825 case CONNECTION_SETENV:
1828 * Do post-connection housekeeping (only needed in protocol 2.0).
1830 * We pretend that the connection is OK for the duration of these
1833 conn->status = CONNECTION_OK;
1835 switch (pqSetenvPoll(conn))
1837 case PGRES_POLLING_OK: /* Success */
1840 case PGRES_POLLING_READING: /* Still going */
1841 conn->status = CONNECTION_SETENV;
1842 return PGRES_POLLING_READING;
1844 case PGRES_POLLING_WRITING: /* Still going */
1845 conn->status = CONNECTION_SETENV;
1846 return PGRES_POLLING_WRITING;
1852 /* We are open for business! */
1853 conn->status = CONNECTION_OK;
1854 return PGRES_POLLING_OK;
1857 printfPQExpBuffer(&conn->errorMessage,
1859 "invalid connection state %c, "
1860 "probably indicative of memory corruption\n"
1871 * We used to close the socket at this point, but that makes it awkward
1872 * for those above us if they wish to remove this socket from their own
1873 * records (an fd_set for example). We'll just have this socket closed
1874 * when PQfinish is called (which is compulsory even after an error, since
1875 * the connection structure must be freed).
1877 conn->status = CONNECTION_BAD;
1878 return PGRES_POLLING_FAILED;
1884 * - create a PGconn data structure with (as yet) no interesting data
1887 makeEmptyPGconn(void)
1894 * Make sure socket support is up and running.
1898 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1903 conn = (PGconn *) malloc(sizeof(PGconn));
1912 /* Zero all pointers and booleans */
1913 MemSet(conn, 0, sizeof(PGconn));
1915 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1916 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1917 conn->status = CONNECTION_BAD;
1918 conn->asyncStatus = PGASYNC_IDLE;
1919 conn->xactStatus = PQTRANS_IDLE;
1920 conn->options_valid = false;
1921 conn->nonblocking = false;
1922 conn->setenv_state = SETENV_STATE_IDLE;
1923 conn->client_encoding = PG_SQL_ASCII;
1924 conn->std_strings = false; /* unless server says differently */
1925 conn->verbosity = PQERRORS_DEFAULT;
1927 conn->password_needed = false;
1929 conn->allow_ssl_try = true;
1930 conn->wait_ssl_try = false;
1934 * We try to send at least 8K at a time, which is the usual size of pipe
1935 * buffers on Unix systems. That way, when we are sending a large amount
1936 * of data, we avoid incurring extra kernel context swaps for partial
1937 * bufferloads. The output buffer is initially made 16K in size, and we
1938 * try to dump it after accumulating 8K.
1940 * With the same goal of minimizing context swaps, the input buffer will
1941 * be enlarged anytime it has less than 8K free, so we initially allocate
1944 conn->inBufSize = 16 * 1024;
1945 conn->inBuffer = (char *) malloc(conn->inBufSize);
1946 conn->outBufSize = 16 * 1024;
1947 conn->outBuffer = (char *) malloc(conn->outBufSize);
1948 initPQExpBuffer(&conn->errorMessage);
1949 initPQExpBuffer(&conn->workBuffer);
1951 if (conn->inBuffer == NULL ||
1952 conn->outBuffer == NULL ||
1953 conn->errorMessage.data == NULL ||
1954 conn->workBuffer.data == NULL)
1956 /* out of memory already :-( */
1966 * - free an idle (closed) PGconn data structure
1968 * NOTE: this should not overlap any functionality with closePGconn().
1969 * Clearing/resetting of transient state belongs there; what we do here is
1970 * release data that is to be held for the life of the PGconn structure.
1971 * If a value ought to be cleared/freed during PQreset(), do it there not here.
1974 freePGconn(PGconn *conn)
1978 if (conn->pghostaddr)
1979 free(conn->pghostaddr);
1982 if (conn->pgunixsocket)
1983 free(conn->pgunixsocket);
1986 if (conn->connect_timeout)
1987 free(conn->connect_timeout);
1988 if (conn->pgoptions)
1989 free(conn->pgoptions);
1997 free(conn->sslmode);
1998 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1999 if (conn->krbsrvname)
2000 free(conn->krbsrvname);
2002 /* Note that conn->Pfdebug is not ours to close or free */
2003 if (conn->last_query)
2004 free(conn->last_query);
2006 free(conn->inBuffer);
2007 if (conn->outBuffer)
2008 free(conn->outBuffer);
2009 termPQExpBuffer(&conn->errorMessage);
2010 termPQExpBuffer(&conn->workBuffer);
2021 * - properly close a connection to the backend
2023 * This should reset or release all transient state, but NOT the connection
2024 * parameters. On exit, the PGconn should be in condition to start a fresh
2025 * connection with the same parameters (see PQreset()).
2028 closePGconn(PGconn *conn)
2031 pgParameterStatus *pstatus;
2034 * Note that the protocol doesn't allow us to send Terminate messages
2035 * during the startup phase.
2037 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2040 * Try to send "close connection" message to backend. Ignore any
2043 pqPutMsgStart('X', false, conn);
2049 * Must reset the blocking status so a possible reconnect will work.
2051 * Don't call PQsetnonblocking() because it will fail if it's unable to
2052 * flush the connection.
2054 conn->nonblocking = FALSE;
2057 * Close the connection, reset all transient state, flush I/O buffers.
2059 if (conn->sock >= 0)
2061 pqsecure_close(conn);
2062 closesocket(conn->sock);
2065 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2067 conn->asyncStatus = PGASYNC_IDLE;
2068 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2069 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2070 conn->addrlist = NULL;
2071 conn->addr_cur = NULL;
2072 notify = conn->notifyHead;
2073 while (notify != NULL)
2075 PGnotify *prev = notify;
2077 notify = notify->next;
2080 conn->notifyHead = conn->notifyTail = NULL;
2081 pstatus = conn->pstatus;
2082 while (pstatus != NULL)
2084 pgParameterStatus *prev = pstatus;
2086 pstatus = pstatus->next;
2089 conn->pstatus = NULL;
2090 if (conn->lobjfuncs)
2091 free(conn->lobjfuncs);
2092 conn->lobjfuncs = NULL;
2093 conn->inStart = conn->inCursor = conn->inEnd = 0;
2100 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2101 if (conn->gtarg_nam)
2102 gss_release_name(&min_s, &conn->gtarg_nam);
2103 if (conn->ginbuf.length)
2104 gss_release_buffer(&min_s, &conn->ginbuf);
2105 if (conn->goutbuf.length)
2106 gss_release_buffer(&min_s, &conn->goutbuf);
2110 if (conn->ginbuf.length)
2111 free(conn->ginbuf.value);
2112 conn->ginbuf.length = 0;
2113 conn->ginbuf.value = NULL;
2114 if (conn->sspitarget)
2115 free(conn->sspitarget);
2116 conn->sspitarget = NULL;
2119 FreeCredentialsHandle(conn->sspicred);
2120 free(conn->sspicred);
2121 conn->sspicred = NULL;
2125 DeleteSecurityContext(conn->sspictx);
2126 free(conn->sspictx);
2127 conn->sspictx = NULL;
2133 * PQfinish: properly close a connection to the backend. Also frees
2134 * the PGconn data structure so it shouldn't be re-used after this.
2137 PQfinish(PGconn *conn)
2147 * PQreset: resets the connection to the backend by closing the
2148 * existing connection and creating a new one.
2151 PQreset(PGconn *conn)
2157 if (connectDBStart(conn))
2158 (void) connectDBComplete(conn);
2165 * resets the connection to the backend
2166 * closes the existing connection and makes a new one
2167 * Returns 1 on success, 0 on failure.
2170 PQresetStart(PGconn *conn)
2176 return connectDBStart(conn);
2185 * resets the connection to the backend
2186 * closes the existing connection and makes a new one
2188 PostgresPollingStatusType
2189 PQresetPoll(PGconn *conn)
2192 return PQconnectPoll(conn);
2194 return PGRES_POLLING_FAILED;
2198 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2200 * A copy is needed to be able to cancel a running query from a different
2201 * thread. If the same structure is used all structure members would have
2202 * to be individually locked (if the entire structure was locked, it would
2203 * be impossible to cancel a synchronous query because the structure would
2204 * have to stay locked for the duration of the query).
2207 PQgetCancel(PGconn *conn)
2217 cancel = malloc(sizeof(PGcancel));
2221 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2222 cancel->be_pid = conn->be_pid;
2223 cancel->be_key = conn->be_key;
2228 /* PQfreeCancel: free a cancel structure */
2230 PQfreeCancel(PGcancel *cancel)
2238 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2239 * current operation.
2241 * The return value is TRUE if the cancel request was successfully
2242 * dispatched, FALSE if not (in which case an error message is available).
2243 * Note: successful dispatch is no guarantee that there will be any effect at
2244 * the backend. The application must read the operation result as usual.
2246 * CAUTION: we want this routine to be safely callable from a signal handler
2247 * (for example, an application might want to call it in a SIGINT handler).
2248 * This means we cannot use any C library routine that might be non-reentrant.
2249 * malloc/free are often non-reentrant, and anything that might call them is
2250 * just as dangerous. We avoid sprintf here for that reason. Building up
2251 * error messages with strcpy/strcat is tedious but should be quite safe.
2252 * We also save/restore errno in case the signal handler support doesn't.
2254 * internal_cancel() is an internal helper function to make code-sharing
2255 * between the two versions of the cancel function possible.
2258 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2259 char *errbuf, int errbufsize)
2261 int save_errno = SOCK_ERRNO;
2268 CancelRequestPacket cp;
2272 * We need to open a temporary connection to the postmaster. Do this with
2273 * only kernel calls.
2275 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2277 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2278 goto cancel_errReturn;
2281 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2284 if (SOCK_ERRNO == EINTR)
2285 /* Interrupted system call - we'll just try again */
2287 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2288 goto cancel_errReturn;
2292 * We needn't set nonblocking I/O or NODELAY options here.
2295 /* Create and send the cancel request packet. */
2297 crp.packetlen = htonl((uint32) sizeof(crp));
2298 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2299 crp.cp.backendPID = htonl(be_pid);
2300 crp.cp.cancelAuthCode = htonl(be_key);
2303 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2305 if (SOCK_ERRNO == EINTR)
2306 /* Interrupted system call - we'll just try again */
2308 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2309 goto cancel_errReturn;
2313 * Wait for the postmaster to close the connection, which indicates that
2314 * it's processed the request. Without this delay, we might issue another
2315 * command only to find that our cancel zaps that command instead of the
2316 * one we thought we were canceling. Note we don't actually expect this
2317 * read to obtain any data, we are just waiting for EOF to be signaled.
2320 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2322 if (SOCK_ERRNO == EINTR)
2323 /* Interrupted system call - we'll just try again */
2325 /* we ignore other error conditions */
2329 closesocket(tmpsock);
2330 SOCK_ERRNO_SET(save_errno);
2336 * Make sure we don't overflow the error buffer. Leave space for the \n at
2337 * the end, and for the terminating zero.
2339 maxlen = errbufsize - strlen(errbuf) - 2;
2342 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2344 strcat(errbuf, "\n");
2347 closesocket(tmpsock);
2348 SOCK_ERRNO_SET(save_errno);
2353 * PQcancel: request query cancel
2355 * Returns TRUE if able to send the cancel request, FALSE if not.
2357 * On failure, an error message is stored in *errbuf, which must be of size
2358 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2362 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2366 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2370 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2371 errbuf, errbufsize);
2375 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2377 * Returns TRUE if able to send the cancel request, FALSE if not.
2379 * On failure, the error message is saved in conn->errorMessage; this means
2380 * that this can't be used when there might be other active operations on
2381 * the connection object.
2383 * NOTE: error messages will be cut off at the current size of the
2384 * error message buffer, since we dare not try to expand conn->errorMessage!
2387 PQrequestCancel(PGconn *conn)
2391 /* Check we have an open connection */
2397 strlcpy(conn->errorMessage.data,
2398 "PQrequestCancel() -- connection is not open\n",
2399 conn->errorMessage.maxlen);
2400 conn->errorMessage.len = strlen(conn->errorMessage.data);
2405 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2406 conn->errorMessage.data, conn->errorMessage.maxlen);
2409 conn->errorMessage.len = strlen(conn->errorMessage.data);
2416 * pqPacketSend() -- convenience routine to send a message to server.
2418 * pack_type: the single-byte message type code. (Pass zero for startup
2419 * packets, which have no message type code.)
2421 * buf, buf_len: contents of message. The given length includes only what
2422 * is in buf; the message type and message length fields are added here.
2424 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2425 * SIDE_EFFECTS: may block.
2427 * Note: all messages sent with this routine have a length word, whether
2428 * it's protocol 2.0 or 3.0.
2431 pqPacketSend(PGconn *conn, char pack_type,
2432 const void *buf, size_t buf_len)
2434 /* Start the message. */
2435 if (pqPutMsgStart(pack_type, true, conn))
2436 return STATUS_ERROR;
2438 /* Send the message body. */
2439 if (pqPutnchar(buf, buf_len, conn))
2440 return STATUS_ERROR;
2442 /* Finish the message. */
2443 if (pqPutMsgEnd(conn))
2444 return STATUS_ERROR;
2446 /* Flush to ensure backend gets it. */
2448 return STATUS_ERROR;
2455 #define LDAP_URL "ldap://"
2456 #define LDAP_DEF_PORT 389
2457 #define PGLDAP_TIMEOUT 2
2459 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2460 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2466 * Search the LDAP URL passed as first argument, treat the result as a
2467 * string of connection options that are parsed and added to the array of
2468 * options passed as second argument.
2470 * LDAP URLs must conform to RFC 1959 without escape sequences.
2471 * ldap://host:port/dn?attributes?scope?filter?extensions
2474 * 0 if the lookup was successful,
2475 * 1 if the connection to the LDAP server could be established but
2476 * the search was unsuccessful,
2477 * 2 if a connection could not be established, and
2478 * 3 if a fatal error occurred.
2480 * An error message is returned in the third argument for return codes 1 and 3.
2483 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2484 PQExpBuffer errorMessage)
2486 int port = LDAP_DEF_PORT,
2507 char *attrs[2] = {NULL, NULL};
2511 struct berval **values;
2512 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2514 if ((url = strdup(purl)) == NULL)
2516 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2521 * Parse URL components, check for correctness. Basically, url has '\0'
2522 * placed at component boundaries and variables are pointed at each
2526 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2528 printfPQExpBuffer(errorMessage,
2529 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2535 hostname = url + strlen(LDAP_URL);
2536 if (*hostname == '/') /* no hostname? */
2537 hostname = "localhost"; /* the default */
2539 /* dn, "distinguished name" */
2540 p = strchr(url + strlen(LDAP_URL), '/');
2541 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2543 printfPQExpBuffer(errorMessage, libpq_gettext(
2544 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2548 *p = '\0'; /* terminate hostname */
2552 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2554 printfPQExpBuffer(errorMessage, libpq_gettext(
2555 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2563 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2565 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2573 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2575 printfPQExpBuffer(errorMessage,
2576 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2582 if ((p = strchr(filter, '?')) != NULL)
2586 if ((p1 = strchr(hostname, ':')) != NULL)
2593 lport = strtol(portstr, &endptr, 10);
2594 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2596 printfPQExpBuffer(errorMessage, libpq_gettext(
2597 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2604 /* Allow only one attribute */
2605 if (strchr(attrs[0], ',') != NULL)
2607 printfPQExpBuffer(errorMessage, libpq_gettext(
2608 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2614 if (pg_strcasecmp(scopestr, "base") == 0)
2615 scope = LDAP_SCOPE_BASE;
2616 else if (pg_strcasecmp(scopestr, "one") == 0)
2617 scope = LDAP_SCOPE_ONELEVEL;
2618 else if (pg_strcasecmp(scopestr, "sub") == 0)
2619 scope = LDAP_SCOPE_SUBTREE;
2622 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2627 /* initialize LDAP structure */
2628 if ((ld = ldap_init(hostname, port)) == NULL)
2630 printfPQExpBuffer(errorMessage,
2631 libpq_gettext("could not create LDAP structure\n"));
2637 * Initialize connection to the server. We do an explicit bind because we
2638 * want to return 2 if the bind fails.
2640 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2642 /* error in ldap_simple_bind() */
2648 /* wait some time for the connection to succeed */
2650 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2658 /* error in ldap_result() */
2667 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2672 printfPQExpBuffer(errorMessage,
2673 libpq_gettext("lookup on LDAP server failed: %s\n"),
2674 ldap_err2string(rc));
2680 /* complain if there was not exactly one result */
2681 if ((rc = ldap_count_entries(ld, res)) != 1)
2683 printfPQExpBuffer(errorMessage,
2684 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2685 : libpq_gettext("no entry found on LDAP lookup\n"));
2693 if ((entry = ldap_first_entry(ld, res)) == NULL)
2695 /* should never happen */
2696 printfPQExpBuffer(errorMessage,
2697 libpq_gettext("no entry found on LDAP lookup\n"));
2705 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2707 printfPQExpBuffer(errorMessage,
2708 libpq_gettext("attribute has no values on LDAP lookup\n"));
2718 if (values[0] == NULL)
2720 printfPQExpBuffer(errorMessage,
2721 libpq_gettext("attribute has no values on LDAP lookup\n"));
2722 ldap_value_free_len(values);
2727 /* concatenate values to a single string */
2728 for (size = 0, i = 0; values[i] != NULL; ++i)
2729 size += values[i]->bv_len + 1;
2730 if ((result = malloc(size + 1)) == NULL)
2732 printfPQExpBuffer(errorMessage,
2733 libpq_gettext("out of memory\n"));
2734 ldap_value_free_len(values);
2738 for (p = result, i = 0; values[i] != NULL; ++i)
2740 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2741 p += values[i]->bv_len;
2743 if (values[i + 1] == NULL)
2747 ldap_value_free_len(values);
2750 /* parse result string */
2751 oldstate = state = 0;
2752 for (p = result; *p != '\0'; ++p)
2756 case 0: /* between entries */
2757 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2763 case 1: /* in option name */
2764 if (ld_is_sp_tab(*p))
2769 else if (ld_is_nl_cr(*p))
2771 printfPQExpBuffer(errorMessage, libpq_gettext(
2772 "missing \"=\" after \"%s\" in connection info string\n"),
2782 case 2: /* after option name */
2787 else if (!ld_is_sp_tab(*p))
2789 printfPQExpBuffer(errorMessage, libpq_gettext(
2790 "missing \"=\" after \"%s\" in connection info string\n"),
2795 case 3: /* before option value */
2802 else if (ld_is_nl_cr(*p))
2804 optval = optname + strlen(optname); /* empty */
2807 else if (!ld_is_sp_tab(*p))
2813 case 4: /* in unquoted option value */
2814 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
2820 case 5: /* in quoted option value */
2826 else if (*p == '\\')
2831 case 6: /* in quoted option value after escape */
2837 if (state == 0 && oldstate != 0)
2839 found_keyword = false;
2840 for (i = 0; options[i].keyword; i++)
2842 if (strcmp(options[i].keyword, optname) == 0)
2844 if (options[i].val == NULL)
2845 options[i].val = strdup(optval);
2846 found_keyword = true;
2852 printfPQExpBuffer(errorMessage,
2853 libpq_gettext("invalid connection option \"%s\"\n"),
2863 if (state == 5 || state == 6)
2865 printfPQExpBuffer(errorMessage, libpq_gettext(
2866 "unterminated quoted string in connection info string\n"));
2874 #define MAXBUFSIZE 256
2877 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2879 char *service = conninfo_getval(options, "service");
2880 char serviceFile[MAXPGPATH];
2881 bool group_found = false;
2886 * We have to special-case the environment variable PGSERVICE here, since
2887 * this is and should be called before inserting environment defaults for
2888 * other connection options.
2890 if (service == NULL)
2891 service = getenv("PGSERVICE");
2894 * This could be used by any application so we can't use the binary
2895 * location to find our config files.
2897 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2898 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2900 if (service != NULL)
2903 char buf[MAXBUFSIZE],
2906 f = fopen(serviceFile, "r");
2909 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2914 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
2918 if (strlen(line) >= sizeof(buf) - 1)
2921 printfPQExpBuffer(errorMessage,
2922 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2928 /* ignore EOL at end of line */
2929 if (strlen(line) && line[strlen(line) - 1] == '\n')
2930 line[strlen(line) - 1] = 0;
2932 /* ignore leading blanks */
2933 while (*line && isspace((unsigned char) line[0]))
2936 /* ignore comments and empty lines */
2937 if (strlen(line) == 0 || line[0] == '#')
2940 /* Check for right groupname */
2945 /* group info already read */
2950 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2951 line[strlen(service) + 1] == ']')
2954 group_found = false;
2961 * Finally, we are in the right group and can parse the
2969 if (strncmp(line, "ldap", 4) == 0)
2971 int rc = ldapServiceLookup(line, options, errorMessage);
2973 /* if rc = 2, go on reading for fallback */
2990 val = strchr(line, '=');
2993 printfPQExpBuffer(errorMessage,
2994 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3003 * Set the parameter --- but don't override any previous
3006 found_keyword = false;
3007 for (i = 0; options[i].keyword; i++)
3009 if (strcmp(options[i].keyword, key) == 0)
3011 if (options[i].val == NULL)
3012 options[i].val = strdup(val);
3013 found_keyword = true;
3020 printfPQExpBuffer(errorMessage,
3021 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3039 * Conninfo parser routine
3041 * If successful, a malloc'd PQconninfoOption array is returned.
3042 * If not successful, NULL is returned and an error message is
3043 * left in errorMessage.
3044 * *password_from_string is set TRUE if we got a password from the
3045 * conninfo string, otherwise FALSE.
3047 static PQconninfoOption *
3048 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3049 bool *password_from_string)
3057 PQconninfoOption *options;
3058 PQconninfoOption *option;
3060 *password_from_string = false; /* default result */
3062 /* Make a working copy of PQconninfoOptions */
3063 options = malloc(sizeof(PQconninfoOptions));
3064 if (options == NULL)
3066 printfPQExpBuffer(errorMessage,
3067 libpq_gettext("out of memory\n"));
3070 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3072 /* Need a modifiable copy of the input string */
3073 if ((buf = strdup(conninfo)) == NULL)
3075 printfPQExpBuffer(errorMessage,
3076 libpq_gettext("out of memory\n"));
3077 PQconninfoFree(options);
3084 /* Skip blanks before the parameter name */
3085 if (isspace((unsigned char) *cp))
3091 /* Get the parameter name */
3097 if (isspace((unsigned char) *cp))
3102 if (!isspace((unsigned char) *cp))
3111 /* Check that there is a following '=' */
3114 printfPQExpBuffer(errorMessage,
3115 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3117 PQconninfoFree(options);
3123 /* Skip blanks after the '=' */
3126 if (!isspace((unsigned char) *cp))
3131 /* Get the parameter value */
3139 if (isspace((unsigned char) *cp))
3163 printfPQExpBuffer(errorMessage,
3164 libpq_gettext("unterminated quoted string in connection info string\n"));
3165 PQconninfoFree(options);
3187 * Now we have the name and the value. Search for the param record.
3189 for (option = options; option->keyword != NULL; option++)
3191 if (strcmp(option->keyword, pname) == 0)
3194 if (option->keyword == NULL)
3196 printfPQExpBuffer(errorMessage,
3197 libpq_gettext("invalid connection option \"%s\"\n"),
3199 PQconninfoFree(options);
3209 option->val = strdup(pval);
3212 printfPQExpBuffer(errorMessage,
3213 libpq_gettext("out of memory\n"));
3214 PQconninfoFree(options);
3220 * Special handling for password
3222 if (strcmp(option->keyword, "password") == 0)
3223 *password_from_string = (option->val[0] != '\0');
3226 /* Done with the modifiable input string */
3230 * If there's a service spec, use it to obtain any not-explicitly-given
3233 if (parseServiceInfo(options, errorMessage))
3235 PQconninfoFree(options);
3240 * Get the fallback resources for parameters not specified in the conninfo
3241 * string nor the service.
3243 for (option = options; option->keyword != NULL; option++)
3245 if (option->val != NULL)
3246 continue; /* Value was in conninfo or service */
3249 * Try to get the environment variable fallback
3251 if (option->envvar != NULL)
3253 if ((tmp = getenv(option->envvar)) != NULL)
3255 option->val = strdup(tmp);
3258 printfPQExpBuffer(errorMessage,
3259 libpq_gettext("out of memory\n"));
3260 PQconninfoFree(options);
3268 * No environment variable specified or this one isn't set - try
3271 if (option->compiled != NULL)
3273 option->val = strdup(option->compiled);
3276 printfPQExpBuffer(errorMessage,
3277 libpq_gettext("out of memory\n"));
3278 PQconninfoFree(options);
3285 * Special handling for user
3287 if (strcmp(option->keyword, "user") == 0)
3289 option->val = pg_fe_getauthname(errorMessage);
3299 conninfo_getval(PQconninfoOption *connOptions,
3300 const char *keyword)
3302 PQconninfoOption *option;
3304 for (option = connOptions; option->keyword != NULL; option++)
3306 if (strcmp(option->keyword, keyword) == 0)
3315 PQconninfoFree(PQconninfoOption *connOptions)
3317 PQconninfoOption *option;
3319 if (connOptions == NULL)
3322 for (option = connOptions; option->keyword != NULL; option++)
3324 if (option->val != NULL)
3331 /* =========== accessor functions for PGconn ========= */
3333 PQdb(const PGconn *conn)
3337 return conn->dbName;
3341 PQuser(const PGconn *conn)
3345 return conn->pguser;
3349 PQpass(const PGconn *conn)
3353 return conn->pgpass;
3357 PQhost(const PGconn *conn)
3361 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3365 PQport(const PGconn *conn)
3369 return conn->pgport;
3373 PQtty(const PGconn *conn)
3381 PQoptions(const PGconn *conn)
3385 return conn->pgoptions;
3389 PQstatus(const PGconn *conn)
3392 return CONNECTION_BAD;
3393 return conn->status;
3396 PGTransactionStatusType
3397 PQtransactionStatus(const PGconn *conn)
3399 if (!conn || conn->status != CONNECTION_OK)
3400 return PQTRANS_UNKNOWN;
3401 if (conn->asyncStatus != PGASYNC_IDLE)
3402 return PQTRANS_ACTIVE;
3403 return conn->xactStatus;
3407 PQparameterStatus(const PGconn *conn, const char *paramName)
3409 const pgParameterStatus *pstatus;
3411 if (!conn || !paramName)
3413 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3415 if (strcmp(pstatus->name, paramName) == 0)
3416 return pstatus->value;
3422 PQprotocolVersion(const PGconn *conn)
3426 if (conn->status == CONNECTION_BAD)
3428 return PG_PROTOCOL_MAJOR(conn->pversion);
3432 PQserverVersion(const PGconn *conn)
3436 if (conn->status == CONNECTION_BAD)
3438 return conn->sversion;
3442 PQerrorMessage(const PGconn *conn)
3445 return libpq_gettext("connection pointer is NULL\n");
3447 return conn->errorMessage.data;
3451 PQsocket(const PGconn *conn)
3459 PQbackendPID(const PGconn *conn)
3461 if (!conn || conn->status != CONNECTION_OK)
3463 return conn->be_pid;
3467 PQconnectionNeedsPassword(const PGconn *conn)
3471 if (conn->password_needed &&
3472 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
3479 PQconnectionUsedPassword(const PGconn *conn)
3483 if (conn->password_needed && conn->pgpass_from_client)
3490 PQclientEncoding(const PGconn *conn)
3492 if (!conn || conn->status != CONNECTION_OK)
3494 return conn->client_encoding;
3498 PQsetClientEncoding(PGconn *conn, const char *encoding)
3501 static const char query[] = "set client_encoding to '%s'";
3505 if (!conn || conn->status != CONNECTION_OK)
3511 /* check query buffer overflow */
3512 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3515 /* ok, now send a query */
3516 sprintf(qbuf, query, encoding);
3517 res = PQexec(conn, qbuf);
3521 if (res->resultStatus != PGRES_COMMAND_OK)
3526 * In protocol 2 we have to assume the setting will stick, and adjust
3527 * our state immediately. In protocol 3 and up we can rely on the
3528 * backend to report the parameter value, and we'll change state at
3531 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3532 pqSaveParameterStatus(conn, "client_encoding", encoding);
3533 status = 0; /* everything is ok */
3540 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3545 return PQERRORS_DEFAULT;
3546 old = conn->verbosity;
3547 conn->verbosity = verbosity;
3552 PQtrace(PGconn *conn, FILE *debug_port)
3557 conn->Pfdebug = debug_port;
3561 PQuntrace(PGconn *conn)
3567 fflush(conn->Pfdebug);
3568 conn->Pfdebug = NULL;
3573 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3575 PQnoticeReceiver old;
3580 old = conn->noticeHooks.noticeRec;
3583 conn->noticeHooks.noticeRec = proc;
3584 conn->noticeHooks.noticeRecArg = arg;
3590 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3592 PQnoticeProcessor old;
3597 old = conn->noticeHooks.noticeProc;
3600 conn->noticeHooks.noticeProc = proc;
3601 conn->noticeHooks.noticeProcArg = arg;
3607 * The default notice message receiver just gets the standard notice text
3608 * and sends it to the notice processor. This two-level setup exists
3609 * mostly for backwards compatibility; perhaps we should deprecate use of
3610 * PQsetNoticeProcessor?
3613 defaultNoticeReceiver(void *arg, const PGresult *res)
3615 (void) arg; /* not used */
3616 if (res->noticeHooks.noticeProc != NULL)
3617 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3618 PQresultErrorMessage(res));
3622 * The default notice message processor just prints the
3623 * message on stderr. Applications can override this if they
3624 * want the messages to go elsewhere (a window, for example).
3625 * Note that simply discarding notices is probably a bad idea.
3628 defaultNoticeProcessor(void *arg, const char *message)
3630 (void) arg; /* not used */
3631 /* Note: we expect the supplied string to end with a newline already. */
3632 fprintf(stderr, "%s", message);
3636 * returns a pointer to the next token or NULL if the current
3637 * token doesn't match
3640 pwdfMatchesString(char *buf, char *token)
3644 bool bslash = false;
3646 if (buf == NULL || token == NULL)
3654 if (*tbuf == '\\' && !bslash)
3659 if (*tbuf == ':' && *ttok == 0 && !bslash)
3675 /* Get a password from the password file. Return value is malloc'd. */
3677 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3680 char pgpassfile[MAXPGPATH];
3681 struct stat stat_buf;
3684 #define LINELEN NAMEDATALEN*5
3687 if (dbname == NULL || strlen(dbname) == 0)
3690 if (username == NULL || strlen(username) == 0)
3693 /* 'localhost' matches pghost of '' or the default socket directory */
3694 if (hostname == NULL)
3695 hostname = DefaultHost;
3696 else if (is_absolute_path(hostname))
3699 * We should probably use canonicalize_path(), but then we have to
3700 * bring path.c into libpq, and it doesn't seem worth it.
3702 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3703 hostname = DefaultHost;
3706 port = DEF_PGPORT_STR;
3708 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3709 /* use the literal path from the environment, if set */
3710 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3713 char homedir[MAXPGPATH];
3715 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3717 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3720 /* If password file cannot be opened, ignore it. */
3721 if (stat(pgpassfile, &stat_buf) == -1)
3726 if (!S_ISREG(stat_buf.st_mode))
3729 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3734 /* If password file is insecure, alert the user and ignore it. */
3735 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3738 libpq_gettext("WARNING: password file \"%s\" has world or group read access; permission should be u=rw (0600)\n"),
3745 * On Win32, the directory is protected, so we don't have to check the
3750 fp = fopen(pgpassfile, "r");
3760 fgets(buf, sizeof(buf), fp);
3766 /* Remove trailing newline */
3767 if (buf[len - 1] == '\n')
3770 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3771 (t = pwdfMatchesString(t, port)) == NULL ||
3772 (t = pwdfMatchesString(t, dbname)) == NULL ||
3773 (t = pwdfMatchesString(t, username)) == NULL)
3787 * Obtain user's home directory, return in given buffer
3789 * On Unix, this actually returns the user's home directory. On Windows
3790 * it returns the PostgreSQL-specific application data folder.
3792 * This is essentially the same as get_home_path(), but we don't use that
3793 * because we don't want to pull path.c into libpq (it pollutes application
3797 pqGetHomeDirectory(char *buf, int bufsize)
3800 char pwdbuf[BUFSIZ];
3801 struct passwd pwdstr;
3802 struct passwd *pwd = NULL;
3804 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3806 strlcpy(buf, pwd->pw_dir, bufsize);
3809 char tmppath[MAX_PATH];
3811 ZeroMemory(tmppath, sizeof(tmppath));
3812 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3814 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3820 * To keep the API consistent, the locking stubs are always provided, even
3821 * if they are not required.
3825 default_threadlock(int acquire)
3827 #ifdef ENABLE_THREAD_SAFETY
3829 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3831 static pthread_mutex_t singlethread_lock = NULL;
3832 static long mutex_initlock = 0;
3834 if (singlethread_lock == NULL)
3836 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3837 /* loop, another thread own the lock */ ;
3838 if (singlethread_lock == NULL)
3839 pthread_mutex_init(&singlethread_lock, NULL);
3840 InterlockedExchange(&mutex_initlock, 0);
3844 pthread_mutex_lock(&singlethread_lock);
3846 pthread_mutex_unlock(&singlethread_lock);
3851 PQregisterThreadLock(pgthreadlock_t newhandler)
3853 pgthreadlock_t prev = pg_g_threadlock;
3856 pg_g_threadlock = newhandler;
3858 pg_g_threadlock = default_threadlock;