Make pwdfMatchesString() a little more careful about matching * fields.
[PostgreSQL.git] / src / interfaces / libpq / fe-connect.c
blob7f4ae4c52d599bed64bdea0512cbfe52777eda6e
1 /*-------------------------------------------------------------------------
3 * fe-connect.c
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
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 * ssl options are allowed even without client SSL support because the
179 * client can still handle SSL modes "disable" and "allow". Other parameters
180 * have no effect on non-SSL connections, so there is no reason to exclude them
181 * since none of them are mandatory.
183 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
184 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
186 {"sslcert", "PGSSLCERT", NULL, NULL,
187 "SSL-Client-Cert", "", 64},
189 {"sslkey", "PGSSLKEY", NULL, NULL,
190 "SSL-Client-Key", "", 64},
192 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
193 "SSL-Root-Certificate", "", 64},
195 {"sslcrl", "PGSSLCRL", NULL, NULL,
196 "SSL-Revocation-List", "", 64},
198 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
199 /* Kerberos and GSSAPI authentication support specifying the service name */
200 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
201 "Kerberos-service-name", "", 20},
202 #endif
204 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
207 * GSSAPI and SSPI both enabled, give a way to override which is used by
208 * default
210 {"gsslib", "PGGSSLIB", NULL, NULL,
211 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
212 #endif
214 /* Terminating entry --- MUST BE LAST */
215 {NULL, NULL, NULL, NULL,
216 NULL, NULL, 0}
219 static const PQEnvironmentOption EnvironmentOptions[] =
221 /* common user-interface settings */
223 "PGDATESTYLE", "datestyle"
226 "PGTZ", "timezone"
229 "PGCLIENTENCODING", "client_encoding"
231 /* internal performance-related settings */
233 "PGGEQO", "geqo"
236 NULL, NULL
241 static bool connectOptions1(PGconn *conn, const char *conninfo);
242 static bool connectOptions2(PGconn *conn);
243 static int connectDBStart(PGconn *conn);
244 static int connectDBComplete(PGconn *conn);
245 static PGconn *makeEmptyPGconn(void);
246 static void freePGconn(PGconn *conn);
247 static void closePGconn(PGconn *conn);
248 static PQconninfoOption *conninfo_parse(const char *conninfo,
249 PQExpBuffer errorMessage, bool use_defaults);
250 static char *conninfo_getval(PQconninfoOption *connOptions,
251 const char *keyword);
252 static void defaultNoticeReceiver(void *arg, const PGresult *res);
253 static void defaultNoticeProcessor(void *arg, const char *message);
254 static int parseServiceInfo(PQconninfoOption *options,
255 PQExpBuffer errorMessage);
256 static char *pwdfMatchesString(char *buf, char *token);
257 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
258 char *username);
259 static void default_threadlock(int acquire);
262 /* global variable because fe-auth.c needs to access it */
263 pgthreadlock_t pg_g_threadlock = default_threadlock;
267 * Connecting to a Database
269 * There are now four different ways a user of this API can connect to the
270 * database. Two are not recommended for use in new code, because of their
271 * lack of extensibility with respect to the passing of options to the
272 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
273 * to the latter).
275 * If it is desired to connect in a synchronous (blocking) manner, use the
276 * function PQconnectdb.
278 * To connect in an asynchronous (non-blocking) manner, use the functions
279 * PQconnectStart, and PQconnectPoll.
281 * Internally, the static functions connectDBStart, connectDBComplete
282 * are part of the connection procedure.
286 * PQconnectdb
288 * establishes a connection to a postgres backend through the postmaster
289 * using connection information in a string.
291 * The conninfo string is a white-separated list of
293 * option = value
295 * definitions. Value might be a single value containing no whitespaces or
296 * a single quoted string. If a single quote should appear anywhere in
297 * the value, it must be escaped with a backslash like \'
299 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
300 * if a memory allocation failed.
301 * If the status field of the connection returned is CONNECTION_BAD,
302 * then some fields may be null'ed out instead of having valid values.
304 * You should call PQfinish (if conn is not NULL) regardless of whether this
305 * call succeeded.
307 PGconn *
308 PQconnectdb(const char *conninfo)
310 PGconn *conn = PQconnectStart(conninfo);
312 if (conn && conn->status != CONNECTION_BAD)
313 (void) connectDBComplete(conn);
315 return conn;
319 * PQconnectStart
321 * Begins the establishment of a connection to a postgres backend through the
322 * postmaster using connection information in a string.
324 * See comment for PQconnectdb for the definition of the string format.
326 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
327 * you should not attempt to proceed with this connection. If the status
328 * field of the connection returned is CONNECTION_BAD, an error has
329 * occurred. In this case you should call PQfinish on the result, (perhaps
330 * inspecting the error message first). Other fields of the structure may not
331 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
332 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
333 * this is necessary.
335 * See PQconnectPoll for more info.
337 PGconn *
338 PQconnectStart(const char *conninfo)
340 PGconn *conn;
343 * Allocate memory for the conn structure
345 conn = makeEmptyPGconn();
346 if (conn == NULL)
347 return NULL;
350 * Parse the conninfo string
352 if (!connectOptions1(conn, conninfo))
353 return conn;
356 * Compute derived options
358 if (!connectOptions2(conn))
359 return conn;
362 * Connect to the database
364 if (!connectDBStart(conn))
366 /* Just in case we failed to set it in connectDBStart */
367 conn->status = CONNECTION_BAD;
370 return conn;
374 * connectOptions1
376 * Internal subroutine to set up connection parameters given an already-
377 * created PGconn and a conninfo string. Derived settings should be
378 * processed by calling connectOptions2 next. (We split them because
379 * PQsetdbLogin overrides defaults in between.)
381 * Returns true if OK, false if trouble (in which case errorMessage is set
382 * and so is conn->status).
384 static bool
385 connectOptions1(PGconn *conn, const char *conninfo)
387 PQconninfoOption *connOptions;
388 char *tmp;
391 * Parse the conninfo string
393 connOptions = conninfo_parse(conninfo, &conn->errorMessage, true);
394 if (connOptions == NULL)
396 conn->status = CONNECTION_BAD;
397 /* errorMessage is already set */
398 return false;
402 * Move option values into conn structure
404 * Don't put anything cute here --- intelligence should be in
405 * connectOptions2 ...
407 * XXX: probably worth checking strdup() return value here...
409 tmp = conninfo_getval(connOptions, "hostaddr");
410 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
411 tmp = conninfo_getval(connOptions, "host");
412 conn->pghost = tmp ? strdup(tmp) : NULL;
413 tmp = conninfo_getval(connOptions, "port");
414 conn->pgport = tmp ? strdup(tmp) : NULL;
415 tmp = conninfo_getval(connOptions, "tty");
416 conn->pgtty = tmp ? strdup(tmp) : NULL;
417 tmp = conninfo_getval(connOptions, "options");
418 conn->pgoptions = tmp ? strdup(tmp) : NULL;
419 tmp = conninfo_getval(connOptions, "dbname");
420 conn->dbName = tmp ? strdup(tmp) : NULL;
421 tmp = conninfo_getval(connOptions, "user");
422 conn->pguser = tmp ? strdup(tmp) : NULL;
423 tmp = conninfo_getval(connOptions, "password");
424 conn->pgpass = tmp ? strdup(tmp) : NULL;
425 tmp = conninfo_getval(connOptions, "connect_timeout");
426 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
427 tmp = conninfo_getval(connOptions, "sslmode");
428 conn->sslmode = tmp ? strdup(tmp) : NULL;
429 tmp = conninfo_getval(connOptions, "sslkey");
430 conn->sslkey = tmp ? strdup(tmp) : NULL;
431 tmp = conninfo_getval(connOptions, "sslcert");
432 conn->sslcert = tmp ? strdup(tmp) : NULL;
433 tmp = conninfo_getval(connOptions, "sslrootcert");
434 conn->sslrootcert = tmp ? strdup(tmp) : NULL;
435 tmp = conninfo_getval(connOptions, "sslcrl");
436 conn->sslcrl = tmp ? strdup(tmp) : NULL;
437 #ifdef USE_SSL
438 tmp = conninfo_getval(connOptions, "requiressl");
439 if (tmp && tmp[0] == '1')
441 /* here warn that the requiressl option is deprecated? */
442 if (conn->sslmode)
443 free(conn->sslmode);
444 conn->sslmode = strdup("require");
446 #endif
447 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
448 tmp = conninfo_getval(connOptions, "krbsrvname");
449 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
450 #endif
451 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
452 tmp = conninfo_getval(connOptions, "gsslib");
453 conn->gsslib = tmp ? strdup(tmp) : NULL;
454 #endif
457 * Free the option info - all is in conn now
459 PQconninfoFree(connOptions);
461 return true;
465 * connectOptions2
467 * Compute derived connection options after absorbing all user-supplied info.
469 * Returns true if OK, false if trouble (in which case errorMessage is set
470 * and so is conn->status).
472 static bool
473 connectOptions2(PGconn *conn)
476 * If database name was not given, default it to equal user name
478 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
479 && conn->pguser != NULL)
481 if (conn->dbName)
482 free(conn->dbName);
483 conn->dbName = strdup(conn->pguser);
487 * Supply default password if none given
489 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
491 if (conn->pgpass)
492 free(conn->pgpass);
493 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
494 conn->dbName, conn->pguser);
495 if (conn->pgpass == NULL)
496 conn->pgpass = strdup(DefaultPassword);
500 * Allow unix socket specification in the host name
502 if (conn->pghost && is_absolute_path(conn->pghost))
504 if (conn->pgunixsocket)
505 free(conn->pgunixsocket);
506 conn->pgunixsocket = conn->pghost;
507 conn->pghost = NULL;
511 * validate sslmode option
513 if (conn->sslmode)
515 if (strcmp(conn->sslmode, "disable") != 0
516 && strcmp(conn->sslmode, "allow") != 0
517 && strcmp(conn->sslmode, "prefer") != 0
518 && strcmp(conn->sslmode, "require") != 0
519 && strcmp(conn->sslmode, "verify-ca") != 0
520 && strcmp(conn->sslmode, "verify-full") != 0)
522 conn->status = CONNECTION_BAD;
523 printfPQExpBuffer(&conn->errorMessage,
524 libpq_gettext("invalid sslmode value: \"%s\"\n"),
525 conn->sslmode);
526 return false;
529 #ifndef USE_SSL
530 switch (conn->sslmode[0])
532 case 'a': /* "allow" */
533 case 'p': /* "prefer" */
536 * warn user that an SSL connection will never be negotiated
537 * since SSL was not compiled in?
539 break;
541 case 'r': /* "require" */
542 case 'v': /* "verify-ca" or "verify-full" */
543 conn->status = CONNECTION_BAD;
544 printfPQExpBuffer(&conn->errorMessage,
545 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
546 conn->sslmode);
547 return false;
549 #endif
551 else
552 conn->sslmode = strdup(DefaultSSLMode);
555 * Only if we get this far is it appropriate to try to connect. (We need a
556 * state flag, rather than just the boolean result of this function, in
557 * case someone tries to PQreset() the PGconn.)
559 conn->options_valid = true;
561 return true;
565 * PQconndefaults
567 * Parse an empty string like PQconnectdb() would do and return the
568 * resulting connection options array, ie, all the default values that are
569 * available from the environment etc. On error (eg out of memory),
570 * NULL is returned.
572 * Using this function, an application may determine all possible options
573 * and their current default values.
575 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
576 * and should be freed when no longer needed via PQconninfoFree(). (In prior
577 * versions, the returned array was static, but that's not thread-safe.)
578 * Pre-7.0 applications that use this function will see a small memory leak
579 * until they are updated to call PQconninfoFree.
581 PQconninfoOption *
582 PQconndefaults(void)
584 PQExpBufferData errorBuf;
585 PQconninfoOption *connOptions;
587 initPQExpBuffer(&errorBuf);
588 if (PQExpBufferBroken(&errorBuf))
589 return NULL; /* out of memory already :-( */
590 connOptions = conninfo_parse("", &errorBuf, true);
591 termPQExpBuffer(&errorBuf);
592 return connOptions;
595 /* ----------------
596 * PQsetdbLogin
598 * establishes a connection to a postgres backend through the postmaster
599 * at the specified host and port.
601 * returns a PGconn* which is needed for all subsequent libpq calls
603 * if the status field of the connection returned is CONNECTION_BAD,
604 * then only the errorMessage is likely to be useful.
605 * ----------------
607 PGconn *
608 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
609 const char *pgtty, const char *dbName, const char *login,
610 const char *pwd)
612 PGconn *conn;
615 * Allocate memory for the conn structure
617 conn = makeEmptyPGconn();
618 if (conn == NULL)
619 return NULL;
622 * If the dbName parameter contains '=', assume it's a conninfo string.
624 if (dbName && strchr(dbName, '='))
626 if (!connectOptions1(conn, dbName))
627 return conn;
629 else
632 * Old-style path: first, parse an empty conninfo string in order to
633 * set up the same defaults that PQconnectdb() would use.
635 if (!connectOptions1(conn, ""))
636 return conn;
638 /* Insert dbName parameter value into struct */
639 if (dbName && dbName[0] != '\0')
641 if (conn->dbName)
642 free(conn->dbName);
643 conn->dbName = strdup(dbName);
648 * Insert remaining parameters into struct, overriding defaults (as well
649 * as any conflicting data from dbName taken as a conninfo).
651 if (pghost && pghost[0] != '\0')
653 if (conn->pghost)
654 free(conn->pghost);
655 conn->pghost = strdup(pghost);
658 if (pgport && pgport[0] != '\0')
660 if (conn->pgport)
661 free(conn->pgport);
662 conn->pgport = strdup(pgport);
665 if (pgoptions && pgoptions[0] != '\0')
667 if (conn->pgoptions)
668 free(conn->pgoptions);
669 conn->pgoptions = strdup(pgoptions);
672 if (pgtty && pgtty[0] != '\0')
674 if (conn->pgtty)
675 free(conn->pgtty);
676 conn->pgtty = strdup(pgtty);
679 if (login && login[0] != '\0')
681 if (conn->pguser)
682 free(conn->pguser);
683 conn->pguser = strdup(login);
686 if (pwd && pwd[0] != '\0')
688 if (conn->pgpass)
689 free(conn->pgpass);
690 conn->pgpass = strdup(pwd);
694 * Compute derived options
696 if (!connectOptions2(conn))
697 return conn;
700 * Connect to the database
702 if (connectDBStart(conn))
703 (void) connectDBComplete(conn);
705 return conn;
709 /* ----------
710 * connectNoDelay -
711 * Sets the TCP_NODELAY socket option.
712 * Returns 1 if successful, 0 if not.
713 * ----------
715 static int
716 connectNoDelay(PGconn *conn)
718 #ifdef TCP_NODELAY
719 int on = 1;
721 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
722 (char *) &on,
723 sizeof(on)) < 0)
725 char sebuf[256];
727 appendPQExpBuffer(&conn->errorMessage,
728 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
729 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
730 return 0;
732 #endif
734 return 1;
738 /* ----------
739 * connectFailureMessage -
740 * create a friendly error message on connection failure.
741 * ----------
743 static void
744 connectFailureMessage(PGconn *conn, int errorno)
746 char sebuf[256];
748 #ifdef HAVE_UNIX_SOCKETS
749 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
751 char service[NI_MAXHOST];
753 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
754 NULL, 0,
755 service, sizeof(service),
756 NI_NUMERICSERV);
757 appendPQExpBuffer(&conn->errorMessage,
758 libpq_gettext("could not connect to server: %s\n"
759 "\tIs the server running locally and accepting\n"
760 "\tconnections on Unix domain socket \"%s\"?\n"),
761 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
762 service);
764 else
765 #endif /* HAVE_UNIX_SOCKETS */
767 appendPQExpBuffer(&conn->errorMessage,
768 libpq_gettext("could not connect to server: %s\n"
769 "\tIs the server running on host \"%s\" and accepting\n"
770 "\tTCP/IP connections on port %s?\n"),
771 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
772 conn->pghostaddr
773 ? conn->pghostaddr
774 : (conn->pghost
775 ? conn->pghost
776 : "???"),
777 conn->pgport);
782 /* ----------
783 * connectDBStart -
784 * Begin the process of making a connection to the backend.
786 * Returns 1 if successful, 0 if not.
787 * ----------
789 static int
790 connectDBStart(PGconn *conn)
792 int portnum;
793 char portstr[128];
794 struct addrinfo *addrs = NULL;
795 struct addrinfo hint;
796 const char *node;
797 int ret;
799 if (!conn)
800 return 0;
802 if (!conn->options_valid)
803 goto connect_errReturn;
805 /* Ensure our buffers are empty */
806 conn->inStart = conn->inCursor = conn->inEnd = 0;
807 conn->outCount = 0;
810 * Determine the parameters to pass to pg_getaddrinfo_all.
813 /* Initialize hint structure */
814 MemSet(&hint, 0, sizeof(hint));
815 hint.ai_socktype = SOCK_STREAM;
816 hint.ai_family = AF_UNSPEC;
818 /* Set up port number as a string */
819 if (conn->pgport != NULL && conn->pgport[0] != '\0')
820 portnum = atoi(conn->pgport);
821 else
822 portnum = DEF_PGPORT;
823 snprintf(portstr, sizeof(portstr), "%d", portnum);
825 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
827 /* Using pghostaddr avoids a hostname lookup */
828 node = conn->pghostaddr;
829 hint.ai_family = AF_UNSPEC;
830 hint.ai_flags = AI_NUMERICHOST;
832 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
834 /* Using pghost, so we have to look-up the hostname */
835 node = conn->pghost;
836 hint.ai_family = AF_UNSPEC;
838 else
840 #ifdef HAVE_UNIX_SOCKETS
841 /* pghostaddr and pghost are NULL, so use Unix domain socket */
842 node = NULL;
843 hint.ai_family = AF_UNIX;
844 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
845 #else
846 /* Without Unix sockets, default to localhost instead */
847 node = "localhost";
848 hint.ai_family = AF_UNSPEC;
849 #endif /* HAVE_UNIX_SOCKETS */
852 /* Use pg_getaddrinfo_all() to resolve the address */
853 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
854 if (ret || !addrs)
856 if (node)
857 appendPQExpBuffer(&conn->errorMessage,
858 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
859 node, gai_strerror(ret));
860 else
861 appendPQExpBuffer(&conn->errorMessage,
862 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
863 portstr, gai_strerror(ret));
864 if (addrs)
865 pg_freeaddrinfo_all(hint.ai_family, addrs);
866 goto connect_errReturn;
869 #ifdef USE_SSL
870 /* setup values based on SSL mode */
871 if (conn->sslmode[0] == 'd') /* "disable" */
872 conn->allow_ssl_try = false;
873 else if (conn->sslmode[0] == 'a') /* "allow" */
874 conn->wait_ssl_try = true;
875 #endif
878 * Set up to try to connect, with protocol 3.0 as the first attempt.
880 conn->addrlist = addrs;
881 conn->addr_cur = addrs;
882 conn->addrlist_family = hint.ai_family;
883 conn->pversion = PG_PROTOCOL(3, 0);
884 conn->status = CONNECTION_NEEDED;
887 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
888 * so that it can easily be re-executed if needed again during the
889 * asynchronous startup process. However, we must run it once here,
890 * because callers expect a success return from this routine to mean that
891 * we are in PGRES_POLLING_WRITING connection state.
893 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
894 return 1;
896 connect_errReturn:
897 if (conn->sock >= 0)
899 pqsecure_close(conn);
900 closesocket(conn->sock);
901 conn->sock = -1;
903 conn->status = CONNECTION_BAD;
904 return 0;
909 * connectDBComplete
911 * Block and complete a connection.
913 * Returns 1 on success, 0 on failure.
915 static int
916 connectDBComplete(PGconn *conn)
918 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
919 time_t finish_time = ((time_t) -1);
921 if (conn == NULL || conn->status == CONNECTION_BAD)
922 return 0;
925 * Set up a time limit, if connect_timeout isn't zero.
927 if (conn->connect_timeout != NULL)
929 int timeout = atoi(conn->connect_timeout);
931 if (timeout > 0)
934 * Rounding could cause connection to fail; need at least 2 secs
936 if (timeout < 2)
937 timeout = 2;
938 /* calculate the finish time based on start + timeout */
939 finish_time = time(NULL) + timeout;
943 for (;;)
946 * Wait, if necessary. Note that the initial state (just after
947 * PQconnectStart) is to wait for the socket to select for writing.
949 switch (flag)
951 case PGRES_POLLING_OK:
952 /* Reset stored error messages since we now have a working connection */
953 resetPQExpBuffer(&conn->errorMessage);
954 return 1; /* success! */
956 case PGRES_POLLING_READING:
957 if (pqWaitTimed(1, 0, conn, finish_time))
959 conn->status = CONNECTION_BAD;
960 return 0;
962 break;
964 case PGRES_POLLING_WRITING:
965 if (pqWaitTimed(0, 1, conn, finish_time))
967 conn->status = CONNECTION_BAD;
968 return 0;
970 break;
972 default:
973 /* Just in case we failed to set it in PQconnectPoll */
974 conn->status = CONNECTION_BAD;
975 return 0;
979 * Now try to advance the state machine.
981 flag = PQconnectPoll(conn);
985 /* ----------------
986 * PQconnectPoll
988 * Poll an asynchronous connection.
990 * Returns a PostgresPollingStatusType.
991 * Before calling this function, use select(2) to determine when data
992 * has arrived..
994 * You must call PQfinish whether or not this fails.
996 * This function and PQconnectStart are intended to allow connections to be
997 * made without blocking the execution of your program on remote I/O. However,
998 * there are a number of caveats:
1000 * o If you call PQtrace, ensure that the stream object into which you trace
1001 * will not block.
1002 * o If you do not supply an IP address for the remote host (i.e. you
1003 * supply a host name instead) then PQconnectStart will block on
1004 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1005 * supplying neither a host name nor a host address).
1006 * o If your backend wants to use Kerberos authentication then you must
1007 * supply both a host name and a host address, otherwise this function
1008 * may block on gethostname.
1010 * ----------------
1012 PostgresPollingStatusType
1013 PQconnectPoll(PGconn *conn)
1015 PGresult *res;
1016 char sebuf[256];
1018 if (conn == NULL)
1019 return PGRES_POLLING_FAILED;
1021 /* Get the new data */
1022 switch (conn->status)
1025 * We really shouldn't have been polled in these two cases, but we
1026 * can handle it.
1028 case CONNECTION_BAD:
1029 return PGRES_POLLING_FAILED;
1030 case CONNECTION_OK:
1031 return PGRES_POLLING_OK;
1033 /* These are reading states */
1034 case CONNECTION_AWAITING_RESPONSE:
1035 case CONNECTION_AUTH_OK:
1037 /* Load waiting data */
1038 int n = pqReadData(conn);
1040 if (n < 0)
1041 goto error_return;
1042 if (n == 0)
1043 return PGRES_POLLING_READING;
1045 break;
1048 /* These are writing states, so we just proceed. */
1049 case CONNECTION_STARTED:
1050 case CONNECTION_MADE:
1051 break;
1053 /* We allow pqSetenvPoll to decide whether to proceed. */
1054 case CONNECTION_SETENV:
1055 break;
1057 /* Special cases: proceed without waiting. */
1058 case CONNECTION_SSL_STARTUP:
1059 case CONNECTION_NEEDED:
1060 break;
1062 default:
1063 appendPQExpBuffer(&conn->errorMessage,
1064 libpq_gettext(
1065 "invalid connection state, "
1066 "probably indicative of memory corruption\n"
1068 goto error_return;
1072 keep_going: /* We will come back to here until there is
1073 * nothing left to do. */
1074 switch (conn->status)
1076 case CONNECTION_NEEDED:
1079 * Try to initiate a connection to one of the addresses
1080 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1081 * next one to try. We fail when we run out of addresses
1082 * (reporting the error returned for the *last* alternative,
1083 * which may not be what users expect :-().
1085 while (conn->addr_cur != NULL)
1087 struct addrinfo *addr_cur = conn->addr_cur;
1089 /* Remember current address for possible error msg */
1090 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1091 addr_cur->ai_addrlen);
1092 conn->raddr.salen = addr_cur->ai_addrlen;
1094 /* Open a socket */
1095 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1096 if (conn->sock < 0)
1099 * ignore socket() failure if we have more addresses
1100 * to try
1102 if (addr_cur->ai_next != NULL)
1104 conn->addr_cur = addr_cur->ai_next;
1105 continue;
1107 appendPQExpBuffer(&conn->errorMessage,
1108 libpq_gettext("could not create socket: %s\n"),
1109 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1110 break;
1114 * Select socket options: no delay of outgoing data for
1115 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1116 * of this fails.
1118 if (!IS_AF_UNIX(addr_cur->ai_family))
1120 if (!connectNoDelay(conn))
1122 closesocket(conn->sock);
1123 conn->sock = -1;
1124 conn->addr_cur = addr_cur->ai_next;
1125 continue;
1128 if (!pg_set_noblock(conn->sock))
1130 appendPQExpBuffer(&conn->errorMessage,
1131 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1132 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1133 closesocket(conn->sock);
1134 conn->sock = -1;
1135 conn->addr_cur = addr_cur->ai_next;
1136 continue;
1139 #ifdef F_SETFD
1140 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1142 appendPQExpBuffer(&conn->errorMessage,
1143 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1144 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1145 closesocket(conn->sock);
1146 conn->sock = -1;
1147 conn->addr_cur = addr_cur->ai_next;
1148 continue;
1150 #endif /* F_SETFD */
1153 * Start/make connection. This should not block, since we
1154 * are in nonblock mode. If it does, well, too bad.
1156 if (connect(conn->sock, addr_cur->ai_addr,
1157 addr_cur->ai_addrlen) < 0)
1159 if (SOCK_ERRNO == EINPROGRESS ||
1160 SOCK_ERRNO == EWOULDBLOCK ||
1161 SOCK_ERRNO == EINTR ||
1162 SOCK_ERRNO == 0)
1165 * This is fine - we're in non-blocking mode, and
1166 * the connection is in progress. Tell caller to
1167 * wait for write-ready on socket.
1169 conn->status = CONNECTION_STARTED;
1170 return PGRES_POLLING_WRITING;
1172 /* otherwise, trouble */
1174 else
1177 * Hm, we're connected already --- seems the "nonblock
1178 * connection" wasn't. Advance the state machine and
1179 * go do the next stuff.
1181 conn->status = CONNECTION_STARTED;
1182 goto keep_going;
1186 * This connection failed --- set up error report, then
1187 * close socket (do it this way in case close() affects
1188 * the value of errno...). We will ignore the connect()
1189 * failure and keep going if there are more addresses.
1191 connectFailureMessage(conn, SOCK_ERRNO);
1192 if (conn->sock >= 0)
1194 closesocket(conn->sock);
1195 conn->sock = -1;
1199 * Try the next address, if any.
1201 conn->addr_cur = addr_cur->ai_next;
1202 } /* loop over addresses */
1205 * Ooops, no more addresses. An appropriate error message is
1206 * already set up, so just set the right status.
1208 goto error_return;
1211 case CONNECTION_STARTED:
1213 int optval;
1214 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1217 * Write ready, since we've made it here, so the connection
1218 * has been made ... or has failed.
1222 * Now check (using getsockopt) that there is not an error
1223 * state waiting for us on the socket.
1226 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1227 (char *) &optval, &optlen) == -1)
1229 appendPQExpBuffer(&conn->errorMessage,
1230 libpq_gettext("could not get socket error status: %s\n"),
1231 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1232 goto error_return;
1234 else if (optval != 0)
1237 * When using a nonblocking connect, we will typically see
1238 * connect failures at this point, so provide a friendly
1239 * error message.
1241 connectFailureMessage(conn, optval);
1244 * If more addresses remain, keep trying, just as in the
1245 * case where connect() returned failure immediately.
1247 if (conn->addr_cur->ai_next != NULL)
1249 if (conn->sock >= 0)
1251 closesocket(conn->sock);
1252 conn->sock = -1;
1254 conn->addr_cur = conn->addr_cur->ai_next;
1255 conn->status = CONNECTION_NEEDED;
1256 goto keep_going;
1258 goto error_return;
1261 /* Fill in the client address */
1262 conn->laddr.salen = sizeof(conn->laddr.addr);
1263 if (getsockname(conn->sock,
1264 (struct sockaddr *) & conn->laddr.addr,
1265 &conn->laddr.salen) < 0)
1267 appendPQExpBuffer(&conn->errorMessage,
1268 libpq_gettext("could not get client address from socket: %s\n"),
1269 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1270 goto error_return;
1274 * Make sure we can write before advancing to next step.
1276 conn->status = CONNECTION_MADE;
1277 return PGRES_POLLING_WRITING;
1280 case CONNECTION_MADE:
1282 char *startpacket;
1283 int packetlen;
1285 #ifdef USE_SSL
1288 * If SSL is enabled and we haven't already got it running,
1289 * request it instead of sending the startup message.
1291 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1293 /* Don't bother requesting SSL over a Unix socket */
1294 conn->allow_ssl_try = false;
1296 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1297 conn->ssl == NULL)
1299 ProtocolVersion pv;
1302 * Send the SSL request packet.
1304 * Theoretically, this could block, but it really
1305 * shouldn't since we only got here if the socket is
1306 * write-ready.
1308 pv = htonl(NEGOTIATE_SSL_CODE);
1309 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1311 appendPQExpBuffer(&conn->errorMessage,
1312 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1313 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1314 goto error_return;
1316 /* Ok, wait for response */
1317 conn->status = CONNECTION_SSL_STARTUP;
1318 return PGRES_POLLING_READING;
1320 #endif /* USE_SSL */
1323 * Build the startup packet.
1325 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1326 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1327 EnvironmentOptions);
1328 else
1329 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1330 EnvironmentOptions);
1331 if (!startpacket)
1333 /* will not appendbuffer here, since it's likely to also run out of memory */
1334 printfPQExpBuffer(&conn->errorMessage,
1335 libpq_gettext("out of memory\n"));
1336 goto error_return;
1340 * Send the startup packet.
1342 * Theoretically, this could block, but it really shouldn't
1343 * since we only got here if the socket is write-ready.
1345 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1347 appendPQExpBuffer(&conn->errorMessage,
1348 libpq_gettext("could not send startup packet: %s\n"),
1349 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1350 free(startpacket);
1351 goto error_return;
1354 free(startpacket);
1356 conn->status = CONNECTION_AWAITING_RESPONSE;
1357 return PGRES_POLLING_READING;
1361 * Handle SSL negotiation: wait for postmaster messages and
1362 * respond as necessary.
1364 case CONNECTION_SSL_STARTUP:
1366 #ifdef USE_SSL
1367 PostgresPollingStatusType pollres;
1370 * On first time through, get the postmaster's response to our
1371 * SSL negotiation packet.
1373 if (conn->ssl == NULL)
1376 * We use pqReadData here since it has the logic to
1377 * distinguish no-data-yet from connection closure. Since
1378 * conn->ssl isn't set, a plain recv() will occur.
1380 char SSLok;
1381 int rdresult;
1383 rdresult = pqReadData(conn);
1384 if (rdresult < 0)
1386 /* errorMessage is already filled in */
1387 goto error_return;
1389 if (rdresult == 0)
1391 /* caller failed to wait for data */
1392 return PGRES_POLLING_READING;
1394 if (pqGetc(&SSLok, conn) < 0)
1396 /* should not happen really */
1397 return PGRES_POLLING_READING;
1399 /* mark byte consumed */
1400 conn->inStart = conn->inCursor;
1401 if (SSLok == 'S')
1403 /* Set up global SSL state if required */
1404 if (pqsecure_initialize(conn) == -1)
1405 goto error_return;
1407 else if (SSLok == 'N')
1409 if (conn->sslmode[0] == 'r' || /* "require" */
1410 conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1412 /* Require SSL, but server does not want it */
1413 appendPQExpBuffer(&conn->errorMessage,
1414 libpq_gettext("server does not support SSL, but SSL was required\n"));
1415 goto error_return;
1417 /* Otherwise, proceed with normal startup */
1418 conn->allow_ssl_try = false;
1419 conn->status = CONNECTION_MADE;
1420 return PGRES_POLLING_WRITING;
1422 else if (SSLok == 'E')
1424 /* Received error - probably protocol mismatch */
1425 if (conn->Pfdebug)
1426 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1427 if (conn->sslmode[0] == 'r' || /* "require" */
1428 conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1430 /* Require SSL, but server is too old */
1431 appendPQExpBuffer(&conn->errorMessage,
1432 libpq_gettext("server does not support SSL, but SSL was required\n"));
1433 goto error_return;
1435 /* Otherwise, try again without SSL */
1436 conn->allow_ssl_try = false;
1437 /* Assume it ain't gonna handle protocol 3, either */
1438 conn->pversion = PG_PROTOCOL(2, 0);
1439 /* Must drop the old connection */
1440 closesocket(conn->sock);
1441 conn->sock = -1;
1442 conn->status = CONNECTION_NEEDED;
1443 goto keep_going;
1445 else
1447 appendPQExpBuffer(&conn->errorMessage,
1448 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1449 SSLok);
1450 goto error_return;
1455 * Begin or continue the SSL negotiation process.
1457 pollres = pqsecure_open_client(conn);
1458 if (pollres == PGRES_POLLING_OK)
1460 /* SSL handshake done, ready to send startup packet */
1461 conn->status = CONNECTION_MADE;
1462 return PGRES_POLLING_WRITING;
1464 if (pollres == PGRES_POLLING_FAILED)
1467 * Failed ... if sslmode is "prefer" then do a non-SSL
1468 * retry
1470 if (conn->sslmode[0] == 'p' /* "prefer" */
1471 && conn->allow_ssl_try /* redundant? */
1472 && !conn->wait_ssl_try) /* redundant? */
1474 /* only retry once */
1475 conn->allow_ssl_try = false;
1476 /* Must drop the old connection */
1477 closesocket(conn->sock);
1478 conn->sock = -1;
1479 conn->status = CONNECTION_NEEDED;
1480 goto keep_going;
1483 return pollres;
1484 #else /* !USE_SSL */
1485 /* can't get here */
1486 goto error_return;
1487 #endif /* USE_SSL */
1491 * Handle authentication exchange: wait for postmaster messages
1492 * and respond as necessary.
1494 case CONNECTION_AWAITING_RESPONSE:
1496 char beresp;
1497 int msgLength;
1498 int avail;
1499 AuthRequest areq;
1502 * Scan the message from current point (note that if we find
1503 * the message is incomplete, we will return without advancing
1504 * inStart, and resume here next time).
1506 conn->inCursor = conn->inStart;
1508 /* Read type byte */
1509 if (pqGetc(&beresp, conn))
1511 /* We'll come back when there is more data */
1512 return PGRES_POLLING_READING;
1516 * Validate message type: we expect only an authentication
1517 * request or an error here. Anything else probably means
1518 * it's not Postgres on the other end at all.
1520 if (!(beresp == 'R' || beresp == 'E'))
1522 appendPQExpBuffer(&conn->errorMessage,
1523 libpq_gettext(
1524 "expected authentication request from "
1525 "server, but received %c\n"),
1526 beresp);
1527 goto error_return;
1530 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1532 /* Read message length word */
1533 if (pqGetInt(&msgLength, 4, conn))
1535 /* We'll come back when there is more data */
1536 return PGRES_POLLING_READING;
1539 else
1541 /* Set phony message length to disable checks below */
1542 msgLength = 8;
1546 * Try to validate message length before using it.
1547 * Authentication requests can't be very large, although GSS
1548 * auth requests may not be that small. Errors can be a
1549 * little larger, but not huge. If we see a large apparent
1550 * length in an error, it means we're really talking to a
1551 * pre-3.0-protocol server; cope.
1553 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1555 appendPQExpBuffer(&conn->errorMessage,
1556 libpq_gettext(
1557 "expected authentication request from "
1558 "server, but received %c\n"),
1559 beresp);
1560 goto error_return;
1563 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1565 /* Handle error from a pre-3.0 server */
1566 conn->inCursor = conn->inStart + 1; /* reread data */
1567 if (pqGets_append(&conn->errorMessage, conn))
1569 /* We'll come back when there is more data */
1570 return PGRES_POLLING_READING;
1572 /* OK, we read the message; mark data consumed */
1573 conn->inStart = conn->inCursor;
1576 * The postmaster typically won't end its message with a
1577 * newline, so add one to conform to libpq conventions.
1579 appendPQExpBufferChar(&conn->errorMessage, '\n');
1582 * If we tried to open the connection in 3.0 protocol,
1583 * fall back to 2.0 protocol.
1585 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1587 conn->pversion = PG_PROTOCOL(2, 0);
1588 /* Must drop the old connection */
1589 pqsecure_close(conn);
1590 closesocket(conn->sock);
1591 conn->sock = -1;
1592 conn->status = CONNECTION_NEEDED;
1593 goto keep_going;
1596 goto error_return;
1600 * Can't process if message body isn't all here yet.
1602 * (In protocol 2.0 case, we are assuming messages carry at
1603 * least 4 bytes of data.)
1605 msgLength -= 4;
1606 avail = conn->inEnd - conn->inCursor;
1607 if (avail < msgLength)
1610 * Before returning, try to enlarge the input buffer if
1611 * needed to hold the whole message; see notes in
1612 * pqParseInput3.
1614 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1615 conn))
1616 goto error_return;
1617 /* We'll come back when there is more data */
1618 return PGRES_POLLING_READING;
1621 /* Handle errors. */
1622 if (beresp == 'E')
1624 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1626 if (pqGetErrorNotice3(conn, true))
1628 /* We'll come back when there is more data */
1629 return PGRES_POLLING_READING;
1632 else
1634 if (pqGets_append(&conn->errorMessage, conn))
1636 /* We'll come back when there is more data */
1637 return PGRES_POLLING_READING;
1640 /* OK, we read the message; mark data consumed */
1641 conn->inStart = conn->inCursor;
1643 #ifdef USE_SSL
1646 * if sslmode is "allow" and we haven't tried an SSL
1647 * connection already, then retry with an SSL connection
1649 if (conn->sslmode[0] == 'a' /* "allow" */
1650 && conn->ssl == NULL
1651 && conn->allow_ssl_try
1652 && conn->wait_ssl_try)
1654 /* only retry once */
1655 conn->wait_ssl_try = false;
1656 /* Must drop the old connection */
1657 closesocket(conn->sock);
1658 conn->sock = -1;
1659 conn->status = CONNECTION_NEEDED;
1660 goto keep_going;
1664 * if sslmode is "prefer" and we're in an SSL connection,
1665 * then do a non-SSL retry
1667 if (conn->sslmode[0] == 'p' /* "prefer" */
1668 && conn->ssl
1669 && conn->allow_ssl_try /* redundant? */
1670 && !conn->wait_ssl_try) /* redundant? */
1672 /* only retry once */
1673 conn->allow_ssl_try = false;
1674 /* Must drop the old connection */
1675 pqsecure_close(conn);
1676 closesocket(conn->sock);
1677 conn->sock = -1;
1678 conn->status = CONNECTION_NEEDED;
1679 goto keep_going;
1681 #endif
1683 goto error_return;
1686 /* It is an authentication request. */
1687 /* Get the type of request. */
1688 if (pqGetInt((int *) &areq, 4, conn))
1690 /* We'll come back when there are more data */
1691 return PGRES_POLLING_READING;
1694 /* Get the password salt if there is one. */
1695 if (areq == AUTH_REQ_MD5)
1697 if (pqGetnchar(conn->md5Salt,
1698 sizeof(conn->md5Salt), conn))
1700 /* We'll come back when there are more data */
1701 return PGRES_POLLING_READING;
1704 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1707 * Continue GSSAPI/SSPI authentication
1709 if (areq == AUTH_REQ_GSS_CONT)
1711 int llen = msgLength - 4;
1714 * We can be called repeatedly for the same buffer. Avoid
1715 * re-allocating the buffer in this case - just re-use the
1716 * old buffer.
1718 if (llen != conn->ginbuf.length)
1720 if (conn->ginbuf.value)
1721 free(conn->ginbuf.value);
1723 conn->ginbuf.length = llen;
1724 conn->ginbuf.value = malloc(llen);
1725 if (!conn->ginbuf.value)
1727 printfPQExpBuffer(&conn->errorMessage,
1728 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1729 llen);
1730 goto error_return;
1734 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1736 /* We'll come back when there is more data. */
1737 return PGRES_POLLING_READING;
1740 #endif
1743 * OK, we successfully read the message; mark data consumed
1745 conn->inStart = conn->inCursor;
1747 /* Respond to the request if necessary. */
1750 * Note that conn->pghost must be non-NULL if we are going to
1751 * avoid the Kerberos code doing a hostname look-up.
1754 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1756 conn->errorMessage.len = strlen(conn->errorMessage.data);
1757 goto error_return;
1759 conn->errorMessage.len = strlen(conn->errorMessage.data);
1762 * Just make sure that any data sent by pg_fe_sendauth is
1763 * flushed out. Although this theoretically could block, it
1764 * really shouldn't since we don't send large auth responses.
1766 if (pqFlush(conn))
1767 goto error_return;
1769 if (areq == AUTH_REQ_OK)
1771 /* We are done with authentication exchange */
1772 conn->status = CONNECTION_AUTH_OK;
1775 * Set asyncStatus so that PQsetResult will think that
1776 * what comes back next is the result of a query. See
1777 * below.
1779 conn->asyncStatus = PGASYNC_BUSY;
1782 /* Look to see if we have more data yet. */
1783 goto keep_going;
1786 case CONNECTION_AUTH_OK:
1789 * Now we expect to hear from the backend. A ReadyForQuery
1790 * message indicates that startup is successful, but we might
1791 * also get an Error message indicating failure. (Notice
1792 * messages indicating nonfatal warnings are also allowed by
1793 * the protocol, as are ParameterStatus and BackendKeyData
1794 * messages.) Easiest way to handle this is to let
1795 * PQgetResult() read the messages. We just have to fake it
1796 * out about the state of the connection, by setting
1797 * asyncStatus = PGASYNC_BUSY (done above).
1800 if (PQisBusy(conn))
1801 return PGRES_POLLING_READING;
1803 res = PQgetResult(conn);
1806 * NULL return indicating we have gone to IDLE state is
1807 * expected
1809 if (res)
1811 if (res->resultStatus != PGRES_FATAL_ERROR)
1812 appendPQExpBuffer(&conn->errorMessage,
1813 libpq_gettext("unexpected message from server during startup\n"));
1816 * if the resultStatus is FATAL, then conn->errorMessage
1817 * already has a copy of the error; needn't copy it back.
1818 * But add a newline if it's not there already, since
1819 * postmaster error messages may not have one.
1821 if (conn->errorMessage.len <= 0 ||
1822 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1823 appendPQExpBufferChar(&conn->errorMessage, '\n');
1824 PQclear(res);
1825 goto error_return;
1828 /* We can release the address list now. */
1829 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1830 conn->addrlist = NULL;
1831 conn->addr_cur = NULL;
1833 /* Fire up post-connection housekeeping if needed */
1834 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1836 conn->status = CONNECTION_SETENV;
1837 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1838 conn->next_eo = EnvironmentOptions;
1839 return PGRES_POLLING_WRITING;
1842 /* Otherwise, we are open for business! */
1843 conn->status = CONNECTION_OK;
1844 return PGRES_POLLING_OK;
1847 case CONNECTION_SETENV:
1850 * Do post-connection housekeeping (only needed in protocol 2.0).
1852 * We pretend that the connection is OK for the duration of these
1853 * queries.
1855 conn->status = CONNECTION_OK;
1857 switch (pqSetenvPoll(conn))
1859 case PGRES_POLLING_OK: /* Success */
1860 break;
1862 case PGRES_POLLING_READING: /* Still going */
1863 conn->status = CONNECTION_SETENV;
1864 return PGRES_POLLING_READING;
1866 case PGRES_POLLING_WRITING: /* Still going */
1867 conn->status = CONNECTION_SETENV;
1868 return PGRES_POLLING_WRITING;
1870 default:
1871 goto error_return;
1874 /* We are open for business! */
1875 conn->status = CONNECTION_OK;
1876 return PGRES_POLLING_OK;
1878 default:
1879 appendPQExpBuffer(&conn->errorMessage,
1880 libpq_gettext(
1881 "invalid connection state %c, "
1882 "probably indicative of memory corruption\n"
1884 conn->status);
1885 goto error_return;
1888 /* Unreachable */
1890 error_return:
1893 * We used to close the socket at this point, but that makes it awkward
1894 * for those above us if they wish to remove this socket from their own
1895 * records (an fd_set for example). We'll just have this socket closed
1896 * when PQfinish is called (which is compulsory even after an error, since
1897 * the connection structure must be freed).
1899 conn->status = CONNECTION_BAD;
1900 return PGRES_POLLING_FAILED;
1905 * makeEmptyPGconn
1906 * - create a PGconn data structure with (as yet) no interesting data
1908 static PGconn *
1909 makeEmptyPGconn(void)
1911 PGconn *conn;
1913 #ifdef WIN32
1916 * Make sure socket support is up and running.
1918 WSADATA wsaData;
1920 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1921 return NULL;
1922 WSASetLastError(0);
1923 #endif
1925 conn = (PGconn *) malloc(sizeof(PGconn));
1926 if (conn == NULL)
1928 #ifdef WIN32
1929 WSACleanup();
1930 #endif
1931 return conn;
1934 /* Zero all pointers and booleans */
1935 MemSet(conn, 0, sizeof(PGconn));
1937 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
1938 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
1939 conn->status = CONNECTION_BAD;
1940 conn->asyncStatus = PGASYNC_IDLE;
1941 conn->xactStatus = PQTRANS_IDLE;
1942 conn->options_valid = false;
1943 conn->nonblocking = false;
1944 conn->setenv_state = SETENV_STATE_IDLE;
1945 conn->client_encoding = PG_SQL_ASCII;
1946 conn->std_strings = false; /* unless server says differently */
1947 conn->verbosity = PQERRORS_DEFAULT;
1948 conn->sock = -1;
1949 conn->password_needed = false;
1950 #ifdef USE_SSL
1951 conn->allow_ssl_try = true;
1952 conn->wait_ssl_try = false;
1953 #endif
1956 * We try to send at least 8K at a time, which is the usual size of pipe
1957 * buffers on Unix systems. That way, when we are sending a large amount
1958 * of data, we avoid incurring extra kernel context swaps for partial
1959 * bufferloads. The output buffer is initially made 16K in size, and we
1960 * try to dump it after accumulating 8K.
1962 * With the same goal of minimizing context swaps, the input buffer will
1963 * be enlarged anytime it has less than 8K free, so we initially allocate
1964 * twice that.
1966 conn->inBufSize = 16 * 1024;
1967 conn->inBuffer = (char *) malloc(conn->inBufSize);
1968 conn->outBufSize = 16 * 1024;
1969 conn->outBuffer = (char *) malloc(conn->outBufSize);
1970 initPQExpBuffer(&conn->errorMessage);
1971 initPQExpBuffer(&conn->workBuffer);
1973 if (conn->inBuffer == NULL ||
1974 conn->outBuffer == NULL ||
1975 PQExpBufferBroken(&conn->errorMessage) ||
1976 PQExpBufferBroken(&conn->workBuffer))
1978 /* out of memory already :-( */
1979 freePGconn(conn);
1980 conn = NULL;
1983 return conn;
1987 * freePGconn
1988 * - free an idle (closed) PGconn data structure
1990 * NOTE: this should not overlap any functionality with closePGconn().
1991 * Clearing/resetting of transient state belongs there; what we do here is
1992 * release data that is to be held for the life of the PGconn structure.
1993 * If a value ought to be cleared/freed during PQreset(), do it there not here.
1995 static void
1996 freePGconn(PGconn *conn)
1998 int i;
2000 /* let any event procs clean up their state data */
2001 for (i = 0; i < conn->nEvents; i++)
2003 PGEventConnDestroy evt;
2005 evt.conn = conn;
2006 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2007 conn->events[i].passThrough);
2008 free(conn->events[i].name);
2011 if (conn->events)
2012 free(conn->events);
2013 if (conn->pghost)
2014 free(conn->pghost);
2015 if (conn->pghostaddr)
2016 free(conn->pghostaddr);
2017 if (conn->pgport)
2018 free(conn->pgport);
2019 if (conn->pgunixsocket)
2020 free(conn->pgunixsocket);
2021 if (conn->pgtty)
2022 free(conn->pgtty);
2023 if (conn->connect_timeout)
2024 free(conn->connect_timeout);
2025 if (conn->pgoptions)
2026 free(conn->pgoptions);
2027 if (conn->dbName)
2028 free(conn->dbName);
2029 if (conn->pguser)
2030 free(conn->pguser);
2031 if (conn->pgpass)
2032 free(conn->pgpass);
2033 if (conn->sslmode)
2034 free(conn->sslmode);
2035 if (conn->sslcert)
2036 free(conn->sslcert);
2037 if (conn->sslkey)
2038 free(conn->sslkey);
2039 if (conn->sslrootcert)
2040 free(conn->sslrootcert);
2041 if (conn->sslcrl)
2042 free(conn->sslcrl);
2043 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2044 if (conn->krbsrvname)
2045 free(conn->krbsrvname);
2046 #endif
2047 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2048 if (conn->gsslib)
2049 free(conn->gsslib);
2050 #endif
2051 /* Note that conn->Pfdebug is not ours to close or free */
2052 if (conn->last_query)
2053 free(conn->last_query);
2054 if (conn->inBuffer)
2055 free(conn->inBuffer);
2056 if (conn->outBuffer)
2057 free(conn->outBuffer);
2058 termPQExpBuffer(&conn->errorMessage);
2059 termPQExpBuffer(&conn->workBuffer);
2061 free(conn);
2063 #ifdef WIN32
2064 WSACleanup();
2065 #endif
2069 * closePGconn
2070 * - properly close a connection to the backend
2072 * This should reset or release all transient state, but NOT the connection
2073 * parameters. On exit, the PGconn should be in condition to start a fresh
2074 * connection with the same parameters (see PQreset()).
2076 static void
2077 closePGconn(PGconn *conn)
2079 PGnotify *notify;
2080 pgParameterStatus *pstatus;
2083 * Note that the protocol doesn't allow us to send Terminate messages
2084 * during the startup phase.
2086 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2089 * Try to send "close connection" message to backend. Ignore any
2090 * error.
2092 pqPutMsgStart('X', false, conn);
2093 pqPutMsgEnd(conn);
2094 pqFlush(conn);
2098 * Must reset the blocking status so a possible reconnect will work.
2100 * Don't call PQsetnonblocking() because it will fail if it's unable to
2101 * flush the connection.
2103 conn->nonblocking = FALSE;
2106 * Close the connection, reset all transient state, flush I/O buffers.
2108 if (conn->sock >= 0)
2110 pqsecure_close(conn);
2111 closesocket(conn->sock);
2113 conn->sock = -1;
2114 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2115 * absent */
2116 conn->asyncStatus = PGASYNC_IDLE;
2117 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2118 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2119 conn->addrlist = NULL;
2120 conn->addr_cur = NULL;
2121 notify = conn->notifyHead;
2122 while (notify != NULL)
2124 PGnotify *prev = notify;
2126 notify = notify->next;
2127 free(prev);
2129 conn->notifyHead = conn->notifyTail = NULL;
2130 pstatus = conn->pstatus;
2131 while (pstatus != NULL)
2133 pgParameterStatus *prev = pstatus;
2135 pstatus = pstatus->next;
2136 free(prev);
2138 conn->pstatus = NULL;
2139 if (conn->lobjfuncs)
2140 free(conn->lobjfuncs);
2141 conn->lobjfuncs = NULL;
2142 conn->inStart = conn->inCursor = conn->inEnd = 0;
2143 conn->outCount = 0;
2144 #ifdef ENABLE_GSS
2146 OM_uint32 min_s;
2148 if (conn->gctx)
2149 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2150 if (conn->gtarg_nam)
2151 gss_release_name(&min_s, &conn->gtarg_nam);
2152 if (conn->ginbuf.length)
2153 gss_release_buffer(&min_s, &conn->ginbuf);
2154 if (conn->goutbuf.length)
2155 gss_release_buffer(&min_s, &conn->goutbuf);
2157 #endif
2158 #ifdef ENABLE_SSPI
2159 if (conn->ginbuf.length)
2160 free(conn->ginbuf.value);
2161 conn->ginbuf.length = 0;
2162 conn->ginbuf.value = NULL;
2163 if (conn->sspitarget)
2164 free(conn->sspitarget);
2165 conn->sspitarget = NULL;
2166 if (conn->sspicred)
2168 FreeCredentialsHandle(conn->sspicred);
2169 free(conn->sspicred);
2170 conn->sspicred = NULL;
2172 if (conn->sspictx)
2174 DeleteSecurityContext(conn->sspictx);
2175 free(conn->sspictx);
2176 conn->sspictx = NULL;
2178 #endif
2182 * PQfinish: properly close a connection to the backend. Also frees
2183 * the PGconn data structure so it shouldn't be re-used after this.
2185 void
2186 PQfinish(PGconn *conn)
2188 if (conn)
2190 closePGconn(conn);
2191 freePGconn(conn);
2196 * PQreset: resets the connection to the backend by closing the
2197 * existing connection and creating a new one.
2199 void
2200 PQreset(PGconn *conn)
2202 if (conn)
2204 closePGconn(conn);
2206 if (connectDBStart(conn) && connectDBComplete(conn))
2209 * Notify event procs of successful reset. We treat an event
2210 * proc failure as disabling the connection ... good idea?
2212 int i;
2214 for (i = 0; i < conn->nEvents; i++)
2216 PGEventConnReset evt;
2218 evt.conn = conn;
2219 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2220 conn->events[i].passThrough))
2222 conn->status = CONNECTION_BAD;
2223 printfPQExpBuffer(&conn->errorMessage,
2224 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2225 conn->events[i].name);
2226 break;
2235 * PQresetStart:
2236 * resets the connection to the backend
2237 * closes the existing connection and makes a new one
2238 * Returns 1 on success, 0 on failure.
2241 PQresetStart(PGconn *conn)
2243 if (conn)
2245 closePGconn(conn);
2247 return connectDBStart(conn);
2250 return 0;
2255 * PQresetPoll:
2256 * resets the connection to the backend
2257 * closes the existing connection and makes a new one
2259 PostgresPollingStatusType
2260 PQresetPoll(PGconn *conn)
2262 if (conn)
2264 PostgresPollingStatusType status = PQconnectPoll(conn);
2266 if (status == PGRES_POLLING_OK)
2269 * Notify event procs of successful reset. We treat an event
2270 * proc failure as disabling the connection ... good idea?
2272 int i;
2274 for (i = 0; i < conn->nEvents; i++)
2276 PGEventConnReset evt;
2278 evt.conn = conn;
2279 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2280 conn->events[i].passThrough))
2282 conn->status = CONNECTION_BAD;
2283 printfPQExpBuffer(&conn->errorMessage,
2284 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2285 conn->events[i].name);
2286 return PGRES_POLLING_FAILED;
2291 return status;
2294 return PGRES_POLLING_FAILED;
2298 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2300 * A copy is needed to be able to cancel a running query from a different
2301 * thread. If the same structure is used all structure members would have
2302 * to be individually locked (if the entire structure was locked, it would
2303 * be impossible to cancel a synchronous query because the structure would
2304 * have to stay locked for the duration of the query).
2306 PGcancel *
2307 PQgetCancel(PGconn *conn)
2309 PGcancel *cancel;
2311 if (!conn)
2312 return NULL;
2314 if (conn->sock < 0)
2315 return NULL;
2317 cancel = malloc(sizeof(PGcancel));
2318 if (cancel == NULL)
2319 return NULL;
2321 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2322 cancel->be_pid = conn->be_pid;
2323 cancel->be_key = conn->be_key;
2325 return cancel;
2328 /* PQfreeCancel: free a cancel structure */
2329 void
2330 PQfreeCancel(PGcancel *cancel)
2332 if (cancel)
2333 free(cancel);
2338 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2339 * current operation.
2341 * The return value is TRUE if the cancel request was successfully
2342 * dispatched, FALSE if not (in which case an error message is available).
2343 * Note: successful dispatch is no guarantee that there will be any effect at
2344 * the backend. The application must read the operation result as usual.
2346 * CAUTION: we want this routine to be safely callable from a signal handler
2347 * (for example, an application might want to call it in a SIGINT handler).
2348 * This means we cannot use any C library routine that might be non-reentrant.
2349 * malloc/free are often non-reentrant, and anything that might call them is
2350 * just as dangerous. We avoid sprintf here for that reason. Building up
2351 * error messages with strcpy/strcat is tedious but should be quite safe.
2352 * We also save/restore errno in case the signal handler support doesn't.
2354 * internal_cancel() is an internal helper function to make code-sharing
2355 * between the two versions of the cancel function possible.
2357 static int
2358 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2359 char *errbuf, int errbufsize)
2361 int save_errno = SOCK_ERRNO;
2362 int tmpsock = -1;
2363 char sebuf[256];
2364 int maxlen;
2365 struct
2367 uint32 packetlen;
2368 CancelRequestPacket cp;
2369 } crp;
2372 * We need to open a temporary connection to the postmaster. Do this with
2373 * only kernel calls.
2375 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2377 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2378 goto cancel_errReturn;
2380 retry3:
2381 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2382 raddr->salen) < 0)
2384 if (SOCK_ERRNO == EINTR)
2385 /* Interrupted system call - we'll just try again */
2386 goto retry3;
2387 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2388 goto cancel_errReturn;
2392 * We needn't set nonblocking I/O or NODELAY options here.
2395 /* Create and send the cancel request packet. */
2397 crp.packetlen = htonl((uint32) sizeof(crp));
2398 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2399 crp.cp.backendPID = htonl(be_pid);
2400 crp.cp.cancelAuthCode = htonl(be_key);
2402 retry4:
2403 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2405 if (SOCK_ERRNO == EINTR)
2406 /* Interrupted system call - we'll just try again */
2407 goto retry4;
2408 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2409 goto cancel_errReturn;
2413 * Wait for the postmaster to close the connection, which indicates that
2414 * it's processed the request. Without this delay, we might issue another
2415 * command only to find that our cancel zaps that command instead of the
2416 * one we thought we were canceling. Note we don't actually expect this
2417 * read to obtain any data, we are just waiting for EOF to be signaled.
2419 retry5:
2420 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2422 if (SOCK_ERRNO == EINTR)
2423 /* Interrupted system call - we'll just try again */
2424 goto retry5;
2425 /* we ignore other error conditions */
2428 /* All done */
2429 closesocket(tmpsock);
2430 SOCK_ERRNO_SET(save_errno);
2431 return TRUE;
2433 cancel_errReturn:
2436 * Make sure we don't overflow the error buffer. Leave space for the \n at
2437 * the end, and for the terminating zero.
2439 maxlen = errbufsize - strlen(errbuf) - 2;
2440 if (maxlen >= 0)
2442 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2443 maxlen);
2444 strcat(errbuf, "\n");
2446 if (tmpsock >= 0)
2447 closesocket(tmpsock);
2448 SOCK_ERRNO_SET(save_errno);
2449 return FALSE;
2453 * PQcancel: request query cancel
2455 * Returns TRUE if able to send the cancel request, FALSE if not.
2457 * On failure, an error message is stored in *errbuf, which must be of size
2458 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2459 * success return.
2462 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2464 if (!cancel)
2466 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2467 return FALSE;
2470 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2471 errbuf, errbufsize);
2475 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2477 * Returns TRUE if able to send the cancel request, FALSE if not.
2479 * On failure, the error message is saved in conn->errorMessage; this means
2480 * that this can't be used when there might be other active operations on
2481 * the connection object.
2483 * NOTE: error messages will be cut off at the current size of the
2484 * error message buffer, since we dare not try to expand conn->errorMessage!
2487 PQrequestCancel(PGconn *conn)
2489 int r;
2491 /* Check we have an open connection */
2492 if (!conn)
2493 return FALSE;
2495 if (conn->sock < 0)
2497 strlcpy(conn->errorMessage.data,
2498 "PQrequestCancel() -- connection is not open\n",
2499 conn->errorMessage.maxlen);
2500 conn->errorMessage.len = strlen(conn->errorMessage.data);
2502 return FALSE;
2505 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2506 conn->errorMessage.data, conn->errorMessage.maxlen);
2508 if (!r)
2509 conn->errorMessage.len = strlen(conn->errorMessage.data);
2511 return r;
2516 * pqPacketSend() -- convenience routine to send a message to server.
2518 * pack_type: the single-byte message type code. (Pass zero for startup
2519 * packets, which have no message type code.)
2521 * buf, buf_len: contents of message. The given length includes only what
2522 * is in buf; the message type and message length fields are added here.
2524 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2525 * SIDE_EFFECTS: may block.
2527 * Note: all messages sent with this routine have a length word, whether
2528 * it's protocol 2.0 or 3.0.
2531 pqPacketSend(PGconn *conn, char pack_type,
2532 const void *buf, size_t buf_len)
2534 /* Start the message. */
2535 if (pqPutMsgStart(pack_type, true, conn))
2536 return STATUS_ERROR;
2538 /* Send the message body. */
2539 if (pqPutnchar(buf, buf_len, conn))
2540 return STATUS_ERROR;
2542 /* Finish the message. */
2543 if (pqPutMsgEnd(conn))
2544 return STATUS_ERROR;
2546 /* Flush to ensure backend gets it. */
2547 if (pqFlush(conn))
2548 return STATUS_ERROR;
2550 return STATUS_OK;
2553 #ifdef USE_LDAP
2555 #define LDAP_URL "ldap://"
2556 #define LDAP_DEF_PORT 389
2557 #define PGLDAP_TIMEOUT 2
2559 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2560 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2564 * ldapServiceLookup
2566 * Search the LDAP URL passed as first argument, treat the result as a
2567 * string of connection options that are parsed and added to the array of
2568 * options passed as second argument.
2570 * LDAP URLs must conform to RFC 1959 without escape sequences.
2571 * ldap://host:port/dn?attributes?scope?filter?extensions
2573 * Returns
2574 * 0 if the lookup was successful,
2575 * 1 if the connection to the LDAP server could be established but
2576 * the search was unsuccessful,
2577 * 2 if a connection could not be established, and
2578 * 3 if a fatal error occurred.
2580 * An error message is returned in the third argument for return codes 1 and 3.
2582 static int
2583 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2584 PQExpBuffer errorMessage)
2586 int port = LDAP_DEF_PORT,
2587 scope,
2589 msgid,
2590 size,
2591 state,
2592 oldstate,
2594 bool found_keyword;
2595 char *url,
2596 *hostname,
2597 *portstr,
2598 *endptr,
2599 *dn,
2600 *scopestr,
2601 *filter,
2602 *result,
2604 *p1 = NULL,
2605 *optname = NULL,
2606 *optval = NULL;
2607 char *attrs[2] = {NULL, NULL};
2608 LDAP *ld = NULL;
2609 LDAPMessage *res,
2610 *entry;
2611 struct berval **values;
2612 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2614 if ((url = strdup(purl)) == NULL)
2616 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2617 return 3;
2621 * Parse URL components, check for correctness. Basically, url has '\0'
2622 * placed at component boundaries and variables are pointed at each
2623 * component.
2626 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2628 printfPQExpBuffer(errorMessage,
2629 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2630 free(url);
2631 return 3;
2634 /* hostname */
2635 hostname = url + strlen(LDAP_URL);
2636 if (*hostname == '/') /* no hostname? */
2637 hostname = "localhost"; /* the default */
2639 /* dn, "distinguished name" */
2640 p = strchr(url + strlen(LDAP_URL), '/');
2641 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2643 printfPQExpBuffer(errorMessage, libpq_gettext(
2644 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2645 free(url);
2646 return 3;
2648 *p = '\0'; /* terminate hostname */
2649 dn = p + 1;
2651 /* attribute */
2652 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2654 printfPQExpBuffer(errorMessage, libpq_gettext(
2655 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2656 free(url);
2657 return 3;
2659 *p = '\0';
2660 attrs[0] = p + 1;
2662 /* scope */
2663 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2665 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2666 free(url);
2667 return 3;
2669 *p = '\0';
2670 scopestr = p + 1;
2672 /* filter */
2673 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2675 printfPQExpBuffer(errorMessage,
2676 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2677 free(url);
2678 return 3;
2680 *p = '\0';
2681 filter = p + 1;
2682 if ((p = strchr(filter, '?')) != NULL)
2683 *p = '\0';
2685 /* port number? */
2686 if ((p1 = strchr(hostname, ':')) != NULL)
2688 long lport;
2690 *p1 = '\0';
2691 portstr = p1 + 1;
2692 errno = 0;
2693 lport = strtol(portstr, &endptr, 10);
2694 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2696 printfPQExpBuffer(errorMessage, libpq_gettext(
2697 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2698 free(url);
2699 return 3;
2701 port = (int) lport;
2704 /* Allow only one attribute */
2705 if (strchr(attrs[0], ',') != NULL)
2707 printfPQExpBuffer(errorMessage, libpq_gettext(
2708 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2709 free(url);
2710 return 3;
2713 /* set scope */
2714 if (pg_strcasecmp(scopestr, "base") == 0)
2715 scope = LDAP_SCOPE_BASE;
2716 else if (pg_strcasecmp(scopestr, "one") == 0)
2717 scope = LDAP_SCOPE_ONELEVEL;
2718 else if (pg_strcasecmp(scopestr, "sub") == 0)
2719 scope = LDAP_SCOPE_SUBTREE;
2720 else
2722 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2723 free(url);
2724 return 3;
2727 /* initialize LDAP structure */
2728 if ((ld = ldap_init(hostname, port)) == NULL)
2730 printfPQExpBuffer(errorMessage,
2731 libpq_gettext("could not create LDAP structure\n"));
2732 free(url);
2733 return 3;
2737 * Initialize connection to the server. We do an explicit bind because we
2738 * want to return 2 if the bind fails.
2740 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
2742 /* error in ldap_simple_bind() */
2743 free(url);
2744 ldap_unbind(ld);
2745 return 2;
2748 /* wait some time for the connection to succeed */
2749 res = NULL;
2750 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
2751 res == NULL)
2753 if (res != NULL)
2755 /* timeout */
2756 ldap_msgfree(res);
2758 /* error in ldap_result() */
2759 free(url);
2760 ldap_unbind(ld);
2761 return 2;
2763 ldap_msgfree(res);
2765 /* search */
2766 res = NULL;
2767 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
2768 != LDAP_SUCCESS)
2770 if (res != NULL)
2771 ldap_msgfree(res);
2772 printfPQExpBuffer(errorMessage,
2773 libpq_gettext("lookup on LDAP server failed: %s\n"),
2774 ldap_err2string(rc));
2775 ldap_unbind(ld);
2776 free(url);
2777 return 1;
2780 /* complain if there was not exactly one result */
2781 if ((rc = ldap_count_entries(ld, res)) != 1)
2783 printfPQExpBuffer(errorMessage,
2784 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
2785 : libpq_gettext("no entry found on LDAP lookup\n"));
2786 ldap_msgfree(res);
2787 ldap_unbind(ld);
2788 free(url);
2789 return 1;
2792 /* get entry */
2793 if ((entry = ldap_first_entry(ld, res)) == NULL)
2795 /* should never happen */
2796 printfPQExpBuffer(errorMessage,
2797 libpq_gettext("no entry found on LDAP lookup\n"));
2798 ldap_msgfree(res);
2799 ldap_unbind(ld);
2800 free(url);
2801 return 1;
2804 /* get values */
2805 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
2807 printfPQExpBuffer(errorMessage,
2808 libpq_gettext("attribute has no values on LDAP lookup\n"));
2809 ldap_msgfree(res);
2810 ldap_unbind(ld);
2811 free(url);
2812 return 1;
2815 ldap_msgfree(res);
2816 free(url);
2818 if (values[0] == NULL)
2820 printfPQExpBuffer(errorMessage,
2821 libpq_gettext("attribute has no values on LDAP lookup\n"));
2822 ldap_value_free_len(values);
2823 ldap_unbind(ld);
2824 return 1;
2827 /* concatenate values to a single string */
2828 for (size = 0, i = 0; values[i] != NULL; ++i)
2829 size += values[i]->bv_len + 1;
2830 if ((result = malloc(size + 1)) == NULL)
2832 printfPQExpBuffer(errorMessage,
2833 libpq_gettext("out of memory\n"));
2834 ldap_value_free_len(values);
2835 ldap_unbind(ld);
2836 return 3;
2838 for (p = result, i = 0; values[i] != NULL; ++i)
2840 strncpy(p, values[i]->bv_val, values[i]->bv_len);
2841 p += values[i]->bv_len;
2842 *(p++) = '\n';
2843 if (values[i + 1] == NULL)
2844 *(p + 1) = '\0';
2847 ldap_value_free_len(values);
2848 ldap_unbind(ld);
2850 /* parse result string */
2851 oldstate = state = 0;
2852 for (p = result; *p != '\0'; ++p)
2854 switch (state)
2856 case 0: /* between entries */
2857 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
2859 optname = p;
2860 state = 1;
2862 break;
2863 case 1: /* in option name */
2864 if (ld_is_sp_tab(*p))
2866 *p = '\0';
2867 state = 2;
2869 else if (ld_is_nl_cr(*p))
2871 printfPQExpBuffer(errorMessage, libpq_gettext(
2872 "missing \"=\" after \"%s\" in connection info string\n"),
2873 optname);
2874 return 3;
2876 else if (*p == '=')
2878 *p = '\0';
2879 state = 3;
2881 break;
2882 case 2: /* after option name */
2883 if (*p == '=')
2885 state = 3;
2887 else if (!ld_is_sp_tab(*p))
2889 printfPQExpBuffer(errorMessage, libpq_gettext(
2890 "missing \"=\" after \"%s\" in connection info string\n"),
2891 optname);
2892 return 3;
2894 break;
2895 case 3: /* before option value */
2896 if (*p == '\'')
2898 optval = p + 1;
2899 p1 = p + 1;
2900 state = 5;
2902 else if (ld_is_nl_cr(*p))
2904 optval = optname + strlen(optname); /* empty */
2905 state = 0;
2907 else if (!ld_is_sp_tab(*p))
2909 optval = p;
2910 state = 4;
2912 break;
2913 case 4: /* in unquoted option value */
2914 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
2916 *p = '\0';
2917 state = 0;
2919 break;
2920 case 5: /* in quoted option value */
2921 if (*p == '\'')
2923 *p1 = '\0';
2924 state = 0;
2926 else if (*p == '\\')
2927 state = 6;
2928 else
2929 *(p1++) = *p;
2930 break;
2931 case 6: /* in quoted option value after escape */
2932 *(p1++) = *p;
2933 state = 5;
2934 break;
2937 if (state == 0 && oldstate != 0)
2939 found_keyword = false;
2940 for (i = 0; options[i].keyword; i++)
2942 if (strcmp(options[i].keyword, optname) == 0)
2944 if (options[i].val == NULL)
2945 options[i].val = strdup(optval);
2946 found_keyword = true;
2947 break;
2950 if (!found_keyword)
2952 printfPQExpBuffer(errorMessage,
2953 libpq_gettext("invalid connection option \"%s\"\n"),
2954 optname);
2955 return 1;
2957 optname = NULL;
2958 optval = NULL;
2960 oldstate = state;
2963 if (state == 5 || state == 6)
2965 printfPQExpBuffer(errorMessage, libpq_gettext(
2966 "unterminated quoted string in connection info string\n"));
2967 return 3;
2970 return 0;
2972 #endif
2974 #define MAXBUFSIZE 256
2976 static int
2977 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2979 char *service = conninfo_getval(options, "service");
2980 char serviceFile[MAXPGPATH];
2981 bool group_found = false;
2982 int linenr = 0,
2986 * We have to special-case the environment variable PGSERVICE here, since
2987 * this is and should be called before inserting environment defaults for
2988 * other connection options.
2990 if (service == NULL)
2991 service = getenv("PGSERVICE");
2994 * This could be used by any application so we can't use the binary
2995 * location to find our config files.
2997 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
2998 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3000 if (service != NULL)
3002 FILE *f;
3003 char buf[MAXBUFSIZE],
3004 *line;
3006 f = fopen(serviceFile, "r");
3007 if (f == NULL)
3009 printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: service file \"%s\" not found\n"),
3010 serviceFile);
3011 return 1;
3014 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3016 linenr++;
3018 if (strlen(line) >= sizeof(buf) - 1)
3020 fclose(f);
3021 printfPQExpBuffer(errorMessage,
3022 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
3023 linenr,
3024 serviceFile);
3025 return 2;
3028 /* ignore EOL at end of line */
3029 if (strlen(line) && line[strlen(line) - 1] == '\n')
3030 line[strlen(line) - 1] = 0;
3032 /* ignore leading blanks */
3033 while (*line && isspace((unsigned char) line[0]))
3034 line++;
3036 /* ignore comments and empty lines */
3037 if (strlen(line) == 0 || line[0] == '#')
3038 continue;
3040 /* Check for right groupname */
3041 if (line[0] == '[')
3043 if (group_found)
3045 /* group info already read */
3046 fclose(f);
3047 return 0;
3050 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3051 line[strlen(service) + 1] == ']')
3052 group_found = true;
3053 else
3054 group_found = false;
3056 else
3058 if (group_found)
3061 * Finally, we are in the right group and can parse the
3062 * line
3064 char *key,
3065 *val;
3066 bool found_keyword;
3068 #ifdef USE_LDAP
3069 if (strncmp(line, "ldap", 4) == 0)
3071 int rc = ldapServiceLookup(line, options, errorMessage);
3073 /* if rc = 2, go on reading for fallback */
3074 switch (rc)
3076 case 0:
3077 fclose(f);
3078 return 0;
3079 case 1:
3080 case 3:
3081 fclose(f);
3082 return 3;
3083 case 2:
3084 continue;
3087 #endif
3089 key = line;
3090 val = strchr(line, '=');
3091 if (val == NULL)
3093 printfPQExpBuffer(errorMessage,
3094 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3095 serviceFile,
3096 linenr);
3097 fclose(f);
3098 return 3;
3100 *val++ = '\0';
3103 * Set the parameter --- but don't override any previous
3104 * explicit setting.
3106 found_keyword = false;
3107 for (i = 0; options[i].keyword; i++)
3109 if (strcmp(options[i].keyword, key) == 0)
3111 if (options[i].val == NULL)
3112 options[i].val = strdup(val);
3113 found_keyword = true;
3114 break;
3118 if (!found_keyword)
3120 printfPQExpBuffer(errorMessage,
3121 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3122 serviceFile,
3123 linenr);
3124 fclose(f);
3125 return 3;
3131 fclose(f);
3134 return 0;
3139 * PQconninfoParse
3141 * Parse a string like PQconnectdb() would do and return the
3142 * resulting connection options array. NULL is returned on failure.
3143 * The result contains only options specified directly in the string,
3144 * not any possible default values.
3146 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3147 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3148 * both *errmsg and the result could be NULL.
3150 * NOTE: the returned array is dynamically allocated and should
3151 * be freed when no longer needed via PQconninfoFree().
3153 PQconninfoOption *
3154 PQconninfoParse(const char *conninfo, char **errmsg)
3156 PQExpBufferData errorBuf;
3157 PQconninfoOption *connOptions;
3159 if (errmsg)
3160 *errmsg = NULL; /* default */
3161 initPQExpBuffer(&errorBuf);
3162 if (PQExpBufferBroken(&errorBuf))
3163 return NULL; /* out of memory already :-( */
3164 connOptions = conninfo_parse(conninfo, &errorBuf, false);
3165 if (connOptions == NULL && errmsg)
3166 *errmsg = errorBuf.data;
3167 else
3168 termPQExpBuffer(&errorBuf);
3169 return connOptions;
3173 * Conninfo parser routine
3175 * If successful, a malloc'd PQconninfoOption array is returned.
3176 * If not successful, NULL is returned and an error message is
3177 * left in errorMessage.
3178 * Defaults are supplied (from a service file, environment variables, etc)
3179 * for unspecified options, but only if use_defaults is TRUE.
3181 static PQconninfoOption *
3182 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3183 bool use_defaults)
3185 char *pname;
3186 char *pval;
3187 char *buf;
3188 char *tmp;
3189 char *cp;
3190 char *cp2;
3191 PQconninfoOption *options;
3192 PQconninfoOption *option;
3194 /* Make a working copy of PQconninfoOptions */
3195 options = malloc(sizeof(PQconninfoOptions));
3196 if (options == NULL)
3198 printfPQExpBuffer(errorMessage,
3199 libpq_gettext("out of memory\n"));
3200 return NULL;
3202 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3204 /* Need a modifiable copy of the input string */
3205 if ((buf = strdup(conninfo)) == NULL)
3207 printfPQExpBuffer(errorMessage,
3208 libpq_gettext("out of memory\n"));
3209 PQconninfoFree(options);
3210 return NULL;
3212 cp = buf;
3214 while (*cp)
3216 /* Skip blanks before the parameter name */
3217 if (isspace((unsigned char) *cp))
3219 cp++;
3220 continue;
3223 /* Get the parameter name */
3224 pname = cp;
3225 while (*cp)
3227 if (*cp == '=')
3228 break;
3229 if (isspace((unsigned char) *cp))
3231 *cp++ = '\0';
3232 while (*cp)
3234 if (!isspace((unsigned char) *cp))
3235 break;
3236 cp++;
3238 break;
3240 cp++;
3243 /* Check that there is a following '=' */
3244 if (*cp != '=')
3246 printfPQExpBuffer(errorMessage,
3247 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3248 pname);
3249 PQconninfoFree(options);
3250 free(buf);
3251 return NULL;
3253 *cp++ = '\0';
3255 /* Skip blanks after the '=' */
3256 while (*cp)
3258 if (!isspace((unsigned char) *cp))
3259 break;
3260 cp++;
3263 /* Get the parameter value */
3264 pval = cp;
3266 if (*cp != '\'')
3268 cp2 = pval;
3269 while (*cp)
3271 if (isspace((unsigned char) *cp))
3273 *cp++ = '\0';
3274 break;
3276 if (*cp == '\\')
3278 cp++;
3279 if (*cp != '\0')
3280 *cp2++ = *cp++;
3282 else
3283 *cp2++ = *cp++;
3285 *cp2 = '\0';
3287 else
3289 cp2 = pval;
3290 cp++;
3291 for (;;)
3293 if (*cp == '\0')
3295 printfPQExpBuffer(errorMessage,
3296 libpq_gettext("unterminated quoted string in connection info string\n"));
3297 PQconninfoFree(options);
3298 free(buf);
3299 return NULL;
3301 if (*cp == '\\')
3303 cp++;
3304 if (*cp != '\0')
3305 *cp2++ = *cp++;
3306 continue;
3308 if (*cp == '\'')
3310 *cp2 = '\0';
3311 cp++;
3312 break;
3314 *cp2++ = *cp++;
3319 * Now we have the name and the value. Search for the param record.
3321 for (option = options; option->keyword != NULL; option++)
3323 if (strcmp(option->keyword, pname) == 0)
3324 break;
3326 if (option->keyword == NULL)
3328 printfPQExpBuffer(errorMessage,
3329 libpq_gettext("invalid connection option \"%s\"\n"),
3330 pname);
3331 PQconninfoFree(options);
3332 free(buf);
3333 return NULL;
3337 * Store the value
3339 if (option->val)
3340 free(option->val);
3341 option->val = strdup(pval);
3342 if (!option->val)
3344 printfPQExpBuffer(errorMessage,
3345 libpq_gettext("out of memory\n"));
3346 PQconninfoFree(options);
3347 free(buf);
3348 return NULL;
3352 /* Done with the modifiable input string */
3353 free(buf);
3356 * Stop here if caller doesn't want defaults filled in.
3358 if (!use_defaults)
3359 return options;
3362 * If there's a service spec, use it to obtain any not-explicitly-given
3363 * parameters.
3365 if (parseServiceInfo(options, errorMessage))
3367 PQconninfoFree(options);
3368 return NULL;
3372 * Get the fallback resources for parameters not specified in the conninfo
3373 * string nor the service.
3375 for (option = options; option->keyword != NULL; option++)
3377 if (option->val != NULL)
3378 continue; /* Value was in conninfo or service */
3381 * Try to get the environment variable fallback
3383 if (option->envvar != NULL)
3385 if ((tmp = getenv(option->envvar)) != NULL)
3387 option->val = strdup(tmp);
3388 if (!option->val)
3390 printfPQExpBuffer(errorMessage,
3391 libpq_gettext("out of memory\n"));
3392 PQconninfoFree(options);
3393 return NULL;
3395 continue;
3400 * No environment variable specified or this one isn't set - try
3401 * compiled in
3403 if (option->compiled != NULL)
3405 option->val = strdup(option->compiled);
3406 if (!option->val)
3408 printfPQExpBuffer(errorMessage,
3409 libpq_gettext("out of memory\n"));
3410 PQconninfoFree(options);
3411 return NULL;
3413 continue;
3417 * Special handling for user
3419 if (strcmp(option->keyword, "user") == 0)
3421 option->val = pg_fe_getauthname(errorMessage);
3422 continue;
3426 return options;
3430 static char *
3431 conninfo_getval(PQconninfoOption *connOptions,
3432 const char *keyword)
3434 PQconninfoOption *option;
3436 for (option = connOptions; option->keyword != NULL; option++)
3438 if (strcmp(option->keyword, keyword) == 0)
3439 return option->val;
3442 return NULL;
3446 void
3447 PQconninfoFree(PQconninfoOption *connOptions)
3449 PQconninfoOption *option;
3451 if (connOptions == NULL)
3452 return;
3454 for (option = connOptions; option->keyword != NULL; option++)
3456 if (option->val != NULL)
3457 free(option->val);
3459 free(connOptions);
3463 /* =========== accessor functions for PGconn ========= */
3464 char *
3465 PQdb(const PGconn *conn)
3467 if (!conn)
3468 return NULL;
3469 return conn->dbName;
3472 char *
3473 PQuser(const PGconn *conn)
3475 if (!conn)
3476 return NULL;
3477 return conn->pguser;
3480 char *
3481 PQpass(const PGconn *conn)
3483 if (!conn)
3484 return NULL;
3485 return conn->pgpass;
3488 char *
3489 PQhost(const PGconn *conn)
3491 if (!conn)
3492 return NULL;
3493 return conn->pghost ? conn->pghost : conn->pgunixsocket;
3496 char *
3497 PQport(const PGconn *conn)
3499 if (!conn)
3500 return NULL;
3501 return conn->pgport;
3504 char *
3505 PQtty(const PGconn *conn)
3507 if (!conn)
3508 return NULL;
3509 return conn->pgtty;
3512 char *
3513 PQoptions(const PGconn *conn)
3515 if (!conn)
3516 return NULL;
3517 return conn->pgoptions;
3520 ConnStatusType
3521 PQstatus(const PGconn *conn)
3523 if (!conn)
3524 return CONNECTION_BAD;
3525 return conn->status;
3528 PGTransactionStatusType
3529 PQtransactionStatus(const PGconn *conn)
3531 if (!conn || conn->status != CONNECTION_OK)
3532 return PQTRANS_UNKNOWN;
3533 if (conn->asyncStatus != PGASYNC_IDLE)
3534 return PQTRANS_ACTIVE;
3535 return conn->xactStatus;
3538 const char *
3539 PQparameterStatus(const PGconn *conn, const char *paramName)
3541 const pgParameterStatus *pstatus;
3543 if (!conn || !paramName)
3544 return NULL;
3545 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
3547 if (strcmp(pstatus->name, paramName) == 0)
3548 return pstatus->value;
3550 return NULL;
3554 PQprotocolVersion(const PGconn *conn)
3556 if (!conn)
3557 return 0;
3558 if (conn->status == CONNECTION_BAD)
3559 return 0;
3560 return PG_PROTOCOL_MAJOR(conn->pversion);
3564 PQserverVersion(const PGconn *conn)
3566 if (!conn)
3567 return 0;
3568 if (conn->status == CONNECTION_BAD)
3569 return 0;
3570 return conn->sversion;
3573 char *
3574 PQerrorMessage(const PGconn *conn)
3576 if (!conn)
3577 return libpq_gettext("connection pointer is NULL\n");
3579 return conn->errorMessage.data;
3583 PQsocket(const PGconn *conn)
3585 if (!conn)
3586 return -1;
3587 return conn->sock;
3591 PQbackendPID(const PGconn *conn)
3593 if (!conn || conn->status != CONNECTION_OK)
3594 return 0;
3595 return conn->be_pid;
3599 PQconnectionNeedsPassword(const PGconn *conn)
3601 if (!conn)
3602 return false;
3603 if (conn->password_needed &&
3604 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
3605 return true;
3606 else
3607 return false;
3611 PQconnectionUsedPassword(const PGconn *conn)
3613 if (!conn)
3614 return false;
3615 if (conn->password_needed)
3616 return true;
3617 else
3618 return false;
3622 PQclientEncoding(const PGconn *conn)
3624 if (!conn || conn->status != CONNECTION_OK)
3625 return -1;
3626 return conn->client_encoding;
3630 PQsetClientEncoding(PGconn *conn, const char *encoding)
3632 char qbuf[128];
3633 static const char query[] = "set client_encoding to '%s'";
3634 PGresult *res;
3635 int status;
3637 if (!conn || conn->status != CONNECTION_OK)
3638 return -1;
3640 if (!encoding)
3641 return -1;
3643 /* check query buffer overflow */
3644 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
3645 return -1;
3647 /* ok, now send a query */
3648 sprintf(qbuf, query, encoding);
3649 res = PQexec(conn, qbuf);
3651 if (res == NULL)
3652 return -1;
3653 if (res->resultStatus != PGRES_COMMAND_OK)
3654 status = -1;
3655 else
3658 * In protocol 2 we have to assume the setting will stick, and adjust
3659 * our state immediately. In protocol 3 and up we can rely on the
3660 * backend to report the parameter value, and we'll change state at
3661 * that time.
3663 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3664 pqSaveParameterStatus(conn, "client_encoding", encoding);
3665 status = 0; /* everything is ok */
3667 PQclear(res);
3668 return status;
3671 PGVerbosity
3672 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
3674 PGVerbosity old;
3676 if (!conn)
3677 return PQERRORS_DEFAULT;
3678 old = conn->verbosity;
3679 conn->verbosity = verbosity;
3680 return old;
3683 void
3684 PQtrace(PGconn *conn, FILE *debug_port)
3686 if (conn == NULL)
3687 return;
3688 PQuntrace(conn);
3689 conn->Pfdebug = debug_port;
3692 void
3693 PQuntrace(PGconn *conn)
3695 if (conn == NULL)
3696 return;
3697 if (conn->Pfdebug)
3699 fflush(conn->Pfdebug);
3700 conn->Pfdebug = NULL;
3704 PQnoticeReceiver
3705 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
3707 PQnoticeReceiver old;
3709 if (conn == NULL)
3710 return NULL;
3712 old = conn->noticeHooks.noticeRec;
3713 if (proc)
3715 conn->noticeHooks.noticeRec = proc;
3716 conn->noticeHooks.noticeRecArg = arg;
3718 return old;
3721 PQnoticeProcessor
3722 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3724 PQnoticeProcessor old;
3726 if (conn == NULL)
3727 return NULL;
3729 old = conn->noticeHooks.noticeProc;
3730 if (proc)
3732 conn->noticeHooks.noticeProc = proc;
3733 conn->noticeHooks.noticeProcArg = arg;
3735 return old;
3739 * The default notice message receiver just gets the standard notice text
3740 * and sends it to the notice processor. This two-level setup exists
3741 * mostly for backwards compatibility; perhaps we should deprecate use of
3742 * PQsetNoticeProcessor?
3744 static void
3745 defaultNoticeReceiver(void *arg, const PGresult *res)
3747 (void) arg; /* not used */
3748 if (res->noticeHooks.noticeProc != NULL)
3749 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
3750 PQresultErrorMessage(res));
3754 * The default notice message processor just prints the
3755 * message on stderr. Applications can override this if they
3756 * want the messages to go elsewhere (a window, for example).
3757 * Note that simply discarding notices is probably a bad idea.
3759 static void
3760 defaultNoticeProcessor(void *arg, const char *message)
3762 (void) arg; /* not used */
3763 /* Note: we expect the supplied string to end with a newline already. */
3764 fprintf(stderr, "%s", message);
3768 * returns a pointer to the next token or NULL if the current
3769 * token doesn't match
3771 static char *
3772 pwdfMatchesString(char *buf, char *token)
3774 char *tbuf,
3775 *ttok;
3776 bool bslash = false;
3778 if (buf == NULL || token == NULL)
3779 return NULL;
3780 tbuf = buf;
3781 ttok = token;
3782 if (tbuf[0] == '*' && tbuf[1] == ':')
3783 return tbuf + 2;
3784 while (*tbuf != 0)
3786 if (*tbuf == '\\' && !bslash)
3788 tbuf++;
3789 bslash = true;
3791 if (*tbuf == ':' && *ttok == 0 && !bslash)
3792 return tbuf + 1;
3793 bslash = false;
3794 if (*ttok == 0)
3795 return NULL;
3796 if (*tbuf == *ttok)
3798 tbuf++;
3799 ttok++;
3801 else
3802 return NULL;
3804 return NULL;
3807 /* Get a password from the password file. Return value is malloc'd. */
3808 static char *
3809 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3811 FILE *fp;
3812 char pgpassfile[MAXPGPATH];
3813 struct stat stat_buf;
3814 char *passfile_env;
3816 #define LINELEN NAMEDATALEN*5
3817 char buf[LINELEN];
3819 if (dbname == NULL || strlen(dbname) == 0)
3820 return NULL;
3822 if (username == NULL || strlen(username) == 0)
3823 return NULL;
3825 /* 'localhost' matches pghost of '' or the default socket directory */
3826 if (hostname == NULL)
3827 hostname = DefaultHost;
3828 else if (is_absolute_path(hostname))
3831 * We should probably use canonicalize_path(), but then we have to
3832 * bring path.c into libpq, and it doesn't seem worth it.
3834 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
3835 hostname = DefaultHost;
3837 if (port == NULL)
3838 port = DEF_PGPORT_STR;
3840 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
3841 /* use the literal path from the environment, if set */
3842 strlcpy(pgpassfile, passfile_env, sizeof(pgpassfile));
3843 else
3845 char homedir[MAXPGPATH];
3847 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3848 return NULL;
3849 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
3852 /* If password file cannot be opened, ignore it. */
3853 if (stat(pgpassfile, &stat_buf) != 0)
3854 return NULL;
3856 #ifndef WIN32
3857 if (!S_ISREG(stat_buf.st_mode))
3859 fprintf(stderr,
3860 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3861 pgpassfile);
3862 return NULL;
3865 /* If password file is insecure, alert the user and ignore it. */
3866 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
3868 fprintf(stderr,
3869 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
3870 pgpassfile);
3871 return NULL;
3873 #else
3876 * On Win32, the directory is protected, so we don't have to check the
3877 * file.
3879 #endif
3881 fp = fopen(pgpassfile, "r");
3882 if (fp == NULL)
3883 return NULL;
3885 while (!feof(fp))
3887 char *t = buf,
3888 *ret;
3889 int len;
3891 fgets(buf, sizeof(buf), fp);
3893 len = strlen(buf);
3894 if (len == 0)
3895 continue;
3897 /* Remove trailing newline */
3898 if (buf[len - 1] == '\n')
3899 buf[len - 1] = 0;
3901 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
3902 (t = pwdfMatchesString(t, port)) == NULL ||
3903 (t = pwdfMatchesString(t, dbname)) == NULL ||
3904 (t = pwdfMatchesString(t, username)) == NULL)
3905 continue;
3906 ret = strdup(t);
3907 fclose(fp);
3908 return ret;
3911 fclose(fp);
3912 return NULL;
3914 #undef LINELEN
3918 * Obtain user's home directory, return in given buffer
3920 * On Unix, this actually returns the user's home directory. On Windows
3921 * it returns the PostgreSQL-specific application data folder.
3923 * This is essentially the same as get_home_path(), but we don't use that
3924 * because we don't want to pull path.c into libpq (it pollutes application
3925 * namespace)
3927 bool
3928 pqGetHomeDirectory(char *buf, int bufsize)
3930 #ifndef WIN32
3931 char pwdbuf[BUFSIZ];
3932 struct passwd pwdstr;
3933 struct passwd *pwd = NULL;
3935 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
3936 return false;
3937 strlcpy(buf, pwd->pw_dir, bufsize);
3938 return true;
3939 #else
3940 char tmppath[MAX_PATH];
3942 ZeroMemory(tmppath, sizeof(tmppath));
3943 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3944 return false;
3945 snprintf(buf, bufsize, "%s/postgresql", tmppath);
3946 return true;
3947 #endif
3951 * To keep the API consistent, the locking stubs are always provided, even
3952 * if they are not required.
3955 static void
3956 default_threadlock(int acquire)
3958 #ifdef ENABLE_THREAD_SAFETY
3959 #ifndef WIN32
3960 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
3961 #else
3962 static pthread_mutex_t singlethread_lock = NULL;
3963 static long mutex_initlock = 0;
3965 if (singlethread_lock == NULL)
3967 while (InterlockedExchange(&mutex_initlock, 1) == 1)
3968 /* loop, another thread own the lock */ ;
3969 if (singlethread_lock == NULL)
3971 if (pthread_mutex_init(&singlethread_lock, NULL))
3972 PGTHREAD_ERROR("failed to initialize mutex");
3974 InterlockedExchange(&mutex_initlock, 0);
3976 #endif
3977 if (acquire)
3979 if (pthread_mutex_lock(&singlethread_lock))
3980 PGTHREAD_ERROR("failed to lock mutex");
3982 else
3984 if (pthread_mutex_unlock(&singlethread_lock))
3985 PGTHREAD_ERROR("failed to unlock mutex");
3987 #endif
3990 pgthreadlock_t
3991 PQregisterThreadLock(pgthreadlock_t newhandler)
3993 pgthreadlock_t prev = pg_g_threadlock;
3995 if (newhandler)
3996 pg_g_threadlock = newhandler;
3997 else
3998 pg_g_threadlock = default_threadlock;
4000 return prev;