Get rid of pgpass_from_client tracking inside libpq --- given the conclusion
[PostgreSQL.git] / src / interfaces / libpq / fe-connect.c
blobd1b7ad22e5818019c758d49e4bf1d351dd5ca025
1 /*-------------------------------------------------------------------------
3 * fe-connect.c
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <time.h>
23 #include <unistd.h>
25 #include "libpq-fe.h"
26 #include "libpq-int.h"
27 #include "fe-auth.h"
28 #include "pg_config_paths.h"
30 #ifdef WIN32
31 #include "win32.h"
32 #ifdef _WIN32_IE
33 #undef _WIN32_IE
34 #endif
35 #define _WIN32_IE 0x0500
36 #ifdef near
37 #undef near
38 #endif
39 #define near
40 #include <shlobj.h>
41 #else
42 #include <sys/socket.h>
43 #include <netdb.h>
44 #include <netinet/in.h>
45 #ifdef HAVE_NETINET_TCP_H
46 #include <netinet/tcp.h>
47 #endif
48 #include <arpa/inet.h>
49 #endif
51 #ifdef ENABLE_THREAD_SAFETY
52 #ifdef WIN32
53 #include "pthread-win32.h"
54 #else
55 #include <pthread.h>
56 #endif
57 #endif
59 #ifdef USE_LDAP
60 #ifdef WIN32
61 #include <winldap.h>
62 #else
63 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
64 #define LDAP_DEPRECATED 1
65 #include <ldap.h>
66 typedef struct timeval LDAP_TIMEVAL;
67 #endif
68 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
69 PQExpBuffer errorMessage);
70 #endif
72 #include "libpq/ip.h"
73 #include "mb/pg_wchar.h"
75 #ifndef FD_CLOEXEC
76 #define FD_CLOEXEC 1
77 #endif
80 #ifndef WIN32
81 #define PGPASSFILE ".pgpass"
82 #else
83 #define PGPASSFILE "pgpass.conf"
84 #endif
86 /* fall back options if they are not specified by arguments or defined
87 by environment variables */
88 #define DefaultHost "localhost"
89 #define DefaultTty ""
90 #define DefaultOption ""
91 #define DefaultAuthtype ""
92 #define DefaultPassword ""
93 #ifdef USE_SSL
94 #define DefaultSSLMode "prefer"
95 #else
96 #define DefaultSSLMode "disable"
97 #endif
99 /* ----------
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).
122 * ----------
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
159 * compatibility.
161 {"tty", "PGTTY", DefaultTty, NULL,
162 "Backend-Debug-TTY", "D", 40},
164 {"options", "PGOPTIONS", DefaultOption, NULL,
165 "Backend-Debug-Options", "D", 40},
167 #ifdef USE_SSL
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},
175 #endif
178 * "sslmode" option is allowed even without client SSL support because the
179 * client can still handle SSL modes "disable" and "allow".
181 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
182 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
184 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
185 /* Kerberos and GSSAPI authentication support specifying the service name */
186 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
187 "Kerberos-service-name", "", 20},
188 #endif
190 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
193 * GSSAPI and SSPI both enabled, give a way to override which is used by
194 * default
196 {"gsslib", "PGGSSLIB", NULL, NULL,
197 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
198 #endif
200 /* Terminating entry --- MUST BE LAST */
201 {NULL, NULL, NULL, NULL,
202 NULL, NULL, 0}
205 static const PQEnvironmentOption EnvironmentOptions[] =
207 /* common user-interface settings */
209 "PGDATESTYLE", "datestyle"
212 "PGTZ", "timezone"
215 "PGCLIENTENCODING", "client_encoding"
217 /* internal performance-related settings */
219 "PGGEQO", "geqo"
222 NULL, NULL
227 static bool connectOptions1(PGconn *conn, const char *conninfo);
228 static bool connectOptions2(PGconn *conn);
229 static int connectDBStart(PGconn *conn);
230 static int connectDBComplete(PGconn *conn);
231 static PGconn *makeEmptyPGconn(void);
232 static void freePGconn(PGconn *conn);
233 static void closePGconn(PGconn *conn);
234 static PQconninfoOption *conninfo_parse(const char *conninfo,
235 PQExpBuffer errorMessage, bool use_defaults);
236 static char *conninfo_getval(PQconninfoOption *connOptions,
237 const char *keyword);
238 static void defaultNoticeReceiver(void *arg, const PGresult *res);
239 static void defaultNoticeProcessor(void *arg, const char *message);
240 static int parseServiceInfo(PQconninfoOption *options,
241 PQExpBuffer errorMessage);
242 static char *pwdfMatchesString(char *buf, char *token);
243 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
244 char *username);
245 static void default_threadlock(int acquire);
248 /* global variable because fe-auth.c needs to access it */
249 pgthreadlock_t pg_g_threadlock = default_threadlock;
253 * Connecting to a Database
255 * There are now four different ways a user of this API can connect to the
256 * database. Two are not recommended for use in new code, because of their
257 * lack of extensibility with respect to the passing of options to the
258 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
259 * to the latter).
261 * If it is desired to connect in a synchronous (blocking) manner, use the
262 * function PQconnectdb.
264 * To connect in an asynchronous (non-blocking) manner, use the functions
265 * PQconnectStart, and PQconnectPoll.
267 * Internally, the static functions connectDBStart, connectDBComplete
268 * are part of the connection procedure.
272 * PQconnectdb
274 * establishes a connection to a postgres backend through the postmaster
275 * using connection information in a string.
277 * The conninfo string is a white-separated list of
279 * option = value
281 * definitions. Value might be a single value containing no whitespaces or
282 * a single quoted string. If a single quote should appear anywhere in
283 * the value, it must be escaped with a backslash like \'
285 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
286 * if a memory allocation failed.
287 * If the status field of the connection returned is CONNECTION_BAD,
288 * then some fields may be null'ed out instead of having valid values.
290 * You should call PQfinish (if conn is not NULL) regardless of whether this
291 * call succeeded.
293 PGconn *
294 PQconnectdb(const char *conninfo)
296 PGconn *conn = PQconnectStart(conninfo);
298 if (conn && conn->status != CONNECTION_BAD)
299 (void) connectDBComplete(conn);
301 return conn;
305 * PQconnectStart
307 * Begins the establishment of a connection to a postgres backend through the
308 * postmaster using connection information in a string.
310 * See comment for PQconnectdb for the definition of the string format.
312 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
313 * you should not attempt to proceed with this connection. If the status
314 * field of the connection returned is CONNECTION_BAD, an error has
315 * occurred. In this case you should call PQfinish on the result, (perhaps
316 * inspecting the error message first). Other fields of the structure may not
317 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
318 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
319 * this is necessary.
321 * See PQconnectPoll for more info.
323 PGconn *
324 PQconnectStart(const char *conninfo)
326 PGconn *conn;
329 * Allocate memory for the conn structure
331 conn = makeEmptyPGconn();
332 if (conn == NULL)
333 return NULL;
336 * Parse the conninfo string
338 if (!connectOptions1(conn, conninfo))
339 return conn;
342 * Compute derived options
344 if (!connectOptions2(conn))
345 return conn;
348 * Connect to the database
350 if (!connectDBStart(conn))
352 /* Just in case we failed to set it in connectDBStart */
353 conn->status = CONNECTION_BAD;
356 return conn;
360 * connectOptions1
362 * Internal subroutine to set up connection parameters given an already-
363 * created PGconn and a conninfo string. Derived settings should be
364 * processed by calling connectOptions2 next. (We split them because
365 * PQsetdbLogin overrides defaults in between.)
367 * Returns true if OK, false if trouble (in which case errorMessage is set
368 * and so is conn->status).
370 static bool
371 connectOptions1(PGconn *conn, const char *conninfo)
373 PQconninfoOption *connOptions;
374 char *tmp;
377 * Parse the conninfo string
379 connOptions = conninfo_parse(conninfo, &conn->errorMessage, true);
380 if (connOptions == NULL)
382 conn->status = CONNECTION_BAD;
383 /* errorMessage is already set */
384 return false;
388 * Move option values into conn structure
390 * Don't put anything cute here --- intelligence should be in
391 * connectOptions2 ...
393 * XXX: probably worth checking strdup() return value here...
395 tmp = conninfo_getval(connOptions, "hostaddr");
396 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
397 tmp = conninfo_getval(connOptions, "host");
398 conn->pghost = tmp ? strdup(tmp) : NULL;
399 tmp = conninfo_getval(connOptions, "port");
400 conn->pgport = tmp ? strdup(tmp) : NULL;
401 tmp = conninfo_getval(connOptions, "tty");
402 conn->pgtty = tmp ? strdup(tmp) : NULL;
403 tmp = conninfo_getval(connOptions, "options");
404 conn->pgoptions = tmp ? strdup(tmp) : NULL;
405 tmp = conninfo_getval(connOptions, "dbname");
406 conn->dbName = tmp ? strdup(tmp) : NULL;
407 tmp = conninfo_getval(connOptions, "user");
408 conn->pguser = tmp ? strdup(tmp) : NULL;
409 tmp = conninfo_getval(connOptions, "password");
410 conn->pgpass = tmp ? strdup(tmp) : NULL;
411 tmp = conninfo_getval(connOptions, "connect_timeout");
412 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
413 tmp = conninfo_getval(connOptions, "sslmode");
414 conn->sslmode = tmp ? strdup(tmp) : NULL;
415 #ifdef USE_SSL
416 tmp = conninfo_getval(connOptions, "requiressl");
417 if (tmp && tmp[0] == '1')
419 /* here warn that the requiressl option is deprecated? */
420 if (conn->sslmode)
421 free(conn->sslmode);
422 conn->sslmode = strdup("require");
424 #endif
425 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
426 tmp = conninfo_getval(connOptions, "krbsrvname");
427 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
428 #endif
429 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
430 tmp = conninfo_getval(connOptions, "gsslib");
431 conn->gsslib = tmp ? strdup(tmp) : NULL;
432 #endif
435 * Free the option info - all is in conn now
437 PQconninfoFree(connOptions);
439 return true;
443 * connectOptions2
445 * Compute derived connection options after absorbing all user-supplied info.
447 * Returns true if OK, false if trouble (in which case errorMessage is set
448 * and so is conn->status).
450 static bool
451 connectOptions2(PGconn *conn)
454 * If database name was not given, default it to equal user name
456 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
457 && conn->pguser != NULL)
459 if (conn->dbName)
460 free(conn->dbName);
461 conn->dbName = strdup(conn->pguser);
465 * Supply default password if none given
467 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
469 if (conn->pgpass)
470 free(conn->pgpass);
471 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
472 conn->dbName, conn->pguser);
473 if (conn->pgpass == NULL)
474 conn->pgpass = strdup(DefaultPassword);
478 * Allow unix socket specification in the host name
480 if (conn->pghost && is_absolute_path(conn->pghost))
482 if (conn->pgunixsocket)
483 free(conn->pgunixsocket);
484 conn->pgunixsocket = conn->pghost;
485 conn->pghost = NULL;
489 * validate sslmode option
491 if (conn->sslmode)
493 if (strcmp(conn->sslmode, "disable") != 0
494 && strcmp(conn->sslmode, "allow") != 0
495 && strcmp(conn->sslmode, "prefer") != 0
496 && strcmp(conn->sslmode, "require") != 0)
498 conn->status = CONNECTION_BAD;
499 printfPQExpBuffer(&conn->errorMessage,
500 libpq_gettext("invalid sslmode value: \"%s\"\n"),
501 conn->sslmode);
502 return false;
505 #ifndef USE_SSL
506 switch (conn->sslmode[0])
508 case 'a': /* "allow" */
509 case 'p': /* "prefer" */
512 * warn user that an SSL connection will never be negotiated
513 * since SSL was not compiled in?
515 break;
517 case 'r': /* "require" */
518 conn->status = CONNECTION_BAD;
519 printfPQExpBuffer(&conn->errorMessage,
520 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
521 conn->sslmode);
522 return false;
524 #endif
526 else
527 conn->sslmode = strdup(DefaultSSLMode);
530 * Only if we get this far is it appropriate to try to connect. (We need a
531 * state flag, rather than just the boolean result of this function, in
532 * case someone tries to PQreset() the PGconn.)
534 conn->options_valid = true;
536 return true;
540 * PQconndefaults
542 * Parse an empty string like PQconnectdb() would do and return the
543 * resulting connection options array, ie, all the default values that are
544 * available from the environment etc. On error (eg out of memory),
545 * NULL is returned.
547 * Using this function, an application may determine all possible options
548 * and their current default values.
550 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
551 * and should be freed when no longer needed via PQconninfoFree(). (In prior
552 * versions, the returned array was static, but that's not thread-safe.)
553 * Pre-7.0 applications that use this function will see a small memory leak
554 * until they are updated to call PQconninfoFree.
556 PQconninfoOption *
557 PQconndefaults(void)
559 PQExpBufferData errorBuf;
560 PQconninfoOption *connOptions;
562 initPQExpBuffer(&errorBuf);
563 if (errorBuf.data == NULL)
564 return NULL; /* out of memory already :-( */
565 connOptions = conninfo_parse("", &errorBuf, true);
566 termPQExpBuffer(&errorBuf);
567 return connOptions;
570 /* ----------------
571 * PQsetdbLogin
573 * establishes a connection to a postgres backend through the postmaster
574 * at the specified host and port.
576 * returns a PGconn* which is needed for all subsequent libpq calls
578 * if the status field of the connection returned is CONNECTION_BAD,
579 * then only the errorMessage is likely to be useful.
580 * ----------------
582 PGconn *
583 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
584 const char *pgtty, const char *dbName, const char *login,
585 const char *pwd)
587 PGconn *conn;
590 * Allocate memory for the conn structure
592 conn = makeEmptyPGconn();
593 if (conn == NULL)
594 return NULL;
597 * If the dbName parameter contains '=', assume it's a conninfo string.
599 if (dbName && strchr(dbName, '='))
601 if (!connectOptions1(conn, dbName))
602 return conn;
604 else
607 * Old-style path: first, parse an empty conninfo string in order to
608 * set up the same defaults that PQconnectdb() would use.
610 if (!connectOptions1(conn, ""))
611 return conn;
613 /* Insert dbName parameter value into struct */
614 if (dbName && dbName[0] != '\0')
616 if (conn->dbName)
617 free(conn->dbName);
618 conn->dbName = strdup(dbName);
623 * Insert remaining parameters into struct, overriding defaults (as well
624 * as any conflicting data from dbName taken as a conninfo).
626 if (pghost && pghost[0] != '\0')
628 if (conn->pghost)
629 free(conn->pghost);
630 conn->pghost = strdup(pghost);
633 if (pgport && pgport[0] != '\0')
635 if (conn->pgport)
636 free(conn->pgport);
637 conn->pgport = strdup(pgport);
640 if (pgoptions && pgoptions[0] != '\0')
642 if (conn->pgoptions)
643 free(conn->pgoptions);
644 conn->pgoptions = strdup(pgoptions);
647 if (pgtty && pgtty[0] != '\0')
649 if (conn->pgtty)
650 free(conn->pgtty);
651 conn->pgtty = strdup(pgtty);
654 if (login && login[0] != '\0')
656 if (conn->pguser)
657 free(conn->pguser);
658 conn->pguser = strdup(login);
661 if (pwd && pwd[0] != '\0')
663 if (conn->pgpass)
664 free(conn->pgpass);
665 conn->pgpass = strdup(pwd);
669 * Compute derived options
671 if (!connectOptions2(conn))
672 return conn;
675 * Connect to the database
677 if (connectDBStart(conn))
678 (void) connectDBComplete(conn);
680 return conn;
684 /* ----------
685 * connectNoDelay -
686 * Sets the TCP_NODELAY socket option.
687 * Returns 1 if successful, 0 if not.
688 * ----------
690 static int
691 connectNoDelay(PGconn *conn)
693 #ifdef TCP_NODELAY
694 int on = 1;
696 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
697 (char *) &on,
698 sizeof(on)) < 0)
700 char sebuf[256];
702 printfPQExpBuffer(&conn->errorMessage,
703 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
704 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
705 return 0;
707 #endif
709 return 1;
713 /* ----------
714 * connectFailureMessage -
715 * create a friendly error message on connection failure.
716 * ----------
718 static void
719 connectFailureMessage(PGconn *conn, int errorno)
721 char sebuf[256];
723 #ifdef HAVE_UNIX_SOCKETS
724 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
726 char service[NI_MAXHOST];
728 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
729 NULL, 0,
730 service, sizeof(service),
731 NI_NUMERICSERV);
732 printfPQExpBuffer(&conn->errorMessage,
733 libpq_gettext("could not connect to server: %s\n"
734 "\tIs the server running locally and accepting\n"
735 "\tconnections on Unix domain socket \"%s\"?\n"),
736 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
737 service);
739 else
740 #endif /* HAVE_UNIX_SOCKETS */
742 printfPQExpBuffer(&conn->errorMessage,
743 libpq_gettext("could not connect to server: %s\n"
744 "\tIs the server running on host \"%s\" and accepting\n"
745 "\tTCP/IP connections on port %s?\n"),
746 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
747 conn->pghostaddr
748 ? conn->pghostaddr
749 : (conn->pghost
750 ? conn->pghost
751 : "???"),
752 conn->pgport);
757 /* ----------
758 * connectDBStart -
759 * Begin the process of making a connection to the backend.
761 * Returns 1 if successful, 0 if not.
762 * ----------
764 static int
765 connectDBStart(PGconn *conn)
767 int portnum;
768 char portstr[128];
769 struct addrinfo *addrs = NULL;
770 struct addrinfo hint;
771 const char *node;
772 int ret;
774 if (!conn)
775 return 0;
777 if (!conn->options_valid)
778 goto connect_errReturn;
780 /* Ensure our buffers are empty */
781 conn->inStart = conn->inCursor = conn->inEnd = 0;
782 conn->outCount = 0;
785 * Determine the parameters to pass to pg_getaddrinfo_all.
788 /* Initialize hint structure */
789 MemSet(&hint, 0, sizeof(hint));
790 hint.ai_socktype = SOCK_STREAM;
791 hint.ai_family = AF_UNSPEC;
793 /* Set up port number as a string */
794 if (conn->pgport != NULL && conn->pgport[0] != '\0')
795 portnum = atoi(conn->pgport);
796 else
797 portnum = DEF_PGPORT;
798 snprintf(portstr, sizeof(portstr), "%d", portnum);
800 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
802 /* Using pghostaddr avoids a hostname lookup */
803 node = conn->pghostaddr;
804 hint.ai_family = AF_UNSPEC;
805 hint.ai_flags = AI_NUMERICHOST;
807 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
809 /* Using pghost, so we have to look-up the hostname */
810 node = conn->pghost;
811 hint.ai_family = AF_UNSPEC;
813 else
815 #ifdef HAVE_UNIX_SOCKETS
816 /* pghostaddr and pghost are NULL, so use Unix domain socket */
817 node = NULL;
818 hint.ai_family = AF_UNIX;
819 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
820 #else
821 /* Without Unix sockets, default to localhost instead */
822 node = "localhost";
823 hint.ai_family = AF_UNSPEC;
824 #endif /* HAVE_UNIX_SOCKETS */
827 /* Use pg_getaddrinfo_all() to resolve the address */
828 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
829 if (ret || !addrs)
831 if (node)
832 printfPQExpBuffer(&conn->errorMessage,
833 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
834 node, gai_strerror(ret));
835 else
836 printfPQExpBuffer(&conn->errorMessage,
837 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
838 portstr, gai_strerror(ret));
839 if (addrs)
840 pg_freeaddrinfo_all(hint.ai_family, addrs);
841 goto connect_errReturn;
844 #ifdef USE_SSL
845 /* setup values based on SSL mode */
846 if (conn->sslmode[0] == 'd') /* "disable" */
847 conn->allow_ssl_try = false;
848 else if (conn->sslmode[0] == 'a') /* "allow" */
849 conn->wait_ssl_try = true;
850 #endif
853 * Set up to try to connect, with protocol 3.0 as the first attempt.
855 conn->addrlist = addrs;
856 conn->addr_cur = addrs;
857 conn->addrlist_family = hint.ai_family;
858 conn->pversion = PG_PROTOCOL(3, 0);
859 conn->status = CONNECTION_NEEDED;
862 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
863 * so that it can easily be re-executed if needed again during the
864 * asynchronous startup process. However, we must run it once here,
865 * because callers expect a success return from this routine to mean that
866 * we are in PGRES_POLLING_WRITING connection state.
868 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
869 return 1;
871 connect_errReturn:
872 if (conn->sock >= 0)
874 pqsecure_close(conn);
875 closesocket(conn->sock);
876 conn->sock = -1;
878 conn->status = CONNECTION_BAD;
879 return 0;
884 * connectDBComplete
886 * Block and complete a connection.
888 * Returns 1 on success, 0 on failure.
890 static int
891 connectDBComplete(PGconn *conn)
893 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
894 time_t finish_time = ((time_t) -1);
896 if (conn == NULL || conn->status == CONNECTION_BAD)
897 return 0;
900 * Set up a time limit, if connect_timeout isn't zero.
902 if (conn->connect_timeout != NULL)
904 int timeout = atoi(conn->connect_timeout);
906 if (timeout > 0)
909 * Rounding could cause connection to fail; need at least 2 secs
911 if (timeout < 2)
912 timeout = 2;
913 /* calculate the finish time based on start + timeout */
914 finish_time = time(NULL) + timeout;
918 for (;;)
921 * Wait, if necessary. Note that the initial state (just after
922 * PQconnectStart) is to wait for the socket to select for writing.
924 switch (flag)
926 case PGRES_POLLING_OK:
927 return 1; /* success! */
929 case PGRES_POLLING_READING:
930 if (pqWaitTimed(1, 0, conn, finish_time))
932 conn->status = CONNECTION_BAD;
933 return 0;
935 break;
937 case PGRES_POLLING_WRITING:
938 if (pqWaitTimed(0, 1, conn, finish_time))
940 conn->status = CONNECTION_BAD;
941 return 0;
943 break;
945 default:
946 /* Just in case we failed to set it in PQconnectPoll */
947 conn->status = CONNECTION_BAD;
948 return 0;
952 * Now try to advance the state machine.
954 flag = PQconnectPoll(conn);
958 /* ----------------
959 * PQconnectPoll
961 * Poll an asynchronous connection.
963 * Returns a PostgresPollingStatusType.
964 * Before calling this function, use select(2) to determine when data
965 * has arrived..
967 * You must call PQfinish whether or not this fails.
969 * This function and PQconnectStart are intended to allow connections to be
970 * made without blocking the execution of your program on remote I/O. However,
971 * there are a number of caveats:
973 * o If you call PQtrace, ensure that the stream object into which you trace
974 * will not block.
975 * o If you do not supply an IP address for the remote host (i.e. you
976 * supply a host name instead) then PQconnectStart will block on
977 * gethostbyname. You will be fine if using Unix sockets (i.e. by
978 * supplying neither a host name nor a host address).
979 * o If your backend wants to use Kerberos authentication then you must
980 * supply both a host name and a host address, otherwise this function
981 * may block on gethostname.
983 * ----------------
985 PostgresPollingStatusType
986 PQconnectPoll(PGconn *conn)
988 PGresult *res;
989 char sebuf[256];
991 if (conn == NULL)
992 return PGRES_POLLING_FAILED;
994 /* Get the new data */
995 switch (conn->status)
998 * We really shouldn't have been polled in these two cases, but we
999 * can handle it.
1001 case CONNECTION_BAD:
1002 return PGRES_POLLING_FAILED;
1003 case CONNECTION_OK:
1004 return PGRES_POLLING_OK;
1006 /* These are reading states */
1007 case CONNECTION_AWAITING_RESPONSE:
1008 case CONNECTION_AUTH_OK:
1010 /* Load waiting data */
1011 int n = pqReadData(conn);
1013 if (n < 0)
1014 goto error_return;
1015 if (n == 0)
1016 return PGRES_POLLING_READING;
1018 break;
1021 /* These are writing states, so we just proceed. */
1022 case CONNECTION_STARTED:
1023 case CONNECTION_MADE:
1024 break;
1026 /* We allow pqSetenvPoll to decide whether to proceed. */
1027 case CONNECTION_SETENV:
1028 break;
1030 /* Special cases: proceed without waiting. */
1031 case CONNECTION_SSL_STARTUP:
1032 case CONNECTION_NEEDED:
1033 break;
1035 default:
1036 printfPQExpBuffer(&conn->errorMessage,
1037 libpq_gettext(
1038 "invalid connection state, "
1039 "probably indicative of memory corruption\n"
1041 goto error_return;
1045 keep_going: /* We will come back to here until there is
1046 * nothing left to do. */
1047 switch (conn->status)
1049 case CONNECTION_NEEDED:
1052 * Try to initiate a connection to one of the addresses
1053 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1054 * next one to try. We fail when we run out of addresses
1055 * (reporting the error returned for the *last* alternative,
1056 * which may not be what users expect :-().
1058 while (conn->addr_cur != NULL)
1060 struct addrinfo *addr_cur = conn->addr_cur;
1062 /* Remember current address for possible error msg */
1063 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1064 addr_cur->ai_addrlen);
1065 conn->raddr.salen = addr_cur->ai_addrlen;
1067 /* Open a socket */
1068 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1069 if (conn->sock < 0)
1072 * ignore socket() failure if we have more addresses
1073 * to try
1075 if (addr_cur->ai_next != NULL)
1077 conn->addr_cur = addr_cur->ai_next;
1078 continue;
1080 printfPQExpBuffer(&conn->errorMessage,
1081 libpq_gettext("could not create socket: %s\n"),
1082 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1083 break;
1087 * Select socket options: no delay of outgoing data for
1088 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1089 * of this fails.
1091 if (!IS_AF_UNIX(addr_cur->ai_family))
1093 if (!connectNoDelay(conn))
1095 closesocket(conn->sock);
1096 conn->sock = -1;
1097 conn->addr_cur = addr_cur->ai_next;
1098 continue;
1101 if (!pg_set_noblock(conn->sock))
1103 printfPQExpBuffer(&conn->errorMessage,
1104 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1105 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1106 closesocket(conn->sock);
1107 conn->sock = -1;
1108 conn->addr_cur = addr_cur->ai_next;
1109 continue;
1112 #ifdef F_SETFD
1113 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1115 printfPQExpBuffer(&conn->errorMessage,
1116 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1117 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1118 closesocket(conn->sock);
1119 conn->sock = -1;
1120 conn->addr_cur = addr_cur->ai_next;
1121 continue;
1123 #endif /* F_SETFD */
1126 * Start/make connection. This should not block, since we
1127 * are in nonblock mode. If it does, well, too bad.
1129 if (connect(conn->sock, addr_cur->ai_addr,
1130 addr_cur->ai_addrlen) < 0)
1132 if (SOCK_ERRNO == EINPROGRESS ||
1133 SOCK_ERRNO == EWOULDBLOCK ||
1134 SOCK_ERRNO == EINTR ||
1135 SOCK_ERRNO == 0)
1138 * This is fine - we're in non-blocking mode, and
1139 * the connection is in progress. Tell caller to
1140 * wait for write-ready on socket.
1142 conn->status = CONNECTION_STARTED;
1143 return PGRES_POLLING_WRITING;
1145 /* otherwise, trouble */
1147 else
1150 * Hm, we're connected already --- seems the "nonblock
1151 * connection" wasn't. Advance the state machine and
1152 * go do the next stuff.
1154 conn->status = CONNECTION_STARTED;
1155 goto keep_going;
1159 * This connection failed --- set up error report, then
1160 * close socket (do it this way in case close() affects
1161 * the value of errno...). We will ignore the connect()
1162 * failure and keep going if there are more addresses.
1164 connectFailureMessage(conn, SOCK_ERRNO);
1165 if (conn->sock >= 0)
1167 closesocket(conn->sock);
1168 conn->sock = -1;
1172 * Try the next address, if any.
1174 conn->addr_cur = addr_cur->ai_next;
1175 } /* loop over addresses */
1178 * Ooops, no more addresses. An appropriate error message is
1179 * already set up, so just set the right status.
1181 goto error_return;
1184 case CONNECTION_STARTED:
1186 int optval;
1187 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1190 * Write ready, since we've made it here, so the connection
1191 * has been made ... or has failed.
1195 * Now check (using getsockopt) that there is not an error
1196 * state waiting for us on the socket.
1199 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1200 (char *) &optval, &optlen) == -1)
1202 printfPQExpBuffer(&conn->errorMessage,
1203 libpq_gettext("could not get socket error status: %s\n"),
1204 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1205 goto error_return;
1207 else if (optval != 0)
1210 * When using a nonblocking connect, we will typically see
1211 * connect failures at this point, so provide a friendly
1212 * error message.
1214 connectFailureMessage(conn, optval);
1217 * If more addresses remain, keep trying, just as in the
1218 * case where connect() returned failure immediately.
1220 if (conn->addr_cur->ai_next != NULL)
1222 if (conn->sock >= 0)
1224 closesocket(conn->sock);
1225 conn->sock = -1;
1227 conn->addr_cur = conn->addr_cur->ai_next;
1228 conn->status = CONNECTION_NEEDED;
1229 goto keep_going;
1231 goto error_return;
1234 /* Fill in the client address */
1235 conn->laddr.salen = sizeof(conn->laddr.addr);
1236 if (getsockname(conn->sock,
1237 (struct sockaddr *) & conn->laddr.addr,
1238 &conn->laddr.salen) < 0)
1240 printfPQExpBuffer(&conn->errorMessage,
1241 libpq_gettext("could not get client address from socket: %s\n"),
1242 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1243 goto error_return;
1247 * Make sure we can write before advancing to next step.
1249 conn->status = CONNECTION_MADE;
1250 return PGRES_POLLING_WRITING;
1253 case CONNECTION_MADE:
1255 char *startpacket;
1256 int packetlen;
1258 #ifdef USE_SSL
1261 * If SSL is enabled and we haven't already got it running,
1262 * request it instead of sending the startup message.
1264 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1266 /* Don't bother requesting SSL over a Unix socket */
1267 conn->allow_ssl_try = false;
1269 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1270 conn->ssl == NULL)
1272 ProtocolVersion pv;
1275 * Send the SSL request packet.
1277 * Theoretically, this could block, but it really
1278 * shouldn't since we only got here if the socket is
1279 * write-ready.
1281 pv = htonl(NEGOTIATE_SSL_CODE);
1282 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1284 printfPQExpBuffer(&conn->errorMessage,
1285 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1286 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1287 goto error_return;
1289 /* Ok, wait for response */
1290 conn->status = CONNECTION_SSL_STARTUP;
1291 return PGRES_POLLING_READING;
1293 #endif /* USE_SSL */
1296 * Build the startup packet.
1298 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1299 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1300 EnvironmentOptions);
1301 else
1302 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1303 EnvironmentOptions);
1304 if (!startpacket)
1306 printfPQExpBuffer(&conn->errorMessage,
1307 libpq_gettext("out of memory\n"));
1308 goto error_return;
1312 * Send the startup packet.
1314 * Theoretically, this could block, but it really shouldn't
1315 * since we only got here if the socket is write-ready.
1317 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1319 printfPQExpBuffer(&conn->errorMessage,
1320 libpq_gettext("could not send startup packet: %s\n"),
1321 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1322 free(startpacket);
1323 goto error_return;
1326 free(startpacket);
1328 conn->status = CONNECTION_AWAITING_RESPONSE;
1329 return PGRES_POLLING_READING;
1333 * Handle SSL negotiation: wait for postmaster messages and
1334 * respond as necessary.
1336 case CONNECTION_SSL_STARTUP:
1338 #ifdef USE_SSL
1339 PostgresPollingStatusType pollres;
1342 * On first time through, get the postmaster's response to our
1343 * SSL negotiation packet.
1345 if (conn->ssl == NULL)
1348 * We use pqReadData here since it has the logic to
1349 * distinguish no-data-yet from connection closure. Since
1350 * conn->ssl isn't set, a plain recv() will occur.
1352 char SSLok;
1353 int rdresult;
1355 rdresult = pqReadData(conn);
1356 if (rdresult < 0)
1358 /* errorMessage is already filled in */
1359 goto error_return;
1361 if (rdresult == 0)
1363 /* caller failed to wait for data */
1364 return PGRES_POLLING_READING;
1366 if (pqGetc(&SSLok, conn) < 0)
1368 /* should not happen really */
1369 return PGRES_POLLING_READING;
1371 /* mark byte consumed */
1372 conn->inStart = conn->inCursor;
1373 if (SSLok == 'S')
1375 /* Do one-time setup; this creates conn->ssl */
1376 if (pqsecure_initialize(conn) == -1)
1377 goto error_return;
1379 else if (SSLok == 'N')
1381 if (conn->sslmode[0] == 'r') /* "require" */
1383 /* Require SSL, but server does not want it */
1384 printfPQExpBuffer(&conn->errorMessage,
1385 libpq_gettext("server does not support SSL, but SSL was required\n"));
1386 goto error_return;
1388 /* Otherwise, proceed with normal startup */
1389 conn->allow_ssl_try = false;
1390 conn->status = CONNECTION_MADE;
1391 return PGRES_POLLING_WRITING;
1393 else if (SSLok == 'E')
1395 /* Received error - probably protocol mismatch */
1396 if (conn->Pfdebug)
1397 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1398 if (conn->sslmode[0] == 'r') /* "require" */
1400 /* Require SSL, but server is too old */
1401 printfPQExpBuffer(&conn->errorMessage,
1402 libpq_gettext("server does not support SSL, but SSL was required\n"));
1403 goto error_return;
1405 /* Otherwise, try again without SSL */
1406 conn->allow_ssl_try = false;
1407 /* Assume it ain't gonna handle protocol 3, either */
1408 conn->pversion = PG_PROTOCOL(2, 0);
1409 /* Must drop the old connection */
1410 closesocket(conn->sock);
1411 conn->sock = -1;
1412 conn->status = CONNECTION_NEEDED;
1413 goto keep_going;
1415 else
1417 printfPQExpBuffer(&conn->errorMessage,
1418 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1419 SSLok);
1420 goto error_return;
1425 * Begin or continue the SSL negotiation process.
1427 pollres = pqsecure_open_client(conn);
1428 if (pollres == PGRES_POLLING_OK)
1430 /* SSL handshake done, ready to send startup packet */
1431 conn->status = CONNECTION_MADE;
1432 return PGRES_POLLING_WRITING;
1434 if (pollres == PGRES_POLLING_FAILED)
1437 * Failed ... if sslmode is "prefer" then do a non-SSL
1438 * retry
1440 if (conn->sslmode[0] == 'p' /* "prefer" */
1441 && conn->allow_ssl_try /* redundant? */
1442 && !conn->wait_ssl_try) /* redundant? */
1444 /* only retry once */
1445 conn->allow_ssl_try = false;
1446 /* Must drop the old connection */
1447 closesocket(conn->sock);
1448 conn->sock = -1;
1449 conn->status = CONNECTION_NEEDED;
1450 goto keep_going;
1453 return pollres;
1454 #else /* !USE_SSL */
1455 /* can't get here */
1456 goto error_return;
1457 #endif /* USE_SSL */
1461 * Handle authentication exchange: wait for postmaster messages
1462 * and respond as necessary.
1464 case CONNECTION_AWAITING_RESPONSE:
1466 char beresp;
1467 int msgLength;
1468 int avail;
1469 AuthRequest areq;
1472 * Scan the message from current point (note that if we find
1473 * the message is incomplete, we will return without advancing
1474 * inStart, and resume here next time).
1476 conn->inCursor = conn->inStart;
1478 /* Read type byte */
1479 if (pqGetc(&beresp, conn))
1481 /* We'll come back when there is more data */
1482 return PGRES_POLLING_READING;
1486 * Validate message type: we expect only an authentication
1487 * request or an error here. Anything else probably means
1488 * it's not Postgres on the other end at all.
1490 if (!(beresp == 'R' || beresp == 'E'))
1492 printfPQExpBuffer(&conn->errorMessage,
1493 libpq_gettext(
1494 "expected authentication request from "
1495 "server, but received %c\n"),
1496 beresp);
1497 goto error_return;
1500 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1502 /* Read message length word */
1503 if (pqGetInt(&msgLength, 4, conn))
1505 /* We'll come back when there is more data */
1506 return PGRES_POLLING_READING;
1509 else
1511 /* Set phony message length to disable checks below */
1512 msgLength = 8;
1516 * Try to validate message length before using it.
1517 * Authentication requests can't be very large, although GSS
1518 * auth requests may not be that small. Errors can be a
1519 * little larger, but not huge. If we see a large apparent
1520 * length in an error, it means we're really talking to a
1521 * pre-3.0-protocol server; cope.
1523 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1525 printfPQExpBuffer(&conn->errorMessage,
1526 libpq_gettext(
1527 "expected authentication request from "
1528 "server, but received %c\n"),
1529 beresp);
1530 goto error_return;
1533 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1535 /* Handle error from a pre-3.0 server */
1536 conn->inCursor = conn->inStart + 1; /* reread data */
1537 if (pqGets(&conn->errorMessage, conn))
1539 /* We'll come back when there is more data */
1540 return PGRES_POLLING_READING;
1542 /* OK, we read the message; mark data consumed */
1543 conn->inStart = conn->inCursor;
1546 * The postmaster typically won't end its message with a
1547 * newline, so add one to conform to libpq conventions.
1549 appendPQExpBufferChar(&conn->errorMessage, '\n');
1552 * If we tried to open the connection in 3.0 protocol,
1553 * fall back to 2.0 protocol.
1555 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1557 conn->pversion = PG_PROTOCOL(2, 0);
1558 /* Must drop the old connection */
1559 pqsecure_close(conn);
1560 closesocket(conn->sock);
1561 conn->sock = -1;
1562 conn->status = CONNECTION_NEEDED;
1563 goto keep_going;
1566 goto error_return;
1570 * Can't process if message body isn't all here yet.
1572 * (In protocol 2.0 case, we are assuming messages carry at
1573 * least 4 bytes of data.)
1575 msgLength -= 4;
1576 avail = conn->inEnd - conn->inCursor;
1577 if (avail < msgLength)
1580 * Before returning, try to enlarge the input buffer if
1581 * needed to hold the whole message; see notes in
1582 * pqParseInput3.
1584 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1585 conn))
1586 goto error_return;
1587 /* We'll come back when there is more data */
1588 return PGRES_POLLING_READING;
1591 /* Handle errors. */
1592 if (beresp == 'E')
1594 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1596 if (pqGetErrorNotice3(conn, true))
1598 /* We'll come back when there is more data */
1599 return PGRES_POLLING_READING;
1602 else
1604 if (pqGets(&conn->errorMessage, conn))
1606 /* We'll come back when there is more data */
1607 return PGRES_POLLING_READING;
1610 /* OK, we read the message; mark data consumed */
1611 conn->inStart = conn->inCursor;
1613 #ifdef USE_SSL
1616 * if sslmode is "allow" and we haven't tried an SSL
1617 * connection already, then retry with an SSL connection
1619 if (conn->sslmode[0] == 'a' /* "allow" */
1620 && conn->ssl == NULL
1621 && conn->allow_ssl_try
1622 && conn->wait_ssl_try)
1624 /* only retry once */
1625 conn->wait_ssl_try = false;
1626 /* Must drop the old connection */
1627 closesocket(conn->sock);
1628 conn->sock = -1;
1629 conn->status = CONNECTION_NEEDED;
1630 goto keep_going;
1634 * if sslmode is "prefer" and we're in an SSL connection,
1635 * then do a non-SSL retry
1637 if (conn->sslmode[0] == 'p' /* "prefer" */
1638 && conn->ssl
1639 && conn->allow_ssl_try /* redundant? */
1640 && !conn->wait_ssl_try) /* redundant? */
1642 /* only retry once */
1643 conn->allow_ssl_try = false;
1644 /* Must drop the old connection */
1645 pqsecure_close(conn);
1646 closesocket(conn->sock);
1647 conn->sock = -1;
1648 conn->status = CONNECTION_NEEDED;
1649 goto keep_going;
1651 #endif
1653 goto error_return;
1656 /* It is an authentication request. */
1657 /* Get the type of request. */
1658 if (pqGetInt((int *) &areq, 4, conn))
1660 /* We'll come back when there are more data */
1661 return PGRES_POLLING_READING;
1664 /* Get the password salt if there is one. */
1665 if (areq == AUTH_REQ_MD5)
1667 if (pqGetnchar(conn->md5Salt,
1668 sizeof(conn->md5Salt), conn))
1670 /* We'll come back when there are more data */
1671 return PGRES_POLLING_READING;
1674 if (areq == AUTH_REQ_CRYPT)
1676 if (pqGetnchar(conn->cryptSalt,
1677 sizeof(conn->cryptSalt), conn))
1679 /* We'll come back when there are more data */
1680 return PGRES_POLLING_READING;
1683 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1686 * Continue GSSAPI/SSPI authentication
1688 if (areq == AUTH_REQ_GSS_CONT)
1690 int llen = msgLength - 4;
1693 * We can be called repeatedly for the same buffer. Avoid
1694 * re-allocating the buffer in this case - just re-use the
1695 * old buffer.
1697 if (llen != conn->ginbuf.length)
1699 if (conn->ginbuf.value)
1700 free(conn->ginbuf.value);
1702 conn->ginbuf.length = llen;
1703 conn->ginbuf.value = malloc(llen);
1704 if (!conn->ginbuf.value)
1706 printfPQExpBuffer(&conn->errorMessage,
1707 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1708 llen);
1709 goto error_return;
1713 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1715 /* We'll come back when there is more data. */
1716 return PGRES_POLLING_READING;
1719 #endif
1722 * OK, we successfully read the message; mark data consumed
1724 conn->inStart = conn->inCursor;
1726 /* Respond to the request if necessary. */
1729 * Note that conn->pghost must be non-NULL if we are going to
1730 * avoid the Kerberos code doing a hostname look-up.
1733 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1735 conn->errorMessage.len = strlen(conn->errorMessage.data);
1736 goto error_return;
1738 conn->errorMessage.len = strlen(conn->errorMessage.data);
1741 * Just make sure that any data sent by pg_fe_sendauth is
1742 * flushed out. Although this theoretically could block, it
1743 * really shouldn't since we don't send large auth responses.
1745 if (pqFlush(conn))
1746 goto error_return;
1748 if (areq == AUTH_REQ_OK)
1750 /* We are done with authentication exchange */
1751 conn->status = CONNECTION_AUTH_OK;
1754 * Set asyncStatus so that PQsetResult will think that
1755 * what comes back next is the result of a query. See
1756 * below.
1758 conn->asyncStatus = PGASYNC_BUSY;
1761 /* Look to see if we have more data yet. */
1762 goto keep_going;
1765 case CONNECTION_AUTH_OK:
1768 * Now we expect to hear from the backend. A ReadyForQuery
1769 * message indicates that startup is successful, but we might
1770 * also get an Error message indicating failure. (Notice
1771 * messages indicating nonfatal warnings are also allowed by
1772 * the protocol, as are ParameterStatus and BackendKeyData
1773 * messages.) Easiest way to handle this is to let
1774 * PQgetResult() read the messages. We just have to fake it
1775 * out about the state of the connection, by setting
1776 * asyncStatus = PGASYNC_BUSY (done above).
1779 if (PQisBusy(conn))
1780 return PGRES_POLLING_READING;
1782 res = PQgetResult(conn);
1785 * NULL return indicating we have gone to IDLE state is
1786 * expected
1788 if (res)
1790 if (res->resultStatus != PGRES_FATAL_ERROR)
1791 printfPQExpBuffer(&conn->errorMessage,
1792 libpq_gettext("unexpected message from server during startup\n"));
1795 * if the resultStatus is FATAL, then conn->errorMessage
1796 * already has a copy of the error; needn't copy it back.
1797 * But add a newline if it's not there already, since
1798 * postmaster error messages may not have one.
1800 if (conn->errorMessage.len <= 0 ||
1801 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1802 appendPQExpBufferChar(&conn->errorMessage, '\n');
1803 PQclear(res);
1804 goto error_return;
1807 /* We can release the address list now. */
1808 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1809 conn->addrlist = NULL;
1810 conn->addr_cur = NULL;
1812 /* Fire up post-connection housekeeping if needed */
1813 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1815 conn->status = CONNECTION_SETENV;
1816 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1817 conn->next_eo = EnvironmentOptions;
1818 return PGRES_POLLING_WRITING;
1821 /* Otherwise, we are open for business! */
1822 conn->status = CONNECTION_OK;
1823 return PGRES_POLLING_OK;
1826 case CONNECTION_SETENV:
1829 * Do post-connection housekeeping (only needed in protocol 2.0).
1831 * We pretend that the connection is OK for the duration of these
1832 * queries.
1834 conn->status = CONNECTION_OK;
1836 switch (pqSetenvPoll(conn))
1838 case PGRES_POLLING_OK: /* Success */
1839 break;
1841 case PGRES_POLLING_READING: /* Still going */
1842 conn->status = CONNECTION_SETENV;
1843 return PGRES_POLLING_READING;
1845 case PGRES_POLLING_WRITING: /* Still going */
1846 conn->status = CONNECTION_SETENV;
1847 return PGRES_POLLING_WRITING;
1849 default:
1850 goto error_return;
1853 /* We are open for business! */
1854 conn->status = CONNECTION_OK;
1855 return PGRES_POLLING_OK;
1857 default:
1858 printfPQExpBuffer(&conn->errorMessage,
1859 libpq_gettext(
1860 "invalid connection state %c, "
1861 "probably indicative of memory corruption\n"
1863 conn->status);
1864 goto error_return;
1867 /* Unreachable */
1869 error_return:
1872 * We used to close the socket at this point, but that makes it awkward
1873 * for those above us if they wish to remove this socket from their own
1874 * records (an fd_set for example). We'll just have this socket closed
1875 * when PQfinish is called (which is compulsory even after an error, since
1876 * the connection structure must be freed).
1878 conn->status = CONNECTION_BAD;
1879 return PGRES_POLLING_FAILED;
1884 * makeEmptyPGconn
1885 * - create a PGconn data structure with (as yet) no interesting data
1887 static PGconn *
1888 makeEmptyPGconn(void)
1890 PGconn *conn;
1892 #ifdef WIN32
1895 * Make sure socket support is up and running.
1897 WSADATA wsaData;
1899 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1900 return NULL;
1901 WSASetLastError(0);
1902 #endif
1904 conn = (PGconn *) malloc(sizeof(PGconn));
1905 if (conn == NULL)
1907 #ifdef WIN32
1908 WSACleanup();
1909 #endif
1910 return conn;
1913 /* Zero all pointers and booleans */
1914 MemSet(conn, 0, sizeof(PGconn));
1916 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1917 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1918 conn->status = CONNECTION_BAD;
1919 conn->asyncStatus = PGASYNC_IDLE;
1920 conn->xactStatus = PQTRANS_IDLE;
1921 conn->options_valid = false;
1922 conn->nonblocking = false;
1923 conn->setenv_state = SETENV_STATE_IDLE;
1924 conn->client_encoding = PG_SQL_ASCII;
1925 conn->std_strings = false; /* unless server says differently */
1926 conn->verbosity = PQERRORS_DEFAULT;
1927 conn->sock = -1;
1928 conn->password_needed = false;
1929 #ifdef USE_SSL
1930 conn->allow_ssl_try = true;
1931 conn->wait_ssl_try = false;
1932 #endif
1935 * We try to send at least 8K at a time, which is the usual size of pipe
1936 * buffers on Unix systems. That way, when we are sending a large amount
1937 * of data, we avoid incurring extra kernel context swaps for partial
1938 * bufferloads. The output buffer is initially made 16K in size, and we
1939 * try to dump it after accumulating 8K.
1941 * With the same goal of minimizing context swaps, the input buffer will
1942 * be enlarged anytime it has less than 8K free, so we initially allocate
1943 * twice that.
1945 conn->inBufSize = 16 * 1024;
1946 conn->inBuffer = (char *) malloc(conn->inBufSize);
1947 conn->outBufSize = 16 * 1024;
1948 conn->outBuffer = (char *) malloc(conn->outBufSize);
1949 initPQExpBuffer(&conn->errorMessage);
1950 initPQExpBuffer(&conn->workBuffer);
1952 if (conn->inBuffer == NULL ||
1953 conn->outBuffer == NULL ||
1954 conn->errorMessage.data == NULL ||
1955 conn->workBuffer.data == NULL)
1957 /* out of memory already :-( */
1958 freePGconn(conn);
1959 conn = NULL;
1962 return conn;
1966 * freePGconn
1967 * - free an idle (closed) PGconn data structure
1969 * NOTE: this should not overlap any functionality with closePGconn().
1970 * Clearing/resetting of transient state belongs there; what we do here is
1971 * release data that is to be held for the life of the PGconn structure.
1972 * If a value ought to be cleared/freed during PQreset(), do it there not here.
1974 static void
1975 freePGconn(PGconn *conn)
1977 int i;
1979 /* let any event procs clean up their state data */
1980 for (i = 0; i < conn->nEvents; i++)
1982 PGEventConnDestroy evt;
1984 evt.conn = conn;
1985 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
1986 conn->events[i].passThrough);
1987 free(conn->events[i].name);
1990 if (conn->events)
1991 free(conn->events);
1992 if (conn->pghost)
1993 free(conn->pghost);
1994 if (conn->pghostaddr)
1995 free(conn->pghostaddr);
1996 if (conn->pgport)
1997 free(conn->pgport);
1998 if (conn->pgunixsocket)
1999 free(conn->pgunixsocket);
2000 if (conn->pgtty)
2001 free(conn->pgtty);
2002 if (conn->connect_timeout)
2003 free(conn->connect_timeout);
2004 if (conn->pgoptions)
2005 free(conn->pgoptions);
2006 if (conn->dbName)
2007 free(conn->dbName);
2008 if (conn->pguser)
2009 free(conn->pguser);
2010 if (conn->pgpass)
2011 free(conn->pgpass);
2012 if (conn->sslmode)
2013 free(conn->sslmode);
2014 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2015 if (conn->krbsrvname)
2016 free(conn->krbsrvname);
2017 #endif
2018 /* Note that conn->Pfdebug is not ours to close or free */
2019 if (conn->last_query)
2020 free(conn->last_query);
2021 if (conn->inBuffer)
2022 free(conn->inBuffer);
2023 if (conn->outBuffer)
2024 free(conn->outBuffer);
2025 termPQExpBuffer(&conn->errorMessage);
2026 termPQExpBuffer(&conn->workBuffer);
2028 free(conn);
2030 #ifdef WIN32
2031 WSACleanup();
2032 #endif
2036 * closePGconn
2037 * - properly close a connection to the backend
2039 * This should reset or release all transient state, but NOT the connection
2040 * parameters. On exit, the PGconn should be in condition to start a fresh
2041 * connection with the same parameters (see PQreset()).
2043 static void
2044 closePGconn(PGconn *conn)
2046 PGnotify *notify;
2047 pgParameterStatus *pstatus;
2050 * Note that the protocol doesn't allow us to send Terminate messages
2051 * during the startup phase.
2053 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2056 * Try to send "close connection" message to backend. Ignore any
2057 * error.
2059 pqPutMsgStart('X', false, conn);
2060 pqPutMsgEnd(conn);
2061 pqFlush(conn);
2065 * Must reset the blocking status so a possible reconnect will work.
2067 * Don't call PQsetnonblocking() because it will fail if it's unable to
2068 * flush the connection.
2070 conn->nonblocking = FALSE;
2073 * Close the connection, reset all transient state, flush I/O buffers.
2075 if (conn->sock >= 0)
2077 pqsecure_close(conn);
2078 closesocket(conn->sock);
2080 conn->sock = -1;
2081 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2082 * absent */
2083 conn->asyncStatus = PGASYNC_IDLE;
2084 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2085 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2086 conn->addrlist = NULL;
2087 conn->addr_cur = NULL;
2088 notify = conn->notifyHead;
2089 while (notify != NULL)
2091 PGnotify *prev = notify;
2093 notify = notify->next;
2094 free(prev);
2096 conn->notifyHead = conn->notifyTail = NULL;
2097 pstatus = conn->pstatus;
2098 while (pstatus != NULL)
2100 pgParameterStatus *prev = pstatus;
2102 pstatus = pstatus->next;
2103 free(prev);
2105 conn->pstatus = NULL;
2106 if (conn->lobjfuncs)
2107 free(conn->lobjfuncs);
2108 conn->lobjfuncs = NULL;
2109 conn->inStart = conn->inCursor = conn->inEnd = 0;
2110 conn->outCount = 0;
2111 #ifdef ENABLE_GSS
2113 OM_uint32 min_s;
2115 if (conn->gctx)
2116 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2117 if (conn->gtarg_nam)
2118 gss_release_name(&min_s, &conn->gtarg_nam);
2119 if (conn->ginbuf.length)
2120 gss_release_buffer(&min_s, &conn->ginbuf);
2121 if (conn->goutbuf.length)
2122 gss_release_buffer(&min_s, &conn->goutbuf);
2124 #endif
2125 #ifdef ENABLE_SSPI
2126 if (conn->ginbuf.length)
2127 free(conn->ginbuf.value);
2128 conn->ginbuf.length = 0;
2129 conn->ginbuf.value = NULL;
2130 if (conn->sspitarget)
2131 free(conn->sspitarget);
2132 conn->sspitarget = NULL;
2133 if (conn->sspicred)
2135 FreeCredentialsHandle(conn->sspicred);
2136 free(conn->sspicred);
2137 conn->sspicred = NULL;
2139 if (conn->sspictx)
2141 DeleteSecurityContext(conn->sspictx);
2142 free(conn->sspictx);
2143 conn->sspictx = NULL;
2145 #endif
2149 * PQfinish: properly close a connection to the backend. Also frees
2150 * the PGconn data structure so it shouldn't be re-used after this.
2152 void
2153 PQfinish(PGconn *conn)
2155 if (conn)
2157 closePGconn(conn);
2158 freePGconn(conn);
2163 * PQreset: resets the connection to the backend by closing the
2164 * existing connection and creating a new one.
2166 void
2167 PQreset(PGconn *conn)
2169 if (conn)
2171 closePGconn(conn);
2173 if (connectDBStart(conn) && connectDBComplete(conn))
2176 * Notify event procs of successful reset. We treat an event
2177 * proc failure as disabling the connection ... good idea?
2179 int i;
2181 for (i = 0; i < conn->nEvents; i++)
2183 PGEventConnReset evt;
2185 evt.conn = conn;
2186 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2187 conn->events[i].passThrough))
2189 conn->status = CONNECTION_BAD;
2190 printfPQExpBuffer(&conn->errorMessage,
2191 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2192 conn->events[i].name);
2193 break;
2202 * PQresetStart:
2203 * resets the connection to the backend
2204 * closes the existing connection and makes a new one
2205 * Returns 1 on success, 0 on failure.
2208 PQresetStart(PGconn *conn)
2210 if (conn)
2212 closePGconn(conn);
2214 return connectDBStart(conn);
2217 return 0;
2222 * PQresetPoll:
2223 * resets the connection to the backend
2224 * closes the existing connection and makes a new one
2226 PostgresPollingStatusType
2227 PQresetPoll(PGconn *conn)
2229 if (conn)
2231 PostgresPollingStatusType status = PQconnectPoll(conn);
2233 if (status == PGRES_POLLING_OK)
2236 * Notify event procs of successful reset. We treat an event
2237 * proc failure as disabling the connection ... good idea?
2239 int i;
2241 for (i = 0; i < conn->nEvents; i++)
2243 PGEventConnReset evt;
2245 evt.conn = conn;
2246 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2247 conn->events[i].passThrough))
2249 conn->status = CONNECTION_BAD;
2250 printfPQExpBuffer(&conn->errorMessage,
2251 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2252 conn->events[i].name);
2253 return PGRES_POLLING_FAILED;
2258 return status;
2261 return PGRES_POLLING_FAILED;
2265 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2267 * A copy is needed to be able to cancel a running query from a different
2268 * thread. If the same structure is used all structure members would have
2269 * to be individually locked (if the entire structure was locked, it would
2270 * be impossible to cancel a synchronous query because the structure would
2271 * have to stay locked for the duration of the query).
2273 PGcancel *
2274 PQgetCancel(PGconn *conn)
2276 PGcancel *cancel;
2278 if (!conn)
2279 return NULL;
2281 if (conn->sock < 0)
2282 return NULL;
2284 cancel = malloc(sizeof(PGcancel));
2285 if (cancel == NULL)
2286 return NULL;
2288 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2289 cancel->be_pid = conn->be_pid;
2290 cancel->be_key = conn->be_key;
2292 return cancel;
2295 /* PQfreeCancel: free a cancel structure */
2296 void
2297 PQfreeCancel(PGcancel *cancel)
2299 if (cancel)
2300 free(cancel);
2305 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2306 * current operation.
2308 * The return value is TRUE if the cancel request was successfully
2309 * dispatched, FALSE if not (in which case an error message is available).
2310 * Note: successful dispatch is no guarantee that there will be any effect at
2311 * the backend. The application must read the operation result as usual.
2313 * CAUTION: we want this routine to be safely callable from a signal handler
2314 * (for example, an application might want to call it in a SIGINT handler).
2315 * This means we cannot use any C library routine that might be non-reentrant.
2316 * malloc/free are often non-reentrant, and anything that might call them is
2317 * just as dangerous. We avoid sprintf here for that reason. Building up
2318 * error messages with strcpy/strcat is tedious but should be quite safe.
2319 * We also save/restore errno in case the signal handler support doesn't.
2321 * internal_cancel() is an internal helper function to make code-sharing
2322 * between the two versions of the cancel function possible.
2324 static int
2325 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2326 char *errbuf, int errbufsize)
2328 int save_errno = SOCK_ERRNO;
2329 int tmpsock = -1;
2330 char sebuf[256];
2331 int maxlen;
2332 struct
2334 uint32 packetlen;
2335 CancelRequestPacket cp;
2336 } crp;
2339 * We need to open a temporary connection to the postmaster. Do this with
2340 * only kernel calls.
2342 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2344 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2345 goto cancel_errReturn;
2347 retry3:
2348 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2349 raddr->salen) < 0)
2351 if (SOCK_ERRNO == EINTR)
2352 /* Interrupted system call - we'll just try again */
2353 goto retry3;
2354 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2355 goto cancel_errReturn;
2359 * We needn't set nonblocking I/O or NODELAY options here.
2362 /* Create and send the cancel request packet. */
2364 crp.packetlen = htonl((uint32) sizeof(crp));
2365 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2366 crp.cp.backendPID = htonl(be_pid);
2367 crp.cp.cancelAuthCode = htonl(be_key);
2369 retry4:
2370 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2372 if (SOCK_ERRNO == EINTR)
2373 /* Interrupted system call - we'll just try again */
2374 goto retry4;
2375 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2376 goto cancel_errReturn;
2380 * Wait for the postmaster to close the connection, which indicates that
2381 * it's processed the request. Without this delay, we might issue another
2382 * command only to find that our cancel zaps that command instead of the
2383 * one we thought we were canceling. Note we don't actually expect this
2384 * read to obtain any data, we are just waiting for EOF to be signaled.
2386 retry5:
2387 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2389 if (SOCK_ERRNO == EINTR)
2390 /* Interrupted system call - we'll just try again */
2391 goto retry5;
2392 /* we ignore other error conditions */
2395 /* All done */
2396 closesocket(tmpsock);
2397 SOCK_ERRNO_SET(save_errno);
2398 return TRUE;
2400 cancel_errReturn:
2403 * Make sure we don't overflow the error buffer. Leave space for the \n at
2404 * the end, and for the terminating zero.
2406 maxlen = errbufsize - strlen(errbuf) - 2;
2407 if (maxlen >= 0)
2409 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2410 maxlen);
2411 strcat(errbuf, "\n");
2413 if (tmpsock >= 0)
2414 closesocket(tmpsock);
2415 SOCK_ERRNO_SET(save_errno);
2416 return FALSE;
2420 * PQcancel: request query cancel
2422 * Returns TRUE if able to send the cancel request, FALSE if not.
2424 * On failure, an error message is stored in *errbuf, which must be of size
2425 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2426 * success return.
2429 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2431 if (!cancel)
2433 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2434 return FALSE;
2437 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2438 errbuf, errbufsize);
2442 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2444 * Returns TRUE if able to send the cancel request, FALSE if not.
2446 * On failure, the error message is saved in conn->errorMessage; this means
2447 * that this can't be used when there might be other active operations on
2448 * the connection object.
2450 * NOTE: error messages will be cut off at the current size of the
2451 * error message buffer, since we dare not try to expand conn->errorMessage!
2454 PQrequestCancel(PGconn *conn)
2456 int r;
2458 /* Check we have an open connection */
2459 if (!conn)
2460 return FALSE;
2462 if (conn->sock < 0)
2464 strlcpy(conn->errorMessage.data,
2465 "PQrequestCancel() -- connection is not open\n",
2466 conn->errorMessage.maxlen);
2467 conn->errorMessage.len = strlen(conn->errorMessage.data);
2469 return FALSE;
2472 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2473 conn->errorMessage.data, conn->errorMessage.maxlen);
2475 if (!r)
2476 conn->errorMessage.len = strlen(conn->errorMessage.data);
2478 return r;
2483 * pqPacketSend() -- convenience routine to send a message to server.
2485 * pack_type: the single-byte message type code. (Pass zero for startup
2486 * packets, which have no message type code.)
2488 * buf, buf_len: contents of message. The given length includes only what
2489 * is in buf; the message type and message length fields are added here.
2491 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2492 * SIDE_EFFECTS: may block.
2494 * Note: all messages sent with this routine have a length word, whether
2495 * it's protocol 2.0 or 3.0.
2498 pqPacketSend(PGconn *conn, char pack_type,
2499 const void *buf, size_t buf_len)
2501 /* Start the message. */
2502 if (pqPutMsgStart(pack_type, true, conn))
2503 return STATUS_ERROR;
2505 /* Send the message body. */
2506 if (pqPutnchar(buf, buf_len, conn))
2507 return STATUS_ERROR;
2509 /* Finish the message. */
2510 if (pqPutMsgEnd(conn))
2511 return STATUS_ERROR;
2513 /* Flush to ensure backend gets it. */
2514 if (pqFlush(conn))
2515 return STATUS_ERROR;
2517 return STATUS_OK;
2520 #ifdef USE_LDAP
2522 #define LDAP_URL "ldap://"
2523 #define LDAP_DEF_PORT 389
2524 #define PGLDAP_TIMEOUT 2
2526 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2527 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2531 * ldapServiceLookup
2533 * Search the LDAP URL passed as first argument, treat the result as a
2534 * string of connection options that are parsed and added to the array of
2535 * options passed as second argument.
2537 * LDAP URLs must conform to RFC 1959 without escape sequences.
2538 * ldap://host:port/dn?attributes?scope?filter?extensions
2540 * Returns
2541 * 0 if the lookup was successful,
2542 * 1 if the connection to the LDAP server could be established but
2543 * the search was unsuccessful,
2544 * 2 if a connection could not be established, and
2545 * 3 if a fatal error occurred.
2547 * An error message is returned in the third argument for return codes 1 and 3.
2549 static int
2550 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2551 PQExpBuffer errorMessage)
2553 int port = LDAP_DEF_PORT,
2554 scope,
2556 msgid,
2557 size,
2558 state,
2559 oldstate,
2561 bool found_keyword;
2562 char *url,
2563 *hostname,
2564 *portstr,
2565 *endptr,
2566 *dn,
2567 *scopestr,
2568 *filter,
2569 *result,
2571 *p1 = NULL,
2572 *optname = NULL,
2573 *optval = NULL;
2574 char *attrs[2] = {NULL, NULL};
2575 LDAP *ld = NULL;
2576 LDAPMessage *res,
2577 *entry;
2578 struct berval **values;
2579 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2581 if ((url = strdup(purl)) == NULL)
2583 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2584 return 3;
2588 * Parse URL components, check for correctness. Basically, url has '\0'
2589 * placed at component boundaries and variables are pointed at each
2590 * component.
2593 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2595 printfPQExpBuffer(errorMessage,
2596 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2597 free(url);
2598 return 3;
2601 /* hostname */
2602 hostname = url + strlen(LDAP_URL);
2603 if (*hostname == '/') /* no hostname? */
2604 hostname = "localhost"; /* the default */
2606 /* dn, "distinguished name" */
2607 p = strchr(url + strlen(LDAP_URL), '/');
2608 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2610 printfPQExpBuffer(errorMessage, libpq_gettext(
2611 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2612 free(url);
2613 return 3;
2615 *p = '\0'; /* terminate hostname */
2616 dn = p + 1;
2618 /* attribute */
2619 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2621 printfPQExpBuffer(errorMessage, libpq_gettext(
2622 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2623 free(url);
2624 return 3;
2626 *p = '\0';
2627 attrs[0] = p + 1;
2629 /* scope */
2630 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2632 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2633 free(url);
2634 return 3;
2636 *p = '\0';
2637 scopestr = p + 1;
2639 /* filter */
2640 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2642 printfPQExpBuffer(errorMessage,
2643 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2644 free(url);
2645 return 3;
2647 *p = '\0';
2648 filter = p + 1;
2649 if ((p = strchr(filter, '?')) != NULL)
2650 *p = '\0';
2652 /* port number? */
2653 if ((p1 = strchr(hostname, ':')) != NULL)
2655 long lport;
2657 *p1 = '\0';
2658 portstr = p1 + 1;
2659 errno = 0;
2660 lport = strtol(portstr, &endptr, 10);
2661 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2663 printfPQExpBuffer(errorMessage, libpq_gettext(
2664 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2665 free(url);
2666 return 3;
2668 port = (int) lport;
2671 /* Allow only one attribute */
2672 if (strchr(attrs[0], ',') != NULL)
2674 printfPQExpBuffer(errorMessage, libpq_gettext(
2675 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2676 free(url);
2677 return 3;
2680 /* set scope */
2681 if (pg_strcasecmp(scopestr, "base") == 0)
2682 scope = LDAP_SCOPE_BASE;
2683 else if (pg_strcasecmp(scopestr, "one") == 0)
2684 scope = LDAP_SCOPE_ONELEVEL;
2685 else if (pg_strcasecmp(scopestr, "sub") == 0)
2686 scope = LDAP_SCOPE_SUBTREE;
2687 else
2689 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2690 free(url);
2691 return 3;
2694 /* initialize LDAP structure */
2695 if ((ld = ldap_init(hostname, port)) == NULL)
2697 printfPQExpBuffer(errorMessage,
2698 libpq_gettext("could not create LDAP structure\n"));
2699 free(url);
2700 return 3;
2704 * Initialize connection to the server. We do an explicit bind because we
2705 * want to return 2 if the bind fails.
2707 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2709 /* error in ldap_simple_bind() */
2710 free(url);
2711 ldap_unbind(ld);
2712 return 2;
2715 /* wait some time for the connection to succeed */
2716 res = NULL;
2717 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2718 res == NULL)
2720 if (res != NULL)
2722 /* timeout */
2723 ldap_msgfree(res);
2725 /* error in ldap_result() */
2726 free(url);
2727 ldap_unbind(ld);
2728 return 2;
2730 ldap_msgfree(res);
2732 /* search */
2733 res = NULL;
2734 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2735 != LDAP_SUCCESS)
2737 if (res != NULL)
2738 ldap_msgfree(res);
2739 printfPQExpBuffer(errorMessage,
2740 libpq_gettext("lookup on LDAP server failed: %s\n"),
2741 ldap_err2string(rc));
2742 ldap_unbind(ld);
2743 free(url);
2744 return 1;
2747 /* complain if there was not exactly one result */
2748 if ((rc = ldap_count_entries(ld, res)) != 1)
2750 printfPQExpBuffer(errorMessage,
2751 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2752 : libpq_gettext("no entry found on LDAP lookup\n"));
2753 ldap_msgfree(res);
2754 ldap_unbind(ld);
2755 free(url);
2756 return 1;
2759 /* get entry */
2760 if ((entry = ldap_first_entry(ld, res)) == NULL)
2762 /* should never happen */
2763 printfPQExpBuffer(errorMessage,
2764 libpq_gettext("no entry found on LDAP lookup\n"));
2765 ldap_msgfree(res);
2766 ldap_unbind(ld);
2767 free(url);
2768 return 1;
2771 /* get values */
2772 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2774 printfPQExpBuffer(errorMessage,
2775 libpq_gettext("attribute has no values on LDAP lookup\n"));
2776 ldap_msgfree(res);
2777 ldap_unbind(ld);
2778 free(url);
2779 return 1;
2782 ldap_msgfree(res);
2783 free(url);
2785 if (values[0] == NULL)
2787 printfPQExpBuffer(errorMessage,
2788 libpq_gettext("attribute has no values on LDAP lookup\n"));
2789 ldap_value_free_len(values);
2790 ldap_unbind(ld);
2791 return 1;
2794 /* concatenate values to a single string */
2795 for (size = 0, i = 0; values[i] != NULL; ++i)
2796 size += values[i]->bv_len + 1;
2797 if ((result = malloc(size + 1)) == NULL)
2799 printfPQExpBuffer(errorMessage,
2800 libpq_gettext("out of memory\n"));
2801 ldap_value_free_len(values);
2802 ldap_unbind(ld);
2803 return 3;
2805 for (p = result, i = 0; values[i] != NULL; ++i)
2807 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2808 p += values[i]->bv_len;
2809 *(p++) = '\n';
2810 if (values[i + 1] == NULL)
2811 *(p + 1) = '\0';
2814 ldap_value_free_len(values);
2815 ldap_unbind(ld);
2817 /* parse result string */
2818 oldstate = state = 0;
2819 for (p = result; *p != '\0'; ++p)
2821 switch (state)
2823 case 0: /* between entries */
2824 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2826 optname = p;
2827 state = 1;
2829 break;
2830 case 1: /* in option name */
2831 if (ld_is_sp_tab(*p))
2833 *p = '\0';
2834 state = 2;
2836 else if (ld_is_nl_cr(*p))
2838 printfPQExpBuffer(errorMessage, libpq_gettext(
2839 "missing \"=\" after \"%s\" in connection info string\n"),
2840 optname);
2841 return 3;
2843 else if (*p == '=')
2845 *p = '\0';
2846 state = 3;
2848 break;
2849 case 2: /* after option name */
2850 if (*p == '=')
2852 state = 3;
2854 else if (!ld_is_sp_tab(*p))
2856 printfPQExpBuffer(errorMessage, libpq_gettext(
2857 "missing \"=\" after \"%s\" in connection info string\n"),
2858 optname);
2859 return 3;
2861 break;
2862 case 3: /* before option value */
2863 if (*p == '\'')
2865 optval = p + 1;
2866 p1 = p + 1;
2867 state = 5;
2869 else if (ld_is_nl_cr(*p))
2871 optval = optname + strlen(optname); /* empty */
2872 state = 0;
2874 else if (!ld_is_sp_tab(*p))
2876 optval = p;
2877 state = 4;
2879 break;
2880 case 4: /* in unquoted option value */
2881 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
2883 *p = '\0';
2884 state = 0;
2886 break;
2887 case 5: /* in quoted option value */
2888 if (*p == '\'')
2890 *p1 = '\0';
2891 state = 0;
2893 else if (*p == '\\')
2894 state = 6;
2895 else
2896 *(p1++) = *p;
2897 break;
2898 case 6: /* in quoted option value after escape */
2899 *(p1++) = *p;
2900 state = 5;
2901 break;
2904 if (state == 0 && oldstate != 0)
2906 found_keyword = false;
2907 for (i = 0; options[i].keyword; i++)
2909 if (strcmp(options[i].keyword, optname) == 0)
2911 if (options[i].val == NULL)
2912 options[i].val = strdup(optval);
2913 found_keyword = true;
2914 break;
2917 if (!found_keyword)
2919 printfPQExpBuffer(errorMessage,
2920 libpq_gettext("invalid connection option \"%s\"\n"),
2921 optname);
2922 return 1;
2924 optname = NULL;
2925 optval = NULL;
2927 oldstate = state;
2930 if (state == 5 || state == 6)
2932 printfPQExpBuffer(errorMessage, libpq_gettext(
2933 "unterminated quoted string in connection info string\n"));
2934 return 3;
2937 return 0;
2939 #endif
2941 #define MAXBUFSIZE 256
2943 static int
2944 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2946 char *service = conninfo_getval(options, "service");
2947 char serviceFile[MAXPGPATH];
2948 bool group_found = false;
2949 int linenr = 0,
2953 * We have to special-case the environment variable PGSERVICE here, since
2954 * this is and should be called before inserting environment defaults for
2955 * other connection options.
2957 if (service == NULL)
2958 service = getenv("PGSERVICE");
2961 * This could be used by any application so we can't use the binary
2962 * location to find our config files.
2964 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2965 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2967 if (service != NULL)
2969 FILE *f;
2970 char buf[MAXBUFSIZE],
2971 *line;
2973 f = fopen(serviceFile, "r");
2974 if (f == NULL)
2976 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2977 serviceFile);
2978 return 1;
2981 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
2983 linenr++;
2985 if (strlen(line) >= sizeof(buf) - 1)
2987 fclose(f);
2988 printfPQExpBuffer(errorMessage,
2989 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2990 linenr,
2991 serviceFile);
2992 return 2;
2995 /* ignore EOL at end of line */
2996 if (strlen(line) && line[strlen(line) - 1] == '\n')
2997 line[strlen(line) - 1] = 0;
2999 /* ignore leading blanks */
3000 while (*line && isspace((unsigned char) line[0]))
3001 line++;
3003 /* ignore comments and empty lines */
3004 if (strlen(line) == 0 || line[0] == '#')
3005 continue;
3007 /* Check for right groupname */
3008 if (line[0] == '[')
3010 if (group_found)
3012 /* group info already read */
3013 fclose(f);
3014 return 0;
3017 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3018 line[strlen(service) + 1] == ']')
3019 group_found = true;
3020 else
3021 group_found = false;
3023 else
3025 if (group_found)
3028 * Finally, we are in the right group and can parse the
3029 * line
3031 char *key,
3032 *val;
3033 bool found_keyword;
3035 #ifdef USE_LDAP
3036 if (strncmp(line, "ldap", 4) == 0)
3038 int rc = ldapServiceLookup(line, options, errorMessage);
3040 /* if rc = 2, go on reading for fallback */
3041 switch (rc)
3043 case 0:
3044 fclose(f);
3045 return 0;
3046 case 1:
3047 case 3:
3048 fclose(f);
3049 return 3;
3050 case 2:
3051 continue;
3054 #endif
3056 key = line;
3057 val = strchr(line, '=');
3058 if (val == NULL)
3060 printfPQExpBuffer(errorMessage,
3061 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3062 serviceFile,
3063 linenr);
3064 fclose(f);
3065 return 3;
3067 *val++ = '\0';
3070 * Set the parameter --- but don't override any previous
3071 * explicit setting.
3073 found_keyword = false;
3074 for (i = 0; options[i].keyword; i++)
3076 if (strcmp(options[i].keyword, key) == 0)
3078 if (options[i].val == NULL)
3079 options[i].val = strdup(val);
3080 found_keyword = true;
3081 break;
3085 if (!found_keyword)
3087 printfPQExpBuffer(errorMessage,
3088 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3089 serviceFile,
3090 linenr);
3091 fclose(f);
3092 return 3;
3098 fclose(f);
3101 return 0;
3106 * PQconninfoParse
3108 * Parse a string like PQconnectdb() would do and return the
3109 * resulting connection options array. NULL is returned on failure.
3110 * The result contains only options specified directly in the string,
3111 * not any possible default values.
3113 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3114 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3115 * both *errmsg and the result could be NULL.
3117 * NOTE: the returned array is dynamically allocated and should
3118 * be freed when no longer needed via PQconninfoFree().
3120 PQconninfoOption *
3121 PQconninfoParse(const char *conninfo, char **errmsg)
3123 PQExpBufferData errorBuf;
3124 PQconninfoOption *connOptions;
3126 if (errmsg)
3127 *errmsg = NULL; /* default */
3128 initPQExpBuffer(&errorBuf);
3129 if (errorBuf.data == NULL)
3130 return NULL; /* out of memory already :-( */
3131 connOptions = conninfo_parse(conninfo, &errorBuf, false);
3132 if (connOptions == NULL && errmsg)
3133 *errmsg = errorBuf.data;
3134 else
3135 termPQExpBuffer(&errorBuf);
3136 return connOptions;
3140 * Conninfo parser routine
3142 * If successful, a malloc'd PQconninfoOption array is returned.
3143 * If not successful, NULL is returned and an error message is
3144 * left in errorMessage.
3145 * Defaults are supplied (from a service file, environment variables, etc)
3146 * for unspecified options, but only if use_defaults is TRUE.
3148 static PQconninfoOption *
3149 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3150 bool use_defaults)
3152 char *pname;
3153 char *pval;
3154 char *buf;
3155 char *tmp;
3156 char *cp;
3157 char *cp2;
3158 PQconninfoOption *options;
3159 PQconninfoOption *option;
3161 /* Make a working copy of PQconninfoOptions */
3162 options = malloc(sizeof(PQconninfoOptions));
3163 if (options == NULL)
3165 printfPQExpBuffer(errorMessage,
3166 libpq_gettext("out of memory\n"));
3167 return NULL;
3169 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3171 /* Need a modifiable copy of the input string */
3172 if ((buf = strdup(conninfo)) == NULL)
3174 printfPQExpBuffer(errorMessage,
3175 libpq_gettext("out of memory\n"));
3176 PQconninfoFree(options);
3177 return NULL;
3179 cp = buf;
3181 while (*cp)
3183 /* Skip blanks before the parameter name */
3184 if (isspace((unsigned char) *cp))
3186 cp++;
3187 continue;
3190 /* Get the parameter name */
3191 pname = cp;
3192 while (*cp)
3194 if (*cp == '=')
3195 break;
3196 if (isspace((unsigned char) *cp))
3198 *cp++ = '\0';
3199 while (*cp)
3201 if (!isspace((unsigned char) *cp))
3202 break;
3203 cp++;
3205 break;
3207 cp++;
3210 /* Check that there is a following '=' */
3211 if (*cp != '=')
3213 printfPQExpBuffer(errorMessage,
3214 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3215 pname);
3216 PQconninfoFree(options);
3217 free(buf);
3218 return NULL;
3220 *cp++ = '\0';
3222 /* Skip blanks after the '=' */
3223 while (*cp)
3225 if (!isspace((unsigned char) *cp))
3226 break;
3227 cp++;
3230 /* Get the parameter value */
3231 pval = cp;
3233 if (*cp != '\'')
3235 cp2 = pval;
3236 while (*cp)
3238 if (isspace((unsigned char) *cp))
3240 *cp++ = '\0';
3241 break;
3243 if (*cp == '\\')
3245 cp++;
3246 if (*cp != '\0')
3247 *cp2++ = *cp++;
3249 else
3250 *cp2++ = *cp++;
3252 *cp2 = '\0';
3254 else
3256 cp2 = pval;
3257 cp++;
3258 for (;;)
3260 if (*cp == '\0')
3262 printfPQExpBuffer(errorMessage,
3263 libpq_gettext("unterminated quoted string in connection info string\n"));
3264 PQconninfoFree(options);
3265 free(buf);
3266 return NULL;
3268 if (*cp == '\\')
3270 cp++;
3271 if (*cp != '\0')
3272 *cp2++ = *cp++;
3273 continue;
3275 if (*cp == '\'')
3277 *cp2 = '\0';
3278 cp++;
3279 break;
3281 *cp2++ = *cp++;
3286 * Now we have the name and the value. Search for the param record.
3288 for (option = options; option->keyword != NULL; option++)
3290 if (strcmp(option->keyword, pname) == 0)
3291 break;
3293 if (option->keyword == NULL)
3295 printfPQExpBuffer(errorMessage,
3296 libpq_gettext("invalid connection option \"%s\"\n"),
3297 pname);
3298 PQconninfoFree(options);
3299 free(buf);
3300 return NULL;
3304 * Store the value
3306 if (option->val)
3307 free(option->val);
3308 option->val = strdup(pval);
3309 if (!option->val)
3311 printfPQExpBuffer(errorMessage,
3312 libpq_gettext("out of memory\n"));
3313 PQconninfoFree(options);
3314 free(buf);
3315 return NULL;
3319 /* Done with the modifiable input string */
3320 free(buf);
3323 * Stop here if caller doesn't want defaults filled in.
3325 if (!use_defaults)
3326 return options;
3329 * If there's a service spec, use it to obtain any not-explicitly-given
3330 * parameters.
3332 if (parseServiceInfo(options, errorMessage))
3334 PQconninfoFree(options);
3335 return NULL;
3339 * Get the fallback resources for parameters not specified in the conninfo
3340 * string nor the service.
3342 for (option = options; option->keyword != NULL; option++)
3344 if (option->val != NULL)
3345 continue; /* Value was in conninfo or service */
3348 * Try to get the environment variable fallback
3350 if (option->envvar != NULL)
3352 if ((tmp = getenv(option->envvar)) != NULL)
3354 option->val = strdup(tmp);
3355 if (!option->val)
3357 printfPQExpBuffer(errorMessage,
3358 libpq_gettext("out of memory\n"));
3359 PQconninfoFree(options);
3360 return NULL;
3362 continue;
3367 * No environment variable specified or this one isn't set - try
3368 * compiled in
3370 if (option->compiled != NULL)
3372 option->val = strdup(option->compiled);
3373 if (!option->val)
3375 printfPQExpBuffer(errorMessage,
3376 libpq_gettext("out of memory\n"));
3377 PQconninfoFree(options);
3378 return NULL;
3380 continue;
3384 * Special handling for user
3386 if (strcmp(option->keyword, "user") == 0)
3388 option->val = pg_fe_getauthname(errorMessage);
3389 continue;
3393 return options;
3397 static char *
3398 conninfo_getval(PQconninfoOption *connOptions,
3399 const char *keyword)
3401 PQconninfoOption *option;
3403 for (option = connOptions; option->keyword != NULL; option++)
3405 if (strcmp(option->keyword, keyword) == 0)
3406 return option->val;
3409 return NULL;
3413 void
3414 PQconninfoFree(PQconninfoOption *connOptions)
3416 PQconninfoOption *option;
3418 if (connOptions == NULL)
3419 return;
3421 for (option = connOptions; option->keyword != NULL; option++)
3423 if (option->val != NULL)
3424 free(option->val);
3426 free(connOptions);
3430 /* =========== accessor functions for PGconn ========= */
3431 char *
3432 PQdb(const PGconn *conn)
3434 if (!conn)
3435 return NULL;
3436 return conn->dbName;
3439 char *
3440 PQuser(const PGconn *conn)
3442 if (!conn)
3443 return NULL;
3444 return conn->pguser;
3447 char *
3448 PQpass(const PGconn *conn)
3450 if (!conn)
3451 return NULL;
3452 return conn->pgpass;
3455 char *
3456 PQhost(const PGconn *conn)
3458 if (!conn)
3459 return NULL;
3460 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3463 char *
3464 PQport(const PGconn *conn)
3466 if (!conn)
3467 return NULL;
3468 return conn->pgport;
3471 char *
3472 PQtty(const PGconn *conn)
3474 if (!conn)
3475 return NULL;
3476 return conn->pgtty;
3479 char *
3480 PQoptions(const PGconn *conn)
3482 if (!conn)
3483 return NULL;
3484 return conn->pgoptions;
3487 ConnStatusType
3488 PQstatus(const PGconn *conn)
3490 if (!conn)
3491 return CONNECTION_BAD;
3492 return conn->status;
3495 PGTransactionStatusType
3496 PQtransactionStatus(const PGconn *conn)
3498 if (!conn || conn->status != CONNECTION_OK)
3499 return PQTRANS_UNKNOWN;
3500 if (conn->asyncStatus != PGASYNC_IDLE)
3501 return PQTRANS_ACTIVE;
3502 return conn->xactStatus;
3505 const char *
3506 PQparameterStatus(const PGconn *conn, const char *paramName)
3508 const pgParameterStatus *pstatus;
3510 if (!conn || !paramName)
3511 return NULL;
3512 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3514 if (strcmp(pstatus->name, paramName) == 0)
3515 return pstatus->value;
3517 return NULL;
3521 PQprotocolVersion(const PGconn *conn)
3523 if (!conn)
3524 return 0;
3525 if (conn->status == CONNECTION_BAD)
3526 return 0;
3527 return PG_PROTOCOL_MAJOR(conn->pversion);
3531 PQserverVersion(const PGconn *conn)
3533 if (!conn)
3534 return 0;
3535 if (conn->status == CONNECTION_BAD)
3536 return 0;
3537 return conn->sversion;
3540 char *
3541 PQerrorMessage(const PGconn *conn)
3543 if (!conn)
3544 return libpq_gettext("connection pointer is NULL\n");
3546 return conn->errorMessage.data;
3550 PQsocket(const PGconn *conn)
3552 if (!conn)
3553 return -1;
3554 return conn->sock;
3558 PQbackendPID(const PGconn *conn)
3560 if (!conn || conn->status != CONNECTION_OK)
3561 return 0;
3562 return conn->be_pid;
3566 PQconnectionNeedsPassword(const PGconn *conn)
3568 if (!conn)
3569 return false;
3570 if (conn->password_needed &&
3571 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
3572 return true;
3573 else
3574 return false;
3578 PQconnectionUsedPassword(const PGconn *conn)
3580 if (!conn)
3581 return false;
3582 if (conn->password_needed)
3583 return true;
3584 else
3585 return false;
3589 PQclientEncoding(const PGconn *conn)
3591 if (!conn || conn->status != CONNECTION_OK)
3592 return -1;
3593 return conn->client_encoding;
3597 PQsetClientEncoding(PGconn *conn, const char *encoding)
3599 char qbuf[128];
3600 static const char query[] = "set client_encoding to '%s'";
3601 PGresult *res;
3602 int status;
3604 if (!conn || conn->status != CONNECTION_OK)
3605 return -1;
3607 if (!encoding)
3608 return -1;
3610 /* check query buffer overflow */
3611 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3612 return -1;
3614 /* ok, now send a query */
3615 sprintf(qbuf, query, encoding);
3616 res = PQexec(conn, qbuf);
3618 if (res == NULL)
3619 return -1;
3620 if (res->resultStatus != PGRES_COMMAND_OK)
3621 status = -1;
3622 else
3625 * In protocol 2 we have to assume the setting will stick, and adjust
3626 * our state immediately. In protocol 3 and up we can rely on the
3627 * backend to report the parameter value, and we'll change state at
3628 * that time.
3630 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3631 pqSaveParameterStatus(conn, "client_encoding", encoding);
3632 status = 0; /* everything is ok */
3634 PQclear(res);
3635 return status;
3638 PGVerbosity
3639 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3641 PGVerbosity old;
3643 if (!conn)
3644 return PQERRORS_DEFAULT;
3645 old = conn->verbosity;
3646 conn->verbosity = verbosity;
3647 return old;
3650 void
3651 PQtrace(PGconn *conn, FILE *debug_port)
3653 if (conn == NULL)
3654 return;
3655 PQuntrace(conn);
3656 conn->Pfdebug = debug_port;
3659 void
3660 PQuntrace(PGconn *conn)
3662 if (conn == NULL)
3663 return;
3664 if (conn->Pfdebug)
3666 fflush(conn->Pfdebug);
3667 conn->Pfdebug = NULL;
3671 PQnoticeReceiver
3672 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3674 PQnoticeReceiver old;
3676 if (conn == NULL)
3677 return NULL;
3679 old = conn->noticeHooks.noticeRec;
3680 if (proc)
3682 conn->noticeHooks.noticeRec = proc;
3683 conn->noticeHooks.noticeRecArg = arg;
3685 return old;
3688 PQnoticeProcessor
3689 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3691 PQnoticeProcessor old;
3693 if (conn == NULL)
3694 return NULL;
3696 old = conn->noticeHooks.noticeProc;
3697 if (proc)
3699 conn->noticeHooks.noticeProc = proc;
3700 conn->noticeHooks.noticeProcArg = arg;
3702 return old;
3706 * The default notice message receiver just gets the standard notice text
3707 * and sends it to the notice processor. This two-level setup exists
3708 * mostly for backwards compatibility; perhaps we should deprecate use of
3709 * PQsetNoticeProcessor?
3711 static void
3712 defaultNoticeReceiver(void *arg, const PGresult *res)
3714 (void) arg; /* not used */
3715 if (res->noticeHooks.noticeProc != NULL)
3716 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3717 PQresultErrorMessage(res));
3721 * The default notice message processor just prints the
3722 * message on stderr. Applications can override this if they
3723 * want the messages to go elsewhere (a window, for example).
3724 * Note that simply discarding notices is probably a bad idea.
3726 static void
3727 defaultNoticeProcessor(void *arg, const char *message)
3729 (void) arg; /* not used */
3730 /* Note: we expect the supplied string to end with a newline already. */
3731 fprintf(stderr, "%s", message);
3735 * returns a pointer to the next token or NULL if the current
3736 * token doesn't match
3738 static char *
3739 pwdfMatchesString(char *buf, char *token)
3741 char *tbuf,
3742 *ttok;
3743 bool bslash = false;
3745 if (buf == NULL || token == NULL)
3746 return NULL;
3747 tbuf = buf;
3748 ttok = token;
3749 if (*tbuf == '*')
3750 return tbuf + 2;
3751 while (*tbuf != 0)
3753 if (*tbuf == '\\' && !bslash)
3755 tbuf++;
3756 bslash = true;
3758 if (*tbuf == ':' && *ttok == 0 && !bslash)
3759 return tbuf + 1;
3760 bslash = false;
3761 if (*ttok == 0)
3762 return NULL;
3763 if (*tbuf == *ttok)
3765 tbuf++;
3766 ttok++;
3768 else
3769 return NULL;
3771 return NULL;
3774 /* Get a password from the password file. Return value is malloc'd. */
3775 static char *
3776 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3778 FILE *fp;
3779 char pgpassfile[MAXPGPATH];
3780 struct stat stat_buf;
3781 char *passfile_env;
3783 #define LINELEN NAMEDATALEN*5
3784 char buf[LINELEN];
3786 if (dbname == NULL || strlen(dbname) == 0)
3787 return NULL;
3789 if (username == NULL || strlen(username) == 0)
3790 return NULL;
3792 /* 'localhost' matches pghost of '' or the default socket directory */
3793 if (hostname == NULL)
3794 hostname = DefaultHost;
3795 else if (is_absolute_path(hostname))
3798 * We should probably use canonicalize_path(), but then we have to
3799 * bring path.c into libpq, and it doesn't seem worth it.
3801 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3802 hostname = DefaultHost;
3804 if (port == NULL)
3805 port = DEF_PGPORT_STR;
3807 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3808 /* use the literal path from the environment, if set */
3809 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3810 else
3812 char homedir[MAXPGPATH];
3814 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3815 return NULL;
3816 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3819 /* If password file cannot be opened, ignore it. */
3820 if (stat(pgpassfile, &stat_buf) != 0)
3821 return NULL;
3823 #ifndef WIN32
3824 if (!S_ISREG(stat_buf.st_mode))
3826 fprintf(stderr,
3827 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3828 pgpassfile);
3829 return NULL;
3832 /* If password file is insecure, alert the user and ignore it. */
3833 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3835 fprintf(stderr,
3836 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
3837 pgpassfile);
3838 return NULL;
3840 #else
3843 * On Win32, the directory is protected, so we don't have to check the
3844 * file.
3846 #endif
3848 fp = fopen(pgpassfile, "r");
3849 if (fp == NULL)
3850 return NULL;
3852 while (!feof(fp))
3854 char *t = buf,
3855 *ret;
3856 int len;
3858 fgets(buf, sizeof(buf), fp);
3860 len = strlen(buf);
3861 if (len == 0)
3862 continue;
3864 /* Remove trailing newline */
3865 if (buf[len - 1] == '\n')
3866 buf[len - 1] = 0;
3868 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3869 (t = pwdfMatchesString(t, port)) == NULL ||
3870 (t = pwdfMatchesString(t, dbname)) == NULL ||
3871 (t = pwdfMatchesString(t, username)) == NULL)
3872 continue;
3873 ret = strdup(t);
3874 fclose(fp);
3875 return ret;
3878 fclose(fp);
3879 return NULL;
3881 #undef LINELEN
3885 * Obtain user's home directory, return in given buffer
3887 * On Unix, this actually returns the user's home directory. On Windows
3888 * it returns the PostgreSQL-specific application data folder.
3890 * This is essentially the same as get_home_path(), but we don't use that
3891 * because we don't want to pull path.c into libpq (it pollutes application
3892 * namespace)
3894 bool
3895 pqGetHomeDirectory(char *buf, int bufsize)
3897 #ifndef WIN32
3898 char pwdbuf[BUFSIZ];
3899 struct passwd pwdstr;
3900 struct passwd *pwd = NULL;
3902 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3903 return false;
3904 strlcpy(buf, pwd->pw_dir, bufsize);
3905 return true;
3906 #else
3907 char tmppath[MAX_PATH];
3909 ZeroMemory(tmppath, sizeof(tmppath));
3910 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3911 return false;
3912 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3913 return true;
3914 #endif
3918 * To keep the API consistent, the locking stubs are always provided, even
3919 * if they are not required.
3922 static void
3923 default_threadlock(int acquire)
3925 #ifdef ENABLE_THREAD_SAFETY
3926 #ifndef WIN32
3927 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3928 #else
3929 static pthread_mutex_t singlethread_lock = NULL;
3930 static long mutex_initlock = 0;
3932 if (singlethread_lock == NULL)
3934 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3935 /* loop, another thread own the lock */ ;
3936 if (singlethread_lock == NULL)
3938 if (pthread_mutex_init(&singlethread_lock, NULL))
3939 PGTHREAD_ERROR("failed to initialize mutex");
3941 InterlockedExchange(&mutex_initlock, 0);
3943 #endif
3944 if (acquire)
3946 if (pthread_mutex_lock(&singlethread_lock))
3947 PGTHREAD_ERROR("failed to lock mutex");
3949 else
3951 if (pthread_mutex_unlock(&singlethread_lock))
3952 PGTHREAD_ERROR("failed to unlock mutex");
3954 #endif
3957 pgthreadlock_t
3958 PQregisterThreadLock(pgthreadlock_t newhandler)
3960 pgthreadlock_t prev = pg_g_threadlock;
3962 if (newhandler)
3963 pg_g_threadlock = newhandler;
3964 else
3965 pg_g_threadlock = default_threadlock;
3967 return prev;