1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2006, 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.333 2006/06/07 22:24:46 momjian Exp $
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
30 #include "libpq-int.h"
32 #include "pg_config_paths.h"
39 #define _WIN32_IE 0x0500
46 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #ifdef HAVE_NETINET_TCP_H
50 #include <netinet/tcp.h>
52 #include <arpa/inet.h>
55 #ifdef ENABLE_THREAD_SAFETY
57 #include "pthread-win32.h"
64 #include "mb/pg_wchar.h"
72 #define PGPASSFILE ".pgpass"
74 #define PGPASSFILE "pgpass.conf"
77 /* fall back options if they are not specified by arguments or defined
78 by environment variables */
79 #define DefaultHost "localhost"
81 #define DefaultOption ""
82 #define DefaultAuthtype ""
83 #define DefaultPassword ""
85 #define DefaultSSLMode "prefer"
87 #define DefaultSSLMode "disable"
91 * Definition of the conninfo parameters and their fallback resources.
93 * If Environment-Var and Compiled-in are specified as NULL, no
94 * fallback is available. If after all no value can be determined
95 * for an option, an error is returned.
97 * The value for the username is treated specially in conninfo_parse.
98 * If the Compiled-in resource is specified as a NULL value, the
99 * user is determined by pg_fe_getauthname().
101 * The Label and Disp-Char entries are provided for applications that
102 * want to use PQconndefaults() to create a generic database connection
103 * dialog. Disp-Char is defined as follows:
104 * "" Normal input field
105 * "*" Password field - hide value
106 * "D" Debug option - don't show by default
108 * PQconninfoOptions[] is a constant static array that we use to initialize
109 * a dynamically allocated working copy. All the "val" fields in
110 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
111 * fields point to malloc'd strings that should be freed when the working
112 * array is freed (see PQconninfoFree).
115 static const PQconninfoOption PQconninfoOptions[] = {
117 * "authtype" is no longer used, so mark it "don't show". We keep it in
118 * the array so as not to reject conninfo strings from old apps that might
119 * still try to set it.
121 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
122 "Database-Authtype", "D", 20},
124 {"service", "PGSERVICE", NULL, NULL,
125 "Database-Service", "", 20},
127 {"user", "PGUSER", NULL, NULL,
128 "Database-User", "", 20},
130 {"password", "PGPASSWORD", NULL, NULL,
131 "Database-Password", "*", 20},
133 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
134 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
136 {"dbname", "PGDATABASE", NULL, NULL,
137 "Database-Name", "", 20},
139 {"host", "PGHOST", NULL, NULL,
140 "Database-Host", "", 40},
142 {"hostaddr", "PGHOSTADDR", NULL, NULL,
143 "Database-Host-IP-Address", "", 45},
145 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
146 "Database-Port", "", 6},
149 * "tty" is no longer used either, but keep it present for backwards
152 {"tty", "PGTTY", DefaultTty, NULL,
153 "Backend-Debug-TTY", "D", 40},
155 {"options", "PGOPTIONS", DefaultOption, NULL,
156 "Backend-Debug-Options", "D", 40},
161 * "requiressl" is deprecated, its purpose having been taken over by
162 * "sslmode". It remains for backwards compatibility.
164 {"requiressl", "PGREQUIRESSL", "0", NULL,
165 "Require-SSL", "D", 1},
169 * "sslmode" option is allowed even without client SSL support because the
170 * client can still handle SSL modes "disable" and "allow".
172 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
173 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
176 /* Kerberos authentication supports specifying the service name */
177 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
178 "Kerberos-service-name", "", 20},
181 /* Terminating entry --- MUST BE LAST */
182 {NULL, NULL, NULL, NULL,
186 static const PQEnvironmentOption EnvironmentOptions[] =
188 /* common user-interface settings */
190 "PGDATESTYLE", "datestyle"
196 "PGCLIENTENCODING", "client_encoding"
198 /* internal performance-related settings */
208 static bool connectOptions1(PGconn *conn, const char *conninfo);
209 static bool connectOptions2(PGconn *conn);
210 static int connectDBStart(PGconn *conn);
211 static int connectDBComplete(PGconn *conn);
212 static PGconn *makeEmptyPGconn(void);
213 static void freePGconn(PGconn *conn);
214 static void closePGconn(PGconn *conn);
215 static PQconninfoOption *conninfo_parse(const char *conninfo,
216 PQExpBuffer errorMessage);
217 static char *conninfo_getval(PQconninfoOption *connOptions,
218 const char *keyword);
219 static void defaultNoticeReceiver(void *arg, const PGresult *res);
220 static void defaultNoticeProcessor(void *arg, const char *message);
221 static int parseServiceInfo(PQconninfoOption *options,
222 PQExpBuffer errorMessage);
223 static char *pwdfMatchesString(char *buf, char *token);
224 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
226 static void default_threadlock(int acquire);
229 /* global variable because fe-auth.c needs to access it */
230 pgthreadlock_t pg_g_threadlock = default_threadlock;
234 * Connecting to a Database
236 * There are now four different ways a user of this API can connect to the
237 * database. Two are not recommended for use in new code, because of their
238 * lack of extensibility with respect to the passing of options to the
239 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
242 * If it is desired to connect in a synchronous (blocking) manner, use the
243 * function PQconnectdb.
245 * To connect in an asynchronous (non-blocking) manner, use the functions
246 * PQconnectStart, and PQconnectPoll.
248 * Internally, the static functions connectDBStart, connectDBComplete
249 * are part of the connection procedure.
255 * establishes a connection to a postgres backend through the postmaster
256 * using connection information in a string.
258 * The conninfo string is a white-separated list of
262 * definitions. Value might be a single value containing no whitespaces or
263 * a single quoted string. If a single quote should appear anywhere in
264 * the value, it must be escaped with a backslash like \'
266 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
267 * if a memory allocation failed.
268 * If the status field of the connection returned is CONNECTION_BAD,
269 * then some fields may be null'ed out instead of having valid values.
271 * You should call PQfinish (if conn is not NULL) regardless of whether this
275 PQconnectdb(const char *conninfo)
277 PGconn *conn = PQconnectStart(conninfo);
279 if (conn && conn->status != CONNECTION_BAD)
280 (void) connectDBComplete(conn);
288 * Begins the establishment of a connection to a postgres backend through the
289 * postmaster using connection information in a string.
291 * See comment for PQconnectdb for the definition of the string format.
293 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
294 * you should not attempt to proceed with this connection. If the status
295 * field of the connection returned is CONNECTION_BAD, an error has
296 * occurred. In this case you should call PQfinish on the result, (perhaps
297 * inspecting the error message first). Other fields of the structure may not
298 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
299 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
302 * See PQconnectPoll for more info.
305 PQconnectStart(const char *conninfo)
310 * Allocate memory for the conn structure
312 conn = makeEmptyPGconn();
317 * Parse the conninfo string
319 if (!connectOptions1(conn, conninfo))
323 * Compute derived options
325 if (!connectOptions2(conn))
329 * Connect to the database
331 if (!connectDBStart(conn))
333 /* Just in case we failed to set it in connectDBStart */
334 conn->status = CONNECTION_BAD;
343 * Internal subroutine to set up connection parameters given an already-
344 * created PGconn and a conninfo string. Derived settings should be
345 * processed by calling connectOptions2 next. (We split them because
346 * PQsetdbLogin overrides defaults in between.)
348 * Returns true if OK, false if trouble (in which case errorMessage is set
349 * and so is conn->status).
352 connectOptions1(PGconn *conn, const char *conninfo)
354 PQconninfoOption *connOptions;
358 * Parse the conninfo string
360 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
361 if (connOptions == NULL)
363 conn->status = CONNECTION_BAD;
364 /* errorMessage is already set */
369 * Move option values into conn structure
371 * Don't put anything cute here --- intelligence should be in
372 * connectOptions2 ...
374 * XXX: probably worth checking strdup() return value here...
376 tmp = conninfo_getval(connOptions, "hostaddr");
377 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
378 tmp = conninfo_getval(connOptions, "host");
379 conn->pghost = tmp ? strdup(tmp) : NULL;
380 tmp = conninfo_getval(connOptions, "port");
381 conn->pgport = tmp ? strdup(tmp) : NULL;
382 tmp = conninfo_getval(connOptions, "tty");
383 conn->pgtty = tmp ? strdup(tmp) : NULL;
384 tmp = conninfo_getval(connOptions, "options");
385 conn->pgoptions = tmp ? strdup(tmp) : NULL;
386 tmp = conninfo_getval(connOptions, "dbname");
387 conn->dbName = tmp ? strdup(tmp) : NULL;
388 tmp = conninfo_getval(connOptions, "user");
389 conn->pguser = tmp ? strdup(tmp) : NULL;
390 tmp = conninfo_getval(connOptions, "password");
391 conn->pgpass = tmp ? strdup(tmp) : NULL;
392 tmp = conninfo_getval(connOptions, "connect_timeout");
393 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
394 tmp = conninfo_getval(connOptions, "sslmode");
395 conn->sslmode = tmp ? strdup(tmp) : NULL;
397 tmp = conninfo_getval(connOptions, "requiressl");
398 if (tmp && tmp[0] == '1')
400 /* here warn that the requiressl option is deprecated? */
403 conn->sslmode = strdup("require");
407 tmp = conninfo_getval(connOptions, "krbsrvname");
408 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
412 * Free the option info - all is in conn now
414 PQconninfoFree(connOptions);
422 * Compute derived connection options after absorbing all user-supplied info.
424 * Returns true if OK, false if trouble (in which case errorMessage is set
425 * and so is conn->status).
428 connectOptions2(PGconn *conn)
431 * If database name was not given, default it to equal user name
433 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
434 && conn->pguser != NULL)
438 conn->dbName = strdup(conn->pguser);
442 * Supply default password if none given
444 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
448 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
449 conn->dbName, conn->pguser);
450 if (conn->pgpass == NULL)
451 conn->pgpass = strdup(DefaultPassword);
455 * Allow unix socket specification in the host name
457 if (conn->pghost && is_absolute_path(conn->pghost))
459 if (conn->pgunixsocket)
460 free(conn->pgunixsocket);
461 conn->pgunixsocket = conn->pghost;
466 * validate sslmode option
470 if (strcmp(conn->sslmode, "disable") != 0
471 && strcmp(conn->sslmode, "allow") != 0
472 && strcmp(conn->sslmode, "prefer") != 0
473 && strcmp(conn->sslmode, "require") != 0)
475 conn->status = CONNECTION_BAD;
476 printfPQExpBuffer(&conn->errorMessage,
477 libpq_gettext("invalid sslmode value: \"%s\"\n"),
483 switch (conn->sslmode[0])
485 case 'a': /* "allow" */
486 case 'p': /* "prefer" */
489 * warn user that an SSL connection will never be negotiated
490 * since SSL was not compiled in?
494 case 'r': /* "require" */
495 conn->status = CONNECTION_BAD;
496 printfPQExpBuffer(&conn->errorMessage,
497 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
504 conn->sslmode = strdup(DefaultSSLMode);
507 * Only if we get this far is it appropriate to try to connect.
508 * (We need a state flag, rather than just the boolean result of
509 * this function, in case someone tries to PQreset() the PGconn.)
511 conn->options_valid = true;
519 * Parse an empty string like PQconnectdb() would do and return the
520 * working connection options array.
522 * Using this function, an application may determine all possible options
523 * and their current default values.
525 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
526 * and should be freed when no longer needed via PQconninfoFree(). (In prior
527 * versions, the returned array was static, but that's not thread-safe.)
528 * Pre-7.0 applications that use this function will see a small memory leak
529 * until they are updated to call PQconninfoFree.
534 PQExpBufferData errorBuf;
535 PQconninfoOption *connOptions;
537 initPQExpBuffer(&errorBuf);
538 connOptions = conninfo_parse("", &errorBuf);
539 termPQExpBuffer(&errorBuf);
546 * establishes a connection to a postgres backend through the postmaster
547 * at the specified host and port.
549 * returns a PGconn* which is needed for all subsequent libpq calls
551 * if the status field of the connection returned is CONNECTION_BAD,
552 * then only the errorMessage is likely to be useful.
556 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
557 const char *pgtty, const char *dbName, const char *login,
563 * Allocate memory for the conn structure
565 conn = makeEmptyPGconn();
570 * Parse an empty conninfo string in order to set up the same defaults
571 * that PQconnectdb() would use.
573 if (!connectOptions1(conn, ""))
577 * Absorb specified options into conn structure, overriding defaults
579 if (pghost && pghost[0] != '\0')
583 conn->pghost = strdup(pghost);
586 if (pgport && pgport[0] != '\0')
590 conn->pgport = strdup(pgport);
593 if (pgoptions && pgoptions[0] != '\0')
596 free(conn->pgoptions);
597 conn->pgoptions = strdup(pgoptions);
600 if (pgtty && pgtty[0] != '\0')
604 conn->pgtty = strdup(pgtty);
607 if (dbName && dbName[0] != '\0')
611 conn->dbName = strdup(dbName);
614 if (login && login[0] != '\0')
618 conn->pguser = strdup(login);
621 if (pwd && pwd[0] != '\0')
625 conn->pgpass = strdup(pwd);
629 * Compute derived options
631 if (!connectOptions2(conn))
635 * Connect to the database
637 if (connectDBStart(conn))
638 (void) connectDBComplete(conn);
646 * Sets the TCP_NODELAY socket option.
647 * Returns 1 if successful, 0 if not.
651 connectNoDelay(PGconn *conn)
656 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
662 printfPQExpBuffer(&conn->errorMessage,
663 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
664 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
674 * connectFailureMessage -
675 * create a friendly error message on connection failure.
679 connectFailureMessage(PGconn *conn, int errorno)
683 #ifdef HAVE_UNIX_SOCKETS
684 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
686 char service[NI_MAXHOST];
688 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
690 service, sizeof(service),
692 printfPQExpBuffer(&conn->errorMessage,
693 libpq_gettext("could not connect to server: %s\n"
694 "\tIs the server running locally and accepting\n"
695 "\tconnections on Unix domain socket \"%s\"?\n"),
696 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
700 #endif /* HAVE_UNIX_SOCKETS */
702 printfPQExpBuffer(&conn->errorMessage,
703 libpq_gettext("could not connect to server: %s\n"
704 "\tIs the server running on host \"%s\" and accepting\n"
705 "\tTCP/IP connections on port %s?\n"),
706 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
719 * Begin the process of making a connection to the backend.
721 * Returns 1 if successful, 0 if not.
725 connectDBStart(PGconn *conn)
729 struct addrinfo *addrs = NULL;
730 struct addrinfo hint;
737 if (!conn->options_valid)
738 goto connect_errReturn;
740 /* Ensure our buffers are empty */
741 conn->inStart = conn->inCursor = conn->inEnd = 0;
745 * Determine the parameters to pass to pg_getaddrinfo_all.
748 /* Initialize hint structure */
749 MemSet(&hint, 0, sizeof(hint));
750 hint.ai_socktype = SOCK_STREAM;
751 hint.ai_family = AF_UNSPEC;
753 /* Set up port number as a string */
754 if (conn->pgport != NULL && conn->pgport[0] != '\0')
755 portnum = atoi(conn->pgport);
757 portnum = DEF_PGPORT;
758 snprintf(portstr, sizeof(portstr), "%d", portnum);
760 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
762 /* Using pghostaddr avoids a hostname lookup */
763 node = conn->pghostaddr;
764 hint.ai_family = AF_UNSPEC;
765 hint.ai_flags = AI_NUMERICHOST;
767 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
769 /* Using pghost, so we have to look-up the hostname */
771 hint.ai_family = AF_UNSPEC;
775 #ifdef HAVE_UNIX_SOCKETS
776 /* pghostaddr and pghost are NULL, so use Unix domain socket */
778 hint.ai_family = AF_UNIX;
779 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
781 /* Without Unix sockets, default to localhost instead */
783 hint.ai_family = AF_UNSPEC;
784 #endif /* HAVE_UNIX_SOCKETS */
787 /* Use pg_getaddrinfo_all() to resolve the address */
788 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
792 printfPQExpBuffer(&conn->errorMessage,
793 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
794 node, gai_strerror(ret));
796 printfPQExpBuffer(&conn->errorMessage,
797 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
798 portstr, gai_strerror(ret));
800 pg_freeaddrinfo_all(hint.ai_family, addrs);
801 goto connect_errReturn;
805 /* setup values based on SSL mode */
806 if (conn->sslmode[0] == 'd') /* "disable" */
807 conn->allow_ssl_try = false;
808 else if (conn->sslmode[0] == 'a') /* "allow" */
809 conn->wait_ssl_try = true;
813 * Set up to try to connect, with protocol 3.0 as the first attempt.
815 conn->addrlist = addrs;
816 conn->addr_cur = addrs;
817 conn->addrlist_family = hint.ai_family;
818 conn->pversion = PG_PROTOCOL(3, 0);
819 conn->status = CONNECTION_NEEDED;
822 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
823 * so that it can easily be re-executed if needed again during the
824 * asynchronous startup process. However, we must run it once here,
825 * because callers expect a success return from this routine to mean that
826 * we are in PGRES_POLLING_WRITING connection state.
828 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
834 pqsecure_close(conn);
835 closesocket(conn->sock);
838 conn->status = CONNECTION_BAD;
846 * Block and complete a connection.
848 * Returns 1 on success, 0 on failure.
851 connectDBComplete(PGconn *conn)
853 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
854 time_t finish_time = ((time_t) -1);
856 if (conn == NULL || conn->status == CONNECTION_BAD)
860 * Set up a time limit, if connect_timeout isn't zero.
862 if (conn->connect_timeout != NULL)
864 int timeout = atoi(conn->connect_timeout);
869 * Rounding could cause connection to fail; need at least 2 secs
873 /* calculate the finish time based on start + timeout */
874 finish_time = time(NULL) + timeout;
881 * Wait, if necessary. Note that the initial state (just after
882 * PQconnectStart) is to wait for the socket to select for writing.
886 case PGRES_POLLING_OK:
887 return 1; /* success! */
889 case PGRES_POLLING_READING:
890 if (pqWaitTimed(1, 0, conn, finish_time))
892 conn->status = CONNECTION_BAD;
897 case PGRES_POLLING_WRITING:
898 if (pqWaitTimed(0, 1, conn, finish_time))
900 conn->status = CONNECTION_BAD;
906 /* Just in case we failed to set it in PQconnectPoll */
907 conn->status = CONNECTION_BAD;
912 * Now try to advance the state machine.
914 flag = PQconnectPoll(conn);
921 * Poll an asynchronous connection.
923 * Returns a PostgresPollingStatusType.
924 * Before calling this function, use select(2) to determine when data
927 * You must call PQfinish whether or not this fails.
929 * This function and PQconnectStart are intended to allow connections to be
930 * made without blocking the execution of your program on remote I/O. However,
931 * there are a number of caveats:
933 * o If you call PQtrace, ensure that the stream object into which you trace
935 * o If you do not supply an IP address for the remote host (i.e. you
936 * supply a host name instead) then PQconnectStart will block on
937 * gethostbyname. You will be fine if using Unix sockets (i.e. by
938 * supplying neither a host name nor a host address).
939 * o If your backend wants to use Kerberos authentication then you must
940 * supply both a host name and a host address, otherwise this function
941 * may block on gethostname.
945 PostgresPollingStatusType
946 PQconnectPoll(PGconn *conn)
952 return PGRES_POLLING_FAILED;
954 /* Get the new data */
955 switch (conn->status)
958 * We really shouldn't have been polled in these two cases, but we
962 return PGRES_POLLING_FAILED;
964 return PGRES_POLLING_OK;
966 /* These are reading states */
967 case CONNECTION_AWAITING_RESPONSE:
968 case CONNECTION_AUTH_OK:
970 /* Load waiting data */
971 int n = pqReadData(conn);
976 return PGRES_POLLING_READING;
981 /* These are writing states, so we just proceed. */
982 case CONNECTION_STARTED:
983 case CONNECTION_MADE:
986 /* We allow pqSetenvPoll to decide whether to proceed. */
987 case CONNECTION_SETENV:
990 /* Special cases: proceed without waiting. */
991 case CONNECTION_SSL_STARTUP:
992 case CONNECTION_NEEDED:
996 printfPQExpBuffer(&conn->errorMessage,
998 "invalid connection state, "
999 "probably indicative of memory corruption\n"
1005 keep_going: /* We will come back to here until there is
1006 * nothing left to do. */
1007 switch (conn->status)
1009 case CONNECTION_NEEDED:
1012 * Try to initiate a connection to one of the addresses
1013 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1014 * next one to try. We fail when we run out of addresses
1015 * (reporting the error returned for the *last* alternative,
1016 * which may not be what users expect :-().
1018 while (conn->addr_cur != NULL)
1020 struct addrinfo *addr_cur = conn->addr_cur;
1022 /* Remember current address for possible error msg */
1023 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1024 addr_cur->ai_addrlen);
1025 conn->raddr.salen = addr_cur->ai_addrlen;
1028 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1032 * ignore socket() failure if we have more addresses
1035 if (addr_cur->ai_next != NULL)
1037 conn->addr_cur = addr_cur->ai_next;
1040 printfPQExpBuffer(&conn->errorMessage,
1041 libpq_gettext("could not create socket: %s\n"),
1042 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1047 * Select socket options: no delay of outgoing data for
1048 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1051 if (!IS_AF_UNIX(addr_cur->ai_family))
1053 if (!connectNoDelay(conn))
1055 closesocket(conn->sock);
1057 conn->addr_cur = addr_cur->ai_next;
1061 if (!pg_set_noblock(conn->sock))
1063 printfPQExpBuffer(&conn->errorMessage,
1064 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1065 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1066 closesocket(conn->sock);
1068 conn->addr_cur = addr_cur->ai_next;
1073 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1075 printfPQExpBuffer(&conn->errorMessage,
1076 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1077 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1078 closesocket(conn->sock);
1080 conn->addr_cur = addr_cur->ai_next;
1083 #endif /* F_SETFD */
1086 * Start/make connection. This should not block, since we
1087 * are in nonblock mode. If it does, well, too bad.
1089 if (connect(conn->sock, addr_cur->ai_addr,
1090 addr_cur->ai_addrlen) < 0)
1092 if (SOCK_ERRNO == EINPROGRESS ||
1093 SOCK_ERRNO == EWOULDBLOCK ||
1094 SOCK_ERRNO == EINTR ||
1098 * This is fine - we're in non-blocking mode, and
1099 * the connection is in progress. Tell caller to
1100 * wait for write-ready on socket.
1102 conn->status = CONNECTION_STARTED;
1103 return PGRES_POLLING_WRITING;
1105 /* otherwise, trouble */
1110 * Hm, we're connected already --- seems the "nonblock
1111 * connection" wasn't. Advance the state machine and
1112 * go do the next stuff.
1114 conn->status = CONNECTION_STARTED;
1119 * This connection failed --- set up error report, then
1120 * close socket (do it this way in case close() affects
1121 * the value of errno...). We will ignore the connect()
1122 * failure and keep going if there are more addresses.
1124 connectFailureMessage(conn, SOCK_ERRNO);
1125 if (conn->sock >= 0)
1127 closesocket(conn->sock);
1132 * Try the next address, if any.
1134 conn->addr_cur = addr_cur->ai_next;
1135 } /* loop over addresses */
1138 * Ooops, no more addresses. An appropriate error message is
1139 * already set up, so just set the right status.
1144 case CONNECTION_STARTED:
1147 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1150 * Write ready, since we've made it here, so the connection
1151 * has been made ... or has failed.
1155 * Now check (using getsockopt) that there is not an error
1156 * state waiting for us on the socket.
1159 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1160 (char *) &optval, &optlen) == -1)
1162 printfPQExpBuffer(&conn->errorMessage,
1163 libpq_gettext("could not get socket error status: %s\n"),
1164 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1167 else if (optval != 0)
1170 * When using a nonblocking connect, we will typically see
1171 * connect failures at this point, so provide a friendly
1174 connectFailureMessage(conn, optval);
1177 * If more addresses remain, keep trying, just as in the
1178 * case where connect() returned failure immediately.
1180 if (conn->addr_cur->ai_next != NULL)
1182 if (conn->sock >= 0)
1184 closesocket(conn->sock);
1187 conn->addr_cur = conn->addr_cur->ai_next;
1188 conn->status = CONNECTION_NEEDED;
1194 /* Fill in the client address */
1195 conn->laddr.salen = sizeof(conn->laddr.addr);
1196 if (getsockname(conn->sock,
1197 (struct sockaddr *) & conn->laddr.addr,
1198 &conn->laddr.salen) < 0)
1200 printfPQExpBuffer(&conn->errorMessage,
1201 libpq_gettext("could not get client address from socket: %s\n"),
1202 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1207 * Make sure we can write before advancing to next step.
1209 conn->status = CONNECTION_MADE;
1210 return PGRES_POLLING_WRITING;
1213 case CONNECTION_MADE:
1221 * If SSL is enabled and we haven't already got it running,
1222 * request it instead of sending the startup message.
1224 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1226 /* Don't bother requesting SSL over a Unix socket */
1227 conn->allow_ssl_try = false;
1229 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1235 * Send the SSL request packet.
1237 * Theoretically, this could block, but it really
1238 * shouldn't since we only got here if the socket is
1241 pv = htonl(NEGOTIATE_SSL_CODE);
1242 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1244 printfPQExpBuffer(&conn->errorMessage,
1245 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1246 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1249 /* Ok, wait for response */
1250 conn->status = CONNECTION_SSL_STARTUP;
1251 return PGRES_POLLING_READING;
1253 #endif /* USE_SSL */
1256 * Build the startup packet.
1258 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1259 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1260 EnvironmentOptions);
1262 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1263 EnvironmentOptions);
1266 printfPQExpBuffer(&conn->errorMessage,
1267 libpq_gettext("out of memory\n"));
1272 * Send the startup packet.
1274 * Theoretically, this could block, but it really shouldn't
1275 * since we only got here if the socket is write-ready.
1277 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1279 printfPQExpBuffer(&conn->errorMessage,
1280 libpq_gettext("could not send startup packet: %s\n"),
1281 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1288 conn->status = CONNECTION_AWAITING_RESPONSE;
1289 return PGRES_POLLING_READING;
1293 * Handle SSL negotiation: wait for postmaster messages and
1294 * respond as necessary.
1296 case CONNECTION_SSL_STARTUP:
1299 PostgresPollingStatusType pollres;
1302 * On first time through, get the postmaster's response to our
1303 * SSL negotiation packet.
1305 if (conn->ssl == NULL)
1308 * We use pqReadData here since it has the logic to
1309 * distinguish no-data-yet from connection closure. Since
1310 * conn->ssl isn't set, a plain recv() will occur.
1315 rdresult = pqReadData(conn);
1318 /* errorMessage is already filled in */
1323 /* caller failed to wait for data */
1324 return PGRES_POLLING_READING;
1326 if (pqGetc(&SSLok, conn) < 0)
1328 /* should not happen really */
1329 return PGRES_POLLING_READING;
1331 /* mark byte consumed */
1332 conn->inStart = conn->inCursor;
1335 /* Do one-time setup; this creates conn->ssl */
1336 if (pqsecure_initialize(conn) == -1)
1339 else if (SSLok == 'N')
1341 if (conn->sslmode[0] == 'r') /* "require" */
1343 /* Require SSL, but server does not want it */
1344 printfPQExpBuffer(&conn->errorMessage,
1345 libpq_gettext("server does not support SSL, but SSL was required\n"));
1348 /* Otherwise, proceed with normal startup */
1349 conn->allow_ssl_try = false;
1350 conn->status = CONNECTION_MADE;
1351 return PGRES_POLLING_WRITING;
1353 else if (SSLok == 'E')
1355 /* Received error - probably protocol mismatch */
1357 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1358 if (conn->sslmode[0] == 'r') /* "require" */
1360 /* Require SSL, but server is too old */
1361 printfPQExpBuffer(&conn->errorMessage,
1362 libpq_gettext("server does not support SSL, but SSL was required\n"));
1365 /* Otherwise, try again without SSL */
1366 conn->allow_ssl_try = false;
1367 /* Assume it ain't gonna handle protocol 3, either */
1368 conn->pversion = PG_PROTOCOL(2, 0);
1369 /* Must drop the old connection */
1370 closesocket(conn->sock);
1372 conn->status = CONNECTION_NEEDED;
1377 printfPQExpBuffer(&conn->errorMessage,
1378 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1385 * Begin or continue the SSL negotiation process.
1387 pollres = pqsecure_open_client(conn);
1388 if (pollres == PGRES_POLLING_OK)
1390 /* SSL handshake done, ready to send startup packet */
1391 conn->status = CONNECTION_MADE;
1392 return PGRES_POLLING_WRITING;
1395 #else /* !USE_SSL */
1396 /* can't get here */
1398 #endif /* USE_SSL */
1402 * Handle authentication exchange: wait for postmaster messages
1403 * and respond as necessary.
1405 case CONNECTION_AWAITING_RESPONSE:
1413 * Scan the message from current point (note that if we find
1414 * the message is incomplete, we will return without advancing
1415 * inStart, and resume here next time).
1417 conn->inCursor = conn->inStart;
1419 /* Read type byte */
1420 if (pqGetc(&beresp, conn))
1422 /* We'll come back when there is more data */
1423 return PGRES_POLLING_READING;
1427 * Validate message type: we expect only an authentication
1428 * request or an error here. Anything else probably means
1429 * it's not Postgres on the other end at all.
1431 if (!(beresp == 'R' || beresp == 'E'))
1433 printfPQExpBuffer(&conn->errorMessage,
1435 "expected authentication request from "
1436 "server, but received %c\n"),
1441 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1443 /* Read message length word */
1444 if (pqGetInt(&msgLength, 4, conn))
1446 /* We'll come back when there is more data */
1447 return PGRES_POLLING_READING;
1452 /* Set phony message length to disable checks below */
1457 * Try to validate message length before using it.
1458 * Authentication requests can't be very large. Errors can be
1459 * a little larger, but not huge. If we see a large apparent
1460 * length in an error, it means we're really talking to a
1461 * pre-3.0-protocol server; cope.
1463 if (beresp == 'R' && (msgLength < 8 || msgLength > 100))
1465 printfPQExpBuffer(&conn->errorMessage,
1467 "expected authentication request from "
1468 "server, but received %c\n"),
1473 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1475 /* Handle error from a pre-3.0 server */
1476 conn->inCursor = conn->inStart + 1; /* reread data */
1477 if (pqGets(&conn->errorMessage, conn))
1479 /* We'll come back when there is more data */
1480 return PGRES_POLLING_READING;
1482 /* OK, we read the message; mark data consumed */
1483 conn->inStart = conn->inCursor;
1486 * The postmaster typically won't end its message with a
1487 * newline, so add one to conform to libpq conventions.
1489 appendPQExpBufferChar(&conn->errorMessage, '\n');
1492 * If we tried to open the connection in 3.0 protocol,
1493 * fall back to 2.0 protocol.
1495 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1497 conn->pversion = PG_PROTOCOL(2, 0);
1498 /* Must drop the old connection */
1499 pqsecure_close(conn);
1500 closesocket(conn->sock);
1502 conn->status = CONNECTION_NEEDED;
1510 * Can't process if message body isn't all here yet.
1512 * (In protocol 2.0 case, we are assuming messages carry at
1513 * least 4 bytes of data.)
1516 avail = conn->inEnd - conn->inCursor;
1517 if (avail < msgLength)
1520 * Before returning, try to enlarge the input buffer if
1521 * needed to hold the whole message; see notes in
1524 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1526 /* We'll come back when there is more data */
1527 return PGRES_POLLING_READING;
1530 /* Handle errors. */
1533 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1535 if (pqGetErrorNotice3(conn, true))
1537 /* We'll come back when there is more data */
1538 return PGRES_POLLING_READING;
1543 if (pqGets(&conn->errorMessage, conn))
1545 /* We'll come back when there is more data */
1546 return PGRES_POLLING_READING;
1549 /* OK, we read the message; mark data consumed */
1550 conn->inStart = conn->inCursor;
1555 * if sslmode is "allow" and we haven't tried an SSL
1556 * connection already, then retry with an SSL connection
1558 if (conn->sslmode[0] == 'a' /* "allow" */
1559 && conn->ssl == NULL
1560 && conn->allow_ssl_try
1561 && conn->wait_ssl_try)
1563 /* only retry once */
1564 conn->wait_ssl_try = false;
1565 /* Must drop the old connection */
1566 closesocket(conn->sock);
1568 conn->status = CONNECTION_NEEDED;
1573 * if sslmode is "prefer" and we're in an SSL connection,
1574 * then do a non-SSL retry
1576 if (conn->sslmode[0] == 'p' /* "prefer" */
1578 && conn->allow_ssl_try /* redundant? */
1579 && !conn->wait_ssl_try) /* redundant? */
1581 /* only retry once */
1582 conn->allow_ssl_try = false;
1583 /* Must drop the old connection */
1584 pqsecure_close(conn);
1585 closesocket(conn->sock);
1587 conn->status = CONNECTION_NEEDED;
1595 /* It is an authentication request. */
1596 /* Get the type of request. */
1597 if (pqGetInt((int *) &areq, 4, conn))
1599 /* We'll come back when there are more data */
1600 return PGRES_POLLING_READING;
1603 /* Get the password salt if there is one. */
1604 if (areq == AUTH_REQ_MD5)
1606 if (pqGetnchar(conn->md5Salt,
1607 sizeof(conn->md5Salt), conn))
1609 /* We'll come back when there are more data */
1610 return PGRES_POLLING_READING;
1613 if (areq == AUTH_REQ_CRYPT)
1615 if (pqGetnchar(conn->cryptSalt,
1616 sizeof(conn->cryptSalt), conn))
1618 /* We'll come back when there are more data */
1619 return PGRES_POLLING_READING;
1624 * OK, we successfully read the message; mark data consumed
1626 conn->inStart = conn->inCursor;
1628 /* Respond to the request if necessary. */
1631 * Note that conn->pghost must be non-NULL if we are going to
1632 * avoid the Kerberos code doing a hostname look-up.
1636 * XXX fe-auth.c has not been fixed to support PQExpBuffers,
1639 if (pg_fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1640 conn->errorMessage.data) != STATUS_OK)
1642 conn->errorMessage.len = strlen(conn->errorMessage.data);
1645 conn->errorMessage.len = strlen(conn->errorMessage.data);
1648 * Just make sure that any data sent by pg_fe_sendauth is
1649 * flushed out. Although this theoretically could block, it
1650 * really shouldn't since we don't send large auth responses.
1655 if (areq == AUTH_REQ_OK)
1657 /* We are done with authentication exchange */
1658 conn->status = CONNECTION_AUTH_OK;
1661 * Set asyncStatus so that PQsetResult will think that
1662 * what comes back next is the result of a query. See
1665 conn->asyncStatus = PGASYNC_BUSY;
1668 /* Look to see if we have more data yet. */
1672 case CONNECTION_AUTH_OK:
1675 * Now we expect to hear from the backend. A ReadyForQuery
1676 * message indicates that startup is successful, but we might
1677 * also get an Error message indicating failure. (Notice
1678 * messages indicating nonfatal warnings are also allowed by
1679 * the protocol, as are ParameterStatus and BackendKeyData
1680 * messages.) Easiest way to handle this is to let
1681 * PQgetResult() read the messages. We just have to fake it
1682 * out about the state of the connection, by setting
1683 * asyncStatus = PGASYNC_BUSY (done above).
1687 return PGRES_POLLING_READING;
1689 res = PQgetResult(conn);
1692 * NULL return indicating we have gone to IDLE state is
1697 if (res->resultStatus != PGRES_FATAL_ERROR)
1698 printfPQExpBuffer(&conn->errorMessage,
1699 libpq_gettext("unexpected message from server during startup\n"));
1702 * if the resultStatus is FATAL, then conn->errorMessage
1703 * already has a copy of the error; needn't copy it back.
1704 * But add a newline if it's not there already, since
1705 * postmaster error messages may not have one.
1707 if (conn->errorMessage.len <= 0 ||
1708 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1709 appendPQExpBufferChar(&conn->errorMessage, '\n');
1714 /* We can release the address list now. */
1715 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1716 conn->addrlist = NULL;
1717 conn->addr_cur = NULL;
1719 /* Fire up post-connection housekeeping if needed */
1720 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1722 conn->status = CONNECTION_SETENV;
1723 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1724 conn->next_eo = EnvironmentOptions;
1725 return PGRES_POLLING_WRITING;
1728 /* Otherwise, we are open for business! */
1729 conn->status = CONNECTION_OK;
1730 return PGRES_POLLING_OK;
1733 case CONNECTION_SETENV:
1736 * Do post-connection housekeeping (only needed in protocol 2.0).
1738 * We pretend that the connection is OK for the duration of these
1741 conn->status = CONNECTION_OK;
1743 switch (pqSetenvPoll(conn))
1745 case PGRES_POLLING_OK: /* Success */
1748 case PGRES_POLLING_READING: /* Still going */
1749 conn->status = CONNECTION_SETENV;
1750 return PGRES_POLLING_READING;
1752 case PGRES_POLLING_WRITING: /* Still going */
1753 conn->status = CONNECTION_SETENV;
1754 return PGRES_POLLING_WRITING;
1760 /* We are open for business! */
1761 conn->status = CONNECTION_OK;
1762 return PGRES_POLLING_OK;
1765 printfPQExpBuffer(&conn->errorMessage,
1767 "invalid connection state %c, "
1768 "probably indicative of memory corruption\n"
1779 * We used to close the socket at this point, but that makes it awkward
1780 * for those above us if they wish to remove this socket from their own
1781 * records (an fd_set for example). We'll just have this socket closed
1782 * when PQfinish is called (which is compulsory even after an error, since
1783 * the connection structure must be freed).
1785 conn->status = CONNECTION_BAD;
1786 return PGRES_POLLING_FAILED;
1792 * - create a PGconn data structure with (as yet) no interesting data
1795 makeEmptyPGconn(void)
1802 * Make sure socket support is up and running. Even though this is done in
1803 * libpqdll.c, that is only for MSVC and BCC builds and doesn't work for
1804 * static builds at all, so we have to do it in the main code too.
1808 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1813 conn = (PGconn *) malloc(sizeof(PGconn));
1817 /* Zero all pointers and booleans */
1818 MemSet(conn, 0, sizeof(PGconn));
1820 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1821 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1822 conn->status = CONNECTION_BAD;
1823 conn->asyncStatus = PGASYNC_IDLE;
1824 conn->xactStatus = PQTRANS_IDLE;
1825 conn->options_valid = false;
1826 conn->nonblocking = false;
1827 conn->setenv_state = SETENV_STATE_IDLE;
1828 conn->client_encoding = PG_SQL_ASCII;
1829 conn->std_strings = false; /* unless server says differently */
1830 conn->verbosity = PQERRORS_DEFAULT;
1833 conn->allow_ssl_try = true;
1834 conn->wait_ssl_try = false;
1838 * We try to send at least 8K at a time, which is the usual size of pipe
1839 * buffers on Unix systems. That way, when we are sending a large amount
1840 * of data, we avoid incurring extra kernel context swaps for partial
1841 * bufferloads. The output buffer is initially made 16K in size, and we
1842 * try to dump it after accumulating 8K.
1844 * With the same goal of minimizing context swaps, the input buffer will
1845 * be enlarged anytime it has less than 8K free, so we initially allocate
1848 conn->inBufSize = 16 * 1024;
1849 conn->inBuffer = (char *) malloc(conn->inBufSize);
1850 conn->outBufSize = 16 * 1024;
1851 conn->outBuffer = (char *) malloc(conn->outBufSize);
1852 initPQExpBuffer(&conn->errorMessage);
1853 initPQExpBuffer(&conn->workBuffer);
1855 if (conn->inBuffer == NULL ||
1856 conn->outBuffer == NULL ||
1857 conn->errorMessage.data == NULL ||
1858 conn->workBuffer.data == NULL)
1860 /* out of memory already :-( */
1870 * - free the PGconn data structure
1872 * When changing/adding to this function, see also closePGconn!
1875 freePGconn(PGconn *conn)
1878 pgParameterStatus *pstatus;
1887 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1888 if (conn->sock >= 0)
1890 pqsecure_close(conn);
1891 closesocket(conn->sock);
1895 if (conn->pghostaddr)
1896 free(conn->pghostaddr);
1899 if (conn->pgunixsocket)
1900 free(conn->pgunixsocket);
1903 if (conn->connect_timeout)
1904 free(conn->connect_timeout);
1905 if (conn->pgoptions)
1906 free(conn->pgoptions);
1914 free(conn->sslmode);
1916 if (conn->krbsrvname)
1917 free(conn->krbsrvname);
1919 /* Note that conn->Pfdebug is not ours to close or free */
1920 if (conn->last_query)
1921 free(conn->last_query);
1922 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1923 notify = conn->notifyHead;
1924 while (notify != NULL)
1926 PGnotify *prev = notify;
1928 notify = notify->next;
1931 pstatus = conn->pstatus;
1932 while (pstatus != NULL)
1934 pgParameterStatus *prev = pstatus;
1936 pstatus = pstatus->next;
1939 if (conn->lobjfuncs)
1940 free(conn->lobjfuncs);
1942 free(conn->inBuffer);
1943 if (conn->outBuffer)
1944 free(conn->outBuffer);
1945 termPQExpBuffer(&conn->errorMessage);
1946 termPQExpBuffer(&conn->workBuffer);
1952 * - properly close a connection to the backend
1954 * Release all transient state, but NOT the connection parameters.
1957 closePGconn(PGconn *conn)
1960 pgParameterStatus *pstatus;
1963 * Note that the protocol doesn't allow us to send Terminate messages
1964 * during the startup phase.
1966 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1969 * Try to send "close connection" message to backend. Ignore any
1972 pqPutMsgStart('X', false, conn);
1978 * must reset the blocking status so a possible reconnect will work don't
1979 * call PQsetnonblocking() because it will fail if it's unable to flush
1982 conn->nonblocking = FALSE;
1985 * Close the connection, reset all transient state, flush I/O buffers.
1987 if (conn->sock >= 0)
1989 pqsecure_close(conn);
1990 closesocket(conn->sock);
1993 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
1995 conn->asyncStatus = PGASYNC_IDLE;
1996 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1997 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1998 conn->addrlist = NULL;
1999 conn->addr_cur = NULL;
2000 notify = conn->notifyHead;
2001 while (notify != NULL)
2003 PGnotify *prev = notify;
2005 notify = notify->next;
2008 conn->notifyHead = NULL;
2009 pstatus = conn->pstatus;
2010 while (pstatus != NULL)
2012 pgParameterStatus *prev = pstatus;
2014 pstatus = pstatus->next;
2017 conn->pstatus = NULL;
2018 if (conn->lobjfuncs)
2019 free(conn->lobjfuncs);
2020 conn->lobjfuncs = NULL;
2021 conn->inStart = conn->inCursor = conn->inEnd = 0;
2026 * PQfinish: properly close a connection to the backend. Also frees
2027 * the PGconn data structure so it shouldn't be re-used after this.
2030 PQfinish(PGconn *conn)
2040 * PQreset: resets the connection to the backend by closing the
2041 * existing connection and creating a new one.
2044 PQreset(PGconn *conn)
2050 if (connectDBStart(conn))
2051 (void) connectDBComplete(conn);
2058 * resets the connection to the backend
2059 * closes the existing connection and makes a new one
2060 * Returns 1 on success, 0 on failure.
2063 PQresetStart(PGconn *conn)
2069 return connectDBStart(conn);
2078 * resets the connection to the backend
2079 * closes the existing connection and makes a new one
2081 PostgresPollingStatusType
2082 PQresetPoll(PGconn *conn)
2085 return PQconnectPoll(conn);
2087 return PGRES_POLLING_FAILED;
2091 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2093 * A copy is needed to be able to cancel a running query from a different
2094 * thread. If the same structure is used all structure members would have
2095 * to be individually locked (if the entire structure was locked, it would
2096 * be impossible to cancel a synchronous query because the structure would
2097 * have to stay locked for the duration of the query).
2100 PQgetCancel(PGconn *conn)
2110 cancel = malloc(sizeof(PGcancel));
2114 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2115 cancel->be_pid = conn->be_pid;
2116 cancel->be_key = conn->be_key;
2121 /* PQfreeCancel: free a cancel structure */
2123 PQfreeCancel(PGcancel *cancel)
2131 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2132 * current operation.
2134 * The return value is TRUE if the cancel request was successfully
2135 * dispatched, FALSE if not (in which case an error message is available).
2136 * Note: successful dispatch is no guarantee that there will be any effect at
2137 * the backend. The application must read the operation result as usual.
2139 * CAUTION: we want this routine to be safely callable from a signal handler
2140 * (for example, an application might want to call it in a SIGINT handler).
2141 * This means we cannot use any C library routine that might be non-reentrant.
2142 * malloc/free are often non-reentrant, and anything that might call them is
2143 * just as dangerous. We avoid sprintf here for that reason. Building up
2144 * error messages with strcpy/strcat is tedious but should be quite safe.
2145 * We also save/restore errno in case the signal handler support doesn't.
2147 * internal_cancel() is an internal helper function to make code-sharing
2148 * between the two versions of the cancel function possible.
2151 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2152 char *errbuf, int errbufsize)
2154 int save_errno = SOCK_ERRNO;
2161 CancelRequestPacket cp;
2165 * We need to open a temporary connection to the postmaster. Do this with
2166 * only kernel calls.
2168 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2170 StrNCpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2171 goto cancel_errReturn;
2174 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2177 if (SOCK_ERRNO == EINTR)
2178 /* Interrupted system call - we'll just try again */
2180 StrNCpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2181 goto cancel_errReturn;
2185 * We needn't set nonblocking I/O or NODELAY options here.
2188 /* Create and send the cancel request packet. */
2190 crp.packetlen = htonl((uint32) sizeof(crp));
2191 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2192 crp.cp.backendPID = htonl(be_pid);
2193 crp.cp.cancelAuthCode = htonl(be_key);
2196 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2198 if (SOCK_ERRNO == EINTR)
2199 /* Interrupted system call - we'll just try again */
2201 StrNCpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2202 goto cancel_errReturn;
2206 * Wait for the postmaster to close the connection, which indicates that
2207 * it's processed the request. Without this delay, we might issue another
2208 * command only to find that our cancel zaps that command instead of the
2209 * one we thought we were canceling. Note we don't actually expect this
2210 * read to obtain any data, we are just waiting for EOF to be signaled.
2213 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2215 if (SOCK_ERRNO == EINTR)
2216 /* Interrupted system call - we'll just try again */
2218 /* we ignore other error conditions */
2222 closesocket(tmpsock);
2223 SOCK_ERRNO_SET(save_errno);
2229 * Make sure we don't overflow the error buffer. Leave space for the \n at
2230 * the end, and for the terminating zero.
2232 maxlen = errbufsize - strlen(errbuf) - 2;
2235 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2237 strcat(errbuf, "\n");
2240 closesocket(tmpsock);
2241 SOCK_ERRNO_SET(save_errno);
2246 * PQcancel: request query cancel
2248 * Returns TRUE if able to send the cancel request, FALSE if not.
2250 * On failure, an error message is stored in *errbuf, which must be of size
2251 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2255 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2259 StrNCpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2263 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2264 errbuf, errbufsize);
2268 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2270 * Returns TRUE if able to send the cancel request, FALSE if not.
2272 * On failure, the error message is saved in conn->errorMessage; this means
2273 * that this can't be used when there might be other active operations on
2274 * the connection object.
2276 * NOTE: error messages will be cut off at the current size of the
2277 * error message buffer, since we dare not try to expand conn->errorMessage!
2280 PQrequestCancel(PGconn *conn)
2284 /* Check we have an open connection */
2290 StrNCpy(conn->errorMessage.data,
2291 "PQrequestCancel() -- connection is not open\n",
2292 conn->errorMessage.maxlen);
2293 conn->errorMessage.len = strlen(conn->errorMessage.data);
2298 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2299 conn->errorMessage.data, conn->errorMessage.maxlen);
2302 conn->errorMessage.len = strlen(conn->errorMessage.data);
2309 * pqPacketSend() -- convenience routine to send a message to server.
2311 * pack_type: the single-byte message type code. (Pass zero for startup
2312 * packets, which have no message type code.)
2314 * buf, buf_len: contents of message. The given length includes only what
2315 * is in buf; the message type and message length fields are added here.
2317 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2318 * SIDE_EFFECTS: may block.
2320 * Note: all messages sent with this routine have a length word, whether
2321 * it's protocol 2.0 or 3.0.
2324 pqPacketSend(PGconn *conn, char pack_type,
2325 const void *buf, size_t buf_len)
2327 /* Start the message. */
2328 if (pqPutMsgStart(pack_type, true, conn))
2329 return STATUS_ERROR;
2331 /* Send the message body. */
2332 if (pqPutnchar(buf, buf_len, conn))
2333 return STATUS_ERROR;
2335 /* Finish the message. */
2336 if (pqPutMsgEnd(conn))
2337 return STATUS_ERROR;
2339 /* Flush to ensure backend gets it. */
2341 return STATUS_ERROR;
2348 #define MAXBUFSIZE 256
2351 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2353 char *service = conninfo_getval(options, "service");
2354 char serviceFile[MAXPGPATH];
2355 bool group_found = false;
2360 * We have to special-case the environment variable PGSERVICE here, since
2361 * this is and should be called before inserting environment defaults for
2362 * other connection options.
2364 if (service == NULL)
2365 service = getenv("PGSERVICE");
2368 * This could be used by any application so we can't use the binary
2369 * location to find our config files.
2371 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2372 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2374 if (service != NULL)
2377 char buf[MAXBUFSIZE],
2380 f = fopen(serviceFile, "r");
2383 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2388 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2392 if (strlen(line) >= MAXBUFSIZE - 2)
2395 printfPQExpBuffer(errorMessage,
2396 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2402 /* ignore EOL at end of line */
2403 if (strlen(line) && line[strlen(line) - 1] == '\n')
2404 line[strlen(line) - 1] = 0;
2406 /* ignore leading blanks */
2407 while (*line && isspace((unsigned char) line[0]))
2410 /* ignore comments and empty lines */
2411 if (strlen(line) == 0 || line[0] == '#')
2414 /* Check for right groupname */
2419 /* group info already read */
2424 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2425 line[strlen(service) + 1] == ']')
2428 group_found = false;
2435 * Finally, we are in the right group and can parse the
2443 val = strchr(line, '=');
2446 printfPQExpBuffer(errorMessage,
2447 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
2456 * Set the parameter --- but don't override any previous
2459 found_keyword = false;
2460 for (i = 0; options[i].keyword; i++)
2462 if (strcmp(options[i].keyword, key) == 0)
2464 if (options[i].val == NULL)
2465 options[i].val = strdup(val);
2466 found_keyword = true;
2473 printfPQExpBuffer(errorMessage,
2474 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
2492 * Conninfo parser routine
2494 * If successful, a malloc'd PQconninfoOption array is returned.
2495 * If not successful, NULL is returned and an error message is
2496 * left in errorMessage.
2498 static PQconninfoOption *
2499 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2507 PQconninfoOption *options;
2508 PQconninfoOption *option;
2509 char errortmp[PQERRORMSG_LENGTH];
2511 /* Make a working copy of PQconninfoOptions */
2512 options = malloc(sizeof(PQconninfoOptions));
2513 if (options == NULL)
2515 printfPQExpBuffer(errorMessage,
2516 libpq_gettext("out of memory\n"));
2519 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2521 /* Need a modifiable copy of the input string */
2522 if ((buf = strdup(conninfo)) == NULL)
2524 printfPQExpBuffer(errorMessage,
2525 libpq_gettext("out of memory\n"));
2526 PQconninfoFree(options);
2533 /* Skip blanks before the parameter name */
2534 if (isspace((unsigned char) *cp))
2540 /* Get the parameter name */
2546 if (isspace((unsigned char) *cp))
2551 if (!isspace((unsigned char) *cp))
2560 /* Check that there is a following '=' */
2563 printfPQExpBuffer(errorMessage,
2564 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2566 PQconninfoFree(options);
2572 /* Skip blanks after the '=' */
2575 if (!isspace((unsigned char) *cp))
2580 /* Get the parameter value */
2588 if (isspace((unsigned char) *cp))
2612 printfPQExpBuffer(errorMessage,
2613 libpq_gettext("unterminated quoted string in connection info string\n"));
2614 PQconninfoFree(options);
2636 * Now we have the name and the value. Search for the param record.
2638 for (option = options; option->keyword != NULL; option++)
2640 if (strcmp(option->keyword, pname) == 0)
2643 if (option->keyword == NULL)
2645 printfPQExpBuffer(errorMessage,
2646 libpq_gettext("invalid connection option \"%s\"\n"),
2648 PQconninfoFree(options);
2658 option->val = strdup(pval);
2661 printfPQExpBuffer(errorMessage,
2662 libpq_gettext("out of memory\n"));
2663 PQconninfoFree(options);
2669 /* Done with the modifiable input string */
2673 * If there's a service spec, use it to obtain any not-explicitly-given
2676 if (parseServiceInfo(options, errorMessage))
2678 PQconninfoFree(options);
2683 * Get the fallback resources for parameters not specified in the conninfo
2684 * string nor the service.
2686 for (option = options; option->keyword != NULL; option++)
2688 if (option->val != NULL)
2689 continue; /* Value was in conninfo or service */
2692 * Try to get the environment variable fallback
2694 if (option->envvar != NULL)
2696 if ((tmp = getenv(option->envvar)) != NULL)
2698 option->val = strdup(tmp);
2701 printfPQExpBuffer(errorMessage,
2702 libpq_gettext("out of memory\n"));
2703 PQconninfoFree(options);
2711 * No environment variable specified or this one isn't set - try
2714 if (option->compiled != NULL)
2716 option->val = strdup(option->compiled);
2719 printfPQExpBuffer(errorMessage,
2720 libpq_gettext("out of memory\n"));
2721 PQconninfoFree(options);
2728 * Special handling for user
2730 if (strcmp(option->keyword, "user") == 0)
2732 option->val = pg_fe_getauthname(errortmp);
2733 /* note any error message is thrown away */
2743 conninfo_getval(PQconninfoOption *connOptions,
2744 const char *keyword)
2746 PQconninfoOption *option;
2748 for (option = connOptions; option->keyword != NULL; option++)
2750 if (strcmp(option->keyword, keyword) == 0)
2759 PQconninfoFree(PQconninfoOption *connOptions)
2761 PQconninfoOption *option;
2763 if (connOptions == NULL)
2766 for (option = connOptions; option->keyword != NULL; option++)
2768 if (option->val != NULL)
2775 /* =========== accessor functions for PGconn ========= */
2777 PQdb(const PGconn *conn)
2781 return conn->dbName;
2785 PQuser(const PGconn *conn)
2789 return conn->pguser;
2793 PQpass(const PGconn *conn)
2797 return conn->pgpass;
2801 PQhost(const PGconn *conn)
2805 return conn->pghost ? conn->pghost : conn->pgunixsocket;
2809 PQport(const PGconn *conn)
2813 return conn->pgport;
2817 PQtty(const PGconn *conn)
2825 PQoptions(const PGconn *conn)
2829 return conn->pgoptions;
2833 PQstatus(const PGconn *conn)
2836 return CONNECTION_BAD;
2837 return conn->status;
2840 PGTransactionStatusType
2841 PQtransactionStatus(const PGconn *conn)
2843 if (!conn || conn->status != CONNECTION_OK)
2844 return PQTRANS_UNKNOWN;
2845 if (conn->asyncStatus != PGASYNC_IDLE)
2846 return PQTRANS_ACTIVE;
2847 return conn->xactStatus;
2851 PQparameterStatus(const PGconn *conn, const char *paramName)
2853 const pgParameterStatus *pstatus;
2855 if (!conn || !paramName)
2857 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
2859 if (strcmp(pstatus->name, paramName) == 0)
2860 return pstatus->value;
2866 PQprotocolVersion(const PGconn *conn)
2870 if (conn->status == CONNECTION_BAD)
2872 return PG_PROTOCOL_MAJOR(conn->pversion);
2876 PQserverVersion(const PGconn *conn)
2880 if (conn->status == CONNECTION_BAD)
2882 return conn->sversion;
2886 PQerrorMessage(const PGconn *conn)
2889 return libpq_gettext("connection pointer is NULL\n");
2891 return conn->errorMessage.data;
2895 PQsocket(const PGconn *conn)
2903 PQbackendPID(const PGconn *conn)
2905 if (!conn || conn->status != CONNECTION_OK)
2907 return conn->be_pid;
2911 PQclientEncoding(const PGconn *conn)
2913 if (!conn || conn->status != CONNECTION_OK)
2915 return conn->client_encoding;
2919 PQsetClientEncoding(PGconn *conn, const char *encoding)
2922 static const char query[] = "set client_encoding to '%s'";
2926 if (!conn || conn->status != CONNECTION_OK)
2932 /* check query buffer overflow */
2933 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2936 /* ok, now send a query */
2937 sprintf(qbuf, query, encoding);
2938 res = PQexec(conn, qbuf);
2942 if (res->resultStatus != PGRES_COMMAND_OK)
2947 * In protocol 2 we have to assume the setting will stick, and
2948 * adjust our state immediately. In protocol 3 and up we can
2949 * rely on the backend to report the parameter value, and we'll
2950 * change state at that time.
2952 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2953 pqSaveParameterStatus(conn, "client_encoding", encoding);
2954 status = 0; /* everything is ok */
2961 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
2966 return PQERRORS_DEFAULT;
2967 old = conn->verbosity;
2968 conn->verbosity = verbosity;
2973 PQtrace(PGconn *conn, FILE *debug_port)
2978 conn->Pfdebug = debug_port;
2982 PQuntrace(PGconn *conn)
2988 fflush(conn->Pfdebug);
2989 conn->Pfdebug = NULL;
2994 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
2996 PQnoticeReceiver old;
3001 old = conn->noticeHooks.noticeRec;
3004 conn->noticeHooks.noticeRec = proc;
3005 conn->noticeHooks.noticeRecArg = arg;
3011 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3013 PQnoticeProcessor old;
3018 old = conn->noticeHooks.noticeProc;
3021 conn->noticeHooks.noticeProc = proc;
3022 conn->noticeHooks.noticeProcArg = arg;
3028 * The default notice message receiver just gets the standard notice text
3029 * and sends it to the notice processor. This two-level setup exists
3030 * mostly for backwards compatibility; perhaps we should deprecate use of
3031 * PQsetNoticeProcessor?
3034 defaultNoticeReceiver(void *arg, const PGresult *res)
3036 (void) arg; /* not used */
3037 if (res->noticeHooks.noticeProc != NULL)
3038 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3039 PQresultErrorMessage(res));
3043 * The default notice message processor just prints the
3044 * message on stderr. Applications can override this if they
3045 * want the messages to go elsewhere (a window, for example).
3046 * Note that simply discarding notices is probably a bad idea.
3049 defaultNoticeProcessor(void *arg, const char *message)
3051 (void) arg; /* not used */
3052 /* Note: we expect the supplied string to end with a newline already. */
3053 fprintf(stderr, "%s", message);
3057 * returns a pointer to the next token or NULL if the current
3058 * token doesn't match
3061 pwdfMatchesString(char *buf, char *token)
3065 bool bslash = false;
3067 if (buf == NULL || token == NULL)
3075 if (*tbuf == '\\' && !bslash)
3080 if (*tbuf == ':' && *ttok == 0 && !bslash)
3096 /* Get a password from the password file. Return value is malloc'd. */
3098 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3101 char pgpassfile[MAXPGPATH];
3102 struct stat stat_buf;
3105 #define LINELEN NAMEDATALEN*5
3108 if (dbname == NULL || strlen(dbname) == 0)
3111 if (username == NULL || strlen(username) == 0)
3114 /* 'localhost' matches pghost of '' or the default socket directory */
3115 if (hostname == NULL)
3116 hostname = DefaultHost;
3117 else if (is_absolute_path(hostname))
3119 * We should probably use canonicalize_path(), but then
3120 * we have to bring path.c into libpq, and it doesn't
3123 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3124 hostname = DefaultHost;
3127 port = DEF_PGPORT_STR;
3129 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3130 /* use the literal path from the environment, if set */
3131 StrNCpy(pgpassfile, passfile_env, MAXPGPATH);
3134 char homedir[MAXPGPATH];
3136 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3138 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3141 /* If password file cannot be opened, ignore it. */
3142 if (stat(pgpassfile, &stat_buf) == -1)
3147 if (!S_ISREG(stat_buf.st_mode))
3150 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3156 /* If password file is insecure, alert the user and ignore it. */
3157 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3160 libpq_gettext("WARNING: password file \"%s\" has world or group read access; permission should be u=rw (0600)\n"),
3166 fp = fopen(pgpassfile, "r");
3176 fgets(buf, LINELEN - 1, fp);
3182 /* Remove trailing newline */
3183 if (buf[len - 1] == '\n')
3186 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3187 (t = pwdfMatchesString(t, port)) == NULL ||
3188 (t = pwdfMatchesString(t, dbname)) == NULL ||
3189 (t = pwdfMatchesString(t, username)) == NULL)
3203 * Obtain user's home directory, return in given buffer
3205 * On Unix, this actually returns the user's home directory. On Windows
3206 * it returns the PostgreSQL-specific application data folder.
3208 * This is essentially the same as get_home_path(), but we don't use that
3209 * because we don't want to pull path.c into libpq (it pollutes application
3213 pqGetHomeDirectory(char *buf, int bufsize)
3216 char pwdbuf[BUFSIZ];
3217 struct passwd pwdstr;
3218 struct passwd *pwd = NULL;
3220 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3222 StrNCpy(buf, pwd->pw_dir, bufsize);
3225 char tmppath[MAX_PATH];
3227 ZeroMemory(tmppath, sizeof(tmppath));
3228 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3230 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3236 * To keep the API consistent, the locking stubs are always provided, even
3237 * if they are not required.
3241 default_threadlock(int acquire)
3243 #ifdef ENABLE_THREAD_SAFETY
3245 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3247 static pthread_mutex_t singlethread_lock = NULL;
3248 static long mutex_initlock = 0;
3250 if (singlethread_lock == NULL)
3252 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3253 /* loop, another thread own the lock */ ;
3254 if (singlethread_lock == NULL)
3255 pthread_mutex_init(&singlethread_lock, NULL);
3256 InterlockedExchange(&mutex_initlock, 0);
3260 pthread_mutex_lock(&singlethread_lock);
3262 pthread_mutex_unlock(&singlethread_lock);
3267 PQregisterThreadLock(pgthreadlock_t newhandler)
3269 pgthreadlock_t prev = pg_g_threadlock;
3272 pg_g_threadlock = newhandler;
3274 pg_g_threadlock = default_threadlock;