1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-connect.c,v 1.247 2003/06/12 08:15:29 momjian Exp $
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
33 #include "libpq-int.h"
39 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_TCP_H
44 #include <netinet/tcp.h>
46 #include <arpa/inet.h>
50 #include "mb/pg_wchar.h"
52 /* For FNCTL_NONBLOCK */
53 #if defined(WIN32) || defined(__BEOS__)
57 #define PGPASSFILE ".pgpass"
59 /* fall back options if they are not specified by arguments or defined
60 by environment variables */
61 #define DefaultHost "localhost"
63 #define DefaultOption ""
64 #define DefaultAuthtype ""
65 #define DefaultPassword ""
69 * Definition of the conninfo parameters and their fallback resources.
71 * If Environment-Var and Compiled-in are specified as NULL, no
72 * fallback is available. If after all no value can be determined
73 * for an option, an error is returned.
75 * The value for the username is treated specially in conninfo_parse.
76 * If the Compiled-in resource is specified as a NULL value, the
77 * user is determined by fe_getauthname().
79 * The Label and Disp-Char entries are provided for applications that
80 * want to use PQconndefaults() to create a generic database connection
81 * dialog. Disp-Char is defined as follows:
82 * "" Normal input field
83 * "*" Password field - hide value
84 * "D" Debug option - don't show by default
86 * PQconninfoOptions[] is a constant static array that we use to initialize
87 * a dynamically allocated working copy. All the "val" fields in
88 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
89 * fields point to malloc'd strings that should be freed when the working
90 * array is freed (see PQconninfoFree).
93 static const PQconninfoOption PQconninfoOptions[] = {
95 * "authtype" is no longer used, so mark it "don't show". We keep it
96 * in the array so as not to reject conninfo strings from old apps
97 * that might still try to set it.
99 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
100 "Database-Authtype", "D", 20},
102 {"service", "PGSERVICE", NULL, NULL,
103 "Database-Service", "", 20},
105 {"user", "PGUSER", NULL, NULL,
106 "Database-User", "", 20},
108 {"password", "PGPASSWORD", NULL, NULL,
109 "Database-Password", "*", 20},
111 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
112 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
114 {"dbname", "PGDATABASE", NULL, NULL,
115 "Database-Name", "", 20},
117 {"host", "PGHOST", NULL, NULL,
118 "Database-Host", "", 40},
120 {"hostaddr", "PGHOSTADDR", NULL, NULL,
121 "Database-Host-IP-Address", "", 45},
123 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
124 "Database-Port", "", 6},
127 * "tty" is no longer used either, but keep it present for backwards
130 {"tty", "PGTTY", DefaultTty, NULL,
131 "Backend-Debug-TTY", "D", 40},
133 {"options", "PGOPTIONS", DefaultOption, NULL,
134 "Backend-Debug-Options", "D", 40},
137 {"requiressl", "PGREQUIRESSL", "0", NULL,
138 "Require-SSL", "", 1},
141 /* Terminating entry --- MUST BE LAST */
142 {NULL, NULL, NULL, NULL,
146 static const PQEnvironmentOption EnvironmentOptions[] =
148 /* common user-interface settings */
150 "PGDATESTYLE", "datestyle"
156 "PGCLIENTENCODING", "client_encoding"
158 /* internal performance-related settings */
168 static bool connectOptions1(PGconn *conn, const char *conninfo);
169 static bool connectOptions2(PGconn *conn);
170 static int connectDBStart(PGconn *conn);
171 static int connectDBComplete(PGconn *conn);
172 static PGconn *makeEmptyPGconn(void);
173 static void freePGconn(PGconn *conn);
174 static void closePGconn(PGconn *conn);
175 static PQconninfoOption *conninfo_parse(const char *conninfo,
176 PQExpBuffer errorMessage);
177 static char *conninfo_getval(PQconninfoOption *connOptions,
178 const char *keyword);
179 static void defaultNoticeProcessor(void *arg, const char *message);
180 static int parseServiceInfo(PQconninfoOption *options,
181 PQExpBuffer errorMessage);
182 static char *pwdfMatchesString(char *buf, char *token);
183 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
187 * Connecting to a Database
189 * There are now four different ways a user of this API can connect to the
190 * database. Two are not recommended for use in new code, because of their
191 * lack of extensibility with respect to the passing of options to the
192 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
195 * If it is desired to connect in a synchronous (blocking) manner, use the
196 * function PQconnectdb.
198 * To connect in an asynchronous (non-blocking) manner, use the functions
199 * PQconnectStart, and PQconnectPoll.
201 * Internally, the static functions connectDBStart, connectDBComplete
202 * are part of the connection procedure.
208 * establishes a connection to a postgres backend through the postmaster
209 * using connection information in a string.
211 * The conninfo string is a white-separated list of
215 * definitions. Value might be a single value containing no whitespaces or
216 * a single quoted string. If a single quote should appear anywhere in
217 * the value, it must be escaped with a backslash like \'
219 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
220 * if a memory allocation failed.
221 * If the status field of the connection returned is CONNECTION_BAD,
222 * then some fields may be null'ed out instead of having valid values.
224 * You should call PQfinish (if conn is not NULL) regardless of whether this
228 PQconnectdb(const char *conninfo)
230 PGconn *conn = PQconnectStart(conninfo);
232 if (conn && conn->status != CONNECTION_BAD)
233 (void) connectDBComplete(conn);
241 * Begins the establishment of a connection to a postgres backend through the
242 * postmaster using connection information in a string.
244 * See comment for PQconnectdb for the definition of the string format.
246 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
247 * you should not attempt to proceed with this connection. If the status
248 * field of the connection returned is CONNECTION_BAD, an error has
249 * occurred. In this case you should call PQfinish on the result, (perhaps
250 * inspecting the error message first). Other fields of the structure may not
251 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
252 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
255 * See PQconnectPoll for more info.
258 PQconnectStart(const char *conninfo)
263 * Allocate memory for the conn structure
265 conn = makeEmptyPGconn();
267 return (PGconn *) NULL;
270 * Parse the conninfo string
272 if (!connectOptions1(conn, conninfo))
276 * Compute derived options
278 if (!connectOptions2(conn))
282 * Connect to the database
284 if (!connectDBStart(conn))
286 /* Just in case we failed to set it in connectDBStart */
287 conn->status = CONNECTION_BAD;
296 * Internal subroutine to set up connection parameters given an already-
297 * created PGconn and a conninfo string. Derived settings should be
298 * processed by calling connectOptions2 next. (We split them because
299 * PQsetdbLogin overrides defaults in between.)
301 * Returns true if OK, false if trouble (in which case errorMessage is set
302 * and so is conn->status).
305 connectOptions1(PGconn *conn, const char *conninfo)
307 PQconninfoOption *connOptions;
311 * Parse the conninfo string
313 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
314 if (connOptions == NULL)
316 conn->status = CONNECTION_BAD;
317 /* errorMessage is already set */
322 * Move option values into conn structure
324 * Don't put anything cute here --- intelligence should be in
325 * connectOptions2 ...
327 tmp = conninfo_getval(connOptions, "hostaddr");
328 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
329 tmp = conninfo_getval(connOptions, "host");
330 conn->pghost = tmp ? strdup(tmp) : NULL;
331 tmp = conninfo_getval(connOptions, "port");
332 conn->pgport = tmp ? strdup(tmp) : NULL;
333 tmp = conninfo_getval(connOptions, "tty");
334 conn->pgtty = tmp ? strdup(tmp) : NULL;
335 tmp = conninfo_getval(connOptions, "options");
336 conn->pgoptions = tmp ? strdup(tmp) : NULL;
337 tmp = conninfo_getval(connOptions, "dbname");
338 conn->dbName = tmp ? strdup(tmp) : NULL;
339 tmp = conninfo_getval(connOptions, "user");
340 conn->pguser = tmp ? strdup(tmp) : NULL;
341 tmp = conninfo_getval(connOptions, "password");
342 conn->pgpass = tmp ? strdup(tmp) : NULL;
343 tmp = conninfo_getval(connOptions, "connect_timeout");
344 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
346 tmp = conninfo_getval(connOptions, "requiressl");
347 if (tmp && tmp[0] == '1')
348 conn->require_ssl = true;
352 * Free the option info - all is in conn now
354 PQconninfoFree(connOptions);
362 * Compute derived connection options after absorbing all user-supplied info.
364 * Returns true if OK, false if trouble (in which case errorMessage is set
365 * and so is conn->status).
368 connectOptions2(PGconn *conn)
371 * If database name was not given, default it to equal user name
373 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
374 && conn->pguser != NULL)
378 conn->dbName = strdup(conn->pguser);
382 * Supply default password if none given
384 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
388 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
389 conn->dbName, conn->pguser);
390 if (conn->pgpass == NULL)
391 conn->pgpass = strdup(DefaultPassword);
395 * Allow unix socket specification in the host name
397 if (conn->pghost && is_absolute_path(conn->pghost))
399 if (conn->pgunixsocket)
400 free(conn->pgunixsocket);
401 conn->pgunixsocket = conn->pghost;
407 * parse dbName to get all additional info in it, if any
409 if (update_db_info(conn) != 0)
411 conn->status = CONNECTION_BAD;
412 /* errorMessage is already set */
423 * Parse an empty string like PQconnectdb() would do and return the
424 * working connection options array.
426 * Using this function, an application may determine all possible options
427 * and their current default values.
429 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
430 * and should be freed when no longer needed via PQconninfoFree(). (In prior
431 * versions, the returned array was static, but that's not thread-safe.)
432 * Pre-7.0 applications that use this function will see a small memory leak
433 * until they are updated to call PQconninfoFree.
438 PQExpBufferData errorBuf;
439 PQconninfoOption *connOptions;
441 initPQExpBuffer(&errorBuf);
442 connOptions = conninfo_parse("", &errorBuf);
443 termPQExpBuffer(&errorBuf);
450 * establishes a connection to a postgres backend through the postmaster
451 * at the specified host and port.
453 * returns a PGconn* which is needed for all subsequent libpq calls
455 * if the status field of the connection returned is CONNECTION_BAD,
456 * then only the errorMessage is likely to be useful.
460 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
461 const char *pgtty, const char *dbName, const char *login,
467 * Allocate memory for the conn structure
469 conn = makeEmptyPGconn();
471 return (PGconn *) NULL;
474 * Parse an empty conninfo string in order to set up the same defaults
475 * that PQconnectdb() would use.
477 if (!connectOptions1(conn, ""))
481 * Absorb specified options into conn structure, overriding defaults
483 if (pghost && pghost[0] != '\0')
487 conn->pghost = strdup(pghost);
490 if (pgport && pgport[0] != '\0')
494 conn->pgport = strdup(pgport);
497 if (pgoptions && pgoptions[0] != '\0')
500 free(conn->pgoptions);
501 conn->pgoptions = strdup(pgoptions);
504 if (pgtty && pgtty[0] != '\0')
508 conn->pgtty = strdup(pgtty);
511 if (dbName && dbName[0] != '\0')
515 conn->dbName = strdup(dbName);
518 if (login && login[0] != '\0')
522 conn->pguser = strdup(login);
525 if (pwd && pwd[0] != '\0')
529 conn->pgpass = strdup(pwd);
533 * Compute derived options
535 if (!connectOptions2(conn))
539 * Connect to the database
541 if (connectDBStart(conn))
542 (void) connectDBComplete(conn);
548 #ifdef NOT_USED /* because it's broken */
551 * get all additional info out of dbName
554 update_db_info(PGconn *conn)
560 if (strchr(conn->dbName, '@') != NULL)
562 /* old style: dbname[@server][:port] */
563 tmp = strrchr(conn->dbName, ':');
564 if (tmp != NULL) /* port number given */
568 conn->pgport = strdup(tmp + 1);
572 tmp = strrchr(conn->dbName, '@');
573 if (tmp != NULL) /* host name given */
577 conn->pghost = strdup(tmp + 1);
581 conn->dbName = strdup(old);
589 * only allow protocols tcp and unix
591 if (strncmp(conn->dbName, "tcp:", 4) == 0)
593 else if (strncmp(conn->dbName, "unix:", 5) == 0)
598 if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
603 * <tcp|unix>:postgresql://server[:port|:/unixsocket/path:]
604 * [/db name][?options]
607 offset += strlen("postgresql://");
609 tmp = strrchr(conn->dbName + offset, '?');
610 if (tmp != NULL) /* options given */
613 free(conn->pgoptions);
614 conn->pgoptions = strdup(tmp + 1);
618 tmp = last_path_separator(conn->dbName + offset);
619 if (tmp != NULL) /* database name given */
623 conn->dbName = strdup(tmp + 1);
629 * Why do we default only this value from the environment
632 if ((tmp = getenv("PGDATABASE")) != NULL)
636 conn->dbName = strdup(tmp);
638 else if (conn->pguser)
642 conn->dbName = strdup(conn->pguser);
646 tmp = strrchr(old + offset, ':');
647 if (tmp != NULL) /* port number or Unix socket path given */
650 if ((tmp2 = strchr(tmp + 1, ':')) != NULL)
652 if (strncmp(old, "unix:", 5) != 0)
654 printfPQExpBuffer(&conn->errorMessage,
655 "connectDBStart() -- "
656 "socket name can only be specified with "
661 if (conn->pgunixsocket)
662 free(conn->pgunixsocket);
663 conn->pgunixsocket = strdup(tmp + 1);
669 conn->pgport = strdup(tmp + 1);
670 if (conn->pgunixsocket)
671 free(conn->pgunixsocket);
672 conn->pgunixsocket = NULL;
676 if (strncmp(old, "unix:", 5) == 0)
681 if (strcmp(old + offset, "localhost") != 0)
683 printfPQExpBuffer(&conn->errorMessage,
684 "connectDBStart() -- "
685 "non-TCP access only possible on "
694 conn->pghost = strdup(old + offset);
702 #endif /* NOT_USED */
706 * connectMakeNonblocking -
707 * Make a connection non-blocking.
708 * Returns 1 if successful, 0 if not.
712 connectMakeNonblocking(PGconn *conn)
714 if (FCNTL_NONBLOCK(conn->sock) < 0)
716 printfPQExpBuffer(&conn->errorMessage,
717 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
718 SOCK_STRERROR(SOCK_ERRNO));
727 * Sets the TCP_NODELAY socket option.
728 * Returns 1 if successful, 0 if not.
732 connectNoDelay(PGconn *conn)
737 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
741 printfPQExpBuffer(&conn->errorMessage,
742 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
743 SOCK_STRERROR(SOCK_ERRNO));
753 * connectFailureMessage -
754 * create a friendly error message on connection failure.
758 connectFailureMessage(PGconn *conn, int errorno)
760 char hostname[NI_MAXHOST];
761 char service[NI_MAXHOST];
763 getnameinfo((struct sockaddr *)&conn->raddr.addr, conn->raddr.salen,
764 hostname, sizeof(hostname), service, sizeof(service),
765 NI_NUMERICHOST | NI_NUMERICSERV);
766 if (conn->raddr.addr.ss_family == AF_UNIX)
767 printfPQExpBuffer(&conn->errorMessage,
769 "could not connect to server: %s\n"
770 "\tIs the server running locally and accepting\n"
771 "\tconnections on Unix domain socket \"%s\"?\n"
773 SOCK_STRERROR(errorno), service);
775 printfPQExpBuffer(&conn->errorMessage,
777 "could not connect to server: %s\n"
778 "\tIs the server running on host %s and accepting\n"
779 "\tTCP/IP connections on port %s?\n"
781 SOCK_STRERROR(errorno),
793 * Begin the process of making a connection to the backend.
795 * Returns 1 if successful, 0 if not.
799 connectDBStart(PGconn *conn)
803 struct addrinfo *addrs = NULL;
804 struct addrinfo hint;
805 const char *node = NULL;
811 /* Ensure our buffers are empty */
812 conn->inStart = conn->inCursor = conn->inEnd = 0;
816 * Determine the parameters to pass to getaddrinfo2.
819 /* Initialize hint structure */
820 MemSet(&hint, 0, sizeof(hint));
821 hint.ai_socktype = SOCK_STREAM;
822 hint.ai_family = AF_UNSPEC;
824 /* Set up port number as a string */
825 if (conn->pgport != NULL && conn->pgport[0] != '\0')
826 portnum = atoi(conn->pgport);
828 portnum = DEF_PGPORT;
829 snprintf(portstr, sizeof(portstr), "%d", portnum);
831 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
833 /* Using pghostaddr avoids a hostname lookup */
834 node = conn->pghostaddr;
835 hint.ai_family = AF_UNSPEC;
836 hint.ai_flags = AI_NUMERICHOST;
838 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
840 /* Using pghost, so we have to look-up the hostname */
842 hint.ai_family = AF_UNSPEC;
844 #ifdef HAVE_UNIX_SOCKETS
847 /* pghostaddr and pghost are NULL, so use Unix domain socket */
849 hint.ai_family = AF_UNIX;
850 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
852 #endif /* HAVE_UNIX_SOCKETS */
854 /* Use getaddrinfo2() to resolve the address */
855 ret = getaddrinfo2(node, portstr, &hint, &addrs);
856 if (ret || addrs == NULL)
858 printfPQExpBuffer(&conn->errorMessage,
859 libpq_gettext("getaddrinfo() failed: %s\n"),
861 freeaddrinfo2(hint.ai_family, addrs);
862 goto connect_errReturn;
866 * Set up to try to connect, with protocol 3.0 as the first attempt.
868 conn->addrlist = addrs;
869 conn->addr_cur = addrs;
870 conn->addrlist_family = hint.ai_family;
871 conn->pversion = PG_PROTOCOL(3,0);
872 conn->status = CONNECTION_NEEDED;
875 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
876 * so that it can easily be re-executed if needed again during the
877 * asynchronous startup process. However, we must run it once here,
878 * because callers expect a success return from this routine to mean
879 * that we are in PGRES_POLLING_WRITING connection state.
881 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
887 pqsecure_close(conn);
888 closesocket(conn->sock);
891 conn->status = CONNECTION_BAD;
899 * Block and complete a connection.
901 * Returns 1 on success, 0 on failure.
904 connectDBComplete(PGconn *conn)
906 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
907 time_t finish_time = ((time_t) -1);
909 if (conn == NULL || conn->status == CONNECTION_BAD)
913 * Set up a time limit, if connect_timeout isn't zero.
915 if (conn->connect_timeout != NULL)
917 int timeout = atoi(conn->connect_timeout);
922 * Rounding could cause connection to fail; need at least 2
927 /* calculate the finish time based on start + timeout */
928 finish_time = time(NULL) + timeout;
935 * Wait, if necessary. Note that the initial state (just after
936 * PQconnectStart) is to wait for the socket to select for
941 case PGRES_POLLING_OK:
942 return 1; /* success! */
944 case PGRES_POLLING_READING:
945 if (pqWaitTimed(1, 0, conn, finish_time))
947 conn->status = CONNECTION_BAD;
952 case PGRES_POLLING_WRITING:
953 if (pqWaitTimed(0, 1, conn, finish_time))
955 conn->status = CONNECTION_BAD;
961 /* Just in case we failed to set it in PQconnectPoll */
962 conn->status = CONNECTION_BAD;
967 * Now try to advance the state machine.
969 flag = PQconnectPoll(conn);
976 * Poll an asynchronous connection.
978 * Returns a PostgresPollingStatusType.
979 * Before calling this function, use select(2) to determine when data
982 * You must call PQfinish whether or not this fails.
984 * This function and PQconnectStart are intended to allow connections to be
985 * made without blocking the execution of your program on remote I/O. However,
986 * there are a number of caveats:
988 * o If you call PQtrace, ensure that the stream object into which you trace
990 * o If you do not supply an IP address for the remote host (i.e. you
991 * supply a host name instead) then PQconnectStart will block on
992 * gethostbyname. You will be fine if using Unix sockets (i.e. by
993 * supplying neither a host name nor a host address).
994 * o If your backend wants to use Kerberos authentication then you must
995 * supply both a host name and a host address, otherwise this function
996 * may block on gethostname.
1000 PostgresPollingStatusType
1001 PQconnectPoll(PGconn *conn)
1006 return PGRES_POLLING_FAILED;
1008 /* Get the new data */
1009 switch (conn->status)
1012 * We really shouldn't have been polled in these two cases,
1013 * but we can handle it.
1015 case CONNECTION_BAD:
1016 return PGRES_POLLING_FAILED;
1018 return PGRES_POLLING_OK;
1020 /* These are reading states */
1021 case CONNECTION_AWAITING_RESPONSE:
1022 case CONNECTION_AUTH_OK:
1024 /* Load waiting data */
1025 int n = pqReadData(conn);
1030 return PGRES_POLLING_READING;
1035 /* These are writing states, so we just proceed. */
1036 case CONNECTION_STARTED:
1037 case CONNECTION_MADE:
1040 /* We allow pqSetenvPoll to decide whether to proceed. */
1041 case CONNECTION_SETENV:
1044 /* Special cases: proceed without waiting. */
1045 case CONNECTION_SSL_STARTUP:
1046 case CONNECTION_NEEDED:
1050 printfPQExpBuffer(&conn->errorMessage,
1052 "invalid connection state, "
1053 "probably indicative of memory corruption\n"
1059 keep_going: /* We will come back to here until there
1060 * is nothing left to do. */
1061 switch (conn->status)
1063 case CONNECTION_NEEDED:
1066 * Try to initiate a connection to one of the addresses
1067 * returned by getaddrinfo2(). conn->addr_cur is the
1068 * next one to try. We fail when we run out of addresses
1069 * (reporting the error returned for the *last* alternative,
1070 * which may not be what users expect :-().
1072 while (conn->addr_cur != NULL)
1074 struct addrinfo *addr_cur = conn->addr_cur;
1076 /* Remember current address for possible error msg */
1077 memcpy(&conn->raddr, addr_cur->ai_addr,
1078 addr_cur->ai_addrlen);
1081 conn->sock = socket(addr_cur->ai_family,
1082 addr_cur->ai_socktype,
1083 addr_cur->ai_protocol);
1087 * ignore socket() failure if we have more addresses
1090 if (addr_cur->ai_next != NULL)
1092 conn->addr_cur = addr_cur->ai_next;
1095 printfPQExpBuffer(&conn->errorMessage,
1096 libpq_gettext("could not create socket: %s\n"),
1097 SOCK_STRERROR(SOCK_ERRNO));
1102 * Select socket options: no delay of outgoing data for
1103 * TCP sockets, and nonblock mode. Fail if this fails.
1105 if (!IS_AF_UNIX(addr_cur->ai_family))
1107 if (!connectNoDelay(conn))
1109 closesocket(conn->sock);
1111 conn->addr_cur = addr_cur->ai_next;
1115 if (connectMakeNonblocking(conn) == 0)
1117 closesocket(conn->sock);
1119 conn->addr_cur = addr_cur->ai_next;
1123 * Start/make connection. This should not block, since
1124 * we are in nonblock mode. If it does, well, too bad.
1127 if (connect(conn->sock, addr_cur->ai_addr,
1128 addr_cur->ai_addrlen) < 0)
1130 if (SOCK_ERRNO == EINTR)
1131 /* Interrupted system call - just try again */
1133 if (SOCK_ERRNO == EINPROGRESS ||
1134 SOCK_ERRNO == EWOULDBLOCK ||
1138 * This is fine - we're in non-blocking mode,
1139 * and the connection is in progress. Tell
1140 * caller to wait for write-ready on socket.
1142 conn->status = CONNECTION_STARTED;
1143 return PGRES_POLLING_WRITING;
1145 /* otherwise, trouble */
1150 * Hm, we're connected already --- seems the
1151 * "nonblock connection" wasn't. Advance the state
1152 * machine and go do the next stuff.
1154 conn->status = CONNECTION_STARTED;
1158 * This connection failed --- set up error report,
1159 * then close socket (do it this way in case close()
1160 * affects the value of errno...). We will ignore the
1161 * connect() failure and keep going if there are
1164 connectFailureMessage(conn, SOCK_ERRNO);
1165 if (conn->sock >= 0)
1167 closesocket(conn->sock);
1171 * Try the next address, if any.
1173 conn->addr_cur = addr_cur->ai_next;
1174 } /* loop over addresses */
1177 * Ooops, no more addresses. An appropriate error message
1178 * is already set up, so just set the right status.
1183 case CONNECTION_STARTED:
1186 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1189 * Write ready, since we've made it here, so the
1190 * connection has been made ... or has failed.
1194 * Now check (using getsockopt) that there is not an error
1195 * state waiting for us on the socket.
1198 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1199 (char *) &optval, &optlen) == -1)
1201 printfPQExpBuffer(&conn->errorMessage,
1202 libpq_gettext("could not get socket error status: %s\n"),
1203 SOCK_STRERROR(SOCK_ERRNO));
1206 else if (optval != 0)
1209 * When using a nonblocking connect, we will typically
1210 * see connect failures at this point, so provide a
1211 * friendly error message.
1213 connectFailureMessage(conn, optval);
1215 * If more addresses remain, keep trying, just as in
1216 * the case where connect() returned failure immediately.
1218 if (conn->addr_cur->ai_next != NULL)
1220 if (conn->sock >= 0)
1222 closesocket(conn->sock);
1225 conn->addr_cur = conn->addr_cur->ai_next;
1226 conn->status = CONNECTION_NEEDED;
1232 /* Fill in the client address */
1233 conn->laddr.salen = sizeof(conn->laddr.addr);
1234 if (getsockname(conn->sock,
1235 (struct sockaddr *)&conn->laddr.addr,
1236 &conn->laddr.salen) < 0)
1238 printfPQExpBuffer(&conn->errorMessage,
1239 libpq_gettext("could not get client address from socket: %s\n"),
1240 SOCK_STRERROR(SOCK_ERRNO));
1245 * Make sure we can write before advancing to next step.
1247 conn->status = CONNECTION_MADE;
1248 return PGRES_POLLING_WRITING;
1251 case CONNECTION_MADE:
1258 * If SSL is enabled and we haven't already got it running,
1259 * request it instead of sending the startup message.
1262 #ifdef HAVE_UNIX_SOCKETS
1263 if (conn->raddr.addr.ss_family == AF_UNIX)
1265 /* Don't bother requesting SSL over a Unix socket */
1266 conn->allow_ssl_try = false;
1267 conn->require_ssl = false;
1270 if (conn->allow_ssl_try && conn->ssl == NULL)
1275 * Send the SSL request packet.
1277 * Theoretically, this could block, but it really shouldn't
1278 * since we only got here if the socket is write-ready.
1280 pv = htonl(NEGOTIATE_SSL_CODE);
1281 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1283 printfPQExpBuffer(&conn->errorMessage,
1284 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1285 SOCK_STRERROR(SOCK_ERRNO));
1288 /* Ok, wait for response */
1289 conn->status = CONNECTION_SSL_STARTUP;
1290 return PGRES_POLLING_READING;
1292 #endif /* USE_SSL */
1295 * Build the startup packet.
1297 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1298 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1299 EnvironmentOptions);
1301 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1302 EnvironmentOptions);
1305 printfPQExpBuffer(&conn->errorMessage,
1306 libpq_gettext("out of memory\n"));
1311 * Send the startup packet.
1313 * Theoretically, this could block, but it really shouldn't
1314 * since we only got here if the socket is write-ready.
1316 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1318 printfPQExpBuffer(&conn->errorMessage,
1319 libpq_gettext("could not send startup packet: %s\n"),
1320 SOCK_STRERROR(SOCK_ERRNO));
1327 conn->status = CONNECTION_AWAITING_RESPONSE;
1328 return PGRES_POLLING_READING;
1332 * Handle SSL negotiation: wait for postmaster
1333 * messages and respond as necessary.
1335 case CONNECTION_SSL_STARTUP:
1338 PostgresPollingStatusType pollres;
1341 * On first time through, get the postmaster's response
1342 * to our SSL negotiation packet. Be careful to read only
1343 * one byte (if there's more, it could be SSL data).
1345 if (conn->ssl == NULL)
1351 nread = recv(conn->sock, &SSLok, 1, 0);
1354 if (SOCK_ERRNO == EINTR)
1355 /* Interrupted system call - just try again */
1356 goto retry_ssl_read;
1358 printfPQExpBuffer(&conn->errorMessage,
1359 libpq_gettext("could not receive server response to SSL negotiation packet: %s\n"),
1360 SOCK_STRERROR(SOCK_ERRNO));
1364 /* caller failed to wait for data */
1365 return PGRES_POLLING_READING;
1368 /* Do one-time setup; this creates conn->ssl */
1369 if (pqsecure_initialize(conn) == -1)
1372 else if (SSLok == 'N')
1374 if (conn->require_ssl)
1376 /* Require SSL, but server does not want it */
1377 printfPQExpBuffer(&conn->errorMessage,
1378 libpq_gettext("server does not support SSL, but SSL was required\n"));
1381 /* Otherwise, proceed with normal startup */
1382 conn->allow_ssl_try = false;
1383 conn->status = CONNECTION_MADE;
1384 return PGRES_POLLING_WRITING;
1386 else if (SSLok == 'E')
1388 /* Received error - probably protocol mismatch */
1390 fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-7.0.\n");
1391 if (conn->require_ssl)
1393 /* Require SSL, but server is too old */
1394 printfPQExpBuffer(&conn->errorMessage,
1395 libpq_gettext("server does not support SSL, but SSL was required\n"));
1398 /* Otherwise, try again without SSL */
1399 conn->allow_ssl_try = false;
1400 /* Assume it ain't gonna handle protocol 3, either */
1401 conn->pversion = PG_PROTOCOL(2,0);
1402 /* Must drop the old connection */
1403 closesocket(conn->sock);
1405 conn->status = CONNECTION_NEEDED;
1410 printfPQExpBuffer(&conn->errorMessage,
1411 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1417 * Begin or continue the SSL negotiation process.
1419 pollres = pqsecure_open_client(conn);
1420 if (pollres == PGRES_POLLING_OK)
1422 /* SSL handshake done, ready to send startup packet */
1423 conn->status = CONNECTION_MADE;
1424 return PGRES_POLLING_WRITING;
1427 #else /* !USE_SSL */
1428 /* can't get here */
1430 #endif /* USE_SSL */
1434 * Handle authentication exchange: wait for postmaster
1435 * messages and respond as necessary.
1437 case CONNECTION_AWAITING_RESPONSE:
1445 * Scan the message from current point (note that if we
1446 * find the message is incomplete, we will return without
1447 * advancing inStart, and resume here next time).
1449 conn->inCursor = conn->inStart;
1451 /* Read type byte */
1452 if (pqGetc(&beresp, conn))
1454 /* We'll come back when there is more data */
1455 return PGRES_POLLING_READING;
1459 * Validate message type: we expect only an authentication
1460 * request or an error here. Anything else probably means
1461 * it's not Postgres on the other end at all.
1463 if (!(beresp == 'R' || beresp == 'E'))
1465 printfPQExpBuffer(&conn->errorMessage,
1467 "expected authentication request from "
1468 "server, but received %c\n"),
1473 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1475 /* Read message length word */
1476 if (pqGetInt(&msgLength, 4, conn))
1478 /* We'll come back when there is more data */
1479 return PGRES_POLLING_READING;
1484 /* Set phony message length to disable checks below */
1489 * Try to validate message length before using it.
1490 * Authentication requests can't be very large. Errors
1491 * can be a little larger, but not huge. If we see a large
1492 * apparent length in an error, it means we're really talking
1493 * to a pre-3.0-protocol server; cope.
1495 if (beresp == 'R' && (msgLength < 8 || msgLength > 100))
1497 printfPQExpBuffer(&conn->errorMessage,
1499 "expected authentication request from "
1500 "server, but received %c\n"),
1505 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1507 /* Handle error from a pre-3.0 server */
1508 conn->inCursor = conn->inStart + 1; /* reread data */
1509 if (pqGets(&conn->errorMessage, conn))
1511 /* We'll come back when there is more data */
1512 return PGRES_POLLING_READING;
1514 /* OK, we read the message; mark data consumed */
1515 conn->inStart = conn->inCursor;
1518 * The postmaster typically won't end its message with
1519 * a newline, so add one to conform to libpq
1522 appendPQExpBufferChar(&conn->errorMessage, '\n');
1525 * If we tried to open the connection in 3.0 protocol,
1526 * fall back to 2.0 protocol.
1528 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1530 conn->pversion = PG_PROTOCOL(2,0);
1531 /* Must drop the old connection */
1532 pqsecure_close(conn);
1533 closesocket(conn->sock);
1535 conn->status = CONNECTION_NEEDED;
1543 * Can't process if message body isn't all here yet.
1545 * (In protocol 2.0 case, we are assuming messages carry
1546 * at least 4 bytes of data.)
1549 avail = conn->inEnd - conn->inCursor;
1550 if (avail < msgLength)
1553 * Before returning, try to enlarge the input buffer if
1554 * needed to hold the whole message; see notes in
1557 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1559 /* We'll come back when there is more data */
1560 return PGRES_POLLING_READING;
1563 /* Handle errors. */
1566 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1568 if (pqGetErrorNotice3(conn, true))
1570 /* We'll come back when there is more data */
1571 return PGRES_POLLING_READING;
1576 if (pqGets(&conn->errorMessage, conn))
1578 /* We'll come back when there is more data */
1579 return PGRES_POLLING_READING;
1582 /* OK, we read the message; mark data consumed */
1583 conn->inStart = conn->inCursor;
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
1619 conn->inStart = conn->inCursor;
1621 /* Respond to the request if necessary. */
1624 * Note that conn->pghost must be non-NULL if we are going
1625 * to avoid the Kerberos code doing a hostname look-up.
1629 * XXX fe-auth.c has not been fixed to support
1632 if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1633 conn->errorMessage.data) != STATUS_OK)
1635 conn->errorMessage.len = strlen(conn->errorMessage.data);
1638 conn->errorMessage.len = strlen(conn->errorMessage.data);
1641 * Just make sure that any data sent by fe_sendauth is
1642 * flushed out. Although this theoretically could block,
1643 * it really shouldn't since we don't send large auth
1649 if (areq == AUTH_REQ_OK)
1651 /* We are done with authentication exchange */
1652 conn->status = CONNECTION_AUTH_OK;
1655 * Set asyncStatus so that PQsetResult will think that
1656 * what comes back next is the result of a query. See
1659 conn->asyncStatus = PGASYNC_BUSY;
1662 /* Look to see if we have more data yet. */
1666 case CONNECTION_AUTH_OK:
1669 * Now we expect to hear from the backend. A ReadyForQuery
1670 * message indicates that startup is successful, but we
1671 * might also get an Error message indicating failure.
1672 * (Notice messages indicating nonfatal warnings are also
1673 * allowed by the protocol, as are ParameterStatus and
1674 * BackendKeyData messages.) Easiest way to handle this is
1675 * to let PQgetResult() read the messages. We just have to
1676 * fake it out about the state of the connection, by setting
1677 * asyncStatus = PGASYNC_BUSY (done above).
1681 return PGRES_POLLING_READING;
1683 res = PQgetResult(conn);
1686 * NULL return indicating we have gone to IDLE state is
1691 if (res->resultStatus != PGRES_FATAL_ERROR)
1692 printfPQExpBuffer(&conn->errorMessage,
1693 libpq_gettext("unexpected message from server during startup\n"));
1696 * if the resultStatus is FATAL, then
1697 * conn->errorMessage already has a copy of the error;
1698 * needn't copy it back. But add a newline if it's not
1699 * there already, since postmaster error messages may
1702 if (conn->errorMessage.len <= 0 ||
1703 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1704 appendPQExpBufferChar(&conn->errorMessage, '\n');
1709 /* We can release the address list now. */
1710 freeaddrinfo2(conn->addrlist_family, conn->addrlist);
1711 conn->addrlist = NULL;
1712 conn->addr_cur = NULL;
1714 /* Fire up post-connection housekeeping if needed */
1715 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1717 conn->status = CONNECTION_SETENV;
1718 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1719 conn->next_eo = EnvironmentOptions;
1720 return PGRES_POLLING_WRITING;
1723 /* Otherwise, we are open for business! */
1724 conn->status = CONNECTION_OK;
1725 return PGRES_POLLING_OK;
1728 case CONNECTION_SETENV:
1731 * Do post-connection housekeeping (only needed in protocol 2.0).
1733 * We pretend that the connection is OK for the duration of
1736 conn->status = CONNECTION_OK;
1738 switch (pqSetenvPoll(conn))
1740 case PGRES_POLLING_OK: /* Success */
1743 case PGRES_POLLING_READING: /* Still going */
1744 conn->status = CONNECTION_SETENV;
1745 return PGRES_POLLING_READING;
1747 case PGRES_POLLING_WRITING: /* Still going */
1748 conn->status = CONNECTION_SETENV;
1749 return PGRES_POLLING_WRITING;
1755 /* We are open for business! */
1756 conn->status = CONNECTION_OK;
1757 return PGRES_POLLING_OK;
1760 printfPQExpBuffer(&conn->errorMessage,
1762 "invalid connection state %c, "
1763 "probably indicative of memory corruption\n"
1774 * We used to close the socket at this point, but that makes it
1775 * awkward for those above us if they wish to remove this socket from
1776 * their own records (an fd_set for example). We'll just have this
1777 * socket closed when PQfinish is called (which is compulsory even
1778 * after an error, since the connection structure must be freed).
1780 conn->status = CONNECTION_BAD;
1781 return PGRES_POLLING_FAILED;
1787 * - create a PGconn data structure with (as yet) no interesting data
1790 makeEmptyPGconn(void)
1792 PGconn *conn = (PGconn *) malloc(sizeof(PGconn));
1797 /* Zero all pointers and booleans */
1798 MemSet((char *) conn, 0, sizeof(PGconn));
1800 conn->noticeHook = defaultNoticeProcessor;
1801 conn->status = CONNECTION_BAD;
1802 conn->asyncStatus = PGASYNC_IDLE;
1803 conn->setenv_state = SETENV_STATE_IDLE;
1804 conn->client_encoding = PG_SQL_ASCII;
1805 conn->notifyList = DLNewList();
1808 conn->allow_ssl_try = TRUE;
1812 * We try to send at least 8K at a time, which is the usual size
1813 * of pipe buffers on Unix systems. That way, when we are sending a
1814 * large amount of data, we avoid incurring extra kernel context swaps
1815 * for partial bufferloads. The output buffer is initially made 16K
1816 * in size, and we try to dump it after accumulating 8K.
1818 * With the same goal of minimizing context swaps, the input buffer will
1819 * be enlarged anytime it has less than 8K free, so we initially
1820 * allocate twice that.
1822 conn->inBufSize = 16 * 1024;
1823 conn->inBuffer = (char *) malloc(conn->inBufSize);
1824 conn->outBufSize = 16 * 1024;
1825 conn->outBuffer = (char *) malloc(conn->outBufSize);
1826 conn->nonblocking = FALSE;
1827 initPQExpBuffer(&conn->errorMessage);
1828 initPQExpBuffer(&conn->workBuffer);
1830 if (conn->inBuffer == NULL ||
1831 conn->outBuffer == NULL ||
1832 conn->errorMessage.data == NULL ||
1833 conn->workBuffer.data == NULL)
1835 /* out of memory already :-( */
1845 * - free the PGconn data structure
1849 freePGconn(PGconn *conn)
1853 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1854 if (conn->sock >= 0)
1856 pqsecure_close(conn);
1857 closesocket(conn->sock);
1861 if (conn->pghostaddr)
1862 free(conn->pghostaddr);
1865 if (conn->pgunixsocket)
1866 free(conn->pgunixsocket);
1869 if (conn->connect_timeout)
1870 free(conn->connect_timeout);
1871 if (conn->pgoptions)
1872 free(conn->pgoptions);
1879 /* Note that conn->Pfdebug is not ours to close or free */
1880 if (conn->notifyList)
1881 DLFreeList(conn->notifyList);
1882 freeaddrinfo2(conn->addrlist_family, conn->addrlist);
1883 if (conn->lobjfuncs)
1884 free(conn->lobjfuncs);
1886 free(conn->inBuffer);
1887 if (conn->outBuffer)
1888 free(conn->outBuffer);
1889 termPQExpBuffer(&conn->errorMessage);
1890 termPQExpBuffer(&conn->workBuffer);
1896 - properly close a connection to the backend
1899 closePGconn(PGconn *conn)
1902 * Note that the protocol doesn't allow us to send Terminate messages
1903 * during the startup phase.
1905 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1908 * Try to send "close connection" message to backend. Ignore any
1911 pqPutMsgStart('X', false, conn);
1917 * must reset the blocking status so a possible reconnect will work
1918 * don't call PQsetnonblocking() because it will fail if it's unable
1919 * to flush the connection.
1921 conn->nonblocking = FALSE;
1924 * Close the connection, reset all transient state, flush I/O buffers.
1926 if (conn->sock >= 0)
1928 pqsecure_close(conn);
1929 closesocket(conn->sock);
1932 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
1934 conn->asyncStatus = PGASYNC_IDLE;
1935 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1936 if (conn->lobjfuncs)
1937 free(conn->lobjfuncs);
1938 conn->lobjfuncs = NULL;
1939 conn->inStart = conn->inCursor = conn->inEnd = 0;
1945 properly close a connection to the backend
1946 also frees the PGconn data structure so it shouldn't be re-used
1950 PQfinish(PGconn *conn)
1960 resets the connection to the backend
1961 closes the existing connection and makes a new one
1964 PQreset(PGconn *conn)
1970 if (connectDBStart(conn))
1971 (void) connectDBComplete(conn);
1977 resets the connection to the backend
1978 closes the existing connection and makes a new one
1979 Returns 1 on success, 0 on failure.
1982 PQresetStart(PGconn *conn)
1988 return connectDBStart(conn);
1996 resets the connection to the backend
1997 closes the existing connection and makes a new one
2000 PostgresPollingStatusType
2001 PQresetPoll(PGconn *conn)
2004 return PQconnectPoll(conn);
2006 return PGRES_POLLING_FAILED;
2011 * PQrequestCancel: attempt to request cancellation of the current operation.
2013 * The return value is TRUE if the cancel request was successfully
2014 * dispatched, FALSE if not (in which case conn->errorMessage is set).
2015 * Note: successful dispatch is no guarantee that there will be any effect at
2016 * the backend. The application must read the operation result as usual.
2018 * XXX it was a bad idea to have the error message returned in
2019 * conn->errorMessage, since it could overwrite a message already there.
2020 * Would be better to return it in a char array passed by the caller.
2022 * CAUTION: we want this routine to be safely callable from a signal handler
2023 * (for example, an application might want to call it in a SIGINT handler).
2024 * This means we cannot use any C library routine that might be non-reentrant.
2025 * malloc/free are often non-reentrant, and anything that might call them is
2026 * just as dangerous. We avoid sprintf here for that reason. Building up
2027 * error messages with strcpy/strcat is tedious but should be quite safe.
2028 * We also save/restore errno in case the signal handler support doesn't.
2030 * NOTE: this routine must not generate any error message longer than
2031 * INITIAL_EXPBUFFER_SIZE (currently 256), since we dare not try to
2032 * expand conn->errorMessage!
2036 PQrequestCancel(PGconn *conn)
2038 int save_errno = SOCK_ERRNO;
2043 CancelRequestPacket cp;
2046 /* Check we have an open connection */
2052 strcpy(conn->errorMessage.data,
2053 "PQrequestCancel() -- connection is not open\n");
2054 conn->errorMessage.len = strlen(conn->errorMessage.data);
2056 WSASetLastError(save_errno);
2064 * We need to open a temporary connection to the postmaster. Use the
2065 * information saved by connectDB to do this with only kernel calls.
2067 if ((tmpsock = socket(conn->raddr.addr.ss_family, SOCK_STREAM, 0)) < 0)
2069 strcpy(conn->errorMessage.data,
2070 "PQrequestCancel() -- socket() failed: ");
2071 goto cancel_errReturn;
2074 if (connect(tmpsock, (struct sockaddr *)&conn->raddr.addr,
2075 conn->raddr.salen) < 0)
2077 if (SOCK_ERRNO == EINTR)
2078 /* Interrupted system call - we'll just try again */
2080 strcpy(conn->errorMessage.data,
2081 "PQrequestCancel() -- connect() failed: ");
2082 goto cancel_errReturn;
2086 * We needn't set nonblocking I/O or NODELAY options here.
2089 /* Create and send the cancel request packet. */
2091 crp.packetlen = htonl((uint32) sizeof(crp));
2092 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2093 crp.cp.backendPID = htonl(conn->be_pid);
2094 crp.cp.cancelAuthCode = htonl(conn->be_key);
2097 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2099 if (SOCK_ERRNO == EINTR)
2100 /* Interrupted system call - we'll just try again */
2102 strcpy(conn->errorMessage.data,
2103 "PQrequestCancel() -- send() failed: ");
2104 goto cancel_errReturn;
2108 closesocket(tmpsock);
2110 WSASetLastError(save_errno);
2118 strcat(conn->errorMessage.data, SOCK_STRERROR(SOCK_ERRNO));
2119 strcat(conn->errorMessage.data, "\n");
2120 conn->errorMessage.len = strlen(conn->errorMessage.data);
2123 closesocket(tmpsock);
2125 WSASetLastError(save_errno);
2135 * pqPacketSend() -- convenience routine to send a message to server.
2137 * pack_type: the single-byte message type code. (Pass zero for startup
2138 * packets, which have no message type code.)
2140 * buf, buf_len: contents of message. The given length includes only what
2141 * is in buf; the message type and message length fields are added here.
2143 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2144 * SIDE_EFFECTS: may block.
2146 * Note: all messages sent with this routine have a length word, whether
2147 * it's protocol 2.0 or 3.0.
2150 pqPacketSend(PGconn *conn, char pack_type,
2151 const void *buf, size_t buf_len)
2153 /* Start the message. */
2154 if (pqPutMsgStart(pack_type, true, conn))
2155 return STATUS_ERROR;
2157 /* Send the message body. */
2158 if (pqPutnchar(buf, buf_len, conn))
2159 return STATUS_ERROR;
2161 /* Finish the message. */
2162 if (pqPutMsgEnd(conn))
2163 return STATUS_ERROR;
2165 /* Flush to ensure backend gets it. */
2167 return STATUS_ERROR;
2175 #error "You must compile this file with SYSCONFDIR defined."
2178 #define MAXBUFSIZE 256
2181 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2183 char *service = conninfo_getval(options, "service");
2184 char *serviceFile = SYSCONFDIR "/pg_service.conf";
2185 int group_found = 0;
2190 * We have to special-case the environment variable PGSERVICE here,
2191 * since this is and should be called before inserting environment
2192 * defaults for other connection options.
2194 if (service == NULL)
2195 service = getenv("PGSERVICE");
2197 if (service != NULL)
2200 char buf[MAXBUFSIZE],
2203 f = fopen(serviceFile, "r");
2206 printfPQExpBuffer(errorMessage, "ERROR: Service file '%s' not found\n",
2211 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2215 if (strlen(line) >= MAXBUFSIZE - 2)
2218 printfPQExpBuffer(errorMessage,
2219 "ERROR: line %d too long in service file '%s'\n",
2225 /* ignore EOL at end of line */
2226 if (strlen(line) && line[strlen(line) - 1] == '\n')
2227 line[strlen(line) - 1] = 0;
2229 /* ignore leading blanks */
2230 while (*line && isspace((unsigned char) line[0]))
2233 /* ignore comments and empty lines */
2234 if (strlen(line) == 0 || line[0] == '#')
2237 /* Check for right groupname */
2242 /* group info already read */
2247 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2248 line[strlen(service) + 1] == ']')
2258 * Finally, we are in the right group and can parse
2265 key = strtok(line, "=");
2268 printfPQExpBuffer(errorMessage,
2269 "ERROR: syntax error in service file '%s', line %d\n",
2277 * If not already set, set the database name to the
2278 * name of the service
2280 for (i = 0; options[i].keyword; i++)
2282 if (strcmp(options[i].keyword, "dbname") == 0)
2284 if (options[i].val == NULL)
2285 options[i].val = strdup(service);
2290 val = line + strlen(line) + 1;
2293 * Set the parameter --- but don't override any
2294 * previous explicit setting.
2297 for (i = 0; options[i].keyword; i++)
2299 if (strcmp(options[i].keyword, key) == 0)
2301 if (options[i].val == NULL)
2302 options[i].val = strdup(val);
2310 printfPQExpBuffer(errorMessage,
2311 "ERROR: syntax error in service file '%s', line %d\n",
2329 * Conninfo parser routine
2331 * If successful, a malloc'd PQconninfoOption array is returned.
2332 * If not successful, NULL is returned and an error message is
2333 * left in errorMessage.
2335 static PQconninfoOption *
2336 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2344 PQconninfoOption *options;
2345 PQconninfoOption *option;
2346 char errortmp[PQERRORMSG_LENGTH];
2348 /* Make a working copy of PQconninfoOptions */
2349 options = malloc(sizeof(PQconninfoOptions));
2350 if (options == NULL)
2352 printfPQExpBuffer(errorMessage,
2353 libpq_gettext("out of memory\n"));
2356 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2358 /* Need a modifiable copy of the input string */
2359 if ((buf = strdup(conninfo)) == NULL)
2361 printfPQExpBuffer(errorMessage,
2362 libpq_gettext("out of memory\n"));
2363 PQconninfoFree(options);
2370 /* Skip blanks before the parameter name */
2371 if (isspace((unsigned char) *cp))
2377 /* Get the parameter name */
2383 if (isspace((unsigned char) *cp))
2388 if (!isspace((unsigned char) *cp))
2397 /* Check that there is a following '=' */
2400 printfPQExpBuffer(errorMessage,
2401 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2403 PQconninfoFree(options);
2409 /* Skip blanks after the '=' */
2412 if (!isspace((unsigned char) *cp))
2417 /* Get the parameter value */
2425 if (isspace((unsigned char) *cp))
2449 printfPQExpBuffer(errorMessage,
2450 libpq_gettext("unterminated quoted string in connection info string\n"));
2451 PQconninfoFree(options);
2473 * Now we have the name and the value. Search for the param
2476 for (option = options; option->keyword != NULL; option++)
2478 if (strcmp(option->keyword, pname) == 0)
2481 if (option->keyword == NULL)
2483 printfPQExpBuffer(errorMessage,
2484 libpq_gettext("invalid connection option \"%s\"\n"),
2486 PQconninfoFree(options);
2496 option->val = strdup(pval);
2500 /* Done with the modifiable input string */
2504 * If there's a service spec, use it to obtain any not-explicitly-given
2507 if (parseServiceInfo(options, errorMessage))
2509 PQconninfoFree(options);
2514 * Get the fallback resources for parameters not specified in the
2515 * conninfo string nor the service.
2517 for (option = options; option->keyword != NULL; option++)
2519 if (option->val != NULL)
2520 continue; /* Value was in conninfo or service */
2523 * Try to get the environment variable fallback
2525 if (option->envvar != NULL)
2527 if ((tmp = getenv(option->envvar)) != NULL)
2529 option->val = strdup(tmp);
2535 * No environment variable specified or this one isn't set - try
2538 if (option->compiled != NULL)
2540 option->val = strdup(option->compiled);
2545 * Special handling for user
2547 if (strcmp(option->keyword, "user") == 0)
2549 option->val = fe_getauthname(errortmp);
2550 /* note any error message is thrown away */
2560 conninfo_getval(PQconninfoOption *connOptions,
2561 const char *keyword)
2563 PQconninfoOption *option;
2565 for (option = connOptions; option->keyword != NULL; option++)
2567 if (strcmp(option->keyword, keyword) == 0)
2576 PQconninfoFree(PQconninfoOption *connOptions)
2578 PQconninfoOption *option;
2580 if (connOptions == NULL)
2583 for (option = connOptions; option->keyword != NULL; option++)
2585 if (option->val != NULL)
2592 /* =========== accessor functions for PGconn ========= */
2594 PQdb(const PGconn *conn)
2597 return (char *) NULL;
2598 return conn->dbName;
2602 PQuser(const PGconn *conn)
2605 return (char *) NULL;
2606 return conn->pguser;
2610 PQpass(const PGconn *conn)
2613 return (char *) NULL;
2614 return conn->pgpass;
2618 PQhost(const PGconn *conn)
2621 return (char *) NULL;
2622 return conn->pghost ? conn->pghost : conn->pgunixsocket;
2626 PQport(const PGconn *conn)
2629 return (char *) NULL;
2630 return conn->pgport;
2634 PQtty(const PGconn *conn)
2637 return (char *) NULL;
2642 PQoptions(const PGconn *conn)
2645 return (char *) NULL;
2646 return conn->pgoptions;
2650 PQstatus(const PGconn *conn)
2653 return CONNECTION_BAD;
2654 return conn->status;
2658 PQerrorMessage(const PGconn *conn)
2661 return libpq_gettext("connection pointer is NULL\n");
2663 return conn->errorMessage.data;
2667 PQsocket(const PGconn *conn)
2675 PQbackendPID(const PGconn *conn)
2677 if (!conn || conn->status != CONNECTION_OK)
2679 return conn->be_pid;
2683 PQclientEncoding(const PGconn *conn)
2685 if (!conn || conn->status != CONNECTION_OK)
2687 return conn->client_encoding;
2691 PQsetClientEncoding(PGconn *conn, const char *encoding)
2694 static char query[] = "set client_encoding to '%s'";
2698 if (!conn || conn->status != CONNECTION_OK)
2704 /* check query buffer overflow */
2705 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2708 /* ok, now send a query */
2709 sprintf(qbuf, query, encoding);
2710 res = PQexec(conn, qbuf);
2712 if (res == (PGresult *) NULL)
2714 if (res->resultStatus != PGRES_COMMAND_OK)
2718 /* change libpq internal encoding */
2719 conn->client_encoding = pg_char_to_encoding(encoding);
2720 status = 0; /* everything is ok */
2727 PQtrace(PGconn *conn, FILE *debug_port)
2730 conn->status == CONNECTION_BAD)
2733 conn->Pfdebug = debug_port;
2737 PQuntrace(PGconn *conn)
2739 /* note: better allow untrace even when connection bad */
2744 fflush(conn->Pfdebug);
2745 conn->Pfdebug = NULL;
2750 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2752 PQnoticeProcessor old;
2757 old = conn->noticeHook;
2760 conn->noticeHook = proc;
2761 conn->noticeArg = arg;
2767 * The default notice/error message processor just prints the
2768 * message on stderr. Applications can override this if they
2769 * want the messages to go elsewhere (a window, for example).
2770 * Note that simply discarding notices is probably a bad idea.
2774 defaultNoticeProcessor(void *arg, const char *message)
2776 (void) arg; /* not used */
2777 /* Note: we expect the supplied string to end with a newline already. */
2778 fprintf(stderr, "%s", message);
2782 * returns a pointer to the next token or NULL if the current
2783 * token doesn't match
2786 pwdfMatchesString(char *buf, char *token)
2790 bool bslash = false;
2792 if (buf == NULL || token == NULL)
2800 if (*tbuf == '\\' && !bslash)
2805 if (*tbuf == ':' && *ttok == 0 && !bslash)
2821 /* Get a password from the password file. Return value is malloc'd. */
2823 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
2828 struct stat stat_buf;
2830 #define LINELEN NAMEDATALEN*5
2833 if (dbname == NULL || strlen(dbname) == 0)
2836 if (username == NULL || strlen(username) == 0)
2839 if (hostname == NULL)
2840 hostname = DefaultHost;
2843 port = DEF_PGPORT_STR;
2845 /* Look for it in the home dir */
2846 home = getenv("HOME");
2850 pgpassfile = malloc(strlen(home) + 1 + strlen(PGPASSFILE) + 1);
2853 fprintf(stderr, libpq_gettext("out of memory\n"));
2857 sprintf(pgpassfile, "%s/%s", home, PGPASSFILE);
2859 /* If password file cannot be opened, ignore it. */
2860 if (stat(pgpassfile, &stat_buf) == -1)
2867 /* If password file is insecure, alert the user and ignore it. */
2868 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
2871 libpq_gettext("WARNING: Password file %s has world or group read access; permission should be u=rw (0600)\n"),
2878 fp = fopen(pgpassfile, "r");
2889 fgets(buf, LINELEN - 1, fp);
2895 /* Remove trailing newline */
2896 if (buf[len - 1] == '\n')
2899 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
2900 (t = pwdfMatchesString(t, port)) == NULL ||
2901 (t = pwdfMatchesString(t, dbname)) == NULL ||
2902 (t = pwdfMatchesString(t, username)) == NULL)