1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2010, 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.382 2010/01/02 16:58:11 momjian 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"
87 * Pre-8.5 servers will return this SQLSTATE if asked to set
88 * application_name in a startup packet. We hard-wire the value rather
89 * than looking into errcodes.h since it reflects historical behavior
90 * rather than that of the current code.
92 #define ERRCODE_APPNAME_UNKNOWN "42704"
95 * fall back options if they are not specified by arguments or defined
96 * by environment variables
98 #define DefaultHost "localhost"
100 #define DefaultOption ""
101 #define DefaultAuthtype ""
102 #define DefaultPassword ""
104 #define DefaultSSLMode "prefer"
106 #define DefaultSSLMode "disable"
110 * Definition of the conninfo parameters and their fallback resources.
112 * If Environment-Var and Compiled-in are specified as NULL, no
113 * fallback is available. If after all no value can be determined
114 * for an option, an error is returned.
116 * The value for the username is treated specially in conninfo_parse.
117 * If the Compiled-in resource is specified as a NULL value, the
118 * user is determined by pg_fe_getauthname().
120 * The Label and Disp-Char entries are provided for applications that
121 * want to use PQconndefaults() to create a generic database connection
122 * dialog. Disp-Char is defined as follows:
123 * "" Normal input field
124 * "*" Password field - hide value
125 * "D" Debug option - don't show by default
127 * PQconninfoOptions[] is a constant static array that we use to initialize
128 * a dynamically allocated working copy. All the "val" fields in
129 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
130 * fields point to malloc'd strings that should be freed when the working
131 * array is freed (see PQconninfoFree).
134 static const PQconninfoOption PQconninfoOptions[] = {
136 * "authtype" is no longer used, so mark it "don't show". We keep it in
137 * the array so as not to reject conninfo strings from old apps that might
138 * still try to set it.
140 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
141 "Database-Authtype", "D", 20},
143 {"service", "PGSERVICE", NULL, NULL,
144 "Database-Service", "", 20},
146 {"user", "PGUSER", NULL, NULL,
147 "Database-User", "", 20},
149 {"password", "PGPASSWORD", NULL, NULL,
150 "Database-Password", "*", 20},
152 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
153 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
155 {"dbname", "PGDATABASE", NULL, NULL,
156 "Database-Name", "", 20},
158 {"host", "PGHOST", NULL, NULL,
159 "Database-Host", "", 40},
161 {"hostaddr", "PGHOSTADDR", NULL, NULL,
162 "Database-Host-IP-Address", "", 45},
164 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
165 "Database-Port", "", 6},
168 * "tty" is no longer used either, but keep it present for backwards
171 {"tty", "PGTTY", DefaultTty, NULL,
172 "Backend-Debug-TTY", "D", 40},
174 {"options", "PGOPTIONS", DefaultOption, NULL,
175 "Backend-Debug-Options", "D", 40},
177 {"application_name", "PGAPPNAME", NULL, NULL,
178 "Application-Name", "", 64},
180 {"fallback_application_name", NULL, NULL, NULL,
181 "Fallback-Application-Name", "", 64},
186 * "requiressl" is deprecated, its purpose having been taken over by
187 * "sslmode". It remains for backwards compatibility.
189 {"requiressl", "PGREQUIRESSL", "0", NULL,
190 "Require-SSL", "D", 1},
194 * ssl options are allowed even without client SSL support because the
195 * client can still handle SSL modes "disable" and "allow". Other
196 * parameters have no effect on non-SSL connections, so there is no reason
197 * to exclude them since none of them are mandatory.
199 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
200 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
202 {"sslcert", "PGSSLCERT", NULL, NULL,
203 "SSL-Client-Cert", "", 64},
205 {"sslkey", "PGSSLKEY", NULL, NULL,
206 "SSL-Client-Key", "", 64},
208 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
209 "SSL-Root-Certificate", "", 64},
211 {"sslcrl", "PGSSLCRL", NULL, NULL,
212 "SSL-Revocation-List", "", 64},
214 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
215 /* Kerberos and GSSAPI authentication support specifying the service name */
216 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
217 "Kerberos-service-name", "", 20},
220 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
223 * GSSAPI and SSPI both enabled, give a way to override which is used by
226 {"gsslib", "PGGSSLIB", NULL, NULL,
227 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
230 /* Terminating entry --- MUST BE LAST */
231 {NULL, NULL, NULL, NULL,
235 static const PQEnvironmentOption EnvironmentOptions[] =
237 /* common user-interface settings */
239 "PGDATESTYLE", "datestyle"
245 "PGCLIENTENCODING", "client_encoding"
247 /* internal performance-related settings */
257 static bool connectOptions1(PGconn *conn, const char *conninfo);
258 static bool connectOptions2(PGconn *conn);
259 static int connectDBStart(PGconn *conn);
260 static int connectDBComplete(PGconn *conn);
261 static PGconn *makeEmptyPGconn(void);
262 static void freePGconn(PGconn *conn);
263 static void closePGconn(PGconn *conn);
264 static PQconninfoOption *conninfo_parse(const char *conninfo,
265 PQExpBuffer errorMessage, bool use_defaults);
266 static char *conninfo_getval(PQconninfoOption *connOptions,
267 const char *keyword);
268 static void defaultNoticeReceiver(void *arg, const PGresult *res);
269 static void defaultNoticeProcessor(void *arg, const char *message);
270 static int parseServiceInfo(PQconninfoOption *options,
271 PQExpBuffer errorMessage);
272 static char *pwdfMatchesString(char *buf, char *token);
273 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
275 static void default_threadlock(int acquire);
278 /* global variable because fe-auth.c needs to access it */
279 pgthreadlock_t pg_g_threadlock = default_threadlock;
283 * Connecting to a Database
285 * There are now four different ways a user of this API can connect to the
286 * database. Two are not recommended for use in new code, because of their
287 * lack of extensibility with respect to the passing of options to the
288 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
291 * If it is desired to connect in a synchronous (blocking) manner, use the
292 * function PQconnectdb.
294 * To connect in an asynchronous (non-blocking) manner, use the functions
295 * PQconnectStart, and PQconnectPoll.
297 * Internally, the static functions connectDBStart, connectDBComplete
298 * are part of the connection procedure.
304 * establishes a connection to a postgres backend through the postmaster
305 * using connection information in a string.
307 * The conninfo string is a white-separated list of
311 * definitions. Value might be a single value containing no whitespaces or
312 * a single quoted string. If a single quote should appear anywhere in
313 * the value, it must be escaped with a backslash like \'
315 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
316 * if a memory allocation failed.
317 * If the status field of the connection returned is CONNECTION_BAD,
318 * then some fields may be null'ed out instead of having valid values.
320 * You should call PQfinish (if conn is not NULL) regardless of whether this
324 PQconnectdb(const char *conninfo)
326 PGconn *conn = PQconnectStart(conninfo);
328 if (conn && conn->status != CONNECTION_BAD)
329 (void) connectDBComplete(conn);
337 * Begins the establishment of a connection to a postgres backend through the
338 * postmaster using connection information in a string.
340 * See comment for PQconnectdb for the definition of the string format.
342 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
343 * you should not attempt to proceed with this connection. If the status
344 * field of the connection returned is CONNECTION_BAD, an error has
345 * occurred. In this case you should call PQfinish on the result, (perhaps
346 * inspecting the error message first). Other fields of the structure may not
347 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
348 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
351 * See PQconnectPoll for more info.
354 PQconnectStart(const char *conninfo)
359 * Allocate memory for the conn structure
361 conn = makeEmptyPGconn();
366 * Parse the conninfo string
368 if (!connectOptions1(conn, conninfo))
372 * Compute derived options
374 if (!connectOptions2(conn))
378 * Connect to the database
380 if (!connectDBStart(conn))
382 /* Just in case we failed to set it in connectDBStart */
383 conn->status = CONNECTION_BAD;
392 * Internal subroutine to set up connection parameters given an already-
393 * created PGconn and a conninfo string. Derived settings should be
394 * processed by calling connectOptions2 next. (We split them because
395 * PQsetdbLogin overrides defaults in between.)
397 * Returns true if OK, false if trouble (in which case errorMessage is set
398 * and so is conn->status).
401 connectOptions1(PGconn *conn, const char *conninfo)
403 PQconninfoOption *connOptions;
407 * Parse the conninfo string
409 connOptions = conninfo_parse(conninfo, &conn->errorMessage, true);
410 if (connOptions == NULL)
412 conn->status = CONNECTION_BAD;
413 /* errorMessage is already set */
418 * Move option values into conn structure
420 * Don't put anything cute here --- intelligence should be in
421 * connectOptions2 ...
423 * XXX: probably worth checking strdup() return value here...
425 tmp = conninfo_getval(connOptions, "hostaddr");
426 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
427 tmp = conninfo_getval(connOptions, "host");
428 conn->pghost = tmp ? strdup(tmp) : NULL;
429 tmp = conninfo_getval(connOptions, "port");
430 conn->pgport = tmp ? strdup(tmp) : NULL;
431 tmp = conninfo_getval(connOptions, "tty");
432 conn->pgtty = tmp ? strdup(tmp) : NULL;
433 tmp = conninfo_getval(connOptions, "options");
434 conn->pgoptions = tmp ? strdup(tmp) : NULL;
435 tmp = conninfo_getval(connOptions, "application_name");
436 conn->appname = tmp ? strdup(tmp) : NULL;
437 tmp = conninfo_getval(connOptions, "fallback_application_name");
438 conn->fbappname = tmp ? strdup(tmp) : NULL;
439 tmp = conninfo_getval(connOptions, "dbname");
440 conn->dbName = tmp ? strdup(tmp) : NULL;
441 tmp = conninfo_getval(connOptions, "user");
442 conn->pguser = tmp ? strdup(tmp) : NULL;
443 tmp = conninfo_getval(connOptions, "password");
444 conn->pgpass = tmp ? strdup(tmp) : NULL;
445 tmp = conninfo_getval(connOptions, "connect_timeout");
446 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
447 tmp = conninfo_getval(connOptions, "sslmode");
448 conn->sslmode = tmp ? strdup(tmp) : NULL;
449 tmp = conninfo_getval(connOptions, "sslkey");
450 conn->sslkey = tmp ? strdup(tmp) : NULL;
451 tmp = conninfo_getval(connOptions, "sslcert");
452 conn->sslcert = tmp ? strdup(tmp) : NULL;
453 tmp = conninfo_getval(connOptions, "sslrootcert");
454 conn->sslrootcert = tmp ? strdup(tmp) : NULL;
455 tmp = conninfo_getval(connOptions, "sslcrl");
456 conn->sslcrl = tmp ? strdup(tmp) : NULL;
458 tmp = conninfo_getval(connOptions, "requiressl");
459 if (tmp && tmp[0] == '1')
461 /* here warn that the requiressl option is deprecated? */
464 conn->sslmode = strdup("require");
467 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
468 tmp = conninfo_getval(connOptions, "krbsrvname");
469 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
471 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
472 tmp = conninfo_getval(connOptions, "gsslib");
473 conn->gsslib = tmp ? strdup(tmp) : NULL;
477 * Free the option info - all is in conn now
479 PQconninfoFree(connOptions);
487 * Compute derived connection options after absorbing all user-supplied info.
489 * Returns true if OK, false if trouble (in which case errorMessage is set
490 * and so is conn->status).
493 connectOptions2(PGconn *conn)
496 * If database name was not given, default it to equal user name
498 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
499 && conn->pguser != NULL)
503 conn->dbName = strdup(conn->pguser);
507 * Supply default password if none given
509 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
513 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
514 conn->dbName, conn->pguser);
515 if (conn->pgpass == NULL)
516 conn->pgpass = strdup(DefaultPassword);
520 * Allow unix socket specification in the host name
522 if (conn->pghost && is_absolute_path(conn->pghost))
524 if (conn->pgunixsocket)
525 free(conn->pgunixsocket);
526 conn->pgunixsocket = conn->pghost;
531 * validate sslmode option
535 if (strcmp(conn->sslmode, "disable") != 0
536 && strcmp(conn->sslmode, "allow") != 0
537 && strcmp(conn->sslmode, "prefer") != 0
538 && strcmp(conn->sslmode, "require") != 0
539 && strcmp(conn->sslmode, "verify-ca") != 0
540 && strcmp(conn->sslmode, "verify-full") != 0)
542 conn->status = CONNECTION_BAD;
543 printfPQExpBuffer(&conn->errorMessage,
544 libpq_gettext("invalid sslmode value: \"%s\"\n"),
550 switch (conn->sslmode[0])
552 case 'a': /* "allow" */
553 case 'p': /* "prefer" */
556 * warn user that an SSL connection will never be negotiated
557 * since SSL was not compiled in?
561 case 'r': /* "require" */
562 case 'v': /* "verify-ca" or "verify-full" */
563 conn->status = CONNECTION_BAD;
564 printfPQExpBuffer(&conn->errorMessage,
565 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
572 conn->sslmode = strdup(DefaultSSLMode);
575 * Only if we get this far is it appropriate to try to connect. (We need a
576 * state flag, rather than just the boolean result of this function, in
577 * case someone tries to PQreset() the PGconn.)
579 conn->options_valid = true;
587 * Parse an empty string like PQconnectdb() would do and return the
588 * resulting connection options array, ie, all the default values that are
589 * available from the environment etc. On error (eg out of memory),
592 * Using this function, an application may determine all possible options
593 * and their current default values.
595 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
596 * and should be freed when no longer needed via PQconninfoFree(). (In prior
597 * versions, the returned array was static, but that's not thread-safe.)
598 * Pre-7.0 applications that use this function will see a small memory leak
599 * until they are updated to call PQconninfoFree.
604 PQExpBufferData errorBuf;
605 PQconninfoOption *connOptions;
607 initPQExpBuffer(&errorBuf);
608 if (PQExpBufferBroken(&errorBuf))
609 return NULL; /* out of memory already :-( */
610 connOptions = conninfo_parse("", &errorBuf, true);
611 termPQExpBuffer(&errorBuf);
618 * establishes a connection to a postgres backend through the postmaster
619 * at the specified host and port.
621 * returns a PGconn* which is needed for all subsequent libpq calls
623 * if the status field of the connection returned is CONNECTION_BAD,
624 * then only the errorMessage is likely to be useful.
628 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
629 const char *pgtty, const char *dbName, const char *login,
635 * Allocate memory for the conn structure
637 conn = makeEmptyPGconn();
642 * If the dbName parameter contains '=', assume it's a conninfo string.
644 if (dbName && strchr(dbName, '='))
646 if (!connectOptions1(conn, dbName))
652 * Old-style path: first, parse an empty conninfo string in order to
653 * set up the same defaults that PQconnectdb() would use.
655 if (!connectOptions1(conn, ""))
658 /* Insert dbName parameter value into struct */
659 if (dbName && dbName[0] != '\0')
663 conn->dbName = strdup(dbName);
668 * Insert remaining parameters into struct, overriding defaults (as well
669 * as any conflicting data from dbName taken as a conninfo).
671 if (pghost && pghost[0] != '\0')
675 conn->pghost = strdup(pghost);
678 if (pgport && pgport[0] != '\0')
682 conn->pgport = strdup(pgport);
685 if (pgoptions && pgoptions[0] != '\0')
688 free(conn->pgoptions);
689 conn->pgoptions = strdup(pgoptions);
692 if (pgtty && pgtty[0] != '\0')
696 conn->pgtty = strdup(pgtty);
699 if (login && login[0] != '\0')
703 conn->pguser = strdup(login);
706 if (pwd && pwd[0] != '\0')
710 conn->pgpass = strdup(pwd);
714 * Compute derived options
716 if (!connectOptions2(conn))
720 * Connect to the database
722 if (connectDBStart(conn))
723 (void) connectDBComplete(conn);
731 * Sets the TCP_NODELAY socket option.
732 * Returns 1 if successful, 0 if not.
736 connectNoDelay(PGconn *conn)
741 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
747 appendPQExpBuffer(&conn->errorMessage,
748 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
749 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
759 * connectFailureMessage -
760 * create a friendly error message on connection failure.
764 connectFailureMessage(PGconn *conn, int errorno)
768 #ifdef HAVE_UNIX_SOCKETS
769 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
771 char service[NI_MAXHOST];
773 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
775 service, sizeof(service),
777 appendPQExpBuffer(&conn->errorMessage,
778 libpq_gettext("could not connect to server: %s\n"
779 "\tIs the server running locally and accepting\n"
780 "\tconnections on Unix domain socket \"%s\"?\n"),
781 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
785 #endif /* HAVE_UNIX_SOCKETS */
787 appendPQExpBuffer(&conn->errorMessage,
788 libpq_gettext("could not connect to server: %s\n"
789 "\tIs the server running on host \"%s\" and accepting\n"
790 "\tTCP/IP connections on port %s?\n"),
791 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
804 * Begin the process of making a connection to the backend.
806 * Returns 1 if successful, 0 if not.
810 connectDBStart(PGconn *conn)
814 struct addrinfo *addrs = NULL;
815 struct addrinfo hint;
822 if (!conn->options_valid)
823 goto connect_errReturn;
825 /* Ensure our buffers are empty */
826 conn->inStart = conn->inCursor = conn->inEnd = 0;
830 * Determine the parameters to pass to pg_getaddrinfo_all.
833 /* Initialize hint structure */
834 MemSet(&hint, 0, sizeof(hint));
835 hint.ai_socktype = SOCK_STREAM;
836 hint.ai_family = AF_UNSPEC;
838 /* Set up port number as a string */
839 if (conn->pgport != NULL && conn->pgport[0] != '\0')
841 portnum = atoi(conn->pgport);
842 if (portnum < 1 || portnum > 65535)
844 appendPQExpBuffer(&conn->errorMessage,
845 libpq_gettext("invalid port number: \"%s\"\n"),
847 goto connect_errReturn;
851 portnum = DEF_PGPORT;
852 snprintf(portstr, sizeof(portstr), "%d", portnum);
854 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
856 /* Using pghostaddr avoids a hostname lookup */
857 node = conn->pghostaddr;
858 hint.ai_family = AF_UNSPEC;
859 hint.ai_flags = AI_NUMERICHOST;
861 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
863 /* Using pghost, so we have to look-up the hostname */
865 hint.ai_family = AF_UNSPEC;
869 #ifdef HAVE_UNIX_SOCKETS
870 /* pghostaddr and pghost are NULL, so use Unix domain socket */
872 hint.ai_family = AF_UNIX;
873 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
875 /* Without Unix sockets, default to localhost instead */
877 hint.ai_family = AF_UNSPEC;
878 #endif /* HAVE_UNIX_SOCKETS */
881 /* Use pg_getaddrinfo_all() to resolve the address */
882 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
886 appendPQExpBuffer(&conn->errorMessage,
887 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
888 node, gai_strerror(ret));
890 appendPQExpBuffer(&conn->errorMessage,
891 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
892 portstr, gai_strerror(ret));
894 pg_freeaddrinfo_all(hint.ai_family, addrs);
895 goto connect_errReturn;
899 /* setup values based on SSL mode */
900 if (conn->sslmode[0] == 'd') /* "disable" */
901 conn->allow_ssl_try = false;
902 else if (conn->sslmode[0] == 'a') /* "allow" */
903 conn->wait_ssl_try = true;
907 * Set up to try to connect, with protocol 3.0 as the first attempt.
909 conn->addrlist = addrs;
910 conn->addr_cur = addrs;
911 conn->addrlist_family = hint.ai_family;
912 conn->pversion = PG_PROTOCOL(3, 0);
913 conn->send_appname = true;
914 conn->status = CONNECTION_NEEDED;
917 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
918 * so that it can easily be re-executed if needed again during the
919 * asynchronous startup process. However, we must run it once here,
920 * because callers expect a success return from this routine to mean that
921 * we are in PGRES_POLLING_WRITING connection state.
923 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
929 pqsecure_close(conn);
930 closesocket(conn->sock);
933 conn->status = CONNECTION_BAD;
941 * Block and complete a connection.
943 * Returns 1 on success, 0 on failure.
946 connectDBComplete(PGconn *conn)
948 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
949 time_t finish_time = ((time_t) -1);
951 if (conn == NULL || conn->status == CONNECTION_BAD)
955 * Set up a time limit, if connect_timeout isn't zero.
957 if (conn->connect_timeout != NULL)
959 int timeout = atoi(conn->connect_timeout);
964 * Rounding could cause connection to fail; need at least 2 secs
968 /* calculate the finish time based on start + timeout */
969 finish_time = time(NULL) + timeout;
976 * Wait, if necessary. Note that the initial state (just after
977 * PQconnectStart) is to wait for the socket to select for writing.
981 case PGRES_POLLING_OK:
984 * Reset stored error messages since we now have a working
987 resetPQExpBuffer(&conn->errorMessage);
988 return 1; /* success! */
990 case PGRES_POLLING_READING:
991 if (pqWaitTimed(1, 0, conn, finish_time))
993 conn->status = CONNECTION_BAD;
998 case PGRES_POLLING_WRITING:
999 if (pqWaitTimed(0, 1, conn, finish_time))
1001 conn->status = CONNECTION_BAD;
1007 /* Just in case we failed to set it in PQconnectPoll */
1008 conn->status = CONNECTION_BAD;
1013 * Now try to advance the state machine.
1015 flag = PQconnectPoll(conn);
1022 * Poll an asynchronous connection.
1024 * Returns a PostgresPollingStatusType.
1025 * Before calling this function, use select(2) to determine when data
1028 * You must call PQfinish whether or not this fails.
1030 * This function and PQconnectStart are intended to allow connections to be
1031 * made without blocking the execution of your program on remote I/O. However,
1032 * there are a number of caveats:
1034 * o If you call PQtrace, ensure that the stream object into which you trace
1036 * o If you do not supply an IP address for the remote host (i.e. you
1037 * supply a host name instead) then PQconnectStart will block on
1038 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1039 * supplying neither a host name nor a host address).
1040 * o If your backend wants to use Kerberos authentication then you must
1041 * supply both a host name and a host address, otherwise this function
1042 * may block on gethostname.
1046 PostgresPollingStatusType
1047 PQconnectPoll(PGconn *conn)
1054 return PGRES_POLLING_FAILED;
1056 /* Get the new data */
1057 switch (conn->status)
1060 * We really shouldn't have been polled in these two cases, but we
1063 case CONNECTION_BAD:
1064 return PGRES_POLLING_FAILED;
1066 return PGRES_POLLING_OK;
1068 /* These are reading states */
1069 case CONNECTION_AWAITING_RESPONSE:
1070 case CONNECTION_AUTH_OK:
1072 /* Load waiting data */
1073 int n = pqReadData(conn);
1078 return PGRES_POLLING_READING;
1083 /* These are writing states, so we just proceed. */
1084 case CONNECTION_STARTED:
1085 case CONNECTION_MADE:
1088 /* We allow pqSetenvPoll to decide whether to proceed. */
1089 case CONNECTION_SETENV:
1092 /* Special cases: proceed without waiting. */
1093 case CONNECTION_SSL_STARTUP:
1094 case CONNECTION_NEEDED:
1098 appendPQExpBuffer(&conn->errorMessage,
1100 "invalid connection state, "
1101 "probably indicative of memory corruption\n"
1107 keep_going: /* We will come back to here until there is
1108 * nothing left to do. */
1109 switch (conn->status)
1111 case CONNECTION_NEEDED:
1114 * Try to initiate a connection to one of the addresses
1115 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1116 * next one to try. We fail when we run out of addresses
1117 * (reporting the error returned for the *last* alternative,
1118 * which may not be what users expect :-().
1120 while (conn->addr_cur != NULL)
1122 struct addrinfo *addr_cur = conn->addr_cur;
1124 /* Remember current address for possible error msg */
1125 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1126 addr_cur->ai_addrlen);
1127 conn->raddr.salen = addr_cur->ai_addrlen;
1130 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1134 * ignore socket() failure if we have more addresses
1137 if (addr_cur->ai_next != NULL)
1139 conn->addr_cur = addr_cur->ai_next;
1142 appendPQExpBuffer(&conn->errorMessage,
1143 libpq_gettext("could not create socket: %s\n"),
1144 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1149 * Select socket options: no delay of outgoing data for
1150 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1153 if (!IS_AF_UNIX(addr_cur->ai_family))
1155 if (!connectNoDelay(conn))
1157 closesocket(conn->sock);
1159 conn->addr_cur = addr_cur->ai_next;
1163 if (!pg_set_noblock(conn->sock))
1165 appendPQExpBuffer(&conn->errorMessage,
1166 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1167 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1168 closesocket(conn->sock);
1170 conn->addr_cur = addr_cur->ai_next;
1175 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1177 appendPQExpBuffer(&conn->errorMessage,
1178 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1179 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1180 closesocket(conn->sock);
1182 conn->addr_cur = addr_cur->ai_next;
1185 #endif /* F_SETFD */
1188 * We have three methods of blocking SIGPIPE during
1189 * send() calls to this socket:
1191 * - setsockopt(sock, SO_NOSIGPIPE)
1192 * - send(sock, ..., MSG_NOSIGNAL)
1193 * - setting the signal mask to SIG_IGN during send()
1195 * The third method requires three syscalls per send,
1196 * so we prefer either of the first two, but they are
1197 * less portable. The state is tracked in the following
1198 * members of PGconn:
1200 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
1201 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
1203 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
1204 * and we're done. Otherwise, set sigpipe_flag so that
1205 * we will try MSG_NOSIGNAL on sends. If we get an error
1206 * with MSG_NOSIGNAL, we'll clear that flag and revert to
1210 conn->sigpipe_so = false;
1212 conn->sigpipe_flag = true;
1214 conn->sigpipe_flag = false;
1215 #endif /* MSG_NOSIGNAL */
1219 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
1220 (char *) &optval, sizeof(optval)) == 0)
1222 conn->sigpipe_so = true;
1223 conn->sigpipe_flag = false;
1225 #endif /* SO_NOSIGPIPE */
1228 * Start/make connection. This should not block, since we
1229 * are in nonblock mode. If it does, well, too bad.
1231 if (connect(conn->sock, addr_cur->ai_addr,
1232 addr_cur->ai_addrlen) < 0)
1234 if (SOCK_ERRNO == EINPROGRESS ||
1235 SOCK_ERRNO == EWOULDBLOCK ||
1236 SOCK_ERRNO == EINTR ||
1240 * This is fine - we're in non-blocking mode, and
1241 * the connection is in progress. Tell caller to
1242 * wait for write-ready on socket.
1244 conn->status = CONNECTION_STARTED;
1245 return PGRES_POLLING_WRITING;
1247 /* otherwise, trouble */
1252 * Hm, we're connected already --- seems the "nonblock
1253 * connection" wasn't. Advance the state machine and
1254 * go do the next stuff.
1256 conn->status = CONNECTION_STARTED;
1261 * This connection failed --- set up error report, then
1262 * close socket (do it this way in case close() affects
1263 * the value of errno...). We will ignore the connect()
1264 * failure and keep going if there are more addresses.
1266 connectFailureMessage(conn, SOCK_ERRNO);
1267 if (conn->sock >= 0)
1269 closesocket(conn->sock);
1274 * Try the next address, if any.
1276 conn->addr_cur = addr_cur->ai_next;
1277 } /* loop over addresses */
1280 * Ooops, no more addresses. An appropriate error message is
1281 * already set up, so just set the right status.
1286 case CONNECTION_STARTED:
1288 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1291 * Write ready, since we've made it here, so the connection
1292 * has been made ... or has failed.
1296 * Now check (using getsockopt) that there is not an error
1297 * state waiting for us on the socket.
1300 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1301 (char *) &optval, &optlen) == -1)
1303 appendPQExpBuffer(&conn->errorMessage,
1304 libpq_gettext("could not get socket error status: %s\n"),
1305 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1308 else if (optval != 0)
1311 * When using a nonblocking connect, we will typically see
1312 * connect failures at this point, so provide a friendly
1315 connectFailureMessage(conn, optval);
1318 * If more addresses remain, keep trying, just as in the
1319 * case where connect() returned failure immediately.
1321 if (conn->addr_cur->ai_next != NULL)
1323 if (conn->sock >= 0)
1325 closesocket(conn->sock);
1328 conn->addr_cur = conn->addr_cur->ai_next;
1329 conn->status = CONNECTION_NEEDED;
1335 /* Fill in the client address */
1336 conn->laddr.salen = sizeof(conn->laddr.addr);
1337 if (getsockname(conn->sock,
1338 (struct sockaddr *) & conn->laddr.addr,
1339 &conn->laddr.salen) < 0)
1341 appendPQExpBuffer(&conn->errorMessage,
1342 libpq_gettext("could not get client address from socket: %s\n"),
1343 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1348 * Make sure we can write before advancing to next step.
1350 conn->status = CONNECTION_MADE;
1351 return PGRES_POLLING_WRITING;
1354 case CONNECTION_MADE:
1362 * If SSL is enabled and we haven't already got it running,
1363 * request it instead of sending the startup message.
1365 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1367 /* Don't bother requesting SSL over a Unix socket */
1368 conn->allow_ssl_try = false;
1370 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1376 * Send the SSL request packet.
1378 * Theoretically, this could block, but it really
1379 * shouldn't since we only got here if the socket is
1382 pv = htonl(NEGOTIATE_SSL_CODE);
1383 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1385 appendPQExpBuffer(&conn->errorMessage,
1386 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1387 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1390 /* Ok, wait for response */
1391 conn->status = CONNECTION_SSL_STARTUP;
1392 return PGRES_POLLING_READING;
1394 #endif /* USE_SSL */
1397 * Build the startup packet.
1399 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1400 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1401 EnvironmentOptions);
1403 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1404 EnvironmentOptions);
1408 * will not appendbuffer here, since it's likely to also
1411 printfPQExpBuffer(&conn->errorMessage,
1412 libpq_gettext("out of memory\n"));
1417 * Send the startup packet.
1419 * Theoretically, this could block, but it really shouldn't
1420 * since we only got here if the socket is write-ready.
1422 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1424 appendPQExpBuffer(&conn->errorMessage,
1425 libpq_gettext("could not send startup packet: %s\n"),
1426 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1433 conn->status = CONNECTION_AWAITING_RESPONSE;
1434 return PGRES_POLLING_READING;
1438 * Handle SSL negotiation: wait for postmaster messages and
1439 * respond as necessary.
1441 case CONNECTION_SSL_STARTUP:
1444 PostgresPollingStatusType pollres;
1447 * On first time through, get the postmaster's response to our
1448 * SSL negotiation packet.
1450 if (conn->ssl == NULL)
1453 * We use pqReadData here since it has the logic to
1454 * distinguish no-data-yet from connection closure. Since
1455 * conn->ssl isn't set, a plain recv() will occur.
1460 rdresult = pqReadData(conn);
1463 /* errorMessage is already filled in */
1468 /* caller failed to wait for data */
1469 return PGRES_POLLING_READING;
1471 if (pqGetc(&SSLok, conn) < 0)
1473 /* should not happen really */
1474 return PGRES_POLLING_READING;
1476 /* mark byte consumed */
1477 conn->inStart = conn->inCursor;
1480 /* Set up global SSL state if required */
1481 if (pqsecure_initialize(conn) == -1)
1484 else if (SSLok == 'N')
1486 if (conn->sslmode[0] == 'r' || /* "require" */
1487 conn->sslmode[0] == 'v') /* "verify-ca" or
1490 /* Require SSL, but server does not want it */
1491 appendPQExpBuffer(&conn->errorMessage,
1492 libpq_gettext("server does not support SSL, but SSL was required\n"));
1495 /* Otherwise, proceed with normal startup */
1496 conn->allow_ssl_try = false;
1497 conn->status = CONNECTION_MADE;
1498 return PGRES_POLLING_WRITING;
1500 else if (SSLok == 'E')
1502 /* Received error - probably protocol mismatch */
1504 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1505 if (conn->sslmode[0] == 'r' || /* "require" */
1506 conn->sslmode[0] == 'v') /* "verify-ca" or
1509 /* Require SSL, but server is too old */
1510 appendPQExpBuffer(&conn->errorMessage,
1511 libpq_gettext("server does not support SSL, but SSL was required\n"));
1514 /* Otherwise, try again without SSL */
1515 conn->allow_ssl_try = false;
1516 /* Assume it ain't gonna handle protocol 3, either */
1517 conn->pversion = PG_PROTOCOL(2, 0);
1518 /* Must drop the old connection */
1519 closesocket(conn->sock);
1521 conn->status = CONNECTION_NEEDED;
1526 appendPQExpBuffer(&conn->errorMessage,
1527 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1534 * Begin or continue the SSL negotiation process.
1536 pollres = pqsecure_open_client(conn);
1537 if (pollres == PGRES_POLLING_OK)
1539 /* SSL handshake done, ready to send startup packet */
1540 conn->status = CONNECTION_MADE;
1541 return PGRES_POLLING_WRITING;
1543 if (pollres == PGRES_POLLING_FAILED)
1546 * Failed ... if sslmode is "prefer" then do a non-SSL
1549 if (conn->sslmode[0] == 'p' /* "prefer" */
1550 && conn->allow_ssl_try /* redundant? */
1551 && !conn->wait_ssl_try) /* redundant? */
1553 /* only retry once */
1554 conn->allow_ssl_try = false;
1555 /* Must drop the old connection */
1556 closesocket(conn->sock);
1558 conn->status = CONNECTION_NEEDED;
1563 #else /* !USE_SSL */
1564 /* can't get here */
1566 #endif /* USE_SSL */
1570 * Handle authentication exchange: wait for postmaster messages
1571 * and respond as necessary.
1573 case CONNECTION_AWAITING_RESPONSE:
1581 * Scan the message from current point (note that if we find
1582 * the message is incomplete, we will return without advancing
1583 * inStart, and resume here next time).
1585 conn->inCursor = conn->inStart;
1587 /* Read type byte */
1588 if (pqGetc(&beresp, conn))
1590 /* We'll come back when there is more data */
1591 return PGRES_POLLING_READING;
1595 * Validate message type: we expect only an authentication
1596 * request or an error here. Anything else probably means
1597 * it's not Postgres on the other end at all.
1599 if (!(beresp == 'R' || beresp == 'E'))
1601 appendPQExpBuffer(&conn->errorMessage,
1603 "expected authentication request from "
1604 "server, but received %c\n"),
1609 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1611 /* Read message length word */
1612 if (pqGetInt(&msgLength, 4, conn))
1614 /* We'll come back when there is more data */
1615 return PGRES_POLLING_READING;
1620 /* Set phony message length to disable checks below */
1625 * Try to validate message length before using it.
1626 * Authentication requests can't be very large, although GSS
1627 * auth requests may not be that small. Errors can be a
1628 * little larger, but not huge. If we see a large apparent
1629 * length in an error, it means we're really talking to a
1630 * pre-3.0-protocol server; cope.
1632 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1634 appendPQExpBuffer(&conn->errorMessage,
1636 "expected authentication request from "
1637 "server, but received %c\n"),
1642 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1644 /* Handle error from a pre-3.0 server */
1645 conn->inCursor = conn->inStart + 1; /* reread data */
1646 if (pqGets_append(&conn->errorMessage, conn))
1648 /* We'll come back when there is more data */
1649 return PGRES_POLLING_READING;
1651 /* OK, we read the message; mark data consumed */
1652 conn->inStart = conn->inCursor;
1655 * The postmaster typically won't end its message with a
1656 * newline, so add one to conform to libpq conventions.
1658 appendPQExpBufferChar(&conn->errorMessage, '\n');
1661 * If we tried to open the connection in 3.0 protocol,
1662 * fall back to 2.0 protocol.
1664 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1666 conn->pversion = PG_PROTOCOL(2, 0);
1667 /* Must drop the old connection */
1668 pqsecure_close(conn);
1669 closesocket(conn->sock);
1671 conn->status = CONNECTION_NEEDED;
1679 * Can't process if message body isn't all here yet.
1681 * (In protocol 2.0 case, we are assuming messages carry at
1682 * least 4 bytes of data.)
1685 avail = conn->inEnd - conn->inCursor;
1686 if (avail < msgLength)
1689 * Before returning, try to enlarge the input buffer if
1690 * needed to hold the whole message; see notes in
1693 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1696 /* We'll come back when there is more data */
1697 return PGRES_POLLING_READING;
1700 /* Handle errors. */
1703 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1705 if (pqGetErrorNotice3(conn, true))
1707 /* We'll come back when there is more data */
1708 return PGRES_POLLING_READING;
1713 if (pqGets_append(&conn->errorMessage, conn))
1715 /* We'll come back when there is more data */
1716 return PGRES_POLLING_READING;
1719 /* OK, we read the message; mark data consumed */
1720 conn->inStart = conn->inCursor;
1725 * if sslmode is "allow" and we haven't tried an SSL
1726 * connection already, then retry with an SSL connection
1728 if (conn->sslmode[0] == 'a' /* "allow" */
1729 && conn->ssl == NULL
1730 && conn->allow_ssl_try
1731 && conn->wait_ssl_try)
1733 /* only retry once */
1734 conn->wait_ssl_try = false;
1735 /* Must drop the old connection */
1736 closesocket(conn->sock);
1738 conn->status = CONNECTION_NEEDED;
1743 * if sslmode is "prefer" and we're in an SSL connection,
1744 * then do a non-SSL retry
1746 if (conn->sslmode[0] == 'p' /* "prefer" */
1748 && conn->allow_ssl_try /* redundant? */
1749 && !conn->wait_ssl_try) /* redundant? */
1751 /* only retry once */
1752 conn->allow_ssl_try = false;
1753 /* Must drop the old connection */
1754 pqsecure_close(conn);
1755 closesocket(conn->sock);
1757 conn->status = CONNECTION_NEEDED;
1765 /* It is an authentication request. */
1766 /* Get the type of request. */
1767 if (pqGetInt((int *) &areq, 4, conn))
1769 /* We'll come back when there are more data */
1770 return PGRES_POLLING_READING;
1773 /* Get the password salt if there is one. */
1774 if (areq == AUTH_REQ_MD5)
1776 if (pqGetnchar(conn->md5Salt,
1777 sizeof(conn->md5Salt), conn))
1779 /* We'll come back when there are more data */
1780 return PGRES_POLLING_READING;
1783 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1786 * Continue GSSAPI/SSPI authentication
1788 if (areq == AUTH_REQ_GSS_CONT)
1790 int llen = msgLength - 4;
1793 * We can be called repeatedly for the same buffer. Avoid
1794 * re-allocating the buffer in this case - just re-use the
1797 if (llen != conn->ginbuf.length)
1799 if (conn->ginbuf.value)
1800 free(conn->ginbuf.value);
1802 conn->ginbuf.length = llen;
1803 conn->ginbuf.value = malloc(llen);
1804 if (!conn->ginbuf.value)
1806 printfPQExpBuffer(&conn->errorMessage,
1807 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1813 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1815 /* We'll come back when there is more data. */
1816 return PGRES_POLLING_READING;
1822 * OK, we successfully read the message; mark data consumed
1824 conn->inStart = conn->inCursor;
1826 /* Respond to the request if necessary. */
1829 * Note that conn->pghost must be non-NULL if we are going to
1830 * avoid the Kerberos code doing a hostname look-up.
1833 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1835 conn->errorMessage.len = strlen(conn->errorMessage.data);
1838 conn->errorMessage.len = strlen(conn->errorMessage.data);
1841 * Just make sure that any data sent by pg_fe_sendauth is
1842 * flushed out. Although this theoretically could block, it
1843 * really shouldn't since we don't send large auth responses.
1848 if (areq == AUTH_REQ_OK)
1850 /* We are done with authentication exchange */
1851 conn->status = CONNECTION_AUTH_OK;
1854 * Set asyncStatus so that PQsetResult will think that
1855 * what comes back next is the result of a query. See
1858 conn->asyncStatus = PGASYNC_BUSY;
1861 /* Look to see if we have more data yet. */
1865 case CONNECTION_AUTH_OK:
1868 * Now we expect to hear from the backend. A ReadyForQuery
1869 * message indicates that startup is successful, but we might
1870 * also get an Error message indicating failure. (Notice
1871 * messages indicating nonfatal warnings are also allowed by
1872 * the protocol, as are ParameterStatus and BackendKeyData
1873 * messages.) Easiest way to handle this is to let
1874 * PQgetResult() read the messages. We just have to fake it
1875 * out about the state of the connection, by setting
1876 * asyncStatus = PGASYNC_BUSY (done above).
1880 return PGRES_POLLING_READING;
1882 res = PQgetResult(conn);
1885 * NULL return indicating we have gone to IDLE state is
1890 if (res->resultStatus != PGRES_FATAL_ERROR)
1891 appendPQExpBuffer(&conn->errorMessage,
1892 libpq_gettext("unexpected message from server during startup\n"));
1893 else if (conn->send_appname &&
1894 (conn->appname || conn->fbappname))
1897 * If we tried to send application_name, check to see
1898 * if the error is about that --- pre-8.5 servers will
1899 * reject it at this stage of the process. If so,
1900 * close the connection and retry without sending
1901 * application_name. We could possibly get a false
1902 * SQLSTATE match here and retry uselessly, but there
1903 * seems no great harm in that; we'll just get the
1904 * same error again if it's unrelated.
1906 const char *sqlstate;
1908 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
1910 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
1913 conn->send_appname = false;
1914 /* Must drop the old connection */
1915 pqsecure_close(conn);
1916 closesocket(conn->sock);
1918 conn->status = CONNECTION_NEEDED;
1924 * if the resultStatus is FATAL, then conn->errorMessage
1925 * already has a copy of the error; needn't copy it back.
1926 * But add a newline if it's not there already, since
1927 * postmaster error messages may not have one.
1929 if (conn->errorMessage.len <= 0 ||
1930 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1931 appendPQExpBufferChar(&conn->errorMessage, '\n');
1936 /* We can release the address list now. */
1937 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1938 conn->addrlist = NULL;
1939 conn->addr_cur = NULL;
1941 /* Fire up post-connection housekeeping if needed */
1942 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1944 conn->status = CONNECTION_SETENV;
1945 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1946 conn->next_eo = EnvironmentOptions;
1947 return PGRES_POLLING_WRITING;
1950 /* Otherwise, we are open for business! */
1951 conn->status = CONNECTION_OK;
1952 return PGRES_POLLING_OK;
1955 case CONNECTION_SETENV:
1958 * Do post-connection housekeeping (only needed in protocol 2.0).
1960 * We pretend that the connection is OK for the duration of these
1963 conn->status = CONNECTION_OK;
1965 switch (pqSetenvPoll(conn))
1967 case PGRES_POLLING_OK: /* Success */
1970 case PGRES_POLLING_READING: /* Still going */
1971 conn->status = CONNECTION_SETENV;
1972 return PGRES_POLLING_READING;
1974 case PGRES_POLLING_WRITING: /* Still going */
1975 conn->status = CONNECTION_SETENV;
1976 return PGRES_POLLING_WRITING;
1982 /* We are open for business! */
1983 conn->status = CONNECTION_OK;
1984 return PGRES_POLLING_OK;
1987 appendPQExpBuffer(&conn->errorMessage,
1988 libpq_gettext("invalid connection state %d, "
1989 "probably indicative of memory corruption\n"),
1999 * We used to close the socket at this point, but that makes it awkward
2000 * for those above us if they wish to remove this socket from their own
2001 * records (an fd_set for example). We'll just have this socket closed
2002 * when PQfinish is called (which is compulsory even after an error, since
2003 * the connection structure must be freed).
2005 conn->status = CONNECTION_BAD;
2006 return PGRES_POLLING_FAILED;
2012 * - create a PGconn data structure with (as yet) no interesting data
2015 makeEmptyPGconn(void)
2022 * Make sure socket support is up and running.
2026 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
2031 conn = (PGconn *) malloc(sizeof(PGconn));
2040 /* Zero all pointers and booleans */
2041 MemSet(conn, 0, sizeof(PGconn));
2043 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2044 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2045 conn->status = CONNECTION_BAD;
2046 conn->asyncStatus = PGASYNC_IDLE;
2047 conn->xactStatus = PQTRANS_IDLE;
2048 conn->options_valid = false;
2049 conn->nonblocking = false;
2050 conn->setenv_state = SETENV_STATE_IDLE;
2051 conn->client_encoding = PG_SQL_ASCII;
2052 conn->std_strings = false; /* unless server says differently */
2053 conn->verbosity = PQERRORS_DEFAULT;
2055 conn->password_needed = false;
2057 conn->allow_ssl_try = true;
2058 conn->wait_ssl_try = false;
2062 * We try to send at least 8K at a time, which is the usual size of pipe
2063 * buffers on Unix systems. That way, when we are sending a large amount
2064 * of data, we avoid incurring extra kernel context swaps for partial
2065 * bufferloads. The output buffer is initially made 16K in size, and we
2066 * try to dump it after accumulating 8K.
2068 * With the same goal of minimizing context swaps, the input buffer will
2069 * be enlarged anytime it has less than 8K free, so we initially allocate
2072 conn->inBufSize = 16 * 1024;
2073 conn->inBuffer = (char *) malloc(conn->inBufSize);
2074 conn->outBufSize = 16 * 1024;
2075 conn->outBuffer = (char *) malloc(conn->outBufSize);
2076 initPQExpBuffer(&conn->errorMessage);
2077 initPQExpBuffer(&conn->workBuffer);
2079 if (conn->inBuffer == NULL ||
2080 conn->outBuffer == NULL ||
2081 PQExpBufferBroken(&conn->errorMessage) ||
2082 PQExpBufferBroken(&conn->workBuffer))
2084 /* out of memory already :-( */
2094 * - free an idle (closed) PGconn data structure
2096 * NOTE: this should not overlap any functionality with closePGconn().
2097 * Clearing/resetting of transient state belongs there; what we do here is
2098 * release data that is to be held for the life of the PGconn structure.
2099 * If a value ought to be cleared/freed during PQreset(), do it there not here.
2102 freePGconn(PGconn *conn)
2106 /* let any event procs clean up their state data */
2107 for (i = 0; i < conn->nEvents; i++)
2109 PGEventConnDestroy evt;
2112 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2113 conn->events[i].passThrough);
2114 free(conn->events[i].name);
2121 if (conn->pghostaddr)
2122 free(conn->pghostaddr);
2125 if (conn->pgunixsocket)
2126 free(conn->pgunixsocket);
2129 if (conn->connect_timeout)
2130 free(conn->connect_timeout);
2131 if (conn->pgoptions)
2132 free(conn->pgoptions);
2134 free(conn->appname);
2135 if (conn->fbappname)
2136 free(conn->fbappname);
2144 free(conn->sslmode);
2146 free(conn->sslcert);
2149 if (conn->sslrootcert)
2150 free(conn->sslrootcert);
2153 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2154 if (conn->krbsrvname)
2155 free(conn->krbsrvname);
2157 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2161 /* Note that conn->Pfdebug is not ours to close or free */
2162 if (conn->last_query)
2163 free(conn->last_query);
2165 free(conn->inBuffer);
2166 if (conn->outBuffer)
2167 free(conn->outBuffer);
2168 termPQExpBuffer(&conn->errorMessage);
2169 termPQExpBuffer(&conn->workBuffer);
2180 * - properly close a connection to the backend
2182 * This should reset or release all transient state, but NOT the connection
2183 * parameters. On exit, the PGconn should be in condition to start a fresh
2184 * connection with the same parameters (see PQreset()).
2187 closePGconn(PGconn *conn)
2190 pgParameterStatus *pstatus;
2193 * Note that the protocol doesn't allow us to send Terminate messages
2194 * during the startup phase.
2196 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2199 * Try to send "close connection" message to backend. Ignore any
2202 pqPutMsgStart('X', false, conn);
2208 * Must reset the blocking status so a possible reconnect will work.
2210 * Don't call PQsetnonblocking() because it will fail if it's unable to
2211 * flush the connection.
2213 conn->nonblocking = FALSE;
2216 * Close the connection, reset all transient state, flush I/O buffers.
2218 if (conn->sock >= 0)
2220 pqsecure_close(conn);
2221 closesocket(conn->sock);
2224 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2226 conn->asyncStatus = PGASYNC_IDLE;
2227 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2228 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2229 conn->addrlist = NULL;
2230 conn->addr_cur = NULL;
2231 notify = conn->notifyHead;
2232 while (notify != NULL)
2234 PGnotify *prev = notify;
2236 notify = notify->next;
2239 conn->notifyHead = conn->notifyTail = NULL;
2240 pstatus = conn->pstatus;
2241 while (pstatus != NULL)
2243 pgParameterStatus *prev = pstatus;
2245 pstatus = pstatus->next;
2248 conn->pstatus = NULL;
2249 if (conn->lobjfuncs)
2250 free(conn->lobjfuncs);
2251 conn->lobjfuncs = NULL;
2252 conn->inStart = conn->inCursor = conn->inEnd = 0;
2259 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2260 if (conn->gtarg_nam)
2261 gss_release_name(&min_s, &conn->gtarg_nam);
2262 if (conn->ginbuf.length)
2263 gss_release_buffer(&min_s, &conn->ginbuf);
2264 if (conn->goutbuf.length)
2265 gss_release_buffer(&min_s, &conn->goutbuf);
2269 if (conn->ginbuf.length)
2270 free(conn->ginbuf.value);
2271 conn->ginbuf.length = 0;
2272 conn->ginbuf.value = NULL;
2273 if (conn->sspitarget)
2274 free(conn->sspitarget);
2275 conn->sspitarget = NULL;
2278 FreeCredentialsHandle(conn->sspicred);
2279 free(conn->sspicred);
2280 conn->sspicred = NULL;
2284 DeleteSecurityContext(conn->sspictx);
2285 free(conn->sspictx);
2286 conn->sspictx = NULL;
2292 * PQfinish: properly close a connection to the backend. Also frees
2293 * the PGconn data structure so it shouldn't be re-used after this.
2296 PQfinish(PGconn *conn)
2306 * PQreset: resets the connection to the backend by closing the
2307 * existing connection and creating a new one.
2310 PQreset(PGconn *conn)
2316 if (connectDBStart(conn) && connectDBComplete(conn))
2319 * Notify event procs of successful reset. We treat an event proc
2320 * failure as disabling the connection ... good idea?
2324 for (i = 0; i < conn->nEvents; i++)
2326 PGEventConnReset evt;
2329 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2330 conn->events[i].passThrough))
2332 conn->status = CONNECTION_BAD;
2333 printfPQExpBuffer(&conn->errorMessage,
2334 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2335 conn->events[i].name);
2346 * resets the connection to the backend
2347 * closes the existing connection and makes a new one
2348 * Returns 1 on success, 0 on failure.
2351 PQresetStart(PGconn *conn)
2357 return connectDBStart(conn);
2366 * resets the connection to the backend
2367 * closes the existing connection and makes a new one
2369 PostgresPollingStatusType
2370 PQresetPoll(PGconn *conn)
2374 PostgresPollingStatusType status = PQconnectPoll(conn);
2376 if (status == PGRES_POLLING_OK)
2379 * Notify event procs of successful reset. We treat an event proc
2380 * failure as disabling the connection ... good idea?
2384 for (i = 0; i < conn->nEvents; i++)
2386 PGEventConnReset evt;
2389 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2390 conn->events[i].passThrough))
2392 conn->status = CONNECTION_BAD;
2393 printfPQExpBuffer(&conn->errorMessage,
2394 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2395 conn->events[i].name);
2396 return PGRES_POLLING_FAILED;
2404 return PGRES_POLLING_FAILED;
2408 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2410 * A copy is needed to be able to cancel a running query from a different
2411 * thread. If the same structure is used all structure members would have
2412 * to be individually locked (if the entire structure was locked, it would
2413 * be impossible to cancel a synchronous query because the structure would
2414 * have to stay locked for the duration of the query).
2417 PQgetCancel(PGconn *conn)
2427 cancel = malloc(sizeof(PGcancel));
2431 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2432 cancel->be_pid = conn->be_pid;
2433 cancel->be_key = conn->be_key;
2438 /* PQfreeCancel: free a cancel structure */
2440 PQfreeCancel(PGcancel *cancel)
2448 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2449 * current operation.
2451 * The return value is TRUE if the cancel request was successfully
2452 * dispatched, FALSE if not (in which case an error message is available).
2453 * Note: successful dispatch is no guarantee that there will be any effect at
2454 * the backend. The application must read the operation result as usual.
2456 * CAUTION: we want this routine to be safely callable from a signal handler
2457 * (for example, an application might want to call it in a SIGINT handler).
2458 * This means we cannot use any C library routine that might be non-reentrant.
2459 * malloc/free are often non-reentrant, and anything that might call them is
2460 * just as dangerous. We avoid sprintf here for that reason. Building up
2461 * error messages with strcpy/strcat is tedious but should be quite safe.
2462 * We also save/restore errno in case the signal handler support doesn't.
2464 * internal_cancel() is an internal helper function to make code-sharing
2465 * between the two versions of the cancel function possible.
2468 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2469 char *errbuf, int errbufsize)
2471 int save_errno = SOCK_ERRNO;
2478 CancelRequestPacket cp;
2482 * We need to open a temporary connection to the postmaster. Do this with
2483 * only kernel calls.
2485 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2487 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2488 goto cancel_errReturn;
2491 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2494 if (SOCK_ERRNO == EINTR)
2495 /* Interrupted system call - we'll just try again */
2497 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2498 goto cancel_errReturn;
2502 * We needn't set nonblocking I/O or NODELAY options here.
2505 /* Create and send the cancel request packet. */
2507 crp.packetlen = htonl((uint32) sizeof(crp));
2508 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2509 crp.cp.backendPID = htonl(be_pid);
2510 crp.cp.cancelAuthCode = htonl(be_key);
2513 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2515 if (SOCK_ERRNO == EINTR)
2516 /* Interrupted system call - we'll just try again */
2518 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2519 goto cancel_errReturn;
2523 * Wait for the postmaster to close the connection, which indicates that
2524 * it's processed the request. Without this delay, we might issue another
2525 * command only to find that our cancel zaps that command instead of the
2526 * one we thought we were canceling. Note we don't actually expect this
2527 * read to obtain any data, we are just waiting for EOF to be signaled.
2530 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2532 if (SOCK_ERRNO == EINTR)
2533 /* Interrupted system call - we'll just try again */
2535 /* we ignore other error conditions */
2539 closesocket(tmpsock);
2540 SOCK_ERRNO_SET(save_errno);
2546 * Make sure we don't overflow the error buffer. Leave space for the \n at
2547 * the end, and for the terminating zero.
2549 maxlen = errbufsize - strlen(errbuf) - 2;
2552 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2554 strcat(errbuf, "\n");
2557 closesocket(tmpsock);
2558 SOCK_ERRNO_SET(save_errno);
2563 * PQcancel: request query cancel
2565 * Returns TRUE if able to send the cancel request, FALSE if not.
2567 * On failure, an error message is stored in *errbuf, which must be of size
2568 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2572 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2576 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2580 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2581 errbuf, errbufsize);
2585 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2587 * Returns TRUE if able to send the cancel request, FALSE if not.
2589 * On failure, the error message is saved in conn->errorMessage; this means
2590 * that this can't be used when there might be other active operations on
2591 * the connection object.
2593 * NOTE: error messages will be cut off at the current size of the
2594 * error message buffer, since we dare not try to expand conn->errorMessage!
2597 PQrequestCancel(PGconn *conn)
2601 /* Check we have an open connection */
2607 strlcpy(conn->errorMessage.data,
2608 "PQrequestCancel() -- connection is not open\n",
2609 conn->errorMessage.maxlen);
2610 conn->errorMessage.len = strlen(conn->errorMessage.data);
2615 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2616 conn->errorMessage.data, conn->errorMessage.maxlen);
2619 conn->errorMessage.len = strlen(conn->errorMessage.data);
2626 * pqPacketSend() -- convenience routine to send a message to server.
2628 * pack_type: the single-byte message type code. (Pass zero for startup
2629 * packets, which have no message type code.)
2631 * buf, buf_len: contents of message. The given length includes only what
2632 * is in buf; the message type and message length fields are added here.
2634 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2635 * SIDE_EFFECTS: may block.
2637 * Note: all messages sent with this routine have a length word, whether
2638 * it's protocol 2.0 or 3.0.
2641 pqPacketSend(PGconn *conn, char pack_type,
2642 const void *buf, size_t buf_len)
2644 /* Start the message. */
2645 if (pqPutMsgStart(pack_type, true, conn))
2646 return STATUS_ERROR;
2648 /* Send the message body. */
2649 if (pqPutnchar(buf, buf_len, conn))
2650 return STATUS_ERROR;
2652 /* Finish the message. */
2653 if (pqPutMsgEnd(conn))
2654 return STATUS_ERROR;
2656 /* Flush to ensure backend gets it. */
2658 return STATUS_ERROR;
2665 #define LDAP_URL "ldap://"
2666 #define LDAP_DEF_PORT 389
2667 #define PGLDAP_TIMEOUT 2
2669 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2670 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2676 * Search the LDAP URL passed as first argument, treat the result as a
2677 * string of connection options that are parsed and added to the array of
2678 * options passed as second argument.
2680 * LDAP URLs must conform to RFC 1959 without escape sequences.
2681 * ldap://host:port/dn?attributes?scope?filter?extensions
2684 * 0 if the lookup was successful,
2685 * 1 if the connection to the LDAP server could be established but
2686 * the search was unsuccessful,
2687 * 2 if a connection could not be established, and
2688 * 3 if a fatal error occurred.
2690 * An error message is returned in the third argument for return codes 1 and 3.
2693 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2694 PQExpBuffer errorMessage)
2696 int port = LDAP_DEF_PORT,
2717 char *attrs[2] = {NULL, NULL};
2721 struct berval **values;
2722 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2724 if ((url = strdup(purl)) == NULL)
2726 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2731 * Parse URL components, check for correctness. Basically, url has '\0'
2732 * placed at component boundaries and variables are pointed at each
2736 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2738 printfPQExpBuffer(errorMessage,
2739 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2745 hostname = url + strlen(LDAP_URL);
2746 if (*hostname == '/') /* no hostname? */
2747 hostname = "localhost"; /* the default */
2749 /* dn, "distinguished name" */
2750 p = strchr(url + strlen(LDAP_URL), '/');
2751 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2753 printfPQExpBuffer(errorMessage, libpq_gettext(
2754 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2758 *p = '\0'; /* terminate hostname */
2762 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2764 printfPQExpBuffer(errorMessage, libpq_gettext(
2765 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2773 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2775 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2783 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2785 printfPQExpBuffer(errorMessage,
2786 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2792 if ((p = strchr(filter, '?')) != NULL)
2796 if ((p1 = strchr(hostname, ':')) != NULL)
2803 lport = strtol(portstr, &endptr, 10);
2804 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2806 printfPQExpBuffer(errorMessage, libpq_gettext(
2807 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2814 /* Allow only one attribute */
2815 if (strchr(attrs[0], ',') != NULL)
2817 printfPQExpBuffer(errorMessage, libpq_gettext(
2818 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2824 if (pg_strcasecmp(scopestr, "base") == 0)
2825 scope = LDAP_SCOPE_BASE;
2826 else if (pg_strcasecmp(scopestr, "one") == 0)
2827 scope = LDAP_SCOPE_ONELEVEL;
2828 else if (pg_strcasecmp(scopestr, "sub") == 0)
2829 scope = LDAP_SCOPE_SUBTREE;
2832 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2837 /* initialize LDAP structure */
2838 if ((ld = ldap_init(hostname, port)) == NULL)
2840 printfPQExpBuffer(errorMessage,
2841 libpq_gettext("could not create LDAP structure\n"));
2847 * Initialize connection to the server. We do an explicit bind because we
2848 * want to return 2 if the bind fails.
2850 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2852 /* error in ldap_simple_bind() */
2858 /* wait some time for the connection to succeed */
2860 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2868 /* error in ldap_result() */
2877 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2882 printfPQExpBuffer(errorMessage,
2883 libpq_gettext("lookup on LDAP server failed: %s\n"),
2884 ldap_err2string(rc));
2890 /* complain if there was not exactly one result */
2891 if ((rc = ldap_count_entries(ld, res)) != 1)
2893 printfPQExpBuffer(errorMessage,
2894 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2895 : libpq_gettext("no entry found on LDAP lookup\n"));
2903 if ((entry = ldap_first_entry(ld, res)) == NULL)
2905 /* should never happen */
2906 printfPQExpBuffer(errorMessage,
2907 libpq_gettext("no entry found on LDAP lookup\n"));
2915 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2917 printfPQExpBuffer(errorMessage,
2918 libpq_gettext("attribute has no values on LDAP lookup\n"));
2928 if (values[0] == NULL)
2930 printfPQExpBuffer(errorMessage,
2931 libpq_gettext("attribute has no values on LDAP lookup\n"));
2932 ldap_value_free_len(values);
2937 /* concatenate values to a single string */
2938 for (size = 0, i = 0; values[i] != NULL; ++i)
2939 size += values[i]->bv_len + 1;
2940 if ((result = malloc(size + 1)) == NULL)
2942 printfPQExpBuffer(errorMessage,
2943 libpq_gettext("out of memory\n"));
2944 ldap_value_free_len(values);
2948 for (p = result, i = 0; values[i] != NULL; ++i)
2950 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2951 p += values[i]->bv_len;
2953 if (values[i + 1] == NULL)
2957 ldap_value_free_len(values);
2960 /* parse result string */
2961 oldstate = state = 0;
2962 for (p = result; *p != '\0'; ++p)
2966 case 0: /* between entries */
2967 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2973 case 1: /* in option name */
2974 if (ld_is_sp_tab(*p))
2979 else if (ld_is_nl_cr(*p))
2981 printfPQExpBuffer(errorMessage, libpq_gettext(
2982 "missing \"=\" after \"%s\" in connection info string\n"),
2992 case 2: /* after option name */
2997 else if (!ld_is_sp_tab(*p))
2999 printfPQExpBuffer(errorMessage, libpq_gettext(
3000 "missing \"=\" after \"%s\" in connection info string\n"),
3005 case 3: /* before option value */
3012 else if (ld_is_nl_cr(*p))
3014 optval = optname + strlen(optname); /* empty */
3017 else if (!ld_is_sp_tab(*p))
3023 case 4: /* in unquoted option value */
3024 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3030 case 5: /* in quoted option value */
3036 else if (*p == '\\')
3041 case 6: /* in quoted option value after escape */
3047 if (state == 0 && oldstate != 0)
3049 found_keyword = false;
3050 for (i = 0; options[i].keyword; i++)
3052 if (strcmp(options[i].keyword, optname) == 0)
3054 if (options[i].val == NULL)
3055 options[i].val = strdup(optval);
3056 found_keyword = true;
3062 printfPQExpBuffer(errorMessage,
3063 libpq_gettext("invalid connection option \"%s\"\n"),
3073 if (state == 5 || state == 6)
3075 printfPQExpBuffer(errorMessage, libpq_gettext(
3076 "unterminated quoted string in connection info string\n"));
3084 #define MAXBUFSIZE 256
3087 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3089 char *service = conninfo_getval(options, "service");
3090 char serviceFile[MAXPGPATH];
3091 bool group_found = false;
3096 * We have to special-case the environment variable PGSERVICE here, since
3097 * this is and should be called before inserting environment defaults for
3098 * other connection options.
3100 if (service == NULL)
3101 service = getenv("PGSERVICE");
3104 * This could be used by any application so we can't use the binary
3105 * location to find our config files.
3107 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3108 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3110 if (service != NULL)
3113 char buf[MAXBUFSIZE],
3116 f = fopen(serviceFile, "r");
3119 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3124 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3128 if (strlen(line) >= sizeof(buf) - 1)
3131 printfPQExpBuffer(errorMessage,
3132 libpq_gettext("line %d too long in service file \"%s\"\n"),
3138 /* ignore EOL at end of line */
3139 if (strlen(line) && line[strlen(line) - 1] == '\n')
3140 line[strlen(line) - 1] = 0;
3142 /* ignore leading blanks */
3143 while (*line && isspace((unsigned char) line[0]))
3146 /* ignore comments and empty lines */
3147 if (strlen(line) == 0 || line[0] == '#')
3150 /* Check for right groupname */
3155 /* group info already read */
3160 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3161 line[strlen(service) + 1] == ']')
3164 group_found = false;
3171 * Finally, we are in the right group and can parse the
3179 if (strncmp(line, "ldap", 4) == 0)
3181 int rc = ldapServiceLookup(line, options, errorMessage);
3183 /* if rc = 2, go on reading for fallback */
3200 val = strchr(line, '=');
3203 printfPQExpBuffer(errorMessage,
3204 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3213 * Set the parameter --- but don't override any previous
3216 found_keyword = false;
3217 for (i = 0; options[i].keyword; i++)
3219 if (strcmp(options[i].keyword, key) == 0)
3221 if (options[i].val == NULL)
3222 options[i].val = strdup(val);
3223 found_keyword = true;
3230 printfPQExpBuffer(errorMessage,
3231 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3245 printfPQExpBuffer(errorMessage,
3246 libpq_gettext("definition of service \"%s\" not found\n"), service);
3258 * Parse a string like PQconnectdb() would do and return the
3259 * resulting connection options array. NULL is returned on failure.
3260 * The result contains only options specified directly in the string,
3261 * not any possible default values.
3263 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3264 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3265 * both *errmsg and the result could be NULL.
3267 * NOTE: the returned array is dynamically allocated and should
3268 * be freed when no longer needed via PQconninfoFree().
3271 PQconninfoParse(const char *conninfo, char **errmsg)
3273 PQExpBufferData errorBuf;
3274 PQconninfoOption *connOptions;
3277 *errmsg = NULL; /* default */
3278 initPQExpBuffer(&errorBuf);
3279 if (PQExpBufferBroken(&errorBuf))
3280 return NULL; /* out of memory already :-( */
3281 connOptions = conninfo_parse(conninfo, &errorBuf, false);
3282 if (connOptions == NULL && errmsg)
3283 *errmsg = errorBuf.data;
3285 termPQExpBuffer(&errorBuf);
3290 * Conninfo parser routine
3292 * If successful, a malloc'd PQconninfoOption array is returned.
3293 * If not successful, NULL is returned and an error message is
3294 * left in errorMessage.
3295 * Defaults are supplied (from a service file, environment variables, etc)
3296 * for unspecified options, but only if use_defaults is TRUE.
3298 static PQconninfoOption *
3299 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3308 PQconninfoOption *options;
3309 PQconninfoOption *option;
3311 /* Make a working copy of PQconninfoOptions */
3312 options = malloc(sizeof(PQconninfoOptions));
3313 if (options == NULL)
3315 printfPQExpBuffer(errorMessage,
3316 libpq_gettext("out of memory\n"));
3319 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3321 /* Need a modifiable copy of the input string */
3322 if ((buf = strdup(conninfo)) == NULL)
3324 printfPQExpBuffer(errorMessage,
3325 libpq_gettext("out of memory\n"));
3326 PQconninfoFree(options);
3333 /* Skip blanks before the parameter name */
3334 if (isspace((unsigned char) *cp))
3340 /* Get the parameter name */
3346 if (isspace((unsigned char) *cp))
3351 if (!isspace((unsigned char) *cp))
3360 /* Check that there is a following '=' */
3363 printfPQExpBuffer(errorMessage,
3364 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3366 PQconninfoFree(options);
3372 /* Skip blanks after the '=' */
3375 if (!isspace((unsigned char) *cp))
3380 /* Get the parameter value */
3388 if (isspace((unsigned char) *cp))
3412 printfPQExpBuffer(errorMessage,
3413 libpq_gettext("unterminated quoted string in connection info string\n"));
3414 PQconninfoFree(options);
3436 * Now we have the name and the value. Search for the param record.
3438 for (option = options; option->keyword != NULL; option++)
3440 if (strcmp(option->keyword, pname) == 0)
3443 if (option->keyword == NULL)
3445 printfPQExpBuffer(errorMessage,
3446 libpq_gettext("invalid connection option \"%s\"\n"),
3448 PQconninfoFree(options);
3458 option->val = strdup(pval);
3461 printfPQExpBuffer(errorMessage,
3462 libpq_gettext("out of memory\n"));
3463 PQconninfoFree(options);
3469 /* Done with the modifiable input string */
3473 * Stop here if caller doesn't want defaults filled in.
3479 * If there's a service spec, use it to obtain any not-explicitly-given
3482 if (parseServiceInfo(options, errorMessage))
3484 PQconninfoFree(options);
3489 * Get the fallback resources for parameters not specified in the conninfo
3490 * string nor the service.
3492 for (option = options; option->keyword != NULL; option++)
3494 if (option->val != NULL)
3495 continue; /* Value was in conninfo or service */
3498 * Try to get the environment variable fallback
3500 if (option->envvar != NULL)
3502 if ((tmp = getenv(option->envvar)) != NULL)
3504 option->val = strdup(tmp);
3507 printfPQExpBuffer(errorMessage,
3508 libpq_gettext("out of memory\n"));
3509 PQconninfoFree(options);
3517 * No environment variable specified or this one isn't set - try
3520 if (option->compiled != NULL)
3522 option->val = strdup(option->compiled);
3525 printfPQExpBuffer(errorMessage,
3526 libpq_gettext("out of memory\n"));
3527 PQconninfoFree(options);
3534 * Special handling for user
3536 if (strcmp(option->keyword, "user") == 0)
3538 option->val = pg_fe_getauthname(errorMessage);
3548 conninfo_getval(PQconninfoOption *connOptions,
3549 const char *keyword)
3551 PQconninfoOption *option;
3553 for (option = connOptions; option->keyword != NULL; option++)
3555 if (strcmp(option->keyword, keyword) == 0)
3564 PQconninfoFree(PQconninfoOption *connOptions)
3566 PQconninfoOption *option;
3568 if (connOptions == NULL)
3571 for (option = connOptions; option->keyword != NULL; option++)
3573 if (option->val != NULL)
3580 /* =========== accessor functions for PGconn ========= */
3582 PQdb(const PGconn *conn)
3586 return conn->dbName;
3590 PQuser(const PGconn *conn)
3594 return conn->pguser;
3598 PQpass(const PGconn *conn)
3602 return conn->pgpass;
3606 PQhost(const PGconn *conn)
3610 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3614 PQport(const PGconn *conn)
3618 return conn->pgport;
3622 PQtty(const PGconn *conn)
3630 PQoptions(const PGconn *conn)
3634 return conn->pgoptions;
3638 PQstatus(const PGconn *conn)
3641 return CONNECTION_BAD;
3642 return conn->status;
3645 PGTransactionStatusType
3646 PQtransactionStatus(const PGconn *conn)
3648 if (!conn || conn->status != CONNECTION_OK)
3649 return PQTRANS_UNKNOWN;
3650 if (conn->asyncStatus != PGASYNC_IDLE)
3651 return PQTRANS_ACTIVE;
3652 return conn->xactStatus;
3656 PQparameterStatus(const PGconn *conn, const char *paramName)
3658 const pgParameterStatus *pstatus;
3660 if (!conn || !paramName)
3662 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3664 if (strcmp(pstatus->name, paramName) == 0)
3665 return pstatus->value;
3671 PQprotocolVersion(const PGconn *conn)
3675 if (conn->status == CONNECTION_BAD)
3677 return PG_PROTOCOL_MAJOR(conn->pversion);
3681 PQserverVersion(const PGconn *conn)
3685 if (conn->status == CONNECTION_BAD)
3687 return conn->sversion;
3691 PQerrorMessage(const PGconn *conn)
3694 return libpq_gettext("connection pointer is NULL\n");
3696 return conn->errorMessage.data;
3700 PQsocket(const PGconn *conn)
3708 PQbackendPID(const PGconn *conn)
3710 if (!conn || conn->status != CONNECTION_OK)
3712 return conn->be_pid;
3716 PQconnectionNeedsPassword(const PGconn *conn)
3720 if (conn->password_needed &&
3721 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
3728 PQconnectionUsedPassword(const PGconn *conn)
3732 if (conn->password_needed)
3739 PQclientEncoding(const PGconn *conn)
3741 if (!conn || conn->status != CONNECTION_OK)
3743 return conn->client_encoding;
3747 PQsetClientEncoding(PGconn *conn, const char *encoding)
3750 static const char query[] = "set client_encoding to '%s'";
3754 if (!conn || conn->status != CONNECTION_OK)
3760 /* check query buffer overflow */
3761 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3764 /* ok, now send a query */
3765 sprintf(qbuf, query, encoding);
3766 res = PQexec(conn, qbuf);
3770 if (res->resultStatus != PGRES_COMMAND_OK)
3775 * In protocol 2 we have to assume the setting will stick, and adjust
3776 * our state immediately. In protocol 3 and up we can rely on the
3777 * backend to report the parameter value, and we'll change state at
3780 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3781 pqSaveParameterStatus(conn, "client_encoding", encoding);
3782 status = 0; /* everything is ok */
3789 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3794 return PQERRORS_DEFAULT;
3795 old = conn->verbosity;
3796 conn->verbosity = verbosity;
3801 PQtrace(PGconn *conn, FILE *debug_port)
3806 conn->Pfdebug = debug_port;
3810 PQuntrace(PGconn *conn)
3816 fflush(conn->Pfdebug);
3817 conn->Pfdebug = NULL;
3822 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3824 PQnoticeReceiver old;
3829 old = conn->noticeHooks.noticeRec;
3832 conn->noticeHooks.noticeRec = proc;
3833 conn->noticeHooks.noticeRecArg = arg;
3839 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3841 PQnoticeProcessor old;
3846 old = conn->noticeHooks.noticeProc;
3849 conn->noticeHooks.noticeProc = proc;
3850 conn->noticeHooks.noticeProcArg = arg;
3856 * The default notice message receiver just gets the standard notice text
3857 * and sends it to the notice processor. This two-level setup exists
3858 * mostly for backwards compatibility; perhaps we should deprecate use of
3859 * PQsetNoticeProcessor?
3862 defaultNoticeReceiver(void *arg, const PGresult *res)
3864 (void) arg; /* not used */
3865 if (res->noticeHooks.noticeProc != NULL)
3866 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3867 PQresultErrorMessage(res));
3871 * The default notice message processor just prints the
3872 * message on stderr. Applications can override this if they
3873 * want the messages to go elsewhere (a window, for example).
3874 * Note that simply discarding notices is probably a bad idea.
3877 defaultNoticeProcessor(void *arg, const char *message)
3879 (void) arg; /* not used */
3880 /* Note: we expect the supplied string to end with a newline already. */
3881 fprintf(stderr, "%s", message);
3885 * returns a pointer to the next token or NULL if the current
3886 * token doesn't match
3889 pwdfMatchesString(char *buf, char *token)
3893 bool bslash = false;
3895 if (buf == NULL || token == NULL)
3899 if (tbuf[0] == '*' && tbuf[1] == ':')
3903 if (*tbuf == '\\' && !bslash)
3908 if (*tbuf == ':' && *ttok == 0 && !bslash)
3924 /* Get a password from the password file. Return value is malloc'd. */
3926 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3929 char pgpassfile[MAXPGPATH];
3930 struct stat stat_buf;
3933 #define LINELEN NAMEDATALEN*5
3936 if (dbname == NULL || strlen(dbname) == 0)
3939 if (username == NULL || strlen(username) == 0)
3942 /* 'localhost' matches pghost of '' or the default socket directory */
3943 if (hostname == NULL)
3944 hostname = DefaultHost;
3945 else if (is_absolute_path(hostname))
3948 * We should probably use canonicalize_path(), but then we have to
3949 * bring path.c into libpq, and it doesn't seem worth it.
3951 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3952 hostname = DefaultHost;
3955 port = DEF_PGPORT_STR;
3957 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3958 /* use the literal path from the environment, if set */
3959 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3962 char homedir[MAXPGPATH];
3964 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3966 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3969 /* If password file cannot be opened, ignore it. */
3970 if (stat(pgpassfile, &stat_buf) != 0)
3974 if (!S_ISREG(stat_buf.st_mode))
3977 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3982 /* If password file is insecure, alert the user and ignore it. */
3983 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3986 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
3993 * On Win32, the directory is protected, so we don't have to check the
3998 fp = fopen(pgpassfile, "r");
4008 fgets(buf, sizeof(buf), fp);
4014 /* Remove trailing newline */
4015 if (buf[len - 1] == '\n')
4018 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
4019 (t = pwdfMatchesString(t, port)) == NULL ||
4020 (t = pwdfMatchesString(t, dbname)) == NULL ||
4021 (t = pwdfMatchesString(t, username)) == NULL)
4035 * Obtain user's home directory, return in given buffer
4037 * On Unix, this actually returns the user's home directory. On Windows
4038 * it returns the PostgreSQL-specific application data folder.
4040 * This is essentially the same as get_home_path(), but we don't use that
4041 * because we don't want to pull path.c into libpq (it pollutes application
4045 pqGetHomeDirectory(char *buf, int bufsize)
4048 char pwdbuf[BUFSIZ];
4049 struct passwd pwdstr;
4050 struct passwd *pwd = NULL;
4052 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
4054 strlcpy(buf, pwd->pw_dir, bufsize);
4057 char tmppath[MAX_PATH];
4059 ZeroMemory(tmppath, sizeof(tmppath));
4060 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
4062 snprintf(buf, bufsize, "%s/postgresql", tmppath);
4068 * To keep the API consistent, the locking stubs are always provided, even
4069 * if they are not required.
4073 default_threadlock(int acquire)
4075 #ifdef ENABLE_THREAD_SAFETY
4077 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
4079 static pthread_mutex_t singlethread_lock = NULL;
4080 static long mutex_initlock = 0;
4082 if (singlethread_lock == NULL)
4084 while (InterlockedExchange(&mutex_initlock, 1) == 1)
4085 /* loop, another thread own the lock */ ;
4086 if (singlethread_lock == NULL)
4088 if (pthread_mutex_init(&singlethread_lock, NULL))
4089 PGTHREAD_ERROR("failed to initialize mutex");
4091 InterlockedExchange(&mutex_initlock, 0);
4096 if (pthread_mutex_lock(&singlethread_lock))
4097 PGTHREAD_ERROR("failed to lock mutex");
4101 if (pthread_mutex_unlock(&singlethread_lock))
4102 PGTHREAD_ERROR("failed to unlock mutex");
4108 PQregisterThreadLock(pgthreadlock_t newhandler)
4110 pgthreadlock_t prev = pg_g_threadlock;
4113 pg_g_threadlock = newhandler;
4115 pg_g_threadlock = default_threadlock;