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.367 2008/11/09 00:28:35 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"
212 "PGINTERVALSTYLE", "intervalstyle"
218 "PGCLIENTENCODING", "client_encoding"
220 /* internal performance-related settings */
230 static bool connectOptions1(PGconn *conn, const char *conninfo);
231 static bool connectOptions2(PGconn *conn);
232 static int connectDBStart(PGconn *conn);
233 static int connectDBComplete(PGconn *conn);
234 static PGconn *makeEmptyPGconn(void);
235 static void freePGconn(PGconn *conn);
236 static void closePGconn(PGconn *conn);
237 static PQconninfoOption *conninfo_parse(const char *conninfo,
238 PQExpBuffer errorMessage, bool use_defaults);
239 static char *conninfo_getval(PQconninfoOption *connOptions,
240 const char *keyword);
241 static void defaultNoticeReceiver(void *arg, const PGresult *res);
242 static void defaultNoticeProcessor(void *arg, const char *message);
243 static int parseServiceInfo(PQconninfoOption *options,
244 PQExpBuffer errorMessage);
245 static char *pwdfMatchesString(char *buf, char *token);
246 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
248 static void default_threadlock(int acquire);
251 /* global variable because fe-auth.c needs to access it */
252 pgthreadlock_t pg_g_threadlock = default_threadlock;
256 * Connecting to a Database
258 * There are now four different ways a user of this API can connect to the
259 * database. Two are not recommended for use in new code, because of their
260 * lack of extensibility with respect to the passing of options to the
261 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
264 * If it is desired to connect in a synchronous (blocking) manner, use the
265 * function PQconnectdb.
267 * To connect in an asynchronous (non-blocking) manner, use the functions
268 * PQconnectStart, and PQconnectPoll.
270 * Internally, the static functions connectDBStart, connectDBComplete
271 * are part of the connection procedure.
277 * establishes a connection to a postgres backend through the postmaster
278 * using connection information in a string.
280 * The conninfo string is a white-separated list of
284 * definitions. Value might be a single value containing no whitespaces or
285 * a single quoted string. If a single quote should appear anywhere in
286 * the value, it must be escaped with a backslash like \'
288 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
289 * if a memory allocation failed.
290 * If the status field of the connection returned is CONNECTION_BAD,
291 * then some fields may be null'ed out instead of having valid values.
293 * You should call PQfinish (if conn is not NULL) regardless of whether this
297 PQconnectdb(const char *conninfo)
299 PGconn *conn = PQconnectStart(conninfo);
301 if (conn && conn->status != CONNECTION_BAD)
302 (void) connectDBComplete(conn);
310 * Begins the establishment of a connection to a postgres backend through the
311 * postmaster using connection information in a string.
313 * See comment for PQconnectdb for the definition of the string format.
315 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
316 * you should not attempt to proceed with this connection. If the status
317 * field of the connection returned is CONNECTION_BAD, an error has
318 * occurred. In this case you should call PQfinish on the result, (perhaps
319 * inspecting the error message first). Other fields of the structure may not
320 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
321 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
324 * See PQconnectPoll for more info.
327 PQconnectStart(const char *conninfo)
332 * Allocate memory for the conn structure
334 conn = makeEmptyPGconn();
339 * Parse the conninfo string
341 if (!connectOptions1(conn, conninfo))
345 * Compute derived options
347 if (!connectOptions2(conn))
351 * Connect to the database
353 if (!connectDBStart(conn))
355 /* Just in case we failed to set it in connectDBStart */
356 conn->status = CONNECTION_BAD;
365 * Internal subroutine to set up connection parameters given an already-
366 * created PGconn and a conninfo string. Derived settings should be
367 * processed by calling connectOptions2 next. (We split them because
368 * PQsetdbLogin overrides defaults in between.)
370 * Returns true if OK, false if trouble (in which case errorMessage is set
371 * and so is conn->status).
374 connectOptions1(PGconn *conn, const char *conninfo)
376 PQconninfoOption *connOptions;
380 * Parse the conninfo string
382 connOptions = conninfo_parse(conninfo, &conn->errorMessage, true);
383 if (connOptions == NULL)
385 conn->status = CONNECTION_BAD;
386 /* errorMessage is already set */
391 * Move option values into conn structure
393 * Don't put anything cute here --- intelligence should be in
394 * connectOptions2 ...
396 * XXX: probably worth checking strdup() return value here...
398 tmp = conninfo_getval(connOptions, "hostaddr");
399 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
400 tmp = conninfo_getval(connOptions, "host");
401 conn->pghost = tmp ? strdup(tmp) : NULL;
402 tmp = conninfo_getval(connOptions, "port");
403 conn->pgport = tmp ? strdup(tmp) : NULL;
404 tmp = conninfo_getval(connOptions, "tty");
405 conn->pgtty = tmp ? strdup(tmp) : NULL;
406 tmp = conninfo_getval(connOptions, "options");
407 conn->pgoptions = tmp ? strdup(tmp) : NULL;
408 tmp = conninfo_getval(connOptions, "dbname");
409 conn->dbName = tmp ? strdup(tmp) : NULL;
410 tmp = conninfo_getval(connOptions, "user");
411 conn->pguser = tmp ? strdup(tmp) : NULL;
412 tmp = conninfo_getval(connOptions, "password");
413 conn->pgpass = tmp ? strdup(tmp) : NULL;
414 tmp = conninfo_getval(connOptions, "connect_timeout");
415 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
416 tmp = conninfo_getval(connOptions, "sslmode");
417 conn->sslmode = tmp ? strdup(tmp) : NULL;
419 tmp = conninfo_getval(connOptions, "requiressl");
420 if (tmp && tmp[0] == '1')
422 /* here warn that the requiressl option is deprecated? */
425 conn->sslmode = strdup("require");
428 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
429 tmp = conninfo_getval(connOptions, "krbsrvname");
430 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
432 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
433 tmp = conninfo_getval(connOptions, "gsslib");
434 conn->gsslib = tmp ? strdup(tmp) : NULL;
438 * Free the option info - all is in conn now
440 PQconninfoFree(connOptions);
448 * Compute derived connection options after absorbing all user-supplied info.
450 * Returns true if OK, false if trouble (in which case errorMessage is set
451 * and so is conn->status).
454 connectOptions2(PGconn *conn)
457 * If database name was not given, default it to equal user name
459 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
460 && conn->pguser != NULL)
464 conn->dbName = strdup(conn->pguser);
468 * Supply default password if none given
470 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
474 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
475 conn->dbName, conn->pguser);
476 if (conn->pgpass == NULL)
477 conn->pgpass = strdup(DefaultPassword);
481 * Allow unix socket specification in the host name
483 if (conn->pghost && is_absolute_path(conn->pghost))
485 if (conn->pgunixsocket)
486 free(conn->pgunixsocket);
487 conn->pgunixsocket = conn->pghost;
492 * validate sslmode option
496 if (strcmp(conn->sslmode, "disable") != 0
497 && strcmp(conn->sslmode, "allow") != 0
498 && strcmp(conn->sslmode, "prefer") != 0
499 && strcmp(conn->sslmode, "require") != 0)
501 conn->status = CONNECTION_BAD;
502 printfPQExpBuffer(&conn->errorMessage,
503 libpq_gettext("invalid sslmode value: \"%s\"\n"),
509 switch (conn->sslmode[0])
511 case 'a': /* "allow" */
512 case 'p': /* "prefer" */
515 * warn user that an SSL connection will never be negotiated
516 * since SSL was not compiled in?
520 case 'r': /* "require" */
521 conn->status = CONNECTION_BAD;
522 printfPQExpBuffer(&conn->errorMessage,
523 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
530 conn->sslmode = strdup(DefaultSSLMode);
533 * Only if we get this far is it appropriate to try to connect. (We need a
534 * state flag, rather than just the boolean result of this function, in
535 * case someone tries to PQreset() the PGconn.)
537 conn->options_valid = true;
545 * Parse an empty string like PQconnectdb() would do and return the
546 * resulting connection options array, ie, all the default values that are
547 * available from the environment etc. On error (eg out of memory),
550 * Using this function, an application may determine all possible options
551 * and their current default values.
553 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
554 * and should be freed when no longer needed via PQconninfoFree(). (In prior
555 * versions, the returned array was static, but that's not thread-safe.)
556 * Pre-7.0 applications that use this function will see a small memory leak
557 * until they are updated to call PQconninfoFree.
562 PQExpBufferData errorBuf;
563 PQconninfoOption *connOptions;
565 initPQExpBuffer(&errorBuf);
566 if (errorBuf.data == NULL)
567 return NULL; /* out of memory already :-( */
568 connOptions = conninfo_parse("", &errorBuf, true);
569 termPQExpBuffer(&errorBuf);
576 * establishes a connection to a postgres backend through the postmaster
577 * at the specified host and port.
579 * returns a PGconn* which is needed for all subsequent libpq calls
581 * if the status field of the connection returned is CONNECTION_BAD,
582 * then only the errorMessage is likely to be useful.
586 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
587 const char *pgtty, const char *dbName, const char *login,
593 * Allocate memory for the conn structure
595 conn = makeEmptyPGconn();
600 * If the dbName parameter contains '=', assume it's a conninfo string.
602 if (dbName && strchr(dbName, '='))
604 if (!connectOptions1(conn, dbName))
610 * Old-style path: first, parse an empty conninfo string in order to
611 * set up the same defaults that PQconnectdb() would use.
613 if (!connectOptions1(conn, ""))
616 /* Insert dbName parameter value into struct */
617 if (dbName && dbName[0] != '\0')
621 conn->dbName = strdup(dbName);
626 * Insert remaining parameters into struct, overriding defaults (as well
627 * as any conflicting data from dbName taken as a conninfo).
629 if (pghost && pghost[0] != '\0')
633 conn->pghost = strdup(pghost);
636 if (pgport && pgport[0] != '\0')
640 conn->pgport = strdup(pgport);
643 if (pgoptions && pgoptions[0] != '\0')
646 free(conn->pgoptions);
647 conn->pgoptions = strdup(pgoptions);
650 if (pgtty && pgtty[0] != '\0')
654 conn->pgtty = strdup(pgtty);
657 if (login && login[0] != '\0')
661 conn->pguser = strdup(login);
664 if (pwd && pwd[0] != '\0')
668 conn->pgpass = strdup(pwd);
672 * Compute derived options
674 if (!connectOptions2(conn))
678 * Connect to the database
680 if (connectDBStart(conn))
681 (void) connectDBComplete(conn);
689 * Sets the TCP_NODELAY socket option.
690 * Returns 1 if successful, 0 if not.
694 connectNoDelay(PGconn *conn)
699 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
705 appendPQExpBuffer(&conn->errorMessage,
706 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
707 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
717 * connectFailureMessage -
718 * create a friendly error message on connection failure.
722 connectFailureMessage(PGconn *conn, int errorno)
726 #ifdef HAVE_UNIX_SOCKETS
727 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
729 char service[NI_MAXHOST];
731 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
733 service, sizeof(service),
735 appendPQExpBuffer(&conn->errorMessage,
736 libpq_gettext("could not connect to server: %s\n"
737 "\tIs the server running locally and accepting\n"
738 "\tconnections on Unix domain socket \"%s\"?\n"),
739 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
743 #endif /* HAVE_UNIX_SOCKETS */
745 appendPQExpBuffer(&conn->errorMessage,
746 libpq_gettext("could not connect to server: %s\n"
747 "\tIs the server running on host \"%s\" and accepting\n"
748 "\tTCP/IP connections on port %s?\n"),
749 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
762 * Begin the process of making a connection to the backend.
764 * Returns 1 if successful, 0 if not.
768 connectDBStart(PGconn *conn)
772 struct addrinfo *addrs = NULL;
773 struct addrinfo hint;
780 if (!conn->options_valid)
781 goto connect_errReturn;
783 /* Ensure our buffers are empty */
784 conn->inStart = conn->inCursor = conn->inEnd = 0;
788 * Determine the parameters to pass to pg_getaddrinfo_all.
791 /* Initialize hint structure */
792 MemSet(&hint, 0, sizeof(hint));
793 hint.ai_socktype = SOCK_STREAM;
794 hint.ai_family = AF_UNSPEC;
796 /* Set up port number as a string */
797 if (conn->pgport != NULL && conn->pgport[0] != '\0')
798 portnum = atoi(conn->pgport);
800 portnum = DEF_PGPORT;
801 snprintf(portstr, sizeof(portstr), "%d", portnum);
803 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
805 /* Using pghostaddr avoids a hostname lookup */
806 node = conn->pghostaddr;
807 hint.ai_family = AF_UNSPEC;
808 hint.ai_flags = AI_NUMERICHOST;
810 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
812 /* Using pghost, so we have to look-up the hostname */
814 hint.ai_family = AF_UNSPEC;
818 #ifdef HAVE_UNIX_SOCKETS
819 /* pghostaddr and pghost are NULL, so use Unix domain socket */
821 hint.ai_family = AF_UNIX;
822 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
824 /* Without Unix sockets, default to localhost instead */
826 hint.ai_family = AF_UNSPEC;
827 #endif /* HAVE_UNIX_SOCKETS */
830 /* Use pg_getaddrinfo_all() to resolve the address */
831 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
835 appendPQExpBuffer(&conn->errorMessage,
836 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
837 node, gai_strerror(ret));
839 appendPQExpBuffer(&conn->errorMessage,
840 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
841 portstr, gai_strerror(ret));
843 pg_freeaddrinfo_all(hint.ai_family, addrs);
844 goto connect_errReturn;
848 /* setup values based on SSL mode */
849 if (conn->sslmode[0] == 'd') /* "disable" */
850 conn->allow_ssl_try = false;
851 else if (conn->sslmode[0] == 'a') /* "allow" */
852 conn->wait_ssl_try = true;
856 * Set up to try to connect, with protocol 3.0 as the first attempt.
858 conn->addrlist = addrs;
859 conn->addr_cur = addrs;
860 conn->addrlist_family = hint.ai_family;
861 conn->pversion = PG_PROTOCOL(3, 0);
862 conn->status = CONNECTION_NEEDED;
865 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
866 * so that it can easily be re-executed if needed again during the
867 * asynchronous startup process. However, we must run it once here,
868 * because callers expect a success return from this routine to mean that
869 * we are in PGRES_POLLING_WRITING connection state.
871 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
877 pqsecure_close(conn);
878 closesocket(conn->sock);
881 conn->status = CONNECTION_BAD;
889 * Block and complete a connection.
891 * Returns 1 on success, 0 on failure.
894 connectDBComplete(PGconn *conn)
896 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
897 time_t finish_time = ((time_t) -1);
899 if (conn == NULL || conn->status == CONNECTION_BAD)
903 * Set up a time limit, if connect_timeout isn't zero.
905 if (conn->connect_timeout != NULL)
907 int timeout = atoi(conn->connect_timeout);
912 * Rounding could cause connection to fail; need at least 2 secs
916 /* calculate the finish time based on start + timeout */
917 finish_time = time(NULL) + timeout;
924 * Wait, if necessary. Note that the initial state (just after
925 * PQconnectStart) is to wait for the socket to select for writing.
929 case PGRES_POLLING_OK:
930 /* Reset stored error messages since we now have a working connection */
931 resetPQExpBuffer(&conn->errorMessage);
932 return 1; /* success! */
934 case PGRES_POLLING_READING:
935 if (pqWaitTimed(1, 0, conn, finish_time))
937 conn->status = CONNECTION_BAD;
942 case PGRES_POLLING_WRITING:
943 if (pqWaitTimed(0, 1, conn, finish_time))
945 conn->status = CONNECTION_BAD;
951 /* Just in case we failed to set it in PQconnectPoll */
952 conn->status = CONNECTION_BAD;
957 * Now try to advance the state machine.
959 flag = PQconnectPoll(conn);
966 * Poll an asynchronous connection.
968 * Returns a PostgresPollingStatusType.
969 * Before calling this function, use select(2) to determine when data
972 * You must call PQfinish whether or not this fails.
974 * This function and PQconnectStart are intended to allow connections to be
975 * made without blocking the execution of your program on remote I/O. However,
976 * there are a number of caveats:
978 * o If you call PQtrace, ensure that the stream object into which you trace
980 * o If you do not supply an IP address for the remote host (i.e. you
981 * supply a host name instead) then PQconnectStart will block on
982 * gethostbyname. You will be fine if using Unix sockets (i.e. by
983 * supplying neither a host name nor a host address).
984 * o If your backend wants to use Kerberos authentication then you must
985 * supply both a host name and a host address, otherwise this function
986 * may block on gethostname.
990 PostgresPollingStatusType
991 PQconnectPoll(PGconn *conn)
997 return PGRES_POLLING_FAILED;
999 /* Get the new data */
1000 switch (conn->status)
1003 * We really shouldn't have been polled in these two cases, but we
1006 case CONNECTION_BAD:
1007 return PGRES_POLLING_FAILED;
1009 return PGRES_POLLING_OK;
1011 /* These are reading states */
1012 case CONNECTION_AWAITING_RESPONSE:
1013 case CONNECTION_AUTH_OK:
1015 /* Load waiting data */
1016 int n = pqReadData(conn);
1021 return PGRES_POLLING_READING;
1026 /* These are writing states, so we just proceed. */
1027 case CONNECTION_STARTED:
1028 case CONNECTION_MADE:
1031 /* We allow pqSetenvPoll to decide whether to proceed. */
1032 case CONNECTION_SETENV:
1035 /* Special cases: proceed without waiting. */
1036 case CONNECTION_SSL_STARTUP:
1037 case CONNECTION_NEEDED:
1041 appendPQExpBuffer(&conn->errorMessage,
1043 "invalid connection state, "
1044 "probably indicative of memory corruption\n"
1050 keep_going: /* We will come back to here until there is
1051 * nothing left to do. */
1052 switch (conn->status)
1054 case CONNECTION_NEEDED:
1057 * Try to initiate a connection to one of the addresses
1058 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1059 * next one to try. We fail when we run out of addresses
1060 * (reporting the error returned for the *last* alternative,
1061 * which may not be what users expect :-().
1063 while (conn->addr_cur != NULL)
1065 struct addrinfo *addr_cur = conn->addr_cur;
1067 /* Remember current address for possible error msg */
1068 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1069 addr_cur->ai_addrlen);
1070 conn->raddr.salen = addr_cur->ai_addrlen;
1073 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1077 * ignore socket() failure if we have more addresses
1080 if (addr_cur->ai_next != NULL)
1082 conn->addr_cur = addr_cur->ai_next;
1085 appendPQExpBuffer(&conn->errorMessage,
1086 libpq_gettext("could not create socket: %s\n"),
1087 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1092 * Select socket options: no delay of outgoing data for
1093 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1096 if (!IS_AF_UNIX(addr_cur->ai_family))
1098 if (!connectNoDelay(conn))
1100 closesocket(conn->sock);
1102 conn->addr_cur = addr_cur->ai_next;
1106 if (!pg_set_noblock(conn->sock))
1108 appendPQExpBuffer(&conn->errorMessage,
1109 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1110 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1111 closesocket(conn->sock);
1113 conn->addr_cur = addr_cur->ai_next;
1118 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1120 appendPQExpBuffer(&conn->errorMessage,
1121 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1122 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1123 closesocket(conn->sock);
1125 conn->addr_cur = addr_cur->ai_next;
1128 #endif /* F_SETFD */
1131 * Start/make connection. This should not block, since we
1132 * are in nonblock mode. If it does, well, too bad.
1134 if (connect(conn->sock, addr_cur->ai_addr,
1135 addr_cur->ai_addrlen) < 0)
1137 if (SOCK_ERRNO == EINPROGRESS ||
1138 SOCK_ERRNO == EWOULDBLOCK ||
1139 SOCK_ERRNO == EINTR ||
1143 * This is fine - we're in non-blocking mode, and
1144 * the connection is in progress. Tell caller to
1145 * wait for write-ready on socket.
1147 conn->status = CONNECTION_STARTED;
1148 return PGRES_POLLING_WRITING;
1150 /* otherwise, trouble */
1155 * Hm, we're connected already --- seems the "nonblock
1156 * connection" wasn't. Advance the state machine and
1157 * go do the next stuff.
1159 conn->status = CONNECTION_STARTED;
1164 * This connection failed --- set up error report, then
1165 * close socket (do it this way in case close() affects
1166 * the value of errno...). We will ignore the connect()
1167 * failure and keep going if there are more addresses.
1169 connectFailureMessage(conn, SOCK_ERRNO);
1170 if (conn->sock >= 0)
1172 closesocket(conn->sock);
1177 * Try the next address, if any.
1179 conn->addr_cur = addr_cur->ai_next;
1180 } /* loop over addresses */
1183 * Ooops, no more addresses. An appropriate error message is
1184 * already set up, so just set the right status.
1189 case CONNECTION_STARTED:
1192 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1195 * Write ready, since we've made it here, so the connection
1196 * has been made ... or has failed.
1200 * Now check (using getsockopt) that there is not an error
1201 * state waiting for us on the socket.
1204 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1205 (char *) &optval, &optlen) == -1)
1207 appendPQExpBuffer(&conn->errorMessage,
1208 libpq_gettext("could not get socket error status: %s\n"),
1209 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1212 else if (optval != 0)
1215 * When using a nonblocking connect, we will typically see
1216 * connect failures at this point, so provide a friendly
1219 connectFailureMessage(conn, optval);
1222 * If more addresses remain, keep trying, just as in the
1223 * case where connect() returned failure immediately.
1225 if (conn->addr_cur->ai_next != NULL)
1227 if (conn->sock >= 0)
1229 closesocket(conn->sock);
1232 conn->addr_cur = conn->addr_cur->ai_next;
1233 conn->status = CONNECTION_NEEDED;
1239 /* Fill in the client address */
1240 conn->laddr.salen = sizeof(conn->laddr.addr);
1241 if (getsockname(conn->sock,
1242 (struct sockaddr *) & conn->laddr.addr,
1243 &conn->laddr.salen) < 0)
1245 appendPQExpBuffer(&conn->errorMessage,
1246 libpq_gettext("could not get client address from socket: %s\n"),
1247 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1252 * Make sure we can write before advancing to next step.
1254 conn->status = CONNECTION_MADE;
1255 return PGRES_POLLING_WRITING;
1258 case CONNECTION_MADE:
1266 * If SSL is enabled and we haven't already got it running,
1267 * request it instead of sending the startup message.
1269 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1271 /* Don't bother requesting SSL over a Unix socket */
1272 conn->allow_ssl_try = false;
1274 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1280 * Send the SSL request packet.
1282 * Theoretically, this could block, but it really
1283 * shouldn't since we only got here if the socket is
1286 pv = htonl(NEGOTIATE_SSL_CODE);
1287 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1289 appendPQExpBuffer(&conn->errorMessage,
1290 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1291 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1294 /* Ok, wait for response */
1295 conn->status = CONNECTION_SSL_STARTUP;
1296 return PGRES_POLLING_READING;
1298 #endif /* USE_SSL */
1301 * Build the startup packet.
1303 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1304 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1305 EnvironmentOptions);
1307 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1308 EnvironmentOptions);
1311 /* will not appendbuffer here, since it's likely to also run out of memory */
1312 printfPQExpBuffer(&conn->errorMessage,
1313 libpq_gettext("out of memory\n"));
1318 * Send the startup packet.
1320 * Theoretically, this could block, but it really shouldn't
1321 * since we only got here if the socket is write-ready.
1323 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1325 appendPQExpBuffer(&conn->errorMessage,
1326 libpq_gettext("could not send startup packet: %s\n"),
1327 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1334 conn->status = CONNECTION_AWAITING_RESPONSE;
1335 return PGRES_POLLING_READING;
1339 * Handle SSL negotiation: wait for postmaster messages and
1340 * respond as necessary.
1342 case CONNECTION_SSL_STARTUP:
1345 PostgresPollingStatusType pollres;
1348 * On first time through, get the postmaster's response to our
1349 * SSL negotiation packet.
1351 if (conn->ssl == NULL)
1354 * We use pqReadData here since it has the logic to
1355 * distinguish no-data-yet from connection closure. Since
1356 * conn->ssl isn't set, a plain recv() will occur.
1361 rdresult = pqReadData(conn);
1364 /* errorMessage is already filled in */
1369 /* caller failed to wait for data */
1370 return PGRES_POLLING_READING;
1372 if (pqGetc(&SSLok, conn) < 0)
1374 /* should not happen really */
1375 return PGRES_POLLING_READING;
1377 /* mark byte consumed */
1378 conn->inStart = conn->inCursor;
1381 /* Set up global SSL state if required */
1382 if (pqsecure_initialize(conn) == -1)
1385 else if (SSLok == 'N')
1387 if (conn->sslmode[0] == 'r') /* "require" */
1389 /* Require SSL, but server does not want it */
1390 appendPQExpBuffer(&conn->errorMessage,
1391 libpq_gettext("server does not support SSL, but SSL was required\n"));
1394 /* Otherwise, proceed with normal startup */
1395 conn->allow_ssl_try = false;
1396 conn->status = CONNECTION_MADE;
1397 return PGRES_POLLING_WRITING;
1399 else if (SSLok == 'E')
1401 /* Received error - probably protocol mismatch */
1403 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1404 if (conn->sslmode[0] == 'r') /* "require" */
1406 /* Require SSL, but server is too old */
1407 appendPQExpBuffer(&conn->errorMessage,
1408 libpq_gettext("server does not support SSL, but SSL was required\n"));
1411 /* Otherwise, try again without SSL */
1412 conn->allow_ssl_try = false;
1413 /* Assume it ain't gonna handle protocol 3, either */
1414 conn->pversion = PG_PROTOCOL(2, 0);
1415 /* Must drop the old connection */
1416 closesocket(conn->sock);
1418 conn->status = CONNECTION_NEEDED;
1423 appendPQExpBuffer(&conn->errorMessage,
1424 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1431 * Begin or continue the SSL negotiation process.
1433 pollres = pqsecure_open_client(conn);
1434 if (pollres == PGRES_POLLING_OK)
1436 /* SSL handshake done, ready to send startup packet */
1437 conn->status = CONNECTION_MADE;
1438 return PGRES_POLLING_WRITING;
1440 if (pollres == PGRES_POLLING_FAILED)
1443 * Failed ... if sslmode is "prefer" then do a non-SSL
1446 if (conn->sslmode[0] == 'p' /* "prefer" */
1447 && conn->allow_ssl_try /* redundant? */
1448 && !conn->wait_ssl_try) /* redundant? */
1450 /* only retry once */
1451 conn->allow_ssl_try = false;
1452 /* Must drop the old connection */
1453 closesocket(conn->sock);
1455 conn->status = CONNECTION_NEEDED;
1460 #else /* !USE_SSL */
1461 /* can't get here */
1463 #endif /* USE_SSL */
1467 * Handle authentication exchange: wait for postmaster messages
1468 * and respond as necessary.
1470 case CONNECTION_AWAITING_RESPONSE:
1478 * Scan the message from current point (note that if we find
1479 * the message is incomplete, we will return without advancing
1480 * inStart, and resume here next time).
1482 conn->inCursor = conn->inStart;
1484 /* Read type byte */
1485 if (pqGetc(&beresp, conn))
1487 /* We'll come back when there is more data */
1488 return PGRES_POLLING_READING;
1492 * Validate message type: we expect only an authentication
1493 * request or an error here. Anything else probably means
1494 * it's not Postgres on the other end at all.
1496 if (!(beresp == 'R' || beresp == 'E'))
1498 appendPQExpBuffer(&conn->errorMessage,
1500 "expected authentication request from "
1501 "server, but received %c\n"),
1506 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1508 /* Read message length word */
1509 if (pqGetInt(&msgLength, 4, conn))
1511 /* We'll come back when there is more data */
1512 return PGRES_POLLING_READING;
1517 /* Set phony message length to disable checks below */
1522 * Try to validate message length before using it.
1523 * Authentication requests can't be very large, although GSS
1524 * auth requests may not be that small. Errors can be a
1525 * little larger, but not huge. If we see a large apparent
1526 * length in an error, it means we're really talking to a
1527 * pre-3.0-protocol server; cope.
1529 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1531 appendPQExpBuffer(&conn->errorMessage,
1533 "expected authentication request from "
1534 "server, but received %c\n"),
1539 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1541 /* Handle error from a pre-3.0 server */
1542 conn->inCursor = conn->inStart + 1; /* reread data */
1543 if (pqGets_append(&conn->errorMessage, conn))
1545 /* We'll come back when there is more data */
1546 return PGRES_POLLING_READING;
1548 /* OK, we read the message; mark data consumed */
1549 conn->inStart = conn->inCursor;
1552 * The postmaster typically won't end its message with a
1553 * newline, so add one to conform to libpq conventions.
1555 appendPQExpBufferChar(&conn->errorMessage, '\n');
1558 * If we tried to open the connection in 3.0 protocol,
1559 * fall back to 2.0 protocol.
1561 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1563 conn->pversion = PG_PROTOCOL(2, 0);
1564 /* Must drop the old connection */
1565 pqsecure_close(conn);
1566 closesocket(conn->sock);
1568 conn->status = CONNECTION_NEEDED;
1576 * Can't process if message body isn't all here yet.
1578 * (In protocol 2.0 case, we are assuming messages carry at
1579 * least 4 bytes of data.)
1582 avail = conn->inEnd - conn->inCursor;
1583 if (avail < msgLength)
1586 * Before returning, try to enlarge the input buffer if
1587 * needed to hold the whole message; see notes in
1590 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1593 /* We'll come back when there is more data */
1594 return PGRES_POLLING_READING;
1597 /* Handle errors. */
1600 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1602 if (pqGetErrorNotice3(conn, true))
1604 /* We'll come back when there is more data */
1605 return PGRES_POLLING_READING;
1610 if (pqGets_append(&conn->errorMessage, conn))
1612 /* We'll come back when there is more data */
1613 return PGRES_POLLING_READING;
1616 /* OK, we read the message; mark data consumed */
1617 conn->inStart = conn->inCursor;
1622 * if sslmode is "allow" and we haven't tried an SSL
1623 * connection already, then retry with an SSL connection
1625 if (conn->sslmode[0] == 'a' /* "allow" */
1626 && conn->ssl == NULL
1627 && conn->allow_ssl_try
1628 && conn->wait_ssl_try)
1630 /* only retry once */
1631 conn->wait_ssl_try = false;
1632 /* Must drop the old connection */
1633 closesocket(conn->sock);
1635 conn->status = CONNECTION_NEEDED;
1640 * if sslmode is "prefer" and we're in an SSL connection,
1641 * then do a non-SSL retry
1643 if (conn->sslmode[0] == 'p' /* "prefer" */
1645 && conn->allow_ssl_try /* redundant? */
1646 && !conn->wait_ssl_try) /* redundant? */
1648 /* only retry once */
1649 conn->allow_ssl_try = false;
1650 /* Must drop the old connection */
1651 pqsecure_close(conn);
1652 closesocket(conn->sock);
1654 conn->status = CONNECTION_NEEDED;
1662 /* It is an authentication request. */
1663 /* Get the type of request. */
1664 if (pqGetInt((int *) &areq, 4, conn))
1666 /* We'll come back when there are more data */
1667 return PGRES_POLLING_READING;
1670 /* Get the password salt if there is one. */
1671 if (areq == AUTH_REQ_MD5)
1673 if (pqGetnchar(conn->md5Salt,
1674 sizeof(conn->md5Salt), conn))
1676 /* We'll come back when there are more data */
1677 return PGRES_POLLING_READING;
1680 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1683 * Continue GSSAPI/SSPI authentication
1685 if (areq == AUTH_REQ_GSS_CONT)
1687 int llen = msgLength - 4;
1690 * We can be called repeatedly for the same buffer. Avoid
1691 * re-allocating the buffer in this case - just re-use the
1694 if (llen != conn->ginbuf.length)
1696 if (conn->ginbuf.value)
1697 free(conn->ginbuf.value);
1699 conn->ginbuf.length = llen;
1700 conn->ginbuf.value = malloc(llen);
1701 if (!conn->ginbuf.value)
1703 printfPQExpBuffer(&conn->errorMessage,
1704 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1710 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1712 /* We'll come back when there is more data. */
1713 return PGRES_POLLING_READING;
1719 * OK, we successfully read the message; mark data consumed
1721 conn->inStart = conn->inCursor;
1723 /* Respond to the request if necessary. */
1726 * Note that conn->pghost must be non-NULL if we are going to
1727 * avoid the Kerberos code doing a hostname look-up.
1730 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1732 conn->errorMessage.len = strlen(conn->errorMessage.data);
1735 conn->errorMessage.len = strlen(conn->errorMessage.data);
1738 * Just make sure that any data sent by pg_fe_sendauth is
1739 * flushed out. Although this theoretically could block, it
1740 * really shouldn't since we don't send large auth responses.
1745 if (areq == AUTH_REQ_OK)
1747 /* We are done with authentication exchange */
1748 conn->status = CONNECTION_AUTH_OK;
1751 * Set asyncStatus so that PQsetResult will think that
1752 * what comes back next is the result of a query. See
1755 conn->asyncStatus = PGASYNC_BUSY;
1758 /* Look to see if we have more data yet. */
1762 case CONNECTION_AUTH_OK:
1765 * Now we expect to hear from the backend. A ReadyForQuery
1766 * message indicates that startup is successful, but we might
1767 * also get an Error message indicating failure. (Notice
1768 * messages indicating nonfatal warnings are also allowed by
1769 * the protocol, as are ParameterStatus and BackendKeyData
1770 * messages.) Easiest way to handle this is to let
1771 * PQgetResult() read the messages. We just have to fake it
1772 * out about the state of the connection, by setting
1773 * asyncStatus = PGASYNC_BUSY (done above).
1777 return PGRES_POLLING_READING;
1779 res = PQgetResult(conn);
1782 * NULL return indicating we have gone to IDLE state is
1787 if (res->resultStatus != PGRES_FATAL_ERROR)
1788 appendPQExpBuffer(&conn->errorMessage,
1789 libpq_gettext("unexpected message from server during startup\n"));
1792 * if the resultStatus is FATAL, then conn->errorMessage
1793 * already has a copy of the error; needn't copy it back.
1794 * But add a newline if it's not there already, since
1795 * postmaster error messages may not have one.
1797 if (conn->errorMessage.len <= 0 ||
1798 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1799 appendPQExpBufferChar(&conn->errorMessage, '\n');
1804 /* We can release the address list now. */
1805 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1806 conn->addrlist = NULL;
1807 conn->addr_cur = NULL;
1809 /* Fire up post-connection housekeeping if needed */
1810 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1812 conn->status = CONNECTION_SETENV;
1813 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1814 conn->next_eo = EnvironmentOptions;
1815 return PGRES_POLLING_WRITING;
1818 /* Otherwise, we are open for business! */
1819 conn->status = CONNECTION_OK;
1820 return PGRES_POLLING_OK;
1823 case CONNECTION_SETENV:
1826 * Do post-connection housekeeping (only needed in protocol 2.0).
1828 * We pretend that the connection is OK for the duration of these
1831 conn->status = CONNECTION_OK;
1833 switch (pqSetenvPoll(conn))
1835 case PGRES_POLLING_OK: /* Success */
1838 case PGRES_POLLING_READING: /* Still going */
1839 conn->status = CONNECTION_SETENV;
1840 return PGRES_POLLING_READING;
1842 case PGRES_POLLING_WRITING: /* Still going */
1843 conn->status = CONNECTION_SETENV;
1844 return PGRES_POLLING_WRITING;
1850 /* We are open for business! */
1851 conn->status = CONNECTION_OK;
1852 return PGRES_POLLING_OK;
1855 appendPQExpBuffer(&conn->errorMessage,
1857 "invalid connection state %c, "
1858 "probably indicative of memory corruption\n"
1869 * We used to close the socket at this point, but that makes it awkward
1870 * for those above us if they wish to remove this socket from their own
1871 * records (an fd_set for example). We'll just have this socket closed
1872 * when PQfinish is called (which is compulsory even after an error, since
1873 * the connection structure must be freed).
1875 conn->status = CONNECTION_BAD;
1876 return PGRES_POLLING_FAILED;
1882 * - create a PGconn data structure with (as yet) no interesting data
1885 makeEmptyPGconn(void)
1892 * Make sure socket support is up and running.
1896 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1901 conn = (PGconn *) malloc(sizeof(PGconn));
1910 /* Zero all pointers and booleans */
1911 MemSet(conn, 0, sizeof(PGconn));
1913 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1914 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1915 conn->status = CONNECTION_BAD;
1916 conn->asyncStatus = PGASYNC_IDLE;
1917 conn->xactStatus = PQTRANS_IDLE;
1918 conn->options_valid = false;
1919 conn->nonblocking = false;
1920 conn->setenv_state = SETENV_STATE_IDLE;
1921 conn->client_encoding = PG_SQL_ASCII;
1922 conn->std_strings = false; /* unless server says differently */
1923 conn->verbosity = PQERRORS_DEFAULT;
1925 conn->password_needed = false;
1927 conn->allow_ssl_try = true;
1928 conn->wait_ssl_try = false;
1932 * We try to send at least 8K at a time, which is the usual size of pipe
1933 * buffers on Unix systems. That way, when we are sending a large amount
1934 * of data, we avoid incurring extra kernel context swaps for partial
1935 * bufferloads. The output buffer is initially made 16K in size, and we
1936 * try to dump it after accumulating 8K.
1938 * With the same goal of minimizing context swaps, the input buffer will
1939 * be enlarged anytime it has less than 8K free, so we initially allocate
1942 conn->inBufSize = 16 * 1024;
1943 conn->inBuffer = (char *) malloc(conn->inBufSize);
1944 conn->outBufSize = 16 * 1024;
1945 conn->outBuffer = (char *) malloc(conn->outBufSize);
1946 initPQExpBuffer(&conn->errorMessage);
1947 initPQExpBuffer(&conn->workBuffer);
1949 if (conn->inBuffer == NULL ||
1950 conn->outBuffer == NULL ||
1951 conn->errorMessage.data == NULL ||
1952 conn->workBuffer.data == NULL)
1954 /* out of memory already :-( */
1964 * - free an idle (closed) PGconn data structure
1966 * NOTE: this should not overlap any functionality with closePGconn().
1967 * Clearing/resetting of transient state belongs there; what we do here is
1968 * release data that is to be held for the life of the PGconn structure.
1969 * If a value ought to be cleared/freed during PQreset(), do it there not here.
1972 freePGconn(PGconn *conn)
1976 /* let any event procs clean up their state data */
1977 for (i = 0; i < conn->nEvents; i++)
1979 PGEventConnDestroy evt;
1982 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
1983 conn->events[i].passThrough);
1984 free(conn->events[i].name);
1991 if (conn->pghostaddr)
1992 free(conn->pghostaddr);
1995 if (conn->pgunixsocket)
1996 free(conn->pgunixsocket);
1999 if (conn->connect_timeout)
2000 free(conn->connect_timeout);
2001 if (conn->pgoptions)
2002 free(conn->pgoptions);
2010 free(conn->sslmode);
2011 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2012 if (conn->krbsrvname)
2013 free(conn->krbsrvname);
2015 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2019 /* Note that conn->Pfdebug is not ours to close or free */
2020 if (conn->last_query)
2021 free(conn->last_query);
2023 free(conn->inBuffer);
2024 if (conn->outBuffer)
2025 free(conn->outBuffer);
2026 termPQExpBuffer(&conn->errorMessage);
2027 termPQExpBuffer(&conn->workBuffer);
2038 * - properly close a connection to the backend
2040 * This should reset or release all transient state, but NOT the connection
2041 * parameters. On exit, the PGconn should be in condition to start a fresh
2042 * connection with the same parameters (see PQreset()).
2045 closePGconn(PGconn *conn)
2048 pgParameterStatus *pstatus;
2051 * Note that the protocol doesn't allow us to send Terminate messages
2052 * during the startup phase.
2054 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2057 * Try to send "close connection" message to backend. Ignore any
2060 pqPutMsgStart('X', false, conn);
2066 * Must reset the blocking status so a possible reconnect will work.
2068 * Don't call PQsetnonblocking() because it will fail if it's unable to
2069 * flush the connection.
2071 conn->nonblocking = FALSE;
2074 * Close the connection, reset all transient state, flush I/O buffers.
2076 if (conn->sock >= 0)
2078 pqsecure_close(conn);
2079 closesocket(conn->sock);
2082 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2084 conn->asyncStatus = PGASYNC_IDLE;
2085 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2086 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2087 conn->addrlist = NULL;
2088 conn->addr_cur = NULL;
2089 notify = conn->notifyHead;
2090 while (notify != NULL)
2092 PGnotify *prev = notify;
2094 notify = notify->next;
2097 conn->notifyHead = conn->notifyTail = NULL;
2098 pstatus = conn->pstatus;
2099 while (pstatus != NULL)
2101 pgParameterStatus *prev = pstatus;
2103 pstatus = pstatus->next;
2106 conn->pstatus = NULL;
2107 if (conn->lobjfuncs)
2108 free(conn->lobjfuncs);
2109 conn->lobjfuncs = NULL;
2110 conn->inStart = conn->inCursor = conn->inEnd = 0;
2117 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2118 if (conn->gtarg_nam)
2119 gss_release_name(&min_s, &conn->gtarg_nam);
2120 if (conn->ginbuf.length)
2121 gss_release_buffer(&min_s, &conn->ginbuf);
2122 if (conn->goutbuf.length)
2123 gss_release_buffer(&min_s, &conn->goutbuf);
2127 if (conn->ginbuf.length)
2128 free(conn->ginbuf.value);
2129 conn->ginbuf.length = 0;
2130 conn->ginbuf.value = NULL;
2131 if (conn->sspitarget)
2132 free(conn->sspitarget);
2133 conn->sspitarget = NULL;
2136 FreeCredentialsHandle(conn->sspicred);
2137 free(conn->sspicred);
2138 conn->sspicred = NULL;
2142 DeleteSecurityContext(conn->sspictx);
2143 free(conn->sspictx);
2144 conn->sspictx = NULL;
2150 * PQfinish: properly close a connection to the backend. Also frees
2151 * the PGconn data structure so it shouldn't be re-used after this.
2154 PQfinish(PGconn *conn)
2164 * PQreset: resets the connection to the backend by closing the
2165 * existing connection and creating a new one.
2168 PQreset(PGconn *conn)
2174 if (connectDBStart(conn) && connectDBComplete(conn))
2177 * Notify event procs of successful reset. We treat an event
2178 * proc failure as disabling the connection ... good idea?
2182 for (i = 0; i < conn->nEvents; i++)
2184 PGEventConnReset evt;
2187 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2188 conn->events[i].passThrough))
2190 conn->status = CONNECTION_BAD;
2191 printfPQExpBuffer(&conn->errorMessage,
2192 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2193 conn->events[i].name);
2204 * resets the connection to the backend
2205 * closes the existing connection and makes a new one
2206 * Returns 1 on success, 0 on failure.
2209 PQresetStart(PGconn *conn)
2215 return connectDBStart(conn);
2224 * resets the connection to the backend
2225 * closes the existing connection and makes a new one
2227 PostgresPollingStatusType
2228 PQresetPoll(PGconn *conn)
2232 PostgresPollingStatusType status = PQconnectPoll(conn);
2234 if (status == PGRES_POLLING_OK)
2237 * Notify event procs of successful reset. We treat an event
2238 * proc failure as disabling the connection ... good idea?
2242 for (i = 0; i < conn->nEvents; i++)
2244 PGEventConnReset evt;
2247 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2248 conn->events[i].passThrough))
2250 conn->status = CONNECTION_BAD;
2251 printfPQExpBuffer(&conn->errorMessage,
2252 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2253 conn->events[i].name);
2254 return PGRES_POLLING_FAILED;
2262 return PGRES_POLLING_FAILED;
2266 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2268 * A copy is needed to be able to cancel a running query from a different
2269 * thread. If the same structure is used all structure members would have
2270 * to be individually locked (if the entire structure was locked, it would
2271 * be impossible to cancel a synchronous query because the structure would
2272 * have to stay locked for the duration of the query).
2275 PQgetCancel(PGconn *conn)
2285 cancel = malloc(sizeof(PGcancel));
2289 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2290 cancel->be_pid = conn->be_pid;
2291 cancel->be_key = conn->be_key;
2296 /* PQfreeCancel: free a cancel structure */
2298 PQfreeCancel(PGcancel *cancel)
2306 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2307 * current operation.
2309 * The return value is TRUE if the cancel request was successfully
2310 * dispatched, FALSE if not (in which case an error message is available).
2311 * Note: successful dispatch is no guarantee that there will be any effect at
2312 * the backend. The application must read the operation result as usual.
2314 * CAUTION: we want this routine to be safely callable from a signal handler
2315 * (for example, an application might want to call it in a SIGINT handler).
2316 * This means we cannot use any C library routine that might be non-reentrant.
2317 * malloc/free are often non-reentrant, and anything that might call them is
2318 * just as dangerous. We avoid sprintf here for that reason. Building up
2319 * error messages with strcpy/strcat is tedious but should be quite safe.
2320 * We also save/restore errno in case the signal handler support doesn't.
2322 * internal_cancel() is an internal helper function to make code-sharing
2323 * between the two versions of the cancel function possible.
2326 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2327 char *errbuf, int errbufsize)
2329 int save_errno = SOCK_ERRNO;
2336 CancelRequestPacket cp;
2340 * We need to open a temporary connection to the postmaster. Do this with
2341 * only kernel calls.
2343 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2345 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2346 goto cancel_errReturn;
2349 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2352 if (SOCK_ERRNO == EINTR)
2353 /* Interrupted system call - we'll just try again */
2355 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2356 goto cancel_errReturn;
2360 * We needn't set nonblocking I/O or NODELAY options here.
2363 /* Create and send the cancel request packet. */
2365 crp.packetlen = htonl((uint32) sizeof(crp));
2366 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2367 crp.cp.backendPID = htonl(be_pid);
2368 crp.cp.cancelAuthCode = htonl(be_key);
2371 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2373 if (SOCK_ERRNO == EINTR)
2374 /* Interrupted system call - we'll just try again */
2376 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2377 goto cancel_errReturn;
2381 * Wait for the postmaster to close the connection, which indicates that
2382 * it's processed the request. Without this delay, we might issue another
2383 * command only to find that our cancel zaps that command instead of the
2384 * one we thought we were canceling. Note we don't actually expect this
2385 * read to obtain any data, we are just waiting for EOF to be signaled.
2388 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2390 if (SOCK_ERRNO == EINTR)
2391 /* Interrupted system call - we'll just try again */
2393 /* we ignore other error conditions */
2397 closesocket(tmpsock);
2398 SOCK_ERRNO_SET(save_errno);
2404 * Make sure we don't overflow the error buffer. Leave space for the \n at
2405 * the end, and for the terminating zero.
2407 maxlen = errbufsize - strlen(errbuf) - 2;
2410 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2412 strcat(errbuf, "\n");
2415 closesocket(tmpsock);
2416 SOCK_ERRNO_SET(save_errno);
2421 * PQcancel: request query cancel
2423 * Returns TRUE if able to send the cancel request, FALSE if not.
2425 * On failure, an error message is stored in *errbuf, which must be of size
2426 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2430 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2434 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2438 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2439 errbuf, errbufsize);
2443 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2445 * Returns TRUE if able to send the cancel request, FALSE if not.
2447 * On failure, the error message is saved in conn->errorMessage; this means
2448 * that this can't be used when there might be other active operations on
2449 * the connection object.
2451 * NOTE: error messages will be cut off at the current size of the
2452 * error message buffer, since we dare not try to expand conn->errorMessage!
2455 PQrequestCancel(PGconn *conn)
2459 /* Check we have an open connection */
2465 strlcpy(conn->errorMessage.data,
2466 "PQrequestCancel() -- connection is not open\n",
2467 conn->errorMessage.maxlen);
2468 conn->errorMessage.len = strlen(conn->errorMessage.data);
2473 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2474 conn->errorMessage.data, conn->errorMessage.maxlen);
2477 conn->errorMessage.len = strlen(conn->errorMessage.data);
2484 * pqPacketSend() -- convenience routine to send a message to server.
2486 * pack_type: the single-byte message type code. (Pass zero for startup
2487 * packets, which have no message type code.)
2489 * buf, buf_len: contents of message. The given length includes only what
2490 * is in buf; the message type and message length fields are added here.
2492 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2493 * SIDE_EFFECTS: may block.
2495 * Note: all messages sent with this routine have a length word, whether
2496 * it's protocol 2.0 or 3.0.
2499 pqPacketSend(PGconn *conn, char pack_type,
2500 const void *buf, size_t buf_len)
2502 /* Start the message. */
2503 if (pqPutMsgStart(pack_type, true, conn))
2504 return STATUS_ERROR;
2506 /* Send the message body. */
2507 if (pqPutnchar(buf, buf_len, conn))
2508 return STATUS_ERROR;
2510 /* Finish the message. */
2511 if (pqPutMsgEnd(conn))
2512 return STATUS_ERROR;
2514 /* Flush to ensure backend gets it. */
2516 return STATUS_ERROR;
2523 #define LDAP_URL "ldap://"
2524 #define LDAP_DEF_PORT 389
2525 #define PGLDAP_TIMEOUT 2
2527 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2528 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2534 * Search the LDAP URL passed as first argument, treat the result as a
2535 * string of connection options that are parsed and added to the array of
2536 * options passed as second argument.
2538 * LDAP URLs must conform to RFC 1959 without escape sequences.
2539 * ldap://host:port/dn?attributes?scope?filter?extensions
2542 * 0 if the lookup was successful,
2543 * 1 if the connection to the LDAP server could be established but
2544 * the search was unsuccessful,
2545 * 2 if a connection could not be established, and
2546 * 3 if a fatal error occurred.
2548 * An error message is returned in the third argument for return codes 1 and 3.
2551 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2552 PQExpBuffer errorMessage)
2554 int port = LDAP_DEF_PORT,
2575 char *attrs[2] = {NULL, NULL};
2579 struct berval **values;
2580 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2582 if ((url = strdup(purl)) == NULL)
2584 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2589 * Parse URL components, check for correctness. Basically, url has '\0'
2590 * placed at component boundaries and variables are pointed at each
2594 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2596 printfPQExpBuffer(errorMessage,
2597 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2603 hostname = url + strlen(LDAP_URL);
2604 if (*hostname == '/') /* no hostname? */
2605 hostname = "localhost"; /* the default */
2607 /* dn, "distinguished name" */
2608 p = strchr(url + strlen(LDAP_URL), '/');
2609 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2611 printfPQExpBuffer(errorMessage, libpq_gettext(
2612 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2616 *p = '\0'; /* terminate hostname */
2620 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2622 printfPQExpBuffer(errorMessage, libpq_gettext(
2623 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2631 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2633 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2641 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2643 printfPQExpBuffer(errorMessage,
2644 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2650 if ((p = strchr(filter, '?')) != NULL)
2654 if ((p1 = strchr(hostname, ':')) != NULL)
2661 lport = strtol(portstr, &endptr, 10);
2662 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2664 printfPQExpBuffer(errorMessage, libpq_gettext(
2665 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2672 /* Allow only one attribute */
2673 if (strchr(attrs[0], ',') != NULL)
2675 printfPQExpBuffer(errorMessage, libpq_gettext(
2676 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2682 if (pg_strcasecmp(scopestr, "base") == 0)
2683 scope = LDAP_SCOPE_BASE;
2684 else if (pg_strcasecmp(scopestr, "one") == 0)
2685 scope = LDAP_SCOPE_ONELEVEL;
2686 else if (pg_strcasecmp(scopestr, "sub") == 0)
2687 scope = LDAP_SCOPE_SUBTREE;
2690 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2695 /* initialize LDAP structure */
2696 if ((ld = ldap_init(hostname, port)) == NULL)
2698 printfPQExpBuffer(errorMessage,
2699 libpq_gettext("could not create LDAP structure\n"));
2705 * Initialize connection to the server. We do an explicit bind because we
2706 * want to return 2 if the bind fails.
2708 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2710 /* error in ldap_simple_bind() */
2716 /* wait some time for the connection to succeed */
2718 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2726 /* error in ldap_result() */
2735 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2740 printfPQExpBuffer(errorMessage,
2741 libpq_gettext("lookup on LDAP server failed: %s\n"),
2742 ldap_err2string(rc));
2748 /* complain if there was not exactly one result */
2749 if ((rc = ldap_count_entries(ld, res)) != 1)
2751 printfPQExpBuffer(errorMessage,
2752 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2753 : libpq_gettext("no entry found on LDAP lookup\n"));
2761 if ((entry = ldap_first_entry(ld, res)) == NULL)
2763 /* should never happen */
2764 printfPQExpBuffer(errorMessage,
2765 libpq_gettext("no entry found on LDAP lookup\n"));
2773 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2775 printfPQExpBuffer(errorMessage,
2776 libpq_gettext("attribute has no values on LDAP lookup\n"));
2786 if (values[0] == NULL)
2788 printfPQExpBuffer(errorMessage,
2789 libpq_gettext("attribute has no values on LDAP lookup\n"));
2790 ldap_value_free_len(values);
2795 /* concatenate values to a single string */
2796 for (size = 0, i = 0; values[i] != NULL; ++i)
2797 size += values[i]->bv_len + 1;
2798 if ((result = malloc(size + 1)) == NULL)
2800 printfPQExpBuffer(errorMessage,
2801 libpq_gettext("out of memory\n"));
2802 ldap_value_free_len(values);
2806 for (p = result, i = 0; values[i] != NULL; ++i)
2808 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2809 p += values[i]->bv_len;
2811 if (values[i + 1] == NULL)
2815 ldap_value_free_len(values);
2818 /* parse result string */
2819 oldstate = state = 0;
2820 for (p = result; *p != '\0'; ++p)
2824 case 0: /* between entries */
2825 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2831 case 1: /* in option name */
2832 if (ld_is_sp_tab(*p))
2837 else if (ld_is_nl_cr(*p))
2839 printfPQExpBuffer(errorMessage, libpq_gettext(
2840 "missing \"=\" after \"%s\" in connection info string\n"),
2850 case 2: /* after option name */
2855 else if (!ld_is_sp_tab(*p))
2857 printfPQExpBuffer(errorMessage, libpq_gettext(
2858 "missing \"=\" after \"%s\" in connection info string\n"),
2863 case 3: /* before option value */
2870 else if (ld_is_nl_cr(*p))
2872 optval = optname + strlen(optname); /* empty */
2875 else if (!ld_is_sp_tab(*p))
2881 case 4: /* in unquoted option value */
2882 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
2888 case 5: /* in quoted option value */
2894 else if (*p == '\\')
2899 case 6: /* in quoted option value after escape */
2905 if (state == 0 && oldstate != 0)
2907 found_keyword = false;
2908 for (i = 0; options[i].keyword; i++)
2910 if (strcmp(options[i].keyword, optname) == 0)
2912 if (options[i].val == NULL)
2913 options[i].val = strdup(optval);
2914 found_keyword = true;
2920 printfPQExpBuffer(errorMessage,
2921 libpq_gettext("invalid connection option \"%s\"\n"),
2931 if (state == 5 || state == 6)
2933 printfPQExpBuffer(errorMessage, libpq_gettext(
2934 "unterminated quoted string in connection info string\n"));
2942 #define MAXBUFSIZE 256
2945 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2947 char *service = conninfo_getval(options, "service");
2948 char serviceFile[MAXPGPATH];
2949 bool group_found = false;
2954 * We have to special-case the environment variable PGSERVICE here, since
2955 * this is and should be called before inserting environment defaults for
2956 * other connection options.
2958 if (service == NULL)
2959 service = getenv("PGSERVICE");
2962 * This could be used by any application so we can't use the binary
2963 * location to find our config files.
2965 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2966 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2968 if (service != NULL)
2971 char buf[MAXBUFSIZE],
2974 f = fopen(serviceFile, "r");
2977 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2982 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
2986 if (strlen(line) >= sizeof(buf) - 1)
2989 printfPQExpBuffer(errorMessage,
2990 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2996 /* ignore EOL at end of line */
2997 if (strlen(line) && line[strlen(line) - 1] == '\n')
2998 line[strlen(line) - 1] = 0;
3000 /* ignore leading blanks */
3001 while (*line && isspace((unsigned char) line[0]))
3004 /* ignore comments and empty lines */
3005 if (strlen(line) == 0 || line[0] == '#')
3008 /* Check for right groupname */
3013 /* group info already read */
3018 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3019 line[strlen(service) + 1] == ']')
3022 group_found = false;
3029 * Finally, we are in the right group and can parse the
3037 if (strncmp(line, "ldap", 4) == 0)
3039 int rc = ldapServiceLookup(line, options, errorMessage);
3041 /* if rc = 2, go on reading for fallback */
3058 val = strchr(line, '=');
3061 printfPQExpBuffer(errorMessage,
3062 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3071 * Set the parameter --- but don't override any previous
3074 found_keyword = false;
3075 for (i = 0; options[i].keyword; i++)
3077 if (strcmp(options[i].keyword, key) == 0)
3079 if (options[i].val == NULL)
3080 options[i].val = strdup(val);
3081 found_keyword = true;
3088 printfPQExpBuffer(errorMessage,
3089 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3109 * Parse a string like PQconnectdb() would do and return the
3110 * resulting connection options array. NULL is returned on failure.
3111 * The result contains only options specified directly in the string,
3112 * not any possible default values.
3114 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3115 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3116 * both *errmsg and the result could be NULL.
3118 * NOTE: the returned array is dynamically allocated and should
3119 * be freed when no longer needed via PQconninfoFree().
3122 PQconninfoParse(const char *conninfo, char **errmsg)
3124 PQExpBufferData errorBuf;
3125 PQconninfoOption *connOptions;
3128 *errmsg = NULL; /* default */
3129 initPQExpBuffer(&errorBuf);
3130 if (errorBuf.data == NULL)
3131 return NULL; /* out of memory already :-( */
3132 connOptions = conninfo_parse(conninfo, &errorBuf, false);
3133 if (connOptions == NULL && errmsg)
3134 *errmsg = errorBuf.data;
3136 termPQExpBuffer(&errorBuf);
3141 * Conninfo parser routine
3143 * If successful, a malloc'd PQconninfoOption array is returned.
3144 * If not successful, NULL is returned and an error message is
3145 * left in errorMessage.
3146 * Defaults are supplied (from a service file, environment variables, etc)
3147 * for unspecified options, but only if use_defaults is TRUE.
3149 static PQconninfoOption *
3150 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3159 PQconninfoOption *options;
3160 PQconninfoOption *option;
3162 /* Make a working copy of PQconninfoOptions */
3163 options = malloc(sizeof(PQconninfoOptions));
3164 if (options == NULL)
3166 printfPQExpBuffer(errorMessage,
3167 libpq_gettext("out of memory\n"));
3170 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3172 /* Need a modifiable copy of the input string */
3173 if ((buf = strdup(conninfo)) == NULL)
3175 printfPQExpBuffer(errorMessage,
3176 libpq_gettext("out of memory\n"));
3177 PQconninfoFree(options);
3184 /* Skip blanks before the parameter name */
3185 if (isspace((unsigned char) *cp))
3191 /* Get the parameter name */
3197 if (isspace((unsigned char) *cp))
3202 if (!isspace((unsigned char) *cp))
3211 /* Check that there is a following '=' */
3214 printfPQExpBuffer(errorMessage,
3215 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3217 PQconninfoFree(options);
3223 /* Skip blanks after the '=' */
3226 if (!isspace((unsigned char) *cp))
3231 /* Get the parameter value */
3239 if (isspace((unsigned char) *cp))
3263 printfPQExpBuffer(errorMessage,
3264 libpq_gettext("unterminated quoted string in connection info string\n"));
3265 PQconninfoFree(options);
3287 * Now we have the name and the value. Search for the param record.
3289 for (option = options; option->keyword != NULL; option++)
3291 if (strcmp(option->keyword, pname) == 0)
3294 if (option->keyword == NULL)
3296 printfPQExpBuffer(errorMessage,
3297 libpq_gettext("invalid connection option \"%s\"\n"),
3299 PQconninfoFree(options);
3309 option->val = strdup(pval);
3312 printfPQExpBuffer(errorMessage,
3313 libpq_gettext("out of memory\n"));
3314 PQconninfoFree(options);
3320 /* Done with the modifiable input string */
3324 * Stop here if caller doesn't want defaults filled in.
3330 * If there's a service spec, use it to obtain any not-explicitly-given
3333 if (parseServiceInfo(options, errorMessage))
3335 PQconninfoFree(options);
3340 * Get the fallback resources for parameters not specified in the conninfo
3341 * string nor the service.
3343 for (option = options; option->keyword != NULL; option++)
3345 if (option->val != NULL)
3346 continue; /* Value was in conninfo or service */
3349 * Try to get the environment variable fallback
3351 if (option->envvar != NULL)
3353 if ((tmp = getenv(option->envvar)) != NULL)
3355 option->val = strdup(tmp);
3358 printfPQExpBuffer(errorMessage,
3359 libpq_gettext("out of memory\n"));
3360 PQconninfoFree(options);
3368 * No environment variable specified or this one isn't set - try
3371 if (option->compiled != NULL)
3373 option->val = strdup(option->compiled);
3376 printfPQExpBuffer(errorMessage,
3377 libpq_gettext("out of memory\n"));
3378 PQconninfoFree(options);
3385 * Special handling for user
3387 if (strcmp(option->keyword, "user") == 0)
3389 option->val = pg_fe_getauthname(errorMessage);
3399 conninfo_getval(PQconninfoOption *connOptions,
3400 const char *keyword)
3402 PQconninfoOption *option;
3404 for (option = connOptions; option->keyword != NULL; option++)
3406 if (strcmp(option->keyword, keyword) == 0)
3415 PQconninfoFree(PQconninfoOption *connOptions)
3417 PQconninfoOption *option;
3419 if (connOptions == NULL)
3422 for (option = connOptions; option->keyword != NULL; option++)
3424 if (option->val != NULL)
3431 /* =========== accessor functions for PGconn ========= */
3433 PQdb(const PGconn *conn)
3437 return conn->dbName;
3441 PQuser(const PGconn *conn)
3445 return conn->pguser;
3449 PQpass(const PGconn *conn)
3453 return conn->pgpass;
3457 PQhost(const PGconn *conn)
3461 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3465 PQport(const PGconn *conn)
3469 return conn->pgport;
3473 PQtty(const PGconn *conn)
3481 PQoptions(const PGconn *conn)
3485 return conn->pgoptions;
3489 PQstatus(const PGconn *conn)
3492 return CONNECTION_BAD;
3493 return conn->status;
3496 PGTransactionStatusType
3497 PQtransactionStatus(const PGconn *conn)
3499 if (!conn || conn->status != CONNECTION_OK)
3500 return PQTRANS_UNKNOWN;
3501 if (conn->asyncStatus != PGASYNC_IDLE)
3502 return PQTRANS_ACTIVE;
3503 return conn->xactStatus;
3507 PQparameterStatus(const PGconn *conn, const char *paramName)
3509 const pgParameterStatus *pstatus;
3511 if (!conn || !paramName)
3513 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3515 if (strcmp(pstatus->name, paramName) == 0)
3516 return pstatus->value;
3522 PQprotocolVersion(const PGconn *conn)
3526 if (conn->status == CONNECTION_BAD)
3528 return PG_PROTOCOL_MAJOR(conn->pversion);
3532 PQserverVersion(const PGconn *conn)
3536 if (conn->status == CONNECTION_BAD)
3538 return conn->sversion;
3542 PQerrorMessage(const PGconn *conn)
3545 return libpq_gettext("connection pointer is NULL\n");
3547 return conn->errorMessage.data;
3551 PQsocket(const PGconn *conn)
3559 PQbackendPID(const PGconn *conn)
3561 if (!conn || conn->status != CONNECTION_OK)
3563 return conn->be_pid;
3567 PQconnectionNeedsPassword(const PGconn *conn)
3571 if (conn->password_needed &&
3572 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
3579 PQconnectionUsedPassword(const PGconn *conn)
3583 if (conn->password_needed)
3590 PQclientEncoding(const PGconn *conn)
3592 if (!conn || conn->status != CONNECTION_OK)
3594 return conn->client_encoding;
3598 PQsetClientEncoding(PGconn *conn, const char *encoding)
3601 static const char query[] = "set client_encoding to '%s'";
3605 if (!conn || conn->status != CONNECTION_OK)
3611 /* check query buffer overflow */
3612 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3615 /* ok, now send a query */
3616 sprintf(qbuf, query, encoding);
3617 res = PQexec(conn, qbuf);
3621 if (res->resultStatus != PGRES_COMMAND_OK)
3626 * In protocol 2 we have to assume the setting will stick, and adjust
3627 * our state immediately. In protocol 3 and up we can rely on the
3628 * backend to report the parameter value, and we'll change state at
3631 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3632 pqSaveParameterStatus(conn, "client_encoding", encoding);
3633 status = 0; /* everything is ok */
3640 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3645 return PQERRORS_DEFAULT;
3646 old = conn->verbosity;
3647 conn->verbosity = verbosity;
3652 PQtrace(PGconn *conn, FILE *debug_port)
3657 conn->Pfdebug = debug_port;
3661 PQuntrace(PGconn *conn)
3667 fflush(conn->Pfdebug);
3668 conn->Pfdebug = NULL;
3673 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3675 PQnoticeReceiver old;
3680 old = conn->noticeHooks.noticeRec;
3683 conn->noticeHooks.noticeRec = proc;
3684 conn->noticeHooks.noticeRecArg = arg;
3690 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3692 PQnoticeProcessor old;
3697 old = conn->noticeHooks.noticeProc;
3700 conn->noticeHooks.noticeProc = proc;
3701 conn->noticeHooks.noticeProcArg = arg;
3707 * The default notice message receiver just gets the standard notice text
3708 * and sends it to the notice processor. This two-level setup exists
3709 * mostly for backwards compatibility; perhaps we should deprecate use of
3710 * PQsetNoticeProcessor?
3713 defaultNoticeReceiver(void *arg, const PGresult *res)
3715 (void) arg; /* not used */
3716 if (res->noticeHooks.noticeProc != NULL)
3717 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3718 PQresultErrorMessage(res));
3722 * The default notice message processor just prints the
3723 * message on stderr. Applications can override this if they
3724 * want the messages to go elsewhere (a window, for example).
3725 * Note that simply discarding notices is probably a bad idea.
3728 defaultNoticeProcessor(void *arg, const char *message)
3730 (void) arg; /* not used */
3731 /* Note: we expect the supplied string to end with a newline already. */
3732 fprintf(stderr, "%s", message);
3736 * returns a pointer to the next token or NULL if the current
3737 * token doesn't match
3740 pwdfMatchesString(char *buf, char *token)
3744 bool bslash = false;
3746 if (buf == NULL || token == NULL)
3754 if (*tbuf == '\\' && !bslash)
3759 if (*tbuf == ':' && *ttok == 0 && !bslash)
3775 /* Get a password from the password file. Return value is malloc'd. */
3777 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3780 char pgpassfile[MAXPGPATH];
3781 struct stat stat_buf;
3784 #define LINELEN NAMEDATALEN*5
3787 if (dbname == NULL || strlen(dbname) == 0)
3790 if (username == NULL || strlen(username) == 0)
3793 /* 'localhost' matches pghost of '' or the default socket directory */
3794 if (hostname == NULL)
3795 hostname = DefaultHost;
3796 else if (is_absolute_path(hostname))
3799 * We should probably use canonicalize_path(), but then we have to
3800 * bring path.c into libpq, and it doesn't seem worth it.
3802 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3803 hostname = DefaultHost;
3806 port = DEF_PGPORT_STR;
3808 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3809 /* use the literal path from the environment, if set */
3810 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3813 char homedir[MAXPGPATH];
3815 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3817 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3820 /* If password file cannot be opened, ignore it. */
3821 if (stat(pgpassfile, &stat_buf) != 0)
3825 if (!S_ISREG(stat_buf.st_mode))
3828 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3833 /* If password file is insecure, alert the user and ignore it. */
3834 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3837 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
3844 * On Win32, the directory is protected, so we don't have to check the
3849 fp = fopen(pgpassfile, "r");
3859 fgets(buf, sizeof(buf), fp);
3865 /* Remove trailing newline */
3866 if (buf[len - 1] == '\n')
3869 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3870 (t = pwdfMatchesString(t, port)) == NULL ||
3871 (t = pwdfMatchesString(t, dbname)) == NULL ||
3872 (t = pwdfMatchesString(t, username)) == NULL)
3886 * Obtain user's home directory, return in given buffer
3888 * On Unix, this actually returns the user's home directory. On Windows
3889 * it returns the PostgreSQL-specific application data folder.
3891 * This is essentially the same as get_home_path(), but we don't use that
3892 * because we don't want to pull path.c into libpq (it pollutes application
3896 pqGetHomeDirectory(char *buf, int bufsize)
3899 char pwdbuf[BUFSIZ];
3900 struct passwd pwdstr;
3901 struct passwd *pwd = NULL;
3903 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3905 strlcpy(buf, pwd->pw_dir, bufsize);
3908 char tmppath[MAX_PATH];
3910 ZeroMemory(tmppath, sizeof(tmppath));
3911 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3913 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3919 * To keep the API consistent, the locking stubs are always provided, even
3920 * if they are not required.
3924 default_threadlock(int acquire)
3926 #ifdef ENABLE_THREAD_SAFETY
3928 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3930 static pthread_mutex_t singlethread_lock = NULL;
3931 static long mutex_initlock = 0;
3933 if (singlethread_lock == NULL)
3935 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3936 /* loop, another thread own the lock */ ;
3937 if (singlethread_lock == NULL)
3939 if (pthread_mutex_init(&singlethread_lock, NULL))
3940 PGTHREAD_ERROR("failed to initialize mutex");
3942 InterlockedExchange(&mutex_initlock, 0);
3947 if (pthread_mutex_lock(&singlethread_lock))
3948 PGTHREAD_ERROR("failed to lock mutex");
3952 if (pthread_mutex_unlock(&singlethread_lock))
3953 PGTHREAD_ERROR("failed to unlock mutex");
3959 PQregisterThreadLock(pgthreadlock_t newhandler)
3961 pgthreadlock_t prev = pg_g_threadlock;
3964 pg_g_threadlock = newhandler;
3966 pg_g_threadlock = default_threadlock;