1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2005, 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.325 2006/01/11 08:43:13 neilc Exp $
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
23 #ifndef WIN32_CLIENT_ONLY
32 #include "libpq-int.h"
34 #include "pg_config_paths.h"
41 #define _WIN32_IE 0x0500
48 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #ifdef HAVE_NETINET_TCP_H
52 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
57 #ifdef ENABLE_THREAD_SAFETY
59 #include "pthread-win32.h"
66 #include "mb/pg_wchar.h"
74 #define PGPASSFILE ".pgpass"
76 #define PGPASSFILE "pgpass.conf"
79 /* fall back options if they are not specified by arguments or defined
80 by environment variables */
81 #define DefaultHost "localhost"
83 #define DefaultOption ""
84 #define DefaultAuthtype ""
85 #define DefaultPassword ""
87 #define DefaultSSLMode "prefer"
89 #define DefaultSSLMode "disable"
93 * Definition of the conninfo parameters and their fallback resources.
95 * If Environment-Var and Compiled-in are specified as NULL, no
96 * fallback is available. If after all no value can be determined
97 * for an option, an error is returned.
99 * The value for the username is treated specially in conninfo_parse.
100 * If the Compiled-in resource is specified as a NULL value, the
101 * user is determined by pg_fe_getauthname().
103 * The Label and Disp-Char entries are provided for applications that
104 * want to use PQconndefaults() to create a generic database connection
105 * dialog. Disp-Char is defined as follows:
106 * "" Normal input field
107 * "*" Password field - hide value
108 * "D" Debug option - don't show by default
110 * PQconninfoOptions[] is a constant static array that we use to initialize
111 * a dynamically allocated working copy. All the "val" fields in
112 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
113 * fields point to malloc'd strings that should be freed when the working
114 * array is freed (see PQconninfoFree).
117 static const PQconninfoOption PQconninfoOptions[] = {
119 * "authtype" is no longer used, so mark it "don't show". We keep it in
120 * the array so as not to reject conninfo strings from old apps that might
121 * still try to set it.
123 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
124 "Database-Authtype", "D", 20},
126 {"service", "PGSERVICE", NULL, NULL,
127 "Database-Service", "", 20},
129 {"user", "PGUSER", NULL, NULL,
130 "Database-User", "", 20},
132 {"password", "PGPASSWORD", NULL, NULL,
133 "Database-Password", "*", 20},
135 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
136 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
138 {"dbname", "PGDATABASE", NULL, NULL,
139 "Database-Name", "", 20},
141 {"host", "PGHOST", NULL, NULL,
142 "Database-Host", "", 40},
144 {"hostaddr", "PGHOSTADDR", NULL, NULL,
145 "Database-Host-IP-Address", "", 45},
147 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
148 "Database-Port", "", 6},
151 * "tty" is no longer used either, but keep it present for backwards
154 {"tty", "PGTTY", DefaultTty, NULL,
155 "Backend-Debug-TTY", "D", 40},
157 {"options", "PGOPTIONS", DefaultOption, NULL,
158 "Backend-Debug-Options", "D", 40},
163 * "requiressl" is deprecated, its purpose having been taken over by
164 * "sslmode". It remains for backwards compatibility.
166 {"requiressl", "PGREQUIRESSL", "0", NULL,
167 "Require-SSL", "D", 1},
171 * "sslmode" option is allowed even without client SSL support because the
172 * client can still handle SSL modes "disable" and "allow".
174 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
175 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
178 /* Kerberos authentication supports specifying the service name */
179 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
180 "Kerberos-service-name", "", 20},
183 /* Terminating entry --- MUST BE LAST */
184 {NULL, NULL, NULL, NULL,
188 static const PQEnvironmentOption EnvironmentOptions[] =
190 /* common user-interface settings */
192 "PGDATESTYLE", "datestyle"
198 "PGCLIENTENCODING", "client_encoding"
200 /* internal performance-related settings */
210 static bool connectOptions1(PGconn *conn, const char *conninfo);
211 static bool connectOptions2(PGconn *conn);
212 static int connectDBStart(PGconn *conn);
213 static int connectDBComplete(PGconn *conn);
214 static PGconn *makeEmptyPGconn(void);
215 static void freePGconn(PGconn *conn);
216 static void closePGconn(PGconn *conn);
217 static PQconninfoOption *conninfo_parse(const char *conninfo,
218 PQExpBuffer errorMessage);
219 static char *conninfo_getval(PQconninfoOption *connOptions,
220 const char *keyword);
221 static void defaultNoticeReceiver(void *arg, const PGresult *res);
222 static void defaultNoticeProcessor(void *arg, const char *message);
223 static int parseServiceInfo(PQconninfoOption *options,
224 PQExpBuffer errorMessage);
225 static char *pwdfMatchesString(char *buf, char *token);
226 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
228 static void default_threadlock(int acquire);
231 /* global variable because fe-auth.c needs to access it */
232 pgthreadlock_t pg_g_threadlock = default_threadlock;
236 * Connecting to a Database
238 * There are now four different ways a user of this API can connect to the
239 * database. Two are not recommended for use in new code, because of their
240 * lack of extensibility with respect to the passing of options to the
241 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
244 * If it is desired to connect in a synchronous (blocking) manner, use the
245 * function PQconnectdb.
247 * To connect in an asynchronous (non-blocking) manner, use the functions
248 * PQconnectStart, and PQconnectPoll.
250 * Internally, the static functions connectDBStart, connectDBComplete
251 * are part of the connection procedure.
257 * establishes a connection to a postgres backend through the postmaster
258 * using connection information in a string.
260 * The conninfo string is a white-separated list of
264 * definitions. Value might be a single value containing no whitespaces or
265 * a single quoted string. If a single quote should appear anywhere in
266 * the value, it must be escaped with a backslash like \'
268 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
269 * if a memory allocation failed.
270 * If the status field of the connection returned is CONNECTION_BAD,
271 * then some fields may be null'ed out instead of having valid values.
273 * You should call PQfinish (if conn is not NULL) regardless of whether this
277 PQconnectdb(const char *conninfo)
279 PGconn *conn = PQconnectStart(conninfo);
281 if (conn && conn->status != CONNECTION_BAD)
282 (void) connectDBComplete(conn);
290 * Begins the establishment of a connection to a postgres backend through the
291 * postmaster using connection information in a string.
293 * See comment for PQconnectdb for the definition of the string format.
295 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
296 * you should not attempt to proceed with this connection. If the status
297 * field of the connection returned is CONNECTION_BAD, an error has
298 * occurred. In this case you should call PQfinish on the result, (perhaps
299 * inspecting the error message first). Other fields of the structure may not
300 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
301 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
304 * See PQconnectPoll for more info.
307 PQconnectStart(const char *conninfo)
312 * Allocate memory for the conn structure
314 conn = makeEmptyPGconn();
319 * Parse the conninfo string
321 if (!connectOptions1(conn, conninfo))
325 * Compute derived options
327 if (!connectOptions2(conn))
331 * Connect to the database
333 if (!connectDBStart(conn))
335 /* Just in case we failed to set it in connectDBStart */
336 conn->status = CONNECTION_BAD;
345 * Internal subroutine to set up connection parameters given an already-
346 * created PGconn and a conninfo string. Derived settings should be
347 * processed by calling connectOptions2 next. (We split them because
348 * PQsetdbLogin overrides defaults in between.)
350 * Returns true if OK, false if trouble (in which case errorMessage is set
351 * and so is conn->status).
354 connectOptions1(PGconn *conn, const char *conninfo)
356 PQconninfoOption *connOptions;
360 * Parse the conninfo string
362 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
363 if (connOptions == NULL)
365 conn->status = CONNECTION_BAD;
366 /* errorMessage is already set */
371 * Move option values into conn structure
373 * Don't put anything cute here --- intelligence should be in
374 * connectOptions2 ...
376 * XXX: probably worth checking strdup() return value here...
378 tmp = conninfo_getval(connOptions, "hostaddr");
379 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
380 tmp = conninfo_getval(connOptions, "host");
381 conn->pghost = tmp ? strdup(tmp) : NULL;
382 tmp = conninfo_getval(connOptions, "port");
383 conn->pgport = tmp ? strdup(tmp) : NULL;
384 tmp = conninfo_getval(connOptions, "tty");
385 conn->pgtty = tmp ? strdup(tmp) : NULL;
386 tmp = conninfo_getval(connOptions, "options");
387 conn->pgoptions = tmp ? strdup(tmp) : NULL;
388 tmp = conninfo_getval(connOptions, "dbname");
389 conn->dbName = tmp ? strdup(tmp) : NULL;
390 tmp = conninfo_getval(connOptions, "user");
391 conn->pguser = tmp ? strdup(tmp) : NULL;
392 tmp = conninfo_getval(connOptions, "password");
393 conn->pgpass = tmp ? strdup(tmp) : NULL;
394 tmp = conninfo_getval(connOptions, "connect_timeout");
395 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
396 tmp = conninfo_getval(connOptions, "sslmode");
397 conn->sslmode = tmp ? strdup(tmp) : NULL;
399 tmp = conninfo_getval(connOptions, "requiressl");
400 if (tmp && tmp[0] == '1')
402 /* here warn that the requiressl option is deprecated? */
405 conn->sslmode = strdup("require");
409 tmp = conninfo_getval(connOptions, "krbsrvname");
410 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
414 * Free the option info - all is in conn now
416 PQconninfoFree(connOptions);
424 * Compute derived connection options after absorbing all user-supplied info.
426 * Returns true if OK, false if trouble (in which case errorMessage is set
427 * and so is conn->status).
430 connectOptions2(PGconn *conn)
433 * If database name was not given, default it to equal user name
435 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
436 && conn->pguser != NULL)
440 conn->dbName = strdup(conn->pguser);
444 * Supply default password if none given
446 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
450 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
451 conn->dbName, conn->pguser);
452 if (conn->pgpass == NULL)
453 conn->pgpass = strdup(DefaultPassword);
457 * Allow unix socket specification in the host name
459 if (conn->pghost && is_absolute_path(conn->pghost))
461 if (conn->pgunixsocket)
462 free(conn->pgunixsocket);
463 conn->pgunixsocket = conn->pghost;
468 * validate sslmode option
472 if (strcmp(conn->sslmode, "disable") != 0
473 && strcmp(conn->sslmode, "allow") != 0
474 && strcmp(conn->sslmode, "prefer") != 0
475 && strcmp(conn->sslmode, "require") != 0)
477 conn->status = CONNECTION_BAD;
478 printfPQExpBuffer(&conn->errorMessage,
479 libpq_gettext("invalid sslmode value: \"%s\"\n"),
485 switch (conn->sslmode[0])
487 case 'a': /* "allow" */
488 case 'p': /* "prefer" */
491 * warn user that an SSL connection will never be negotiated
492 * since SSL was not compiled in?
496 case 'r': /* "require" */
497 conn->status = CONNECTION_BAD;
498 printfPQExpBuffer(&conn->errorMessage,
499 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
506 conn->sslmode = strdup(DefaultSSLMode);
514 * Parse an empty string like PQconnectdb() would do and return the
515 * working connection options array.
517 * Using this function, an application may determine all possible options
518 * and their current default values.
520 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
521 * and should be freed when no longer needed via PQconninfoFree(). (In prior
522 * versions, the returned array was static, but that's not thread-safe.)
523 * Pre-7.0 applications that use this function will see a small memory leak
524 * until they are updated to call PQconninfoFree.
529 PQExpBufferData errorBuf;
530 PQconninfoOption *connOptions;
532 initPQExpBuffer(&errorBuf);
533 connOptions = conninfo_parse("", &errorBuf);
534 termPQExpBuffer(&errorBuf);
541 * establishes a connection to a postgres backend through the postmaster
542 * at the specified host and port.
544 * returns a PGconn* which is needed for all subsequent libpq calls
546 * if the status field of the connection returned is CONNECTION_BAD,
547 * then only the errorMessage is likely to be useful.
551 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
552 const char *pgtty, const char *dbName, const char *login,
558 * Allocate memory for the conn structure
560 conn = makeEmptyPGconn();
565 * Parse an empty conninfo string in order to set up the same defaults
566 * that PQconnectdb() would use.
568 if (!connectOptions1(conn, ""))
572 * Absorb specified options into conn structure, overriding defaults
574 if (pghost && pghost[0] != '\0')
578 conn->pghost = strdup(pghost);
581 if (pgport && pgport[0] != '\0')
585 conn->pgport = strdup(pgport);
588 if (pgoptions && pgoptions[0] != '\0')
591 free(conn->pgoptions);
592 conn->pgoptions = strdup(pgoptions);
595 if (pgtty && pgtty[0] != '\0')
599 conn->pgtty = strdup(pgtty);
602 if (dbName && dbName[0] != '\0')
606 conn->dbName = strdup(dbName);
609 if (login && login[0] != '\0')
613 conn->pguser = strdup(login);
616 if (pwd && pwd[0] != '\0')
620 conn->pgpass = strdup(pwd);
624 * Compute derived options
626 if (!connectOptions2(conn))
630 * Connect to the database
632 if (connectDBStart(conn))
633 (void) connectDBComplete(conn);
641 * Sets the TCP_NODELAY socket option.
642 * Returns 1 if successful, 0 if not.
646 connectNoDelay(PGconn *conn)
651 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
657 printfPQExpBuffer(&conn->errorMessage,
658 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
659 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
669 * connectFailureMessage -
670 * create a friendly error message on connection failure.
674 connectFailureMessage(PGconn *conn, int errorno)
678 #ifdef HAVE_UNIX_SOCKETS
679 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
681 char service[NI_MAXHOST];
683 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
685 service, sizeof(service),
687 printfPQExpBuffer(&conn->errorMessage,
688 libpq_gettext("could not connect to server: %s\n"
689 "\tIs the server running locally and accepting\n"
690 "\tconnections on Unix domain socket \"%s\"?\n"),
691 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
695 #endif /* HAVE_UNIX_SOCKETS */
697 printfPQExpBuffer(&conn->errorMessage,
698 libpq_gettext("could not connect to server: %s\n"
699 "\tIs the server running on host \"%s\" and accepting\n"
700 "\tTCP/IP connections on port %s?\n"),
701 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
714 * Begin the process of making a connection to the backend.
716 * Returns 1 if successful, 0 if not.
720 connectDBStart(PGconn *conn)
724 struct addrinfo *addrs = NULL;
725 struct addrinfo hint;
732 /* Ensure our buffers are empty */
733 conn->inStart = conn->inCursor = conn->inEnd = 0;
737 * Determine the parameters to pass to pg_getaddrinfo_all.
740 /* Initialize hint structure */
741 MemSet(&hint, 0, sizeof(hint));
742 hint.ai_socktype = SOCK_STREAM;
743 hint.ai_family = AF_UNSPEC;
745 /* Set up port number as a string */
746 if (conn->pgport != NULL && conn->pgport[0] != '\0')
747 portnum = atoi(conn->pgport);
749 portnum = DEF_PGPORT;
750 snprintf(portstr, sizeof(portstr), "%d", portnum);
752 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
754 /* Using pghostaddr avoids a hostname lookup */
755 node = conn->pghostaddr;
756 hint.ai_family = AF_UNSPEC;
757 hint.ai_flags = AI_NUMERICHOST;
759 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
761 /* Using pghost, so we have to look-up the hostname */
763 hint.ai_family = AF_UNSPEC;
767 #ifdef HAVE_UNIX_SOCKETS
768 /* pghostaddr and pghost are NULL, so use Unix domain socket */
770 hint.ai_family = AF_UNIX;
771 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
773 /* Without Unix sockets, default to localhost instead */
775 hint.ai_family = AF_UNSPEC;
776 #endif /* HAVE_UNIX_SOCKETS */
779 /* Use pg_getaddrinfo_all() to resolve the address */
780 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
784 printfPQExpBuffer(&conn->errorMessage,
785 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
786 node, gai_strerror(ret));
788 printfPQExpBuffer(&conn->errorMessage,
789 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
790 portstr, gai_strerror(ret));
792 pg_freeaddrinfo_all(hint.ai_family, addrs);
793 goto connect_errReturn;
797 /* setup values based on SSL mode */
798 if (conn->sslmode[0] == 'd') /* "disable" */
799 conn->allow_ssl_try = false;
800 else if (conn->sslmode[0] == 'a') /* "allow" */
801 conn->wait_ssl_try = true;
805 * Set up to try to connect, with protocol 3.0 as the first attempt.
807 conn->addrlist = addrs;
808 conn->addr_cur = addrs;
809 conn->addrlist_family = hint.ai_family;
810 conn->pversion = PG_PROTOCOL(3, 0);
811 conn->status = CONNECTION_NEEDED;
814 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
815 * so that it can easily be re-executed if needed again during the
816 * asynchronous startup process. However, we must run it once here,
817 * because callers expect a success return from this routine to mean that
818 * we are in PGRES_POLLING_WRITING connection state.
820 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
826 pqsecure_close(conn);
827 closesocket(conn->sock);
830 conn->status = CONNECTION_BAD;
838 * Block and complete a connection.
840 * Returns 1 on success, 0 on failure.
843 connectDBComplete(PGconn *conn)
845 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
846 time_t finish_time = ((time_t) -1);
848 if (conn == NULL || conn->status == CONNECTION_BAD)
852 * Set up a time limit, if connect_timeout isn't zero.
854 if (conn->connect_timeout != NULL)
856 int timeout = atoi(conn->connect_timeout);
861 * Rounding could cause connection to fail; need at least 2 secs
865 /* calculate the finish time based on start + timeout */
866 finish_time = time(NULL) + timeout;
873 * Wait, if necessary. Note that the initial state (just after
874 * PQconnectStart) is to wait for the socket to select for writing.
878 case PGRES_POLLING_OK:
879 return 1; /* success! */
881 case PGRES_POLLING_READING:
882 if (pqWaitTimed(1, 0, conn, finish_time))
884 conn->status = CONNECTION_BAD;
889 case PGRES_POLLING_WRITING:
890 if (pqWaitTimed(0, 1, conn, finish_time))
892 conn->status = CONNECTION_BAD;
898 /* Just in case we failed to set it in PQconnectPoll */
899 conn->status = CONNECTION_BAD;
904 * Now try to advance the state machine.
906 flag = PQconnectPoll(conn);
913 * Poll an asynchronous connection.
915 * Returns a PostgresPollingStatusType.
916 * Before calling this function, use select(2) to determine when data
919 * You must call PQfinish whether or not this fails.
921 * This function and PQconnectStart are intended to allow connections to be
922 * made without blocking the execution of your program on remote I/O. However,
923 * there are a number of caveats:
925 * o If you call PQtrace, ensure that the stream object into which you trace
927 * o If you do not supply an IP address for the remote host (i.e. you
928 * supply a host name instead) then PQconnectStart will block on
929 * gethostbyname. You will be fine if using Unix sockets (i.e. by
930 * supplying neither a host name nor a host address).
931 * o If your backend wants to use Kerberos authentication then you must
932 * supply both a host name and a host address, otherwise this function
933 * may block on gethostname.
937 PostgresPollingStatusType
938 PQconnectPoll(PGconn *conn)
944 return PGRES_POLLING_FAILED;
946 /* Get the new data */
947 switch (conn->status)
950 * We really shouldn't have been polled in these two cases, but we
954 return PGRES_POLLING_FAILED;
956 return PGRES_POLLING_OK;
958 /* These are reading states */
959 case CONNECTION_AWAITING_RESPONSE:
960 case CONNECTION_AUTH_OK:
962 /* Load waiting data */
963 int n = pqReadData(conn);
968 return PGRES_POLLING_READING;
973 /* These are writing states, so we just proceed. */
974 case CONNECTION_STARTED:
975 case CONNECTION_MADE:
978 /* We allow pqSetenvPoll to decide whether to proceed. */
979 case CONNECTION_SETENV:
982 /* Special cases: proceed without waiting. */
983 case CONNECTION_SSL_STARTUP:
984 case CONNECTION_NEEDED:
988 printfPQExpBuffer(&conn->errorMessage,
990 "invalid connection state, "
991 "probably indicative of memory corruption\n"
997 keep_going: /* We will come back to here until there is
998 * nothing left to do. */
999 switch (conn->status)
1001 case CONNECTION_NEEDED:
1004 * Try to initiate a connection to one of the addresses
1005 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1006 * next one to try. We fail when we run out of addresses
1007 * (reporting the error returned for the *last* alternative,
1008 * which may not be what users expect :-().
1010 while (conn->addr_cur != NULL)
1012 struct addrinfo *addr_cur = conn->addr_cur;
1014 /* Remember current address for possible error msg */
1015 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1016 addr_cur->ai_addrlen);
1017 conn->raddr.salen = addr_cur->ai_addrlen;
1020 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1024 * ignore socket() failure if we have more addresses
1027 if (addr_cur->ai_next != NULL)
1029 conn->addr_cur = addr_cur->ai_next;
1032 printfPQExpBuffer(&conn->errorMessage,
1033 libpq_gettext("could not create socket: %s\n"),
1034 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1039 * Select socket options: no delay of outgoing data for
1040 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1043 if (!IS_AF_UNIX(addr_cur->ai_family))
1045 if (!connectNoDelay(conn))
1047 closesocket(conn->sock);
1049 conn->addr_cur = addr_cur->ai_next;
1053 if (!pg_set_noblock(conn->sock))
1055 printfPQExpBuffer(&conn->errorMessage,
1056 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1057 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1058 closesocket(conn->sock);
1060 conn->addr_cur = addr_cur->ai_next;
1065 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1067 printfPQExpBuffer(&conn->errorMessage,
1068 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1069 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1070 closesocket(conn->sock);
1072 conn->addr_cur = addr_cur->ai_next;
1075 #endif /* F_SETFD */
1078 * Start/make connection. This should not block, since we
1079 * are in nonblock mode. If it does, well, too bad.
1081 if (connect(conn->sock, addr_cur->ai_addr,
1082 addr_cur->ai_addrlen) < 0)
1084 if (SOCK_ERRNO == EINPROGRESS ||
1085 SOCK_ERRNO == EWOULDBLOCK ||
1086 SOCK_ERRNO == EINTR ||
1090 * This is fine - we're in non-blocking mode, and
1091 * the connection is in progress. Tell caller to
1092 * wait for write-ready on socket.
1094 conn->status = CONNECTION_STARTED;
1095 return PGRES_POLLING_WRITING;
1097 /* otherwise, trouble */
1102 * Hm, we're connected already --- seems the "nonblock
1103 * connection" wasn't. Advance the state machine and
1104 * go do the next stuff.
1106 conn->status = CONNECTION_STARTED;
1111 * This connection failed --- set up error report, then
1112 * close socket (do it this way in case close() affects
1113 * the value of errno...). We will ignore the connect()
1114 * failure and keep going if there are more addresses.
1116 connectFailureMessage(conn, SOCK_ERRNO);
1117 if (conn->sock >= 0)
1119 closesocket(conn->sock);
1124 * Try the next address, if any.
1126 conn->addr_cur = addr_cur->ai_next;
1127 } /* loop over addresses */
1130 * Ooops, no more addresses. An appropriate error message is
1131 * already set up, so just set the right status.
1136 case CONNECTION_STARTED:
1139 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1142 * Write ready, since we've made it here, so the connection
1143 * has been made ... or has failed.
1147 * Now check (using getsockopt) that there is not an error
1148 * state waiting for us on the socket.
1151 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1152 (char *) &optval, &optlen) == -1)
1154 printfPQExpBuffer(&conn->errorMessage,
1155 libpq_gettext("could not get socket error status: %s\n"),
1156 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1159 else if (optval != 0)
1162 * When using a nonblocking connect, we will typically see
1163 * connect failures at this point, so provide a friendly
1166 connectFailureMessage(conn, optval);
1169 * If more addresses remain, keep trying, just as in the
1170 * case where connect() returned failure immediately.
1172 if (conn->addr_cur->ai_next != NULL)
1174 if (conn->sock >= 0)
1176 closesocket(conn->sock);
1179 conn->addr_cur = conn->addr_cur->ai_next;
1180 conn->status = CONNECTION_NEEDED;
1186 /* Fill in the client address */
1187 conn->laddr.salen = sizeof(conn->laddr.addr);
1188 if (getsockname(conn->sock,
1189 (struct sockaddr *) & conn->laddr.addr,
1190 &conn->laddr.salen) < 0)
1192 printfPQExpBuffer(&conn->errorMessage,
1193 libpq_gettext("could not get client address from socket: %s\n"),
1194 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1199 * Make sure we can write before advancing to next step.
1201 conn->status = CONNECTION_MADE;
1202 return PGRES_POLLING_WRITING;
1205 case CONNECTION_MADE:
1213 * If SSL is enabled and we haven't already got it running,
1214 * request it instead of sending the startup message.
1216 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1218 /* Don't bother requesting SSL over a Unix socket */
1219 conn->allow_ssl_try = false;
1221 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1227 * Send the SSL request packet.
1229 * Theoretically, this could block, but it really
1230 * shouldn't since we only got here if the socket is
1233 pv = htonl(NEGOTIATE_SSL_CODE);
1234 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1236 printfPQExpBuffer(&conn->errorMessage,
1237 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1238 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1241 /* Ok, wait for response */
1242 conn->status = CONNECTION_SSL_STARTUP;
1243 return PGRES_POLLING_READING;
1245 #endif /* USE_SSL */
1248 * Build the startup packet.
1250 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1251 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1252 EnvironmentOptions);
1254 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1255 EnvironmentOptions);
1258 printfPQExpBuffer(&conn->errorMessage,
1259 libpq_gettext("out of memory\n"));
1264 * Send the startup packet.
1266 * Theoretically, this could block, but it really shouldn't
1267 * since we only got here if the socket is write-ready.
1269 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1271 printfPQExpBuffer(&conn->errorMessage,
1272 libpq_gettext("could not send startup packet: %s\n"),
1273 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1280 conn->status = CONNECTION_AWAITING_RESPONSE;
1281 return PGRES_POLLING_READING;
1285 * Handle SSL negotiation: wait for postmaster messages and
1286 * respond as necessary.
1288 case CONNECTION_SSL_STARTUP:
1291 PostgresPollingStatusType pollres;
1294 * On first time through, get the postmaster's response to our
1295 * SSL negotiation packet.
1297 if (conn->ssl == NULL)
1300 * We use pqReadData here since it has the logic to
1301 * distinguish no-data-yet from connection closure. Since
1302 * conn->ssl isn't set, a plain recv() will occur.
1307 rdresult = pqReadData(conn);
1310 /* errorMessage is already filled in */
1315 /* caller failed to wait for data */
1316 return PGRES_POLLING_READING;
1318 if (pqGetc(&SSLok, conn) < 0)
1320 /* should not happen really */
1321 return PGRES_POLLING_READING;
1323 /* mark byte consumed */
1324 conn->inStart = conn->inCursor;
1327 /* Do one-time setup; this creates conn->ssl */
1328 if (pqsecure_initialize(conn) == -1)
1331 else if (SSLok == 'N')
1333 if (conn->sslmode[0] == 'r') /* "require" */
1335 /* Require SSL, but server does not want it */
1336 printfPQExpBuffer(&conn->errorMessage,
1337 libpq_gettext("server does not support SSL, but SSL was required\n"));
1340 /* Otherwise, proceed with normal startup */
1341 conn->allow_ssl_try = false;
1342 conn->status = CONNECTION_MADE;
1343 return PGRES_POLLING_WRITING;
1345 else if (SSLok == 'E')
1347 /* Received error - probably protocol mismatch */
1349 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1350 if (conn->sslmode[0] == 'r') /* "require" */
1352 /* Require SSL, but server is too old */
1353 printfPQExpBuffer(&conn->errorMessage,
1354 libpq_gettext("server does not support SSL, but SSL was required\n"));
1357 /* Otherwise, try again without SSL */
1358 conn->allow_ssl_try = false;
1359 /* Assume it ain't gonna handle protocol 3, either */
1360 conn->pversion = PG_PROTOCOL(2, 0);
1361 /* Must drop the old connection */
1362 closesocket(conn->sock);
1364 conn->status = CONNECTION_NEEDED;
1369 printfPQExpBuffer(&conn->errorMessage,
1370 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1377 * Begin or continue the SSL negotiation process.
1379 pollres = pqsecure_open_client(conn);
1380 if (pollres == PGRES_POLLING_OK)
1382 /* SSL handshake done, ready to send startup packet */
1383 conn->status = CONNECTION_MADE;
1384 return PGRES_POLLING_WRITING;
1387 #else /* !USE_SSL */
1388 /* can't get here */
1390 #endif /* USE_SSL */
1394 * Handle authentication exchange: wait for postmaster messages
1395 * and respond as necessary.
1397 case CONNECTION_AWAITING_RESPONSE:
1405 * Scan the message from current point (note that if we find
1406 * the message is incomplete, we will return without advancing
1407 * inStart, and resume here next time).
1409 conn->inCursor = conn->inStart;
1411 /* Read type byte */
1412 if (pqGetc(&beresp, conn))
1414 /* We'll come back when there is more data */
1415 return PGRES_POLLING_READING;
1419 * Validate message type: we expect only an authentication
1420 * request or an error here. Anything else probably means
1421 * it's not Postgres on the other end at all.
1423 if (!(beresp == 'R' || beresp == 'E'))
1425 printfPQExpBuffer(&conn->errorMessage,
1427 "expected authentication request from "
1428 "server, but received %c\n"),
1433 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1435 /* Read message length word */
1436 if (pqGetInt(&msgLength, 4, conn))
1438 /* We'll come back when there is more data */
1439 return PGRES_POLLING_READING;
1444 /* Set phony message length to disable checks below */
1449 * Try to validate message length before using it.
1450 * Authentication requests can't be very large. Errors can be
1451 * a little larger, but not huge. If we see a large apparent
1452 * length in an error, it means we're really talking to a
1453 * pre-3.0-protocol server; cope.
1455 if (beresp == 'R' && (msgLength < 8 || msgLength > 100))
1457 printfPQExpBuffer(&conn->errorMessage,
1459 "expected authentication request from "
1460 "server, but received %c\n"),
1465 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1467 /* Handle error from a pre-3.0 server */
1468 conn->inCursor = conn->inStart + 1; /* reread data */
1469 if (pqGets(&conn->errorMessage, conn))
1471 /* We'll come back when there is more data */
1472 return PGRES_POLLING_READING;
1474 /* OK, we read the message; mark data consumed */
1475 conn->inStart = conn->inCursor;
1478 * The postmaster typically won't end its message with a
1479 * newline, so add one to conform to libpq conventions.
1481 appendPQExpBufferChar(&conn->errorMessage, '\n');
1484 * If we tried to open the connection in 3.0 protocol,
1485 * fall back to 2.0 protocol.
1487 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1489 conn->pversion = PG_PROTOCOL(2, 0);
1490 /* Must drop the old connection */
1491 pqsecure_close(conn);
1492 closesocket(conn->sock);
1494 conn->status = CONNECTION_NEEDED;
1502 * Can't process if message body isn't all here yet.
1504 * (In protocol 2.0 case, we are assuming messages carry at
1505 * least 4 bytes of data.)
1508 avail = conn->inEnd - conn->inCursor;
1509 if (avail < msgLength)
1512 * Before returning, try to enlarge the input buffer if
1513 * needed to hold the whole message; see notes in
1516 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1518 /* We'll come back when there is more data */
1519 return PGRES_POLLING_READING;
1522 /* Handle errors. */
1525 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1527 if (pqGetErrorNotice3(conn, true))
1529 /* We'll come back when there is more data */
1530 return PGRES_POLLING_READING;
1535 if (pqGets(&conn->errorMessage, conn))
1537 /* We'll come back when there is more data */
1538 return PGRES_POLLING_READING;
1541 /* OK, we read the message; mark data consumed */
1542 conn->inStart = conn->inCursor;
1547 * if sslmode is "allow" and we haven't tried an SSL
1548 * connection already, then retry with an SSL connection
1550 if (conn->sslmode[0] == 'a' /* "allow" */
1551 && conn->ssl == NULL
1552 && conn->allow_ssl_try
1553 && conn->wait_ssl_try)
1555 /* only retry once */
1556 conn->wait_ssl_try = false;
1557 /* Must drop the old connection */
1558 closesocket(conn->sock);
1560 conn->status = CONNECTION_NEEDED;
1565 * if sslmode is "prefer" and we're in an SSL connection,
1566 * then do a non-SSL retry
1568 if (conn->sslmode[0] == 'p' /* "prefer" */
1570 && conn->allow_ssl_try /* redundant? */
1571 && !conn->wait_ssl_try) /* redundant? */
1573 /* only retry once */
1574 conn->allow_ssl_try = false;
1575 /* Must drop the old connection */
1576 pqsecure_close(conn);
1577 closesocket(conn->sock);
1579 conn->status = CONNECTION_NEEDED;
1587 /* It is an authentication request. */
1588 /* Get the type of request. */
1589 if (pqGetInt((int *) &areq, 4, conn))
1591 /* We'll come back when there are more data */
1592 return PGRES_POLLING_READING;
1595 /* Get the password salt if there is one. */
1596 if (areq == AUTH_REQ_MD5)
1598 if (pqGetnchar(conn->md5Salt,
1599 sizeof(conn->md5Salt), conn))
1601 /* We'll come back when there are more data */
1602 return PGRES_POLLING_READING;
1605 if (areq == AUTH_REQ_CRYPT)
1607 if (pqGetnchar(conn->cryptSalt,
1608 sizeof(conn->cryptSalt), conn))
1610 /* We'll come back when there are more data */
1611 return PGRES_POLLING_READING;
1616 * OK, we successfully read the message; mark data consumed
1618 conn->inStart = conn->inCursor;
1620 /* Respond to the request if necessary. */
1623 * Note that conn->pghost must be non-NULL if we are going to
1624 * avoid the Kerberos code doing a hostname look-up.
1628 * XXX fe-auth.c has not been fixed to support PQExpBuffers,
1631 if (pg_fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1632 conn->errorMessage.data) != STATUS_OK)
1634 conn->errorMessage.len = strlen(conn->errorMessage.data);
1637 conn->errorMessage.len = strlen(conn->errorMessage.data);
1640 * Just make sure that any data sent by pg_fe_sendauth is
1641 * flushed out. Although this theoretically could block, it
1642 * really shouldn't since we don't send large auth responses.
1647 if (areq == AUTH_REQ_OK)
1649 /* We are done with authentication exchange */
1650 conn->status = CONNECTION_AUTH_OK;
1653 * Set asyncStatus so that PQsetResult will think that
1654 * what comes back next is the result of a query. See
1657 conn->asyncStatus = PGASYNC_BUSY;
1660 /* Look to see if we have more data yet. */
1664 case CONNECTION_AUTH_OK:
1667 * Now we expect to hear from the backend. A ReadyForQuery
1668 * message indicates that startup is successful, but we might
1669 * also get an Error message indicating failure. (Notice
1670 * messages indicating nonfatal warnings are also allowed by
1671 * the protocol, as are ParameterStatus and BackendKeyData
1672 * messages.) Easiest way to handle this is to let
1673 * PQgetResult() read the messages. We just have to fake it
1674 * out about the state of the connection, by setting
1675 * asyncStatus = PGASYNC_BUSY (done above).
1679 return PGRES_POLLING_READING;
1681 res = PQgetResult(conn);
1684 * NULL return indicating we have gone to IDLE state is
1689 if (res->resultStatus != PGRES_FATAL_ERROR)
1690 printfPQExpBuffer(&conn->errorMessage,
1691 libpq_gettext("unexpected message from server during startup\n"));
1694 * if the resultStatus is FATAL, then conn->errorMessage
1695 * already has a copy of the error; needn't copy it back.
1696 * But add a newline if it's not there already, since
1697 * postmaster error messages may not have one.
1699 if (conn->errorMessage.len <= 0 ||
1700 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1701 appendPQExpBufferChar(&conn->errorMessage, '\n');
1706 /* We can release the address list now. */
1707 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1708 conn->addrlist = NULL;
1709 conn->addr_cur = NULL;
1711 /* Fire up post-connection housekeeping if needed */
1712 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1714 conn->status = CONNECTION_SETENV;
1715 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1716 conn->next_eo = EnvironmentOptions;
1717 return PGRES_POLLING_WRITING;
1720 /* Otherwise, we are open for business! */
1721 conn->status = CONNECTION_OK;
1722 return PGRES_POLLING_OK;
1725 case CONNECTION_SETENV:
1728 * Do post-connection housekeeping (only needed in protocol 2.0).
1730 * We pretend that the connection is OK for the duration of these
1733 conn->status = CONNECTION_OK;
1735 switch (pqSetenvPoll(conn))
1737 case PGRES_POLLING_OK: /* Success */
1740 case PGRES_POLLING_READING: /* Still going */
1741 conn->status = CONNECTION_SETENV;
1742 return PGRES_POLLING_READING;
1744 case PGRES_POLLING_WRITING: /* Still going */
1745 conn->status = CONNECTION_SETENV;
1746 return PGRES_POLLING_WRITING;
1752 /* We are open for business! */
1753 conn->status = CONNECTION_OK;
1754 return PGRES_POLLING_OK;
1757 printfPQExpBuffer(&conn->errorMessage,
1759 "invalid connection state %c, "
1760 "probably indicative of memory corruption\n"
1771 * We used to close the socket at this point, but that makes it awkward
1772 * for those above us if they wish to remove this socket from their own
1773 * records (an fd_set for example). We'll just have this socket closed
1774 * when PQfinish is called (which is compulsory even after an error, since
1775 * the connection structure must be freed).
1777 conn->status = CONNECTION_BAD;
1778 return PGRES_POLLING_FAILED;
1784 * - create a PGconn data structure with (as yet) no interesting data
1787 makeEmptyPGconn(void)
1794 * Make sure socket support is up and running. Even though this is done in
1795 * libpqdll.c, that is only for MSVC and BCC builds and doesn't work for
1796 * static builds at all, so we have to do it in the main code too.
1800 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1805 conn = (PGconn *) malloc(sizeof(PGconn));
1809 /* Zero all pointers and booleans */
1810 MemSet(conn, 0, sizeof(PGconn));
1812 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1813 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1814 conn->status = CONNECTION_BAD;
1815 conn->asyncStatus = PGASYNC_IDLE;
1816 conn->xactStatus = PQTRANS_IDLE;
1817 conn->setenv_state = SETENV_STATE_IDLE;
1818 conn->client_encoding = PG_SQL_ASCII;
1819 conn->verbosity = PQERRORS_DEFAULT;
1822 conn->allow_ssl_try = true;
1823 conn->wait_ssl_try = false;
1827 * We try to send at least 8K at a time, which is the usual size of pipe
1828 * buffers on Unix systems. That way, when we are sending a large amount
1829 * of data, we avoid incurring extra kernel context swaps for partial
1830 * bufferloads. The output buffer is initially made 16K in size, and we
1831 * try to dump it after accumulating 8K.
1833 * With the same goal of minimizing context swaps, the input buffer will
1834 * be enlarged anytime it has less than 8K free, so we initially allocate
1837 conn->inBufSize = 16 * 1024;
1838 conn->inBuffer = (char *) malloc(conn->inBufSize);
1839 conn->outBufSize = 16 * 1024;
1840 conn->outBuffer = (char *) malloc(conn->outBufSize);
1841 conn->nonblocking = FALSE;
1842 initPQExpBuffer(&conn->errorMessage);
1843 initPQExpBuffer(&conn->workBuffer);
1845 if (conn->inBuffer == NULL ||
1846 conn->outBuffer == NULL ||
1847 conn->errorMessage.data == NULL ||
1848 conn->workBuffer.data == NULL)
1850 /* out of memory already :-( */
1860 * - free the PGconn data structure
1862 * When changing/adding to this function, see also closePGconn!
1865 freePGconn(PGconn *conn)
1868 pgParameterStatus *pstatus;
1877 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1878 if (conn->sock >= 0)
1880 pqsecure_close(conn);
1881 closesocket(conn->sock);
1885 if (conn->pghostaddr)
1886 free(conn->pghostaddr);
1889 if (conn->pgunixsocket)
1890 free(conn->pgunixsocket);
1893 if (conn->connect_timeout)
1894 free(conn->connect_timeout);
1895 if (conn->pgoptions)
1896 free(conn->pgoptions);
1904 free(conn->sslmode);
1906 if (conn->krbsrvname)
1907 free(conn->krbsrvname);
1909 /* Note that conn->Pfdebug is not ours to close or free */
1910 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1911 notify = conn->notifyHead;
1912 while (notify != NULL)
1914 PGnotify *prev = notify;
1916 notify = notify->next;
1919 pstatus = conn->pstatus;
1920 while (pstatus != NULL)
1922 pgParameterStatus *prev = pstatus;
1924 pstatus = pstatus->next;
1927 if (conn->lobjfuncs)
1928 free(conn->lobjfuncs);
1930 free(conn->inBuffer);
1931 if (conn->outBuffer)
1932 free(conn->outBuffer);
1933 termPQExpBuffer(&conn->errorMessage);
1934 termPQExpBuffer(&conn->workBuffer);
1940 * - properly close a connection to the backend
1942 * Release all transient state, but NOT the connection parameters.
1945 closePGconn(PGconn *conn)
1948 pgParameterStatus *pstatus;
1951 * Note that the protocol doesn't allow us to send Terminate messages
1952 * during the startup phase.
1954 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1957 * Try to send "close connection" message to backend. Ignore any
1960 pqPutMsgStart('X', false, conn);
1966 * must reset the blocking status so a possible reconnect will work don't
1967 * call PQsetnonblocking() because it will fail if it's unable to flush
1970 conn->nonblocking = FALSE;
1973 * Close the connection, reset all transient state, flush I/O buffers.
1975 if (conn->sock >= 0)
1977 pqsecure_close(conn);
1978 closesocket(conn->sock);
1981 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
1983 conn->asyncStatus = PGASYNC_IDLE;
1984 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1985 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1986 conn->addrlist = NULL;
1987 conn->addr_cur = NULL;
1988 notify = conn->notifyHead;
1989 while (notify != NULL)
1991 PGnotify *prev = notify;
1993 notify = notify->next;
1996 conn->notifyHead = NULL;
1997 pstatus = conn->pstatus;
1998 while (pstatus != NULL)
2000 pgParameterStatus *prev = pstatus;
2002 pstatus = pstatus->next;
2005 conn->pstatus = NULL;
2006 if (conn->lobjfuncs)
2007 free(conn->lobjfuncs);
2008 conn->lobjfuncs = NULL;
2009 conn->inStart = conn->inCursor = conn->inEnd = 0;
2014 * PQfinish: properly close a connection to the backend. Also frees
2015 * the PGconn data structure so it shouldn't be re-used after this.
2018 PQfinish(PGconn *conn)
2028 * PQreset: resets the connection to the backend by closing the
2029 * existing connection and creating a new one.
2032 PQreset(PGconn *conn)
2038 if (connectDBStart(conn))
2039 (void) connectDBComplete(conn);
2046 * resets the connection to the backend
2047 * closes the existing connection and makes a new one
2048 * Returns 1 on success, 0 on failure.
2051 PQresetStart(PGconn *conn)
2057 return connectDBStart(conn);
2066 * resets the connection to the backend
2067 * closes the existing connection and makes a new one
2069 PostgresPollingStatusType
2070 PQresetPoll(PGconn *conn)
2073 return PQconnectPoll(conn);
2075 return PGRES_POLLING_FAILED;
2079 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2081 * A copy is needed to be able to cancel a running query from a different
2082 * thread. If the same structure is used all structure members would have
2083 * to be individually locked (if the entire structure was locked, it would
2084 * be impossible to cancel a synchronous query becuase the structure would
2085 * have to stay locked for the duration of the query).
2088 PQgetCancel(PGconn *conn)
2098 cancel = malloc(sizeof(PGcancel));
2102 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2103 cancel->be_pid = conn->be_pid;
2104 cancel->be_key = conn->be_key;
2109 /* PQfreeCancel: free a cancel structure */
2111 PQfreeCancel(PGcancel *cancel)
2119 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2120 * current operation.
2122 * The return value is TRUE if the cancel request was successfully
2123 * dispatched, FALSE if not (in which case an error message is available).
2124 * Note: successful dispatch is no guarantee that there will be any effect at
2125 * the backend. The application must read the operation result as usual.
2127 * CAUTION: we want this routine to be safely callable from a signal handler
2128 * (for example, an application might want to call it in a SIGINT handler).
2129 * This means we cannot use any C library routine that might be non-reentrant.
2130 * malloc/free are often non-reentrant, and anything that might call them is
2131 * just as dangerous. We avoid sprintf here for that reason. Building up
2132 * error messages with strcpy/strcat is tedious but should be quite safe.
2133 * We also save/restore errno in case the signal handler support doesn't.
2135 * internal_cancel() is an internal helper function to make code-sharing
2136 * between the two versions of the cancel function possible.
2139 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2140 char *errbuf, int errbufsize)
2142 int save_errno = SOCK_ERRNO;
2149 CancelRequestPacket cp;
2153 * We need to open a temporary connection to the postmaster. Do this with
2154 * only kernel calls.
2156 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2158 StrNCpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2159 goto cancel_errReturn;
2162 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2165 if (SOCK_ERRNO == EINTR)
2166 /* Interrupted system call - we'll just try again */
2168 StrNCpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2169 goto cancel_errReturn;
2173 * We needn't set nonblocking I/O or NODELAY options here.
2176 /* Create and send the cancel request packet. */
2178 crp.packetlen = htonl((uint32) sizeof(crp));
2179 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2180 crp.cp.backendPID = htonl(be_pid);
2181 crp.cp.cancelAuthCode = htonl(be_key);
2184 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2186 if (SOCK_ERRNO == EINTR)
2187 /* Interrupted system call - we'll just try again */
2189 StrNCpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2190 goto cancel_errReturn;
2194 * Wait for the postmaster to close the connection, which indicates that
2195 * it's processed the request. Without this delay, we might issue another
2196 * command only to find that our cancel zaps that command instead of the
2197 * one we thought we were canceling. Note we don't actually expect this
2198 * read to obtain any data, we are just waiting for EOF to be signaled.
2201 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2203 if (SOCK_ERRNO == EINTR)
2204 /* Interrupted system call - we'll just try again */
2206 /* we ignore other error conditions */
2210 closesocket(tmpsock);
2211 SOCK_ERRNO_SET(save_errno);
2217 * Make sure we don't overflow the error buffer. Leave space for the \n at
2218 * the end, and for the terminating zero.
2220 maxlen = errbufsize - strlen(errbuf) - 2;
2223 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2225 strcat(errbuf, "\n");
2228 closesocket(tmpsock);
2229 SOCK_ERRNO_SET(save_errno);
2234 * PQcancel: request query cancel
2236 * Returns TRUE if able to send the cancel request, FALSE if not.
2238 * On failure, an error message is stored in *errbuf, which must be of size
2239 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2243 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2247 StrNCpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2251 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2252 errbuf, errbufsize);
2256 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2258 * Returns TRUE if able to send the cancel request, FALSE if not.
2260 * On failure, the error message is saved in conn->errorMessage; this means
2261 * that this can't be used when there might be other active operations on
2262 * the connection object.
2264 * NOTE: error messages will be cut off at the current size of the
2265 * error message buffer, since we dare not try to expand conn->errorMessage!
2268 PQrequestCancel(PGconn *conn)
2272 /* Check we have an open connection */
2278 StrNCpy(conn->errorMessage.data,
2279 "PQrequestCancel() -- connection is not open\n",
2280 conn->errorMessage.maxlen);
2281 conn->errorMessage.len = strlen(conn->errorMessage.data);
2286 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2287 conn->errorMessage.data, conn->errorMessage.maxlen);
2290 conn->errorMessage.len = strlen(conn->errorMessage.data);
2297 * pqPacketSend() -- convenience routine to send a message to server.
2299 * pack_type: the single-byte message type code. (Pass zero for startup
2300 * packets, which have no message type code.)
2302 * buf, buf_len: contents of message. The given length includes only what
2303 * is in buf; the message type and message length fields are added here.
2305 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2306 * SIDE_EFFECTS: may block.
2308 * Note: all messages sent with this routine have a length word, whether
2309 * it's protocol 2.0 or 3.0.
2312 pqPacketSend(PGconn *conn, char pack_type,
2313 const void *buf, size_t buf_len)
2315 /* Start the message. */
2316 if (pqPutMsgStart(pack_type, true, conn))
2317 return STATUS_ERROR;
2319 /* Send the message body. */
2320 if (pqPutnchar(buf, buf_len, conn))
2321 return STATUS_ERROR;
2323 /* Finish the message. */
2324 if (pqPutMsgEnd(conn))
2325 return STATUS_ERROR;
2327 /* Flush to ensure backend gets it. */
2329 return STATUS_ERROR;
2336 #define MAXBUFSIZE 256
2339 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2341 char *service = conninfo_getval(options, "service");
2342 char serviceFile[MAXPGPATH];
2343 bool group_found = false;
2348 * We have to special-case the environment variable PGSERVICE here, since
2349 * this is and should be called before inserting environment defaults for
2350 * other connection options.
2352 if (service == NULL)
2353 service = getenv("PGSERVICE");
2356 * This could be used by any application so we can't use the binary
2357 * location to find our config files.
2359 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2360 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2362 if (service != NULL)
2365 char buf[MAXBUFSIZE],
2368 f = fopen(serviceFile, "r");
2371 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2376 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2380 if (strlen(line) >= MAXBUFSIZE - 2)
2383 printfPQExpBuffer(errorMessage,
2384 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2390 /* ignore EOL at end of line */
2391 if (strlen(line) && line[strlen(line) - 1] == '\n')
2392 line[strlen(line) - 1] = 0;
2394 /* ignore leading blanks */
2395 while (*line && isspace((unsigned char) line[0]))
2398 /* ignore comments and empty lines */
2399 if (strlen(line) == 0 || line[0] == '#')
2402 /* Check for right groupname */
2407 /* group info already read */
2412 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2413 line[strlen(service) + 1] == ']')
2416 group_found = false;
2423 * Finally, we are in the right group and can parse the
2431 val = strchr(line, '=');
2434 printfPQExpBuffer(errorMessage,
2435 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
2444 * Set the parameter --- but don't override any previous
2447 found_keyword = false;
2448 for (i = 0; options[i].keyword; i++)
2450 if (strcmp(options[i].keyword, key) == 0)
2452 if (options[i].val == NULL)
2453 options[i].val = strdup(val);
2454 found_keyword = true;
2461 printfPQExpBuffer(errorMessage,
2462 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
2480 * Conninfo parser routine
2482 * If successful, a malloc'd PQconninfoOption array is returned.
2483 * If not successful, NULL is returned and an error message is
2484 * left in errorMessage.
2486 static PQconninfoOption *
2487 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2495 PQconninfoOption *options;
2496 PQconninfoOption *option;
2497 char errortmp[PQERRORMSG_LENGTH];
2499 /* Make a working copy of PQconninfoOptions */
2500 options = malloc(sizeof(PQconninfoOptions));
2501 if (options == NULL)
2503 printfPQExpBuffer(errorMessage,
2504 libpq_gettext("out of memory\n"));
2507 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2509 /* Need a modifiable copy of the input string */
2510 if ((buf = strdup(conninfo)) == NULL)
2512 printfPQExpBuffer(errorMessage,
2513 libpq_gettext("out of memory\n"));
2514 PQconninfoFree(options);
2521 /* Skip blanks before the parameter name */
2522 if (isspace((unsigned char) *cp))
2528 /* Get the parameter name */
2534 if (isspace((unsigned char) *cp))
2539 if (!isspace((unsigned char) *cp))
2548 /* Check that there is a following '=' */
2551 printfPQExpBuffer(errorMessage,
2552 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2554 PQconninfoFree(options);
2560 /* Skip blanks after the '=' */
2563 if (!isspace((unsigned char) *cp))
2568 /* Get the parameter value */
2576 if (isspace((unsigned char) *cp))
2600 printfPQExpBuffer(errorMessage,
2601 libpq_gettext("unterminated quoted string in connection info string\n"));
2602 PQconninfoFree(options);
2624 * Now we have the name and the value. Search for the param record.
2626 for (option = options; option->keyword != NULL; option++)
2628 if (strcmp(option->keyword, pname) == 0)
2631 if (option->keyword == NULL)
2633 printfPQExpBuffer(errorMessage,
2634 libpq_gettext("invalid connection option \"%s\"\n"),
2636 PQconninfoFree(options);
2646 option->val = strdup(pval);
2649 printfPQExpBuffer(errorMessage,
2650 libpq_gettext("out of memory\n"));
2651 PQconninfoFree(options);
2657 /* Done with the modifiable input string */
2661 * If there's a service spec, use it to obtain any not-explicitly-given
2664 if (parseServiceInfo(options, errorMessage))
2666 PQconninfoFree(options);
2671 * Get the fallback resources for parameters not specified in the conninfo
2672 * string nor the service.
2674 for (option = options; option->keyword != NULL; option++)
2676 if (option->val != NULL)
2677 continue; /* Value was in conninfo or service */
2680 * Try to get the environment variable fallback
2682 if (option->envvar != NULL)
2684 if ((tmp = getenv(option->envvar)) != NULL)
2686 option->val = strdup(tmp);
2689 printfPQExpBuffer(errorMessage,
2690 libpq_gettext("out of memory\n"));
2691 PQconninfoFree(options);
2699 * No environment variable specified or this one isn't set - try
2702 if (option->compiled != NULL)
2704 option->val = strdup(option->compiled);
2707 printfPQExpBuffer(errorMessage,
2708 libpq_gettext("out of memory\n"));
2709 PQconninfoFree(options);
2716 * Special handling for user
2718 if (strcmp(option->keyword, "user") == 0)
2720 option->val = pg_fe_getauthname(errortmp);
2721 /* note any error message is thrown away */
2731 conninfo_getval(PQconninfoOption *connOptions,
2732 const char *keyword)
2734 PQconninfoOption *option;
2736 for (option = connOptions; option->keyword != NULL; option++)
2738 if (strcmp(option->keyword, keyword) == 0)
2747 PQconninfoFree(PQconninfoOption *connOptions)
2749 PQconninfoOption *option;
2751 if (connOptions == NULL)
2754 for (option = connOptions; option->keyword != NULL; option++)
2756 if (option->val != NULL)
2763 /* =========== accessor functions for PGconn ========= */
2765 PQdb(const PGconn *conn)
2769 return conn->dbName;
2773 PQuser(const PGconn *conn)
2777 return conn->pguser;
2781 PQpass(const PGconn *conn)
2785 return conn->pgpass;
2789 PQhost(const PGconn *conn)
2793 return conn->pghost ? conn->pghost : conn->pgunixsocket;
2797 PQport(const PGconn *conn)
2801 return conn->pgport;
2805 PQtty(const PGconn *conn)
2813 PQoptions(const PGconn *conn)
2817 return conn->pgoptions;
2821 PQstatus(const PGconn *conn)
2824 return CONNECTION_BAD;
2825 return conn->status;
2828 PGTransactionStatusType
2829 PQtransactionStatus(const PGconn *conn)
2831 if (!conn || conn->status != CONNECTION_OK)
2832 return PQTRANS_UNKNOWN;
2833 if (conn->asyncStatus != PGASYNC_IDLE)
2834 return PQTRANS_ACTIVE;
2835 return conn->xactStatus;
2839 PQparameterStatus(const PGconn *conn, const char *paramName)
2841 const pgParameterStatus *pstatus;
2843 if (!conn || !paramName)
2845 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
2847 if (strcmp(pstatus->name, paramName) == 0)
2848 return pstatus->value;
2854 PQprotocolVersion(const PGconn *conn)
2858 if (conn->status == CONNECTION_BAD)
2860 return PG_PROTOCOL_MAJOR(conn->pversion);
2864 PQserverVersion(const PGconn *conn)
2868 if (conn->status == CONNECTION_BAD)
2870 return conn->sversion;
2874 PQerrorMessage(const PGconn *conn)
2877 return libpq_gettext("connection pointer is NULL\n");
2879 return conn->errorMessage.data;
2883 PQsocket(const PGconn *conn)
2891 PQbackendPID(const PGconn *conn)
2893 if (!conn || conn->status != CONNECTION_OK)
2895 return conn->be_pid;
2899 PQclientEncoding(const PGconn *conn)
2901 if (!conn || conn->status != CONNECTION_OK)
2903 return conn->client_encoding;
2907 PQsetClientEncoding(PGconn *conn, const char *encoding)
2910 static const char query[] = "set client_encoding to '%s'";
2914 if (!conn || conn->status != CONNECTION_OK)
2920 /* check query buffer overflow */
2921 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2924 /* ok, now send a query */
2925 sprintf(qbuf, query, encoding);
2926 res = PQexec(conn, qbuf);
2930 if (res->resultStatus != PGRES_COMMAND_OK)
2934 /* change libpq internal encoding */
2935 conn->client_encoding = pg_char_to_encoding(encoding);
2936 status = 0; /* everything is ok */
2943 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
2948 return PQERRORS_DEFAULT;
2949 old = conn->verbosity;
2950 conn->verbosity = verbosity;
2955 PQtrace(PGconn *conn, FILE *debug_port)
2960 conn->Pfdebug = debug_port;
2964 PQuntrace(PGconn *conn)
2970 fflush(conn->Pfdebug);
2971 conn->Pfdebug = NULL;
2976 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
2978 PQnoticeReceiver old;
2983 old = conn->noticeHooks.noticeRec;
2986 conn->noticeHooks.noticeRec = proc;
2987 conn->noticeHooks.noticeRecArg = arg;
2993 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2995 PQnoticeProcessor old;
3000 old = conn->noticeHooks.noticeProc;
3003 conn->noticeHooks.noticeProc = proc;
3004 conn->noticeHooks.noticeProcArg = arg;
3010 * The default notice message receiver just gets the standard notice text
3011 * and sends it to the notice processor. This two-level setup exists
3012 * mostly for backwards compatibility; perhaps we should deprecate use of
3013 * PQsetNoticeProcessor?
3016 defaultNoticeReceiver(void *arg, const PGresult *res)
3018 (void) arg; /* not used */
3019 if (res->noticeHooks.noticeProc != NULL)
3020 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3021 PQresultErrorMessage(res));
3025 * The default notice message processor just prints the
3026 * message on stderr. Applications can override this if they
3027 * want the messages to go elsewhere (a window, for example).
3028 * Note that simply discarding notices is probably a bad idea.
3031 defaultNoticeProcessor(void *arg, const char *message)
3033 (void) arg; /* not used */
3034 /* Note: we expect the supplied string to end with a newline already. */
3035 fprintf(stderr, "%s", message);
3039 * returns a pointer to the next token or NULL if the current
3040 * token doesn't match
3043 pwdfMatchesString(char *buf, char *token)
3047 bool bslash = false;
3049 if (buf == NULL || token == NULL)
3057 if (*tbuf == '\\' && !bslash)
3062 if (*tbuf == ':' && *ttok == 0 && !bslash)
3078 /* Get a password from the password file. Return value is malloc'd. */
3080 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3083 char pgpassfile[MAXPGPATH];
3084 struct stat stat_buf;
3087 #define LINELEN NAMEDATALEN*5
3090 if (dbname == NULL || strlen(dbname) == 0)
3093 if (username == NULL || strlen(username) == 0)
3096 if (hostname == NULL)
3097 hostname = DefaultHost;
3100 port = DEF_PGPORT_STR;
3102 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3103 /* use the literal path from the environment, if set */
3104 StrNCpy(pgpassfile, passfile_env, MAXPGPATH);
3107 char homedir[MAXPGPATH];
3109 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3111 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3114 /* If password file cannot be opened, ignore it. */
3115 if (stat(pgpassfile, &stat_buf) == -1)
3120 if (!S_ISREG(stat_buf.st_mode))
3123 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3129 /* If password file is insecure, alert the user and ignore it. */
3130 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3133 libpq_gettext("WARNING: password file \"%s\" has world or group read access; permission should be u=rw (0600)\n"),
3139 fp = fopen(pgpassfile, "r");
3149 fgets(buf, LINELEN - 1, fp);
3155 /* Remove trailing newline */
3156 if (buf[len - 1] == '\n')
3159 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3160 (t = pwdfMatchesString(t, port)) == NULL ||
3161 (t = pwdfMatchesString(t, dbname)) == NULL ||
3162 (t = pwdfMatchesString(t, username)) == NULL)
3176 * Obtain user's home directory, return in given buffer
3178 * On Unix, this actually returns the user's home directory. On Windows
3179 * it returns the PostgreSQL-specific application data folder.
3181 * This is essentially the same as get_home_path(), but we don't use that
3182 * because we don't want to pull path.c into libpq (it pollutes application
3186 pqGetHomeDirectory(char *buf, int bufsize)
3189 char pwdbuf[BUFSIZ];
3190 struct passwd pwdstr;
3191 struct passwd *pwd = NULL;
3193 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3195 StrNCpy(buf, pwd->pw_dir, bufsize);
3198 char tmppath[MAX_PATH];
3200 ZeroMemory(tmppath, sizeof(tmppath));
3201 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3203 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3209 * To keep the API consistent, the locking stubs are always provided, even
3210 * if they are not required.
3214 default_threadlock(int acquire)
3216 #ifdef ENABLE_THREAD_SAFETY
3218 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3220 static pthread_mutex_t singlethread_lock = NULL;
3221 static long mutex_initlock = 0;
3223 if (singlethread_lock == NULL)
3225 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3226 /* loop, another thread own the lock */ ;
3227 if (singlethread_lock == NULL)
3228 pthread_mutex_init(&singlethread_lock, NULL);
3229 InterlockedExchange(&mutex_initlock, 0);
3233 pthread_mutex_lock(&singlethread_lock);
3235 pthread_mutex_unlock(&singlethread_lock);
3240 PQregisterThreadLock(pgthreadlock_t newhandler)
3242 pgthreadlock_t prev = pg_g_threadlock;
3245 pg_g_threadlock = newhandler;
3247 pg_g_threadlock = default_threadlock;