1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/interfaces/libpq/fe-connect.c,v 1.373 2009/04/24 09:43:10 mha Exp $
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
26 #include "libpq-int.h"
28 #include "pg_config_paths.h"
35 #define _WIN32_IE 0x0500
42 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #ifdef HAVE_NETINET_TCP_H
46 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
51 #ifdef ENABLE_THREAD_SAFETY
53 #include "pthread-win32.h"
63 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
64 #define LDAP_DEPRECATED 1
66 typedef struct timeval LDAP_TIMEVAL;
68 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
69 PQExpBuffer errorMessage);
73 #include "mb/pg_wchar.h"
81 #define PGPASSFILE ".pgpass"
83 #define PGPASSFILE "pgpass.conf"
86 /* fall back options if they are not specified by arguments or defined
87 by environment variables */
88 #define DefaultHost "localhost"
90 #define DefaultOption ""
91 #define DefaultAuthtype ""
92 #define DefaultPassword ""
94 #define DefaultSSLMode "prefer"
96 #define DefaultSSLMode "disable"
100 * Definition of the conninfo parameters and their fallback resources.
102 * If Environment-Var and Compiled-in are specified as NULL, no
103 * fallback is available. If after all no value can be determined
104 * for an option, an error is returned.
106 * The value for the username is treated specially in conninfo_parse.
107 * If the Compiled-in resource is specified as a NULL value, the
108 * user is determined by pg_fe_getauthname().
110 * The Label and Disp-Char entries are provided for applications that
111 * want to use PQconndefaults() to create a generic database connection
112 * dialog. Disp-Char is defined as follows:
113 * "" Normal input field
114 * "*" Password field - hide value
115 * "D" Debug option - don't show by default
117 * PQconninfoOptions[] is a constant static array that we use to initialize
118 * a dynamically allocated working copy. All the "val" fields in
119 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
120 * fields point to malloc'd strings that should be freed when the working
121 * array is freed (see PQconninfoFree).
124 static const PQconninfoOption PQconninfoOptions[] = {
126 * "authtype" is no longer used, so mark it "don't show". We keep it in
127 * the array so as not to reject conninfo strings from old apps that might
128 * still try to set it.
130 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
131 "Database-Authtype", "D", 20},
133 {"service", "PGSERVICE", NULL, NULL,
134 "Database-Service", "", 20},
136 {"user", "PGUSER", NULL, NULL,
137 "Database-User", "", 20},
139 {"password", "PGPASSWORD", NULL, NULL,
140 "Database-Password", "*", 20},
142 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
143 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
145 {"dbname", "PGDATABASE", NULL, NULL,
146 "Database-Name", "", 20},
148 {"host", "PGHOST", NULL, NULL,
149 "Database-Host", "", 40},
151 {"hostaddr", "PGHOSTADDR", NULL, NULL,
152 "Database-Host-IP-Address", "", 45},
154 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
155 "Database-Port", "", 6},
158 * "tty" is no longer used either, but keep it present for backwards
161 {"tty", "PGTTY", DefaultTty, NULL,
162 "Backend-Debug-TTY", "D", 40},
164 {"options", "PGOPTIONS", DefaultOption, NULL,
165 "Backend-Debug-Options", "D", 40},
170 * "requiressl" is deprecated, its purpose having been taken over by
171 * "sslmode". It remains for backwards compatibility.
173 {"requiressl", "PGREQUIRESSL", "0", NULL,
174 "Require-SSL", "D", 1},
178 * ssl options are allowed even without client SSL support because the
179 * client can still handle SSL modes "disable" and "allow". Other parameters
180 * have no effect on non-SSL connections, so there is no reason to exclude them
181 * since none of them are mandatory.
183 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
184 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
186 {"sslcert", "PGSSLCERT", NULL, NULL,
187 "SSL-Client-Cert", "", 64},
189 {"sslkey", "PGSSLKEY", NULL, NULL,
190 "SSL-Client-Key", "", 64},
192 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
193 "SSL-Root-Certificate", "", 64},
195 {"sslcrl", "PGSSLCRL", NULL, NULL,
196 "SSL-Revocation-List", "", 64},
198 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
199 /* Kerberos and GSSAPI authentication support specifying the service name */
200 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
201 "Kerberos-service-name", "", 20},
204 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
207 * GSSAPI and SSPI both enabled, give a way to override which is used by
210 {"gsslib", "PGGSSLIB", NULL, NULL,
211 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
214 /* Terminating entry --- MUST BE LAST */
215 {NULL, NULL, NULL, NULL,
219 static const PQEnvironmentOption EnvironmentOptions[] =
221 /* common user-interface settings */
223 "PGDATESTYLE", "datestyle"
229 "PGCLIENTENCODING", "client_encoding"
231 /* internal performance-related settings */
241 static bool connectOptions1(PGconn *conn, const char *conninfo);
242 static bool connectOptions2(PGconn *conn);
243 static int connectDBStart(PGconn *conn);
244 static int connectDBComplete(PGconn *conn);
245 static PGconn *makeEmptyPGconn(void);
246 static void freePGconn(PGconn *conn);
247 static void closePGconn(PGconn *conn);
248 static PQconninfoOption *conninfo_parse(const char *conninfo,
249 PQExpBuffer errorMessage, bool use_defaults);
250 static char *conninfo_getval(PQconninfoOption *connOptions,
251 const char *keyword);
252 static void defaultNoticeReceiver(void *arg, const PGresult *res);
253 static void defaultNoticeProcessor(void *arg, const char *message);
254 static int parseServiceInfo(PQconninfoOption *options,
255 PQExpBuffer errorMessage);
256 static char *pwdfMatchesString(char *buf, char *token);
257 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
259 static void default_threadlock(int acquire);
262 /* global variable because fe-auth.c needs to access it */
263 pgthreadlock_t pg_g_threadlock = default_threadlock;
267 * Connecting to a Database
269 * There are now four different ways a user of this API can connect to the
270 * database. Two are not recommended for use in new code, because of their
271 * lack of extensibility with respect to the passing of options to the
272 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
275 * If it is desired to connect in a synchronous (blocking) manner, use the
276 * function PQconnectdb.
278 * To connect in an asynchronous (non-blocking) manner, use the functions
279 * PQconnectStart, and PQconnectPoll.
281 * Internally, the static functions connectDBStart, connectDBComplete
282 * are part of the connection procedure.
288 * establishes a connection to a postgres backend through the postmaster
289 * using connection information in a string.
291 * The conninfo string is a white-separated list of
295 * definitions. Value might be a single value containing no whitespaces or
296 * a single quoted string. If a single quote should appear anywhere in
297 * the value, it must be escaped with a backslash like \'
299 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
300 * if a memory allocation failed.
301 * If the status field of the connection returned is CONNECTION_BAD,
302 * then some fields may be null'ed out instead of having valid values.
304 * You should call PQfinish (if conn is not NULL) regardless of whether this
308 PQconnectdb(const char *conninfo)
310 PGconn *conn = PQconnectStart(conninfo);
312 if (conn && conn->status != CONNECTION_BAD)
313 (void) connectDBComplete(conn);
321 * Begins the establishment of a connection to a postgres backend through the
322 * postmaster using connection information in a string.
324 * See comment for PQconnectdb for the definition of the string format.
326 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
327 * you should not attempt to proceed with this connection. If the status
328 * field of the connection returned is CONNECTION_BAD, an error has
329 * occurred. In this case you should call PQfinish on the result, (perhaps
330 * inspecting the error message first). Other fields of the structure may not
331 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
332 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
335 * See PQconnectPoll for more info.
338 PQconnectStart(const char *conninfo)
343 * Allocate memory for the conn structure
345 conn = makeEmptyPGconn();
350 * Parse the conninfo string
352 if (!connectOptions1(conn, conninfo))
356 * Compute derived options
358 if (!connectOptions2(conn))
362 * Connect to the database
364 if (!connectDBStart(conn))
366 /* Just in case we failed to set it in connectDBStart */
367 conn->status = CONNECTION_BAD;
376 * Internal subroutine to set up connection parameters given an already-
377 * created PGconn and a conninfo string. Derived settings should be
378 * processed by calling connectOptions2 next. (We split them because
379 * PQsetdbLogin overrides defaults in between.)
381 * Returns true if OK, false if trouble (in which case errorMessage is set
382 * and so is conn->status).
385 connectOptions1(PGconn *conn, const char *conninfo)
387 PQconninfoOption *connOptions;
391 * Parse the conninfo string
393 connOptions = conninfo_parse(conninfo, &conn->errorMessage, true);
394 if (connOptions == NULL)
396 conn->status = CONNECTION_BAD;
397 /* errorMessage is already set */
402 * Move option values into conn structure
404 * Don't put anything cute here --- intelligence should be in
405 * connectOptions2 ...
407 * XXX: probably worth checking strdup() return value here...
409 tmp = conninfo_getval(connOptions, "hostaddr");
410 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
411 tmp = conninfo_getval(connOptions, "host");
412 conn->pghost = tmp ? strdup(tmp) : NULL;
413 tmp = conninfo_getval(connOptions, "port");
414 conn->pgport = tmp ? strdup(tmp) : NULL;
415 tmp = conninfo_getval(connOptions, "tty");
416 conn->pgtty = tmp ? strdup(tmp) : NULL;
417 tmp = conninfo_getval(connOptions, "options");
418 conn->pgoptions = tmp ? strdup(tmp) : NULL;
419 tmp = conninfo_getval(connOptions, "dbname");
420 conn->dbName = tmp ? strdup(tmp) : NULL;
421 tmp = conninfo_getval(connOptions, "user");
422 conn->pguser = tmp ? strdup(tmp) : NULL;
423 tmp = conninfo_getval(connOptions, "password");
424 conn->pgpass = tmp ? strdup(tmp) : NULL;
425 tmp = conninfo_getval(connOptions, "connect_timeout");
426 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
427 tmp = conninfo_getval(connOptions, "sslmode");
428 conn->sslmode = tmp ? strdup(tmp) : NULL;
429 tmp = conninfo_getval(connOptions, "sslkey");
430 conn->sslkey = tmp ? strdup(tmp) : NULL;
431 tmp = conninfo_getval(connOptions, "sslcert");
432 conn->sslcert = tmp ? strdup(tmp) : NULL;
433 tmp = conninfo_getval(connOptions, "sslrootcert");
434 conn->sslrootcert = tmp ? strdup(tmp) : NULL;
435 tmp = conninfo_getval(connOptions, "sslcrl");
436 conn->sslcrl = tmp ? strdup(tmp) : NULL;
438 tmp = conninfo_getval(connOptions, "requiressl");
439 if (tmp && tmp[0] == '1')
441 /* here warn that the requiressl option is deprecated? */
444 conn->sslmode = strdup("require");
447 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
448 tmp = conninfo_getval(connOptions, "krbsrvname");
449 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
451 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
452 tmp = conninfo_getval(connOptions, "gsslib");
453 conn->gsslib = tmp ? strdup(tmp) : NULL;
457 * Free the option info - all is in conn now
459 PQconninfoFree(connOptions);
467 * Compute derived connection options after absorbing all user-supplied info.
469 * Returns true if OK, false if trouble (in which case errorMessage is set
470 * and so is conn->status).
473 connectOptions2(PGconn *conn)
476 * If database name was not given, default it to equal user name
478 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
479 && conn->pguser != NULL)
483 conn->dbName = strdup(conn->pguser);
487 * Supply default password if none given
489 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
493 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
494 conn->dbName, conn->pguser);
495 if (conn->pgpass == NULL)
496 conn->pgpass = strdup(DefaultPassword);
500 * Allow unix socket specification in the host name
502 if (conn->pghost && is_absolute_path(conn->pghost))
504 if (conn->pgunixsocket)
505 free(conn->pgunixsocket);
506 conn->pgunixsocket = conn->pghost;
511 * validate sslmode option
515 if (strcmp(conn->sslmode, "disable") != 0
516 && strcmp(conn->sslmode, "allow") != 0
517 && strcmp(conn->sslmode, "prefer") != 0
518 && strcmp(conn->sslmode, "require") != 0
519 && strcmp(conn->sslmode, "verify-ca") != 0
520 && strcmp(conn->sslmode, "verify-full") != 0)
522 conn->status = CONNECTION_BAD;
523 printfPQExpBuffer(&conn->errorMessage,
524 libpq_gettext("invalid sslmode value: \"%s\"\n"),
530 switch (conn->sslmode[0])
532 case 'a': /* "allow" */
533 case 'p': /* "prefer" */
536 * warn user that an SSL connection will never be negotiated
537 * since SSL was not compiled in?
541 case 'r': /* "require" */
542 case 'v': /* "verify-ca" or "verify-full" */
543 conn->status = CONNECTION_BAD;
544 printfPQExpBuffer(&conn->errorMessage,
545 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
552 conn->sslmode = strdup(DefaultSSLMode);
555 * Only if we get this far is it appropriate to try to connect. (We need a
556 * state flag, rather than just the boolean result of this function, in
557 * case someone tries to PQreset() the PGconn.)
559 conn->options_valid = true;
567 * Parse an empty string like PQconnectdb() would do and return the
568 * resulting connection options array, ie, all the default values that are
569 * available from the environment etc. On error (eg out of memory),
572 * Using this function, an application may determine all possible options
573 * and their current default values.
575 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
576 * and should be freed when no longer needed via PQconninfoFree(). (In prior
577 * versions, the returned array was static, but that's not thread-safe.)
578 * Pre-7.0 applications that use this function will see a small memory leak
579 * until they are updated to call PQconninfoFree.
584 PQExpBufferData errorBuf;
585 PQconninfoOption *connOptions;
587 initPQExpBuffer(&errorBuf);
588 if (PQExpBufferBroken(&errorBuf))
589 return NULL; /* out of memory already :-( */
590 connOptions = conninfo_parse("", &errorBuf, true);
591 termPQExpBuffer(&errorBuf);
598 * establishes a connection to a postgres backend through the postmaster
599 * at the specified host and port.
601 * returns a PGconn* which is needed for all subsequent libpq calls
603 * if the status field of the connection returned is CONNECTION_BAD,
604 * then only the errorMessage is likely to be useful.
608 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
609 const char *pgtty, const char *dbName, const char *login,
615 * Allocate memory for the conn structure
617 conn = makeEmptyPGconn();
622 * If the dbName parameter contains '=', assume it's a conninfo string.
624 if (dbName && strchr(dbName, '='))
626 if (!connectOptions1(conn, dbName))
632 * Old-style path: first, parse an empty conninfo string in order to
633 * set up the same defaults that PQconnectdb() would use.
635 if (!connectOptions1(conn, ""))
638 /* Insert dbName parameter value into struct */
639 if (dbName && dbName[0] != '\0')
643 conn->dbName = strdup(dbName);
648 * Insert remaining parameters into struct, overriding defaults (as well
649 * as any conflicting data from dbName taken as a conninfo).
651 if (pghost && pghost[0] != '\0')
655 conn->pghost = strdup(pghost);
658 if (pgport && pgport[0] != '\0')
662 conn->pgport = strdup(pgport);
665 if (pgoptions && pgoptions[0] != '\0')
668 free(conn->pgoptions);
669 conn->pgoptions = strdup(pgoptions);
672 if (pgtty && pgtty[0] != '\0')
676 conn->pgtty = strdup(pgtty);
679 if (login && login[0] != '\0')
683 conn->pguser = strdup(login);
686 if (pwd && pwd[0] != '\0')
690 conn->pgpass = strdup(pwd);
694 * Compute derived options
696 if (!connectOptions2(conn))
700 * Connect to the database
702 if (connectDBStart(conn))
703 (void) connectDBComplete(conn);
711 * Sets the TCP_NODELAY socket option.
712 * Returns 1 if successful, 0 if not.
716 connectNoDelay(PGconn *conn)
721 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
727 appendPQExpBuffer(&conn->errorMessage,
728 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
729 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
739 * connectFailureMessage -
740 * create a friendly error message on connection failure.
744 connectFailureMessage(PGconn *conn, int errorno)
748 #ifdef HAVE_UNIX_SOCKETS
749 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
751 char service[NI_MAXHOST];
753 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
755 service, sizeof(service),
757 appendPQExpBuffer(&conn->errorMessage,
758 libpq_gettext("could not connect to server: %s\n"
759 "\tIs the server running locally and accepting\n"
760 "\tconnections on Unix domain socket \"%s\"?\n"),
761 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
765 #endif /* HAVE_UNIX_SOCKETS */
767 appendPQExpBuffer(&conn->errorMessage,
768 libpq_gettext("could not connect to server: %s\n"
769 "\tIs the server running on host \"%s\" and accepting\n"
770 "\tTCP/IP connections on port %s?\n"),
771 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
784 * Begin the process of making a connection to the backend.
786 * Returns 1 if successful, 0 if not.
790 connectDBStart(PGconn *conn)
794 struct addrinfo *addrs = NULL;
795 struct addrinfo hint;
802 if (!conn->options_valid)
803 goto connect_errReturn;
805 /* Ensure our buffers are empty */
806 conn->inStart = conn->inCursor = conn->inEnd = 0;
810 * Determine the parameters to pass to pg_getaddrinfo_all.
813 /* Initialize hint structure */
814 MemSet(&hint, 0, sizeof(hint));
815 hint.ai_socktype = SOCK_STREAM;
816 hint.ai_family = AF_UNSPEC;
818 /* Set up port number as a string */
819 if (conn->pgport != NULL && conn->pgport[0] != '\0')
820 portnum = atoi(conn->pgport);
822 portnum = DEF_PGPORT;
823 snprintf(portstr, sizeof(portstr), "%d", portnum);
825 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
827 /* Using pghostaddr avoids a hostname lookup */
828 node = conn->pghostaddr;
829 hint.ai_family = AF_UNSPEC;
830 hint.ai_flags = AI_NUMERICHOST;
832 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
834 /* Using pghost, so we have to look-up the hostname */
836 hint.ai_family = AF_UNSPEC;
840 #ifdef HAVE_UNIX_SOCKETS
841 /* pghostaddr and pghost are NULL, so use Unix domain socket */
843 hint.ai_family = AF_UNIX;
844 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
846 /* Without Unix sockets, default to localhost instead */
848 hint.ai_family = AF_UNSPEC;
849 #endif /* HAVE_UNIX_SOCKETS */
852 /* Use pg_getaddrinfo_all() to resolve the address */
853 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
857 appendPQExpBuffer(&conn->errorMessage,
858 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
859 node, gai_strerror(ret));
861 appendPQExpBuffer(&conn->errorMessage,
862 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
863 portstr, gai_strerror(ret));
865 pg_freeaddrinfo_all(hint.ai_family, addrs);
866 goto connect_errReturn;
870 /* setup values based on SSL mode */
871 if (conn->sslmode[0] == 'd') /* "disable" */
872 conn->allow_ssl_try = false;
873 else if (conn->sslmode[0] == 'a') /* "allow" */
874 conn->wait_ssl_try = true;
878 * Set up to try to connect, with protocol 3.0 as the first attempt.
880 conn->addrlist = addrs;
881 conn->addr_cur = addrs;
882 conn->addrlist_family = hint.ai_family;
883 conn->pversion = PG_PROTOCOL(3, 0);
884 conn->status = CONNECTION_NEEDED;
887 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
888 * so that it can easily be re-executed if needed again during the
889 * asynchronous startup process. However, we must run it once here,
890 * because callers expect a success return from this routine to mean that
891 * we are in PGRES_POLLING_WRITING connection state.
893 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
899 pqsecure_close(conn);
900 closesocket(conn->sock);
903 conn->status = CONNECTION_BAD;
911 * Block and complete a connection.
913 * Returns 1 on success, 0 on failure.
916 connectDBComplete(PGconn *conn)
918 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
919 time_t finish_time = ((time_t) -1);
921 if (conn == NULL || conn->status == CONNECTION_BAD)
925 * Set up a time limit, if connect_timeout isn't zero.
927 if (conn->connect_timeout != NULL)
929 int timeout = atoi(conn->connect_timeout);
934 * Rounding could cause connection to fail; need at least 2 secs
938 /* calculate the finish time based on start + timeout */
939 finish_time = time(NULL) + timeout;
946 * Wait, if necessary. Note that the initial state (just after
947 * PQconnectStart) is to wait for the socket to select for writing.
951 case PGRES_POLLING_OK:
952 /* Reset stored error messages since we now have a working connection */
953 resetPQExpBuffer(&conn->errorMessage);
954 return 1; /* success! */
956 case PGRES_POLLING_READING:
957 if (pqWaitTimed(1, 0, conn, finish_time))
959 conn->status = CONNECTION_BAD;
964 case PGRES_POLLING_WRITING:
965 if (pqWaitTimed(0, 1, conn, finish_time))
967 conn->status = CONNECTION_BAD;
973 /* Just in case we failed to set it in PQconnectPoll */
974 conn->status = CONNECTION_BAD;
979 * Now try to advance the state machine.
981 flag = PQconnectPoll(conn);
988 * Poll an asynchronous connection.
990 * Returns a PostgresPollingStatusType.
991 * Before calling this function, use select(2) to determine when data
994 * You must call PQfinish whether or not this fails.
996 * This function and PQconnectStart are intended to allow connections to be
997 * made without blocking the execution of your program on remote I/O. However,
998 * there are a number of caveats:
1000 * o If you call PQtrace, ensure that the stream object into which you trace
1002 * o If you do not supply an IP address for the remote host (i.e. you
1003 * supply a host name instead) then PQconnectStart will block on
1004 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1005 * supplying neither a host name nor a host address).
1006 * o If your backend wants to use Kerberos authentication then you must
1007 * supply both a host name and a host address, otherwise this function
1008 * may block on gethostname.
1012 PostgresPollingStatusType
1013 PQconnectPoll(PGconn *conn)
1019 return PGRES_POLLING_FAILED;
1021 /* Get the new data */
1022 switch (conn->status)
1025 * We really shouldn't have been polled in these two cases, but we
1028 case CONNECTION_BAD:
1029 return PGRES_POLLING_FAILED;
1031 return PGRES_POLLING_OK;
1033 /* These are reading states */
1034 case CONNECTION_AWAITING_RESPONSE:
1035 case CONNECTION_AUTH_OK:
1037 /* Load waiting data */
1038 int n = pqReadData(conn);
1043 return PGRES_POLLING_READING;
1048 /* These are writing states, so we just proceed. */
1049 case CONNECTION_STARTED:
1050 case CONNECTION_MADE:
1053 /* We allow pqSetenvPoll to decide whether to proceed. */
1054 case CONNECTION_SETENV:
1057 /* Special cases: proceed without waiting. */
1058 case CONNECTION_SSL_STARTUP:
1059 case CONNECTION_NEEDED:
1063 appendPQExpBuffer(&conn->errorMessage,
1065 "invalid connection state, "
1066 "probably indicative of memory corruption\n"
1072 keep_going: /* We will come back to here until there is
1073 * nothing left to do. */
1074 switch (conn->status)
1076 case CONNECTION_NEEDED:
1079 * Try to initiate a connection to one of the addresses
1080 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1081 * next one to try. We fail when we run out of addresses
1082 * (reporting the error returned for the *last* alternative,
1083 * which may not be what users expect :-().
1085 while (conn->addr_cur != NULL)
1087 struct addrinfo *addr_cur = conn->addr_cur;
1089 /* Remember current address for possible error msg */
1090 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1091 addr_cur->ai_addrlen);
1092 conn->raddr.salen = addr_cur->ai_addrlen;
1095 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1099 * ignore socket() failure if we have more addresses
1102 if (addr_cur->ai_next != NULL)
1104 conn->addr_cur = addr_cur->ai_next;
1107 appendPQExpBuffer(&conn->errorMessage,
1108 libpq_gettext("could not create socket: %s\n"),
1109 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1114 * Select socket options: no delay of outgoing data for
1115 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1118 if (!IS_AF_UNIX(addr_cur->ai_family))
1120 if (!connectNoDelay(conn))
1122 closesocket(conn->sock);
1124 conn->addr_cur = addr_cur->ai_next;
1128 if (!pg_set_noblock(conn->sock))
1130 appendPQExpBuffer(&conn->errorMessage,
1131 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1132 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1133 closesocket(conn->sock);
1135 conn->addr_cur = addr_cur->ai_next;
1140 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1142 appendPQExpBuffer(&conn->errorMessage,
1143 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1144 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1145 closesocket(conn->sock);
1147 conn->addr_cur = addr_cur->ai_next;
1150 #endif /* F_SETFD */
1153 * Start/make connection. This should not block, since we
1154 * are in nonblock mode. If it does, well, too bad.
1156 if (connect(conn->sock, addr_cur->ai_addr,
1157 addr_cur->ai_addrlen) < 0)
1159 if (SOCK_ERRNO == EINPROGRESS ||
1160 SOCK_ERRNO == EWOULDBLOCK ||
1161 SOCK_ERRNO == EINTR ||
1165 * This is fine - we're in non-blocking mode, and
1166 * the connection is in progress. Tell caller to
1167 * wait for write-ready on socket.
1169 conn->status = CONNECTION_STARTED;
1170 return PGRES_POLLING_WRITING;
1172 /* otherwise, trouble */
1177 * Hm, we're connected already --- seems the "nonblock
1178 * connection" wasn't. Advance the state machine and
1179 * go do the next stuff.
1181 conn->status = CONNECTION_STARTED;
1186 * This connection failed --- set up error report, then
1187 * close socket (do it this way in case close() affects
1188 * the value of errno...). We will ignore the connect()
1189 * failure and keep going if there are more addresses.
1191 connectFailureMessage(conn, SOCK_ERRNO);
1192 if (conn->sock >= 0)
1194 closesocket(conn->sock);
1199 * Try the next address, if any.
1201 conn->addr_cur = addr_cur->ai_next;
1202 } /* loop over addresses */
1205 * Ooops, no more addresses. An appropriate error message is
1206 * already set up, so just set the right status.
1211 case CONNECTION_STARTED:
1214 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1217 * Write ready, since we've made it here, so the connection
1218 * has been made ... or has failed.
1222 * Now check (using getsockopt) that there is not an error
1223 * state waiting for us on the socket.
1226 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1227 (char *) &optval, &optlen) == -1)
1229 appendPQExpBuffer(&conn->errorMessage,
1230 libpq_gettext("could not get socket error status: %s\n"),
1231 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1234 else if (optval != 0)
1237 * When using a nonblocking connect, we will typically see
1238 * connect failures at this point, so provide a friendly
1241 connectFailureMessage(conn, optval);
1244 * If more addresses remain, keep trying, just as in the
1245 * case where connect() returned failure immediately.
1247 if (conn->addr_cur->ai_next != NULL)
1249 if (conn->sock >= 0)
1251 closesocket(conn->sock);
1254 conn->addr_cur = conn->addr_cur->ai_next;
1255 conn->status = CONNECTION_NEEDED;
1261 /* Fill in the client address */
1262 conn->laddr.salen = sizeof(conn->laddr.addr);
1263 if (getsockname(conn->sock,
1264 (struct sockaddr *) & conn->laddr.addr,
1265 &conn->laddr.salen) < 0)
1267 appendPQExpBuffer(&conn->errorMessage,
1268 libpq_gettext("could not get client address from socket: %s\n"),
1269 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1274 * Make sure we can write before advancing to next step.
1276 conn->status = CONNECTION_MADE;
1277 return PGRES_POLLING_WRITING;
1280 case CONNECTION_MADE:
1288 * If SSL is enabled and we haven't already got it running,
1289 * request it instead of sending the startup message.
1291 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1293 /* Don't bother requesting SSL over a Unix socket */
1294 conn->allow_ssl_try = false;
1296 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1302 * Send the SSL request packet.
1304 * Theoretically, this could block, but it really
1305 * shouldn't since we only got here if the socket is
1308 pv = htonl(NEGOTIATE_SSL_CODE);
1309 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1311 appendPQExpBuffer(&conn->errorMessage,
1312 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1313 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1316 /* Ok, wait for response */
1317 conn->status = CONNECTION_SSL_STARTUP;
1318 return PGRES_POLLING_READING;
1320 #endif /* USE_SSL */
1323 * Build the startup packet.
1325 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1326 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1327 EnvironmentOptions);
1329 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1330 EnvironmentOptions);
1333 /* will not appendbuffer here, since it's likely to also run out of memory */
1334 printfPQExpBuffer(&conn->errorMessage,
1335 libpq_gettext("out of memory\n"));
1340 * Send the startup packet.
1342 * Theoretically, this could block, but it really shouldn't
1343 * since we only got here if the socket is write-ready.
1345 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1347 appendPQExpBuffer(&conn->errorMessage,
1348 libpq_gettext("could not send startup packet: %s\n"),
1349 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1356 conn->status = CONNECTION_AWAITING_RESPONSE;
1357 return PGRES_POLLING_READING;
1361 * Handle SSL negotiation: wait for postmaster messages and
1362 * respond as necessary.
1364 case CONNECTION_SSL_STARTUP:
1367 PostgresPollingStatusType pollres;
1370 * On first time through, get the postmaster's response to our
1371 * SSL negotiation packet.
1373 if (conn->ssl == NULL)
1376 * We use pqReadData here since it has the logic to
1377 * distinguish no-data-yet from connection closure. Since
1378 * conn->ssl isn't set, a plain recv() will occur.
1383 rdresult = pqReadData(conn);
1386 /* errorMessage is already filled in */
1391 /* caller failed to wait for data */
1392 return PGRES_POLLING_READING;
1394 if (pqGetc(&SSLok, conn) < 0)
1396 /* should not happen really */
1397 return PGRES_POLLING_READING;
1399 /* mark byte consumed */
1400 conn->inStart = conn->inCursor;
1403 /* Set up global SSL state if required */
1404 if (pqsecure_initialize(conn) == -1)
1407 else if (SSLok == 'N')
1409 if (conn->sslmode[0] == 'r' || /* "require" */
1410 conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1412 /* Require SSL, but server does not want it */
1413 appendPQExpBuffer(&conn->errorMessage,
1414 libpq_gettext("server does not support SSL, but SSL was required\n"));
1417 /* Otherwise, proceed with normal startup */
1418 conn->allow_ssl_try = false;
1419 conn->status = CONNECTION_MADE;
1420 return PGRES_POLLING_WRITING;
1422 else if (SSLok == 'E')
1424 /* Received error - probably protocol mismatch */
1426 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1427 if (conn->sslmode[0] == 'r' || /* "require" */
1428 conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1430 /* Require SSL, but server is too old */
1431 appendPQExpBuffer(&conn->errorMessage,
1432 libpq_gettext("server does not support SSL, but SSL was required\n"));
1435 /* Otherwise, try again without SSL */
1436 conn->allow_ssl_try = false;
1437 /* Assume it ain't gonna handle protocol 3, either */
1438 conn->pversion = PG_PROTOCOL(2, 0);
1439 /* Must drop the old connection */
1440 closesocket(conn->sock);
1442 conn->status = CONNECTION_NEEDED;
1447 appendPQExpBuffer(&conn->errorMessage,
1448 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1455 * Begin or continue the SSL negotiation process.
1457 pollres = pqsecure_open_client(conn);
1458 if (pollres == PGRES_POLLING_OK)
1460 /* SSL handshake done, ready to send startup packet */
1461 conn->status = CONNECTION_MADE;
1462 return PGRES_POLLING_WRITING;
1464 if (pollres == PGRES_POLLING_FAILED)
1467 * Failed ... if sslmode is "prefer" then do a non-SSL
1470 if (conn->sslmode[0] == 'p' /* "prefer" */
1471 && conn->allow_ssl_try /* redundant? */
1472 && !conn->wait_ssl_try) /* redundant? */
1474 /* only retry once */
1475 conn->allow_ssl_try = false;
1476 /* Must drop the old connection */
1477 closesocket(conn->sock);
1479 conn->status = CONNECTION_NEEDED;
1484 #else /* !USE_SSL */
1485 /* can't get here */
1487 #endif /* USE_SSL */
1491 * Handle authentication exchange: wait for postmaster messages
1492 * and respond as necessary.
1494 case CONNECTION_AWAITING_RESPONSE:
1502 * Scan the message from current point (note that if we find
1503 * the message is incomplete, we will return without advancing
1504 * inStart, and resume here next time).
1506 conn->inCursor = conn->inStart;
1508 /* Read type byte */
1509 if (pqGetc(&beresp, conn))
1511 /* We'll come back when there is more data */
1512 return PGRES_POLLING_READING;
1516 * Validate message type: we expect only an authentication
1517 * request or an error here. Anything else probably means
1518 * it's not Postgres on the other end at all.
1520 if (!(beresp == 'R' || beresp == 'E'))
1522 appendPQExpBuffer(&conn->errorMessage,
1524 "expected authentication request from "
1525 "server, but received %c\n"),
1530 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1532 /* Read message length word */
1533 if (pqGetInt(&msgLength, 4, conn))
1535 /* We'll come back when there is more data */
1536 return PGRES_POLLING_READING;
1541 /* Set phony message length to disable checks below */
1546 * Try to validate message length before using it.
1547 * Authentication requests can't be very large, although GSS
1548 * auth requests may not be that small. Errors can be a
1549 * little larger, but not huge. If we see a large apparent
1550 * length in an error, it means we're really talking to a
1551 * pre-3.0-protocol server; cope.
1553 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1555 appendPQExpBuffer(&conn->errorMessage,
1557 "expected authentication request from "
1558 "server, but received %c\n"),
1563 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1565 /* Handle error from a pre-3.0 server */
1566 conn->inCursor = conn->inStart + 1; /* reread data */
1567 if (pqGets_append(&conn->errorMessage, conn))
1569 /* We'll come back when there is more data */
1570 return PGRES_POLLING_READING;
1572 /* OK, we read the message; mark data consumed */
1573 conn->inStart = conn->inCursor;
1576 * The postmaster typically won't end its message with a
1577 * newline, so add one to conform to libpq conventions.
1579 appendPQExpBufferChar(&conn->errorMessage, '\n');
1582 * If we tried to open the connection in 3.0 protocol,
1583 * fall back to 2.0 protocol.
1585 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1587 conn->pversion = PG_PROTOCOL(2, 0);
1588 /* Must drop the old connection */
1589 pqsecure_close(conn);
1590 closesocket(conn->sock);
1592 conn->status = CONNECTION_NEEDED;
1600 * Can't process if message body isn't all here yet.
1602 * (In protocol 2.0 case, we are assuming messages carry at
1603 * least 4 bytes of data.)
1606 avail = conn->inEnd - conn->inCursor;
1607 if (avail < msgLength)
1610 * Before returning, try to enlarge the input buffer if
1611 * needed to hold the whole message; see notes in
1614 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1617 /* We'll come back when there is more data */
1618 return PGRES_POLLING_READING;
1621 /* Handle errors. */
1624 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1626 if (pqGetErrorNotice3(conn, true))
1628 /* We'll come back when there is more data */
1629 return PGRES_POLLING_READING;
1634 if (pqGets_append(&conn->errorMessage, conn))
1636 /* We'll come back when there is more data */
1637 return PGRES_POLLING_READING;
1640 /* OK, we read the message; mark data consumed */
1641 conn->inStart = conn->inCursor;
1646 * if sslmode is "allow" and we haven't tried an SSL
1647 * connection already, then retry with an SSL connection
1649 if (conn->sslmode[0] == 'a' /* "allow" */
1650 && conn->ssl == NULL
1651 && conn->allow_ssl_try
1652 && conn->wait_ssl_try)
1654 /* only retry once */
1655 conn->wait_ssl_try = false;
1656 /* Must drop the old connection */
1657 closesocket(conn->sock);
1659 conn->status = CONNECTION_NEEDED;
1664 * if sslmode is "prefer" and we're in an SSL connection,
1665 * then do a non-SSL retry
1667 if (conn->sslmode[0] == 'p' /* "prefer" */
1669 && conn->allow_ssl_try /* redundant? */
1670 && !conn->wait_ssl_try) /* redundant? */
1672 /* only retry once */
1673 conn->allow_ssl_try = false;
1674 /* Must drop the old connection */
1675 pqsecure_close(conn);
1676 closesocket(conn->sock);
1678 conn->status = CONNECTION_NEEDED;
1686 /* It is an authentication request. */
1687 /* Get the type of request. */
1688 if (pqGetInt((int *) &areq, 4, conn))
1690 /* We'll come back when there are more data */
1691 return PGRES_POLLING_READING;
1694 /* Get the password salt if there is one. */
1695 if (areq == AUTH_REQ_MD5)
1697 if (pqGetnchar(conn->md5Salt,
1698 sizeof(conn->md5Salt), conn))
1700 /* We'll come back when there are more data */
1701 return PGRES_POLLING_READING;
1704 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1707 * Continue GSSAPI/SSPI authentication
1709 if (areq == AUTH_REQ_GSS_CONT)
1711 int llen = msgLength - 4;
1714 * We can be called repeatedly for the same buffer. Avoid
1715 * re-allocating the buffer in this case - just re-use the
1718 if (llen != conn->ginbuf.length)
1720 if (conn->ginbuf.value)
1721 free(conn->ginbuf.value);
1723 conn->ginbuf.length = llen;
1724 conn->ginbuf.value = malloc(llen);
1725 if (!conn->ginbuf.value)
1727 printfPQExpBuffer(&conn->errorMessage,
1728 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1734 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1736 /* We'll come back when there is more data. */
1737 return PGRES_POLLING_READING;
1743 * OK, we successfully read the message; mark data consumed
1745 conn->inStart = conn->inCursor;
1747 /* Respond to the request if necessary. */
1750 * Note that conn->pghost must be non-NULL if we are going to
1751 * avoid the Kerberos code doing a hostname look-up.
1754 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1756 conn->errorMessage.len = strlen(conn->errorMessage.data);
1759 conn->errorMessage.len = strlen(conn->errorMessage.data);
1762 * Just make sure that any data sent by pg_fe_sendauth is
1763 * flushed out. Although this theoretically could block, it
1764 * really shouldn't since we don't send large auth responses.
1769 if (areq == AUTH_REQ_OK)
1771 /* We are done with authentication exchange */
1772 conn->status = CONNECTION_AUTH_OK;
1775 * Set asyncStatus so that PQsetResult will think that
1776 * what comes back next is the result of a query. See
1779 conn->asyncStatus = PGASYNC_BUSY;
1782 /* Look to see if we have more data yet. */
1786 case CONNECTION_AUTH_OK:
1789 * Now we expect to hear from the backend. A ReadyForQuery
1790 * message indicates that startup is successful, but we might
1791 * also get an Error message indicating failure. (Notice
1792 * messages indicating nonfatal warnings are also allowed by
1793 * the protocol, as are ParameterStatus and BackendKeyData
1794 * messages.) Easiest way to handle this is to let
1795 * PQgetResult() read the messages. We just have to fake it
1796 * out about the state of the connection, by setting
1797 * asyncStatus = PGASYNC_BUSY (done above).
1801 return PGRES_POLLING_READING;
1803 res = PQgetResult(conn);
1806 * NULL return indicating we have gone to IDLE state is
1811 if (res->resultStatus != PGRES_FATAL_ERROR)
1812 appendPQExpBuffer(&conn->errorMessage,
1813 libpq_gettext("unexpected message from server during startup\n"));
1816 * if the resultStatus is FATAL, then conn->errorMessage
1817 * already has a copy of the error; needn't copy it back.
1818 * But add a newline if it's not there already, since
1819 * postmaster error messages may not have one.
1821 if (conn->errorMessage.len <= 0 ||
1822 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1823 appendPQExpBufferChar(&conn->errorMessage, '\n');
1828 /* We can release the address list now. */
1829 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1830 conn->addrlist = NULL;
1831 conn->addr_cur = NULL;
1833 /* Fire up post-connection housekeeping if needed */
1834 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1836 conn->status = CONNECTION_SETENV;
1837 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1838 conn->next_eo = EnvironmentOptions;
1839 return PGRES_POLLING_WRITING;
1842 /* Otherwise, we are open for business! */
1843 conn->status = CONNECTION_OK;
1844 return PGRES_POLLING_OK;
1847 case CONNECTION_SETENV:
1850 * Do post-connection housekeeping (only needed in protocol 2.0).
1852 * We pretend that the connection is OK for the duration of these
1855 conn->status = CONNECTION_OK;
1857 switch (pqSetenvPoll(conn))
1859 case PGRES_POLLING_OK: /* Success */
1862 case PGRES_POLLING_READING: /* Still going */
1863 conn->status = CONNECTION_SETENV;
1864 return PGRES_POLLING_READING;
1866 case PGRES_POLLING_WRITING: /* Still going */
1867 conn->status = CONNECTION_SETENV;
1868 return PGRES_POLLING_WRITING;
1874 /* We are open for business! */
1875 conn->status = CONNECTION_OK;
1876 return PGRES_POLLING_OK;
1879 appendPQExpBuffer(&conn->errorMessage,
1881 "invalid connection state %c, "
1882 "probably indicative of memory corruption\n"
1893 * We used to close the socket at this point, but that makes it awkward
1894 * for those above us if they wish to remove this socket from their own
1895 * records (an fd_set for example). We'll just have this socket closed
1896 * when PQfinish is called (which is compulsory even after an error, since
1897 * the connection structure must be freed).
1899 conn->status = CONNECTION_BAD;
1900 return PGRES_POLLING_FAILED;
1906 * - create a PGconn data structure with (as yet) no interesting data
1909 makeEmptyPGconn(void)
1916 * Make sure socket support is up and running.
1920 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1925 conn = (PGconn *) malloc(sizeof(PGconn));
1934 /* Zero all pointers and booleans */
1935 MemSet(conn, 0, sizeof(PGconn));
1937 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1938 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1939 conn->status = CONNECTION_BAD;
1940 conn->asyncStatus = PGASYNC_IDLE;
1941 conn->xactStatus = PQTRANS_IDLE;
1942 conn->options_valid = false;
1943 conn->nonblocking = false;
1944 conn->setenv_state = SETENV_STATE_IDLE;
1945 conn->client_encoding = PG_SQL_ASCII;
1946 conn->std_strings = false; /* unless server says differently */
1947 conn->verbosity = PQERRORS_DEFAULT;
1949 conn->password_needed = false;
1951 conn->allow_ssl_try = true;
1952 conn->wait_ssl_try = false;
1956 * We try to send at least 8K at a time, which is the usual size of pipe
1957 * buffers on Unix systems. That way, when we are sending a large amount
1958 * of data, we avoid incurring extra kernel context swaps for partial
1959 * bufferloads. The output buffer is initially made 16K in size, and we
1960 * try to dump it after accumulating 8K.
1962 * With the same goal of minimizing context swaps, the input buffer will
1963 * be enlarged anytime it has less than 8K free, so we initially allocate
1966 conn->inBufSize = 16 * 1024;
1967 conn->inBuffer = (char *) malloc(conn->inBufSize);
1968 conn->outBufSize = 16 * 1024;
1969 conn->outBuffer = (char *) malloc(conn->outBufSize);
1970 initPQExpBuffer(&conn->errorMessage);
1971 initPQExpBuffer(&conn->workBuffer);
1973 if (conn->inBuffer == NULL ||
1974 conn->outBuffer == NULL ||
1975 PQExpBufferBroken(&conn->errorMessage) ||
1976 PQExpBufferBroken(&conn->workBuffer))
1978 /* out of memory already :-( */
1988 * - free an idle (closed) PGconn data structure
1990 * NOTE: this should not overlap any functionality with closePGconn().
1991 * Clearing/resetting of transient state belongs there; what we do here is
1992 * release data that is to be held for the life of the PGconn structure.
1993 * If a value ought to be cleared/freed during PQreset(), do it there not here.
1996 freePGconn(PGconn *conn)
2000 /* let any event procs clean up their state data */
2001 for (i = 0; i < conn->nEvents; i++)
2003 PGEventConnDestroy evt;
2006 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2007 conn->events[i].passThrough);
2008 free(conn->events[i].name);
2015 if (conn->pghostaddr)
2016 free(conn->pghostaddr);
2019 if (conn->pgunixsocket)
2020 free(conn->pgunixsocket);
2023 if (conn->connect_timeout)
2024 free(conn->connect_timeout);
2025 if (conn->pgoptions)
2026 free(conn->pgoptions);
2034 free(conn->sslmode);
2036 free(conn->sslcert);
2039 if (conn->sslrootcert)
2040 free(conn->sslrootcert);
2043 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2044 if (conn->krbsrvname)
2045 free(conn->krbsrvname);
2047 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2051 /* Note that conn->Pfdebug is not ours to close or free */
2052 if (conn->last_query)
2053 free(conn->last_query);
2055 free(conn->inBuffer);
2056 if (conn->outBuffer)
2057 free(conn->outBuffer);
2058 termPQExpBuffer(&conn->errorMessage);
2059 termPQExpBuffer(&conn->workBuffer);
2070 * - properly close a connection to the backend
2072 * This should reset or release all transient state, but NOT the connection
2073 * parameters. On exit, the PGconn should be in condition to start a fresh
2074 * connection with the same parameters (see PQreset()).
2077 closePGconn(PGconn *conn)
2080 pgParameterStatus *pstatus;
2083 * Note that the protocol doesn't allow us to send Terminate messages
2084 * during the startup phase.
2086 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2089 * Try to send "close connection" message to backend. Ignore any
2092 pqPutMsgStart('X', false, conn);
2098 * Must reset the blocking status so a possible reconnect will work.
2100 * Don't call PQsetnonblocking() because it will fail if it's unable to
2101 * flush the connection.
2103 conn->nonblocking = FALSE;
2106 * Close the connection, reset all transient state, flush I/O buffers.
2108 if (conn->sock >= 0)
2110 pqsecure_close(conn);
2111 closesocket(conn->sock);
2114 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2116 conn->asyncStatus = PGASYNC_IDLE;
2117 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2118 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2119 conn->addrlist = NULL;
2120 conn->addr_cur = NULL;
2121 notify = conn->notifyHead;
2122 while (notify != NULL)
2124 PGnotify *prev = notify;
2126 notify = notify->next;
2129 conn->notifyHead = conn->notifyTail = NULL;
2130 pstatus = conn->pstatus;
2131 while (pstatus != NULL)
2133 pgParameterStatus *prev = pstatus;
2135 pstatus = pstatus->next;
2138 conn->pstatus = NULL;
2139 if (conn->lobjfuncs)
2140 free(conn->lobjfuncs);
2141 conn->lobjfuncs = NULL;
2142 conn->inStart = conn->inCursor = conn->inEnd = 0;
2149 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2150 if (conn->gtarg_nam)
2151 gss_release_name(&min_s, &conn->gtarg_nam);
2152 if (conn->ginbuf.length)
2153 gss_release_buffer(&min_s, &conn->ginbuf);
2154 if (conn->goutbuf.length)
2155 gss_release_buffer(&min_s, &conn->goutbuf);
2159 if (conn->ginbuf.length)
2160 free(conn->ginbuf.value);
2161 conn->ginbuf.length = 0;
2162 conn->ginbuf.value = NULL;
2163 if (conn->sspitarget)
2164 free(conn->sspitarget);
2165 conn->sspitarget = NULL;
2168 FreeCredentialsHandle(conn->sspicred);
2169 free(conn->sspicred);
2170 conn->sspicred = NULL;
2174 DeleteSecurityContext(conn->sspictx);
2175 free(conn->sspictx);
2176 conn->sspictx = NULL;
2182 * PQfinish: properly close a connection to the backend. Also frees
2183 * the PGconn data structure so it shouldn't be re-used after this.
2186 PQfinish(PGconn *conn)
2196 * PQreset: resets the connection to the backend by closing the
2197 * existing connection and creating a new one.
2200 PQreset(PGconn *conn)
2206 if (connectDBStart(conn) && connectDBComplete(conn))
2209 * Notify event procs of successful reset. We treat an event
2210 * proc failure as disabling the connection ... good idea?
2214 for (i = 0; i < conn->nEvents; i++)
2216 PGEventConnReset evt;
2219 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2220 conn->events[i].passThrough))
2222 conn->status = CONNECTION_BAD;
2223 printfPQExpBuffer(&conn->errorMessage,
2224 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2225 conn->events[i].name);
2236 * resets the connection to the backend
2237 * closes the existing connection and makes a new one
2238 * Returns 1 on success, 0 on failure.
2241 PQresetStart(PGconn *conn)
2247 return connectDBStart(conn);
2256 * resets the connection to the backend
2257 * closes the existing connection and makes a new one
2259 PostgresPollingStatusType
2260 PQresetPoll(PGconn *conn)
2264 PostgresPollingStatusType status = PQconnectPoll(conn);
2266 if (status == PGRES_POLLING_OK)
2269 * Notify event procs of successful reset. We treat an event
2270 * proc failure as disabling the connection ... good idea?
2274 for (i = 0; i < conn->nEvents; i++)
2276 PGEventConnReset evt;
2279 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2280 conn->events[i].passThrough))
2282 conn->status = CONNECTION_BAD;
2283 printfPQExpBuffer(&conn->errorMessage,
2284 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2285 conn->events[i].name);
2286 return PGRES_POLLING_FAILED;
2294 return PGRES_POLLING_FAILED;
2298 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2300 * A copy is needed to be able to cancel a running query from a different
2301 * thread. If the same structure is used all structure members would have
2302 * to be individually locked (if the entire structure was locked, it would
2303 * be impossible to cancel a synchronous query because the structure would
2304 * have to stay locked for the duration of the query).
2307 PQgetCancel(PGconn *conn)
2317 cancel = malloc(sizeof(PGcancel));
2321 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2322 cancel->be_pid = conn->be_pid;
2323 cancel->be_key = conn->be_key;
2328 /* PQfreeCancel: free a cancel structure */
2330 PQfreeCancel(PGcancel *cancel)
2338 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2339 * current operation.
2341 * The return value is TRUE if the cancel request was successfully
2342 * dispatched, FALSE if not (in which case an error message is available).
2343 * Note: successful dispatch is no guarantee that there will be any effect at
2344 * the backend. The application must read the operation result as usual.
2346 * CAUTION: we want this routine to be safely callable from a signal handler
2347 * (for example, an application might want to call it in a SIGINT handler).
2348 * This means we cannot use any C library routine that might be non-reentrant.
2349 * malloc/free are often non-reentrant, and anything that might call them is
2350 * just as dangerous. We avoid sprintf here for that reason. Building up
2351 * error messages with strcpy/strcat is tedious but should be quite safe.
2352 * We also save/restore errno in case the signal handler support doesn't.
2354 * internal_cancel() is an internal helper function to make code-sharing
2355 * between the two versions of the cancel function possible.
2358 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2359 char *errbuf, int errbufsize)
2361 int save_errno = SOCK_ERRNO;
2368 CancelRequestPacket cp;
2372 * We need to open a temporary connection to the postmaster. Do this with
2373 * only kernel calls.
2375 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2377 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2378 goto cancel_errReturn;
2381 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2384 if (SOCK_ERRNO == EINTR)
2385 /* Interrupted system call - we'll just try again */
2387 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2388 goto cancel_errReturn;
2392 * We needn't set nonblocking I/O or NODELAY options here.
2395 /* Create and send the cancel request packet. */
2397 crp.packetlen = htonl((uint32) sizeof(crp));
2398 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2399 crp.cp.backendPID = htonl(be_pid);
2400 crp.cp.cancelAuthCode = htonl(be_key);
2403 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2405 if (SOCK_ERRNO == EINTR)
2406 /* Interrupted system call - we'll just try again */
2408 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2409 goto cancel_errReturn;
2413 * Wait for the postmaster to close the connection, which indicates that
2414 * it's processed the request. Without this delay, we might issue another
2415 * command only to find that our cancel zaps that command instead of the
2416 * one we thought we were canceling. Note we don't actually expect this
2417 * read to obtain any data, we are just waiting for EOF to be signaled.
2420 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2422 if (SOCK_ERRNO == EINTR)
2423 /* Interrupted system call - we'll just try again */
2425 /* we ignore other error conditions */
2429 closesocket(tmpsock);
2430 SOCK_ERRNO_SET(save_errno);
2436 * Make sure we don't overflow the error buffer. Leave space for the \n at
2437 * the end, and for the terminating zero.
2439 maxlen = errbufsize - strlen(errbuf) - 2;
2442 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2444 strcat(errbuf, "\n");
2447 closesocket(tmpsock);
2448 SOCK_ERRNO_SET(save_errno);
2453 * PQcancel: request query cancel
2455 * Returns TRUE if able to send the cancel request, FALSE if not.
2457 * On failure, an error message is stored in *errbuf, which must be of size
2458 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2462 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2466 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2470 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2471 errbuf, errbufsize);
2475 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2477 * Returns TRUE if able to send the cancel request, FALSE if not.
2479 * On failure, the error message is saved in conn->errorMessage; this means
2480 * that this can't be used when there might be other active operations on
2481 * the connection object.
2483 * NOTE: error messages will be cut off at the current size of the
2484 * error message buffer, since we dare not try to expand conn->errorMessage!
2487 PQrequestCancel(PGconn *conn)
2491 /* Check we have an open connection */
2497 strlcpy(conn->errorMessage.data,
2498 "PQrequestCancel() -- connection is not open\n",
2499 conn->errorMessage.maxlen);
2500 conn->errorMessage.len = strlen(conn->errorMessage.data);
2505 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2506 conn->errorMessage.data, conn->errorMessage.maxlen);
2509 conn->errorMessage.len = strlen(conn->errorMessage.data);
2516 * pqPacketSend() -- convenience routine to send a message to server.
2518 * pack_type: the single-byte message type code. (Pass zero for startup
2519 * packets, which have no message type code.)
2521 * buf, buf_len: contents of message. The given length includes only what
2522 * is in buf; the message type and message length fields are added here.
2524 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2525 * SIDE_EFFECTS: may block.
2527 * Note: all messages sent with this routine have a length word, whether
2528 * it's protocol 2.0 or 3.0.
2531 pqPacketSend(PGconn *conn, char pack_type,
2532 const void *buf, size_t buf_len)
2534 /* Start the message. */
2535 if (pqPutMsgStart(pack_type, true, conn))
2536 return STATUS_ERROR;
2538 /* Send the message body. */
2539 if (pqPutnchar(buf, buf_len, conn))
2540 return STATUS_ERROR;
2542 /* Finish the message. */
2543 if (pqPutMsgEnd(conn))
2544 return STATUS_ERROR;
2546 /* Flush to ensure backend gets it. */
2548 return STATUS_ERROR;
2555 #define LDAP_URL "ldap://"
2556 #define LDAP_DEF_PORT 389
2557 #define PGLDAP_TIMEOUT 2
2559 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2560 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2566 * Search the LDAP URL passed as first argument, treat the result as a
2567 * string of connection options that are parsed and added to the array of
2568 * options passed as second argument.
2570 * LDAP URLs must conform to RFC 1959 without escape sequences.
2571 * ldap://host:port/dn?attributes?scope?filter?extensions
2574 * 0 if the lookup was successful,
2575 * 1 if the connection to the LDAP server could be established but
2576 * the search was unsuccessful,
2577 * 2 if a connection could not be established, and
2578 * 3 if a fatal error occurred.
2580 * An error message is returned in the third argument for return codes 1 and 3.
2583 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2584 PQExpBuffer errorMessage)
2586 int port = LDAP_DEF_PORT,
2607 char *attrs[2] = {NULL, NULL};
2611 struct berval **values;
2612 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2614 if ((url = strdup(purl)) == NULL)
2616 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2621 * Parse URL components, check for correctness. Basically, url has '\0'
2622 * placed at component boundaries and variables are pointed at each
2626 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2628 printfPQExpBuffer(errorMessage,
2629 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2635 hostname = url + strlen(LDAP_URL);
2636 if (*hostname == '/') /* no hostname? */
2637 hostname = "localhost"; /* the default */
2639 /* dn, "distinguished name" */
2640 p = strchr(url + strlen(LDAP_URL), '/');
2641 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2643 printfPQExpBuffer(errorMessage, libpq_gettext(
2644 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2648 *p = '\0'; /* terminate hostname */
2652 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2654 printfPQExpBuffer(errorMessage, libpq_gettext(
2655 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2663 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2665 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2673 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2675 printfPQExpBuffer(errorMessage,
2676 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2682 if ((p = strchr(filter, '?')) != NULL)
2686 if ((p1 = strchr(hostname, ':')) != NULL)
2693 lport = strtol(portstr, &endptr, 10);
2694 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2696 printfPQExpBuffer(errorMessage, libpq_gettext(
2697 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2704 /* Allow only one attribute */
2705 if (strchr(attrs[0], ',') != NULL)
2707 printfPQExpBuffer(errorMessage, libpq_gettext(
2708 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2714 if (pg_strcasecmp(scopestr, "base") == 0)
2715 scope = LDAP_SCOPE_BASE;
2716 else if (pg_strcasecmp(scopestr, "one") == 0)
2717 scope = LDAP_SCOPE_ONELEVEL;
2718 else if (pg_strcasecmp(scopestr, "sub") == 0)
2719 scope = LDAP_SCOPE_SUBTREE;
2722 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2727 /* initialize LDAP structure */
2728 if ((ld = ldap_init(hostname, port)) == NULL)
2730 printfPQExpBuffer(errorMessage,
2731 libpq_gettext("could not create LDAP structure\n"));
2737 * Initialize connection to the server. We do an explicit bind because we
2738 * want to return 2 if the bind fails.
2740 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2742 /* error in ldap_simple_bind() */
2748 /* wait some time for the connection to succeed */
2750 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2758 /* error in ldap_result() */
2767 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2772 printfPQExpBuffer(errorMessage,
2773 libpq_gettext("lookup on LDAP server failed: %s\n"),
2774 ldap_err2string(rc));
2780 /* complain if there was not exactly one result */
2781 if ((rc = ldap_count_entries(ld, res)) != 1)
2783 printfPQExpBuffer(errorMessage,
2784 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2785 : libpq_gettext("no entry found on LDAP lookup\n"));
2793 if ((entry = ldap_first_entry(ld, res)) == NULL)
2795 /* should never happen */
2796 printfPQExpBuffer(errorMessage,
2797 libpq_gettext("no entry found on LDAP lookup\n"));
2805 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2807 printfPQExpBuffer(errorMessage,
2808 libpq_gettext("attribute has no values on LDAP lookup\n"));
2818 if (values[0] == NULL)
2820 printfPQExpBuffer(errorMessage,
2821 libpq_gettext("attribute has no values on LDAP lookup\n"));
2822 ldap_value_free_len(values);
2827 /* concatenate values to a single string */
2828 for (size = 0, i = 0; values[i] != NULL; ++i)
2829 size += values[i]->bv_len + 1;
2830 if ((result = malloc(size + 1)) == NULL)
2832 printfPQExpBuffer(errorMessage,
2833 libpq_gettext("out of memory\n"));
2834 ldap_value_free_len(values);
2838 for (p = result, i = 0; values[i] != NULL; ++i)
2840 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2841 p += values[i]->bv_len;
2843 if (values[i + 1] == NULL)
2847 ldap_value_free_len(values);
2850 /* parse result string */
2851 oldstate = state = 0;
2852 for (p = result; *p != '\0'; ++p)
2856 case 0: /* between entries */
2857 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2863 case 1: /* in option name */
2864 if (ld_is_sp_tab(*p))
2869 else if (ld_is_nl_cr(*p))
2871 printfPQExpBuffer(errorMessage, libpq_gettext(
2872 "missing \"=\" after \"%s\" in connection info string\n"),
2882 case 2: /* after option name */
2887 else if (!ld_is_sp_tab(*p))
2889 printfPQExpBuffer(errorMessage, libpq_gettext(
2890 "missing \"=\" after \"%s\" in connection info string\n"),
2895 case 3: /* before option value */
2902 else if (ld_is_nl_cr(*p))
2904 optval = optname + strlen(optname); /* empty */
2907 else if (!ld_is_sp_tab(*p))
2913 case 4: /* in unquoted option value */
2914 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
2920 case 5: /* in quoted option value */
2926 else if (*p == '\\')
2931 case 6: /* in quoted option value after escape */
2937 if (state == 0 && oldstate != 0)
2939 found_keyword = false;
2940 for (i = 0; options[i].keyword; i++)
2942 if (strcmp(options[i].keyword, optname) == 0)
2944 if (options[i].val == NULL)
2945 options[i].val = strdup(optval);
2946 found_keyword = true;
2952 printfPQExpBuffer(errorMessage,
2953 libpq_gettext("invalid connection option \"%s\"\n"),
2963 if (state == 5 || state == 6)
2965 printfPQExpBuffer(errorMessage, libpq_gettext(
2966 "unterminated quoted string in connection info string\n"));
2974 #define MAXBUFSIZE 256
2977 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2979 char *service = conninfo_getval(options, "service");
2980 char serviceFile[MAXPGPATH];
2981 bool group_found = false;
2986 * We have to special-case the environment variable PGSERVICE here, since
2987 * this is and should be called before inserting environment defaults for
2988 * other connection options.
2990 if (service == NULL)
2991 service = getenv("PGSERVICE");
2994 * This could be used by any application so we can't use the binary
2995 * location to find our config files.
2997 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2998 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3000 if (service != NULL)
3003 char buf[MAXBUFSIZE],
3006 f = fopen(serviceFile, "r");
3009 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
3014 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3018 if (strlen(line) >= sizeof(buf) - 1)
3021 printfPQExpBuffer(errorMessage,
3022 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
3028 /* ignore EOL at end of line */
3029 if (strlen(line) && line[strlen(line) - 1] == '\n')
3030 line[strlen(line) - 1] = 0;
3032 /* ignore leading blanks */
3033 while (*line && isspace((unsigned char) line[0]))
3036 /* ignore comments and empty lines */
3037 if (strlen(line) == 0 || line[0] == '#')
3040 /* Check for right groupname */
3045 /* group info already read */
3050 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3051 line[strlen(service) + 1] == ']')
3054 group_found = false;
3061 * Finally, we are in the right group and can parse the
3069 if (strncmp(line, "ldap", 4) == 0)
3071 int rc = ldapServiceLookup(line, options, errorMessage);
3073 /* if rc = 2, go on reading for fallback */
3090 val = strchr(line, '=');
3093 printfPQExpBuffer(errorMessage,
3094 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3103 * Set the parameter --- but don't override any previous
3106 found_keyword = false;
3107 for (i = 0; options[i].keyword; i++)
3109 if (strcmp(options[i].keyword, key) == 0)
3111 if (options[i].val == NULL)
3112 options[i].val = strdup(val);
3113 found_keyword = true;
3120 printfPQExpBuffer(errorMessage,
3121 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3141 * Parse a string like PQconnectdb() would do and return the
3142 * resulting connection options array. NULL is returned on failure.
3143 * The result contains only options specified directly in the string,
3144 * not any possible default values.
3146 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3147 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3148 * both *errmsg and the result could be NULL.
3150 * NOTE: the returned array is dynamically allocated and should
3151 * be freed when no longer needed via PQconninfoFree().
3154 PQconninfoParse(const char *conninfo, char **errmsg)
3156 PQExpBufferData errorBuf;
3157 PQconninfoOption *connOptions;
3160 *errmsg = NULL; /* default */
3161 initPQExpBuffer(&errorBuf);
3162 if (PQExpBufferBroken(&errorBuf))
3163 return NULL; /* out of memory already :-( */
3164 connOptions = conninfo_parse(conninfo, &errorBuf, false);
3165 if (connOptions == NULL && errmsg)
3166 *errmsg = errorBuf.data;
3168 termPQExpBuffer(&errorBuf);
3173 * Conninfo parser routine
3175 * If successful, a malloc'd PQconninfoOption array is returned.
3176 * If not successful, NULL is returned and an error message is
3177 * left in errorMessage.
3178 * Defaults are supplied (from a service file, environment variables, etc)
3179 * for unspecified options, but only if use_defaults is TRUE.
3181 static PQconninfoOption *
3182 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3191 PQconninfoOption *options;
3192 PQconninfoOption *option;
3194 /* Make a working copy of PQconninfoOptions */
3195 options = malloc(sizeof(PQconninfoOptions));
3196 if (options == NULL)
3198 printfPQExpBuffer(errorMessage,
3199 libpq_gettext("out of memory\n"));
3202 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3204 /* Need a modifiable copy of the input string */
3205 if ((buf = strdup(conninfo)) == NULL)
3207 printfPQExpBuffer(errorMessage,
3208 libpq_gettext("out of memory\n"));
3209 PQconninfoFree(options);
3216 /* Skip blanks before the parameter name */
3217 if (isspace((unsigned char) *cp))
3223 /* Get the parameter name */
3229 if (isspace((unsigned char) *cp))
3234 if (!isspace((unsigned char) *cp))
3243 /* Check that there is a following '=' */
3246 printfPQExpBuffer(errorMessage,
3247 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3249 PQconninfoFree(options);
3255 /* Skip blanks after the '=' */
3258 if (!isspace((unsigned char) *cp))
3263 /* Get the parameter value */
3271 if (isspace((unsigned char) *cp))
3295 printfPQExpBuffer(errorMessage,
3296 libpq_gettext("unterminated quoted string in connection info string\n"));
3297 PQconninfoFree(options);
3319 * Now we have the name and the value. Search for the param record.
3321 for (option = options; option->keyword != NULL; option++)
3323 if (strcmp(option->keyword, pname) == 0)
3326 if (option->keyword == NULL)
3328 printfPQExpBuffer(errorMessage,
3329 libpq_gettext("invalid connection option \"%s\"\n"),
3331 PQconninfoFree(options);
3341 option->val = strdup(pval);
3344 printfPQExpBuffer(errorMessage,
3345 libpq_gettext("out of memory\n"));
3346 PQconninfoFree(options);
3352 /* Done with the modifiable input string */
3356 * Stop here if caller doesn't want defaults filled in.
3362 * If there's a service spec, use it to obtain any not-explicitly-given
3365 if (parseServiceInfo(options, errorMessage))
3367 PQconninfoFree(options);
3372 * Get the fallback resources for parameters not specified in the conninfo
3373 * string nor the service.
3375 for (option = options; option->keyword != NULL; option++)
3377 if (option->val != NULL)
3378 continue; /* Value was in conninfo or service */
3381 * Try to get the environment variable fallback
3383 if (option->envvar != NULL)
3385 if ((tmp = getenv(option->envvar)) != NULL)
3387 option->val = strdup(tmp);
3390 printfPQExpBuffer(errorMessage,
3391 libpq_gettext("out of memory\n"));
3392 PQconninfoFree(options);
3400 * No environment variable specified or this one isn't set - try
3403 if (option->compiled != NULL)
3405 option->val = strdup(option->compiled);
3408 printfPQExpBuffer(errorMessage,
3409 libpq_gettext("out of memory\n"));
3410 PQconninfoFree(options);
3417 * Special handling for user
3419 if (strcmp(option->keyword, "user") == 0)
3421 option->val = pg_fe_getauthname(errorMessage);
3431 conninfo_getval(PQconninfoOption *connOptions,
3432 const char *keyword)
3434 PQconninfoOption *option;
3436 for (option = connOptions; option->keyword != NULL; option++)
3438 if (strcmp(option->keyword, keyword) == 0)
3447 PQconninfoFree(PQconninfoOption *connOptions)
3449 PQconninfoOption *option;
3451 if (connOptions == NULL)
3454 for (option = connOptions; option->keyword != NULL; option++)
3456 if (option->val != NULL)
3463 /* =========== accessor functions for PGconn ========= */
3465 PQdb(const PGconn *conn)
3469 return conn->dbName;
3473 PQuser(const PGconn *conn)
3477 return conn->pguser;
3481 PQpass(const PGconn *conn)
3485 return conn->pgpass;
3489 PQhost(const PGconn *conn)
3493 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3497 PQport(const PGconn *conn)
3501 return conn->pgport;
3505 PQtty(const PGconn *conn)
3513 PQoptions(const PGconn *conn)
3517 return conn->pgoptions;
3521 PQstatus(const PGconn *conn)
3524 return CONNECTION_BAD;
3525 return conn->status;
3528 PGTransactionStatusType
3529 PQtransactionStatus(const PGconn *conn)
3531 if (!conn || conn->status != CONNECTION_OK)
3532 return PQTRANS_UNKNOWN;
3533 if (conn->asyncStatus != PGASYNC_IDLE)
3534 return PQTRANS_ACTIVE;
3535 return conn->xactStatus;
3539 PQparameterStatus(const PGconn *conn, const char *paramName)
3541 const pgParameterStatus *pstatus;
3543 if (!conn || !paramName)
3545 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3547 if (strcmp(pstatus->name, paramName) == 0)
3548 return pstatus->value;
3554 PQprotocolVersion(const PGconn *conn)
3558 if (conn->status == CONNECTION_BAD)
3560 return PG_PROTOCOL_MAJOR(conn->pversion);
3564 PQserverVersion(const PGconn *conn)
3568 if (conn->status == CONNECTION_BAD)
3570 return conn->sversion;
3574 PQerrorMessage(const PGconn *conn)
3577 return libpq_gettext("connection pointer is NULL\n");
3579 return conn->errorMessage.data;
3583 PQsocket(const PGconn *conn)
3591 PQbackendPID(const PGconn *conn)
3593 if (!conn || conn->status != CONNECTION_OK)
3595 return conn->be_pid;
3599 PQconnectionNeedsPassword(const PGconn *conn)
3603 if (conn->password_needed &&
3604 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
3611 PQconnectionUsedPassword(const PGconn *conn)
3615 if (conn->password_needed)
3622 PQclientEncoding(const PGconn *conn)
3624 if (!conn || conn->status != CONNECTION_OK)
3626 return conn->client_encoding;
3630 PQsetClientEncoding(PGconn *conn, const char *encoding)
3633 static const char query[] = "set client_encoding to '%s'";
3637 if (!conn || conn->status != CONNECTION_OK)
3643 /* check query buffer overflow */
3644 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3647 /* ok, now send a query */
3648 sprintf(qbuf, query, encoding);
3649 res = PQexec(conn, qbuf);
3653 if (res->resultStatus != PGRES_COMMAND_OK)
3658 * In protocol 2 we have to assume the setting will stick, and adjust
3659 * our state immediately. In protocol 3 and up we can rely on the
3660 * backend to report the parameter value, and we'll change state at
3663 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3664 pqSaveParameterStatus(conn, "client_encoding", encoding);
3665 status = 0; /* everything is ok */
3672 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3677 return PQERRORS_DEFAULT;
3678 old = conn->verbosity;
3679 conn->verbosity = verbosity;
3684 PQtrace(PGconn *conn, FILE *debug_port)
3689 conn->Pfdebug = debug_port;
3693 PQuntrace(PGconn *conn)
3699 fflush(conn->Pfdebug);
3700 conn->Pfdebug = NULL;
3705 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3707 PQnoticeReceiver old;
3712 old = conn->noticeHooks.noticeRec;
3715 conn->noticeHooks.noticeRec = proc;
3716 conn->noticeHooks.noticeRecArg = arg;
3722 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3724 PQnoticeProcessor old;
3729 old = conn->noticeHooks.noticeProc;
3732 conn->noticeHooks.noticeProc = proc;
3733 conn->noticeHooks.noticeProcArg = arg;
3739 * The default notice message receiver just gets the standard notice text
3740 * and sends it to the notice processor. This two-level setup exists
3741 * mostly for backwards compatibility; perhaps we should deprecate use of
3742 * PQsetNoticeProcessor?
3745 defaultNoticeReceiver(void *arg, const PGresult *res)
3747 (void) arg; /* not used */
3748 if (res->noticeHooks.noticeProc != NULL)
3749 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3750 PQresultErrorMessage(res));
3754 * The default notice message processor just prints the
3755 * message on stderr. Applications can override this if they
3756 * want the messages to go elsewhere (a window, for example).
3757 * Note that simply discarding notices is probably a bad idea.
3760 defaultNoticeProcessor(void *arg, const char *message)
3762 (void) arg; /* not used */
3763 /* Note: we expect the supplied string to end with a newline already. */
3764 fprintf(stderr, "%s", message);
3768 * returns a pointer to the next token or NULL if the current
3769 * token doesn't match
3772 pwdfMatchesString(char *buf, char *token)
3776 bool bslash = false;
3778 if (buf == NULL || token == NULL)
3786 if (*tbuf == '\\' && !bslash)
3791 if (*tbuf == ':' && *ttok == 0 && !bslash)
3807 /* Get a password from the password file. Return value is malloc'd. */
3809 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3812 char pgpassfile[MAXPGPATH];
3813 struct stat stat_buf;
3816 #define LINELEN NAMEDATALEN*5
3819 if (dbname == NULL || strlen(dbname) == 0)
3822 if (username == NULL || strlen(username) == 0)
3825 /* 'localhost' matches pghost of '' or the default socket directory */
3826 if (hostname == NULL)
3827 hostname = DefaultHost;
3828 else if (is_absolute_path(hostname))
3831 * We should probably use canonicalize_path(), but then we have to
3832 * bring path.c into libpq, and it doesn't seem worth it.
3834 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3835 hostname = DefaultHost;
3838 port = DEF_PGPORT_STR;
3840 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3841 /* use the literal path from the environment, if set */
3842 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3845 char homedir[MAXPGPATH];
3847 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3849 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3852 /* If password file cannot be opened, ignore it. */
3853 if (stat(pgpassfile, &stat_buf) != 0)
3857 if (!S_ISREG(stat_buf.st_mode))
3860 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3865 /* If password file is insecure, alert the user and ignore it. */
3866 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3869 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
3876 * On Win32, the directory is protected, so we don't have to check the
3881 fp = fopen(pgpassfile, "r");
3891 fgets(buf, sizeof(buf), fp);
3897 /* Remove trailing newline */
3898 if (buf[len - 1] == '\n')
3901 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3902 (t = pwdfMatchesString(t, port)) == NULL ||
3903 (t = pwdfMatchesString(t, dbname)) == NULL ||
3904 (t = pwdfMatchesString(t, username)) == NULL)
3918 * Obtain user's home directory, return in given buffer
3920 * On Unix, this actually returns the user's home directory. On Windows
3921 * it returns the PostgreSQL-specific application data folder.
3923 * This is essentially the same as get_home_path(), but we don't use that
3924 * because we don't want to pull path.c into libpq (it pollutes application
3928 pqGetHomeDirectory(char *buf, int bufsize)
3931 char pwdbuf[BUFSIZ];
3932 struct passwd pwdstr;
3933 struct passwd *pwd = NULL;
3935 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3937 strlcpy(buf, pwd->pw_dir, bufsize);
3940 char tmppath[MAX_PATH];
3942 ZeroMemory(tmppath, sizeof(tmppath));
3943 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3945 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3951 * To keep the API consistent, the locking stubs are always provided, even
3952 * if they are not required.
3956 default_threadlock(int acquire)
3958 #ifdef ENABLE_THREAD_SAFETY
3960 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3962 static pthread_mutex_t singlethread_lock = NULL;
3963 static long mutex_initlock = 0;
3965 if (singlethread_lock == NULL)
3967 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3968 /* loop, another thread own the lock */ ;
3969 if (singlethread_lock == NULL)
3971 if (pthread_mutex_init(&singlethread_lock, NULL))
3972 PGTHREAD_ERROR("failed to initialize mutex");
3974 InterlockedExchange(&mutex_initlock, 0);
3979 if (pthread_mutex_lock(&singlethread_lock))
3980 PGTHREAD_ERROR("failed to lock mutex");
3984 if (pthread_mutex_unlock(&singlethread_lock))
3985 PGTHREAD_ERROR("failed to unlock mutex");
3991 PQregisterThreadLock(pgthreadlock_t newhandler)
3993 pgthreadlock_t prev = pg_g_threadlock;
3996 pg_g_threadlock = newhandler;
3998 pg_g_threadlock = default_threadlock;