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.312 2005/06/19 13:10:55 momjian 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
62 #include "mb/pg_wchar.h"
70 #define PGPASSFILE ".pgpass"
72 #define PGPASSFILE "pgpass.conf"
75 /* fall back options if they are not specified by arguments or defined
76 by environment variables */
77 #define DefaultHost "localhost"
79 #define DefaultOption ""
80 #define DefaultAuthtype ""
81 #define DefaultPassword ""
83 #define DefaultSSLMode "prefer"
85 #define DefaultSSLMode "disable"
89 * Definition of the conninfo parameters and their fallback resources.
91 * If Environment-Var and Compiled-in are specified as NULL, no
92 * fallback is available. If after all no value can be determined
93 * for an option, an error is returned.
95 * The value for the username is treated specially in conninfo_parse.
96 * If the Compiled-in resource is specified as a NULL value, the
97 * user is determined by fe_getauthname().
99 * The Label and Disp-Char entries are provided for applications that
100 * want to use PQconndefaults() to create a generic database connection
101 * dialog. Disp-Char is defined as follows:
102 * "" Normal input field
103 * "*" Password field - hide value
104 * "D" Debug option - don't show by default
106 * PQconninfoOptions[] is a constant static array that we use to initialize
107 * a dynamically allocated working copy. All the "val" fields in
108 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
109 * fields point to malloc'd strings that should be freed when the working
110 * array is freed (see PQconninfoFree).
113 static const PQconninfoOption PQconninfoOptions[] = {
115 * "authtype" is no longer used, so mark it "don't show". We keep it
116 * in the array so as not to reject conninfo strings from old apps
117 * that might still try to set it.
119 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
120 "Database-Authtype", "D", 20},
122 {"service", "PGSERVICE", NULL, NULL,
123 "Database-Service", "", 20},
125 {"user", "PGUSER", NULL, NULL,
126 "Database-User", "", 20},
128 {"password", "PGPASSWORD", NULL, NULL,
129 "Database-Password", "*", 20},
131 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
132 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
134 {"dbname", "PGDATABASE", NULL, NULL,
135 "Database-Name", "", 20},
137 {"host", "PGHOST", NULL, NULL,
138 "Database-Host", "", 40},
140 {"hostaddr", "PGHOSTADDR", NULL, NULL,
141 "Database-Host-IP-Address", "", 45},
143 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
144 "Database-Port", "", 6},
147 * "tty" is no longer used either, but keep it present for backwards
150 {"tty", "PGTTY", DefaultTty, NULL,
151 "Backend-Debug-TTY", "D", 40},
153 {"options", "PGOPTIONS", DefaultOption, NULL,
154 "Backend-Debug-Options", "D", 40},
159 * "requiressl" is deprecated, its purpose having been taken over by
160 * "sslmode". It remains for backwards compatibility.
162 {"requiressl", "PGREQUIRESSL", "0", NULL,
163 "Require-SSL", "D", 1},
167 * "sslmode" option is allowed even without client SSL support because
168 * the client can still handle SSL modes "disable" and "allow".
170 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
171 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
173 #if defined(KRB4) || defined(KRB5)
174 /* Kerberos authentication supports specifying the service name */
175 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
176 "Kerberos-service-name", "", 20},
179 /* Terminating entry --- MUST BE LAST */
180 {NULL, NULL, NULL, NULL,
184 static const PQEnvironmentOption EnvironmentOptions[] =
186 /* common user-interface settings */
188 "PGDATESTYLE", "datestyle"
194 "PGCLIENTENCODING", "client_encoding"
196 /* internal performance-related settings */
206 static bool connectOptions1(PGconn *conn, const char *conninfo);
207 static bool connectOptions2(PGconn *conn);
208 static int connectDBStart(PGconn *conn);
209 static int connectDBComplete(PGconn *conn);
210 static PGconn *makeEmptyPGconn(void);
211 static void freePGconn(PGconn *conn);
212 static void closePGconn(PGconn *conn);
213 static PQconninfoOption *conninfo_parse(const char *conninfo,
214 PQExpBuffer errorMessage);
215 static char *conninfo_getval(PQconninfoOption *connOptions,
216 const char *keyword);
217 static void defaultNoticeReceiver(void *arg, const PGresult *res);
218 static void defaultNoticeProcessor(void *arg, const char *message);
219 static int parseServiceInfo(PQconninfoOption *options,
220 PQExpBuffer errorMessage);
221 static char *pwdfMatchesString(char *buf, char *token);
222 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
224 static void default_threadlock(int acquire);
227 /* global variable because fe-auth.c needs to access it */
228 pgthreadlock_t pg_g_threadlock = default_threadlock;
232 * Connecting to a Database
234 * There are now four different ways a user of this API can connect to the
235 * database. Two are not recommended for use in new code, because of their
236 * lack of extensibility with respect to the passing of options to the
237 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
240 * If it is desired to connect in a synchronous (blocking) manner, use the
241 * function PQconnectdb.
243 * To connect in an asynchronous (non-blocking) manner, use the functions
244 * PQconnectStart, and PQconnectPoll.
246 * Internally, the static functions connectDBStart, connectDBComplete
247 * are part of the connection procedure.
253 * establishes a connection to a postgres backend through the postmaster
254 * using connection information in a string.
256 * The conninfo string is a white-separated list of
260 * definitions. Value might be a single value containing no whitespaces or
261 * a single quoted string. If a single quote should appear anywhere in
262 * the value, it must be escaped with a backslash like \'
264 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
265 * if a memory allocation failed.
266 * If the status field of the connection returned is CONNECTION_BAD,
267 * then some fields may be null'ed out instead of having valid values.
269 * You should call PQfinish (if conn is not NULL) regardless of whether this
273 PQconnectdb(const char *conninfo)
275 PGconn *conn = PQconnectStart(conninfo);
277 if (conn && conn->status != CONNECTION_BAD)
278 (void) connectDBComplete(conn);
286 * Begins the establishment of a connection to a postgres backend through the
287 * postmaster using connection information in a string.
289 * See comment for PQconnectdb for the definition of the string format.
291 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
292 * you should not attempt to proceed with this connection. If the status
293 * field of the connection returned is CONNECTION_BAD, an error has
294 * occurred. In this case you should call PQfinish on the result, (perhaps
295 * inspecting the error message first). Other fields of the structure may not
296 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
297 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
300 * See PQconnectPoll for more info.
303 PQconnectStart(const char *conninfo)
308 * Allocate memory for the conn structure
310 conn = makeEmptyPGconn();
315 * Parse the conninfo string
317 if (!connectOptions1(conn, conninfo))
321 * Compute derived options
323 if (!connectOptions2(conn))
327 * Connect to the database
329 if (!connectDBStart(conn))
331 /* Just in case we failed to set it in connectDBStart */
332 conn->status = CONNECTION_BAD;
341 * Internal subroutine to set up connection parameters given an already-
342 * created PGconn and a conninfo string. Derived settings should be
343 * processed by calling connectOptions2 next. (We split them because
344 * PQsetdbLogin overrides defaults in between.)
346 * Returns true if OK, false if trouble (in which case errorMessage is set
347 * and so is conn->status).
350 connectOptions1(PGconn *conn, const char *conninfo)
352 PQconninfoOption *connOptions;
356 * Parse the conninfo string
358 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
359 if (connOptions == NULL)
361 conn->status = CONNECTION_BAD;
362 /* errorMessage is already set */
367 * Move option values into conn structure
369 * Don't put anything cute here --- intelligence should be in
370 * connectOptions2 ...
372 * XXX: probably worth checking strdup() return value here...
374 tmp = conninfo_getval(connOptions, "hostaddr");
375 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
376 tmp = conninfo_getval(connOptions, "host");
377 conn->pghost = tmp ? strdup(tmp) : NULL;
378 tmp = conninfo_getval(connOptions, "port");
379 conn->pgport = tmp ? strdup(tmp) : NULL;
380 tmp = conninfo_getval(connOptions, "tty");
381 conn->pgtty = tmp ? strdup(tmp) : NULL;
382 tmp = conninfo_getval(connOptions, "options");
383 conn->pgoptions = tmp ? strdup(tmp) : NULL;
384 tmp = conninfo_getval(connOptions, "dbname");
385 conn->dbName = tmp ? strdup(tmp) : NULL;
386 tmp = conninfo_getval(connOptions, "user");
387 conn->pguser = tmp ? strdup(tmp) : NULL;
388 tmp = conninfo_getval(connOptions, "password");
389 conn->pgpass = tmp ? strdup(tmp) : NULL;
390 tmp = conninfo_getval(connOptions, "connect_timeout");
391 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
392 tmp = conninfo_getval(connOptions, "sslmode");
393 conn->sslmode = tmp ? strdup(tmp) : NULL;
395 tmp = conninfo_getval(connOptions, "requiressl");
396 if (tmp && tmp[0] == '1')
398 /* here warn that the requiressl option is deprecated? */
401 conn->sslmode = strdup("require");
404 #if defined(KRB4) || defined(KRB5)
405 tmp = conninfo_getval(connOptions, "krbsrvname");
406 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
410 * Free the option info - all is in conn now
412 PQconninfoFree(connOptions);
420 * Compute derived connection options after absorbing all user-supplied info.
422 * Returns true if OK, false if trouble (in which case errorMessage is set
423 * and so is conn->status).
426 connectOptions2(PGconn *conn)
429 * If database name was not given, default it to equal user name
431 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
432 && conn->pguser != NULL)
436 conn->dbName = strdup(conn->pguser);
440 * Supply default password if none given
442 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
446 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
447 conn->dbName, conn->pguser);
448 if (conn->pgpass == NULL)
449 conn->pgpass = strdup(DefaultPassword);
453 * Allow unix socket specification in the host name
455 if (conn->pghost && is_absolute_path(conn->pghost))
457 if (conn->pgunixsocket)
458 free(conn->pgunixsocket);
459 conn->pgunixsocket = conn->pghost;
464 * validate sslmode option
468 if (strcmp(conn->sslmode, "disable") != 0
469 && strcmp(conn->sslmode, "allow") != 0
470 && strcmp(conn->sslmode, "prefer") != 0
471 && strcmp(conn->sslmode, "require") != 0)
473 conn->status = CONNECTION_BAD;
474 printfPQExpBuffer(&conn->errorMessage,
475 libpq_gettext("invalid sslmode value: \"%s\"\n"),
481 switch (conn->sslmode[0])
483 case 'a': /* "allow" */
484 case 'p': /* "prefer" */
487 * warn user that an SSL connection will never be
488 * negotiated since SSL was not compiled in?
492 case 'r': /* "require" */
493 conn->status = CONNECTION_BAD;
494 printfPQExpBuffer(&conn->errorMessage,
495 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
502 conn->sslmode = strdup(DefaultSSLMode);
510 * Parse an empty string like PQconnectdb() would do and return the
511 * working connection options array.
513 * Using this function, an application may determine all possible options
514 * and their current default values.
516 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
517 * and should be freed when no longer needed via PQconninfoFree(). (In prior
518 * versions, the returned array was static, but that's not thread-safe.)
519 * Pre-7.0 applications that use this function will see a small memory leak
520 * until they are updated to call PQconninfoFree.
525 PQExpBufferData errorBuf;
526 PQconninfoOption *connOptions;
528 initPQExpBuffer(&errorBuf);
529 connOptions = conninfo_parse("", &errorBuf);
530 termPQExpBuffer(&errorBuf);
537 * establishes a connection to a postgres backend through the postmaster
538 * at the specified host and port.
540 * returns a PGconn* which is needed for all subsequent libpq calls
542 * if the status field of the connection returned is CONNECTION_BAD,
543 * then only the errorMessage is likely to be useful.
547 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
548 const char *pgtty, const char *dbName, const char *login,
554 * Allocate memory for the conn structure
556 conn = makeEmptyPGconn();
561 * Parse an empty conninfo string in order to set up the same defaults
562 * that PQconnectdb() would use.
564 if (!connectOptions1(conn, ""))
568 * Absorb specified options into conn structure, overriding defaults
570 if (pghost && pghost[0] != '\0')
574 conn->pghost = strdup(pghost);
577 if (pgport && pgport[0] != '\0')
581 conn->pgport = strdup(pgport);
584 if (pgoptions && pgoptions[0] != '\0')
587 free(conn->pgoptions);
588 conn->pgoptions = strdup(pgoptions);
591 if (pgtty && pgtty[0] != '\0')
595 conn->pgtty = strdup(pgtty);
598 if (dbName && dbName[0] != '\0')
602 conn->dbName = strdup(dbName);
605 if (login && login[0] != '\0')
609 conn->pguser = strdup(login);
612 if (pwd && pwd[0] != '\0')
616 conn->pgpass = strdup(pwd);
620 * Compute derived options
622 if (!connectOptions2(conn))
626 * Connect to the database
628 if (connectDBStart(conn))
629 (void) connectDBComplete(conn);
637 * Sets the TCP_NODELAY socket option.
638 * Returns 1 if successful, 0 if not.
642 connectNoDelay(PGconn *conn)
647 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
653 printfPQExpBuffer(&conn->errorMessage,
654 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
655 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
665 * connectFailureMessage -
666 * create a friendly error message on connection failure.
670 connectFailureMessage(PGconn *conn, int errorno)
674 #ifdef HAVE_UNIX_SOCKETS
675 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
677 char service[NI_MAXHOST];
679 getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
681 service, sizeof(service),
683 printfPQExpBuffer(&conn->errorMessage,
685 "could not connect to server: %s\n"
686 "\tIs the server running locally and accepting\n"
687 "\tconnections on Unix domain socket \"%s\"?\n"
689 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
693 #endif /* HAVE_UNIX_SOCKETS */
695 printfPQExpBuffer(&conn->errorMessage,
697 "could not connect to server: %s\n"
698 "\tIs the server running on host \"%s\" and accepting\n"
699 "\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 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 getaddrinfo_all() to resolve the address */
780 ret = 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 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
815 * PQconnectPoll(), so that it can easily be re-executed if needed
816 * again during the asynchronous startup process. However, we must
817 * run it once here, because callers expect a success return from this
818 * routine to mean that we are in PGRES_POLLING_WRITING connection
821 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
827 pqsecure_close(conn);
828 closesocket(conn->sock);
831 conn->status = CONNECTION_BAD;
839 * Block and complete a connection.
841 * Returns 1 on success, 0 on failure.
844 connectDBComplete(PGconn *conn)
846 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
847 time_t finish_time = ((time_t) -1);
849 if (conn == NULL || conn->status == CONNECTION_BAD)
853 * Set up a time limit, if connect_timeout isn't zero.
855 if (conn->connect_timeout != NULL)
857 int timeout = atoi(conn->connect_timeout);
862 * Rounding could cause connection to fail; need at least 2
867 /* calculate the finish time based on start + timeout */
868 finish_time = time(NULL) + timeout;
875 * Wait, if necessary. Note that the initial state (just after
876 * PQconnectStart) is to wait for the socket to select for
881 case PGRES_POLLING_OK:
882 return 1; /* success! */
884 case PGRES_POLLING_READING:
885 if (pqWaitTimed(1, 0, conn, finish_time))
887 conn->status = CONNECTION_BAD;
892 case PGRES_POLLING_WRITING:
893 if (pqWaitTimed(0, 1, conn, finish_time))
895 conn->status = CONNECTION_BAD;
901 /* Just in case we failed to set it in PQconnectPoll */
902 conn->status = CONNECTION_BAD;
907 * Now try to advance the state machine.
909 flag = PQconnectPoll(conn);
916 * Poll an asynchronous connection.
918 * Returns a PostgresPollingStatusType.
919 * Before calling this function, use select(2) to determine when data
922 * You must call PQfinish whether or not this fails.
924 * This function and PQconnectStart are intended to allow connections to be
925 * made without blocking the execution of your program on remote I/O. However,
926 * there are a number of caveats:
928 * o If you call PQtrace, ensure that the stream object into which you trace
930 * o If you do not supply an IP address for the remote host (i.e. you
931 * supply a host name instead) then PQconnectStart will block on
932 * gethostbyname. You will be fine if using Unix sockets (i.e. by
933 * supplying neither a host name nor a host address).
934 * o If your backend wants to use Kerberos authentication then you must
935 * supply both a host name and a host address, otherwise this function
936 * may block on gethostname.
940 PostgresPollingStatusType
941 PQconnectPoll(PGconn *conn)
947 return PGRES_POLLING_FAILED;
949 /* Get the new data */
950 switch (conn->status)
953 * We really shouldn't have been polled in these two cases,
954 * but we can handle it.
957 return PGRES_POLLING_FAILED;
959 return PGRES_POLLING_OK;
961 /* These are reading states */
962 case CONNECTION_AWAITING_RESPONSE:
963 case CONNECTION_AUTH_OK:
965 /* Load waiting data */
966 int n = pqReadData(conn);
971 return PGRES_POLLING_READING;
976 /* These are writing states, so we just proceed. */
977 case CONNECTION_STARTED:
978 case CONNECTION_MADE:
981 /* We allow pqSetenvPoll to decide whether to proceed. */
982 case CONNECTION_SETENV:
985 /* Special cases: proceed without waiting. */
986 case CONNECTION_SSL_STARTUP:
987 case CONNECTION_NEEDED:
991 printfPQExpBuffer(&conn->errorMessage,
993 "invalid connection state, "
994 "probably indicative of memory corruption\n"
1000 keep_going: /* We will come back to here until there
1001 * is nothing left to do. */
1002 switch (conn->status)
1004 case CONNECTION_NEEDED:
1007 * Try to initiate a connection to one of the addresses
1008 * returned by getaddrinfo_all(). conn->addr_cur is the
1009 * next one to try. We fail when we run out of addresses
1010 * (reporting the error returned for the *last*
1011 * alternative, which may not be what users expect :-().
1013 while (conn->addr_cur != NULL)
1015 struct addrinfo *addr_cur = conn->addr_cur;
1017 /* Remember current address for possible error msg */
1018 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1019 addr_cur->ai_addrlen);
1020 conn->raddr.salen = addr_cur->ai_addrlen;
1023 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1027 * ignore socket() failure if we have more
1030 if (addr_cur->ai_next != NULL)
1032 conn->addr_cur = addr_cur->ai_next;
1035 printfPQExpBuffer(&conn->errorMessage,
1036 libpq_gettext("could not create socket: %s\n"),
1037 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1042 * Select socket options: no delay of outgoing data
1043 * for TCP sockets, nonblock mode, close-on-exec.
1044 * Fail if any of this fails.
1046 if (!IS_AF_UNIX(addr_cur->ai_family))
1048 if (!connectNoDelay(conn))
1050 closesocket(conn->sock);
1052 conn->addr_cur = addr_cur->ai_next;
1056 if (!pg_set_noblock(conn->sock))
1058 printfPQExpBuffer(&conn->errorMessage,
1059 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1060 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1061 closesocket(conn->sock);
1063 conn->addr_cur = addr_cur->ai_next;
1068 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1070 printfPQExpBuffer(&conn->errorMessage,
1071 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1072 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1073 closesocket(conn->sock);
1075 conn->addr_cur = addr_cur->ai_next;
1078 #endif /* F_SETFD */
1081 * Start/make connection. This should not block,
1082 * since we are in nonblock mode. If it does, well,
1086 if (connect(conn->sock, addr_cur->ai_addr,
1087 addr_cur->ai_addrlen) < 0)
1089 if (SOCK_ERRNO == EINTR)
1090 /* Interrupted system call - just try again */
1092 if (SOCK_ERRNO == EINPROGRESS ||
1093 SOCK_ERRNO == EWOULDBLOCK ||
1097 * This is fine - we're in non-blocking mode,
1098 * and the connection is in progress. Tell
1099 * caller to wait for write-ready on socket.
1101 conn->status = CONNECTION_STARTED;
1102 return PGRES_POLLING_WRITING;
1104 /* otherwise, trouble */
1109 * Hm, we're connected already --- seems the
1110 * "nonblock connection" wasn't. Advance the
1111 * state machine and go do the next stuff.
1113 conn->status = CONNECTION_STARTED;
1118 * This connection failed --- set up error report,
1119 * then close socket (do it this way in case close()
1120 * affects the value of errno...). We will ignore the
1121 * connect() failure and keep going if there are more
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
1139 * is 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
1151 * connection 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
1171 * see connect failures at this point, so provide a
1172 * friendly error message.
1174 connectFailureMessage(conn, optval);
1177 * If more addresses remain, keep trying, just as in
1178 * the case where connect() returned failure
1181 if (conn->addr_cur->ai_next != NULL)
1183 if (conn->sock >= 0)
1185 closesocket(conn->sock);
1188 conn->addr_cur = conn->addr_cur->ai_next;
1189 conn->status = CONNECTION_NEEDED;
1195 /* Fill in the client address */
1196 conn->laddr.salen = sizeof(conn->laddr.addr);
1197 if (getsockname(conn->sock,
1198 (struct sockaddr *) & conn->laddr.addr,
1199 &conn->laddr.salen) < 0)
1201 printfPQExpBuffer(&conn->errorMessage,
1202 libpq_gettext("could not get client address from socket: %s\n"),
1203 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1208 * Make sure we can write before advancing to next step.
1210 conn->status = CONNECTION_MADE;
1211 return PGRES_POLLING_WRITING;
1214 case CONNECTION_MADE:
1222 * If SSL is enabled and we haven't already got it
1223 * running, request it instead of sending the startup
1226 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1228 /* Don't bother requesting SSL over a Unix socket */
1229 conn->allow_ssl_try = false;
1231 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1237 * Send the SSL request packet.
1239 * Theoretically, this could block, but it really
1240 * shouldn't since we only got here if the socket is
1243 pv = htonl(NEGOTIATE_SSL_CODE);
1244 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1246 printfPQExpBuffer(&conn->errorMessage,
1247 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1248 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1251 /* Ok, wait for response */
1252 conn->status = CONNECTION_SSL_STARTUP;
1253 return PGRES_POLLING_READING;
1255 #endif /* USE_SSL */
1258 * Build the startup packet.
1260 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1261 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1262 EnvironmentOptions);
1264 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1265 EnvironmentOptions);
1268 printfPQExpBuffer(&conn->errorMessage,
1269 libpq_gettext("out of memory\n"));
1274 * Send the startup packet.
1276 * Theoretically, this could block, but it really shouldn't
1277 * since we only got here if the socket is write-ready.
1279 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1281 printfPQExpBuffer(&conn->errorMessage,
1282 libpq_gettext("could not send startup packet: %s\n"),
1283 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1290 conn->status = CONNECTION_AWAITING_RESPONSE;
1291 return PGRES_POLLING_READING;
1295 * Handle SSL negotiation: wait for postmaster messages and
1296 * respond as necessary.
1298 case CONNECTION_SSL_STARTUP:
1301 PostgresPollingStatusType pollres;
1304 * On first time through, get the postmaster's response to
1305 * our SSL negotiation packet.
1307 if (conn->ssl == NULL)
1310 * We use pqReadData here since it has the logic to
1311 * distinguish no-data-yet from connection closure.
1312 * Since conn->ssl isn't set, a plain recv() will occur.
1317 rdresult = pqReadData(conn);
1320 /* errorMessage is already filled in */
1325 /* caller failed to wait for data */
1326 return PGRES_POLLING_READING;
1328 if (pqGetc(&SSLok, conn) < 0)
1330 /* should not happen really */
1331 return PGRES_POLLING_READING;
1333 /* mark byte consumed */
1334 conn->inStart = conn->inCursor;
1337 /* Do one-time setup; this creates conn->ssl */
1338 if (pqsecure_initialize(conn) == -1)
1341 else if (SSLok == 'N')
1343 if (conn->sslmode[0] == 'r') /* "require" */
1345 /* Require SSL, but server does not want it */
1346 printfPQExpBuffer(&conn->errorMessage,
1347 libpq_gettext("server does not support SSL, but SSL was required\n"));
1350 /* Otherwise, proceed with normal startup */
1351 conn->allow_ssl_try = false;
1352 conn->status = CONNECTION_MADE;
1353 return PGRES_POLLING_WRITING;
1355 else if (SSLok == 'E')
1357 /* Received error - probably protocol mismatch */
1359 fprintf(conn->Pfdebug, libpq_gettext("Postmaster reports error, attempting fallback to pre-7.0.\n"));
1360 if (conn->sslmode[0] == 'r') /* "require" */
1362 /* Require SSL, but server is too old */
1363 printfPQExpBuffer(&conn->errorMessage,
1364 libpq_gettext("server does not support SSL, but SSL was required\n"));
1367 /* Otherwise, try again without SSL */
1368 conn->allow_ssl_try = false;
1369 /* Assume it ain't gonna handle protocol 3, either */
1370 conn->pversion = PG_PROTOCOL(2, 0);
1371 /* Must drop the old connection */
1372 closesocket(conn->sock);
1374 conn->status = CONNECTION_NEEDED;
1379 printfPQExpBuffer(&conn->errorMessage,
1380 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1387 * Begin or continue the SSL negotiation process.
1389 pollres = pqsecure_open_client(conn);
1390 if (pollres == PGRES_POLLING_OK)
1392 /* SSL handshake done, ready to send startup packet */
1393 conn->status = CONNECTION_MADE;
1394 return PGRES_POLLING_WRITING;
1397 #else /* !USE_SSL */
1398 /* can't get here */
1400 #endif /* USE_SSL */
1404 * Handle authentication exchange: wait for postmaster
1405 * messages and respond as necessary.
1407 case CONNECTION_AWAITING_RESPONSE:
1415 * Scan the message from current point (note that if we
1416 * find the message is incomplete, we will return without
1417 * advancing inStart, and resume here next time).
1419 conn->inCursor = conn->inStart;
1421 /* Read type byte */
1422 if (pqGetc(&beresp, conn))
1424 /* We'll come back when there is more data */
1425 return PGRES_POLLING_READING;
1429 * Validate message type: we expect only an authentication
1430 * request or an error here. Anything else probably means
1431 * it's not Postgres on the other end at all.
1433 if (!(beresp == 'R' || beresp == 'E'))
1435 printfPQExpBuffer(&conn->errorMessage,
1437 "expected authentication request from "
1438 "server, but received %c\n"),
1443 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1445 /* Read message length word */
1446 if (pqGetInt(&msgLength, 4, conn))
1448 /* We'll come back when there is more data */
1449 return PGRES_POLLING_READING;
1454 /* Set phony message length to disable checks below */
1459 * Try to validate message length before using it.
1460 * Authentication requests can't be very large. Errors
1461 * can be a little larger, but not huge. If we see a
1462 * large apparent length in an error, it means we're
1463 * really talking to a pre-3.0-protocol server; cope.
1465 if (beresp == 'R' && (msgLength < 8 || msgLength > 100))
1467 printfPQExpBuffer(&conn->errorMessage,
1469 "expected authentication request from "
1470 "server, but received %c\n"),
1475 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1477 /* Handle error from a pre-3.0 server */
1478 conn->inCursor = conn->inStart + 1; /* reread data */
1479 if (pqGets(&conn->errorMessage, conn))
1481 /* We'll come back when there is more data */
1482 return PGRES_POLLING_READING;
1484 /* OK, we read the message; mark data consumed */
1485 conn->inStart = conn->inCursor;
1488 * The postmaster typically won't end its message with
1489 * a newline, so add one to conform to libpq
1492 appendPQExpBufferChar(&conn->errorMessage, '\n');
1495 * If we tried to open the connection in 3.0 protocol,
1496 * fall back to 2.0 protocol.
1498 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1500 conn->pversion = PG_PROTOCOL(2, 0);
1501 /* Must drop the old connection */
1502 pqsecure_close(conn);
1503 closesocket(conn->sock);
1505 conn->status = CONNECTION_NEEDED;
1513 * Can't process if message body isn't all here yet.
1515 * (In protocol 2.0 case, we are assuming messages carry at
1516 * least 4 bytes of data.)
1519 avail = conn->inEnd - conn->inCursor;
1520 if (avail < msgLength)
1523 * Before returning, try to enlarge the input buffer
1524 * if needed to hold the whole message; see notes in
1527 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1529 /* We'll come back when there is more data */
1530 return PGRES_POLLING_READING;
1533 /* Handle errors. */
1536 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1538 if (pqGetErrorNotice3(conn, true))
1540 /* We'll come back when there is more data */
1541 return PGRES_POLLING_READING;
1546 if (pqGets(&conn->errorMessage, conn))
1548 /* We'll come back when there is more data */
1549 return PGRES_POLLING_READING;
1552 /* OK, we read the message; mark data consumed */
1553 conn->inStart = conn->inCursor;
1558 * if sslmode is "allow" and we haven't tried an SSL
1559 * connection already, then retry with an SSL
1562 if (conn->sslmode[0] == 'a' /* "allow" */
1563 && conn->ssl == NULL
1564 && conn->allow_ssl_try
1565 && conn->wait_ssl_try)
1567 /* only retry once */
1568 conn->wait_ssl_try = false;
1569 /* Must drop the old connection */
1570 closesocket(conn->sock);
1572 conn->status = CONNECTION_NEEDED;
1577 * if sslmode is "prefer" and we're in an SSL
1578 * connection, then do a non-SSL retry
1580 if (conn->sslmode[0] == 'p' /* "prefer" */
1582 && conn->allow_ssl_try /* redundant? */
1583 && !conn->wait_ssl_try) /* redundant? */
1585 /* only retry once */
1586 conn->allow_ssl_try = false;
1587 /* Must drop the old connection */
1588 pqsecure_close(conn);
1589 closesocket(conn->sock);
1591 conn->status = CONNECTION_NEEDED;
1599 /* It is an authentication request. */
1600 /* Get the type of request. */
1601 if (pqGetInt((int *) &areq, 4, conn))
1603 /* We'll come back when there are more data */
1604 return PGRES_POLLING_READING;
1607 /* Get the password salt if there is one. */
1608 if (areq == AUTH_REQ_MD5)
1610 if (pqGetnchar(conn->md5Salt,
1611 sizeof(conn->md5Salt), conn))
1613 /* We'll come back when there are more data */
1614 return PGRES_POLLING_READING;
1617 if (areq == AUTH_REQ_CRYPT)
1619 if (pqGetnchar(conn->cryptSalt,
1620 sizeof(conn->cryptSalt), conn))
1622 /* We'll come back when there are more data */
1623 return PGRES_POLLING_READING;
1628 * OK, we successfully read the message; mark data
1631 conn->inStart = conn->inCursor;
1633 /* Respond to the request if necessary. */
1636 * Note that conn->pghost must be non-NULL if we are going
1637 * to avoid the Kerberos code doing a hostname look-up.
1641 * XXX fe-auth.c has not been fixed to support
1644 if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1645 conn->errorMessage.data) != STATUS_OK)
1647 conn->errorMessage.len = strlen(conn->errorMessage.data);
1650 conn->errorMessage.len = strlen(conn->errorMessage.data);
1653 * Just make sure that any data sent by fe_sendauth is
1654 * flushed out. Although this theoretically could block,
1655 * it really shouldn't since we don't send large auth
1661 if (areq == AUTH_REQ_OK)
1663 /* We are done with authentication exchange */
1664 conn->status = CONNECTION_AUTH_OK;
1667 * Set asyncStatus so that PQsetResult will think that
1668 * what comes back next is the result of a query. See
1671 conn->asyncStatus = PGASYNC_BUSY;
1674 /* Look to see if we have more data yet. */
1678 case CONNECTION_AUTH_OK:
1681 * Now we expect to hear from the backend. A ReadyForQuery
1682 * message indicates that startup is successful, but we
1683 * might also get an Error message indicating failure.
1684 * (Notice messages indicating nonfatal warnings are also
1685 * allowed by the protocol, as are ParameterStatus and
1686 * BackendKeyData messages.) Easiest way to handle this is
1687 * to let PQgetResult() read the messages. We just have to
1688 * fake it out about the state of the connection, by
1689 * setting asyncStatus = PGASYNC_BUSY (done above).
1693 return PGRES_POLLING_READING;
1695 res = PQgetResult(conn);
1698 * NULL return indicating we have gone to IDLE state is
1703 if (res->resultStatus != PGRES_FATAL_ERROR)
1704 printfPQExpBuffer(&conn->errorMessage,
1705 libpq_gettext("unexpected message from server during startup\n"));
1708 * if the resultStatus is FATAL, then
1709 * conn->errorMessage already has a copy of the error;
1710 * needn't copy it back. But add a newline if it's not
1711 * there already, since postmaster error messages may
1714 if (conn->errorMessage.len <= 0 ||
1715 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1716 appendPQExpBufferChar(&conn->errorMessage, '\n');
1721 /* We can release the address list now. */
1722 freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1723 conn->addrlist = NULL;
1724 conn->addr_cur = NULL;
1726 /* Fire up post-connection housekeeping if needed */
1727 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1729 conn->status = CONNECTION_SETENV;
1730 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1731 conn->next_eo = EnvironmentOptions;
1732 return PGRES_POLLING_WRITING;
1735 /* Otherwise, we are open for business! */
1736 conn->status = CONNECTION_OK;
1737 return PGRES_POLLING_OK;
1740 case CONNECTION_SETENV:
1743 * Do post-connection housekeeping (only needed in protocol
1746 * We pretend that the connection is OK for the duration of these
1749 conn->status = CONNECTION_OK;
1751 switch (pqSetenvPoll(conn))
1753 case PGRES_POLLING_OK: /* Success */
1756 case PGRES_POLLING_READING: /* Still going */
1757 conn->status = CONNECTION_SETENV;
1758 return PGRES_POLLING_READING;
1760 case PGRES_POLLING_WRITING: /* Still going */
1761 conn->status = CONNECTION_SETENV;
1762 return PGRES_POLLING_WRITING;
1768 /* We are open for business! */
1769 conn->status = CONNECTION_OK;
1770 return PGRES_POLLING_OK;
1773 printfPQExpBuffer(&conn->errorMessage,
1775 "invalid connection state %c, "
1776 "probably indicative of memory corruption\n"
1787 * We used to close the socket at this point, but that makes it
1788 * awkward for those above us if they wish to remove this socket from
1789 * their own records (an fd_set for example). We'll just have this
1790 * socket closed when PQfinish is called (which is compulsory even
1791 * after an error, since the connection structure must be freed).
1793 conn->status = CONNECTION_BAD;
1794 return PGRES_POLLING_FAILED;
1800 * - create a PGconn data structure with (as yet) no interesting data
1803 makeEmptyPGconn(void)
1809 * Make sure socket support is up and running.
1810 * Even though this is done in libpqdll.c, that is only for MSVC and
1811 * BCC builds and doesn't work for static builds at all, so we have
1812 * to do it in the main code too.
1816 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1821 conn = (PGconn *) malloc(sizeof(PGconn));
1825 /* Zero all pointers and booleans */
1826 MemSet(conn, 0, sizeof(PGconn));
1828 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1829 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1830 conn->status = CONNECTION_BAD;
1831 conn->asyncStatus = PGASYNC_IDLE;
1832 conn->xactStatus = PQTRANS_IDLE;
1833 conn->setenv_state = SETENV_STATE_IDLE;
1834 conn->client_encoding = PG_SQL_ASCII;
1835 conn->verbosity = PQERRORS_DEFAULT;
1838 conn->allow_ssl_try = true;
1839 conn->wait_ssl_try = false;
1843 * We try to send at least 8K at a time, which is the usual size of
1844 * pipe buffers on Unix systems. That way, when we are sending a
1845 * large amount of data, we avoid incurring extra kernel context swaps
1846 * for partial bufferloads. The output buffer is initially made 16K
1847 * in size, and we try to dump it after accumulating 8K.
1849 * With the same goal of minimizing context swaps, the input buffer will
1850 * be enlarged anytime it has less than 8K free, so we initially
1851 * allocate twice that.
1853 conn->inBufSize = 16 * 1024;
1854 conn->inBuffer = (char *) malloc(conn->inBufSize);
1855 conn->outBufSize = 16 * 1024;
1856 conn->outBuffer = (char *) malloc(conn->outBufSize);
1857 conn->nonblocking = FALSE;
1858 initPQExpBuffer(&conn->errorMessage);
1859 initPQExpBuffer(&conn->workBuffer);
1861 if (conn->inBuffer == NULL ||
1862 conn->outBuffer == NULL ||
1863 conn->errorMessage.data == NULL ||
1864 conn->workBuffer.data == NULL)
1866 /* out of memory already :-( */
1876 * - free the PGconn data structure
1879 freePGconn(PGconn *conn)
1882 pgParameterStatus *pstatus;
1891 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1892 if (conn->sock >= 0)
1894 pqsecure_close(conn);
1895 closesocket(conn->sock);
1899 if (conn->pghostaddr)
1900 free(conn->pghostaddr);
1903 if (conn->pgunixsocket)
1904 free(conn->pgunixsocket);
1907 if (conn->connect_timeout)
1908 free(conn->connect_timeout);
1909 if (conn->pgoptions)
1910 free(conn->pgoptions);
1918 free(conn->sslmode);
1919 #if defined(KRB4) || defined(KRB5)
1920 if (conn->krbsrvname)
1921 free(conn->krbsrvname);
1923 /* Note that conn->Pfdebug is not ours to close or free */
1924 notify = conn->notifyHead;
1925 while (notify != NULL)
1927 PGnotify *prev = notify;
1929 notify = notify->next;
1932 freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1933 pstatus = conn->pstatus;
1934 while (pstatus != NULL)
1936 pgParameterStatus *prev = pstatus;
1938 pstatus = pstatus->next;
1941 if (conn->lobjfuncs)
1942 free(conn->lobjfuncs);
1944 free(conn->inBuffer);
1945 if (conn->outBuffer)
1946 free(conn->outBuffer);
1947 termPQExpBuffer(&conn->errorMessage);
1948 termPQExpBuffer(&conn->workBuffer);
1954 * - properly close a connection to the backend
1957 closePGconn(PGconn *conn)
1960 * Note that the protocol doesn't allow us to send Terminate messages
1961 * during the startup phase.
1963 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1966 * Try to send "close connection" message to backend. Ignore any
1969 pqPutMsgStart('X', false, conn);
1975 * must reset the blocking status so a possible reconnect will work
1976 * don't call PQsetnonblocking() because it will fail if it's unable
1977 * to flush the connection.
1979 conn->nonblocking = FALSE;
1982 * Close the connection, reset all transient state, flush I/O buffers.
1984 if (conn->sock >= 0)
1986 pqsecure_close(conn);
1987 closesocket(conn->sock);
1990 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
1992 conn->asyncStatus = PGASYNC_IDLE;
1993 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1994 if (conn->lobjfuncs)
1995 free(conn->lobjfuncs);
1996 conn->lobjfuncs = NULL;
1997 conn->inStart = conn->inCursor = conn->inEnd = 0;
2002 * PQfinish: properly close a connection to the backend. Also frees
2003 * the PGconn data structure so it shouldn't be re-used after this.
2006 PQfinish(PGconn *conn)
2016 * PQreset: resets the connection to the backend by closing the
2017 * existing connection and creating a new one.
2020 PQreset(PGconn *conn)
2026 if (connectDBStart(conn))
2027 (void) connectDBComplete(conn);
2034 * resets the connection to the backend
2035 * closes the existing connection and makes a new one
2036 * Returns 1 on success, 0 on failure.
2039 PQresetStart(PGconn *conn)
2045 return connectDBStart(conn);
2054 * resets the connection to the backend
2055 * closes the existing connection and makes a new one
2057 PostgresPollingStatusType
2058 PQresetPoll(PGconn *conn)
2061 return PQconnectPoll(conn);
2063 return PGRES_POLLING_FAILED;
2067 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2069 * A copy is needed to be able to cancel a running query from a different
2070 * thread. If the same structure is used all structure members would have
2071 * to be individually locked (if the entire structure was locked, it would
2072 * be impossible to cancel a synchronous query becuase the structure would
2073 * have to stay locked for the duration of the query).
2076 PQgetCancel(PGconn *conn)
2086 cancel = malloc(sizeof(PGcancel));
2090 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2091 cancel->be_pid = conn->be_pid;
2092 cancel->be_key = conn->be_key;
2097 /* PQfreeCancel: free a cancel structure */
2099 PQfreeCancel(PGcancel *cancel)
2107 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2108 * current operation.
2110 * The return value is TRUE if the cancel request was successfully
2111 * dispatched, FALSE if not (in which case an error message is available).
2112 * Note: successful dispatch is no guarantee that there will be any effect at
2113 * the backend. The application must read the operation result as usual.
2115 * CAUTION: we want this routine to be safely callable from a signal handler
2116 * (for example, an application might want to call it in a SIGINT handler).
2117 * This means we cannot use any C library routine that might be non-reentrant.
2118 * malloc/free are often non-reentrant, and anything that might call them is
2119 * just as dangerous. We avoid sprintf here for that reason. Building up
2120 * error messages with strcpy/strcat is tedious but should be quite safe.
2121 * We also save/restore errno in case the signal handler support doesn't.
2123 * internal_cancel() is an internal helper function to make code-sharing
2124 * between the two versions of the cancel function possible.
2127 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2128 char *errbuf, int errbufsize)
2130 int save_errno = SOCK_ERRNO;
2137 CancelRequestPacket cp;
2141 * We need to open a temporary connection to the postmaster. Do
2142 * this with only kernel calls.
2144 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2146 StrNCpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2147 goto cancel_errReturn;
2150 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2153 if (SOCK_ERRNO == EINTR)
2154 /* Interrupted system call - we'll just try again */
2156 StrNCpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2157 goto cancel_errReturn;
2161 * We needn't set nonblocking I/O or NODELAY options here.
2164 /* Create and send the cancel request packet. */
2166 crp.packetlen = htonl((uint32) sizeof(crp));
2167 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2168 crp.cp.backendPID = htonl(be_pid);
2169 crp.cp.cancelAuthCode = htonl(be_key);
2172 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2174 if (SOCK_ERRNO == EINTR)
2175 /* Interrupted system call - we'll just try again */
2177 StrNCpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2178 goto cancel_errReturn;
2182 * Wait for the postmaster to close the connection, which indicates
2183 * that it's processed the request. Without this delay, we might
2184 * issue another command only to find that our cancel zaps that
2185 * command instead of the one we thought we were canceling. Note we
2186 * don't actually expect this read to obtain any data, we are just
2187 * waiting for EOF to be signaled.
2190 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2192 if (SOCK_ERRNO == EINTR)
2193 /* Interrupted system call - we'll just try again */
2195 /* we ignore other error conditions */
2199 closesocket(tmpsock);
2200 SOCK_ERRNO_SET(save_errno);
2205 * Make sure we don't overflow the error buffer. Leave space for
2206 * the \n at the end, and for the terminating zero.
2208 maxlen = errbufsize - strlen(errbuf) - 2;
2211 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2213 strcat(errbuf, "\n");
2216 closesocket(tmpsock);
2217 SOCK_ERRNO_SET(save_errno);
2222 * PQcancel: request query cancel
2224 * Returns TRUE if able to send the cancel request, FALSE if not.
2226 * On failure, an error message is stored in *errbuf, which must be of size
2227 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2231 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2235 StrNCpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2239 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2240 errbuf, errbufsize);
2244 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2246 * Returns TRUE if able to send the cancel request, FALSE if not.
2248 * On failure, the error message is saved in conn->errorMessage; this means
2249 * that this can't be used when there might be other active operations on
2250 * the connection object.
2252 * NOTE: error messages will be cut off at the current size of the
2253 * error message buffer, since we dare not try to expand conn->errorMessage!
2256 PQrequestCancel(PGconn *conn)
2260 /* Check we have an open connection */
2266 StrNCpy(conn->errorMessage.data,
2267 "PQrequestCancel() -- connection is not open\n",
2268 conn->errorMessage.maxlen);
2269 conn->errorMessage.len = strlen(conn->errorMessage.data);
2274 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2275 conn->errorMessage.data, conn->errorMessage.maxlen);
2278 conn->errorMessage.len = strlen(conn->errorMessage.data);
2285 * pqPacketSend() -- convenience routine to send a message to server.
2287 * pack_type: the single-byte message type code. (Pass zero for startup
2288 * packets, which have no message type code.)
2290 * buf, buf_len: contents of message. The given length includes only what
2291 * is in buf; the message type and message length fields are added here.
2293 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2294 * SIDE_EFFECTS: may block.
2296 * Note: all messages sent with this routine have a length word, whether
2297 * it's protocol 2.0 or 3.0.
2300 pqPacketSend(PGconn *conn, char pack_type,
2301 const void *buf, size_t buf_len)
2303 /* Start the message. */
2304 if (pqPutMsgStart(pack_type, true, conn))
2305 return STATUS_ERROR;
2307 /* Send the message body. */
2308 if (pqPutnchar(buf, buf_len, conn))
2309 return STATUS_ERROR;
2311 /* Finish the message. */
2312 if (pqPutMsgEnd(conn))
2313 return STATUS_ERROR;
2315 /* Flush to ensure backend gets it. */
2317 return STATUS_ERROR;
2324 #define MAXBUFSIZE 256
2327 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2329 char *service = conninfo_getval(options, "service");
2330 char serviceFile[MAXPGPATH];
2331 bool group_found = false;
2336 * We have to special-case the environment variable PGSERVICE here,
2337 * since this is and should be called before inserting environment
2338 * defaults for other connection options.
2340 if (service == NULL)
2341 service = getenv("PGSERVICE");
2344 * This could be used by any application so we can't use the binary
2345 * location to find our config files.
2347 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2348 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2350 if (service != NULL)
2353 char buf[MAXBUFSIZE],
2356 f = fopen(serviceFile, "r");
2359 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: Service file '%s' not found\n"),
2364 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2368 if (strlen(line) >= MAXBUFSIZE - 2)
2371 printfPQExpBuffer(errorMessage,
2372 libpq_gettext("ERROR: line %d too long in service file '%s'\n"),
2378 /* ignore EOL at end of line */
2379 if (strlen(line) && line[strlen(line) - 1] == '\n')
2380 line[strlen(line) - 1] = 0;
2382 /* ignore leading blanks */
2383 while (*line && isspace((unsigned char) line[0]))
2386 /* ignore comments and empty lines */
2387 if (strlen(line) == 0 || line[0] == '#')
2390 /* Check for right groupname */
2395 /* group info already read */
2400 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2401 line[strlen(service) + 1] == ']')
2404 group_found = false;
2411 * Finally, we are in the right group and can parse
2419 val = strchr(line, '=');
2422 printfPQExpBuffer(errorMessage,
2423 libpq_gettext("ERROR: syntax error in service file '%s', line %d\n"),
2432 * Set the parameter --- but don't override any
2433 * previous explicit setting.
2435 found_keyword = false;
2436 for (i = 0; options[i].keyword; i++)
2438 if (strcmp(options[i].keyword, key) == 0)
2440 if (options[i].val == NULL)
2441 options[i].val = strdup(val);
2442 found_keyword = true;
2449 printfPQExpBuffer(errorMessage,
2450 libpq_gettext("ERROR: syntax error in service file '%s', line %d\n"),
2468 * Conninfo parser routine
2470 * If successful, a malloc'd PQconninfoOption array is returned.
2471 * If not successful, NULL is returned and an error message is
2472 * left in errorMessage.
2474 static PQconninfoOption *
2475 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2483 PQconninfoOption *options;
2484 PQconninfoOption *option;
2485 char errortmp[PQERRORMSG_LENGTH];
2487 /* Make a working copy of PQconninfoOptions */
2488 options = malloc(sizeof(PQconninfoOptions));
2489 if (options == NULL)
2491 printfPQExpBuffer(errorMessage,
2492 libpq_gettext("out of memory\n"));
2495 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2497 /* Need a modifiable copy of the input string */
2498 if ((buf = strdup(conninfo)) == NULL)
2500 printfPQExpBuffer(errorMessage,
2501 libpq_gettext("out of memory\n"));
2502 PQconninfoFree(options);
2509 /* Skip blanks before the parameter name */
2510 if (isspace((unsigned char) *cp))
2516 /* Get the parameter name */
2522 if (isspace((unsigned char) *cp))
2527 if (!isspace((unsigned char) *cp))
2536 /* Check that there is a following '=' */
2539 printfPQExpBuffer(errorMessage,
2540 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2542 PQconninfoFree(options);
2548 /* Skip blanks after the '=' */
2551 if (!isspace((unsigned char) *cp))
2556 /* Get the parameter value */
2564 if (isspace((unsigned char) *cp))
2588 printfPQExpBuffer(errorMessage,
2589 libpq_gettext("unterminated quoted string in connection info string\n"));
2590 PQconninfoFree(options);
2612 * Now we have the name and the value. Search for the param
2615 for (option = options; option->keyword != NULL; option++)
2617 if (strcmp(option->keyword, pname) == 0)
2620 if (option->keyword == NULL)
2622 printfPQExpBuffer(errorMessage,
2623 libpq_gettext("invalid connection option \"%s\"\n"),
2625 PQconninfoFree(options);
2635 option->val = strdup(pval);
2638 printfPQExpBuffer(errorMessage,
2639 libpq_gettext("out of memory\n"));
2640 PQconninfoFree(options);
2646 /* Done with the modifiable input string */
2650 * If there's a service spec, use it to obtain any
2651 * not-explicitly-given parameters.
2653 if (parseServiceInfo(options, errorMessage))
2655 PQconninfoFree(options);
2660 * Get the fallback resources for parameters not specified in the
2661 * conninfo string nor the service.
2663 for (option = options; option->keyword != NULL; option++)
2665 if (option->val != NULL)
2666 continue; /* Value was in conninfo or service */
2669 * Try to get the environment variable fallback
2671 if (option->envvar != NULL)
2673 if ((tmp = getenv(option->envvar)) != NULL)
2675 option->val = strdup(tmp);
2678 printfPQExpBuffer(errorMessage,
2679 libpq_gettext("out of memory\n"));
2680 PQconninfoFree(options);
2688 * No environment variable specified or this one isn't set - try
2691 if (option->compiled != NULL)
2693 option->val = strdup(option->compiled);
2696 printfPQExpBuffer(errorMessage,
2697 libpq_gettext("out of memory\n"));
2698 PQconninfoFree(options);
2705 * Special handling for user
2707 if (strcmp(option->keyword, "user") == 0)
2709 option->val = fe_getauthname(errortmp);
2710 /* note any error message is thrown away */
2720 conninfo_getval(PQconninfoOption *connOptions,
2721 const char *keyword)
2723 PQconninfoOption *option;
2725 for (option = connOptions; option->keyword != NULL; option++)
2727 if (strcmp(option->keyword, keyword) == 0)
2736 PQconninfoFree(PQconninfoOption *connOptions)
2738 PQconninfoOption *option;
2740 if (connOptions == NULL)
2743 for (option = connOptions; option->keyword != NULL; option++)
2745 if (option->val != NULL)
2752 /* =========== accessor functions for PGconn ========= */
2754 PQdb(const PGconn *conn)
2758 return conn->dbName;
2762 PQuser(const PGconn *conn)
2766 return conn->pguser;
2770 PQpass(const PGconn *conn)
2774 return conn->pgpass;
2778 PQhost(const PGconn *conn)
2782 return conn->pghost ? conn->pghost : conn->pgunixsocket;
2786 PQport(const PGconn *conn)
2790 return conn->pgport;
2794 PQtty(const PGconn *conn)
2802 PQoptions(const PGconn *conn)
2806 return conn->pgoptions;
2810 PQstatus(const PGconn *conn)
2813 return CONNECTION_BAD;
2814 return conn->status;
2817 PGTransactionStatusType
2818 PQtransactionStatus(const PGconn *conn)
2820 if (!conn || conn->status != CONNECTION_OK)
2821 return PQTRANS_UNKNOWN;
2822 if (conn->asyncStatus != PGASYNC_IDLE)
2823 return PQTRANS_ACTIVE;
2824 return conn->xactStatus;
2828 PQparameterStatus(const PGconn *conn, const char *paramName)
2830 const pgParameterStatus *pstatus;
2832 if (!conn || !paramName)
2834 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
2836 if (strcmp(pstatus->name, paramName) == 0)
2837 return pstatus->value;
2843 PQprotocolVersion(const PGconn *conn)
2847 if (conn->status == CONNECTION_BAD)
2849 return PG_PROTOCOL_MAJOR(conn->pversion);
2853 PQserverVersion(const PGconn *conn)
2857 if (conn->status == CONNECTION_BAD)
2859 return conn->sversion;
2863 PQerrorMessage(const PGconn *conn)
2866 return libpq_gettext("connection pointer is NULL\n");
2868 return conn->errorMessage.data;
2872 PQsocket(const PGconn *conn)
2880 PQbackendPID(const PGconn *conn)
2882 if (!conn || conn->status != CONNECTION_OK)
2884 return conn->be_pid;
2888 PQclientEncoding(const PGconn *conn)
2890 if (!conn || conn->status != CONNECTION_OK)
2892 return conn->client_encoding;
2896 PQsetClientEncoding(PGconn *conn, const char *encoding)
2899 static const char query[] = "set client_encoding to '%s'";
2903 if (!conn || conn->status != CONNECTION_OK)
2909 /* check query buffer overflow */
2910 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2913 /* ok, now send a query */
2914 sprintf(qbuf, query, encoding);
2915 res = PQexec(conn, qbuf);
2919 if (res->resultStatus != PGRES_COMMAND_OK)
2923 /* change libpq internal encoding */
2924 conn->client_encoding = pg_char_to_encoding(encoding);
2925 status = 0; /* everything is ok */
2932 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
2937 return PQERRORS_DEFAULT;
2938 old = conn->verbosity;
2939 conn->verbosity = verbosity;
2944 PQtrace(PGconn *conn, FILE *debug_port)
2949 conn->Pfdebug = debug_port;
2953 PQuntrace(PGconn *conn)
2959 fflush(conn->Pfdebug);
2960 conn->Pfdebug = NULL;
2965 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
2967 PQnoticeReceiver old;
2972 old = conn->noticeHooks.noticeRec;
2975 conn->noticeHooks.noticeRec = proc;
2976 conn->noticeHooks.noticeRecArg = arg;
2982 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2984 PQnoticeProcessor old;
2989 old = conn->noticeHooks.noticeProc;
2992 conn->noticeHooks.noticeProc = proc;
2993 conn->noticeHooks.noticeProcArg = arg;
2999 * The default notice message receiver just gets the standard notice text
3000 * and sends it to the notice processor. This two-level setup exists
3001 * mostly for backwards compatibility; perhaps we should deprecate use of
3002 * PQsetNoticeProcessor?
3005 defaultNoticeReceiver(void *arg, const PGresult *res)
3007 (void) arg; /* not used */
3008 if (res->noticeHooks.noticeProc != NULL)
3009 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3010 PQresultErrorMessage(res));
3014 * The default notice message processor just prints the
3015 * message on stderr. Applications can override this if they
3016 * want the messages to go elsewhere (a window, for example).
3017 * Note that simply discarding notices is probably a bad idea.
3020 defaultNoticeProcessor(void *arg, const char *message)
3022 (void) arg; /* not used */
3023 /* Note: we expect the supplied string to end with a newline already. */
3024 fprintf(stderr, "%s", message);
3028 * returns a pointer to the next token or NULL if the current
3029 * token doesn't match
3032 pwdfMatchesString(char *buf, char *token)
3036 bool bslash = false;
3038 if (buf == NULL || token == NULL)
3046 if (*tbuf == '\\' && !bslash)
3051 if (*tbuf == ':' && *ttok == 0 && !bslash)
3067 /* Get a password from the password file. Return value is malloc'd. */
3069 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3072 char pgpassfile[MAXPGPATH];
3073 struct stat stat_buf;
3076 #define LINELEN NAMEDATALEN*5
3079 if (dbname == NULL || strlen(dbname) == 0)
3082 if (username == NULL || strlen(username) == 0)
3085 if (hostname == NULL)
3086 hostname = DefaultHost;
3089 port = DEF_PGPORT_STR;
3091 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3092 /* use the literal path from the environment, if set */
3093 StrNCpy(pgpassfile, passfile_env, MAXPGPATH);
3096 char homedir[MAXPGPATH];
3098 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3100 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3103 /* If password file cannot be opened, ignore it. */
3104 if (stat(pgpassfile, &stat_buf) == -1)
3109 if (!S_ISREG(stat_buf.st_mode))
3112 libpq_gettext("WARNING: Password file %s is not a plain file.\n"),
3118 /* If password file is insecure, alert the user and ignore it. */
3119 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3122 libpq_gettext("WARNING: Password file %s has world or group read access; permission should be u=rw (0600)\n"),
3128 fp = fopen(pgpassfile, "r");
3138 fgets(buf, LINELEN - 1, fp);
3144 /* Remove trailing newline */
3145 if (buf[len - 1] == '\n')
3148 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3149 (t = pwdfMatchesString(t, port)) == NULL ||
3150 (t = pwdfMatchesString(t, dbname)) == NULL ||
3151 (t = pwdfMatchesString(t, username)) == NULL)
3165 * Obtain user's home directory, return in given buffer
3167 * On Unix, this actually returns the user's home directory. On Windows
3168 * it returns the PostgreSQL-specific application data folder.
3170 * This is essentially the same as get_home_path(), but we don't use that
3171 * because we don't want to pull path.c into libpq (it pollutes application
3175 pqGetHomeDirectory(char *buf, int bufsize)
3178 char pwdbuf[BUFSIZ];
3179 struct passwd pwdstr;
3180 struct passwd *pwd = NULL;
3182 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3184 StrNCpy(buf, pwd->pw_dir, bufsize);
3188 char tmppath[MAX_PATH];
3190 ZeroMemory(tmppath, sizeof(tmppath));
3191 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3193 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3199 * To keep the API consistent, the locking stubs are always provided, even
3200 * if they are not required.
3204 default_threadlock(int acquire)
3206 #ifdef ENABLE_THREAD_SAFETY
3208 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3211 static pthread_mutex_t singlethread_lock = NULL;
3212 static long mutex_initlock = 0;
3214 if (singlethread_lock == NULL)
3216 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3217 /* loop, another thread own the lock */ ;
3218 if (singlethread_lock == NULL)
3219 pthread_mutex_init(&singlethread_lock, NULL);
3220 InterlockedExchange(&mutex_initlock, 0);
3224 pthread_mutex_lock(&singlethread_lock);
3226 pthread_mutex_unlock(&singlethread_lock);
3231 PQregisterThreadLock(pgthreadlock_t newhandler)
3233 pgthreadlock_t prev = pg_g_threadlock;
3236 pg_g_threadlock = newhandler;
3238 pg_g_threadlock = default_threadlock;