1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2007, 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.353 2007/11/15 21:14:46 momjian 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);
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 if (connOptions == NULL)
382 conn->status = CONNECTION_BAD;
383 /* errorMessage is already set */
388 * Move option values into conn structure
390 * Don't put anything cute here --- intelligence should be in
391 * connectOptions2 ...
393 * XXX: probably worth checking strdup() return value here...
395 tmp = conninfo_getval(connOptions, "hostaddr");
396 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
397 tmp = conninfo_getval(connOptions, "host");
398 conn->pghost = tmp ? strdup(tmp) : NULL;
399 tmp = conninfo_getval(connOptions, "port");
400 conn->pgport = tmp ? strdup(tmp) : NULL;
401 tmp = conninfo_getval(connOptions, "tty");
402 conn->pgtty = tmp ? strdup(tmp) : NULL;
403 tmp = conninfo_getval(connOptions, "options");
404 conn->pgoptions = tmp ? strdup(tmp) : NULL;
405 tmp = conninfo_getval(connOptions, "dbname");
406 conn->dbName = tmp ? strdup(tmp) : NULL;
407 tmp = conninfo_getval(connOptions, "user");
408 conn->pguser = tmp ? strdup(tmp) : NULL;
409 tmp = conninfo_getval(connOptions, "password");
410 conn->pgpass = tmp ? strdup(tmp) : NULL;
411 tmp = conninfo_getval(connOptions, "connect_timeout");
412 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
413 tmp = conninfo_getval(connOptions, "sslmode");
414 conn->sslmode = tmp ? strdup(tmp) : NULL;
416 tmp = conninfo_getval(connOptions, "requiressl");
417 if (tmp && tmp[0] == '1')
419 /* here warn that the requiressl option is deprecated? */
422 conn->sslmode = strdup("require");
425 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
426 tmp = conninfo_getval(connOptions, "krbsrvname");
427 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
429 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
430 tmp = conninfo_getval(connOptions, "gsslib");
431 conn->gsslib = tmp ? strdup(tmp) : NULL;
435 * Free the option info - all is in conn now
437 PQconninfoFree(connOptions);
445 * Compute derived connection options after absorbing all user-supplied info.
447 * Returns true if OK, false if trouble (in which case errorMessage is set
448 * and so is conn->status).
451 connectOptions2(PGconn *conn)
454 * If database name was not given, default it to equal user name
456 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
457 && conn->pguser != NULL)
461 conn->dbName = strdup(conn->pguser);
465 * Supply default password if none given
467 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
471 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
472 conn->dbName, conn->pguser);
473 if (conn->pgpass == NULL)
474 conn->pgpass = strdup(DefaultPassword);
478 * Allow unix socket specification in the host name
480 if (conn->pghost && is_absolute_path(conn->pghost))
482 if (conn->pgunixsocket)
483 free(conn->pgunixsocket);
484 conn->pgunixsocket = conn->pghost;
489 * validate sslmode option
493 if (strcmp(conn->sslmode, "disable") != 0
494 && strcmp(conn->sslmode, "allow") != 0
495 && strcmp(conn->sslmode, "prefer") != 0
496 && strcmp(conn->sslmode, "require") != 0)
498 conn->status = CONNECTION_BAD;
499 printfPQExpBuffer(&conn->errorMessage,
500 libpq_gettext("invalid sslmode value: \"%s\"\n"),
506 switch (conn->sslmode[0])
508 case 'a': /* "allow" */
509 case 'p': /* "prefer" */
512 * warn user that an SSL connection will never be negotiated
513 * since SSL was not compiled in?
517 case 'r': /* "require" */
518 conn->status = CONNECTION_BAD;
519 printfPQExpBuffer(&conn->errorMessage,
520 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
527 conn->sslmode = strdup(DefaultSSLMode);
530 * Only if we get this far is it appropriate to try to connect. (We need a
531 * state flag, rather than just the boolean result of this function, in
532 * case someone tries to PQreset() the PGconn.)
534 conn->options_valid = true;
542 * Parse an empty string like PQconnectdb() would do and return the
543 * working connection options array.
545 * Using this function, an application may determine all possible options
546 * and their current default values.
548 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
549 * and should be freed when no longer needed via PQconninfoFree(). (In prior
550 * versions, the returned array was static, but that's not thread-safe.)
551 * Pre-7.0 applications that use this function will see a small memory leak
552 * until they are updated to call PQconninfoFree.
557 PQExpBufferData errorBuf;
558 PQconninfoOption *connOptions;
560 initPQExpBuffer(&errorBuf);
561 connOptions = conninfo_parse("", &errorBuf);
562 termPQExpBuffer(&errorBuf);
569 * establishes a connection to a postgres backend through the postmaster
570 * at the specified host and port.
572 * returns a PGconn* which is needed for all subsequent libpq calls
574 * if the status field of the connection returned is CONNECTION_BAD,
575 * then only the errorMessage is likely to be useful.
579 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
580 const char *pgtty, const char *dbName, const char *login,
586 * Allocate memory for the conn structure
588 conn = makeEmptyPGconn();
593 * If the dbName parameter contains '=', assume it's a conninfo string.
595 if (dbName && strchr(dbName, '='))
597 if (!connectOptions1(conn, dbName))
603 * Old-style path: first, parse an empty conninfo string in order to
604 * set up the same defaults that PQconnectdb() would use.
606 if (!connectOptions1(conn, ""))
609 /* Insert dbName parameter value into struct */
610 if (dbName && dbName[0] != '\0')
614 conn->dbName = strdup(dbName);
619 * Insert remaining parameters into struct, overriding defaults (as well
620 * as any conflicting data from dbName taken as a conninfo).
622 if (pghost && pghost[0] != '\0')
626 conn->pghost = strdup(pghost);
629 if (pgport && pgport[0] != '\0')
633 conn->pgport = strdup(pgport);
636 if (pgoptions && pgoptions[0] != '\0')
639 free(conn->pgoptions);
640 conn->pgoptions = strdup(pgoptions);
643 if (pgtty && pgtty[0] != '\0')
647 conn->pgtty = strdup(pgtty);
650 if (login && login[0] != '\0')
654 conn->pguser = strdup(login);
657 if (pwd && pwd[0] != '\0')
661 conn->pgpass = strdup(pwd);
665 * Compute derived options
667 if (!connectOptions2(conn))
671 * Connect to the database
673 if (connectDBStart(conn))
674 (void) connectDBComplete(conn);
682 * Sets the TCP_NODELAY socket option.
683 * Returns 1 if successful, 0 if not.
687 connectNoDelay(PGconn *conn)
692 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
698 printfPQExpBuffer(&conn->errorMessage,
699 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
700 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
710 * connectFailureMessage -
711 * create a friendly error message on connection failure.
715 connectFailureMessage(PGconn *conn, int errorno)
719 #ifdef HAVE_UNIX_SOCKETS
720 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
722 char service[NI_MAXHOST];
724 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
726 service, sizeof(service),
728 printfPQExpBuffer(&conn->errorMessage,
729 libpq_gettext("could not connect to server: %s\n"
730 "\tIs the server running locally and accepting\n"
731 "\tconnections on Unix domain socket \"%s\"?\n"),
732 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
736 #endif /* HAVE_UNIX_SOCKETS */
738 printfPQExpBuffer(&conn->errorMessage,
739 libpq_gettext("could not connect to server: %s\n"
740 "\tIs the server running on host \"%s\" and accepting\n"
741 "\tTCP/IP connections on port %s?\n"),
742 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
755 * Begin the process of making a connection to the backend.
757 * Returns 1 if successful, 0 if not.
761 connectDBStart(PGconn *conn)
765 struct addrinfo *addrs = NULL;
766 struct addrinfo hint;
773 if (!conn->options_valid)
774 goto connect_errReturn;
776 /* Ensure our buffers are empty */
777 conn->inStart = conn->inCursor = conn->inEnd = 0;
781 * Determine the parameters to pass to pg_getaddrinfo_all.
784 /* Initialize hint structure */
785 MemSet(&hint, 0, sizeof(hint));
786 hint.ai_socktype = SOCK_STREAM;
787 hint.ai_family = AF_UNSPEC;
789 /* Set up port number as a string */
790 if (conn->pgport != NULL && conn->pgport[0] != '\0')
791 portnum = atoi(conn->pgport);
793 portnum = DEF_PGPORT;
794 snprintf(portstr, sizeof(portstr), "%d", portnum);
796 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
798 /* Using pghostaddr avoids a hostname lookup */
799 node = conn->pghostaddr;
800 hint.ai_family = AF_UNSPEC;
801 hint.ai_flags = AI_NUMERICHOST;
803 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
805 /* Using pghost, so we have to look-up the hostname */
807 hint.ai_family = AF_UNSPEC;
811 #ifdef HAVE_UNIX_SOCKETS
812 /* pghostaddr and pghost are NULL, so use Unix domain socket */
814 hint.ai_family = AF_UNIX;
815 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
817 /* Without Unix sockets, default to localhost instead */
819 hint.ai_family = AF_UNSPEC;
820 #endif /* HAVE_UNIX_SOCKETS */
823 /* Use pg_getaddrinfo_all() to resolve the address */
824 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
828 printfPQExpBuffer(&conn->errorMessage,
829 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
830 node, gai_strerror(ret));
832 printfPQExpBuffer(&conn->errorMessage,
833 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
834 portstr, gai_strerror(ret));
836 pg_freeaddrinfo_all(hint.ai_family, addrs);
837 goto connect_errReturn;
841 /* setup values based on SSL mode */
842 if (conn->sslmode[0] == 'd') /* "disable" */
843 conn->allow_ssl_try = false;
844 else if (conn->sslmode[0] == 'a') /* "allow" */
845 conn->wait_ssl_try = true;
849 * Set up to try to connect, with protocol 3.0 as the first attempt.
851 conn->addrlist = addrs;
852 conn->addr_cur = addrs;
853 conn->addrlist_family = hint.ai_family;
854 conn->pversion = PG_PROTOCOL(3, 0);
855 conn->status = CONNECTION_NEEDED;
858 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
859 * so that it can easily be re-executed if needed again during the
860 * asynchronous startup process. However, we must run it once here,
861 * because callers expect a success return from this routine to mean that
862 * we are in PGRES_POLLING_WRITING connection state.
864 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
870 pqsecure_close(conn);
871 closesocket(conn->sock);
874 conn->status = CONNECTION_BAD;
882 * Block and complete a connection.
884 * Returns 1 on success, 0 on failure.
887 connectDBComplete(PGconn *conn)
889 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
890 time_t finish_time = ((time_t) -1);
892 if (conn == NULL || conn->status == CONNECTION_BAD)
896 * Set up a time limit, if connect_timeout isn't zero.
898 if (conn->connect_timeout != NULL)
900 int timeout = atoi(conn->connect_timeout);
905 * Rounding could cause connection to fail; need at least 2 secs
909 /* calculate the finish time based on start + timeout */
910 finish_time = time(NULL) + timeout;
917 * Wait, if necessary. Note that the initial state (just after
918 * PQconnectStart) is to wait for the socket to select for writing.
922 case PGRES_POLLING_OK:
923 return 1; /* success! */
925 case PGRES_POLLING_READING:
926 if (pqWaitTimed(1, 0, conn, finish_time))
928 conn->status = CONNECTION_BAD;
933 case PGRES_POLLING_WRITING:
934 if (pqWaitTimed(0, 1, conn, finish_time))
936 conn->status = CONNECTION_BAD;
942 /* Just in case we failed to set it in PQconnectPoll */
943 conn->status = CONNECTION_BAD;
948 * Now try to advance the state machine.
950 flag = PQconnectPoll(conn);
957 * Poll an asynchronous connection.
959 * Returns a PostgresPollingStatusType.
960 * Before calling this function, use select(2) to determine when data
963 * You must call PQfinish whether or not this fails.
965 * This function and PQconnectStart are intended to allow connections to be
966 * made without blocking the execution of your program on remote I/O. However,
967 * there are a number of caveats:
969 * o If you call PQtrace, ensure that the stream object into which you trace
971 * o If you do not supply an IP address for the remote host (i.e. you
972 * supply a host name instead) then PQconnectStart will block on
973 * gethostbyname. You will be fine if using Unix sockets (i.e. by
974 * supplying neither a host name nor a host address).
975 * o If your backend wants to use Kerberos authentication then you must
976 * supply both a host name and a host address, otherwise this function
977 * may block on gethostname.
981 PostgresPollingStatusType
982 PQconnectPoll(PGconn *conn)
988 return PGRES_POLLING_FAILED;
990 /* Get the new data */
991 switch (conn->status)
994 * We really shouldn't have been polled in these two cases, but we
998 return PGRES_POLLING_FAILED;
1000 return PGRES_POLLING_OK;
1002 /* These are reading states */
1003 case CONNECTION_AWAITING_RESPONSE:
1004 case CONNECTION_AUTH_OK:
1006 /* Load waiting data */
1007 int n = pqReadData(conn);
1012 return PGRES_POLLING_READING;
1017 /* These are writing states, so we just proceed. */
1018 case CONNECTION_STARTED:
1019 case CONNECTION_MADE:
1022 /* We allow pqSetenvPoll to decide whether to proceed. */
1023 case CONNECTION_SETENV:
1026 /* Special cases: proceed without waiting. */
1027 case CONNECTION_SSL_STARTUP:
1028 case CONNECTION_NEEDED:
1032 printfPQExpBuffer(&conn->errorMessage,
1034 "invalid connection state, "
1035 "probably indicative of memory corruption\n"
1041 keep_going: /* We will come back to here until there is
1042 * nothing left to do. */
1043 switch (conn->status)
1045 case CONNECTION_NEEDED:
1048 * Try to initiate a connection to one of the addresses
1049 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1050 * next one to try. We fail when we run out of addresses
1051 * (reporting the error returned for the *last* alternative,
1052 * which may not be what users expect :-().
1054 while (conn->addr_cur != NULL)
1056 struct addrinfo *addr_cur = conn->addr_cur;
1058 /* Remember current address for possible error msg */
1059 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1060 addr_cur->ai_addrlen);
1061 conn->raddr.salen = addr_cur->ai_addrlen;
1064 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1068 * ignore socket() failure if we have more addresses
1071 if (addr_cur->ai_next != NULL)
1073 conn->addr_cur = addr_cur->ai_next;
1076 printfPQExpBuffer(&conn->errorMessage,
1077 libpq_gettext("could not create socket: %s\n"),
1078 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1083 * Select socket options: no delay of outgoing data for
1084 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1087 if (!IS_AF_UNIX(addr_cur->ai_family))
1089 if (!connectNoDelay(conn))
1091 closesocket(conn->sock);
1093 conn->addr_cur = addr_cur->ai_next;
1097 if (!pg_set_noblock(conn->sock))
1099 printfPQExpBuffer(&conn->errorMessage,
1100 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1101 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1102 closesocket(conn->sock);
1104 conn->addr_cur = addr_cur->ai_next;
1109 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1111 printfPQExpBuffer(&conn->errorMessage,
1112 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1113 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1114 closesocket(conn->sock);
1116 conn->addr_cur = addr_cur->ai_next;
1119 #endif /* F_SETFD */
1122 * Start/make connection. This should not block, since we
1123 * are in nonblock mode. If it does, well, too bad.
1125 if (connect(conn->sock, addr_cur->ai_addr,
1126 addr_cur->ai_addrlen) < 0)
1128 if (SOCK_ERRNO == EINPROGRESS ||
1129 SOCK_ERRNO == EWOULDBLOCK ||
1130 SOCK_ERRNO == EINTR ||
1134 * This is fine - we're in non-blocking mode, and
1135 * the connection is in progress. Tell caller to
1136 * wait for write-ready on socket.
1138 conn->status = CONNECTION_STARTED;
1139 return PGRES_POLLING_WRITING;
1141 /* otherwise, trouble */
1146 * Hm, we're connected already --- seems the "nonblock
1147 * connection" wasn't. Advance the state machine and
1148 * go do the next stuff.
1150 conn->status = CONNECTION_STARTED;
1155 * This connection failed --- set up error report, then
1156 * close socket (do it this way in case close() affects
1157 * the value of errno...). We will ignore the connect()
1158 * failure and keep going if there are more addresses.
1160 connectFailureMessage(conn, SOCK_ERRNO);
1161 if (conn->sock >= 0)
1163 closesocket(conn->sock);
1168 * Try the next address, if any.
1170 conn->addr_cur = addr_cur->ai_next;
1171 } /* loop over addresses */
1174 * Ooops, no more addresses. An appropriate error message is
1175 * already set up, so just set the right status.
1180 case CONNECTION_STARTED:
1183 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1186 * Write ready, since we've made it here, so the connection
1187 * has been made ... or has failed.
1191 * Now check (using getsockopt) that there is not an error
1192 * state waiting for us on the socket.
1195 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1196 (char *) &optval, &optlen) == -1)
1198 printfPQExpBuffer(&conn->errorMessage,
1199 libpq_gettext("could not get socket error status: %s\n"),
1200 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1203 else if (optval != 0)
1206 * When using a nonblocking connect, we will typically see
1207 * connect failures at this point, so provide a friendly
1210 connectFailureMessage(conn, optval);
1213 * If more addresses remain, keep trying, just as in the
1214 * case where connect() returned failure immediately.
1216 if (conn->addr_cur->ai_next != NULL)
1218 if (conn->sock >= 0)
1220 closesocket(conn->sock);
1223 conn->addr_cur = conn->addr_cur->ai_next;
1224 conn->status = CONNECTION_NEEDED;
1230 /* Fill in the client address */
1231 conn->laddr.salen = sizeof(conn->laddr.addr);
1232 if (getsockname(conn->sock,
1233 (struct sockaddr *) & conn->laddr.addr,
1234 &conn->laddr.salen) < 0)
1236 printfPQExpBuffer(&conn->errorMessage,
1237 libpq_gettext("could not get client address from socket: %s\n"),
1238 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1243 * Make sure we can write before advancing to next step.
1245 conn->status = CONNECTION_MADE;
1246 return PGRES_POLLING_WRITING;
1249 case CONNECTION_MADE:
1257 * If SSL is enabled and we haven't already got it running,
1258 * request it instead of sending the startup message.
1260 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1262 /* Don't bother requesting SSL over a Unix socket */
1263 conn->allow_ssl_try = false;
1265 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1271 * Send the SSL request packet.
1273 * Theoretically, this could block, but it really
1274 * shouldn't since we only got here if the socket is
1277 pv = htonl(NEGOTIATE_SSL_CODE);
1278 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1280 printfPQExpBuffer(&conn->errorMessage,
1281 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1282 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1285 /* Ok, wait for response */
1286 conn->status = CONNECTION_SSL_STARTUP;
1287 return PGRES_POLLING_READING;
1289 #endif /* USE_SSL */
1292 * Build the startup packet.
1294 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1295 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1296 EnvironmentOptions);
1298 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1299 EnvironmentOptions);
1302 printfPQExpBuffer(&conn->errorMessage,
1303 libpq_gettext("out of memory\n"));
1308 * Send the startup packet.
1310 * Theoretically, this could block, but it really shouldn't
1311 * since we only got here if the socket is write-ready.
1313 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1315 printfPQExpBuffer(&conn->errorMessage,
1316 libpq_gettext("could not send startup packet: %s\n"),
1317 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1324 conn->status = CONNECTION_AWAITING_RESPONSE;
1325 return PGRES_POLLING_READING;
1329 * Handle SSL negotiation: wait for postmaster messages and
1330 * respond as necessary.
1332 case CONNECTION_SSL_STARTUP:
1335 PostgresPollingStatusType pollres;
1338 * On first time through, get the postmaster's response to our
1339 * SSL negotiation packet.
1341 if (conn->ssl == NULL)
1344 * We use pqReadData here since it has the logic to
1345 * distinguish no-data-yet from connection closure. Since
1346 * conn->ssl isn't set, a plain recv() will occur.
1351 rdresult = pqReadData(conn);
1354 /* errorMessage is already filled in */
1359 /* caller failed to wait for data */
1360 return PGRES_POLLING_READING;
1362 if (pqGetc(&SSLok, conn) < 0)
1364 /* should not happen really */
1365 return PGRES_POLLING_READING;
1367 /* mark byte consumed */
1368 conn->inStart = conn->inCursor;
1371 /* Do one-time setup; this creates conn->ssl */
1372 if (pqsecure_initialize(conn) == -1)
1375 else if (SSLok == 'N')
1377 if (conn->sslmode[0] == 'r') /* "require" */
1379 /* Require SSL, but server does not want it */
1380 printfPQExpBuffer(&conn->errorMessage,
1381 libpq_gettext("server does not support SSL, but SSL was required\n"));
1384 /* Otherwise, proceed with normal startup */
1385 conn->allow_ssl_try = false;
1386 conn->status = CONNECTION_MADE;
1387 return PGRES_POLLING_WRITING;
1389 else if (SSLok == 'E')
1391 /* Received error - probably protocol mismatch */
1393 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1394 if (conn->sslmode[0] == 'r') /* "require" */
1396 /* Require SSL, but server is too old */
1397 printfPQExpBuffer(&conn->errorMessage,
1398 libpq_gettext("server does not support SSL, but SSL was required\n"));
1401 /* Otherwise, try again without SSL */
1402 conn->allow_ssl_try = false;
1403 /* Assume it ain't gonna handle protocol 3, either */
1404 conn->pversion = PG_PROTOCOL(2, 0);
1405 /* Must drop the old connection */
1406 closesocket(conn->sock);
1408 conn->status = CONNECTION_NEEDED;
1413 printfPQExpBuffer(&conn->errorMessage,
1414 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1421 * Begin or continue the SSL negotiation process.
1423 pollres = pqsecure_open_client(conn);
1424 if (pollres == PGRES_POLLING_OK)
1426 /* SSL handshake done, ready to send startup packet */
1427 conn->status = CONNECTION_MADE;
1428 return PGRES_POLLING_WRITING;
1430 if (pollres == PGRES_POLLING_FAILED)
1433 * Failed ... if sslmode is "prefer" then do a non-SSL
1436 if (conn->sslmode[0] == 'p' /* "prefer" */
1437 && conn->allow_ssl_try /* redundant? */
1438 && !conn->wait_ssl_try) /* redundant? */
1440 /* only retry once */
1441 conn->allow_ssl_try = false;
1442 /* Must drop the old connection */
1443 closesocket(conn->sock);
1445 conn->status = CONNECTION_NEEDED;
1450 #else /* !USE_SSL */
1451 /* can't get here */
1453 #endif /* USE_SSL */
1457 * Handle authentication exchange: wait for postmaster messages
1458 * and respond as necessary.
1460 case CONNECTION_AWAITING_RESPONSE:
1468 * Scan the message from current point (note that if we find
1469 * the message is incomplete, we will return without advancing
1470 * inStart, and resume here next time).
1472 conn->inCursor = conn->inStart;
1474 /* Read type byte */
1475 if (pqGetc(&beresp, conn))
1477 /* We'll come back when there is more data */
1478 return PGRES_POLLING_READING;
1482 * Validate message type: we expect only an authentication
1483 * request or an error here. Anything else probably means
1484 * it's not Postgres on the other end at all.
1486 if (!(beresp == 'R' || beresp == 'E'))
1488 printfPQExpBuffer(&conn->errorMessage,
1490 "expected authentication request from "
1491 "server, but received %c\n"),
1496 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1498 /* Read message length word */
1499 if (pqGetInt(&msgLength, 4, conn))
1501 /* We'll come back when there is more data */
1502 return PGRES_POLLING_READING;
1507 /* Set phony message length to disable checks below */
1512 * Try to validate message length before using it.
1513 * Authentication requests can't be very large, although GSS
1514 * auth requests may not be that small. Errors can be a
1515 * little larger, but not huge. If we see a large apparent
1516 * length in an error, it means we're really talking to a
1517 * pre-3.0-protocol server; cope.
1519 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1521 printfPQExpBuffer(&conn->errorMessage,
1523 "expected authentication request from "
1524 "server, but received %c\n"),
1529 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1531 /* Handle error from a pre-3.0 server */
1532 conn->inCursor = conn->inStart + 1; /* reread data */
1533 if (pqGets(&conn->errorMessage, conn))
1535 /* We'll come back when there is more data */
1536 return PGRES_POLLING_READING;
1538 /* OK, we read the message; mark data consumed */
1539 conn->inStart = conn->inCursor;
1542 * The postmaster typically won't end its message with a
1543 * newline, so add one to conform to libpq conventions.
1545 appendPQExpBufferChar(&conn->errorMessage, '\n');
1548 * If we tried to open the connection in 3.0 protocol,
1549 * fall back to 2.0 protocol.
1551 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1553 conn->pversion = PG_PROTOCOL(2, 0);
1554 /* Must drop the old connection */
1555 pqsecure_close(conn);
1556 closesocket(conn->sock);
1558 conn->status = CONNECTION_NEEDED;
1566 * Can't process if message body isn't all here yet.
1568 * (In protocol 2.0 case, we are assuming messages carry at
1569 * least 4 bytes of data.)
1572 avail = conn->inEnd - conn->inCursor;
1573 if (avail < msgLength)
1576 * Before returning, try to enlarge the input buffer if
1577 * needed to hold the whole message; see notes in
1580 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1582 /* We'll come back when there is more data */
1583 return PGRES_POLLING_READING;
1586 /* Handle errors. */
1589 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1591 if (pqGetErrorNotice3(conn, true))
1593 /* We'll come back when there is more data */
1594 return PGRES_POLLING_READING;
1599 if (pqGets(&conn->errorMessage, conn))
1601 /* We'll come back when there is more data */
1602 return PGRES_POLLING_READING;
1605 /* OK, we read the message; mark data consumed */
1606 conn->inStart = conn->inCursor;
1611 * if sslmode is "allow" and we haven't tried an SSL
1612 * connection already, then retry with an SSL connection
1614 if (conn->sslmode[0] == 'a' /* "allow" */
1615 && conn->ssl == NULL
1616 && conn->allow_ssl_try
1617 && conn->wait_ssl_try)
1619 /* only retry once */
1620 conn->wait_ssl_try = false;
1621 /* Must drop the old connection */
1622 closesocket(conn->sock);
1624 conn->status = CONNECTION_NEEDED;
1629 * if sslmode is "prefer" and we're in an SSL connection,
1630 * then do a non-SSL retry
1632 if (conn->sslmode[0] == 'p' /* "prefer" */
1634 && conn->allow_ssl_try /* redundant? */
1635 && !conn->wait_ssl_try) /* redundant? */
1637 /* only retry once */
1638 conn->allow_ssl_try = false;
1639 /* Must drop the old connection */
1640 pqsecure_close(conn);
1641 closesocket(conn->sock);
1643 conn->status = CONNECTION_NEEDED;
1651 /* It is an authentication request. */
1652 /* Get the type of request. */
1653 if (pqGetInt((int *) &areq, 4, conn))
1655 /* We'll come back when there are more data */
1656 return PGRES_POLLING_READING;
1659 /* Get the password salt if there is one. */
1660 if (areq == AUTH_REQ_MD5)
1662 if (pqGetnchar(conn->md5Salt,
1663 sizeof(conn->md5Salt), conn))
1665 /* We'll come back when there are more data */
1666 return PGRES_POLLING_READING;
1669 if (areq == AUTH_REQ_CRYPT)
1671 if (pqGetnchar(conn->cryptSalt,
1672 sizeof(conn->cryptSalt), conn))
1674 /* We'll come back when there are more data */
1675 return PGRES_POLLING_READING;
1678 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1681 * Continue GSSAPI/SSPI authentication
1683 if (areq == AUTH_REQ_GSS_CONT)
1685 int llen = msgLength - 4;
1688 * We can be called repeatedly for the same buffer. Avoid
1689 * re-allocating the buffer in this case - just re-use the
1692 if (llen != conn->ginbuf.length)
1694 if (conn->ginbuf.value)
1695 free(conn->ginbuf.value);
1697 conn->ginbuf.length = llen;
1698 conn->ginbuf.value = malloc(llen);
1699 if (!conn->ginbuf.value)
1701 printfPQExpBuffer(&conn->errorMessage,
1702 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1708 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1710 /* We'll come back when there is more data. */
1711 return PGRES_POLLING_READING;
1717 * OK, we successfully read the message; mark data consumed
1719 conn->inStart = conn->inCursor;
1721 /* Save the authentication request type, if first one. */
1722 if (conn->areq == AUTH_REQ_OK)
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->areq = AUTH_REQ_OK; /* until we receive something else */
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 the PGconn data structure
1968 * When changing/adding to this function, see also closePGconn!
1971 freePGconn(PGconn *conn)
1974 pgParameterStatus *pstatus;
1979 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1980 if (conn->sock >= 0)
1982 pqsecure_close(conn);
1983 closesocket(conn->sock);
1987 if (conn->pghostaddr)
1988 free(conn->pghostaddr);
1991 if (conn->pgunixsocket)
1992 free(conn->pgunixsocket);
1995 if (conn->connect_timeout)
1996 free(conn->connect_timeout);
1997 if (conn->pgoptions)
1998 free(conn->pgoptions);
2006 free(conn->sslmode);
2007 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2008 if (conn->krbsrvname)
2009 free(conn->krbsrvname);
2011 /* Note that conn->Pfdebug is not ours to close or free */
2012 if (conn->last_query)
2013 free(conn->last_query);
2014 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2015 notify = conn->notifyHead;
2016 while (notify != NULL)
2018 PGnotify *prev = notify;
2020 notify = notify->next;
2028 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2029 if (conn->gtarg_nam)
2030 gss_release_name(&min_s, &conn->gtarg_nam);
2031 if (conn->ginbuf.length)
2032 gss_release_buffer(&min_s, &conn->ginbuf);
2033 if (conn->goutbuf.length)
2034 gss_release_buffer(&min_s, &conn->goutbuf);
2039 if (conn->ginbuf.length)
2040 free(conn->ginbuf.value);
2042 if (conn->sspitarget)
2043 free(conn->sspitarget);
2047 FreeCredentialsHandle(conn->sspicred);
2048 free(conn->sspicred);
2052 DeleteSecurityContext(conn->sspictx);
2053 free(conn->sspictx);
2057 pstatus = conn->pstatus;
2058 while (pstatus != NULL)
2060 pgParameterStatus *prev = pstatus;
2062 pstatus = pstatus->next;
2065 if (conn->lobjfuncs)
2066 free(conn->lobjfuncs);
2068 free(conn->inBuffer);
2069 if (conn->outBuffer)
2070 free(conn->outBuffer);
2071 termPQExpBuffer(&conn->errorMessage);
2072 termPQExpBuffer(&conn->workBuffer);
2082 * - properly close a connection to the backend
2084 * Release all transient state, but NOT the connection parameters.
2087 closePGconn(PGconn *conn)
2090 pgParameterStatus *pstatus;
2093 * Note that the protocol doesn't allow us to send Terminate messages
2094 * during the startup phase.
2096 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2099 * Try to send "close connection" message to backend. Ignore any
2102 pqPutMsgStart('X', false, conn);
2108 * must reset the blocking status so a possible reconnect will work don't
2109 * call PQsetnonblocking() because it will fail if it's unable to flush
2112 conn->nonblocking = FALSE;
2115 * Close the connection, reset all transient state, flush I/O buffers.
2117 if (conn->sock >= 0)
2119 pqsecure_close(conn);
2120 closesocket(conn->sock);
2123 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2125 conn->asyncStatus = PGASYNC_IDLE;
2126 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2127 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2128 conn->addrlist = NULL;
2129 conn->addr_cur = NULL;
2130 notify = conn->notifyHead;
2131 while (notify != NULL)
2133 PGnotify *prev = notify;
2135 notify = notify->next;
2138 conn->notifyHead = NULL;
2139 pstatus = conn->pstatus;
2140 while (pstatus != NULL)
2142 pgParameterStatus *prev = pstatus;
2144 pstatus = pstatus->next;
2147 conn->pstatus = NULL;
2148 if (conn->lobjfuncs)
2149 free(conn->lobjfuncs);
2150 conn->lobjfuncs = NULL;
2151 conn->inStart = conn->inCursor = conn->inEnd = 0;
2156 * PQfinish: properly close a connection to the backend. Also frees
2157 * the PGconn data structure so it shouldn't be re-used after this.
2160 PQfinish(PGconn *conn)
2170 * PQreset: resets the connection to the backend by closing the
2171 * existing connection and creating a new one.
2174 PQreset(PGconn *conn)
2180 if (connectDBStart(conn))
2181 (void) connectDBComplete(conn);
2188 * resets the connection to the backend
2189 * closes the existing connection and makes a new one
2190 * Returns 1 on success, 0 on failure.
2193 PQresetStart(PGconn *conn)
2199 return connectDBStart(conn);
2208 * resets the connection to the backend
2209 * closes the existing connection and makes a new one
2211 PostgresPollingStatusType
2212 PQresetPoll(PGconn *conn)
2215 return PQconnectPoll(conn);
2217 return PGRES_POLLING_FAILED;
2221 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2223 * A copy is needed to be able to cancel a running query from a different
2224 * thread. If the same structure is used all structure members would have
2225 * to be individually locked (if the entire structure was locked, it would
2226 * be impossible to cancel a synchronous query because the structure would
2227 * have to stay locked for the duration of the query).
2230 PQgetCancel(PGconn *conn)
2240 cancel = malloc(sizeof(PGcancel));
2244 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2245 cancel->be_pid = conn->be_pid;
2246 cancel->be_key = conn->be_key;
2251 /* PQfreeCancel: free a cancel structure */
2253 PQfreeCancel(PGcancel *cancel)
2261 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2262 * current operation.
2264 * The return value is TRUE if the cancel request was successfully
2265 * dispatched, FALSE if not (in which case an error message is available).
2266 * Note: successful dispatch is no guarantee that there will be any effect at
2267 * the backend. The application must read the operation result as usual.
2269 * CAUTION: we want this routine to be safely callable from a signal handler
2270 * (for example, an application might want to call it in a SIGINT handler).
2271 * This means we cannot use any C library routine that might be non-reentrant.
2272 * malloc/free are often non-reentrant, and anything that might call them is
2273 * just as dangerous. We avoid sprintf here for that reason. Building up
2274 * error messages with strcpy/strcat is tedious but should be quite safe.
2275 * We also save/restore errno in case the signal handler support doesn't.
2277 * internal_cancel() is an internal helper function to make code-sharing
2278 * between the two versions of the cancel function possible.
2281 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2282 char *errbuf, int errbufsize)
2284 int save_errno = SOCK_ERRNO;
2291 CancelRequestPacket cp;
2295 * We need to open a temporary connection to the postmaster. Do this with
2296 * only kernel calls.
2298 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2300 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2301 goto cancel_errReturn;
2304 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2307 if (SOCK_ERRNO == EINTR)
2308 /* Interrupted system call - we'll just try again */
2310 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2311 goto cancel_errReturn;
2315 * We needn't set nonblocking I/O or NODELAY options here.
2318 /* Create and send the cancel request packet. */
2320 crp.packetlen = htonl((uint32) sizeof(crp));
2321 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2322 crp.cp.backendPID = htonl(be_pid);
2323 crp.cp.cancelAuthCode = htonl(be_key);
2326 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2328 if (SOCK_ERRNO == EINTR)
2329 /* Interrupted system call - we'll just try again */
2331 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2332 goto cancel_errReturn;
2336 * Wait for the postmaster to close the connection, which indicates that
2337 * it's processed the request. Without this delay, we might issue another
2338 * command only to find that our cancel zaps that command instead of the
2339 * one we thought we were canceling. Note we don't actually expect this
2340 * read to obtain any data, we are just waiting for EOF to be signaled.
2343 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2345 if (SOCK_ERRNO == EINTR)
2346 /* Interrupted system call - we'll just try again */
2348 /* we ignore other error conditions */
2352 closesocket(tmpsock);
2353 SOCK_ERRNO_SET(save_errno);
2359 * Make sure we don't overflow the error buffer. Leave space for the \n at
2360 * the end, and for the terminating zero.
2362 maxlen = errbufsize - strlen(errbuf) - 2;
2365 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2367 strcat(errbuf, "\n");
2370 closesocket(tmpsock);
2371 SOCK_ERRNO_SET(save_errno);
2376 * PQcancel: request query cancel
2378 * Returns TRUE if able to send the cancel request, FALSE if not.
2380 * On failure, an error message is stored in *errbuf, which must be of size
2381 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2385 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2389 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2393 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2394 errbuf, errbufsize);
2398 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2400 * Returns TRUE if able to send the cancel request, FALSE if not.
2402 * On failure, the error message is saved in conn->errorMessage; this means
2403 * that this can't be used when there might be other active operations on
2404 * the connection object.
2406 * NOTE: error messages will be cut off at the current size of the
2407 * error message buffer, since we dare not try to expand conn->errorMessage!
2410 PQrequestCancel(PGconn *conn)
2414 /* Check we have an open connection */
2420 strlcpy(conn->errorMessage.data,
2421 "PQrequestCancel() -- connection is not open\n",
2422 conn->errorMessage.maxlen);
2423 conn->errorMessage.len = strlen(conn->errorMessage.data);
2428 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2429 conn->errorMessage.data, conn->errorMessage.maxlen);
2432 conn->errorMessage.len = strlen(conn->errorMessage.data);
2439 * pqPacketSend() -- convenience routine to send a message to server.
2441 * pack_type: the single-byte message type code. (Pass zero for startup
2442 * packets, which have no message type code.)
2444 * buf, buf_len: contents of message. The given length includes only what
2445 * is in buf; the message type and message length fields are added here.
2447 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2448 * SIDE_EFFECTS: may block.
2450 * Note: all messages sent with this routine have a length word, whether
2451 * it's protocol 2.0 or 3.0.
2454 pqPacketSend(PGconn *conn, char pack_type,
2455 const void *buf, size_t buf_len)
2457 /* Start the message. */
2458 if (pqPutMsgStart(pack_type, true, conn))
2459 return STATUS_ERROR;
2461 /* Send the message body. */
2462 if (pqPutnchar(buf, buf_len, conn))
2463 return STATUS_ERROR;
2465 /* Finish the message. */
2466 if (pqPutMsgEnd(conn))
2467 return STATUS_ERROR;
2469 /* Flush to ensure backend gets it. */
2471 return STATUS_ERROR;
2478 #define LDAP_URL "ldap://"
2479 #define LDAP_DEF_PORT 389
2480 #define PGLDAP_TIMEOUT 2
2482 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2483 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2489 * Search the LDAP URL passed as first argument, treat the result as a
2490 * string of connection options that are parsed and added to the array of
2491 * options passed as second argument.
2493 * LDAP URLs must conform to RFC 1959 without escape sequences.
2494 * ldap://host:port/dn?attributes?scope?filter?extensions
2497 * 0 if the lookup was successful,
2498 * 1 if the connection to the LDAP server could be established but
2499 * the search was unsuccessful,
2500 * 2 if a connection could not be established, and
2501 * 3 if a fatal error occurred.
2503 * An error message is returned in the third argument for return codes 1 and 3.
2506 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2507 PQExpBuffer errorMessage)
2509 int port = LDAP_DEF_PORT,
2530 char *attrs[2] = {NULL, NULL};
2534 struct berval **values;
2535 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2537 if ((url = strdup(purl)) == NULL)
2539 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2544 * Parse URL components, check for correctness. Basically, url has '\0'
2545 * placed at component boundaries and variables are pointed at each
2549 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2551 printfPQExpBuffer(errorMessage,
2552 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2558 hostname = url + strlen(LDAP_URL);
2559 if (*hostname == '/') /* no hostname? */
2560 hostname = "localhost"; /* the default */
2562 /* dn, "distinguished name" */
2563 p = strchr(url + strlen(LDAP_URL), '/');
2564 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2566 printfPQExpBuffer(errorMessage, libpq_gettext(
2567 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2571 *p = '\0'; /* terminate hostname */
2575 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2577 printfPQExpBuffer(errorMessage, libpq_gettext(
2578 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2586 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2588 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2596 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2598 printfPQExpBuffer(errorMessage,
2599 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2605 if ((p = strchr(filter, '?')) != NULL)
2609 if ((p1 = strchr(hostname, ':')) != NULL)
2616 lport = strtol(portstr, &endptr, 10);
2617 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2619 printfPQExpBuffer(errorMessage, libpq_gettext(
2620 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2627 /* Allow only one attribute */
2628 if (strchr(attrs[0], ',') != NULL)
2630 printfPQExpBuffer(errorMessage, libpq_gettext(
2631 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2637 if (pg_strcasecmp(scopestr, "base") == 0)
2638 scope = LDAP_SCOPE_BASE;
2639 else if (pg_strcasecmp(scopestr, "one") == 0)
2640 scope = LDAP_SCOPE_ONELEVEL;
2641 else if (pg_strcasecmp(scopestr, "sub") == 0)
2642 scope = LDAP_SCOPE_SUBTREE;
2645 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2650 /* initialize LDAP structure */
2651 if ((ld = ldap_init(hostname, port)) == NULL)
2653 printfPQExpBuffer(errorMessage,
2654 libpq_gettext("could not create LDAP structure\n"));
2660 * Initialize connection to the server. We do an explicit bind because we
2661 * want to return 2 if the bind fails.
2663 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2665 /* error in ldap_simple_bind() */
2671 /* wait some time for the connection to succeed */
2673 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2681 /* error in ldap_result() */
2690 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2695 printfPQExpBuffer(errorMessage,
2696 libpq_gettext("lookup on LDAP server failed: %s\n"),
2697 ldap_err2string(rc));
2703 /* complain if there was not exactly one result */
2704 if ((rc = ldap_count_entries(ld, res)) != 1)
2706 printfPQExpBuffer(errorMessage,
2707 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2708 : libpq_gettext("no entry found on LDAP lookup\n"));
2716 if ((entry = ldap_first_entry(ld, res)) == NULL)
2718 /* should never happen */
2719 printfPQExpBuffer(errorMessage,
2720 libpq_gettext("no entry found on LDAP lookup\n"));
2728 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2730 printfPQExpBuffer(errorMessage,
2731 libpq_gettext("attribute has no values on LDAP lookup\n"));
2741 if (values[0] == NULL)
2743 printfPQExpBuffer(errorMessage,
2744 libpq_gettext("attribute has no values on LDAP lookup\n"));
2745 ldap_value_free_len(values);
2750 /* concatenate values to a single string */
2751 for (size = 0, i = 0; values[i] != NULL; ++i)
2752 size += values[i]->bv_len + 1;
2753 if ((result = malloc(size + 1)) == NULL)
2755 printfPQExpBuffer(errorMessage,
2756 libpq_gettext("out of memory\n"));
2757 ldap_value_free_len(values);
2761 for (p = result, i = 0; values[i] != NULL; ++i)
2763 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2764 p += values[i]->bv_len;
2766 if (values[i + 1] == NULL)
2770 ldap_value_free_len(values);
2773 /* parse result string */
2774 oldstate = state = 0;
2775 for (p = result; *p != '\0'; ++p)
2779 case 0: /* between entries */
2780 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2786 case 1: /* in option name */
2787 if (ld_is_sp_tab(*p))
2792 else if (ld_is_nl_cr(*p))
2794 printfPQExpBuffer(errorMessage, libpq_gettext(
2795 "missing \"=\" after \"%s\" in connection info string\n"),
2805 case 2: /* after option name */
2810 else if (!ld_is_sp_tab(*p))
2812 printfPQExpBuffer(errorMessage, libpq_gettext(
2813 "missing \"=\" after \"%s\" in connection info string\n"),
2818 case 3: /* before option value */
2825 else if (ld_is_nl_cr(*p))
2827 optval = optname + strlen(optname); /* empty */
2830 else if (!ld_is_sp_tab(*p))
2836 case 4: /* in unquoted option value */
2837 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
2843 case 5: /* in quoted option value */
2849 else if (*p == '\\')
2854 case 6: /* in quoted option value after escape */
2860 if (state == 0 && oldstate != 0)
2862 found_keyword = false;
2863 for (i = 0; options[i].keyword; i++)
2865 if (strcmp(options[i].keyword, optname) == 0)
2867 if (options[i].val == NULL)
2868 options[i].val = strdup(optval);
2869 found_keyword = true;
2875 printfPQExpBuffer(errorMessage,
2876 libpq_gettext("invalid connection option \"%s\"\n"),
2886 if (state == 5 || state == 6)
2888 printfPQExpBuffer(errorMessage, libpq_gettext(
2889 "unterminated quoted string in connection info string\n"));
2897 #define MAXBUFSIZE 256
2900 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2902 char *service = conninfo_getval(options, "service");
2903 char serviceFile[MAXPGPATH];
2904 bool group_found = false;
2909 * We have to special-case the environment variable PGSERVICE here, since
2910 * this is and should be called before inserting environment defaults for
2911 * other connection options.
2913 if (service == NULL)
2914 service = getenv("PGSERVICE");
2917 * This could be used by any application so we can't use the binary
2918 * location to find our config files.
2920 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2921 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2923 if (service != NULL)
2926 char buf[MAXBUFSIZE],
2929 f = fopen(serviceFile, "r");
2932 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2937 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
2941 if (strlen(line) >= sizeof(buf) - 1)
2944 printfPQExpBuffer(errorMessage,
2945 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2951 /* ignore EOL at end of line */
2952 if (strlen(line) && line[strlen(line) - 1] == '\n')
2953 line[strlen(line) - 1] = 0;
2955 /* ignore leading blanks */
2956 while (*line && isspace((unsigned char) line[0]))
2959 /* ignore comments and empty lines */
2960 if (strlen(line) == 0 || line[0] == '#')
2963 /* Check for right groupname */
2968 /* group info already read */
2973 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2974 line[strlen(service) + 1] == ']')
2977 group_found = false;
2984 * Finally, we are in the right group and can parse the
2992 if (strncmp(line, "ldap", 4) == 0)
2994 int rc = ldapServiceLookup(line, options, errorMessage);
2996 /* if rc = 2, go on reading for fallback */
3013 val = strchr(line, '=');
3016 printfPQExpBuffer(errorMessage,
3017 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3026 * Set the parameter --- but don't override any previous
3029 found_keyword = false;
3030 for (i = 0; options[i].keyword; i++)
3032 if (strcmp(options[i].keyword, key) == 0)
3034 if (options[i].val == NULL)
3035 options[i].val = strdup(val);
3036 found_keyword = true;
3043 printfPQExpBuffer(errorMessage,
3044 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3062 * Conninfo parser routine
3064 * If successful, a malloc'd PQconninfoOption array is returned.
3065 * If not successful, NULL is returned and an error message is
3066 * left in errorMessage.
3068 static PQconninfoOption *
3069 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
3077 PQconninfoOption *options;
3078 PQconninfoOption *option;
3080 /* Make a working copy of PQconninfoOptions */
3081 options = malloc(sizeof(PQconninfoOptions));
3082 if (options == NULL)
3084 printfPQExpBuffer(errorMessage,
3085 libpq_gettext("out of memory\n"));
3088 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3090 /* Need a modifiable copy of the input string */
3091 if ((buf = strdup(conninfo)) == NULL)
3093 printfPQExpBuffer(errorMessage,
3094 libpq_gettext("out of memory\n"));
3095 PQconninfoFree(options);
3102 /* Skip blanks before the parameter name */
3103 if (isspace((unsigned char) *cp))
3109 /* Get the parameter name */
3115 if (isspace((unsigned char) *cp))
3120 if (!isspace((unsigned char) *cp))
3129 /* Check that there is a following '=' */
3132 printfPQExpBuffer(errorMessage,
3133 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3135 PQconninfoFree(options);
3141 /* Skip blanks after the '=' */
3144 if (!isspace((unsigned char) *cp))
3149 /* Get the parameter value */
3157 if (isspace((unsigned char) *cp))
3181 printfPQExpBuffer(errorMessage,
3182 libpq_gettext("unterminated quoted string in connection info string\n"));
3183 PQconninfoFree(options);
3205 * Now we have the name and the value. Search for the param record.
3207 for (option = options; option->keyword != NULL; option++)
3209 if (strcmp(option->keyword, pname) == 0)
3212 if (option->keyword == NULL)
3214 printfPQExpBuffer(errorMessage,
3215 libpq_gettext("invalid connection option \"%s\"\n"),
3217 PQconninfoFree(options);
3227 option->val = strdup(pval);
3230 printfPQExpBuffer(errorMessage,
3231 libpq_gettext("out of memory\n"));
3232 PQconninfoFree(options);
3238 /* Done with the modifiable input string */
3242 * If there's a service spec, use it to obtain any not-explicitly-given
3245 if (parseServiceInfo(options, errorMessage))
3247 PQconninfoFree(options);
3252 * Get the fallback resources for parameters not specified in the conninfo
3253 * string nor the service.
3255 for (option = options; option->keyword != NULL; option++)
3257 if (option->val != NULL)
3258 continue; /* Value was in conninfo or service */
3261 * Try to get the environment variable fallback
3263 if (option->envvar != NULL)
3265 if ((tmp = getenv(option->envvar)) != NULL)
3267 option->val = strdup(tmp);
3270 printfPQExpBuffer(errorMessage,
3271 libpq_gettext("out of memory\n"));
3272 PQconninfoFree(options);
3280 * No environment variable specified or this one isn't set - try
3283 if (option->compiled != NULL)
3285 option->val = strdup(option->compiled);
3288 printfPQExpBuffer(errorMessage,
3289 libpq_gettext("out of memory\n"));
3290 PQconninfoFree(options);
3297 * Special handling for user
3299 if (strcmp(option->keyword, "user") == 0)
3301 option->val = pg_fe_getauthname(errorMessage);
3311 conninfo_getval(PQconninfoOption *connOptions,
3312 const char *keyword)
3314 PQconninfoOption *option;
3316 for (option = connOptions; option->keyword != NULL; option++)
3318 if (strcmp(option->keyword, keyword) == 0)
3327 PQconninfoFree(PQconninfoOption *connOptions)
3329 PQconninfoOption *option;
3331 if (connOptions == NULL)
3334 for (option = connOptions; option->keyword != NULL; option++)
3336 if (option->val != NULL)
3343 /* =========== accessor functions for PGconn ========= */
3345 PQdb(const PGconn *conn)
3349 return conn->dbName;
3353 PQuser(const PGconn *conn)
3357 return conn->pguser;
3361 PQpass(const PGconn *conn)
3365 return conn->pgpass;
3369 PQhost(const PGconn *conn)
3373 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3377 PQport(const PGconn *conn)
3381 return conn->pgport;
3385 PQtty(const PGconn *conn)
3393 PQoptions(const PGconn *conn)
3397 return conn->pgoptions;
3401 PQstatus(const PGconn *conn)
3404 return CONNECTION_BAD;
3405 return conn->status;
3408 PGTransactionStatusType
3409 PQtransactionStatus(const PGconn *conn)
3411 if (!conn || conn->status != CONNECTION_OK)
3412 return PQTRANS_UNKNOWN;
3413 if (conn->asyncStatus != PGASYNC_IDLE)
3414 return PQTRANS_ACTIVE;
3415 return conn->xactStatus;
3419 PQparameterStatus(const PGconn *conn, const char *paramName)
3421 const pgParameterStatus *pstatus;
3423 if (!conn || !paramName)
3425 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3427 if (strcmp(pstatus->name, paramName) == 0)
3428 return pstatus->value;
3434 PQprotocolVersion(const PGconn *conn)
3438 if (conn->status == CONNECTION_BAD)
3440 return PG_PROTOCOL_MAJOR(conn->pversion);
3444 PQserverVersion(const PGconn *conn)
3448 if (conn->status == CONNECTION_BAD)
3450 return conn->sversion;
3454 PQerrorMessage(const PGconn *conn)
3457 return libpq_gettext("connection pointer is NULL\n");
3459 return conn->errorMessage.data;
3463 PQsocket(const PGconn *conn)
3471 PQbackendPID(const PGconn *conn)
3473 if (!conn || conn->status != CONNECTION_OK)
3475 return conn->be_pid;
3479 PQconnectionUsedPassword(const PGconn *conn)
3483 if (conn->areq == AUTH_REQ_MD5 ||
3484 conn->areq == AUTH_REQ_CRYPT ||
3485 conn->areq == AUTH_REQ_PASSWORD)
3492 PQclientEncoding(const PGconn *conn)
3494 if (!conn || conn->status != CONNECTION_OK)
3496 return conn->client_encoding;
3500 PQsetClientEncoding(PGconn *conn, const char *encoding)
3503 static const char query[] = "set client_encoding to '%s'";
3507 if (!conn || conn->status != CONNECTION_OK)
3513 /* check query buffer overflow */
3514 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3517 /* ok, now send a query */
3518 sprintf(qbuf, query, encoding);
3519 res = PQexec(conn, qbuf);
3523 if (res->resultStatus != PGRES_COMMAND_OK)
3528 * In protocol 2 we have to assume the setting will stick, and adjust
3529 * our state immediately. In protocol 3 and up we can rely on the
3530 * backend to report the parameter value, and we'll change state at
3533 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3534 pqSaveParameterStatus(conn, "client_encoding", encoding);
3535 status = 0; /* everything is ok */
3542 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3547 return PQERRORS_DEFAULT;
3548 old = conn->verbosity;
3549 conn->verbosity = verbosity;
3554 PQtrace(PGconn *conn, FILE *debug_port)
3559 conn->Pfdebug = debug_port;
3563 PQuntrace(PGconn *conn)
3569 fflush(conn->Pfdebug);
3570 conn->Pfdebug = NULL;
3575 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3577 PQnoticeReceiver old;
3582 old = conn->noticeHooks.noticeRec;
3585 conn->noticeHooks.noticeRec = proc;
3586 conn->noticeHooks.noticeRecArg = arg;
3592 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3594 PQnoticeProcessor old;
3599 old = conn->noticeHooks.noticeProc;
3602 conn->noticeHooks.noticeProc = proc;
3603 conn->noticeHooks.noticeProcArg = arg;
3609 * The default notice message receiver just gets the standard notice text
3610 * and sends it to the notice processor. This two-level setup exists
3611 * mostly for backwards compatibility; perhaps we should deprecate use of
3612 * PQsetNoticeProcessor?
3615 defaultNoticeReceiver(void *arg, const PGresult *res)
3617 (void) arg; /* not used */
3618 if (res->noticeHooks.noticeProc != NULL)
3619 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3620 PQresultErrorMessage(res));
3624 * The default notice message processor just prints the
3625 * message on stderr. Applications can override this if they
3626 * want the messages to go elsewhere (a window, for example).
3627 * Note that simply discarding notices is probably a bad idea.
3630 defaultNoticeProcessor(void *arg, const char *message)
3632 (void) arg; /* not used */
3633 /* Note: we expect the supplied string to end with a newline already. */
3634 fprintf(stderr, "%s", message);
3638 * returns a pointer to the next token or NULL if the current
3639 * token doesn't match
3642 pwdfMatchesString(char *buf, char *token)
3646 bool bslash = false;
3648 if (buf == NULL || token == NULL)
3656 if (*tbuf == '\\' && !bslash)
3661 if (*tbuf == ':' && *ttok == 0 && !bslash)
3677 /* Get a password from the password file. Return value is malloc'd. */
3679 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3682 char pgpassfile[MAXPGPATH];
3683 struct stat stat_buf;
3686 #define LINELEN NAMEDATALEN*5
3689 if (dbname == NULL || strlen(dbname) == 0)
3692 if (username == NULL || strlen(username) == 0)
3695 /* 'localhost' matches pghost of '' or the default socket directory */
3696 if (hostname == NULL)
3697 hostname = DefaultHost;
3698 else if (is_absolute_path(hostname))
3701 * We should probably use canonicalize_path(), but then we have to
3702 * bring path.c into libpq, and it doesn't seem worth it.
3704 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3705 hostname = DefaultHost;
3708 port = DEF_PGPORT_STR;
3710 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3711 /* use the literal path from the environment, if set */
3712 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3715 char homedir[MAXPGPATH];
3717 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3719 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3722 /* If password file cannot be opened, ignore it. */
3723 if (stat(pgpassfile, &stat_buf) == -1)
3728 if (!S_ISREG(stat_buf.st_mode))
3731 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3736 /* If password file is insecure, alert the user and ignore it. */
3737 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3740 libpq_gettext("WARNING: password file \"%s\" has world or group read access; permission should be u=rw (0600)\n"),
3747 * On Win32, the directory is protected, so we don't have to check the
3752 fp = fopen(pgpassfile, "r");
3762 fgets(buf, sizeof(buf), fp);
3768 /* Remove trailing newline */
3769 if (buf[len - 1] == '\n')
3772 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3773 (t = pwdfMatchesString(t, port)) == NULL ||
3774 (t = pwdfMatchesString(t, dbname)) == NULL ||
3775 (t = pwdfMatchesString(t, username)) == NULL)
3789 * Obtain user's home directory, return in given buffer
3791 * On Unix, this actually returns the user's home directory. On Windows
3792 * it returns the PostgreSQL-specific application data folder.
3794 * This is essentially the same as get_home_path(), but we don't use that
3795 * because we don't want to pull path.c into libpq (it pollutes application
3799 pqGetHomeDirectory(char *buf, int bufsize)
3802 char pwdbuf[BUFSIZ];
3803 struct passwd pwdstr;
3804 struct passwd *pwd = NULL;
3806 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3808 strlcpy(buf, pwd->pw_dir, bufsize);
3811 char tmppath[MAX_PATH];
3813 ZeroMemory(tmppath, sizeof(tmppath));
3814 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3816 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3822 * To keep the API consistent, the locking stubs are always provided, even
3823 * if they are not required.
3827 default_threadlock(int acquire)
3829 #ifdef ENABLE_THREAD_SAFETY
3831 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3833 static pthread_mutex_t singlethread_lock = NULL;
3834 static long mutex_initlock = 0;
3836 if (singlethread_lock == NULL)
3838 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3839 /* loop, another thread own the lock */ ;
3840 if (singlethread_lock == NULL)
3841 pthread_mutex_init(&singlethread_lock, NULL);
3842 InterlockedExchange(&mutex_initlock, 0);
3846 pthread_mutex_lock(&singlethread_lock);
3848 pthread_mutex_unlock(&singlethread_lock);
3853 PQregisterThreadLock(pgthreadlock_t newhandler)
3855 pgthreadlock_t prev = pg_g_threadlock;
3858 pg_g_threadlock = newhandler;
3860 pg_g_threadlock = default_threadlock;