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.229 2003/03/29 11:31:51 petere 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"
55 inet_aton(const char *cp, struct in_addr * inp)
57 unsigned long a = inet_addr(cp);
67 #define NOTIFYLIST_INITIAL_SIZE 10
68 #define NOTIFYLIST_GROWBY 10
70 #define PGPASSFILE ".pgpass"
73 * Definition of the conninfo parameters and their fallback resources.
75 * If Environment-Var and Compiled-in are specified as NULL, no
76 * fallback is available. If after all no value can be determined
77 * for an option, an error is returned.
79 * The values for dbname and user are treated specially in conninfo_parse.
80 * If the Compiled-in resource is specified as a NULL value, the
81 * user is determined by fe_getauthname() and for dbname the user
84 * The Label and Disp-Char entries are provided for applications that
85 * want to use PQconndefaults() to create a generic database connection
86 * dialog. Disp-Char is defined as follows:
87 * "" Normal input field
88 * "*" Password field - hide value
89 * "D" Debug option - don't show by default
91 * PQconninfoOptions[] is a constant static array that we use to initialize
92 * a dynamically allocated working copy. All the "val" fields in
93 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
94 * fields point to malloc'd strings that should be freed when the working
95 * array is freed (see PQconninfoFree).
98 static const PQconninfoOption PQconninfoOptions[] = {
100 * "authtype" is no longer used, so mark it "don't show". We keep it
101 * in the array so as not to reject conninfo strings from old apps
102 * that might still try to set it.
104 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
105 "Database-Authtype", "D", 20},
107 {"service", "PGSERVICE", NULL, NULL,
108 "Database-Service", "", 20},
110 {"user", "PGUSER", NULL, NULL,
111 "Database-User", "", 20},
113 {"password", "PGPASSWORD", DefaultPassword, NULL,
114 "Database-Password", "*", 20},
116 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
117 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
119 {"dbname", "PGDATABASE", NULL, NULL,
120 "Database-Name", "", 20},
122 {"host", "PGHOST", NULL, NULL,
123 "Database-Host", "", 40},
125 {"hostaddr", "PGHOSTADDR", NULL, NULL,
126 "Database-Host-IP-Address", "", 45},
128 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
129 "Database-Port", "", 6},
131 {"tty", "PGTTY", DefaultTty, NULL,
132 "Backend-Debug-TTY", "D", 40},
134 {"options", "PGOPTIONS", DefaultOption, NULL,
135 "Backend-Debug-Options", "D", 40},
138 {"requiressl", "PGREQUIRESSL", "0", NULL,
139 "Require-SSL", "", 1},
142 /* Terminating entry --- MUST BE LAST */
143 {NULL, NULL, NULL, NULL,
147 static const struct EnvironmentOptions
151 } EnvironmentOptions[] =
154 /* common user-interface settings */
156 "PGDATESTYLE", "datestyle"
162 "PGCLIENTENCODING", "client_encoding"
164 /* internal performance-related settings */
174 static int connectDBStart(PGconn *conn);
175 static int connectDBComplete(PGconn *conn);
176 static bool PQsetenvStart(PGconn *conn);
177 static PostgresPollingStatusType PQsetenvPoll(PGconn *conn);
178 static PGconn *makeEmptyPGconn(void);
179 static void freePGconn(PGconn *conn);
180 static void closePGconn(PGconn *conn);
181 static PQconninfoOption *conninfo_parse(const char *conninfo,
182 PQExpBuffer errorMessage);
183 static char *conninfo_getval(PQconninfoOption *connOptions,
184 const char *keyword);
185 static void defaultNoticeProcessor(void *arg, const char *message);
186 static int parseServiceInfo(PQconninfoOption *options,
187 PQExpBuffer errorMessage);
188 char *pwdfMatchesString(char *buf, char *token);
189 char *PasswordFromFile(char *hostname, char *port, char *dbname,
193 * Connecting to a Database
195 * There are now four different ways a user of this API can connect to the
196 * database. Two are not recommended for use in new code, because of their
197 * lack of extensibility with respect to the passing of options to the
198 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
201 * If it is desired to connect in a synchronous (blocking) manner, use the
202 * function PQconnectdb.
204 * To connect in an asynchronous (non-blocking) manner, use the functions
205 * PQconnectStart, and PQconnectPoll.
207 * Internally, the static functions connectDBStart, connectDBComplete
208 * are part of the connection procedure.
214 * establishes a connection to a postgres backend through the postmaster
215 * using connection information in a string.
217 * The conninfo string is a white-separated list of
221 * definitions. Value might be a single value containing no whitespaces or
222 * a single quoted string. If a single quote should appear anywhere in
223 * the value, it must be escaped with a backslash like \'
225 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
226 * if a memory allocation failed.
227 * If the status field of the connection returned is CONNECTION_BAD,
228 * then some fields may be null'ed out instead of having valid values.
230 * You should call PQfinish (if conn is not NULL) regardless of whether this
234 PQconnectdb(const char *conninfo)
236 PGconn *conn = PQconnectStart(conninfo);
238 if (conn && conn->status != CONNECTION_BAD)
239 (void) connectDBComplete(conn);
247 * Begins the establishment of a connection to a postgres backend through the
248 * postmaster using connection information in a string.
250 * See comment for PQconnectdb for the definition of the string format.
252 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
253 * you should not attempt to proceed with this connection. If the status
254 * field of the connection returned is CONNECTION_BAD, an error has
255 * occurred. In this case you should call PQfinish on the result, (perhaps
256 * inspecting the error message first). Other fields of the structure may not
257 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
258 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
261 * See PQconnectPoll for more info.
264 PQconnectStart(const char *conninfo)
267 PQconninfoOption *connOptions;
271 * Allocate memory for the conn structure
274 conn = makeEmptyPGconn();
276 return (PGconn *) NULL;
279 * Parse the conninfo string
281 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
282 if (connOptions == NULL)
284 conn->status = CONNECTION_BAD;
285 /* errorMessage is already set */
290 * Move option values into conn structure
292 tmp = conninfo_getval(connOptions, "hostaddr");
293 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
294 tmp = conninfo_getval(connOptions, "host");
295 conn->pghost = tmp ? strdup(tmp) : NULL;
296 tmp = conninfo_getval(connOptions, "port");
297 conn->pgport = tmp ? strdup(tmp) : NULL;
298 tmp = conninfo_getval(connOptions, "tty");
299 conn->pgtty = tmp ? strdup(tmp) : NULL;
300 tmp = conninfo_getval(connOptions, "options");
301 conn->pgoptions = tmp ? strdup(tmp) : NULL;
302 tmp = conninfo_getval(connOptions, "dbname");
303 conn->dbName = tmp ? strdup(tmp) : NULL;
304 tmp = conninfo_getval(connOptions, "user");
305 conn->pguser = tmp ? strdup(tmp) : NULL;
306 tmp = conninfo_getval(connOptions, "password");
307 conn->pgpass = tmp ? strdup(tmp) : NULL;
308 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
312 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
313 conn->dbName, conn->pguser);
314 if (conn->pgpass == NULL)
315 conn->pgpass = strdup(DefaultPassword);
317 tmp = conninfo_getval(connOptions, "connect_timeout");
318 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
320 tmp = conninfo_getval(connOptions, "requiressl");
321 if (tmp && tmp[0] == '1')
322 conn->require_ssl = true;
326 * Free the option info - all is in conn now
328 PQconninfoFree(connOptions);
331 * Allow unix socket specification in the host name
333 if (conn->pghost && conn->pghost[0] == '/')
335 if (conn->pgunixsocket)
336 free(conn->pgunixsocket);
337 conn->pgunixsocket = conn->pghost;
342 * Connect to the database
344 if (!connectDBStart(conn))
346 /* Just in case we failed to set it in connectDBStart */
347 conn->status = CONNECTION_BAD;
356 * Parse an empty string like PQconnectdb() would do and return the
357 * working connection options array.
359 * Using this function, an application may determine all possible options
360 * and their current default values.
362 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
363 * and should be freed when no longer needed via PQconninfoFree(). (In prior
364 * versions, the returned array was static, but that's not thread-safe.)
365 * Pre-7.0 applications that use this function will see a small memory leak
366 * until they are updated to call PQconninfoFree.
371 PQExpBufferData errorBuf;
372 PQconninfoOption *connOptions;
374 initPQExpBuffer(&errorBuf);
375 connOptions = conninfo_parse("", &errorBuf);
376 termPQExpBuffer(&errorBuf);
383 * establishes a connection to a postgres backend through the postmaster
384 * at the specified host and port.
386 * returns a PGconn* which is needed for all subsequent libpq calls
387 * if the status field of the connection returned is CONNECTION_BAD,
388 * then some fields may be null'ed out instead of having valid values
390 * Uses these environment variables:
392 * PGHOST identifies host to which to connect if <pghost> argument
393 * is NULL or a null string.
395 * PGPORT identifies TCP port to which to connect if <pgport> argument
396 * is NULL or a null string.
398 * PGTTY identifies tty to which to send messages if <pgtty> argument
399 * is NULL or a null string.
401 * PGOPTIONS identifies connection options if <pgoptions> argument is
402 * NULL or a null string.
404 * PGUSER Postgres username to associate with the connection.
406 * PGPASSWORD The user's password.
408 * PGDATABASE name of database to which to connect if <pgdatabase>
409 * argument is NULL or a null string
411 * None of the above need be defined. There are defaults for all of them.
413 * To support "delimited identifiers" for database names, only convert
414 * the database name to lower case if it is not surrounded by double quotes.
415 * Otherwise, strip the double quotes but leave the reset of the string intact.
416 * - thomas 1997-11-08
420 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
421 const char *pgtty, const char *dbName, const char *login,
425 char *tmp; /* An error message from some service we
427 bool error = FALSE; /* We encountered an error. */
429 conn = makeEmptyPGconn();
431 return (PGconn *) NULL;
434 conn->pghost = strdup(pghost);
435 else if ((tmp = getenv("PGHOST")) != NULL)
436 conn->pghost = strdup(tmp);
438 if (pgport == NULL || pgport[0] == '\0')
440 tmp = getenv("PGPORT");
441 if (tmp == NULL || tmp[0] == '\0')
442 tmp = DEF_PGPORT_STR;
443 conn->pgport = strdup(tmp);
446 conn->pgport = strdup(pgport);
449 * We don't allow unix socket path as a function parameter. This
450 * allows unix socket specification in the host name.
452 if (conn->pghost && conn->pghost[0] == '/')
454 if (conn->pgunixsocket)
455 free(conn->pgunixsocket);
456 conn->pgunixsocket = conn->pghost;
462 if ((tmp = getenv("PGTTY")) == NULL)
464 conn->pgtty = strdup(tmp);
467 conn->pgtty = strdup(pgtty);
469 if (pgoptions == NULL)
471 if ((tmp = getenv("PGOPTIONS")) == NULL)
473 conn->pgoptions = strdup(tmp);
476 conn->pgoptions = strdup(pgoptions);
479 conn->pguser = strdup(login);
480 else if ((tmp = getenv("PGUSER")) != NULL)
481 conn->pguser = strdup(tmp);
484 /* fe-auth.c has not been fixed to support PQExpBuffers, so: */
485 conn->pguser = fe_getauthname(conn->errorMessage.data);
486 conn->errorMessage.len = strlen(conn->errorMessage.data);
489 if (conn->pguser == NULL)
492 printfPQExpBuffer(&conn->errorMessage,
493 libpq_gettext("could not determine the PostgreSQL user name to use\n"));
498 if ((tmp = getenv("PGDATABASE")) != NULL)
499 conn->dbName = strdup(tmp);
500 else if (conn->pguser)
501 conn->dbName = strdup(conn->pguser);
504 conn->dbName = strdup(dbName);
507 conn->pgpass = strdup(pwd);
508 else if ((tmp = getenv("PGPASSWORD")) != NULL)
509 conn->pgpass = strdup(tmp);
510 else if ((tmp = PasswordFromFile(conn->pghost, conn->pgport,
511 conn->dbName, conn->pguser)) != NULL)
514 conn->pgpass = strdup(DefaultPassword);
516 if ((tmp = getenv("PGCONNECT_TIMEOUT")) != NULL)
517 conn->connect_timeout = strdup(tmp);
520 if ((tmp = getenv("PGREQUIRESSL")) != NULL)
521 conn->require_ssl = (tmp[0] == '1') ? true : false;
525 conn->status = CONNECTION_BAD;
528 if (connectDBStart(conn))
529 (void) connectDBComplete(conn);
536 #ifdef NOT_USED /* because it's broken */
539 * get all additional info out of dbName
543 update_db_info(PGconn *conn)
549 if (strchr(conn->dbName, '@') != NULL)
551 /* old style: dbname[@server][:port] */
552 tmp = strrchr(conn->dbName, ':');
553 if (tmp != NULL) /* port number given */
557 conn->pgport = strdup(tmp + 1);
561 tmp = strrchr(conn->dbName, '@');
562 if (tmp != NULL) /* host name given */
566 conn->pghost = strdup(tmp + 1);
570 conn->dbName = strdup(old);
578 * only allow protocols tcp and unix
580 if (strncmp(conn->dbName, "tcp:", 4) == 0)
582 else if (strncmp(conn->dbName, "unix:", 5) == 0)
587 if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
592 * <tcp|unix>:postgresql://server[:port|:/unixsocket/path:]
593 * [/db name][?options]
596 offset += strlen("postgresql://");
598 tmp = strrchr(conn->dbName + offset, '?');
599 if (tmp != NULL) /* options given */
602 free(conn->pgoptions);
603 conn->pgoptions = strdup(tmp + 1);
607 tmp = strrchr(conn->dbName + offset, '/');
608 if (tmp != NULL) /* database name given */
612 conn->dbName = strdup(tmp + 1);
618 * Why do we default only this value from the environment
621 if ((tmp = getenv("PGDATABASE")) != NULL)
625 conn->dbName = strdup(tmp);
627 else if (conn->pguser)
631 conn->dbName = strdup(conn->pguser);
635 tmp = strrchr(old + offset, ':');
636 if (tmp != NULL) /* port number or Unix socket path given */
639 if ((tmp2 = strchr(tmp + 1, ':')) != NULL)
641 if (strncmp(old, "unix:", 5) != 0)
643 printfPQExpBuffer(&conn->errorMessage,
644 "connectDBStart() -- "
645 "socket name can only be specified with "
650 if (conn->pgunixsocket)
651 free(conn->pgunixsocket);
652 conn->pgunixsocket = strdup(tmp + 1);
658 conn->pgport = strdup(tmp + 1);
659 if (conn->pgunixsocket)
660 free(conn->pgunixsocket);
661 conn->pgunixsocket = NULL;
665 if (strncmp(old, "unix:", 5) == 0)
670 if (strcmp(old + offset, "localhost") != 0)
672 printfPQExpBuffer(&conn->errorMessage,
673 "connectDBStart() -- "
674 "non-TCP access only possible on "
683 conn->pghost = strdup(old + offset);
691 #endif /* NOT_USED */
695 * connectMakeNonblocking -
696 * Make a connection non-blocking.
697 * Returns 1 if successful, 0 if not.
701 connectMakeNonblocking(PGconn *conn)
703 #if defined(WIN32) || defined(__BEOS__)
708 if (ioctlsocket(conn->sock, FIONBIO, &on) != 0)
709 #elif defined(__BEOS__)
710 if (ioctl(conn->sock, FIONBIO, &on) != 0)
712 if (fcntl(conn->sock, F_SETFL, O_NONBLOCK) < 0)
715 printfPQExpBuffer(&conn->errorMessage,
716 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
717 SOCK_STRERROR(SOCK_ERRNO));
726 * Sets the TCP_NODELAY socket option.
727 * Returns 1 if successful, 0 if not.
731 connectNoDelay(PGconn *conn)
735 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
739 printfPQExpBuffer(&conn->errorMessage,
740 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
741 SOCK_STRERROR(SOCK_ERRNO));
750 * connectFailureMessage -
751 * create a friendly error message on connection failure.
755 connectFailureMessage(PGconn *conn, int errorno)
757 if (conn->raddr.sa.sa_family == AF_UNIX)
758 printfPQExpBuffer(&conn->errorMessage,
760 "could not connect to server: %s\n"
761 "\tIs the server running locally and accepting\n"
762 "\tconnections on Unix domain socket \"%s\"?\n"
764 SOCK_STRERROR(errorno),
765 conn->raddr.un.sun_path);
767 printfPQExpBuffer(&conn->errorMessage,
769 "could not connect to server: %s\n"
770 "\tIs the server running on host %s and accepting\n"
771 "\tTCP/IP connections on port %s?\n"
773 SOCK_STRERROR(errorno),
785 * Start to make a connection to the backend so it is ready to receive
787 * Returns 1 if successful, 0 if not.
791 connectDBStart(PGconn *conn)
796 StartupPacket np; /* Used to negotiate SSL connection */
799 struct addrinfo *addrs = NULL;
800 struct addrinfo *addr_cur = NULL;
801 struct addrinfo hint;
802 const char *node = NULL;
803 const char *unix_node = "unix";
806 /* Initialize hint structure */
807 MemSet(&hint, 0, sizeof(hint));
808 hint.ai_socktype = SOCK_STREAM;
815 * parse dbName to get all additional info in it, if any
817 if (update_db_info(conn) != 0)
818 goto connect_errReturn;
821 /* Ensure our buffers are empty */
822 conn->inStart = conn->inCursor = conn->inEnd = 0;
826 * Set up the connection to postmaster/backend.
829 MemSet((char *) &conn->raddr, 0, sizeof(conn->raddr));
831 /* Set port number */
832 if (conn->pgport != NULL && conn->pgport[0] != '\0')
833 portnum = atoi(conn->pgport);
835 portnum = DEF_PGPORT;
836 snprintf(portstr, sizeof(portstr), "%d", portnum);
838 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
840 /* Using pghostaddr avoids a hostname lookup */
841 node = conn->pghostaddr;
842 hint.ai_family = AF_UNSPEC;
843 hint.ai_flags = AI_NUMERICHOST;
845 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
847 /* Using pghost, so we have to look-up the hostname */
849 hint.ai_family = AF_UNSPEC;
853 /* pghostaddr and pghost are NULL, so use Unix domain socket */
854 #ifdef HAVE_UNIX_SOCKETS
856 hint.ai_family = AF_UNIX;
857 UNIXSOCK_PATH(conn->raddr.un, portnum, conn->pgunixsocket);
858 conn->raddr_len = UNIXSOCK_LEN(conn->raddr.un);
859 StrNCpy(portstr, conn->raddr.un.sun_path, sizeof(portstr));
861 /* Don't bother requesting SSL over a Unix socket */
862 conn->allow_ssl_try = false;
863 conn->require_ssl = false;
865 #endif /* HAVE_UNIX_SOCKETS */
868 /* Use getaddrinfo2() to resolve the address */
869 ret = getaddrinfo2(node, portstr, &hint, &addrs);
870 if (ret || addrs == NULL)
872 printfPQExpBuffer(&conn->errorMessage,
873 libpq_gettext("getaddrinfo() failed: %s\n"),
875 goto connect_errReturn;
879 * We loop over the possible addresses returned by getaddrinfo2(),
880 * and fail only when they all fail (reporting the error returned
881 * for the *last* alternative, which may not be what users expect
884 * In either case, we never actually fall out of the loop; the
885 * only exits are via "break" or "goto connect_errReturn". Thus,
886 * there is no exit test in the for().
888 for (addr_cur = addrs; ; addr_cur = addr_cur->ai_next)
891 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM,
892 addr_cur->ai_protocol);
895 /* ignore socket() failure if we have more addrs to try */
896 if (addr_cur->ai_next != NULL)
898 printfPQExpBuffer(&conn->errorMessage,
899 libpq_gettext("could not create socket: %s\n"),
900 SOCK_STRERROR(SOCK_ERRNO));
901 goto connect_errReturn;
905 * Set the right options. Normally, we need nonblocking I/O, and we
906 * don't want delay of outgoing data for AF_INET sockets. If we are
907 * using SSL, then we need the blocking I/O (XXX Can this be fixed?).
910 if (isAF_INETx(addr_cur->ai_family))
912 if (!connectNoDelay(conn))
913 goto connect_errReturn;
916 #if !defined(USE_SSL)
917 if (connectMakeNonblocking(conn) == 0)
918 goto connect_errReturn;
922 * Start / make connection. We are hopefully in non-blocking mode
923 * now, but it is possible that:
924 * 1. Older systems will still block on connect, despite the
925 * non-blocking flag. (Anyone know if this is true?)
926 * 2. We are using SSL.
927 * Thus, we have to make arrangements for all eventualities.
931 if (connect(conn->sock, addr_cur->ai_addr, addr_cur->ai_addrlen) < 0)
933 if (SOCK_ERRNO == EINTR)
934 /* Interrupted system call - we'll just try again */
937 if (SOCK_ERRNO == EINPROGRESS || SOCK_ERRNO == EWOULDBLOCK || SOCK_ERRNO == 0)
940 * This is fine - we're in non-blocking mode, and the
941 * connection is in progress.
943 conn->status = CONNECTION_STARTED;
946 /* otherwise, trouble */
950 /* We're connected already */
951 conn->status = CONNECTION_MADE;
955 * This connection failed. We need to close the socket,
956 * and either loop to try the next address or report an error.
958 /* ignore connect() failure if we have more addrs to try */
959 if (addr_cur->ai_next != NULL)
965 /* copy failed address for error report */
966 memcpy(&conn->raddr, addr_cur->ai_addr, addr_cur->ai_addrlen);
967 conn->raddr_len = addr_cur->ai_addrlen;
968 connectFailureMessage(conn, SOCK_ERRNO);
969 goto connect_errReturn;
970 } /* loop over addrs */
972 /* Remember the successfully opened address alternative */
973 memcpy(&conn->raddr, addr_cur->ai_addr, addr_cur->ai_addrlen);
974 conn->raddr_len = addr_cur->ai_addrlen;
975 /* and release the address list */
976 freeaddrinfo2(hint.ai_family, addrs);
980 /* Attempt to negotiate SSL usage */
981 if (conn->allow_ssl_try)
983 memset((char *) &np, 0, sizeof(np));
984 np.protoVersion = htonl(NEGOTIATE_SSL_CODE);
985 if (pqPacketSend(conn, (char *) &np, sizeof(StartupPacket)) != STATUS_OK)
987 printfPQExpBuffer(&conn->errorMessage,
988 libpq_gettext("could not send SSL negotiation packet: %s\n"),
989 SOCK_STRERROR(SOCK_ERRNO));
990 goto connect_errReturn;
993 /* Now receive the postmasters response */
994 if (recv(conn->sock, &SSLok, 1, 0) != 1)
996 if (SOCK_ERRNO == EINTR)
997 /* Interrupted system call - we'll just try again */
1000 printfPQExpBuffer(&conn->errorMessage,
1001 libpq_gettext("could not receive server response to SSL negotiation packet: %s\n"),
1002 SOCK_STRERROR(SOCK_ERRNO));
1003 goto connect_errReturn;
1007 if (pqsecure_initialize(conn) == -1 ||
1008 pqsecure_open_client(conn) == -1)
1009 goto connect_errReturn;
1010 /* SSL connection finished. Continue to send startup packet */
1012 else if (SSLok == 'E')
1014 /* Received error - probably protocol mismatch */
1016 fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-7.0.\n");
1017 pqsecure_close(conn);
1019 closesocket(conn->sock);
1024 conn->allow_ssl_try = FALSE;
1025 return connectDBStart(conn);
1027 else if (SSLok != 'N')
1029 printfPQExpBuffer(&conn->errorMessage,
1030 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1032 goto connect_errReturn;
1035 if (conn->require_ssl && !conn->ssl)
1037 /* Require SSL, but server does not support/want it */
1038 printfPQExpBuffer(&conn->errorMessage,
1039 libpq_gettext("server does not support SSL, but SSL was required\n"));
1040 goto connect_errReturn;
1045 * This makes the connection non-blocking, for all those cases which
1046 * forced us not to do it above.
1048 #if defined(USE_SSL)
1049 if (connectMakeNonblocking(conn) == 0)
1050 goto connect_errReturn;
1056 if (conn->sock >= 0)
1058 pqsecure_close(conn);
1060 closesocket(conn->sock);
1066 conn->status = CONNECTION_BAD;
1068 freeaddrinfo2(hint.ai_family, addrs);
1076 * Block and complete a connection.
1078 * Returns 1 on success, 0 on failure.
1081 connectDBComplete(PGconn *conn)
1083 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1084 time_t finish_time = ((time_t) -1);
1086 if (conn == NULL || conn->status == CONNECTION_BAD)
1090 * Set up a time limit, if connect_timeout isn't zero.
1092 if (conn->connect_timeout != NULL)
1094 int timeout = atoi(conn->connect_timeout);
1099 * Rounding could cause connection to fail; need at least 2
1104 /* calculate the finish time based on start + timeout */
1105 finish_time = time(NULL) + timeout;
1112 * Wait, if necessary. Note that the initial state (just after
1113 * PQconnectStart) is to wait for the socket to select for
1118 case PGRES_POLLING_OK:
1119 return 1; /* success! */
1121 case PGRES_POLLING_READING:
1122 if (pqWaitTimed(1, 0, conn, finish_time))
1124 conn->status = CONNECTION_BAD;
1129 case PGRES_POLLING_WRITING:
1130 if (pqWaitTimed(0, 1, conn, finish_time))
1132 conn->status = CONNECTION_BAD;
1138 /* Just in case we failed to set it in PQconnectPoll */
1139 conn->status = CONNECTION_BAD;
1144 * Now try to advance the state machine.
1146 flag = PQconnectPoll(conn);
1153 * Poll an asynchronous connection.
1155 * Returns a PostgresPollingStatusType.
1156 * Before calling this function, use select(2) to determine when data
1159 * You must call PQfinish whether or not this fails.
1161 * This function and PQconnectStart are intended to allow connections to be
1162 * made without blocking the execution of your program on remote I/O. However,
1163 * there are a number of caveats:
1165 * o If you call PQtrace, ensure that the stream object into which you trace
1167 * o If you do not supply an IP address for the remote host (i.e. you
1168 * supply a host name instead) then this function will block on
1169 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1170 * supplying neither a host name nor a host address).
1171 * o If your backend wants to use Kerberos authentication then you must
1172 * supply both a host name and a host address, otherwise this function
1173 * may block on gethostname.
1174 * o This function will block if compiled with USE_SSL.
1178 PostgresPollingStatusType
1179 PQconnectPoll(PGconn *conn)
1184 return PGRES_POLLING_FAILED;
1186 /* Get the new data */
1187 switch (conn->status)
1190 * We really shouldn't have been polled in these two cases,
1191 * but we can handle it.
1193 case CONNECTION_BAD:
1194 return PGRES_POLLING_FAILED;
1196 return PGRES_POLLING_OK;
1198 /* These are reading states */
1199 case CONNECTION_AWAITING_RESPONSE:
1200 case CONNECTION_AUTH_OK:
1202 /* Load waiting data */
1203 int n = pqReadData(conn);
1208 return PGRES_POLLING_READING;
1213 /* These are writing states, so we just proceed. */
1214 case CONNECTION_STARTED:
1215 case CONNECTION_MADE:
1218 case CONNECTION_SETENV:
1219 /* We allow PQsetenvPoll to decide whether to proceed */
1223 printfPQExpBuffer(&conn->errorMessage,
1225 "invalid connection state, "
1226 "probably indicative of memory corruption\n"
1232 keep_going: /* We will come back to here until there
1233 * is nothing left to parse. */
1234 switch (conn->status)
1236 case CONNECTION_STARTED:
1238 ACCEPT_TYPE_ARG3 laddrlen;
1240 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1243 * Write ready, since we've made it here, so the
1244 * connection has been made.
1248 * Now check (using getsockopt) that there is not an error
1249 * state waiting for us on the socket.
1252 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1253 (char *) &optval, &optlen) == -1)
1255 printfPQExpBuffer(&conn->errorMessage,
1256 libpq_gettext("could not get socket error status: %s\n"),
1257 SOCK_STRERROR(SOCK_ERRNO));
1260 else if (optval != 0)
1263 * When using a nonblocking connect, we will typically
1264 * see connect failures at this point, so provide a
1265 * friendly error message.
1267 connectFailureMessage(conn, optval);
1271 /* Fill in the client address */
1272 laddrlen = sizeof(conn->laddr);
1273 if (getsockname(conn->sock, &conn->laddr.sa, &laddrlen) < 0)
1275 printfPQExpBuffer(&conn->errorMessage,
1276 libpq_gettext("could not get client address from socket: %s\n"),
1277 SOCK_STRERROR(SOCK_ERRNO));
1281 conn->status = CONNECTION_MADE;
1282 return PGRES_POLLING_WRITING;
1285 case CONNECTION_MADE:
1290 * Initialize the startup packet.
1293 MemSet((char *) &sp, 0, sizeof(StartupPacket));
1295 sp.protoVersion = (ProtocolVersion) htonl(PG_PROTOCOL_LIBPQ);
1297 strncpy(sp.user, conn->pguser, SM_USER);
1298 strncpy(sp.database, conn->dbName, SM_DATABASE);
1299 strncpy(sp.tty, conn->pgtty, SM_TTY);
1301 if (conn->pgoptions)
1302 strncpy(sp.options, conn->pgoptions, SM_OPTIONS);
1305 * Send the startup packet.
1307 * Theoretically, this could block, but it really shouldn't
1308 * since we only got here if the socket is write-ready.
1311 if (pqPacketSend(conn, (char *) &sp,
1312 sizeof(StartupPacket)) != STATUS_OK)
1314 printfPQExpBuffer(&conn->errorMessage,
1315 libpq_gettext("could not send startup packet: %s\n"),
1316 SOCK_STRERROR(SOCK_ERRNO));
1320 conn->status = CONNECTION_AWAITING_RESPONSE;
1321 return PGRES_POLLING_READING;
1325 * Handle the authentication exchange: wait for postmaster
1326 * messages and respond as necessary.
1328 case CONNECTION_AWAITING_RESPONSE:
1334 * Scan the message from current point (note that if we
1335 * find the message is incomplete, we will return without
1336 * advancing inStart, and resume here next time).
1338 conn->inCursor = conn->inStart;
1340 if (pqGetc(&beresp, conn))
1342 /* We'll come back when there is more data */
1343 return PGRES_POLLING_READING;
1346 /* Handle errors. */
1349 if (pqGets(&conn->errorMessage, conn))
1351 /* We'll come back when there is more data */
1352 return PGRES_POLLING_READING;
1354 /* OK, we read the message; mark data consumed */
1355 conn->inStart = conn->inCursor;
1358 * The postmaster typically won't end its message with
1359 * a newline, so add one to conform to libpq
1362 appendPQExpBufferChar(&conn->errorMessage, '\n');
1366 /* Otherwise it should be an authentication request. */
1369 printfPQExpBuffer(&conn->errorMessage,
1371 "expected authentication request from "
1372 "server, but received %c\n"
1378 /* Get the type of request. */
1379 if (pqGetInt((int *) &areq, 4, conn))
1381 /* We'll come back when there are more data */
1382 return PGRES_POLLING_READING;
1385 /* Get the password salt if there is one. */
1386 if (areq == AUTH_REQ_MD5)
1388 if (pqGetnchar(conn->md5Salt,
1389 sizeof(conn->md5Salt), conn))
1391 /* We'll come back when there are more data */
1392 return PGRES_POLLING_READING;
1395 if (areq == AUTH_REQ_CRYPT)
1397 if (pqGetnchar(conn->cryptSalt,
1398 sizeof(conn->cryptSalt), conn))
1400 /* We'll come back when there are more data */
1401 return PGRES_POLLING_READING;
1406 * OK, we successfully read the message; mark data
1409 conn->inStart = conn->inCursor;
1411 /* Respond to the request if necessary. */
1414 * Note that conn->pghost must be non-NULL if we are going
1415 * to avoid the Kerberos code doing a hostname look-up.
1419 * XXX fe-auth.c has not been fixed to support
1422 if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1423 conn->errorMessage.data) != STATUS_OK)
1425 conn->errorMessage.len = strlen(conn->errorMessage.data);
1428 conn->errorMessage.len = strlen(conn->errorMessage.data);
1431 * Just make sure that any data sent by fe_sendauth is
1432 * flushed out. Although this theoretically could block,
1433 * it really shouldn't since we don't send large auth
1439 if (areq == AUTH_REQ_OK)
1441 /* We are done with authentication exchange */
1442 conn->status = CONNECTION_AUTH_OK;
1445 * Set asyncStatus so that PQsetResult will think that
1446 * what comes back next is the result of a query. See
1449 conn->asyncStatus = PGASYNC_BUSY;
1452 /* Look to see if we have more data yet. */
1456 case CONNECTION_AUTH_OK:
1459 * Now we expect to hear from the backend. A ReadyForQuery
1460 * message indicates that startup is successful, but we
1461 * might also get an Error message indicating failure.
1462 * (Notice messages indicating nonfatal warnings are also
1463 * allowed by the protocol, as is a BackendKeyData
1464 * message.) Easiest way to handle this is to let
1465 * PQgetResult() read the messages. We just have to fake
1466 * it out about the state of the connection, by setting
1467 * asyncStatus = PGASYNC_BUSY (done above).
1471 return PGRES_POLLING_READING;
1473 res = PQgetResult(conn);
1476 * NULL return indicating we have gone to IDLE state is
1481 if (res->resultStatus != PGRES_FATAL_ERROR)
1482 printfPQExpBuffer(&conn->errorMessage,
1483 libpq_gettext("unexpected message from server during startup\n"));
1486 * if the resultStatus is FATAL, then
1487 * conn->errorMessage already has a copy of the error;
1488 * needn't copy it back. But add a newline if it's not
1489 * there already, since postmaster error messages may
1492 if (conn->errorMessage.len <= 0 ||
1493 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1494 appendPQExpBufferChar(&conn->errorMessage, '\n');
1500 * Post-connection housekeeping. Prepare to send
1501 * environment variables to server.
1503 if (!PQsetenvStart(conn))
1506 conn->status = CONNECTION_SETENV;
1511 case CONNECTION_SETENV:
1514 * We pretend that the connection is OK for the duration of
1517 conn->status = CONNECTION_OK;
1519 switch (PQsetenvPoll(conn))
1521 case PGRES_POLLING_OK: /* Success */
1522 conn->status = CONNECTION_OK;
1523 return PGRES_POLLING_OK;
1525 case PGRES_POLLING_READING: /* Still going */
1526 conn->status = CONNECTION_SETENV;
1527 return PGRES_POLLING_READING;
1529 case PGRES_POLLING_WRITING: /* Still going */
1530 conn->status = CONNECTION_SETENV;
1531 return PGRES_POLLING_WRITING;
1534 conn->status = CONNECTION_SETENV;
1540 printfPQExpBuffer(&conn->errorMessage,
1542 "invalid connection state %c, "
1543 "probably indicative of memory corruption\n"
1554 * We used to close the socket at this point, but that makes it
1555 * awkward for those above us if they wish to remove this socket from
1556 * their own records (an fd_set for example). We'll just have this
1557 * socket closed when PQfinish is called (which is compulsory even
1558 * after an error, since the connection structure must be freed).
1560 return PGRES_POLLING_FAILED;
1567 * Starts the process of passing the values of a standard set of environment
1568 * variables to the backend.
1571 PQsetenvStart(PGconn *conn)
1574 conn->status == CONNECTION_BAD ||
1575 conn->setenv_state != SETENV_STATE_IDLE)
1578 conn->setenv_state = SETENV_STATE_ENCODINGS_SEND;
1579 conn->next_eo = EnvironmentOptions;
1587 * Polls the process of passing the values of a standard set of environment
1588 * variables to the backend.
1590 static PostgresPollingStatusType
1591 PQsetenvPoll(PGconn *conn)
1595 if (conn == NULL || conn->status == CONNECTION_BAD)
1596 return PGRES_POLLING_FAILED;
1598 /* Check whether there are any data for us */
1599 switch (conn->setenv_state)
1601 /* These are reading states */
1602 case SETENV_STATE_ENCODINGS_WAIT:
1603 case SETENV_STATE_OPTION_WAIT:
1605 /* Load waiting data */
1606 int n = pqReadData(conn);
1611 return PGRES_POLLING_READING;
1616 /* These are writing states, so we just proceed. */
1617 case SETENV_STATE_ENCODINGS_SEND:
1618 case SETENV_STATE_OPTION_SEND:
1621 /* Should we raise an error if called when not active? */
1622 case SETENV_STATE_IDLE:
1623 return PGRES_POLLING_OK;
1626 printfPQExpBuffer(&conn->errorMessage,
1628 "invalid setenv state %c, "
1629 "probably indicative of memory corruption\n"
1631 conn->setenv_state);
1635 /* We will loop here until there is nothing left to do in this call. */
1638 switch (conn->setenv_state)
1640 case SETENV_STATE_ENCODINGS_SEND:
1642 const char *env = getenv("PGCLIENTENCODING");
1644 if (!env || *env == '\0')
1647 * PGCLIENTENCODING is not specified, so query
1648 * server for it. We must use begin/commit in
1649 * case autocommit is off by default.
1651 if (!PQsendQuery(conn, "begin; select pg_client_encoding(); commit"))
1654 conn->setenv_state = SETENV_STATE_ENCODINGS_WAIT;
1655 return PGRES_POLLING_READING;
1659 /* otherwise set client encoding in pg_conn struct */
1660 int encoding = pg_char_to_encoding(env);
1664 printfPQExpBuffer(&conn->errorMessage,
1665 libpq_gettext("invalid encoding name in PGCLIENTENCODING: %s\n"),
1669 conn->client_encoding = encoding;
1671 /* Move on to setting the environment options */
1672 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1677 case SETENV_STATE_ENCODINGS_WAIT:
1680 return PGRES_POLLING_READING;
1682 res = PQgetResult(conn);
1686 if (PQresultStatus(res) == PGRES_TUPLES_OK)
1688 /* set client encoding in pg_conn struct */
1691 encoding = PQgetvalue(res, 0, 0);
1692 if (!encoding) /* this should not happen */
1693 conn->client_encoding = PG_SQL_ASCII;
1695 conn->client_encoding = pg_char_to_encoding(encoding);
1697 else if (PQresultStatus(res) != PGRES_COMMAND_OK)
1703 /* Keep reading until PQgetResult returns NULL */
1708 * NULL result indicates that the query is
1711 /* Move on to setting the environment options */
1712 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1717 case SETENV_STATE_OPTION_SEND:
1719 /* Send an Environment Option */
1720 char setQuery[100]; /* note length limits in
1721 * sprintf's below */
1723 if (conn->next_eo->envName)
1727 if ((val = getenv(conn->next_eo->envName)))
1729 if (strcasecmp(val, "default") == 0)
1730 sprintf(setQuery, "SET %s = %.60s",
1731 conn->next_eo->pgName, val);
1733 sprintf(setQuery, "SET %s = '%.60s'",
1734 conn->next_eo->pgName, val);
1736 printf("Use environment variable %s to send %s\n",
1737 conn->next_eo->envName, setQuery);
1739 if (!PQsendQuery(conn, setQuery))
1742 conn->setenv_state = SETENV_STATE_OPTION_WAIT;
1749 /* No more options to send, so we are done. */
1750 conn->setenv_state = SETENV_STATE_IDLE;
1755 case SETENV_STATE_OPTION_WAIT:
1758 return PGRES_POLLING_READING;
1760 res = PQgetResult(conn);
1764 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1770 /* Keep reading until PQgetResult returns NULL */
1775 * NULL result indicates that the query is
1778 /* Send the next option */
1780 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1785 case SETENV_STATE_IDLE:
1786 return PGRES_POLLING_OK;
1789 printfPQExpBuffer(&conn->errorMessage,
1790 libpq_gettext("invalid state %c, "
1791 "probably indicative of memory corruption\n"),
1792 conn->setenv_state);
1800 conn->setenv_state = SETENV_STATE_IDLE;
1801 return PGRES_POLLING_FAILED;
1810 * Passes the values of a standard set of environment variables to the
1813 * Returns true on success, false on failure.
1815 * This function used to be exported for no particularly good reason.
1816 * Since it's no longer used by libpq itself, let's try #ifdef'ing it out
1817 * and see if anyone complains.
1820 PQsetenv(PGconn *conn)
1822 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1824 if (!PQsetenvStart(conn))
1830 * Wait, if necessary. Note that the initial state (just after
1831 * PQsetenvStart) is to wait for the socket to select for writing.
1835 case PGRES_POLLING_OK:
1836 return true; /* success! */
1838 case PGRES_POLLING_READING:
1839 if (pqWait(1, 0, conn))
1841 conn->status = CONNECTION_BAD;
1846 case PGRES_POLLING_WRITING:
1847 if (pqWait(0, 1, conn))
1849 conn->status = CONNECTION_BAD;
1855 /* Just in case we failed to set it in PQsetenvPoll */
1856 conn->status = CONNECTION_BAD;
1861 * Now try to advance the state machine.
1863 flag = PQsetenvPoll(conn);
1866 #endif /* NOT_USED */
1871 * - create a PGconn data structure with (as yet) no interesting data
1874 makeEmptyPGconn(void)
1876 PGconn *conn = (PGconn *) malloc(sizeof(PGconn));
1881 /* Zero all pointers and booleans */
1882 MemSet((char *) conn, 0, sizeof(PGconn));
1884 conn->noticeHook = defaultNoticeProcessor;
1885 conn->status = CONNECTION_BAD;
1886 conn->asyncStatus = PGASYNC_IDLE;
1887 conn->setenv_state = SETENV_STATE_IDLE;
1888 conn->notifyList = DLNewList();
1891 conn->allow_ssl_try = TRUE;
1895 * The output buffer size is set to 8K, which is the usual size of
1896 * pipe buffers on Unix systems. That way, when we are sending a
1897 * large amount of data, we avoid incurring extra kernel context swaps
1898 * for partial bufferloads. Note that we currently don't ever enlarge
1899 * the output buffer.
1901 * With the same goal of minimizing context swaps, the input buffer will
1902 * be enlarged anytime it has less than 8K free, so we initially
1903 * allocate twice that.
1905 conn->inBufSize = 16 * 1024;
1906 conn->inBuffer = (char *) malloc(conn->inBufSize);
1907 conn->outBufSize = 8 * 1024;
1908 conn->outBuffer = (char *) malloc(conn->outBufSize);
1909 conn->nonblocking = FALSE;
1910 initPQExpBuffer(&conn->errorMessage);
1911 initPQExpBuffer(&conn->workBuffer);
1912 if (conn->inBuffer == NULL ||
1913 conn->outBuffer == NULL ||
1914 conn->errorMessage.data == NULL ||
1915 conn->workBuffer.data == NULL)
1917 /* out of memory already :-( */
1926 * - free the PGconn data structure
1930 freePGconn(PGconn *conn)
1934 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1935 if (conn->sock >= 0)
1937 pqsecure_close(conn);
1939 closesocket(conn->sock);
1946 if (conn->pghostaddr)
1947 free(conn->pghostaddr);
1950 if (conn->pgunixsocket)
1951 free(conn->pgunixsocket);
1954 if (conn->pgoptions)
1955 free(conn->pgoptions);
1962 if (conn->connect_timeout)
1963 free(conn->connect_timeout);
1964 /* Note that conn->Pfdebug is not ours to close or free */
1965 if (conn->notifyList)
1966 DLFreeList(conn->notifyList);
1967 if (conn->lobjfuncs)
1968 free(conn->lobjfuncs);
1970 free(conn->inBuffer);
1971 if (conn->outBuffer)
1972 free(conn->outBuffer);
1973 termPQExpBuffer(&conn->errorMessage);
1974 termPQExpBuffer(&conn->workBuffer);
1980 - properly close a connection to the backend
1983 closePGconn(PGconn *conn)
1986 * Note that the protocol doesn't allow us to send Terminate messages
1987 * during the startup phase.
1989 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1992 * Try to send "close connection" message to backend. Ignore any
1993 * error. Note: this routine used to go to substantial lengths to
1994 * avoid getting SIGPIPE'd if the connection were already closed.
1995 * Now we rely on pqFlush to avoid the signal.
2002 * must reset the blocking status so a possible reconnect will work
2003 * don't call PQsetnonblocking() because it will fail if it's unable
2004 * to flush the connection.
2006 conn->nonblocking = FALSE;
2009 * Close the connection, reset all transient state, flush I/O buffers.
2011 if (conn->sock >= 0)
2013 pqsecure_close(conn);
2015 closesocket(conn->sock);
2021 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2023 conn->asyncStatus = PGASYNC_IDLE;
2024 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2025 if (conn->lobjfuncs)
2026 free(conn->lobjfuncs);
2027 conn->lobjfuncs = NULL;
2028 conn->inStart = conn->inCursor = conn->inEnd = 0;
2030 conn->nonblocking = FALSE;
2036 properly close a connection to the backend
2037 also frees the PGconn data structure so it shouldn't be re-used
2041 PQfinish(PGconn *conn)
2051 resets the connection to the backend
2052 closes the existing connection and makes a new one
2055 PQreset(PGconn *conn)
2061 if (connectDBStart(conn))
2062 (void) connectDBComplete(conn);
2068 resets the connection to the backend
2069 closes the existing connection and makes a new one
2070 Returns 1 on success, 0 on failure.
2073 PQresetStart(PGconn *conn)
2079 return connectDBStart(conn);
2087 resets the connection to the backend
2088 closes the existing connection and makes a new one
2091 PostgresPollingStatusType
2092 PQresetPoll(PGconn *conn)
2095 return PQconnectPoll(conn);
2097 return PGRES_POLLING_FAILED;
2102 * PQrequestCancel: attempt to request cancellation of the current operation.
2104 * The return value is TRUE if the cancel request was successfully
2105 * dispatched, FALSE if not (in which case conn->errorMessage is set).
2106 * Note: successful dispatch is no guarantee that there will be any effect at
2107 * the backend. The application must read the operation result as usual.
2109 * XXX it was a bad idea to have the error message returned in
2110 * conn->errorMessage, since it could overwrite a message already there.
2111 * Would be better to return it in a char array passed by the caller.
2113 * CAUTION: we want this routine to be safely callable from a signal handler
2114 * (for example, an application might want to call it in a SIGINT handler).
2115 * This means we cannot use any C library routine that might be non-reentrant.
2116 * malloc/free are often non-reentrant, and anything that might call them is
2117 * just as dangerous. We avoid sprintf here for that reason. Building up
2118 * error messages with strcpy/strcat is tedious but should be quite safe.
2119 * We also save/restore errno in case the signal handler support doesn't.
2121 * NOTE: this routine must not generate any error message longer than
2122 * INITIAL_EXPBUFFER_SIZE (currently 256), since we dare not try to
2123 * expand conn->errorMessage!
2127 PQrequestCancel(PGconn *conn)
2129 int save_errno = SOCK_ERRNO;
2134 CancelRequestPacket cp;
2137 /* Check we have an open connection */
2143 strcpy(conn->errorMessage.data,
2144 "PQrequestCancel() -- connection is not open\n");
2145 conn->errorMessage.len = strlen(conn->errorMessage.data);
2147 WSASetLastError(save_errno);
2155 * We need to open a temporary connection to the postmaster. Use the
2156 * information saved by connectDB to do this with only kernel calls.
2158 if ((tmpsock = socket(conn->raddr.sa.sa_family, SOCK_STREAM, 0)) < 0)
2160 strcpy(conn->errorMessage.data,
2161 "PQrequestCancel() -- socket() failed: ");
2162 goto cancel_errReturn;
2165 if (connect(tmpsock, &conn->raddr.sa, conn->raddr_len) < 0)
2167 if (SOCK_ERRNO == EINTR)
2168 /* Interrupted system call - we'll just try again */
2170 strcpy(conn->errorMessage.data,
2171 "PQrequestCancel() -- connect() failed: ");
2172 goto cancel_errReturn;
2176 * We needn't set nonblocking I/O or NODELAY options here.
2179 /* Create and send the cancel request packet. */
2181 crp.packetlen = htonl((uint32) sizeof(crp));
2182 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2183 crp.cp.backendPID = htonl(conn->be_pid);
2184 crp.cp.cancelAuthCode = htonl(conn->be_key);
2187 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2189 if (SOCK_ERRNO == EINTR)
2190 /* Interrupted system call - we'll just try again */
2192 strcpy(conn->errorMessage.data,
2193 "PQrequestCancel() -- send() failed: ");
2194 goto cancel_errReturn;
2199 closesocket(tmpsock);
2200 WSASetLastError(save_errno);
2209 strcat(conn->errorMessage.data, SOCK_STRERROR(SOCK_ERRNO));
2210 strcat(conn->errorMessage.data, "\n");
2211 conn->errorMessage.len = strlen(conn->errorMessage.data);
2215 closesocket(tmpsock);
2216 WSASetLastError(save_errno);
2227 * pqPacketSend() -- send a single-packet message.
2228 * this is like PacketSend(), defined in backend/libpq/pqpacket.c
2230 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2231 * SIDE_EFFECTS: may block.
2234 pqPacketSend(PGconn *conn, const char *buf, size_t len)
2236 /* Send the total packet size. */
2238 if (pqPutInt(4 + len, 4, conn))
2239 return STATUS_ERROR;
2241 /* Send the packet itself. */
2243 if (pqPutnchar(buf, len, conn))
2244 return STATUS_ERROR;
2247 return STATUS_ERROR;
2255 #error "You must compile this file with SYSCONFDIR defined."
2258 #define MAXBUFSIZE 256
2261 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2263 char *service = conninfo_getval(options, "service");
2264 char *serviceFile = SYSCONFDIR "/pg_service.conf";
2265 int group_found = 0;
2269 if (service != NULL)
2272 char buf[MAXBUFSIZE],
2275 f = fopen(serviceFile, "r");
2278 printfPQExpBuffer(errorMessage, "ERROR: Service file '%s' not found\n",
2283 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2287 if (strlen(line) >= MAXBUFSIZE - 2)
2290 printfPQExpBuffer(errorMessage,
2291 "ERROR: line %d too long in service file '%s'\n",
2297 /* ignore EOL at end of line */
2298 if (strlen(line) && line[strlen(line) - 1] == '\n')
2299 line[strlen(line) - 1] = 0;
2301 /* ignore leading blanks */
2302 while (*line && isspace((unsigned char) line[0]))
2305 /* ignore comments and empty lines */
2306 if (strlen(line) == 0 || line[0] == '#')
2309 /* Check for right groupname */
2314 /* group info already read */
2319 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2320 line[strlen(service) + 1] == ']')
2330 * Finally, we are in the right group and can parse
2337 key = strtok(line, "=");
2340 printfPQExpBuffer(errorMessage,
2341 "ERROR: syntax error in service file '%s', line %d\n",
2349 * If not already set, set the database name to the
2350 * name of the service
2352 for (i = 0; options[i].keyword; i++)
2353 if (strcmp(options[i].keyword, "dbname") == 0)
2354 if (options[i].val == NULL)
2355 options[i].val = strdup(service);
2357 val = line + strlen(line) + 1;
2360 for (i = 0; options[i].keyword; i++)
2362 if (strcmp(options[i].keyword, key) == 0)
2364 if (options[i].val != NULL)
2365 free(options[i].val);
2366 options[i].val = strdup(val);
2373 printfPQExpBuffer(errorMessage,
2374 "ERROR: syntax error in service file '%s', line %d\n",
2392 * Conninfo parser routine
2394 * If successful, a malloc'd PQconninfoOption array is returned.
2395 * If not successful, NULL is returned and an error message is
2396 * left in errorMessage.
2398 static PQconninfoOption *
2399 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2407 PQconninfoOption *options;
2408 PQconninfoOption *option;
2409 char errortmp[INITIAL_EXPBUFFER_SIZE];
2411 /* Make a working copy of PQconninfoOptions */
2412 options = malloc(sizeof(PQconninfoOptions));
2413 if (options == NULL)
2415 printfPQExpBuffer(errorMessage,
2416 libpq_gettext("out of memory\n"));
2419 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2421 /* Need a modifiable copy of the input string */
2422 if ((buf = strdup(conninfo)) == NULL)
2424 printfPQExpBuffer(errorMessage,
2425 libpq_gettext("out of memory\n"));
2426 PQconninfoFree(options);
2433 /* Skip blanks before the parameter name */
2434 if (isspace((unsigned char) *cp))
2440 /* Get the parameter name */
2446 if (isspace((unsigned char) *cp))
2451 if (!isspace((unsigned char) *cp))
2460 /* Check that there is a following '=' */
2463 printfPQExpBuffer(errorMessage,
2464 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2466 PQconninfoFree(options);
2472 /* Skip blanks after the '=' */
2475 if (!isspace((unsigned char) *cp))
2480 /* Get the parameter value */
2488 if (isspace((unsigned char) *cp))
2512 printfPQExpBuffer(errorMessage,
2513 libpq_gettext("unterminated quoted string in connection info string\n"));
2514 PQconninfoFree(options);
2536 * Now we have the name and the value. Search for the param
2539 for (option = options; option->keyword != NULL; option++)
2541 if (strcmp(option->keyword, pname) == 0)
2544 if (option->keyword == NULL)
2546 printfPQExpBuffer(errorMessage,
2547 libpq_gettext("invalid connection option \"%s\"\n"),
2549 PQconninfoFree(options);
2559 option->val = strdup(pval);
2563 /* Now check for service info */
2564 if (parseServiceInfo(options, errorMessage))
2566 PQconninfoFree(options);
2571 /* Done with the modifiable input string */
2575 * Get the fallback resources for parameters not specified in the
2578 for (option = options; option->keyword != NULL; option++)
2580 if (option->val != NULL)
2581 continue; /* Value was in conninfo */
2584 * Try to get the environment variable fallback
2586 if (option->envvar != NULL)
2588 if ((tmp = getenv(option->envvar)) != NULL)
2590 option->val = strdup(tmp);
2596 * No environment variable specified or this one isn't set - try
2599 if (option->compiled != NULL)
2601 option->val = strdup(option->compiled);
2606 * Special handling for user
2608 if (strcmp(option->keyword, "user") == 0)
2610 option->val = fe_getauthname(errortmp);
2611 /* note any error message is thrown away */
2616 * Special handling for dbname
2618 if (strcmp(option->keyword, "dbname") == 0)
2620 tmp = conninfo_getval(options, "user");
2622 option->val = strdup(tmp);
2632 conninfo_getval(PQconninfoOption *connOptions,
2633 const char *keyword)
2635 PQconninfoOption *option;
2637 for (option = connOptions; option->keyword != NULL; option++)
2639 if (strcmp(option->keyword, keyword) == 0)
2648 PQconninfoFree(PQconninfoOption *connOptions)
2650 PQconninfoOption *option;
2652 if (connOptions == NULL)
2655 for (option = connOptions; option->keyword != NULL; option++)
2657 if (option->val != NULL)
2664 /* =========== accessor functions for PGconn ========= */
2666 PQdb(const PGconn *conn)
2669 return (char *) NULL;
2670 return conn->dbName;
2674 PQuser(const PGconn *conn)
2677 return (char *) NULL;
2678 return conn->pguser;
2682 PQpass(const PGconn *conn)
2685 return (char *) NULL;
2686 return conn->pgpass;
2690 PQhost(const PGconn *conn)
2693 return (char *) NULL;
2694 return conn->pghost ? conn->pghost : conn->pgunixsocket;
2698 PQport(const PGconn *conn)
2701 return (char *) NULL;
2702 return conn->pgport;
2706 PQtty(const PGconn *conn)
2709 return (char *) NULL;
2714 PQoptions(const PGconn *conn)
2717 return (char *) NULL;
2718 return conn->pgoptions;
2722 PQstatus(const PGconn *conn)
2725 return CONNECTION_BAD;
2726 return conn->status;
2730 PQerrorMessage(const PGconn *conn)
2733 return libpq_gettext("connection pointer is NULL\n");
2735 return conn->errorMessage.data;
2739 PQsocket(const PGconn *conn)
2747 PQbackendPID(const PGconn *conn)
2749 if (!conn || conn->status != CONNECTION_OK)
2751 return conn->be_pid;
2755 PQclientEncoding(const PGconn *conn)
2757 if (!conn || conn->status != CONNECTION_OK)
2759 return conn->client_encoding;
2763 PQsetClientEncoding(PGconn *conn, const char *encoding)
2766 static char query[] = "set client_encoding to '%s'";
2770 if (!conn || conn->status != CONNECTION_OK)
2776 /* check query buffer overflow */
2777 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2780 /* ok, now send a query */
2781 sprintf(qbuf, query, encoding);
2782 res = PQexec(conn, qbuf);
2784 if (res == (PGresult *) NULL)
2786 if (res->resultStatus != PGRES_COMMAND_OK)
2790 /* change libpq internal encoding */
2791 conn->client_encoding = pg_char_to_encoding(encoding);
2792 status = 0; /* everything is ok */
2799 PQtrace(PGconn *conn, FILE *debug_port)
2802 conn->status == CONNECTION_BAD)
2805 conn->Pfdebug = debug_port;
2809 PQuntrace(PGconn *conn)
2811 /* note: better allow untrace even when connection bad */
2816 fflush(conn->Pfdebug);
2817 conn->Pfdebug = NULL;
2822 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2824 PQnoticeProcessor old;
2829 old = conn->noticeHook;
2832 conn->noticeHook = proc;
2833 conn->noticeArg = arg;
2839 * The default notice/error message processor just prints the
2840 * message on stderr. Applications can override this if they
2841 * want the messages to go elsewhere (a window, for example).
2842 * Note that simply discarding notices is probably a bad idea.
2846 defaultNoticeProcessor(void *arg, const char *message)
2848 (void) arg; /* not used */
2849 /* Note: we expect the supplied string to end with a newline already. */
2850 fprintf(stderr, "%s", message);
2853 /* returns a pointer to the next token or NULL if the current
2854 * token doesn't match */
2856 pwdfMatchesString(char *buf, char *token)
2860 bool bslash = false;
2862 if (buf == NULL || token == NULL)
2870 if (*tbuf == '\\' && !bslash)
2875 if (*tbuf == ':' && *ttok == 0 && !bslash)
2891 /* Get a password from the password file. Return value is malloc'd. */
2893 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
2898 struct stat stat_buf;
2900 #define LINELEN NAMEDATALEN*5
2903 if (dbname == NULL || strlen(dbname) == 0)
2906 if (username == NULL || strlen(username) == 0)
2909 if (hostname == NULL)
2910 hostname = DefaultHost;
2913 port = DEF_PGPORT_STR;
2915 /* Look for it in the home dir */
2916 home = getenv("HOME");
2920 pgpassfile = malloc(strlen(home) + 1 + strlen(PGPASSFILE) + 1);
2923 fprintf(stderr, libpq_gettext("out of memory\n"));
2927 sprintf(pgpassfile, "%s/%s", home, PGPASSFILE);
2929 /* If password file cannot be opened, ignore it. */
2930 if (stat(pgpassfile, &stat_buf) == -1)
2937 /* If password file is insecure, alert the user and ignore it. */
2938 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
2941 libpq_gettext("WARNING: Password file %s has world or group read access; permission should be u=rw (0600)\n"),
2948 fp = fopen(pgpassfile, "r");
2959 fgets(buf, LINELEN - 1, fp);
2965 /* Remove trailing newline */
2966 if (buf[len - 1] == '\n')
2969 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
2970 (t = pwdfMatchesString(t, port)) == NULL ||
2971 (t = pwdfMatchesString(t, dbname)) == NULL ||
2972 (t = pwdfMatchesString(t, username)) == NULL)