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.246 2003/06/12 08:11:07 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"
53 #define PGPASSFILE ".pgpass"
55 /* fall back options if they are not specified by arguments or defined
56 by environment variables */
57 #define DefaultHost "localhost"
59 #define DefaultOption ""
60 #define DefaultAuthtype ""
61 #define DefaultPassword ""
65 * Definition of the conninfo parameters and their fallback resources.
67 * If Environment-Var and Compiled-in are specified as NULL, no
68 * fallback is available. If after all no value can be determined
69 * for an option, an error is returned.
71 * The value for the username is treated specially in conninfo_parse.
72 * If the Compiled-in resource is specified as a NULL value, the
73 * user is determined by fe_getauthname().
75 * The Label and Disp-Char entries are provided for applications that
76 * want to use PQconndefaults() to create a generic database connection
77 * dialog. Disp-Char is defined as follows:
78 * "" Normal input field
79 * "*" Password field - hide value
80 * "D" Debug option - don't show by default
82 * PQconninfoOptions[] is a constant static array that we use to initialize
83 * a dynamically allocated working copy. All the "val" fields in
84 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
85 * fields point to malloc'd strings that should be freed when the working
86 * array is freed (see PQconninfoFree).
89 static const PQconninfoOption PQconninfoOptions[] = {
91 * "authtype" is no longer used, so mark it "don't show". We keep it
92 * in the array so as not to reject conninfo strings from old apps
93 * that might still try to set it.
95 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
96 "Database-Authtype", "D", 20},
98 {"service", "PGSERVICE", NULL, NULL,
99 "Database-Service", "", 20},
101 {"user", "PGUSER", NULL, NULL,
102 "Database-User", "", 20},
104 {"password", "PGPASSWORD", NULL, NULL,
105 "Database-Password", "*", 20},
107 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
108 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
110 {"dbname", "PGDATABASE", NULL, NULL,
111 "Database-Name", "", 20},
113 {"host", "PGHOST", NULL, NULL,
114 "Database-Host", "", 40},
116 {"hostaddr", "PGHOSTADDR", NULL, NULL,
117 "Database-Host-IP-Address", "", 45},
119 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
120 "Database-Port", "", 6},
123 * "tty" is no longer used either, but keep it present for backwards
126 {"tty", "PGTTY", DefaultTty, NULL,
127 "Backend-Debug-TTY", "D", 40},
129 {"options", "PGOPTIONS", DefaultOption, NULL,
130 "Backend-Debug-Options", "D", 40},
133 {"requiressl", "PGREQUIRESSL", "0", NULL,
134 "Require-SSL", "", 1},
137 /* Terminating entry --- MUST BE LAST */
138 {NULL, NULL, NULL, NULL,
142 static const PQEnvironmentOption EnvironmentOptions[] =
144 /* common user-interface settings */
146 "PGDATESTYLE", "datestyle"
152 "PGCLIENTENCODING", "client_encoding"
154 /* internal performance-related settings */
164 static bool connectOptions1(PGconn *conn, const char *conninfo);
165 static bool connectOptions2(PGconn *conn);
166 static int connectDBStart(PGconn *conn);
167 static int connectDBComplete(PGconn *conn);
168 static PGconn *makeEmptyPGconn(void);
169 static void freePGconn(PGconn *conn);
170 static void closePGconn(PGconn *conn);
171 static PQconninfoOption *conninfo_parse(const char *conninfo,
172 PQExpBuffer errorMessage);
173 static char *conninfo_getval(PQconninfoOption *connOptions,
174 const char *keyword);
175 static void defaultNoticeProcessor(void *arg, const char *message);
176 static int parseServiceInfo(PQconninfoOption *options,
177 PQExpBuffer errorMessage);
178 static char *pwdfMatchesString(char *buf, char *token);
179 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
183 * Connecting to a Database
185 * There are now four different ways a user of this API can connect to the
186 * database. Two are not recommended for use in new code, because of their
187 * lack of extensibility with respect to the passing of options to the
188 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
191 * If it is desired to connect in a synchronous (blocking) manner, use the
192 * function PQconnectdb.
194 * To connect in an asynchronous (non-blocking) manner, use the functions
195 * PQconnectStart, and PQconnectPoll.
197 * Internally, the static functions connectDBStart, connectDBComplete
198 * are part of the connection procedure.
204 * establishes a connection to a postgres backend through the postmaster
205 * using connection information in a string.
207 * The conninfo string is a white-separated list of
211 * definitions. Value might be a single value containing no whitespaces or
212 * a single quoted string. If a single quote should appear anywhere in
213 * the value, it must be escaped with a backslash like \'
215 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
216 * if a memory allocation failed.
217 * If the status field of the connection returned is CONNECTION_BAD,
218 * then some fields may be null'ed out instead of having valid values.
220 * You should call PQfinish (if conn is not NULL) regardless of whether this
224 PQconnectdb(const char *conninfo)
226 PGconn *conn = PQconnectStart(conninfo);
228 if (conn && conn->status != CONNECTION_BAD)
229 (void) connectDBComplete(conn);
237 * Begins the establishment of a connection to a postgres backend through the
238 * postmaster using connection information in a string.
240 * See comment for PQconnectdb for the definition of the string format.
242 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
243 * you should not attempt to proceed with this connection. If the status
244 * field of the connection returned is CONNECTION_BAD, an error has
245 * occurred. In this case you should call PQfinish on the result, (perhaps
246 * inspecting the error message first). Other fields of the structure may not
247 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
248 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
251 * See PQconnectPoll for more info.
254 PQconnectStart(const char *conninfo)
259 * Allocate memory for the conn structure
261 conn = makeEmptyPGconn();
263 return (PGconn *) NULL;
266 * Parse the conninfo string
268 if (!connectOptions1(conn, conninfo))
272 * Compute derived options
274 if (!connectOptions2(conn))
278 * Connect to the database
280 if (!connectDBStart(conn))
282 /* Just in case we failed to set it in connectDBStart */
283 conn->status = CONNECTION_BAD;
292 * Internal subroutine to set up connection parameters given an already-
293 * created PGconn and a conninfo string. Derived settings should be
294 * processed by calling connectOptions2 next. (We split them because
295 * PQsetdbLogin overrides defaults in between.)
297 * Returns true if OK, false if trouble (in which case errorMessage is set
298 * and so is conn->status).
301 connectOptions1(PGconn *conn, const char *conninfo)
303 PQconninfoOption *connOptions;
307 * Parse the conninfo string
309 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
310 if (connOptions == NULL)
312 conn->status = CONNECTION_BAD;
313 /* errorMessage is already set */
318 * Move option values into conn structure
320 * Don't put anything cute here --- intelligence should be in
321 * connectOptions2 ...
323 tmp = conninfo_getval(connOptions, "hostaddr");
324 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
325 tmp = conninfo_getval(connOptions, "host");
326 conn->pghost = tmp ? strdup(tmp) : NULL;
327 tmp = conninfo_getval(connOptions, "port");
328 conn->pgport = tmp ? strdup(tmp) : NULL;
329 tmp = conninfo_getval(connOptions, "tty");
330 conn->pgtty = tmp ? strdup(tmp) : NULL;
331 tmp = conninfo_getval(connOptions, "options");
332 conn->pgoptions = tmp ? strdup(tmp) : NULL;
333 tmp = conninfo_getval(connOptions, "dbname");
334 conn->dbName = tmp ? strdup(tmp) : NULL;
335 tmp = conninfo_getval(connOptions, "user");
336 conn->pguser = tmp ? strdup(tmp) : NULL;
337 tmp = conninfo_getval(connOptions, "password");
338 conn->pgpass = tmp ? strdup(tmp) : NULL;
339 tmp = conninfo_getval(connOptions, "connect_timeout");
340 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
342 tmp = conninfo_getval(connOptions, "requiressl");
343 if (tmp && tmp[0] == '1')
344 conn->require_ssl = true;
348 * Free the option info - all is in conn now
350 PQconninfoFree(connOptions);
358 * Compute derived connection options after absorbing all user-supplied info.
360 * Returns true if OK, false if trouble (in which case errorMessage is set
361 * and so is conn->status).
364 connectOptions2(PGconn *conn)
367 * If database name was not given, default it to equal user name
369 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
370 && conn->pguser != NULL)
374 conn->dbName = strdup(conn->pguser);
378 * Supply default password if none given
380 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
384 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
385 conn->dbName, conn->pguser);
386 if (conn->pgpass == NULL)
387 conn->pgpass = strdup(DefaultPassword);
391 * Allow unix socket specification in the host name
393 if (conn->pghost && is_absolute_path(conn->pghost))
395 if (conn->pgunixsocket)
396 free(conn->pgunixsocket);
397 conn->pgunixsocket = conn->pghost;
403 * parse dbName to get all additional info in it, if any
405 if (update_db_info(conn) != 0)
407 conn->status = CONNECTION_BAD;
408 /* errorMessage is already set */
419 * Parse an empty string like PQconnectdb() would do and return the
420 * working connection options array.
422 * Using this function, an application may determine all possible options
423 * and their current default values.
425 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
426 * and should be freed when no longer needed via PQconninfoFree(). (In prior
427 * versions, the returned array was static, but that's not thread-safe.)
428 * Pre-7.0 applications that use this function will see a small memory leak
429 * until they are updated to call PQconninfoFree.
434 PQExpBufferData errorBuf;
435 PQconninfoOption *connOptions;
437 initPQExpBuffer(&errorBuf);
438 connOptions = conninfo_parse("", &errorBuf);
439 termPQExpBuffer(&errorBuf);
446 * establishes a connection to a postgres backend through the postmaster
447 * at the specified host and port.
449 * returns a PGconn* which is needed for all subsequent libpq calls
451 * if the status field of the connection returned is CONNECTION_BAD,
452 * then only the errorMessage is likely to be useful.
456 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
457 const char *pgtty, const char *dbName, const char *login,
463 * Allocate memory for the conn structure
465 conn = makeEmptyPGconn();
467 return (PGconn *) NULL;
470 * Parse an empty conninfo string in order to set up the same defaults
471 * that PQconnectdb() would use.
473 if (!connectOptions1(conn, ""))
477 * Absorb specified options into conn structure, overriding defaults
479 if (pghost && pghost[0] != '\0')
483 conn->pghost = strdup(pghost);
486 if (pgport && pgport[0] != '\0')
490 conn->pgport = strdup(pgport);
493 if (pgoptions && pgoptions[0] != '\0')
496 free(conn->pgoptions);
497 conn->pgoptions = strdup(pgoptions);
500 if (pgtty && pgtty[0] != '\0')
504 conn->pgtty = strdup(pgtty);
507 if (dbName && dbName[0] != '\0')
511 conn->dbName = strdup(dbName);
514 if (login && login[0] != '\0')
518 conn->pguser = strdup(login);
521 if (pwd && pwd[0] != '\0')
525 conn->pgpass = strdup(pwd);
529 * Compute derived options
531 if (!connectOptions2(conn))
535 * Connect to the database
537 if (connectDBStart(conn))
538 (void) connectDBComplete(conn);
544 #ifdef NOT_USED /* because it's broken */
547 * get all additional info out of dbName
550 update_db_info(PGconn *conn)
556 if (strchr(conn->dbName, '@') != NULL)
558 /* old style: dbname[@server][:port] */
559 tmp = strrchr(conn->dbName, ':');
560 if (tmp != NULL) /* port number given */
564 conn->pgport = strdup(tmp + 1);
568 tmp = strrchr(conn->dbName, '@');
569 if (tmp != NULL) /* host name given */
573 conn->pghost = strdup(tmp + 1);
577 conn->dbName = strdup(old);
585 * only allow protocols tcp and unix
587 if (strncmp(conn->dbName, "tcp:", 4) == 0)
589 else if (strncmp(conn->dbName, "unix:", 5) == 0)
594 if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
599 * <tcp|unix>:postgresql://server[:port|:/unixsocket/path:]
600 * [/db name][?options]
603 offset += strlen("postgresql://");
605 tmp = strrchr(conn->dbName + offset, '?');
606 if (tmp != NULL) /* options given */
609 free(conn->pgoptions);
610 conn->pgoptions = strdup(tmp + 1);
614 tmp = last_path_separator(conn->dbName + offset);
615 if (tmp != NULL) /* database name given */
619 conn->dbName = strdup(tmp + 1);
625 * Why do we default only this value from the environment
628 if ((tmp = getenv("PGDATABASE")) != NULL)
632 conn->dbName = strdup(tmp);
634 else if (conn->pguser)
638 conn->dbName = strdup(conn->pguser);
642 tmp = strrchr(old + offset, ':');
643 if (tmp != NULL) /* port number or Unix socket path given */
646 if ((tmp2 = strchr(tmp + 1, ':')) != NULL)
648 if (strncmp(old, "unix:", 5) != 0)
650 printfPQExpBuffer(&conn->errorMessage,
651 "connectDBStart() -- "
652 "socket name can only be specified with "
657 if (conn->pgunixsocket)
658 free(conn->pgunixsocket);
659 conn->pgunixsocket = strdup(tmp + 1);
665 conn->pgport = strdup(tmp + 1);
666 if (conn->pgunixsocket)
667 free(conn->pgunixsocket);
668 conn->pgunixsocket = NULL;
672 if (strncmp(old, "unix:", 5) == 0)
677 if (strcmp(old + offset, "localhost") != 0)
679 printfPQExpBuffer(&conn->errorMessage,
680 "connectDBStart() -- "
681 "non-TCP access only possible on "
690 conn->pghost = strdup(old + offset);
698 #endif /* NOT_USED */
702 * connectMakeNonblocking -
703 * Make a connection non-blocking.
704 * Returns 1 if successful, 0 if not.
708 connectMakeNonblocking(PGconn *conn)
710 if (FCNTL_NONBLOCK(conn->sock) < 0)
712 printfPQExpBuffer(&conn->errorMessage,
713 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
714 SOCK_STRERROR(SOCK_ERRNO));
723 * Sets the TCP_NODELAY socket option.
724 * Returns 1 if successful, 0 if not.
728 connectNoDelay(PGconn *conn)
733 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
737 printfPQExpBuffer(&conn->errorMessage,
738 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
739 SOCK_STRERROR(SOCK_ERRNO));
749 * connectFailureMessage -
750 * create a friendly error message on connection failure.
754 connectFailureMessage(PGconn *conn, int errorno)
756 char hostname[NI_MAXHOST];
757 char service[NI_MAXHOST];
759 getnameinfo((struct sockaddr *)&conn->raddr.addr, conn->raddr.salen,
760 hostname, sizeof(hostname), service, sizeof(service),
761 NI_NUMERICHOST | NI_NUMERICSERV);
762 if (conn->raddr.addr.ss_family == AF_UNIX)
763 printfPQExpBuffer(&conn->errorMessage,
765 "could not connect to server: %s\n"
766 "\tIs the server running locally and accepting\n"
767 "\tconnections on Unix domain socket \"%s\"?\n"
769 SOCK_STRERROR(errorno), service);
771 printfPQExpBuffer(&conn->errorMessage,
773 "could not connect to server: %s\n"
774 "\tIs the server running on host %s and accepting\n"
775 "\tTCP/IP connections on port %s?\n"
777 SOCK_STRERROR(errorno),
789 * Begin the process of making a connection to the backend.
791 * Returns 1 if successful, 0 if not.
795 connectDBStart(PGconn *conn)
799 struct addrinfo *addrs = NULL;
800 struct addrinfo hint;
801 const char *node = NULL;
807 /* Ensure our buffers are empty */
808 conn->inStart = conn->inCursor = conn->inEnd = 0;
812 * Determine the parameters to pass to getaddrinfo2.
815 /* Initialize hint structure */
816 MemSet(&hint, 0, sizeof(hint));
817 hint.ai_socktype = SOCK_STREAM;
818 hint.ai_family = AF_UNSPEC;
820 /* Set up port number as a string */
821 if (conn->pgport != NULL && conn->pgport[0] != '\0')
822 portnum = atoi(conn->pgport);
824 portnum = DEF_PGPORT;
825 snprintf(portstr, sizeof(portstr), "%d", portnum);
827 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
829 /* Using pghostaddr avoids a hostname lookup */
830 node = conn->pghostaddr;
831 hint.ai_family = AF_UNSPEC;
832 hint.ai_flags = AI_NUMERICHOST;
834 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
836 /* Using pghost, so we have to look-up the hostname */
838 hint.ai_family = AF_UNSPEC;
840 #ifdef HAVE_UNIX_SOCKETS
843 /* pghostaddr and pghost are NULL, so use Unix domain socket */
845 hint.ai_family = AF_UNIX;
846 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
848 #endif /* HAVE_UNIX_SOCKETS */
850 /* Use getaddrinfo2() to resolve the address */
851 ret = getaddrinfo2(node, portstr, &hint, &addrs);
852 if (ret || addrs == NULL)
854 printfPQExpBuffer(&conn->errorMessage,
855 libpq_gettext("getaddrinfo() failed: %s\n"),
857 freeaddrinfo2(hint.ai_family, addrs);
858 goto connect_errReturn;
862 * Set up to try to connect, with protocol 3.0 as the first attempt.
864 conn->addrlist = addrs;
865 conn->addr_cur = addrs;
866 conn->addrlist_family = hint.ai_family;
867 conn->pversion = PG_PROTOCOL(3,0);
868 conn->status = CONNECTION_NEEDED;
871 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
872 * so that it can easily be re-executed if needed again during the
873 * asynchronous startup process. However, we must run it once here,
874 * because callers expect a success return from this routine to mean
875 * that we are in PGRES_POLLING_WRITING connection state.
877 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
883 pqsecure_close(conn);
884 closesocket(conn->sock);
887 conn->status = CONNECTION_BAD;
895 * Block and complete a connection.
897 * Returns 1 on success, 0 on failure.
900 connectDBComplete(PGconn *conn)
902 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
903 time_t finish_time = ((time_t) -1);
905 if (conn == NULL || conn->status == CONNECTION_BAD)
909 * Set up a time limit, if connect_timeout isn't zero.
911 if (conn->connect_timeout != NULL)
913 int timeout = atoi(conn->connect_timeout);
918 * Rounding could cause connection to fail; need at least 2
923 /* calculate the finish time based on start + timeout */
924 finish_time = time(NULL) + timeout;
931 * Wait, if necessary. Note that the initial state (just after
932 * PQconnectStart) is to wait for the socket to select for
937 case PGRES_POLLING_OK:
938 return 1; /* success! */
940 case PGRES_POLLING_READING:
941 if (pqWaitTimed(1, 0, conn, finish_time))
943 conn->status = CONNECTION_BAD;
948 case PGRES_POLLING_WRITING:
949 if (pqWaitTimed(0, 1, conn, finish_time))
951 conn->status = CONNECTION_BAD;
957 /* Just in case we failed to set it in PQconnectPoll */
958 conn->status = CONNECTION_BAD;
963 * Now try to advance the state machine.
965 flag = PQconnectPoll(conn);
972 * Poll an asynchronous connection.
974 * Returns a PostgresPollingStatusType.
975 * Before calling this function, use select(2) to determine when data
978 * You must call PQfinish whether or not this fails.
980 * This function and PQconnectStart are intended to allow connections to be
981 * made without blocking the execution of your program on remote I/O. However,
982 * there are a number of caveats:
984 * o If you call PQtrace, ensure that the stream object into which you trace
986 * o If you do not supply an IP address for the remote host (i.e. you
987 * supply a host name instead) then PQconnectStart will block on
988 * gethostbyname. You will be fine if using Unix sockets (i.e. by
989 * supplying neither a host name nor a host address).
990 * o If your backend wants to use Kerberos authentication then you must
991 * supply both a host name and a host address, otherwise this function
992 * may block on gethostname.
996 PostgresPollingStatusType
997 PQconnectPoll(PGconn *conn)
1002 return PGRES_POLLING_FAILED;
1004 /* Get the new data */
1005 switch (conn->status)
1008 * We really shouldn't have been polled in these two cases,
1009 * but we can handle it.
1011 case CONNECTION_BAD:
1012 return PGRES_POLLING_FAILED;
1014 return PGRES_POLLING_OK;
1016 /* These are reading states */
1017 case CONNECTION_AWAITING_RESPONSE:
1018 case CONNECTION_AUTH_OK:
1020 /* Load waiting data */
1021 int n = pqReadData(conn);
1026 return PGRES_POLLING_READING;
1031 /* These are writing states, so we just proceed. */
1032 case CONNECTION_STARTED:
1033 case CONNECTION_MADE:
1036 /* We allow pqSetenvPoll to decide whether to proceed. */
1037 case CONNECTION_SETENV:
1040 /* Special cases: proceed without waiting. */
1041 case CONNECTION_SSL_STARTUP:
1042 case CONNECTION_NEEDED:
1046 printfPQExpBuffer(&conn->errorMessage,
1048 "invalid connection state, "
1049 "probably indicative of memory corruption\n"
1055 keep_going: /* We will come back to here until there
1056 * is nothing left to do. */
1057 switch (conn->status)
1059 case CONNECTION_NEEDED:
1062 * Try to initiate a connection to one of the addresses
1063 * returned by getaddrinfo2(). conn->addr_cur is the
1064 * next one to try. We fail when we run out of addresses
1065 * (reporting the error returned for the *last* alternative,
1066 * which may not be what users expect :-().
1068 while (conn->addr_cur != NULL)
1070 struct addrinfo *addr_cur = conn->addr_cur;
1072 /* Remember current address for possible error msg */
1073 memcpy(&conn->raddr, addr_cur->ai_addr,
1074 addr_cur->ai_addrlen);
1077 conn->sock = socket(addr_cur->ai_family,
1078 addr_cur->ai_socktype,
1079 addr_cur->ai_protocol);
1083 * ignore socket() failure if we have more addresses
1086 if (addr_cur->ai_next != NULL)
1088 conn->addr_cur = addr_cur->ai_next;
1091 printfPQExpBuffer(&conn->errorMessage,
1092 libpq_gettext("could not create socket: %s\n"),
1093 SOCK_STRERROR(SOCK_ERRNO));
1098 * Select socket options: no delay of outgoing data for
1099 * TCP sockets, and nonblock mode. Fail if this fails.
1101 if (!IS_AF_UNIX(addr_cur->ai_family))
1103 if (!connectNoDelay(conn))
1105 closesocket(conn->sock);
1107 conn->addr_cur = addr_cur->ai_next;
1111 if (connectMakeNonblocking(conn) == 0)
1113 closesocket(conn->sock);
1115 conn->addr_cur = addr_cur->ai_next;
1119 * Start/make connection. This should not block, since
1120 * we are in nonblock mode. If it does, well, too bad.
1123 if (connect(conn->sock, addr_cur->ai_addr,
1124 addr_cur->ai_addrlen) < 0)
1126 if (SOCK_ERRNO == EINTR)
1127 /* Interrupted system call - just try again */
1129 if (SOCK_ERRNO == EINPROGRESS ||
1130 SOCK_ERRNO == EWOULDBLOCK ||
1134 * This is fine - we're in non-blocking mode,
1135 * and the connection is in progress. Tell
1136 * caller to wait for write-ready on socket.
1138 conn->status = CONNECTION_STARTED;
1139 return PGRES_POLLING_WRITING;
1141 /* otherwise, trouble */
1146 * Hm, we're connected already --- seems the
1147 * "nonblock connection" wasn't. Advance the state
1148 * machine and go do the next stuff.
1150 conn->status = CONNECTION_STARTED;
1154 * This connection failed --- set up error report,
1155 * then close socket (do it this way in case close()
1156 * affects the value of errno...). We will ignore the
1157 * connect() failure and keep going if there are
1160 connectFailureMessage(conn, SOCK_ERRNO);
1161 if (conn->sock >= 0)
1163 closesocket(conn->sock);
1167 * Try the next address, if any.
1169 conn->addr_cur = addr_cur->ai_next;
1170 } /* loop over addresses */
1173 * Ooops, no more addresses. An appropriate error message
1174 * is already set up, so just set the right status.
1179 case CONNECTION_STARTED:
1182 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1185 * Write ready, since we've made it here, so the
1186 * connection has been made ... or has failed.
1190 * Now check (using getsockopt) that there is not an error
1191 * state waiting for us on the socket.
1194 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1195 (char *) &optval, &optlen) == -1)
1197 printfPQExpBuffer(&conn->errorMessage,
1198 libpq_gettext("could not get socket error status: %s\n"),
1199 SOCK_STRERROR(SOCK_ERRNO));
1202 else if (optval != 0)
1205 * When using a nonblocking connect, we will typically
1206 * see connect failures at this point, so provide a
1207 * friendly error message.
1209 connectFailureMessage(conn, optval);
1211 * If more addresses remain, keep trying, just as in
1212 * the case where connect() returned failure immediately.
1214 if (conn->addr_cur->ai_next != NULL)
1216 if (conn->sock >= 0)
1218 closesocket(conn->sock);
1221 conn->addr_cur = conn->addr_cur->ai_next;
1222 conn->status = CONNECTION_NEEDED;
1228 /* Fill in the client address */
1229 conn->laddr.salen = sizeof(conn->laddr.addr);
1230 if (getsockname(conn->sock,
1231 (struct sockaddr *)&conn->laddr.addr,
1232 &conn->laddr.salen) < 0)
1234 printfPQExpBuffer(&conn->errorMessage,
1235 libpq_gettext("could not get client address from socket: %s\n"),
1236 SOCK_STRERROR(SOCK_ERRNO));
1241 * Make sure we can write before advancing to next step.
1243 conn->status = CONNECTION_MADE;
1244 return PGRES_POLLING_WRITING;
1247 case CONNECTION_MADE:
1254 * If SSL is enabled and we haven't already got it running,
1255 * request it instead of sending the startup message.
1258 #ifdef HAVE_UNIX_SOCKETS
1259 if (conn->raddr.addr.ss_family == AF_UNIX)
1261 /* Don't bother requesting SSL over a Unix socket */
1262 conn->allow_ssl_try = false;
1263 conn->require_ssl = false;
1266 if (conn->allow_ssl_try && conn->ssl == NULL)
1271 * Send the SSL request packet.
1273 * Theoretically, this could block, but it really shouldn't
1274 * since we only got here if the socket is write-ready.
1276 pv = htonl(NEGOTIATE_SSL_CODE);
1277 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1279 printfPQExpBuffer(&conn->errorMessage,
1280 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1281 SOCK_STRERROR(SOCK_ERRNO));
1284 /* Ok, wait for response */
1285 conn->status = CONNECTION_SSL_STARTUP;
1286 return PGRES_POLLING_READING;
1288 #endif /* USE_SSL */
1291 * Build the startup packet.
1293 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1294 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1295 EnvironmentOptions);
1297 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1298 EnvironmentOptions);
1301 printfPQExpBuffer(&conn->errorMessage,
1302 libpq_gettext("out of memory\n"));
1307 * Send the startup packet.
1309 * Theoretically, this could block, but it really shouldn't
1310 * since we only got here if the socket is write-ready.
1312 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1314 printfPQExpBuffer(&conn->errorMessage,
1315 libpq_gettext("could not send startup packet: %s\n"),
1316 SOCK_STRERROR(SOCK_ERRNO));
1323 conn->status = CONNECTION_AWAITING_RESPONSE;
1324 return PGRES_POLLING_READING;
1328 * Handle SSL negotiation: wait for postmaster
1329 * messages and respond as necessary.
1331 case CONNECTION_SSL_STARTUP:
1334 PostgresPollingStatusType pollres;
1337 * On first time through, get the postmaster's response
1338 * to our SSL negotiation packet. Be careful to read only
1339 * one byte (if there's more, it could be SSL data).
1341 if (conn->ssl == NULL)
1347 nread = recv(conn->sock, &SSLok, 1, 0);
1350 if (SOCK_ERRNO == EINTR)
1351 /* Interrupted system call - just try again */
1352 goto retry_ssl_read;
1354 printfPQExpBuffer(&conn->errorMessage,
1355 libpq_gettext("could not receive server response to SSL negotiation packet: %s\n"),
1356 SOCK_STRERROR(SOCK_ERRNO));
1360 /* caller failed to wait for data */
1361 return PGRES_POLLING_READING;
1364 /* Do one-time setup; this creates conn->ssl */
1365 if (pqsecure_initialize(conn) == -1)
1368 else if (SSLok == 'N')
1370 if (conn->require_ssl)
1372 /* Require SSL, but server does not want it */
1373 printfPQExpBuffer(&conn->errorMessage,
1374 libpq_gettext("server does not support SSL, but SSL was required\n"));
1377 /* Otherwise, proceed with normal startup */
1378 conn->allow_ssl_try = false;
1379 conn->status = CONNECTION_MADE;
1380 return PGRES_POLLING_WRITING;
1382 else if (SSLok == 'E')
1384 /* Received error - probably protocol mismatch */
1386 fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-7.0.\n");
1387 if (conn->require_ssl)
1389 /* Require SSL, but server is too old */
1390 printfPQExpBuffer(&conn->errorMessage,
1391 libpq_gettext("server does not support SSL, but SSL was required\n"));
1394 /* Otherwise, try again without SSL */
1395 conn->allow_ssl_try = false;
1396 /* Assume it ain't gonna handle protocol 3, either */
1397 conn->pversion = PG_PROTOCOL(2,0);
1398 /* Must drop the old connection */
1399 closesocket(conn->sock);
1401 conn->status = CONNECTION_NEEDED;
1406 printfPQExpBuffer(&conn->errorMessage,
1407 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1413 * Begin or continue the SSL negotiation process.
1415 pollres = pqsecure_open_client(conn);
1416 if (pollres == PGRES_POLLING_OK)
1418 /* SSL handshake done, ready to send startup packet */
1419 conn->status = CONNECTION_MADE;
1420 return PGRES_POLLING_WRITING;
1423 #else /* !USE_SSL */
1424 /* can't get here */
1426 #endif /* USE_SSL */
1430 * Handle authentication exchange: wait for postmaster
1431 * messages and respond as necessary.
1433 case CONNECTION_AWAITING_RESPONSE:
1441 * Scan the message from current point (note that if we
1442 * find the message is incomplete, we will return without
1443 * advancing inStart, and resume here next time).
1445 conn->inCursor = conn->inStart;
1447 /* Read type byte */
1448 if (pqGetc(&beresp, conn))
1450 /* We'll come back when there is more data */
1451 return PGRES_POLLING_READING;
1455 * Validate message type: we expect only an authentication
1456 * request or an error here. Anything else probably means
1457 * it's not Postgres on the other end at all.
1459 if (!(beresp == 'R' || beresp == 'E'))
1461 printfPQExpBuffer(&conn->errorMessage,
1463 "expected authentication request from "
1464 "server, but received %c\n"),
1469 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1471 /* Read message length word */
1472 if (pqGetInt(&msgLength, 4, conn))
1474 /* We'll come back when there is more data */
1475 return PGRES_POLLING_READING;
1480 /* Set phony message length to disable checks below */
1485 * Try to validate message length before using it.
1486 * Authentication requests can't be very large. Errors
1487 * can be a little larger, but not huge. If we see a large
1488 * apparent length in an error, it means we're really talking
1489 * to a pre-3.0-protocol server; cope.
1491 if (beresp == 'R' && (msgLength < 8 || msgLength > 100))
1493 printfPQExpBuffer(&conn->errorMessage,
1495 "expected authentication request from "
1496 "server, but received %c\n"),
1501 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1503 /* Handle error from a pre-3.0 server */
1504 conn->inCursor = conn->inStart + 1; /* reread data */
1505 if (pqGets(&conn->errorMessage, conn))
1507 /* We'll come back when there is more data */
1508 return PGRES_POLLING_READING;
1510 /* OK, we read the message; mark data consumed */
1511 conn->inStart = conn->inCursor;
1514 * The postmaster typically won't end its message with
1515 * a newline, so add one to conform to libpq
1518 appendPQExpBufferChar(&conn->errorMessage, '\n');
1521 * If we tried to open the connection in 3.0 protocol,
1522 * fall back to 2.0 protocol.
1524 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1526 conn->pversion = PG_PROTOCOL(2,0);
1527 /* Must drop the old connection */
1528 pqsecure_close(conn);
1529 closesocket(conn->sock);
1531 conn->status = CONNECTION_NEEDED;
1539 * Can't process if message body isn't all here yet.
1541 * (In protocol 2.0 case, we are assuming messages carry
1542 * at least 4 bytes of data.)
1545 avail = conn->inEnd - conn->inCursor;
1546 if (avail < msgLength)
1549 * Before returning, try to enlarge the input buffer if
1550 * needed to hold the whole message; see notes in
1553 if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
1555 /* We'll come back when there is more data */
1556 return PGRES_POLLING_READING;
1559 /* Handle errors. */
1562 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1564 if (pqGetErrorNotice3(conn, true))
1566 /* We'll come back when there is more data */
1567 return PGRES_POLLING_READING;
1572 if (pqGets(&conn->errorMessage, conn))
1574 /* We'll come back when there is more data */
1575 return PGRES_POLLING_READING;
1578 /* OK, we read the message; mark data consumed */
1579 conn->inStart = conn->inCursor;
1583 /* It is an authentication request. */
1584 /* Get the type of request. */
1585 if (pqGetInt((int *) &areq, 4, conn))
1587 /* We'll come back when there are more data */
1588 return PGRES_POLLING_READING;
1591 /* Get the password salt if there is one. */
1592 if (areq == AUTH_REQ_MD5)
1594 if (pqGetnchar(conn->md5Salt,
1595 sizeof(conn->md5Salt), conn))
1597 /* We'll come back when there are more data */
1598 return PGRES_POLLING_READING;
1601 if (areq == AUTH_REQ_CRYPT)
1603 if (pqGetnchar(conn->cryptSalt,
1604 sizeof(conn->cryptSalt), conn))
1606 /* We'll come back when there are more data */
1607 return PGRES_POLLING_READING;
1612 * OK, we successfully read the message; mark data
1615 conn->inStart = conn->inCursor;
1617 /* Respond to the request if necessary. */
1620 * Note that conn->pghost must be non-NULL if we are going
1621 * to avoid the Kerberos code doing a hostname look-up.
1625 * XXX fe-auth.c has not been fixed to support
1628 if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1629 conn->errorMessage.data) != STATUS_OK)
1631 conn->errorMessage.len = strlen(conn->errorMessage.data);
1634 conn->errorMessage.len = strlen(conn->errorMessage.data);
1637 * Just make sure that any data sent by fe_sendauth is
1638 * flushed out. Although this theoretically could block,
1639 * it really shouldn't since we don't send large auth
1645 if (areq == AUTH_REQ_OK)
1647 /* We are done with authentication exchange */
1648 conn->status = CONNECTION_AUTH_OK;
1651 * Set asyncStatus so that PQsetResult will think that
1652 * what comes back next is the result of a query. See
1655 conn->asyncStatus = PGASYNC_BUSY;
1658 /* Look to see if we have more data yet. */
1662 case CONNECTION_AUTH_OK:
1665 * Now we expect to hear from the backend. A ReadyForQuery
1666 * message indicates that startup is successful, but we
1667 * might also get an Error message indicating failure.
1668 * (Notice messages indicating nonfatal warnings are also
1669 * allowed by the protocol, as are ParameterStatus and
1670 * BackendKeyData messages.) Easiest way to handle this is
1671 * to let PQgetResult() read the messages. We just have to
1672 * fake it out about the state of the connection, by setting
1673 * asyncStatus = PGASYNC_BUSY (done above).
1677 return PGRES_POLLING_READING;
1679 res = PQgetResult(conn);
1682 * NULL return indicating we have gone to IDLE state is
1687 if (res->resultStatus != PGRES_FATAL_ERROR)
1688 printfPQExpBuffer(&conn->errorMessage,
1689 libpq_gettext("unexpected message from server during startup\n"));
1692 * if the resultStatus is FATAL, then
1693 * conn->errorMessage already has a copy of the error;
1694 * needn't copy it back. But add a newline if it's not
1695 * there already, since postmaster error messages may
1698 if (conn->errorMessage.len <= 0 ||
1699 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1700 appendPQExpBufferChar(&conn->errorMessage, '\n');
1705 /* We can release the address list now. */
1706 freeaddrinfo2(conn->addrlist_family, conn->addrlist);
1707 conn->addrlist = NULL;
1708 conn->addr_cur = NULL;
1710 /* Fire up post-connection housekeeping if needed */
1711 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1713 conn->status = CONNECTION_SETENV;
1714 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1715 conn->next_eo = EnvironmentOptions;
1716 return PGRES_POLLING_WRITING;
1719 /* Otherwise, we are open for business! */
1720 conn->status = CONNECTION_OK;
1721 return PGRES_POLLING_OK;
1724 case CONNECTION_SETENV:
1727 * Do post-connection housekeeping (only needed in protocol 2.0).
1729 * We pretend that the connection is OK for the duration of
1732 conn->status = CONNECTION_OK;
1734 switch (pqSetenvPoll(conn))
1736 case PGRES_POLLING_OK: /* Success */
1739 case PGRES_POLLING_READING: /* Still going */
1740 conn->status = CONNECTION_SETENV;
1741 return PGRES_POLLING_READING;
1743 case PGRES_POLLING_WRITING: /* Still going */
1744 conn->status = CONNECTION_SETENV;
1745 return PGRES_POLLING_WRITING;
1751 /* We are open for business! */
1752 conn->status = CONNECTION_OK;
1753 return PGRES_POLLING_OK;
1756 printfPQExpBuffer(&conn->errorMessage,
1758 "invalid connection state %c, "
1759 "probably indicative of memory corruption\n"
1770 * We used to close the socket at this point, but that makes it
1771 * awkward for those above us if they wish to remove this socket from
1772 * their own records (an fd_set for example). We'll just have this
1773 * socket closed when PQfinish is called (which is compulsory even
1774 * after an error, since the connection structure must be freed).
1776 conn->status = CONNECTION_BAD;
1777 return PGRES_POLLING_FAILED;
1783 * - create a PGconn data structure with (as yet) no interesting data
1786 makeEmptyPGconn(void)
1788 PGconn *conn = (PGconn *) malloc(sizeof(PGconn));
1793 /* Zero all pointers and booleans */
1794 MemSet((char *) conn, 0, sizeof(PGconn));
1796 conn->noticeHook = defaultNoticeProcessor;
1797 conn->status = CONNECTION_BAD;
1798 conn->asyncStatus = PGASYNC_IDLE;
1799 conn->setenv_state = SETENV_STATE_IDLE;
1800 conn->client_encoding = PG_SQL_ASCII;
1801 conn->notifyList = DLNewList();
1804 conn->allow_ssl_try = TRUE;
1808 * We try to send at least 8K at a time, which is the usual size
1809 * of pipe buffers on Unix systems. That way, when we are sending a
1810 * large amount of data, we avoid incurring extra kernel context swaps
1811 * for partial bufferloads. The output buffer is initially made 16K
1812 * in size, and we try to dump it after accumulating 8K.
1814 * With the same goal of minimizing context swaps, the input buffer will
1815 * be enlarged anytime it has less than 8K free, so we initially
1816 * allocate twice that.
1818 conn->inBufSize = 16 * 1024;
1819 conn->inBuffer = (char *) malloc(conn->inBufSize);
1820 conn->outBufSize = 16 * 1024;
1821 conn->outBuffer = (char *) malloc(conn->outBufSize);
1822 conn->nonblocking = FALSE;
1823 initPQExpBuffer(&conn->errorMessage);
1824 initPQExpBuffer(&conn->workBuffer);
1826 if (conn->inBuffer == NULL ||
1827 conn->outBuffer == NULL ||
1828 conn->errorMessage.data == NULL ||
1829 conn->workBuffer.data == NULL)
1831 /* out of memory already :-( */
1841 * - free the PGconn data structure
1845 freePGconn(PGconn *conn)
1849 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1850 if (conn->sock >= 0)
1852 pqsecure_close(conn);
1853 closesocket(conn->sock);
1857 if (conn->pghostaddr)
1858 free(conn->pghostaddr);
1861 if (conn->pgunixsocket)
1862 free(conn->pgunixsocket);
1865 if (conn->connect_timeout)
1866 free(conn->connect_timeout);
1867 if (conn->pgoptions)
1868 free(conn->pgoptions);
1875 /* Note that conn->Pfdebug is not ours to close or free */
1876 if (conn->notifyList)
1877 DLFreeList(conn->notifyList);
1878 freeaddrinfo2(conn->addrlist_family, conn->addrlist);
1879 if (conn->lobjfuncs)
1880 free(conn->lobjfuncs);
1882 free(conn->inBuffer);
1883 if (conn->outBuffer)
1884 free(conn->outBuffer);
1885 termPQExpBuffer(&conn->errorMessage);
1886 termPQExpBuffer(&conn->workBuffer);
1892 - properly close a connection to the backend
1895 closePGconn(PGconn *conn)
1898 * Note that the protocol doesn't allow us to send Terminate messages
1899 * during the startup phase.
1901 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1904 * Try to send "close connection" message to backend. Ignore any
1907 pqPutMsgStart('X', false, conn);
1913 * must reset the blocking status so a possible reconnect will work
1914 * don't call PQsetnonblocking() because it will fail if it's unable
1915 * to flush the connection.
1917 conn->nonblocking = FALSE;
1920 * Close the connection, reset all transient state, flush I/O buffers.
1922 if (conn->sock >= 0)
1924 pqsecure_close(conn);
1925 closesocket(conn->sock);
1928 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
1930 conn->asyncStatus = PGASYNC_IDLE;
1931 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1932 if (conn->lobjfuncs)
1933 free(conn->lobjfuncs);
1934 conn->lobjfuncs = NULL;
1935 conn->inStart = conn->inCursor = conn->inEnd = 0;
1941 properly close a connection to the backend
1942 also frees the PGconn data structure so it shouldn't be re-used
1946 PQfinish(PGconn *conn)
1956 resets the connection to the backend
1957 closes the existing connection and makes a new one
1960 PQreset(PGconn *conn)
1966 if (connectDBStart(conn))
1967 (void) connectDBComplete(conn);
1973 resets the connection to the backend
1974 closes the existing connection and makes a new one
1975 Returns 1 on success, 0 on failure.
1978 PQresetStart(PGconn *conn)
1984 return connectDBStart(conn);
1992 resets the connection to the backend
1993 closes the existing connection and makes a new one
1996 PostgresPollingStatusType
1997 PQresetPoll(PGconn *conn)
2000 return PQconnectPoll(conn);
2002 return PGRES_POLLING_FAILED;
2007 * PQrequestCancel: attempt to request cancellation of the current operation.
2009 * The return value is TRUE if the cancel request was successfully
2010 * dispatched, FALSE if not (in which case conn->errorMessage is set).
2011 * Note: successful dispatch is no guarantee that there will be any effect at
2012 * the backend. The application must read the operation result as usual.
2014 * XXX it was a bad idea to have the error message returned in
2015 * conn->errorMessage, since it could overwrite a message already there.
2016 * Would be better to return it in a char array passed by the caller.
2018 * CAUTION: we want this routine to be safely callable from a signal handler
2019 * (for example, an application might want to call it in a SIGINT handler).
2020 * This means we cannot use any C library routine that might be non-reentrant.
2021 * malloc/free are often non-reentrant, and anything that might call them is
2022 * just as dangerous. We avoid sprintf here for that reason. Building up
2023 * error messages with strcpy/strcat is tedious but should be quite safe.
2024 * We also save/restore errno in case the signal handler support doesn't.
2026 * NOTE: this routine must not generate any error message longer than
2027 * INITIAL_EXPBUFFER_SIZE (currently 256), since we dare not try to
2028 * expand conn->errorMessage!
2032 PQrequestCancel(PGconn *conn)
2034 int save_errno = SOCK_ERRNO;
2039 CancelRequestPacket cp;
2042 /* Check we have an open connection */
2048 strcpy(conn->errorMessage.data,
2049 "PQrequestCancel() -- connection is not open\n");
2050 conn->errorMessage.len = strlen(conn->errorMessage.data);
2052 WSASetLastError(save_errno);
2060 * We need to open a temporary connection to the postmaster. Use the
2061 * information saved by connectDB to do this with only kernel calls.
2063 if ((tmpsock = socket(conn->raddr.addr.ss_family, SOCK_STREAM, 0)) < 0)
2065 strcpy(conn->errorMessage.data,
2066 "PQrequestCancel() -- socket() failed: ");
2067 goto cancel_errReturn;
2070 if (connect(tmpsock, (struct sockaddr *)&conn->raddr.addr,
2071 conn->raddr.salen) < 0)
2073 if (SOCK_ERRNO == EINTR)
2074 /* Interrupted system call - we'll just try again */
2076 strcpy(conn->errorMessage.data,
2077 "PQrequestCancel() -- connect() failed: ");
2078 goto cancel_errReturn;
2082 * We needn't set nonblocking I/O or NODELAY options here.
2085 /* Create and send the cancel request packet. */
2087 crp.packetlen = htonl((uint32) sizeof(crp));
2088 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2089 crp.cp.backendPID = htonl(conn->be_pid);
2090 crp.cp.cancelAuthCode = htonl(conn->be_key);
2093 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2095 if (SOCK_ERRNO == EINTR)
2096 /* Interrupted system call - we'll just try again */
2098 strcpy(conn->errorMessage.data,
2099 "PQrequestCancel() -- send() failed: ");
2100 goto cancel_errReturn;
2104 closesocket(tmpsock);
2106 WSASetLastError(save_errno);
2114 strcat(conn->errorMessage.data, SOCK_STRERROR(SOCK_ERRNO));
2115 strcat(conn->errorMessage.data, "\n");
2116 conn->errorMessage.len = strlen(conn->errorMessage.data);
2119 closesocket(tmpsock);
2121 WSASetLastError(save_errno);
2131 * pqPacketSend() -- convenience routine to send a message to server.
2133 * pack_type: the single-byte message type code. (Pass zero for startup
2134 * packets, which have no message type code.)
2136 * buf, buf_len: contents of message. The given length includes only what
2137 * is in buf; the message type and message length fields are added here.
2139 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2140 * SIDE_EFFECTS: may block.
2142 * Note: all messages sent with this routine have a length word, whether
2143 * it's protocol 2.0 or 3.0.
2146 pqPacketSend(PGconn *conn, char pack_type,
2147 const void *buf, size_t buf_len)
2149 /* Start the message. */
2150 if (pqPutMsgStart(pack_type, true, conn))
2151 return STATUS_ERROR;
2153 /* Send the message body. */
2154 if (pqPutnchar(buf, buf_len, conn))
2155 return STATUS_ERROR;
2157 /* Finish the message. */
2158 if (pqPutMsgEnd(conn))
2159 return STATUS_ERROR;
2161 /* Flush to ensure backend gets it. */
2163 return STATUS_ERROR;
2171 #error "You must compile this file with SYSCONFDIR defined."
2174 #define MAXBUFSIZE 256
2177 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2179 char *service = conninfo_getval(options, "service");
2180 char *serviceFile = SYSCONFDIR "/pg_service.conf";
2181 int group_found = 0;
2186 * We have to special-case the environment variable PGSERVICE here,
2187 * since this is and should be called before inserting environment
2188 * defaults for other connection options.
2190 if (service == NULL)
2191 service = getenv("PGSERVICE");
2193 if (service != NULL)
2196 char buf[MAXBUFSIZE],
2199 f = fopen(serviceFile, "r");
2202 printfPQExpBuffer(errorMessage, "ERROR: Service file '%s' not found\n",
2207 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2211 if (strlen(line) >= MAXBUFSIZE - 2)
2214 printfPQExpBuffer(errorMessage,
2215 "ERROR: line %d too long in service file '%s'\n",
2221 /* ignore EOL at end of line */
2222 if (strlen(line) && line[strlen(line) - 1] == '\n')
2223 line[strlen(line) - 1] = 0;
2225 /* ignore leading blanks */
2226 while (*line && isspace((unsigned char) line[0]))
2229 /* ignore comments and empty lines */
2230 if (strlen(line) == 0 || line[0] == '#')
2233 /* Check for right groupname */
2238 /* group info already read */
2243 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2244 line[strlen(service) + 1] == ']')
2254 * Finally, we are in the right group and can parse
2261 key = strtok(line, "=");
2264 printfPQExpBuffer(errorMessage,
2265 "ERROR: syntax error in service file '%s', line %d\n",
2273 * If not already set, set the database name to the
2274 * name of the service
2276 for (i = 0; options[i].keyword; i++)
2278 if (strcmp(options[i].keyword, "dbname") == 0)
2280 if (options[i].val == NULL)
2281 options[i].val = strdup(service);
2286 val = line + strlen(line) + 1;
2289 * Set the parameter --- but don't override any
2290 * previous explicit setting.
2293 for (i = 0; options[i].keyword; i++)
2295 if (strcmp(options[i].keyword, key) == 0)
2297 if (options[i].val == NULL)
2298 options[i].val = strdup(val);
2306 printfPQExpBuffer(errorMessage,
2307 "ERROR: syntax error in service file '%s', line %d\n",
2325 * Conninfo parser routine
2327 * If successful, a malloc'd PQconninfoOption array is returned.
2328 * If not successful, NULL is returned and an error message is
2329 * left in errorMessage.
2331 static PQconninfoOption *
2332 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2340 PQconninfoOption *options;
2341 PQconninfoOption *option;
2342 char errortmp[PQERRORMSG_LENGTH];
2344 /* Make a working copy of PQconninfoOptions */
2345 options = malloc(sizeof(PQconninfoOptions));
2346 if (options == NULL)
2348 printfPQExpBuffer(errorMessage,
2349 libpq_gettext("out of memory\n"));
2352 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2354 /* Need a modifiable copy of the input string */
2355 if ((buf = strdup(conninfo)) == NULL)
2357 printfPQExpBuffer(errorMessage,
2358 libpq_gettext("out of memory\n"));
2359 PQconninfoFree(options);
2366 /* Skip blanks before the parameter name */
2367 if (isspace((unsigned char) *cp))
2373 /* Get the parameter name */
2379 if (isspace((unsigned char) *cp))
2384 if (!isspace((unsigned char) *cp))
2393 /* Check that there is a following '=' */
2396 printfPQExpBuffer(errorMessage,
2397 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2399 PQconninfoFree(options);
2405 /* Skip blanks after the '=' */
2408 if (!isspace((unsigned char) *cp))
2413 /* Get the parameter value */
2421 if (isspace((unsigned char) *cp))
2445 printfPQExpBuffer(errorMessage,
2446 libpq_gettext("unterminated quoted string in connection info string\n"));
2447 PQconninfoFree(options);
2469 * Now we have the name and the value. Search for the param
2472 for (option = options; option->keyword != NULL; option++)
2474 if (strcmp(option->keyword, pname) == 0)
2477 if (option->keyword == NULL)
2479 printfPQExpBuffer(errorMessage,
2480 libpq_gettext("invalid connection option \"%s\"\n"),
2482 PQconninfoFree(options);
2492 option->val = strdup(pval);
2496 /* Done with the modifiable input string */
2500 * If there's a service spec, use it to obtain any not-explicitly-given
2503 if (parseServiceInfo(options, errorMessage))
2505 PQconninfoFree(options);
2510 * Get the fallback resources for parameters not specified in the
2511 * conninfo string nor the service.
2513 for (option = options; option->keyword != NULL; option++)
2515 if (option->val != NULL)
2516 continue; /* Value was in conninfo or service */
2519 * Try to get the environment variable fallback
2521 if (option->envvar != NULL)
2523 if ((tmp = getenv(option->envvar)) != NULL)
2525 option->val = strdup(tmp);
2531 * No environment variable specified or this one isn't set - try
2534 if (option->compiled != NULL)
2536 option->val = strdup(option->compiled);
2541 * Special handling for user
2543 if (strcmp(option->keyword, "user") == 0)
2545 option->val = fe_getauthname(errortmp);
2546 /* note any error message is thrown away */
2556 conninfo_getval(PQconninfoOption *connOptions,
2557 const char *keyword)
2559 PQconninfoOption *option;
2561 for (option = connOptions; option->keyword != NULL; option++)
2563 if (strcmp(option->keyword, keyword) == 0)
2572 PQconninfoFree(PQconninfoOption *connOptions)
2574 PQconninfoOption *option;
2576 if (connOptions == NULL)
2579 for (option = connOptions; option->keyword != NULL; option++)
2581 if (option->val != NULL)
2588 /* =========== accessor functions for PGconn ========= */
2590 PQdb(const PGconn *conn)
2593 return (char *) NULL;
2594 return conn->dbName;
2598 PQuser(const PGconn *conn)
2601 return (char *) NULL;
2602 return conn->pguser;
2606 PQpass(const PGconn *conn)
2609 return (char *) NULL;
2610 return conn->pgpass;
2614 PQhost(const PGconn *conn)
2617 return (char *) NULL;
2618 return conn->pghost ? conn->pghost : conn->pgunixsocket;
2622 PQport(const PGconn *conn)
2625 return (char *) NULL;
2626 return conn->pgport;
2630 PQtty(const PGconn *conn)
2633 return (char *) NULL;
2638 PQoptions(const PGconn *conn)
2641 return (char *) NULL;
2642 return conn->pgoptions;
2646 PQstatus(const PGconn *conn)
2649 return CONNECTION_BAD;
2650 return conn->status;
2654 PQerrorMessage(const PGconn *conn)
2657 return libpq_gettext("connection pointer is NULL\n");
2659 return conn->errorMessage.data;
2663 PQsocket(const PGconn *conn)
2671 PQbackendPID(const PGconn *conn)
2673 if (!conn || conn->status != CONNECTION_OK)
2675 return conn->be_pid;
2679 PQclientEncoding(const PGconn *conn)
2681 if (!conn || conn->status != CONNECTION_OK)
2683 return conn->client_encoding;
2687 PQsetClientEncoding(PGconn *conn, const char *encoding)
2690 static char query[] = "set client_encoding to '%s'";
2694 if (!conn || conn->status != CONNECTION_OK)
2700 /* check query buffer overflow */
2701 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2704 /* ok, now send a query */
2705 sprintf(qbuf, query, encoding);
2706 res = PQexec(conn, qbuf);
2708 if (res == (PGresult *) NULL)
2710 if (res->resultStatus != PGRES_COMMAND_OK)
2714 /* change libpq internal encoding */
2715 conn->client_encoding = pg_char_to_encoding(encoding);
2716 status = 0; /* everything is ok */
2723 PQtrace(PGconn *conn, FILE *debug_port)
2726 conn->status == CONNECTION_BAD)
2729 conn->Pfdebug = debug_port;
2733 PQuntrace(PGconn *conn)
2735 /* note: better allow untrace even when connection bad */
2740 fflush(conn->Pfdebug);
2741 conn->Pfdebug = NULL;
2746 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2748 PQnoticeProcessor old;
2753 old = conn->noticeHook;
2756 conn->noticeHook = proc;
2757 conn->noticeArg = arg;
2763 * The default notice/error message processor just prints the
2764 * message on stderr. Applications can override this if they
2765 * want the messages to go elsewhere (a window, for example).
2766 * Note that simply discarding notices is probably a bad idea.
2770 defaultNoticeProcessor(void *arg, const char *message)
2772 (void) arg; /* not used */
2773 /* Note: we expect the supplied string to end with a newline already. */
2774 fprintf(stderr, "%s", message);
2778 * returns a pointer to the next token or NULL if the current
2779 * token doesn't match
2782 pwdfMatchesString(char *buf, char *token)
2786 bool bslash = false;
2788 if (buf == NULL || token == NULL)
2796 if (*tbuf == '\\' && !bslash)
2801 if (*tbuf == ':' && *ttok == 0 && !bslash)
2817 /* Get a password from the password file. Return value is malloc'd. */
2819 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
2824 struct stat stat_buf;
2826 #define LINELEN NAMEDATALEN*5
2829 if (dbname == NULL || strlen(dbname) == 0)
2832 if (username == NULL || strlen(username) == 0)
2835 if (hostname == NULL)
2836 hostname = DefaultHost;
2839 port = DEF_PGPORT_STR;
2841 /* Look for it in the home dir */
2842 home = getenv("HOME");
2846 pgpassfile = malloc(strlen(home) + 1 + strlen(PGPASSFILE) + 1);
2849 fprintf(stderr, libpq_gettext("out of memory\n"));
2853 sprintf(pgpassfile, "%s/%s", home, PGPASSFILE);
2855 /* If password file cannot be opened, ignore it. */
2856 if (stat(pgpassfile, &stat_buf) == -1)
2863 /* If password file is insecure, alert the user and ignore it. */
2864 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
2867 libpq_gettext("WARNING: Password file %s has world or group read access; permission should be u=rw (0600)\n"),
2874 fp = fopen(pgpassfile, "r");
2885 fgets(buf, LINELEN - 1, fp);
2891 /* Remove trailing newline */
2892 if (buf[len - 1] == '\n')
2895 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
2896 (t = pwdfMatchesString(t, port)) == NULL ||
2897 (t = pwdfMatchesString(t, dbname)) == NULL ||
2898 (t = pwdfMatchesString(t, username)) == NULL)